Skip to content

Commit 1ed7332

Browse files
authored
refactor(profiling): remove redundant locks from memalloc (#13305)
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 baseline 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 a6520bc commit 1ed7332

File tree

9 files changed

+354
-385
lines changed

9 files changed

+354
-385
lines changed

ddtrace/profiling/collector/_memalloc.c

Lines changed: 107 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#define PY_SSIZE_T_CLEAN
66
#include <Python.h>
77

8+
#include "_memalloc_debug.h"
89
#include "_memalloc_heap.h"
910
#include "_memalloc_reentrant.h"
1011
#include "_memalloc_tb.h"
@@ -20,6 +21,14 @@ typedef struct
2021
uint16_t max_events;
2122
/* The maximum number of frames collected in stack traces */
2223
uint16_t max_nframe;
24+
25+
/* alloc_gil_guard checks that the allocation profiler data structures
26+
* are protected by the GIL, and that multiple threads don't try to
27+
* enter critical sections where that state is being modified.
28+
* Managed here instead of inside global_alloc_tracker because the
29+
* value of global_alloc_tracker is regularly updated, which also
30+
* needs to be done under the GIL. */
31+
memalloc_gil_debug_check_t alloc_gil_guard;
2332
} memalloc_context_t;
2433

2534
/* We only support being started once, so we use a global context for the whole
@@ -31,9 +40,9 @@ static memalloc_context_t global_memalloc_ctx;
3140
/* Allocation tracker */
3241
typedef struct
3342
{
34-
/* List of traceback */
43+
/* List of tracebacks for sampled allocations */
3544
traceback_array_t allocs;
36-
/* Total number of allocations */
45+
/* Total number of observed allocations, sampled or not */
3746
uint64_t alloc_count;
3847
} alloc_tracker_t;
3948

@@ -42,113 +51,90 @@ static PyObject* object_string = NULL;
4251

4352
#define ALLOC_TRACKER_MAX_COUNT UINT64_MAX
4453

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-
5954
static alloc_tracker_t* global_alloc_tracker;
6055

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)
56+
/* Determine whether we should sample. Sampling state is protected by the GIL.
57+
* This function must not call into C Python APIs, which could release the GIL. */
58+
static bool
59+
memalloc_should_sample_no_cpython(memalloc_context_t* ctx)
6760
{
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-
}
61+
MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(&ctx->alloc_gil_guard);
62+
/* Safety check: is profiling still enabled? */
63+
if (!global_alloc_tracker) {
64+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&ctx->alloc_gil_guard);
65+
return false;
66+
}
7467

75-
static void
76-
memalloc_postfork_parent(void)
77-
{
78-
memlock_unlock(&g_memalloc_lock);
68+
uint64_t alloc_count = global_alloc_tracker->alloc_count++;
69+
/* Determine if we can capture or if we need to sample */
70+
bool should_sample = false;
71+
if (alloc_count < ctx->max_events) {
72+
/* Buffer is not full, fill it */
73+
should_sample = true;
74+
} else {
75+
/* Sampling mode using a reservoir sampling algorithm: replace a random
76+
* traceback with this one
77+
* NB: this just decides whether we sample. See comment below;
78+
* we will probably have to recompute the index to replace */
79+
uint64_t r = random_range(alloc_count);
80+
should_sample = r < ctx->max_events;
81+
}
82+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&ctx->alloc_gil_guard);
83+
return should_sample;
7984
}
8085

81-
static void
82-
memalloc_postfork_child(void)
86+
/* Insert a sample into the profile data structure. The data structure is
87+
* protected by the GIL. This function must not call into C Python APIs, which
88+
* could release the GIL. Returns a non-NULL traceback if we couldn't add the
89+
* sample because profiling was stopped, or because we are replacing a sample.
90+
* The returned traceback should be freed by the caller, since doing so calls C
91+
* Python APIs. */
92+
static traceback_t*
93+
memalloc_add_sample_no_cpython(memalloc_context_t* ctx, traceback_t* tb)
8394
{
84-
memlock_unlock(&g_memalloc_lock);
85-
}
95+
MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(&ctx->alloc_gil_guard);
96+
if (!global_alloc_tracker) {
97+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&ctx->alloc_gil_guard);
98+
return tb;
99+
}
86100

87-
#ifdef _MSC_VER
88-
#pragma section(".CRT$XCU", read)
89-
__declspec(allocate(".CRT$XCU")) void (*memalloc_init_func)(void) = memalloc_init;
101+
traceback_t* old = NULL;
102+
if (global_alloc_tracker->allocs.count < ctx->max_events) {
103+
traceback_array_append(&global_alloc_tracker->allocs, tb);
104+
} else {
105+
uint64_t r = random_range(ctx->max_events);
106+
/* The caller will free the old traceback, because traceback_free calls
107+
* CPython C APIs which could release the GIL. */
108+
old = global_alloc_tracker->allocs.tab[r];
109+
global_alloc_tracker->allocs.tab[r] = tb;
110+
}
90111

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
112+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&ctx->alloc_gil_guard);
113+
return old;
103114
}
104115

105116
static void
106117
memalloc_add_event(memalloc_context_t* ctx, void* ptr, size_t size)
107118
{
108-
uint64_t alloc_count = atomic_add_clamped(&global_alloc_tracker->alloc_count, 1, ALLOC_TRACKER_MAX_COUNT);
109-
110-
/* Return if we've reached the maximum number of allocations */
111-
if (alloc_count == 0)
119+
if (!memalloc_should_sample_no_cpython(ctx)) {
112120
return;
121+
}
113122

114-
// Return if we can't take the guard
115123
if (!memalloc_take_guard()) {
116124
return;
117125
}
118126

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)) {
127+
traceback_t* tb = memalloc_get_traceback(ctx->max_nframe, ptr, size, ctx->domain);
128+
if (!tb) {
129+
memalloc_yield_guard();
123130
return;
124131
}
125132

126-
/* Determine if we can capture or if we need to sample */
127-
if (global_alloc_tracker->allocs.count < ctx->max_events) {
128-
/* 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-
}
133-
} else {
134-
/* Sampling mode using a reservoir sampling algorithm: replace a random
135-
* traceback with this one */
136-
uint64_t r = random_range(alloc_count);
137-
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);
142-
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-
}
133+
traceback_t* to_free = memalloc_add_sample_no_cpython(ctx, tb);
134+
if (to_free) {
135+
traceback_free(to_free);
149136
}
150137

151-
memlock_unlock(&g_memalloc_lock);
152138
memalloc_yield_guard();
153139
}
154140

@@ -288,6 +274,8 @@ memalloc_start(PyObject* Py_UNUSED(module), PyObject* args)
288274
PyUnicode_InternInPlace(&object_string);
289275
}
290276

277+
memalloc_gil_debug_check_init(&global_memalloc_ctx.alloc_gil_guard);
278+
291279
memalloc_heap_tracker_init((uint32_t)heap_sample_size);
292280

293281
PyMemAllocatorEx alloc;
@@ -301,11 +289,14 @@ memalloc_start(PyObject* Py_UNUSED(module), PyObject* args)
301289

302290
global_memalloc_ctx.domain = PYMEM_DOMAIN_OBJ;
303291

304-
if (memlock_trylock(&g_memalloc_lock)) {
305-
global_alloc_tracker = alloc_tracker_new();
306-
memlock_unlock(&g_memalloc_lock);
292+
alloc_tracker_t* tracker = alloc_tracker_new();
293+
if (!tracker) {
294+
PyErr_SetString(PyExc_RuntimeError, "failed to allocate profiler state");
295+
return NULL;
307296
}
308297

298+
global_alloc_tracker = tracker;
299+
309300
PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &global_memalloc_ctx.pymem_allocator_obj);
310301
PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
311302

@@ -327,16 +318,27 @@ memalloc_stop(PyObject* Py_UNUSED(module), PyObject* Py_UNUSED(args))
327318
return NULL;
328319
}
329320

321+
/* First, uninstall our wrappers. There may still be calls to our wrapper in progress,
322+
* if they happened to release the GIL.
323+
* NB: We're assuming here that this is not called concurrently with iter_events
324+
* or memalloc_heap. The higher-level collector deals with this. */
330325
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-
}
326+
327+
MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(&global_memalloc_ctx.alloc_gil_guard);
328+
alloc_tracker_t* tracker = global_alloc_tracker;
329+
/* Setting this to NULL indicates that in-progress sampling shouldn't add a sample */
330+
global_alloc_tracker = NULL;
331+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&global_memalloc_ctx.alloc_gil_guard);
332+
333+
/* Now any in-progress sampling wil see the NULL global_alloc_tracker and
334+
* abort early, so it's safe to free tracker */
335+
alloc_tracker_free(tracker);
337336

338337
memalloc_heap_tracker_deinit();
339338

339+
/* Finally, we know in-progress sampling won't use the buffer pool, so clear it out */
340+
memalloc_tb_deinit();
341+
340342
Py_RETURN_NONE;
341343
}
342344

@@ -375,31 +377,34 @@ PyDoc_STRVAR(iterevents__doc__,
375377
static PyObject*
376378
iterevents_new(PyTypeObject* type, PyObject* Py_UNUSED(args), PyObject* Py_UNUSED(kwargs))
377379
{
378-
if (!global_alloc_tracker) {
379-
PyErr_SetString(PyExc_RuntimeError, "the memalloc module was not started");
380-
return NULL;
381-
}
382-
383380
IterEventsState* iestate = (IterEventsState*)type->tp_alloc(type, 0);
384381
if (!iestate) {
385382
PyErr_SetString(PyExc_RuntimeError, "failed to allocate IterEventsState");
386383
return NULL;
387384
}
388385

386+
MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(&global_memalloc_ctx.alloc_gil_guard);
387+
if (!global_alloc_tracker) {
388+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&global_memalloc_ctx.alloc_gil_guard);
389+
PyErr_SetString(PyExc_RuntimeError, "the memalloc module was not started");
390+
Py_TYPE(iestate)->tp_free(iestate);
391+
return NULL;
392+
}
393+
389394
/* Reset the current traceback list. Do this outside lock so we can track it,
390395
* and avoid reentrancy/deadlock problems, if we start tracking the raw
391396
* allocator domain */
392397
alloc_tracker_t* tracker = alloc_tracker_new();
393398
if (!tracker) {
399+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&global_memalloc_ctx.alloc_gil_guard);
394400
PyErr_SetString(PyExc_RuntimeError, "failed to allocate new allocation tracker");
395401
Py_TYPE(iestate)->tp_free(iestate);
396402
return NULL;
397403
}
398404

399-
memlock_lock(&g_memalloc_lock);
400405
iestate->alloc_tracker = global_alloc_tracker;
401406
global_alloc_tracker = tracker;
402-
memlock_unlock(&g_memalloc_lock);
407+
MEMALLOC_GIL_DEBUG_CHECK_RELEASE(&global_memalloc_ctx.alloc_gil_guard);
403408

404409
iestate->seq_index = 0;
405410

@@ -414,11 +419,8 @@ iterevents_new(PyTypeObject* type, PyObject* Py_UNUSED(args), PyObject* Py_UNUSE
414419
static void
415420
iterevents_dealloc(IterEventsState* iestate)
416421
{
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-
}
422+
alloc_tracker_free(iestate->alloc_tracker);
423+
Py_TYPE(iestate)->tp_free(iestate);
422424
}
423425

424426
static PyObject*
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#ifndef _DDTRACE_MEMALLOC_DEBUG_H
2+
#define _DDTRACE_MEMALLOC_DEBUG_H
3+
4+
#include <assert.h>
5+
#include <stdbool.h>
6+
7+
#include <Python.h>
8+
9+
/* Release the GIL. For debugging when GIL release allows memory profiling functions
10+
* to interleave from different threads. Call near C Python API calls. */
11+
static inline void
12+
memalloc_debug_gil_release(void)
13+
{
14+
#ifndef NDEBUG
15+
Py_BEGIN_ALLOW_THREADS;
16+
Py_END_ALLOW_THREADS;
17+
#endif
18+
}
19+
20+
typedef struct
21+
{
22+
bool acquired;
23+
} memalloc_gil_debug_check_t;
24+
25+
static void
26+
memalloc_gil_debug_check_init(memalloc_gil_debug_check_t* c)
27+
{
28+
c->acquired = false;
29+
}
30+
31+
#ifndef NDEBUG
32+
/* Annotate that we are beginning a critical section where we don't want other
33+
* memalloc code to run. If compiled assertions enabled, this will check that the
34+
* GIL is held and that the guard has not already been acquired elsewhere.
35+
*
36+
* This is a macro so we get file/line info where it's actually used */
37+
#define MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(c) \
38+
do { \
39+
memalloc_gil_debug_check_t* p = c; \
40+
assert(PyGILState_Check()); \
41+
assert(!p->acquired); \
42+
p->acquired = true; \
43+
} while (0)
44+
45+
/* Annotate that we are ending a critical section where we don't want other
46+
* memalloc code to run. If compiled assertions enabled, this will check that the
47+
* guard is acquired.
48+
*
49+
* This is a macro so we get file/line info where it's actually used */
50+
#define MEMALLOC_GIL_DEBUG_CHECK_RELEASE(c) \
51+
do { \
52+
memalloc_gil_debug_check_t* p = c; \
53+
assert(p->acquired); \
54+
p->acquired = false; \
55+
} while (0)
56+
#else
57+
58+
#define MEMALLOC_GIL_DEBUG_CHECK_ACQUIRE(c)
59+
#define MEMALLOC_GIL_DEBUG_CHECK_RELEASE(c)
60+
61+
#endif
62+
63+
#endif

0 commit comments

Comments
 (0)