Skip to content

Commit 840710b

Browse files
committed
refactor(profiling): remove redundant locks from memalloc
We added locking to memalloc, the memory profiler, in #11460 in order to address crashes. These locks made the crashes go away, but significantly increased the baseline overhead of the profiler and introduced subtle bugs. The locks we added turned out to be fundamentally incompatible with the global interpreter lock (GIL), at least with the implementation from #11460. This PR refactors the profiler to use the GIL exclusively for locking. First, we should acknowledge no-GIL and subinterpreters. As of right now, our module does not support either. A module has to explicitly opt-in to support either, so there is no risk of those modes being enabled under our feet. Supporting either mode is likely a repo-wide project. For now, we can assume the GIL exists. This work was motivated by overhead. We currently acquire and release locks in every memory allocation and free. Even when the locks aren't contended, allocations and frees are very frequent, and the extra works adds up. We add about ~8x overhead to the baselien cost of allocation just with our locking, not including the cost of actually sampling an allocation. We can't get rid of this overhead just by reducing sampling frequency. There are a few rules to follow in order to use the GIL correctly for locking: 1) The GIL is held when a C extension function is called, _except_ possibly in the raw allocator, which we do not profile 2) The GIL may be released during C Python API calls. Even if it is released, though, it will be held again after the call 3) Thus, the GIL creates critical sections only between C Python API calls, and the beginning and end of C extension functions. Modifications to shared state across those points are not atomic. 4) If we take a lock of our own in a C extension code (i.e. a pthread_mutex), and the extension code releases the GIL, then the program will deadlock due to lock order inversion. We can only safely take locks in C extension when the GIL is released. The crashes that #11460 addresed were due to breaking the first three rules. In particular, we could race on accessing the shared scratch buffer used when collecting tracebacks, which lead to double-frees. See #13185 for more details. Our mitigation involved using C locks around any access to the shared profiler state. We nearly broke rule 4 in the process. However, we used try-locks specifically out of a fear of introducing deadlocks. Try-locks mean that we attempt to acquire the lock, but return a failure if the lock is already held. This stopped deadlocks, but introduced bugs: For example: - If we failed to take the lock when trying to report allocation profile events, we'd raise an exception when it was in fact not reasonable for doing that to fail. See #12075. - memalloc_heap_untrack, which removes tracked allocations, was guarded with a try-lock. If we couldn't acquire the lock, we would fail to remove a record for an allocation and effectively leak memory. See #13317 - We attempted to make our locking fork-safe. The first attempt was inefficient; we made it less inefficient but the fix only "worked" because of try-locks. See #11848 Try-locks hide concurrency problems and we shouldn't use them. Using our own locks requires releasing the GIL before acquisition, and then re-acquiring the GIL. That adds unnecessary overhead. We don't inherently need to do any off-GIL work. So, we should try to just use the GIL as long as it is available. The basic refactor is actually pretty simple. In a nutshell, we rearrange the memalloc_add_event and memalloc_heap_track functions so that they make the sampling decision, then take a traceback, then insert the traceback into the appropriate data structure. Collecting a traceback can release the GIL, so we make sure that modifying the data structure happens completely after the traceback is collected. We also safeguard against the possibility that the profiler was stopped during sampling, if the GIL was released. This requires a small rearrangement of memalloc_stop to make sure that the sampling functions don't see partially-freed profiler data structures. For testing, I have mainly used the code from test_memealloc_data_race_regression. I also added a debug mode, enabled by compiling with MEMALLOC_TESTING_GIL_RELEASE, which releases the GIL at places where it would be expected. For performance I examined the overhead of profiling on a basic flask application.
1 parent 4e8a947 commit 840710b

8 files changed

+163
-339
lines changed

ddtrace/profiling/collector/_memalloc.c

Lines changed: 77 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ static memalloc_context_t global_memalloc_ctx;
3131
/* Allocation tracker */
3232
typedef struct
3333
{
34-
/* List of traceback */
34+
/* List of tracebacks for sampled allocations */
3535
traceback_array_t allocs;
36-
/* Total number of allocations */
36+
/* Total number of observed allocations, sampled or not */
3737
uint64_t alloc_count;
3838
} alloc_tracker_t;
3939

@@ -42,113 +42,81 @@ static PyObject* object_string = NULL;
4242

4343
#define ALLOC_TRACKER_MAX_COUNT UINT64_MAX
4444

45-
/* This lock protects access to global_alloc_tracker. The GIL is NOT sufficient
46-
to protect our data structures from concurrent access. For one, the GIL is an
47-
implementation detail and may go away in the future. Additionally, even if the
48-
GIL is held on _entry_ to our C extension functions, making it safe to call
49-
Python C API functions, the GIL can be released during Python C API calls if
50-
we call back into interpreter code. This can happen if we allocate a Python
51-
object (such as frame info), trigger garbage collection, and run arbitrary
52-
destructors. When this happens, other threads can run python code, such as the
53-
thread that aggregates and uploads the profile data and mutates the global
54-
data structures. The GIL does not create critical sections for C extension
55-
functions!
56-
*/
57-
static memlock_t g_memalloc_lock;
58-
5945
static alloc_tracker_t* global_alloc_tracker;
6046

61-
// This is a multiplatform way to define an operation to happen at static initialization time
62-
static void
63-
memalloc_init(void);
64-
65-
static void
66-
memalloc_prefork(void)
67-
{
68-
// Lock the mutex prior to forking. This ensures that the memory profiler
69-
// data structures will be in a consistent state in the child process.
70-
// The rest of the memalloc calls do trylock so we don't run the risk
71-
// of deadlocking if some other fork handler allocates
72-
memlock_lock(&g_memalloc_lock);
73-
}
74-
75-
static void
76-
memalloc_postfork_parent(void)
77-
{
78-
memlock_unlock(&g_memalloc_lock);
79-
}
80-
81-
static void
82-
memalloc_postfork_child(void)
83-
{
84-
memlock_unlock(&g_memalloc_lock);
85-
}
86-
87-
#ifdef _MSC_VER
88-
#pragma section(".CRT$XCU", read)
89-
__declspec(allocate(".CRT$XCU")) void (*memalloc_init_func)(void) = memalloc_init;
90-
91-
#elif defined(__GNUC__) || defined(__clang__)
92-
__attribute__((constructor))
93-
#else
94-
#error Unsupported compiler
95-
#endif
96-
static void
97-
memalloc_init()
98-
{
99-
memlock_init(&g_memalloc_lock);
100-
#ifndef _WIN32
101-
pthread_atfork(memalloc_prefork, memalloc_postfork_parent, memalloc_postfork_child);
102-
#endif
103-
}
104-
10547
static void
10648
memalloc_add_event(memalloc_context_t* ctx, void* ptr, size_t size)
10749
{
108-
uint64_t alloc_count = atomic_add_clamped(&global_alloc_tracker->alloc_count, 1, ALLOC_TRACKER_MAX_COUNT);
50+
/* Safety check: is profiling still enabled? */
51+
if (!global_alloc_tracker)
52+
return;
10953

11054
/* Return if we've reached the maximum number of allocations */
111-
if (alloc_count == 0)
55+
if (global_alloc_tracker->alloc_count == ALLOC_TRACKER_MAX_COUNT)
11256
return;
11357

114-
// Return if we can't take the guard
115-
if (!memalloc_take_guard()) {
116-
return;
117-
}
58+
/* Incrementing the allocation count before taking the guard gives
59+
* an accurate count, but means we'll overweight the allocations we
60+
* do sample relative to their actual size since our count necessarily
61+
* includes allocations we won't sample. We could consider moving this
62+
* below the guard and instead adding a placeholder "self allocation"
63+
* entry to represent the allocations we intentionally don't sample.
64+
*/
65+
uint64_t alloc_count = global_alloc_tracker->alloc_count++;
11866

119-
// In this implementation, the `global_alloc_tracker` isn't intrinsically protected. Before we read or modify,
120-
// take the lock. The count of allocations is already forward-attributed elsewhere, so if we can't take the lock
121-
// there's nothing to do.
122-
if (!memlock_trylock(&g_memalloc_lock)) {
67+
/* Return if we can't take the guard, since we're not going to be able to sample */
68+
if (!memalloc_take_guard()) {
12369
return;
12470
}
12571

12672
/* Determine if we can capture or if we need to sample */
127-
if (global_alloc_tracker->allocs.count < ctx->max_events) {
73+
bool should_sample = false;
74+
if (alloc_count < ctx->max_events) {
12875
/* Buffer is not full, fill it */
129-
traceback_t* tb = memalloc_get_traceback(ctx->max_nframe, ptr, size, ctx->domain);
130-
if (tb) {
131-
traceback_array_append(&global_alloc_tracker->allocs, tb);
132-
}
76+
should_sample = true;
13377
} else {
13478
/* Sampling mode using a reservoir sampling algorithm: replace a random
135-
* traceback with this one */
79+
* traceback with this one
80+
* NB: this just decides whether we sample. See comment below;
81+
* we will probably have to recompute the index to replace */
13682
uint64_t r = random_range(alloc_count);
83+
should_sample = r < ctx->max_events;
84+
}
13785

138-
// In addition to event size, need to check that the tab is in a good state
139-
if (r < ctx->max_events && global_alloc_tracker->allocs.tab != NULL) {
140-
/* Replace a random traceback with this one */
141-
traceback_t* tb = memalloc_get_traceback(ctx->max_nframe, ptr, size, ctx->domain);
86+
if (!should_sample) {
87+
goto done;
88+
}
14289

143-
// Need to check not only that the tb returned
144-
if (tb) {
145-
traceback_free(global_alloc_tracker->allocs.tab[r]);
146-
global_alloc_tracker->allocs.tab[r] = tb;
147-
}
148-
}
90+
traceback_t* tb = memalloc_get_traceback(ctx->max_nframe, ptr, size, ctx->domain);
91+
if (!tb) {
92+
goto done;
14993
}
15094

151-
memlock_unlock(&g_memalloc_lock);
95+
if (!global_alloc_tracker) {
96+
/* If getting a traceback lead to a GIL release, it is possible
97+
* that the profiler was stopped and the traceback array was freed.
98+
* Don't add the sample.
99+
*/
100+
traceback_free(tb);
101+
goto done;
102+
}
103+
104+
/* The GIL may have been released while collecting a traceback above.
105+
* If so, the aggregation/uploading thread may have rotated the tracker.
106+
* We need to recompute the index where the sample will go.
107+
*/
108+
if (global_alloc_tracker->allocs.count < ctx->max_events) {
109+
traceback_array_append(&global_alloc_tracker->allocs, tb);
110+
} else {
111+
uint64_t r = random_range(ctx->max_events);
112+
traceback_t* old = global_alloc_tracker->allocs.tab[r];
113+
global_alloc_tracker->allocs.tab[r] = tb;
114+
/* Free the old traceback only after modifying the table, in case freeing
115+
* releases the GIL */
116+
traceback_free(old);
117+
}
118+
119+
done:
152120
memalloc_yield_guard();
153121
}
154122

@@ -301,11 +269,14 @@ memalloc_start(PyObject* Py_UNUSED(module), PyObject* args)
301269

302270
global_memalloc_ctx.domain = PYMEM_DOMAIN_OBJ;
303271

304-
if (memlock_trylock(&g_memalloc_lock)) {
305-
global_alloc_tracker = alloc_tracker_new();
306-
memlock_unlock(&g_memalloc_lock);
272+
alloc_tracker_t* tracker = alloc_tracker_new();
273+
if (!tracker) {
274+
PyErr_SetString(PyExc_RuntimeError, "failed to allocate profiler state");
275+
return NULL;
307276
}
308277

278+
global_alloc_tracker = tracker;
279+
309280
PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &global_memalloc_ctx.pymem_allocator_obj);
310281
PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
311282

@@ -327,16 +298,24 @@ memalloc_stop(PyObject* Py_UNUSED(module), PyObject* Py_UNUSED(args))
327298
return NULL;
328299
}
329300

301+
/* First, uninstall our wrappers. There may still be calls to our wrapper in progress,
302+
* if they happened to release the GIL.
303+
* NB: We're assuming here that this is not called concurrently with iter_events
304+
* or memalloc_heap. The higher-level collector deals with this. */
330305
PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &global_memalloc_ctx.pymem_allocator_obj);
331-
memalloc_tb_deinit();
332-
if (memlock_trylock(&g_memalloc_lock)) {
333-
alloc_tracker_free(global_alloc_tracker);
334-
global_alloc_tracker = NULL;
335-
memlock_unlock(&g_memalloc_lock);
336-
}
306+
307+
alloc_tracker_t* tracker = global_alloc_tracker;
308+
/* Setting this to NULL indicates that in-progress sampling shouldn't add a sample */
309+
global_alloc_tracker = NULL;
310+
/* Now free the tracker, in case GIL release while deallocating tracebacks lets
311+
* in-process sampling continue and observe a partially de-initialized tracker */
312+
alloc_tracker_free(tracker);
337313

338314
memalloc_heap_tracker_deinit();
339315

316+
/* Finally, we know in-progress sampling won't use the buffer pool, so clear it out */
317+
memalloc_tb_deinit();
318+
340319
Py_RETURN_NONE;
341320
}
342321

@@ -396,10 +375,8 @@ iterevents_new(PyTypeObject* type, PyObject* Py_UNUSED(args), PyObject* Py_UNUSE
396375
return NULL;
397376
}
398377

399-
memlock_lock(&g_memalloc_lock);
400378
iestate->alloc_tracker = global_alloc_tracker;
401379
global_alloc_tracker = tracker;
402-
memlock_unlock(&g_memalloc_lock);
403380

404381
iestate->seq_index = 0;
405382

@@ -414,11 +391,8 @@ iterevents_new(PyTypeObject* type, PyObject* Py_UNUSED(args), PyObject* Py_UNUSE
414391
static void
415392
iterevents_dealloc(IterEventsState* iestate)
416393
{
417-
if (memlock_trylock(&g_memalloc_lock)) {
418-
alloc_tracker_free(iestate->alloc_tracker);
419-
Py_TYPE(iestate)->tp_free(iestate);
420-
memlock_unlock(&g_memalloc_lock);
421-
}
394+
alloc_tracker_free(iestate->alloc_tracker);
395+
Py_TYPE(iestate)->tp_free(iestate);
422396
}
423397

424398
static PyObject*
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#ifndef _DDTRACE_MEMALLOC_DEBUG_H
2+
#define _DDTRACE_MEMALLOC_DEBUG_H
3+
4+
/* Release the GIL. For debugging when GIL release allows memory profiling functions
5+
* to interleave from different threads. Call near C Python API calls. */
6+
static inline void
7+
memalloc_debug_gil_release(void)
8+
{
9+
#ifdef MEMALLOC_TESTING_GIL_RELEASE
10+
Py_BEGIN_ALLOW_THREADS;
11+
Py_END_ALLOW_THREADS;
12+
#endif
13+
}
14+
15+
#endif

0 commit comments

Comments
 (0)