From f40a6f609052c9e42eed17cafd9d34923dad8b67 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 24 Oct 2026 12:41:12 -0500 Subject: [PATCH 1/3] Test that a freed Python compiled function leaves every thread cache PyCompiledFun keys its traces by the address of the Python callable. Each call records its trace in the cache of the calling thread, but the destructor erases the key only from the cache of the thread that called the function last. The new test calls the compiled function on a worker thread and then on the main thread, frees it on the main thread, and compiles the same callable again on the worker. It expects a new trace there. It fails until the destructor erases every thread cache. Co-Authored-By: Claude Opus 5.5 (1M context) --- fork.yaml | 7 +++++ python/tests/test_compile.py | 50 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/fork.yaml b/fork.yaml index 376a8bc9db..82280489a4 100644 --- a/fork.yaml +++ b/fork.yaml @@ -186,6 +186,13 @@ def: globs: - "mlx/compile.cpp" - "tests/compile_tests.cpp" + - title: "Freed Python compiled functions leave every thread cache" + description: | + The test `test_compile_free_erases_every_thread_cache` calls a compiled Python function + on two threads, frees it on the thread that called it last, and compiles the same + callable again on the other thread. It expects a new trace there. + globs: + - "python/tests/test_compile.py" - title: "Integer floor_divide tests" description: | The fork keeps its regression tests for integer `floor_divide` from PR #32. Upstream diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 7436e58cd2..24200b15f6 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -169,6 +169,56 @@ def worker(): raise errors[0] self.assertEqual(len(traces), 2) + def test_compile_free_erases_every_thread_cache(self): + # Each call of a compiled function records its trace in the cache of + # the calling thread. When the function is freed, its entry must go + # from every thread cache, not only from the cache of the thread that + # called it last. Otherwise a later compile of the same callable (so + # the same id) on another thread gets the old tape and is not traced + # again. + traces = [] + + def fun(x): + traces.append(1) + return x + 1 + + holder = {"fn": mx.compile(fun)} + traced = threading.Event() + released = threading.Event() + errors = [] + + def worker(): + try: + # Record a trace in the cache of this thread. + mx.eval(holder["fn"](mx.array([1.0]))) + traced.set() + self.assertTrue(released.wait(10)) + # The same callable, so the same id. + fn = mx.compile(fun) + mx.eval(fn(mx.array([1.0]))) + except Exception as e: + errors.append(e) + finally: + traced.set() + mx.clear_streams() + + # The worker has to outlive the release. On exit it would tear down + # its cache anyway. + thread = threading.Thread(target=worker) + thread.start() + self.assertTrue(traced.wait(10)) + # Call the function last on this thread, then free it here. + mx.eval(holder["fn"](mx.array([1.0]))) + holder.clear() + gc.collect() + released.set() + thread.join() + + if errors: + raise errors[0] + # One trace on each thread, and one more on the worker after the free. + self.assertEqual(len(traces), 3) + def test_compile_grad(self): def loss_fn(x): return mx.exp(x).sum() From ee8eae07926f01d3c83d978969c54ddf44a4c719 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 24 Oct 2026 12:54:22 -0500 Subject: [PATCH 2/3] Make the worker of the Python free test find its own trace The first CI run passed the new test without the fix. A trace is cached under the default stream of the calling thread, and the first op of a new thread makes that stream. The worker's first call recorded its trace before its stream existed, so no later call could match it, and the compile after the free traced again with or without the erase. The worker now makes its default stream first and calls the function twice; the test checks that the second call used the trace (one trace), which shows that a stale entry would be found. Co-Authored-By: Claude Opus 5.5 (1M context) --- python/tests/test_compile.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 24200b15f6..12daa0347b 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -186,11 +186,20 @@ def fun(x): traced = threading.Event() released = threading.Event() errors = [] + worker_traces = [] def worker(): try: - # Record a trace in the cache of this thread. + # Make the default stream of this thread first. A trace is + # cached under the default stream of the calling thread, and + # the first op of a new thread makes that stream. A trace + # recorded before it exists never matches a later call. + mx.default_stream(mx.default_device()) + # Record a trace in the cache of this thread. The second call + # must use it, which shows that this thread finds the entry. mx.eval(holder["fn"](mx.array([1.0]))) + mx.eval(holder["fn"](mx.array([1.0]))) + worker_traces.append(len(traces)) traced.set() self.assertTrue(released.wait(10)) # The same callable, so the same id. @@ -216,6 +225,7 @@ def worker(): if errors: raise errors[0] + self.assertEqual(worker_traces, [1]) # One trace on each thread, and one more on the worker after the free. self.assertEqual(len(traces), 3) From bef32f93516025509fa8cbbb1861e373744966a6 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 24 Oct 2026 12:43:38 -0500 Subject: [PATCH 3/3] Python: erase a freed compiled function from every thread cache PyCompiledFun keys its traces by the address of the Python callable. call_impl stored the cache of the calling thread, so the destructor erased the key only from the cache of the thread that called the function last. Traces from other threads stayed after the free: they kept their arrays alive, and a later compile of a callable at the same address replayed them. The destructor now erases through the cache registry (detail::compile_erase(fun_id)) before it releases the callable, and PyCompiledFun no longer keeps a cache. Co-Authored-By: Claude Opus 5.5 (1M context) --- fork.yaml | 14 +++++++++++--- python/src/transforms.cpp | 15 +++++++++------ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/fork.yaml b/fork.yaml index 82280489a4..61152f06a8 100644 --- a/fork.yaml +++ b/fork.yaml @@ -188,10 +188,18 @@ def: - "tests/compile_tests.cpp" - title: "Freed Python compiled functions leave every thread cache" description: | - The test `test_compile_free_erases_every_thread_cache` calls a compiled Python function - on two threads, frees it on the thread that called it last, and compiles the same - callable again on the other thread. It expects a new trace there. + The Python binding keys the traces of `mx.compile(fun)` by the address of `fun`. Upstream, + `PyCompiledFun` keeps the cache of the thread that called it last, and its destructor + erases the key only from that cache. Each call records its trace in the cache of the + calling thread, so a trace from another thread stayed after the free. The trace kept its + arrays alive, and a later compile of a callable at the same address replayed it without a + new trace. The destructor now erases the key from every live thread cache through the + registry above, before it releases `fun`, and `PyCompiledFun` no longer keeps a cache. + The test `test_compile_free_erases_every_thread_cache` calls a compiled function on two + threads, frees it on the thread that called it last, and compiles the same callable + again on the other thread. It expects a new trace there. (PR #44) globs: + - "python/src/transforms.cpp" - "python/tests/test_compile.py" - title: "Integer floor_divide tests" description: | diff --git a/python/src/transforms.cpp b/python/src/transforms.cpp index 223e232e29..0397ca0447 100644 --- a/python/src/transforms.cpp +++ b/python/src/transforms.cpp @@ -416,7 +416,6 @@ struct PyCompiledFun { nb::object captured_inputs; nb::object captured_outputs; bool shapeless; - mx::detail::CompileCacheWeakPtr cache; // Data to attach to the compiled function that contains the python output // structure and the number of arrays in said structure. @@ -452,14 +451,11 @@ struct PyCompiledFun { fun_id(reinterpret_cast(fun.ptr())), captured_inputs(std::move(other.captured_inputs)), captured_outputs(std::move(other.captured_outputs)), - shapeless(other.shapeless), - cache(other.cache) { + shapeless(other.shapeless) { other.fun_id = 0; }; nb::object call_impl(const nb::args& args, const nb::kwargs& kwargs) { - cache = mx::detail::compile_cache(); - // Flat array inputs std::vector inputs; @@ -593,7 +589,14 @@ struct PyCompiledFun { ~PyCompiledFun() { nb::gil_scoped_acquire gil; - mx::detail::compile_erase(cache, fun_id); + // The compiled function can be called on any thread, and each call + // records its trace in the cache of the calling thread. Erase the key from + // every live thread cache, and do it before fun is released so that no + // new callable can get this address while a trace for it is still cached. + // A moved-from object has fun_id 0 and no traces. + if (fun_id != 0) { + mx::detail::compile_erase(fun_id); + } fun.reset(); captured_inputs.reset(); captured_outputs.reset();