From f46dd995e35e33280aefdc0b82f8192230064c50 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 10:13:53 -0400 Subject: [PATCH 1/8] fix: wait for calls in flight at C exit on Linux and keep llama.cpp statics alive C exit() on Linux destroyed the statics of the llama.cpp libraries while other threads were still inside them (llamadart#949). - The llama.cpp libraries of the Linux bundle bind __cxa_atexit to a definition that registers nothing, so their statics are never destroyed. - C exit() runs the wait of exit teardown and frees nothing. The handler is registered at the first creating call and at the first tracked object. - While teardown waits, a decode or an encode on the CPU backend ends. - validate_linux_artifact.py fails an archive whose libraries import __cxa_atexit. Apple, Android and Windows builds are unchanged. --- .github/workflows/validate_wrapper.yml | 8 + CMakeLists.txt | 53 ++++++- src/llama_dart_static_destructors.c | 24 +++ src/llama_dart_wrapper.cpp | 83 +++++++++- src/llama_dart_wrapper.h | 26 +++- tests/exit_teardown_test.cpp | 207 +++++++++++++++++++++++-- tests/test_validate_exports.py | 75 ++++++++- tests/validate_linux_artifact_test.py | 86 ++++++++++ tools/validate_exports.py | 39 ++++- tools/validate_linux_artifact.py | 42 +++++ 10 files changed, 608 insertions(+), 35 deletions(-) create mode 100644 src/llama_dart_static_destructors.c diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index dffe9149..b5caec7a 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -406,6 +406,14 @@ jobs: --format nm --tool nm build/wrapper-contract/libllamadart.so + # The release archives get the same check from + # validate_linux_artifact.py. + - name: Check that no library registers static destructors with the C library + run: | + for library in build/wrapper-contract/libllamadart.so build/wrapper-contract/bin/*.so; do + python3 tools/validate_exports.py --format readelf --tool readelf \ + --imports-only --forbid-import __cxa_atexit "$library" + done msvc-mtmd-link-contract: needs: changes diff --git a/CMakeLists.txt b/CMakeLists.txt index 700d4cec..3fe73325 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -188,6 +188,30 @@ endif() llamadart_attach_android_cpu_backend_score(ggml-cpu) +# Adds src/llama_dart_static_destructors.c to every shared library and backend +# module that llama.cpp builds, whatever backends are enabled. +function(llamadart_drop_static_destructors directory) + get_property(target_names DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) + foreach(target_name IN LISTS target_names) + get_target_property(target_type ${target_name} TYPE) + if (target_type STREQUAL "SHARED_LIBRARY" OR target_type STREQUAL "MODULE_LIBRARY") + target_sources(${target_name} PRIVATE + $) + endif() + endforeach() + get_property(subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) + foreach(subdirectory IN LISTS subdirectories) + llamadart_drop_static_destructors("${subdirectory}") + endforeach() +endfunction() + +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_library(llamadart_static_destructors OBJECT + "src/llama_dart_static_destructors.c") + llamadart_drop_static_destructors( + "${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp") +endif() + add_library(llamadart_lib SHARED "src/llama_dart_wrapper.cpp" "src/llama_dart_vulkan_device_info.cpp") @@ -306,8 +330,8 @@ if (LLAMADART_BUILD_TESTS) src ) foreach(scenario dispose order repeat in-flight nested settle timeout - idle-wait own-call blocked exit late-static free-in-flight - free-timeout barrier-free barrier-free-idle) + idle-wait own-call blocked exit exit-in-flight late-static + free-in-flight free-timeout barrier-free barrier-free-idle) add_test(NAME llamadart_exit_teardown_${scenario} COMMAND llamadart_exit_teardown_test ${scenario}) endforeach() @@ -325,14 +349,19 @@ if (LLAMADART_BUILD_TESTS) "${exit_teardown_vocabulary_model}") set_tests_properties(llamadart_exit_teardown_barrier-grammar PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_vocabulary_model) - # Teardown runs at exit on Apple only, and only there are the backends part - # of libllamadart, so the scenarios that load a model run there. They use a - # model the test writes itself unless one is given. + # Teardown runs at exit on Apple and Linux, so the scenarios that load a + # model run there. They use a model the test writes itself unless one is + # given. On Linux the backends are modules, of which the test loads the + # CPU one. set(LLAMADART_EXIT_TEARDOWN_TEST_MODEL "" CACHE FILEPATH "GGUF model for the exit teardown tests instead of the generated one") set(LLAMADART_EXIT_TEARDOWN_TEST_MMPROJ "" CACHE FILEPATH "GGUF multimodal projector of that model for the mtmd exit teardown tests") - if (APPLE) + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_compile_definitions(llamadart_exit_teardown_test PRIVATE + LLAMADART_TEST_CPU_BACKEND="$") + endif() + if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME llamadart_exit_teardown_graph COMMAND llamadart_exit_teardown_test graph) set(exit_teardown_model "${LLAMADART_EXIT_TEARDOWN_TEST_MODEL}") @@ -356,6 +385,18 @@ if (LLAMADART_BUILD_TESTS) set_tests_properties(llamadart_exit_teardown_${scenario} PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_model) endforeach() + # What only Linux does: teardown ends a decode on the CPU backend, + # and the statics of llama.cpp outlive an exit. + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + foreach(scenario model-decode-ended model-decode-outlasts-wait) + add_test(NAME llamadart_exit_teardown_${scenario} + COMMAND llamadart_exit_teardown_test ${scenario} + "${exit_teardown_model}") + set_tests_properties(llamadart_exit_teardown_${scenario} + PROPERTIES + FIXTURES_REQUIRED llamadart_exit_teardown_model) + endforeach() + endif() if (LLAMADART_EXIT_TEARDOWN_TEST_MODEL) add_test(NAME llamadart_exit_teardown_model-speculative-process COMMAND llamadart_exit_teardown_test model-speculative-process diff --git a/src/llama_dart_static_destructors.c b/src/llama_dart_static_destructors.c new file mode 100644 index 00000000..1621ed02 --- /dev/null +++ b/src/llama_dart_static_destructors.c @@ -0,0 +1,24 @@ +// Linked into every llama.cpp shared library of the Linux bundle, and not +// into libllamadart (CMakeLists.txt). +// +// The C++ runtime registers the destructor of each static of a library +// through __cxa_atexit. The linker binds those calls to this definition, +// which registers nothing, so the statics of the library are never destroyed. +// +// C exit() destroys statics while other threads are still inside llama.cpp, +// which then read freed memory (https://github.com/leehack/llamadart/issues/949). +// On Apple platforms llama.cpp is part of libllamadart, whose exit teardown +// runs before the first of those statics is destroyed. Here the libraries are +// separate, and exit handlers run in reverse order of registration: no handler +// of libllamadart precedes the destructor of a static that another library +// creates later, in the middle of a model load for one. A static that is never +// destroyed also stays valid for a call that outlasts teardown's wait. +#if defined(__linux__) && !defined(__ANDROID__) +__attribute__((visibility("hidden"), used)) int +__cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { + (void)destroy; + (void)object; + (void)dso_handle; + return 0; +} +#endif diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index b2d4314f..00b6d5f7 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -43,6 +43,20 @@ #endif #endif +// Where C exit() runs exit teardown, or on Linux the wait of it. Android is +// left out: an exit during a call in flight has not been examined there. +#if defined(__linux__) && !defined(__ANDROID__) +#include +#define LLAMA_DART_EXIT_ON_LINUX 1 +#else +#define LLAMA_DART_EXIT_ON_LINUX 0 +#endif +#if defined(__APPLE__) || LLAMA_DART_EXIT_ON_LINUX +#define LLAMA_DART_EXIT_AT_PROCESS_EXIT 1 +#else +#define LLAMA_DART_EXIT_AT_PROCESS_EXIT 0 +#endif + // Global log level (0=none, 1=debug, 2=info, 3=warn, 4=error) static std::atomic g_dart_log_level{3}; // Default to WARN // Track last non-CONT severity so continuation lines inherit proper level. @@ -749,7 +763,31 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, } } -#if defined(__APPLE__) +#if LLAMA_DART_EXIT_ON_LINUX +// Set while teardown waits for the calls in flight, and for good when it gave +// up waiting. A decode or an encode on the CPU backend ends then. One that +// outlasts the wait is still running when the exit reaches the handlers of +// other libraries, and the destructor of OpenBLAS never returns while its +// threads are at work. +static std::atomic llama_dart_exit_ending_calls{false}; + +static bool llama_dart_exit_abort_callback(void *) { + return llama_dart_exit_ending_calls.load(std::memory_order_relaxed); +} + +// Set when C exit() runs teardown, which then frees nothing. Nothing on Linux +// needs the objects freed, and the exit handlers of a GPU driver may have run +// already: an exit with a model left loaded is known to be clean, a free +// among those handlers is not. +static std::atomic llama_dart_exit_keeps_objects{false}; + +static void llama_dart_exit_wait_at_exit() { + llama_dart_exit_keeps_objects.store(true); + llama_dart_exit_teardown(); +} +#endif + +#if LLAMA_DART_EXIT_AT_PROCESS_EXIT struct llama_dart_exit_static_destructor { void (*destroy)(void *); void *object; @@ -759,7 +797,11 @@ static void llama_dart_exit_destroy_static(void *argument) { const auto destructor = *static_cast(argument); free(argument); +#if LLAMA_DART_EXIT_ON_LINUX + llama_dart_exit_wait_at_exit(); +#else llama_dart_exit_teardown(); +#endif destructor.destroy(destructor.object); } @@ -814,6 +856,23 @@ static void llama_dart_exit_arm() { if (!llama_dart_exit_state().armed.exchange(true)) { atexit(llama_dart_exit_teardown); } +#elif LLAMA_DART_EXIT_ON_LINUX + if (!llama_dart_exit_state().armed.exchange(true)) { + atexit(llama_dart_exit_wait_at_exit); + } +#endif +} + +// On Linux llama.cpp is not part of this image and its libraries register no +// static destructors (llama_dart_static_destructors.c), so only a handler +// runs the wait at exit, and the exit that arrives during the first creating +// call needs one that was registered before anything is tracked. +static void llama_dart_exit_arm_creating_call() { +#if LLAMA_DART_EXIT_ON_LINUX + static std::atomic armed{false}; + if (!armed.exchange(true)) { + atexit(llama_dart_exit_wait_at_exit); + } #endif } @@ -923,7 +982,10 @@ struct llama_dart_exit_call { // A call in flight that tracks what it creates. Teardown waits for it even // when nothing is tracked yet. struct llama_dart_exit_creating_call { - llama_dart_exit_creating_call() { llama_dart_exit_begin_call(true); } + llama_dart_exit_creating_call() { + llama_dart_exit_arm_creating_call(); + llama_dart_exit_begin_call(true); + } ~llama_dart_exit_creating_call() { { auto ®istry = llama_dart_exit_state(); @@ -1106,15 +1168,27 @@ LLAMADART_API void llama_dart_exit_teardown(void) { } // A call in flight on this thread cannot end while teardown runs. const int32_t own_calls = llama_dart_exit_call_depth > 0 ? 1 : 0; +#if LLAMA_DART_EXIT_ON_LINUX + llama_dart_exit_ending_calls.store(true); +#endif const bool idle = registry.idle.wait_for( lock, std::chrono::milliseconds(registry.wait_ms), [®istry, own_calls] { return registry.calls == own_calls; }); if (!idle) { return; } +#if LLAMA_DART_EXIT_ON_LINUX + // The free functions that run next may evaluate. + llama_dart_exit_ending_calls.store(false); +#endif registry.idle.wait_until( lock, registry.last_call_end + llama_dart_exit_settle_time, [] { return false; }); +#if LLAMA_DART_EXIT_ON_LINUX + if (llama_dart_exit_keeps_objects.load()) { + return; + } +#endif std::copy_if(registry.objects.begin(), registry.objects.end(), std::back_inserter(objects), can_free); } @@ -1157,6 +1231,11 @@ llama_dart_init_from_model(struct llama_model *model, struct llama_context_params params) { return llama_dart_barrier(nullptr, [model, ¶ms] { llama_dart_exit_creating_call call; +#if LLAMA_DART_EXIT_ON_LINUX + if (params.abort_callback == nullptr) { + params.abort_callback = llama_dart_exit_abort_callback; + } +#endif return llama_dart_exit_track_created( llama_init_from_model(model, params), llama_dart_exit_free_context, LLAMA_DART_EXIT_STAGE_CONTEXT); diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 563d4078..40cc600e 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -352,8 +352,26 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // or hot restart does. ggml-metal aborts in its static destructor while any // Metal buffer is still allocated, so teardown has to run before that // destructor. On Apple platforms it runs during exit, before the first static -// of libllamadart is destroyed. Elsewhere it runs only when -// llama_dart_exit_teardown is called. +// of libllamadart is destroyed. +// +// On Linux, Android excepted, C exit() runs the wait of teardown and frees +// nothing. By the time the exit goes on to what other libraries do at exit, +// the calls in flight have ended and every thread that reaches libllamadart +// is blocked. Nothing on Linux needs the objects freed, and an exit with a +// model left loaded is known to be clean, which a free among the exit +// handlers of a GPU driver is not. llama.cpp is not part of libllamadart +// there, and its libraries register no static destructors: their statics stay +// valid until the process is gone, also under a call that the wait does not +// cover. The wait begins when the exit reaches the handler that libllamadart +// registers at the first creating call and again when the first object is +// tracked, so an exit handler that another library registers later runs +// before it. While teardown waits, on Linux a decode or an encode on the CPU +// backend ends with the status llama.cpp has for an aborted one, 2, unless +// its context has an abort callback of its own. quick_exit and _exit run +// nothing. +// +// Elsewhere nothing runs at exit. llama_dart_exit_teardown runs teardown, and +// frees, on every platform. // // Objects are tracked, before the creating call returns, by // llama_dart_model_load_from_file, llama_dart_init_from_model, @@ -449,7 +467,9 @@ LLAMADART_API struct llama_model * llama_dart_model_load_from_file( struct llama_model_params params); // llama_init_from_model that tracks the context in the CONTEXT stage. Free it -// with llama_dart_exit_free. Blocks after teardown. +// with llama_dart_exit_free. On Linux, when params has no abort callback, the +// context gets the one that ends its evaluations while teardown waits; +// llama_set_abort_callback replaces it. Blocks after teardown. LLAMADART_API struct llama_context * llama_dart_init_from_model( struct llama_model * model, struct llama_context_params params); diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 75a8387c..ebb6e2d0 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -464,15 +464,49 @@ int test_blocked() { return 0; } +// C exit() runs teardown on Apple platforms. On Linux it runs the wait of +// teardown and frees nothing, and teardown ends a decode or an encode on the +// CPU backend while it waits for the calls in flight, with llama.cpp's status +// for an aborted one. #if defined(__APPLE__) -const bool kTeardownRunsAtExit = true; +const bool kExitFreesObjects = true; +const bool kExitWaitsForCalls = true; +const bool kTeardownEndsEvaluations = false; +#elif defined(__linux__) && !defined(__ANDROID__) +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = true; +const bool kTeardownEndsEvaluations = true; #else -const bool kTeardownRunsAtExit = false; +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = false; +const bool kTeardownEndsEvaluations = false; #endif +// Set by a scenario before the teardown that an evaluation may run into. +std::atomic g_teardown_expected{false}; + +bool evaluated(int32_t status) { + return status == 0 || (status == 2 && kTeardownEndsEvaluations && + g_teardown_expected.load()); +} + +// Where the backends are modules next to the llama.cpp libraries and not part +// of libllamadart, a scenario that computes has to load one. The CPU backend +// alone keeps the scenarios the same whatever other modules the build has. +void load_backend_modules() { +#if defined(LLAMADART_TEST_CPU_BACKEND) + assert(ggml_backend_load(LLAMADART_TEST_CPU_BACKEND) != nullptr); +#endif +} + +void init_backends() { + llama_backend_init(); + load_backend_modules(); +} + void expect_freed_at_exit() { const std::vector expected = - kTeardownRunsAtExit ? kStageOrder : std::vector(); + kExitFreesObjects ? kStageOrder : std::vector(); if (recorded() != expected) { fprintf(stderr, "exit teardown freed %zu objects, expected %zu\n", recorded().size(), expected.size()); @@ -487,6 +521,37 @@ int test_exit() { return 0; } +std::atomic g_call_ended{false}; + +void expect_call_ended_at_exit() { + if (kExitWaitsForCalls && !g_call_ended.load()) { + fprintf(stderr, "the exit did not wait for the call in flight\n"); + _Exit(EXIT_FAILURE); + } +} + +// The exit waits for a call in flight when objects were only tracked, with +// no creating call. +int test_exit_in_flight() { + // Registered first, so it runs after the teardown registered by tracking. + assert(atexit(expect_call_ended_at_exit) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + static std::atomic started{false}; + std::thread([] { + llama_dart_exit_call_begin(); + started.store(true); + sleep_ms(400); + g_call_ended.store(true); + llama_dart_exit_call_end(); + }).detach(); + while (!started.load()) { + sleep_ms(1); + } + return 0; +} + std::string g_system_info; // Uses the static behind llama_print_system_info, which teardown must find @@ -511,7 +576,7 @@ int test_late_static() { g_system_info = llama_print_system_info(); // The reader needs text that lives on the heap for a sanitizer to see a use // after the static is gone. There is none where no backend is loaded. - assert(!kTeardownRunsAtExit || g_system_info.size() > 64); + assert(!kExitFreesObjects || g_system_info.size() > 64); return 0; } @@ -661,6 +726,7 @@ struct model_options { bool cpu_only = false; bool embeddings = false; ggml_backend_sched_eval_callback eval_callback = nullptr; + ggml_abort_callback abort_callback = nullptr; }; struct model_fixture { @@ -670,7 +736,7 @@ struct model_fixture { }; model_fixture load_model(const char *path, model_options options = {}) { - llama_backend_init(); + init_backends(); model_fixture fixture; auto model_params = llama_model_default_params(); static ggml_backend_dev_t no_devices[] = {nullptr}; @@ -685,6 +751,7 @@ model_fixture load_model(const char *path, model_options options = {}) { context_params.n_ctx = 256; context_params.embeddings = options.embeddings; context_params.cb_eval = options.eval_callback; + context_params.abort_callback = options.abort_callback; fixture.context = options.tracked ? llama_dart_init_from_model(fixture.model, context_params) @@ -716,8 +783,11 @@ llama_sampler *greedy_sampler() { // One generation step as the Dart side runs it: decode, then sample. llama_token decode_and_sample(model_fixture &fixture, llama_sampler *sampler) { clear_memory(fixture); - assert(llama_dart_decode(fixture.context, prompt(fixture)) == 0); - return llama_dart_sampler_sample(sampler, fixture.context, -1); + const int32_t status = llama_dart_decode(fixture.context, prompt(fixture)); + assert(evaluated(status)); + // A decode that teardown ended has left nothing to sample. + return status == 0 ? llama_dart_sampler_sample(sampler, fixture.context, -1) + : 0; } // Exits with a loaded model and context that nothing frees. @@ -838,7 +908,7 @@ int test_model_wrappers(const char *path) { } int test_graph() { - llama_backend_init(); + init_backends(); ggml_backend_t backend = llama_dart_ggml_backend_dev_init( ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr); assert(backend != nullptr); @@ -1155,6 +1225,7 @@ int test_evaluation_wait(const char *path, void (*evaluate)(model_fixture &), llama_dart_exit_set_wait_ms(30000); held_evaluate = evaluate; g_hold_evaluation.store(true); + g_teardown_expected.store(true); std::thread([] { held_evaluate(fixture); }).detach(); while (!g_evaluation_held.load()) { sleep_ms(1); @@ -1169,11 +1240,11 @@ int test_evaluation_wait(const char *path, void (*evaluate)(model_fixture &), } void decode_prompt(model_fixture &fixture) { - assert(llama_dart_decode(fixture.context, prompt(fixture)) == 0); + assert(evaluated(llama_dart_decode(fixture.context, prompt(fixture)))); } void encode_prompt(model_fixture &fixture) { - assert(llama_dart_encode(fixture.context, prompt(fixture)) == 0); + assert(evaluated(llama_dart_encode(fixture.context, prompt(fixture)))); } // Evaluates a text chunk, which needs no mtmd context. @@ -1182,9 +1253,13 @@ void eval_text_chunk(model_fixture &fixture) { const mtmd_input_chunk *text = mtmd_input_chunks_get(chunks, 0); assert(mtmd_input_chunk_get_type(text) == MTMD_INPUT_CHUNK_TYPE_TEXT); llama_pos position = 0; - assert(llama_dart_mtmd_helper_eval_chunk_single( - nullptr, fixture.context, text, 0, 0, 16, true, &position) == 0); - assert(position == 5); + const int32_t status = llama_dart_mtmd_helper_eval_chunk_single( + nullptr, fixture.context, text, 0, 0, 16, true, &position); + if (status == 0) { + assert(position == 5); + } else { + assert(kTeardownEndsEvaluations && g_teardown_expected.load()); + } mtmd_input_chunks_free(chunks); } @@ -1221,6 +1296,7 @@ int exit_while_generating(model_fixture &fixture) { while (steps.load() < 4) { sleep_ms(1); } + g_teardown_expected.store(true); g_exiting.store(true); return 0; } @@ -1232,6 +1308,83 @@ int test_model_decode(const char *path) { return exit_while_generating(fixture); } +std::atomic g_computed_after_release{0}; + +// Holds the evaluation and, once it is released, has each tensor computed on +// its own so that the ones computed from then on can be counted. +bool hold_then_count_evaluation(ggml_tensor *tensor, bool ask, void *data) { + if (!ask) { + g_computed_after_release.fetch_add(1); + return true; + } + hold_evaluation(tensor, ask, data); + return g_release_evaluation.load(); +} + +void finish_held_evaluation_at_exit() { + g_release_evaluation.store(true); + const int64_t started = now_ms(); + while (g_computed_after_release.load() < 16) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the held decode did not go on during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// On Linux teardown ends a decode in flight on the CPU backend instead of +// sitting it out: the held decode computes no tensor to the end once teardown +// waits for it. +int test_model_decode_ended(const char *path) { + static model_fixture fixture; + model_options options; + options.eval_callback = hold_then_count_evaluation; + fixture = load_model(path, options); + decode_prompt(fixture); + clear_memory(fixture); + llama_dart_exit_set_wait_ms(30000); + g_hold_evaluation.store(true); + g_teardown_expected.store(true); + std::thread([] { decode_prompt(fixture); }).detach(); + while (!g_evaluation_held.load()) { + sleep_ms(1); + } + start_beat(); + std::thread(release_when_teardown_waits).detach(); + llama_dart_exit_teardown(); + assert(!g_released_before_teardown.load()); + assert(g_computed_after_release.load() == 0); + assert(llama_dart_exit_tracked_count() == 0); + return 0; +} + +// Exits while another thread is inside a decode that outlasts teardown's +// wait. On Linux the llama.cpp libraries register no static destructors, so +// the decode computes on, with the statics the model load created, after the +// exit has run its handlers. +int test_model_decode_outlasts_wait(const char *path) { + // Registered first, so it runs after teardown and after the destructors of + // the statics that the load creates, where those are registered. + assert(atexit(finish_held_evaluation_at_exit) == 0); + static model_fixture fixture; + model_options options; + options.eval_callback = hold_then_count_evaluation; + // The caller's own callback, which libllamadart leaves in place: teardown + // does not end this decode. + options.abort_callback = [](void *) { return false; }; + fixture = load_model(path, options); + decode_prompt(fixture); + clear_memory(fixture); + llama_dart_exit_set_wait_ms(100); + g_hold_evaluation.store(true); + std::thread([] { decode_prompt(fixture); }).detach(); + while (!g_evaluation_held.load()) { + sleep_ms(1); + } + return 0; +} + // Exits while another thread generates on a model whose load created statics // in libllamadart that an earlier, different load had not: a CPU-only load, // then one that maps the file into GPU memory. @@ -1248,9 +1401,21 @@ int test_model_late_load(const char *path) { return exit_while_generating(second); } +std::atomic g_load_resumed{false}; + +void expect_exit_waited_for_load() { + if (kExitWaitsForCalls && !g_load_resumed.load()) { + fprintf(stderr, "the exit did not wait for the load in flight\n"); + _Exit(EXIT_FAILURE); + } +} + // Exits while another thread is loading the model. int test_model_load(const char *path) { - llama_backend_init(); + // Registered first, so it runs after teardown, which nothing but the load + // in flight makes run: nothing is tracked. + assert(atexit(expect_exit_waited_for_load) == 0); + init_backends(); static std::atomic loading{false}; static const char *model_path = nullptr; model_path = path; @@ -1269,6 +1434,7 @@ int test_model_load(const char *path) { sleep_ms(1); } sleep_ms(500); + g_load_resumed.store(true); return true; }; std::thread([params] { @@ -1285,7 +1451,7 @@ int test_model_load(const char *path) { // Teardown waits for a load in flight although nothing is tracked yet. int test_model_load_wait(const char *path) { - llama_backend_init(); + init_backends(); static std::atomic loading{false}; static std::atomic held{false}; static const char *model_path = nullptr; @@ -2137,7 +2303,7 @@ using tokens = std::vector; // and stops at an end-of-generation token that the draft predicted, as // llama.cpp's common_sampler_sample_and_accept_n does. int test_model_sample_accept(const char *path) { - llama_backend_init(); + init_backends(); auto model_params = llama_model_default_params(); // On the CPU, where every device can run the backend sampler's argmax: the // Metal device of a virtual machine cannot. @@ -2288,6 +2454,9 @@ int main(int argc, char **argv) { if (scenario == "exit") { return test_exit(); } + if (scenario == "exit-in-flight") { + return test_exit_in_flight(); + } if (scenario == "late-static") { return test_late_static(); } @@ -2367,6 +2536,12 @@ int main(int argc, char **argv) { if (scenario == "model-decode") { return test_model_decode(first); } + if (scenario == "model-decode-ended") { + return test_model_decode_ended(first); + } + if (scenario == "model-decode-outlasts-wait") { + return test_model_decode_outlasts_wait(first); + } if (scenario == "model-late-load") { return test_model_late_load(first); } diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index 997468e2..fc8f1fbd 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -15,6 +15,26 @@ 0000000000004b20 T _llama_dart_decode """ +# readelf -Ws of an ELF library that imports two functions and has a hidden +# definition of __cxa_atexit in its full symbol table. +READELF_OUTPUT = """\ + +Symbol table '.dynsym' contains 3 entries: + Num: Value Size Type Bind Vis Ndx Name + 1: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@GLIBC_2.17 (2) + 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND dlsym@GLIBC_2.34 (3) + 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 llama_dart_decode + +Symbol table '.symtab' contains 1 entry: + Num: Value Size Type Bind Vis Ndx Name + 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 __cxa_atexit +""" + +READELF_IMPORT = ( + ' 4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND ' + '__cxa_atexit@GLIBC_2.17 (2)\n' +) + class ValidateExportsTests(unittest.TestCase): def test_nm_exports_and_imports_are_told_apart(self): @@ -25,7 +45,17 @@ def test_nm_exports_and_imports_are_told_apart(self): validate_exports.imported_symbols_from_nm(NM_OUTPUT), {'__cxa_finalize', 'dlsym'}) - def run_tool(self, nm_output, *arguments, library_bytes=b''): + def test_readelf_imports_are_the_undefined_symbols(self): + self.assertEqual( + validate_exports.imported_symbols_from_readelf(READELF_OUTPUT), + {'__cxa_finalize', 'dlsym'}) + self.assertEqual( + validate_exports.imported_symbols_from_readelf( + READELF_OUTPUT + READELF_IMPORT), + {'__cxa_finalize', 'dlsym', '__cxa_atexit'}) + + def run_tool(self, nm_output, *arguments, library_bytes=b'', + tool_format='nm', symbol='llama_dart_decode'): with tempfile.TemporaryDirectory() as temp: library = Path(temp) / 'libllamadart.dylib' library.write_bytes(library_bytes) @@ -36,10 +66,49 @@ def run_tool(self, nm_output, *arguments, library_bytes=b''): tool.chmod(0o755) return subprocess.run( [sys.executable, str(ROOT / 'tools/validate_exports.py'), - '--format', 'nm', '--tool', str(tool), - '--symbol', 'llama_dart_decode', *arguments, str(library)], + '--format', tool_format, '--tool', str(tool), + '--symbol', symbol, *arguments, str(library)], capture_output=True, text=True) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_forbidden_import_in_readelf_output(self): + # The hidden definition in the symbol table is not an import. + absent = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(absent.returncode, 0, absent.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_imports_only_skips_the_required_exports(self): + # A llama.cpp library exports none of the wrapper's functions. + missing = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(missing.returncode, 1) + self.assertIn('llama_dart_encode', missing.stderr) + + skipped = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', '--imports-only', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(skipped.returncode, 0, skipped.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + '--imports-only', tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + unchecked = self.run_tool( + READELF_OUTPUT, '--imports-only', tool_format='readelf') + self.assertEqual(unchecked.returncode, 2) + self.assertIn('--forbid-import', unchecked.stderr) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') def test_forbidden_import_fails_only_when_imported(self): absent = self.run_tool(NM_OUTPUT, '--forbid-import', '__cxa_atexit') diff --git a/tests/validate_linux_artifact_test.py b/tests/validate_linux_artifact_test.py index 79e38d0f..0d504cfc 100644 --- a/tests/validate_linux_artifact_test.py +++ b/tests/validate_linux_artifact_test.py @@ -16,6 +16,7 @@ from tools.validate_linux_artifact import ( extract_archive, extract_member_safely, + parse_imports, resolve_tool, validate_archive, ) @@ -238,6 +239,91 @@ def test_multi_hop_symlink_cycles_are_rejected(self) -> None: errors, ) + def test_imports_are_the_undefined_dynamic_symbols(self) -> None: + readelf = ( + "Symbol table '.dynsym' contains 4 entries:\n" + " Num: Value Size Type Bind Vis Ndx Name\n" + " 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND \n" + " 1: 0000000000000000 0 FUNC WEAK DEFAULT UND " + "__cxa_finalize@GLIBC_2.17 (2)\n" + " 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + " 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(readelf, "readelf"), {"__cxa_finalize", "__cxa_atexit"} + ) + objdump = ( + "DYNAMIC SYMBOL TABLE:\n" + "0000000000000000 w DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_finalize\n" + "0000000000000000 DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_atexit\n" + "0000000000004b20 g DF .text\t0000000000000040 Base " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(objdump, "objdump"), {"__cxa_finalize", "__cxa_atexit"} + ) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_a_local_library_must_not_import_cxa_atexit(self) -> None: + dynamic = " 0x000000000000000e (SONAME) Library soname: [{soname}]\n" + imported = ( + " 1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + ) + defined = ( + " 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 " + "__cxa_atexit\n" + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + names = ( + "libllamadart.so", + "libmtmd.so.0", + "libggml-cuda.so", + "libopenblas.so.0", + ) + with tarfile.open(archive_path, "w:gz") as archive: + for name in names: + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + + # Answers readelf -d with the file's own name as its SONAME, and + # the symbol listing with the text under test. + symbols = root / "symbols.txt" + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + f" printf '{dynamic.format(soname='%s')}' \"$(basename \"$2\")\"\n" + "else\n" + f' cat "{symbols}"\n' + "fi\n" + ) + tool.chmod(0o755) + + symbols.write_text(imported) + errors = validate_archive(archive_path, str(tool), "readelf") + self.assertEqual( + errors, + [ + f"{name}: imports __cxa_atexit, so C exit() destroys its statics" + for name in ("libggml-cuda.so", "libllamadart.so", "libmtmd.so.0") + ], + ) + + symbols.write_text(defined) + self.assertEqual(validate_archive(archive_path, str(tool), "readelf"), []) + def test_missing_explicit_tool_reports_a_clean_cli_error(self) -> None: with tempfile.TemporaryDirectory() as directory: missing_tool = Path(directory) / "missing-readelf" diff --git a/tools/validate_exports.py b/tools/validate_exports.py index 03f8f0ad..bd86a56c 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -126,7 +126,16 @@ def parse_args() -> argparse.Namespace: default=[], help=( "Symbol the library must not import. Supported for --format nm " - "and single-architecture files." + "on Mach-O and --format readelf on ELF, and for " + "single-architecture files." + ), + ) + parser.add_argument( + "--imports-only", + action="store_true", + help=( + "Check only --forbid-import, for a library that has none of the " + "required exports, such as a llama.cpp library next to the wrapper." ), ) return parser.parse_args() @@ -178,6 +187,15 @@ def exported_symbols_from_readelf(output: str) -> set[str]: return symbols +def imported_symbols_from_readelf(output: str) -> set[str]: + symbols: set[str] = set() + for line in output.splitlines(): + parts = line.split() + if len(parts) >= 8 and parts[6] == "UND": + symbols.add(parts[7].split("@", 1)[0]) + return symbols + + def exported_symbols_from_nm(output: str) -> set[str]: symbols: set[str] = set() for line in output.splitlines(): @@ -216,8 +234,13 @@ def exported_symbols_from_dumpbin(output: str) -> set[str]: def main() -> int: args = parse_args() - if args.forbidden_imports and args.format != "nm": - print("--forbid-import requires --format nm", file=sys.stderr) + # nm names are read as Mach-O ones, without their leading underscore, so + # an ELF import such as __cxa_atexit would never match. + if args.forbidden_imports and args.format not in ("nm", "readelf"): + print("--forbid-import requires --format nm or readelf", file=sys.stderr) + return 2 + if args.imports_only and not args.forbidden_imports: + print("--imports-only requires --forbid-import", file=sys.stderr) return 2 # nm lists only the host architecture of a universal file, so the other # slices would go unchecked. @@ -233,7 +256,9 @@ def main() -> int: "nm": exported_symbols_from_nm, "dumpbin": exported_symbols_from_dumpbin, }[args.format](output) - required = args.symbols or DEFAULT_REQUIRED_SYMBOLS + required = ( + [] if args.imports_only else args.symbols or DEFAULT_REQUIRED_SYMBOLS + ) missing = [symbol for symbol in required if symbol not in exported] if missing: print(f"Missing exports in {args.library}:", file=sys.stderr) @@ -241,7 +266,11 @@ def main() -> int: print(f" - {symbol}", file=sys.stderr) return 1 - imported = imported_symbols_from_nm(output) + imported = ( + imported_symbols_from_readelf(output) + if args.format == "readelf" + else imported_symbols_from_nm(output) + ) forbidden = [s for s in args.forbidden_imports if s in imported] if forbidden: print(f"Forbidden imports in {args.library}:", file=sys.stderr) diff --git a/tools/validate_linux_artifact.py b/tools/validate_linux_artifact.py index 96ab30cf..b2060fd8 100644 --- a/tools/validate_linux_artifact.py +++ b/tools/validate_linux_artifact.py @@ -16,6 +16,12 @@ LOCAL_LIBRARY_PREFIXES = ("libllamadart", "libllama", "libggml", "libmtmd") +# The libraries built here bind __cxa_atexit to a definition of their own: +# libllamadart to the one that runs exit teardown first, the llama.cpp +# libraries to the one that registers no static destructor +# (src/llama_dart_static_destructors.c). One that imports it has its statics +# destroyed by C exit() under the calls in flight. +FORBIDDEN_LOCAL_IMPORTS = ("__cxa_atexit",) PLACEHOLDER = "SOVERSION" MAX_ERROR_DETAIL_LENGTH = 512 TARFILE_EXTRACT_SUPPORTS_FILTER = ( @@ -94,6 +100,26 @@ def inspect_dynamic(path: Path, tool: str, mode: str) -> DynamicMetadata: return DynamicMetadata(soname=soname, needed=tuple(needed), raw=raw) +def parse_imports(raw: str, mode: str) -> set[str]: + imports: set[str] = set() + for line in raw.splitlines(): + parts = line.split() + if mode == "objdump": + if "*UND*" in parts and parts[-1] != "*UND*": + imports.add(parts[-1].split("@", 1)[0]) + elif len(parts) >= 8 and parts[6] == "UND": + imports.add(parts[7].split("@", 1)[0]) + return imports + + +def inspect_imports(path: Path, tool: str, mode: str) -> set[str]: + options = ["-T"] if mode == "objdump" else ["--dyn-syms", "-W"] + result = subprocess.run( + [tool, *options, str(path)], check=True, capture_output=True, text=True + ) + return parse_imports(result.stdout, mode) + + def safe_member_name(name: str) -> str: normalized = name.removeprefix("./") path = PurePosixPath(normalized) @@ -237,6 +263,22 @@ def validate_archive(archive_path: Path, tool: str, mode: str) -> list[str]: for dependency in dynamic.needed: if dependency.startswith(LOCAL_LIBRARY_PREFIXES) and dependency not in names: errors.append(f"{name}: local DT_NEEDED dependency is absent: {dependency}") + if name.startswith(LOCAL_LIBRARY_PREFIXES): + try: + imports = inspect_imports(root / name, tool, mode) + except subprocess.CalledProcessError as error: + errors.append( + f"{name}: symbol inspection failed with exit code {error.returncode}" + ) + continue + except OSError as error: + errors.append(f"{name}: symbol inspection failed: {error}") + continue + for symbol in FORBIDDEN_LOCAL_IMPORTS: + if symbol in imports: + errors.append( + f"{name}: imports {symbol}, so C exit() destroys its statics" + ) mtmd = metadata.get("libmtmd.so") if mtmd is None: From c9bc619b8848e91922bba7b9f53a2b80276d5dfd Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 10:33:41 -0400 Subject: [PATCH 2/8] docs: describe C exit on Linux for the v0.6.0-2 wrapper rebuild --- AGENTS.md | 3 + README.md | 37 ++++- docs/v060_1_wrapper_rebuild.md | 3 + docs/v060_2_wrapper_rebuild.md | 243 +++++++++++++++++++++++++++++++++ 4 files changed, 279 insertions(+), 7 deletions(-) create mode 100644 docs/v060_2_wrapper_rebuild.md diff --git a/AGENTS.md b/AGENTS.md index fbbb24b6..b8187b0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,9 @@ See `docs/v060_qualification.md` for the v0.6.0 wrapper adapters, candidate lane and the Android ISA evidence required before publication or downstream adoption. See `docs/v060_1_wrapper_rebuild.md` for the `v0.6.0-1` header additions and what each export returns after a caught exception. +See `docs/v060_2_wrapper_rebuild.md` for what C `exit()` does on Linux from +`v0.6.0-2`, and why the llama.cpp libraries register no static destructors +there. - `.github/workflows/native_release.yml` - Exact native build + release workflow, used by manual dispatch and the diff --git a/README.md b/README.md index db72b11b..227ab091 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,8 @@ Assets are suffixed with platform/arch, for example: - `tools/package_linux_artifact.py`: preserves Linux ELF version files and SONAME symlinks while transporting split CI artifacts. - `tools/validate_linux_artifact.py`: checks Linux archive members, symlinks, - SONAMEs, and local `DT_NEEDED` dependencies. + SONAMEs, and local `DT_NEEDED` dependencies, and that no library built here + imports `__cxa_atexit`. - `tools/package_apple_xcframework.py`: packages Apple `libllamadart` slices as an SPM-compatible XCFramework zip. - `tools/apple/PrivacyInfo.xcprivacy`: privacy manifest embedded in every @@ -286,15 +287,37 @@ left of it at exit: upstream function is tracked but not freed at exit, so a caller that has not switched to the tracked functions keeps its previous exit behavior. -On other platforms nothing runs at exit; `llama_dart_exit_teardown` runs the -same teardown on request and must be followed directly by `exit`. It is for -native hosts: like `llama_dart_exit_call_begin` and `llama_dart_exit_call_end`, -it is not meant to be bound from Dart. +On Linux, Android excepted, C `exit` destroyed the statics of llama.cpp under +the threads that were still inside it, and those crashed +([llamadart#949](https://github.com/leehack/llamadart/issues/949)). There: + +- The llama.cpp libraries of the bundle register no static destructors + (`src/llama_dart_static_destructors.c`), so their statics stay valid until + the process is gone. On Linux they are separate libraries, and no exit + handler of `libllamadart` can be ordered before the destructor of a static + that another library creates later. +- C `exit` runs the wait of teardown and frees nothing: it waits for the + calls in flight as above, cancels a model load, ends a decode or an encode + on the CPU backend (status 2, unless the context has an abort callback of + its own), and blocks the threads that reach `libllamadart` afterwards. The + exit handlers and destructors of other libraries, such as a GPU driver or + OpenBLAS, then run with no call in flight. +- The wait runs at the handler registered at the first creating call and + again at the first tracked object. An exit handler that another library + registers later runs before it. + +[`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) has the +measurements and what is not verified. + +On other platforms nothing runs at exit. `llama_dart_exit_teardown` runs +teardown on request on every platform, frees included, and must be followed +directly by `exit`. It is for native hosts: like `llama_dart_exit_call_begin` +and `llama_dart_exit_call_end`, it is not meant to be bound from Dart. `src/llama_dart_wrapper.h` documents each function. `llamadart_exit_teardown_test` covers the registry on every platform. On macOS -it also writes a small decoder and a small encoder model and runs the -scenarios that load one, so ctest needs no model file: +and Linux it also writes a small decoder and a small encoder model and runs +the scenarios that load one, so ctest needs no model file: ```bash cmake -S . -B build/exit-teardown -G Ninja -DLLAMADART_BUILD_TESTS=ON diff --git a/docs/v060_1_wrapper_rebuild.md b/docs/v060_1_wrapper_rebuild.md index 11409b73..405ac284 100644 --- a/docs/v060_1_wrapper_rebuild.md +++ b/docs/v060_1_wrapper_rebuild.md @@ -338,6 +338,9 @@ Why the Apple mechanism does not carry over: measure either effect, and the Linux lanes here load no backend, so they run no model scenario. +`v0.6.0-2` fixes it, with the wait and without the frees as recommended below +but without the gate: see [`v060_2_wrapper_rebuild.md`](v060_2_wrapper_rebuild.md). + Recommended design, for a later rebuild: 1. Compile a small object into every shared library of the bundle that holds diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md new file mode 100644 index 00000000..712b3b1b --- /dev/null +++ b/docs/v060_2_wrapper_rebuild.md @@ -0,0 +1,243 @@ +# v0.6.0-2 wrapper rebuild + +Wrapper-only changes on llama.cpp `v0.6.0` +(`d81235049384534c167caea52b85a694f6103d14`) for the native rebuild tag +`v0.6.0-2`. The exported header gains no declaration and loses none: the 85 +symbols of `v0.6.0-1` are the 85 of this rebuild. Only Linux builds change; +the macOS library built from this tree is byte-for-byte the one built from +`v0.6.0-1` (see "Checks"). + +## Exit on Linux + +Issue: [llamadart#949](https://github.com/leehack/llamadart/issues/949). A C +`exit()` while another thread is inside llama.cpp killed the process on +Linux. `exit()` destroys C++ statics that the thread still reads: + +| Frame of the crash | Static | Created | +| --- | --- | --- | +| `ggml_cpu_extra_compute_forward`, `ggml_cpu_extra_work_size` | the vector in `ggml_backend_cpu_get_extra_buffer_types` (`libggml-cpu.so`) | on first use, before the first decode | +| `ggml_backend_dev_type` under `llama_model_load_from_file` | a device of ggml's registry; not traced to one static | before the load | +| `unicode_utf8_to_byte` under `llama_vocab::impl::load` | the map in `unicode_utf8_to_byte` (`libllama.so`) | in the middle of the first model load | + +The third one is why registering an exit handler is not enough. `exit()` +runs one list of handlers and static destructors in reverse order of +registration, so no handler that libllamadart registers before a load runs +before the destructor of a static that the load creates. On Apple platforms +llama.cpp is part of `libllamadart.dylib`, and a definition of `__cxa_atexit` +inside that image orders teardown before all of them. On Linux they are +separate libraries, some of them modules that ggml loads and unloads while it +looks for the best backend. + +### What changes + +1. The llama.cpp libraries register no static destructors. + `src/llama_dart_static_destructors.c` defines a hidden `__cxa_atexit` that + registers nothing, and `CMakeLists.txt` adds it to every shared library and + backend module under `third_party/llama.cpp`, whatever backends the build + enables. The statics stay valid until the process is gone: also for a call + that teardown does not wait for, and for one that outlasts its wait. + Upstream sources are not patched. +2. C `exit()` runs the wait of exit teardown. libllamadart registers the + handler at the first creating call (`llama_dart_model_load_from_file`, + `llama_dart_init_from_model`, `llama_dart_mtmd_init_from_file`, the TTS, + speculative, MTP and n-gram init functions), so that an exit during the + first load finds one, and again when the first object is tracked. The wait is the one of + `llama_dart_exit_teardown`: up to 2 s (`llama_dart_exit_set_wait_ms`) for + the calls in flight, a model load is cancelled, then 250 ms after the last + call, and from then on every thread that reaches libllamadart is blocked. + The exit handlers and destructors of other libraries run after it. +3. The exit frees nothing. Apple frees the tracked objects because + ggml-metal aborts over a live buffer. Nothing on Linux does, the issue + found an exit with a model left loaded clean on CPU, Vulkan and CUDA, and a + free during `exit()` would run among the exit handlers of the GPU driver in + an order that nothing controls. `llama_dart_exit_teardown` called by a + native host still frees. +4. While teardown waits, a decode or an encode on the CPU backend ends with + llama.cpp's status for an aborted evaluation (2). + `llama_dart_init_from_model` sets the context's abort callback for that + when the caller passes none. Without it a long decode outlasts the wait and + is still running when the exit reaches other libraries: with the BLAS + module, OpenBLAS's destructor then never returns (see "Measurements"). + llama.cpp logs three error lines for the ended decode. +5. libllamadart itself binds `__cxa_atexit` to the definition that Apple + uses, so a static of its own is destroyed only after the wait. + +`tools/validate_linux_artifact.py`, which the release runs on every Linux +archive, fails an archive in which a library built here imports +`__cxa_atexit`. + +### Why not a gate in front of every destructor + +[`v060_1_wrapper_rebuild.md`](v060_1_wrapper_rebuild.md) recommended a hidden +`__cxa_atexit` in every library that registers each destructor behind a gate +exported by `libggml-base.so`, which libllamadart points at teardown. The wait +without frees is taken from there. The gate is not: + +- ggml unloads a backend module that it loaded only to score it, or that + failed to initialize. `dlclose` runs the destructors that the module + registered, and each would run the gate, which is teardown, in the middle of + a run. +- A destructor behind a gate still runs once the wait is over. A call that + outlasts the wait would crash as before, which was 10 of 10 for a long + decode with a slow host below. +- It would add an exported symbol to an upstream library. + +### What it does not cover + +- An exit handler that another library registers after the two handlers above + runs before the wait, under the calls in flight. A GPU driver that + registers one late, during a decode for example, is in that position. + Statics that llama.cpp creates late no longer matter. +- A call that is not a call in flight is not waited for, as on Apple. Its + statics stay valid on Linux; what it uses of other libraries may not. +- A call in flight that outlasts the wait and cannot be ended: a decode on a + GPU backend, which does not read the abort callback, an image or audio + evaluation, or a context with an abort callback of its own. The exit then + goes on with the call running. +- `quick_exit` and `_exit` run no handler, as before. Neither destroys + statics. +- A child of `fork` that calls `exit()` runs the handler with the registry it + copied: it waits out the wait time for calls that are not its own. +- An exit handler that code inside a llama.cpp library registers with + `atexit` binds to the same definition and is dropped. No backend built here + registers one; a library such as the CUDA runtime, which the modules load + as a library of its own, is not affected. + +### Other platforms + +- musl: nothing here is specific to glibc. The definition binds at link + time, and libllamadart reaches the C library's `__cxa_atexit` through + `dlsym(RTLD_NEXT)`. No bundle is built for musl and none was run. +- Android: left as it was, by `!defined(__ANDROID__)` in the two sources and + `CMAKE_SYSTEM_NAME STREQUAL "Linux"` in CMake. bionic orders exit handlers + the same way, but the issue has no Android measurement and nothing here ran + on Android. +- Windows: not applicable, going by the documented behavior of the C runtime + and not by a run. `exit()` ends in `ExitProcess`, which terminates + the other threads before any DLL destroys its statics, so a thread is gone + before the statics it read are destroyed. A handler in `llamadart.dll` runs + at `DLL_PROCESS_DETACH`, under the loader lock and after those threads were + terminated: it could wait for nothing, and a lock that a terminated thread + held stays held. A wait there would have to run in the host before + `ExitProcess`, which is `llama_dart_exit_teardown`'s job. No Windows crash + of this kind is known, and no lane could show one. + +## Measurements + +Linux arm64 container (Ubuntu 24.04, glibc 2.39, GCC 13.3) on an Apple M4 +Max, the `linux-arm64-full` preset without KleidiAI: Release with link-time +optimization, OpenMP, the CPU, Vulkan and BLAS modules. A probe opens +`libllamadart.so` with `dlopen`, as Dart does, and calls C `exit()` from the +main thread while another thread is inside a guarded call. "Slow host" adds +an exit handler of the probe's own that takes 300 ms, registered before the +library is opened and so run last, as the handlers of a larger host are. +Vulkan is Mesa 25.2.8 lavapipe (`llvmpipe`, `GGML_VK_VISIBLE_DEVICES=0`, all +layers offloaded); BLAS is OpenBLAS 0.3.26. The numbers are failed runs of +10: a signal, an exit code other than 0, a failed `GGML_ASSERT`, or no exit +within 120 s. + +CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. + +| Exit | Modules | Host | `v0.6.0-1` | This rebuild | +| --- | --- | --- | --- | --- | +| while generating (decode and sample in a loop) | CPU | fast | 7 | 0 | +| | CPU | slow | 10 | 0 | +| | CPU, BLAS | slow | 10 | 0 | +| | Vulkan | fast | 5 | 0 | +| | Vulkan | slow | 10 | 0 | +| inside one decode of 1500 tokens | CPU | fast | 1 | 0 | +| | CPU | slow | 10 | 0 | +| | CPU, BLAS | slow | 10 | 0 | +| | Vulkan | fast | 0 | 0 | +| | Vulkan | slow | 6 | 0 | +| 100 ms into the first load | CPU | slow | 9 | 0 | +| 400 ms into the first load | CPU | slow | 6 | 0 | +| 200 ms and 800 ms into the first load | CPU | fast | 0, 0 | 0, 0 | +| 5 ms and 60 ms into the first load | Vulkan | fast | 0, 0 | 0, 0 | +| | Vulkan | slow | 10, 10 | 0, 0 | +| first load, once tensors are loading | CPU, Vulkan | fast, slow | 0 | 0 | +| halfway through a second load | CPU | slow | 1 | 0 | +| | CPU, Vulkan | fast | 0 | 0 | +| `return` from `main` while generating | CPU | fast | 8 | 0 | +| | Vulkan | fast | 3 | 0 | +| model idle; everything freed; `return` from `main` with a model idle | CPU, BLAS, Vulkan | fast, slow | 0 | 0 | + +`v0.6.0-1` is its source, `ceae6f7`, built in the same container. Every +failed run of it ended in a signal: `SIGSEGV`, and in five lavapipe runs +`SIGABRT` (`double free or corruption`). The scenarios that were clean before +are clean after, with the model left loaded and not freed. + +Two measurements on the way decided parts of the design: + +- Without the abort callback, the 1500-token decode with the BLAS module + hung in OpenBLAS's destructor (`gotoblas_quit`, `blas_thread_shutdown_`) in + 6 of 10 exits and was killed after 120 s; with the callback, 0 of 10. + Without the BLAS module the same exit was clean 10 of 10 either way: the + decode outlasted the wait and ran on, with its statics intact, until the + process was gone. +- A build that also freed the tracked objects during `exit()` was clean in + the 16 lavapipe scenarios it ran (10 of 10 each). That shows nothing about + the NVIDIA driver, which is why the frees stay out. + +On lavapipe the abort callback does not end the 1500-token decode: ggml-vulkan +does not read it. + +## Checks + +```bash +cmake -S . -B build/wrapper-contract -G Ninja -DCMAKE_BUILD_TYPE=Debug \ + -DGGML_NATIVE=OFF -DGGML_OPENMP=OFF -DLLAMADART_BUILD_TESTS=ON +cmake --build build/wrapper-contract --target llamadart_exit_teardown_test +ctest --test-dir build/wrapper-contract -R exit_teardown --output-on-failure +for library in build/wrapper-contract/libllamadart.so build/wrapper-contract/bin/*.so; do + python3 tools/validate_exports.py --format readelf --tool readelf \ + --imports-only --forbid-import __cxa_atexit "$library" +done +``` + +`llamadart_exit_teardown_test` now runs its model scenarios on Linux as well, +on the CPU backend module and the models it writes itself. In the container +above: + +- The release preset: 48 of 48 CTest cases, and the 42 exit cases ten times + over. The same 42 four times in a RelWithDebInfo build with + AddressSanitizer, with no report. +- The configuration of the `wrapper-contract` lane (Debug, no OpenMP) on the + pinned upstream and on the post-v0.4.0 one: 48 of 48 each, and the 42 exit + cases five times over. +- The same test source against the libraries of `v0.6.0-1`: `model-decode`, + `model-late-load` and `model-decode-outlasts-wait` end in `SIGSEGV`, and + `model-load` and `model-free-in-flight` report that the exit did not wait, + 5 of 5 each. +- Each part removed in turn fails one scenario: the abort callback + `model-decode-ended`, the handler at the first creating call `model-load`, + the handler at the first tracked object `exit-in-flight`, the exit that + frees nothing `exit`, and the static destructor object + `model-decode-outlasts-wait` (`SIGSEGV`). Without that object + `validate_linux_artifact.py` names seven libraries of the archive. + +`validate_exports.py --forbid-import` now reads ELF imports with +`--format readelf`. With `--format nm` it reads names as Mach-O ones, without +their leading underscore, and an ELF `__cxa_atexit` never matched. + +macOS arm64 (Apple M4 Max), `macos-arm64-full` preset: `libllamadart.dylib` +built from this tree and from `v0.6.0-1` at the same path have the same +SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). +186 Python tests pass (183 before), and the 20 of the Linux artifact tools +(18 before). + +## Not verified + +- A real Vulkan GPU and CUDA. The container has neither; lavapipe is a CPU + implementation with its own threads and exit handlers, which is a different + driver from the NVIDIA one of the issue. The run that settles it is the one + of the issue on its host (GCE L4 VM, Ubuntu 24.04, NVIDIA 580): the + `quit-loaded`, `quit-generating`, `quit-loading`, `return-loaded` and + dispose-then-quit scenarios of llamadart's + `test/fixtures/llama_cpp_exit_probe.dart` on the `v0.6.0-2` bundle, with the + CPU, Vulkan and CUDA backends, at least 10 runs each. +- Linux x64. The measurements are arm64; `validate_wrapper.yml` runs the + scenarios on x64. +- HIP and musl builds, Android and Windows. +- A Dart or Flutter process. The probe is C++; llamadart's own probe runs + against a published bundle. From 87f30ce6e4a2b067d18722b5190fb43512fa23e7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 12:49:59 -0400 Subject: [PATCH 3/8] fix: spend time at C exit on Linux only for a call in flight and block no thread Audit of c9bc619 (not accepted, two P2): - F1: the exit ran the 250 ms settle although it frees nothing. A Dart VM aborts when its isolates run while exit() takes its time, so an exit with an idle model aborted where it was clean before. The exit now returns at once when no call is in flight. - F2: a thread that reached libllamadart after the exit-time wait was blocked for good, which hung a host whose exit handler joins it. After that wait a free now frees nothing, track and untrack return false, and a call in flight that begins returns its failure value with "the process is exiting" as the last error. The draft contexts of the speculative and MTP state get the abort callback too, and the tests find the llama.cpp libraries in a Linux preset build. --- CMakeLists.txt | 19 +++- src/llama_dart_wrapper.cpp | 118 ++++++++++++++------ src/llama_dart_wrapper.h | 38 ++++--- tests/exit_teardown_test.cpp | 206 +++++++++++++++++++++++++++++++++-- 4 files changed, 323 insertions(+), 58 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3fe73325..d7881bce 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -386,9 +386,14 @@ if (LLAMADART_BUILD_TESTS) FIXTURES_REQUIRED llamadart_exit_teardown_model) endforeach() # What only Linux does: teardown ends a decode on the CPU backend, - # and the statics of llama.cpp outlive an exit. + # the statics of llama.cpp outlive an exit, and the exit takes time + # only for a call in flight and blocks no thread. if (CMAKE_SYSTEM_NAME STREQUAL "Linux") - foreach(scenario model-decode-ended model-decode-outlasts-wait) + add_test(NAME llamadart_exit_teardown_exit-late-calls + COMMAND llamadart_exit_teardown_test exit-late-calls) + foreach(scenario model-decode-ended model-decode-outlasts-wait + model-exit-idle model-exit-join-idle + model-exit-join-generating) add_test(NAME llamadart_exit_teardown_${scenario} COMMAND llamadart_exit_teardown_test ${scenario} "${exit_teardown_model}") @@ -434,6 +439,16 @@ if (LLAMADART_BUILD_TESTS) endif() endif() + # The Linux presets give every binary the run path $ORIGIN, which the + # bundle needs, while the build tree keeps the llama.cpp libraries in a + # directory of their own. + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + get_property(llamadart_tests DIRECTORY PROPERTY TESTS) + set_tests_properties(${llamadart_tests} PROPERTIES + ENVIRONMENT_MODIFICATION + "LD_LIBRARY_PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") + endif() + # Contract assertions must execute against optimized Release libraries too. foreach(test_target llamadart_speculative_api_test llamadart_tts_api_test llamadart_tts_eval_test llamadart_exit_teardown_test llamadart_mtmd_compat_test diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index 00b6d5f7..eddcbf5d 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -741,6 +742,35 @@ static thread_local bool llama_dart_exit_teardown_thread = false; // Calls in flight on this thread. The registry counts the outermost one. static thread_local int32_t llama_dart_exit_call_depth = 0; +#if LLAMA_DART_EXIT_ON_LINUX +// Set while teardown waits for the calls in flight, and for good when it gave +// up waiting or was run by C exit(). A decode or an encode on the CPU backend +// ends then. One that outlasts the wait is still running when the exit +// reaches the handlers of other libraries, and the destructor of OpenBLAS +// never returns while its threads are at work. +static std::atomic llama_dart_exit_ending_calls{false}; + +static bool llama_dart_exit_abort_callback(void *) { + return llama_dart_exit_ending_calls.load(std::memory_order_relaxed); +} + +// Whether the teardown that this thread is about to run is the one of C +// exit(), which only waits. +static thread_local bool llama_dart_exit_only_waits = false; + +// Set, under the registry lock, when C exit() runs teardown: it then frees +// nothing. Nothing on Linux needs the objects freed, and the exit handlers of +// a GPU driver may have run already: an exit with a model left loaded is +// known to be clean, a free among those handlers is not. +static std::atomic llama_dart_exit_keeps_objects{false}; + +static void llama_dart_exit_wait_at_exit() { + llama_dart_exit_only_waits = true; + llama_dart_exit_teardown(); + llama_dart_exit_only_waits = false; +} +#endif + // Called with the registry locked. Returns whether the calling thread may go // on to use tracked objects. Once teardown has begun, teardown waits for a // thread that is in a call in flight, and the teardown thread gets false. Any @@ -757,6 +787,13 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, if (llama_dart_exit_call_depth > 0) { return true; } +#if LLAMA_DART_EXIT_ON_LINUX + // Nothing was freed, so the thread holds nothing that is gone, and blocked + // here it would hang an exit handler of the host that joins it. + if (llama_dart_exit_keeps_objects.load()) { + return false; + } +#endif lock.unlock(); for (;;) { std::this_thread::sleep_for(std::chrono::hours(1)); @@ -764,26 +801,13 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, } #if LLAMA_DART_EXIT_ON_LINUX -// Set while teardown waits for the calls in flight, and for good when it gave -// up waiting. A decode or an encode on the CPU backend ends then. One that -// outlasts the wait is still running when the exit reaches the handlers of -// other libraries, and the destructor of OpenBLAS never returns while its -// threads are at work. -static std::atomic llama_dart_exit_ending_calls{false}; - -static bool llama_dart_exit_abort_callback(void *) { - return llama_dart_exit_ending_calls.load(std::memory_order_relaxed); -} - -// Set when C exit() runs teardown, which then frees nothing. Nothing on Linux -// needs the objects freed, and the exit handlers of a GPU driver may have run -// already: an exit with a model left loaded is known to be clean, a free -// among those handlers is not. -static std::atomic llama_dart_exit_keeps_objects{false}; - -static void llama_dart_exit_wait_at_exit() { - llama_dart_exit_keeps_objects.store(true); - llama_dart_exit_teardown(); +// Whether a call in flight that was just begun on this thread was not counted +// because C exit() has waited already. Such a call must not start work that +// the exit no longer waits for: its function throws, and the barrier returns +// the failure value. +static bool llama_dart_exit_began_too_late() { + return llama_dart_exit_call_depth == 0 && !llama_dart_exit_teardown_thread && + llama_dart_exit_keeps_objects.load(); } #endif @@ -973,7 +997,14 @@ static void llama_dart_exit_begin_call(bool creating) { } struct llama_dart_exit_call { - llama_dart_exit_call() { llama_dart_exit_call_begin(); } + llama_dart_exit_call() { + llama_dart_exit_call_begin(); +#if LLAMA_DART_EXIT_ON_LINUX + if (llama_dart_exit_began_too_late()) { + throw std::runtime_error("the process is exiting"); + } +#endif + } ~llama_dart_exit_call() { llama_dart_exit_call_end(); } llama_dart_exit_call(const llama_dart_exit_call &) = delete; llama_dart_exit_call &operator=(const llama_dart_exit_call &) = delete; @@ -985,6 +1016,16 @@ struct llama_dart_exit_creating_call { llama_dart_exit_creating_call() { llama_dart_exit_arm_creating_call(); llama_dart_exit_begin_call(true); +#if LLAMA_DART_EXIT_ON_LINUX + if (llama_dart_exit_began_too_late()) { + { + auto ®istry = llama_dart_exit_state(); + std::lock_guard lock(registry.mutex); + --registry.creating_calls; + } + throw std::runtime_error("the process is exiting"); + } +#endif } ~llama_dart_exit_creating_call() { { @@ -1055,6 +1096,19 @@ static bool llama_dart_exit_load_progress_callback(float progress, caller->callback(progress, caller->user_data); } +// On Linux, gives a context without an abort callback the one that ends its +// evaluations while teardown waits. +static void llama_dart_exit_end_evaluations_at_exit( + llama_context_params ¶ms) { +#if LLAMA_DART_EXIT_ON_LINUX + if (params.abort_callback == nullptr) { + params.abort_callback = llama_dart_exit_abort_callback; + } +#else + (void)params; +#endif +} + static void llama_dart_exit_free_model(void *object) { llama_model_free(static_cast(object)); } @@ -1156,6 +1210,9 @@ LLAMADART_API void llama_dart_exit_teardown(void) { return; } llama_dart_exit_teardown_thread = true; +#if LLAMA_DART_EXIT_ON_LINUX + llama_dart_exit_keeps_objects.store(llama_dart_exit_only_waits); +#endif const auto can_free = [®istry](const auto &tracked) { return llama_dart_exit_can_free(registry, tracked.second); }; @@ -1178,17 +1235,18 @@ LLAMADART_API void llama_dart_exit_teardown(void) { return; } #if LLAMA_DART_EXIT_ON_LINUX + // The exit frees nothing, so it has no reason to let the threads settle: + // it takes time only while a call is in flight. Time spent in exit() is + // not harmless, as a Dart VM aborts when its isolates run meanwhile. + if (llama_dart_exit_keeps_objects.load()) { + return; + } // The free functions that run next may evaluate. llama_dart_exit_ending_calls.store(false); #endif registry.idle.wait_until( lock, registry.last_call_end + llama_dart_exit_settle_time, [] { return false; }); -#if LLAMA_DART_EXIT_ON_LINUX - if (llama_dart_exit_keeps_objects.load()) { - return; - } -#endif std::copy_if(registry.objects.begin(), registry.objects.end(), std::back_inserter(objects), can_free); } @@ -1231,11 +1289,7 @@ llama_dart_init_from_model(struct llama_model *model, struct llama_context_params params) { return llama_dart_barrier(nullptr, [model, ¶ms] { llama_dart_exit_creating_call call; -#if LLAMA_DART_EXIT_ON_LINUX - if (params.abort_callback == nullptr) { - params.abort_callback = llama_dart_exit_abort_callback; - } -#endif + llama_dart_exit_end_evaluations_at_exit(params); return llama_dart_exit_track_created( llama_init_from_model(model, params), llama_dart_exit_free_context, LLAMA_DART_EXIT_STAGE_CONTEXT); @@ -2133,6 +2187,7 @@ static struct llama_dart_speculative *llama_dart_speculative_init_impl( context_params.embeddings = false; context_params.ctx_other = target_context; + llama_dart_exit_end_evaluations_at_exit(context_params); speculative->ctx_dft = llama_init_from_model(resolved_draft_model, context_params); if (speculative->ctx_dft == nullptr) { @@ -2384,6 +2439,7 @@ static struct llama_dart_mtp *llama_dart_mtp_init_impl( ctx_params.embeddings = false; ctx_params.ctx_other = ctx_tgt; + llama_dart_exit_end_evaluations_at_exit(ctx_params); // Owns the draft context until the handle does, so that neither a failure // nor an exception leaves it behind. std::unique_ptr draft_context( diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 40cc600e..c995e973 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -354,21 +354,30 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // destructor. On Apple platforms it runs during exit, before the first static // of libllamadart is destroyed. // -// On Linux, Android excepted, C exit() runs the wait of teardown and frees -// nothing. By the time the exit goes on to what other libraries do at exit, -// the calls in flight have ended and every thread that reaches libllamadart -// is blocked. Nothing on Linux needs the objects freed, and an exit with a -// model left loaded is known to be clean, which a free among the exit -// handlers of a GPU driver is not. llama.cpp is not part of libllamadart -// there, and its libraries register no static destructors: their statics stay -// valid until the process is gone, also under a call that the wait does not -// cover. The wait begins when the exit reaches the handler that libllamadart +// On Linux, Android excepted, C exit() runs the wait of teardown and nothing +// else. It waits for the calls in flight, for no longer than they take: with +// none in flight it returns at once. It frees nothing and blocks no thread. +// Nothing on Linux needs the objects freed, and an exit with a model left +// loaded is known to be clean, which a free among the exit handlers of a GPU +// driver is not. llama.cpp is not part of libllamadart there, and its +// libraries register no static destructors: their statics stay valid until +// the process is gone, also under a call that the wait does not cover. +// +// Once that wait has begun, a thread other than the exiting one gets this +// from libllamadart instead of being blocked: a call in flight that begins +// returns the failure value of its function, with "the process is exiting" +// as the last error, and starts nothing; llama_dart_exit_free frees nothing; +// llama_dart_exit_track and llama_dart_exit_untrack return false; +// llama_dart_exit_call_begin counts nothing. The call that the exit waited +// for returns to its caller. While teardown waits, and from then on after an +// exit, a decode or an encode on the CPU backend ends with the status +// llama.cpp has for an aborted one, 2, unless its context has an abort +// callback of its own. +// +// The wait begins when the exit reaches the handler that libllamadart // registers at the first creating call and again when the first object is // tracked, so an exit handler that another library registers later runs -// before it. While teardown waits, on Linux a decode or an encode on the CPU -// backend ends with the status llama.cpp has for an aborted one, 2, unless -// its context has an abort callback of its own. quick_exit and _exit run -// nothing. +// before it. quick_exit and _exit run nothing. // // Elsewhere nothing runs at exit. llama_dart_exit_teardown runs teardown, and // frees, on every platform. @@ -468,7 +477,8 @@ LLAMADART_API struct llama_model * llama_dart_model_load_from_file( // llama_init_from_model that tracks the context in the CONTEXT stage. Free it // with llama_dart_exit_free. On Linux, when params has no abort callback, the -// context gets the one that ends its evaluations while teardown waits; +// context gets the one that ends its evaluations while teardown waits, as do +// the draft contexts that the speculative and MTP init functions create; // llama_set_abort_callback replaces it. Blocks after teardown. LLAMADART_API struct llama_context * llama_dart_init_from_model( struct llama_model * model, diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index ebb6e2d0..ad4526ea 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -464,30 +464,47 @@ int test_blocked() { return 0; } -// C exit() runs teardown on Apple platforms. On Linux it runs the wait of -// teardown and frees nothing, and teardown ends a decode or an encode on the -// CPU backend while it waits for the calls in flight, with llama.cpp's status -// for an aborted one. +// C exit() runs teardown on Apple platforms: it frees, and blocks the threads +// that reach libllamadart afterwards. On Linux it runs the wait of teardown +// only: it frees nothing, blocks no thread and refuses the calls in flight +// that begin afterwards. Teardown there also ends a decode or an encode on +// the CPU backend while it waits, with llama.cpp's status for an aborted one. #if defined(__APPLE__) const bool kExitFreesObjects = true; const bool kExitWaitsForCalls = true; +const bool kExitBlocksThreads = true; +const bool kExitRefusesLateCalls = false; const bool kTeardownEndsEvaluations = false; #elif defined(__linux__) && !defined(__ANDROID__) const bool kExitFreesObjects = false; const bool kExitWaitsForCalls = true; +const bool kExitBlocksThreads = false; +const bool kExitRefusesLateCalls = true; const bool kTeardownEndsEvaluations = true; #else const bool kExitFreesObjects = false; const bool kExitWaitsForCalls = false; +const bool kExitBlocksThreads = false; +const bool kExitRefusesLateCalls = false; const bool kTeardownEndsEvaluations = false; #endif // Set by a scenario before the teardown that an evaluation may run into. std::atomic g_teardown_expected{false}; +// Whether the calling thread's last call was refused because C exit() had +// waited already. +bool refused_by_exit() { + const char *error = llama_dart_last_error(); + return kExitRefusesLateCalls && g_teardown_expected.load() && + error != nullptr && strcmp(error, "the process is exiting") == 0; +} + bool evaluated(int32_t status) { - return status == 0 || (status == 2 && kTeardownEndsEvaluations && - g_teardown_expected.load()); + return status == 0 || + (status == 2 && kTeardownEndsEvaluations && + g_teardown_expected.load()) || + refused_by_exit(); } // Where the backends are modules next to the llama.cpp libraries and not part @@ -552,6 +569,50 @@ int test_exit_in_flight() { return 0; } +char kLateObject[] = "late-object"; + +// What a thread other than the exiting one gets from libllamadart once the +// exit has waited, on Linux: nothing blocks, a free frees nothing, and a call +// in flight is refused before it starts. +void make_late_calls() { + g_teardown_expected.store(true); + std::thread([] { + llama_dart_exit_free(kLateObject); + assert(recorded().empty()); + assert(!llama_dart_exit_track(name("later"), free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + assert(llama_dart_exit_tracked_count() == 1); + assert(llama_dart_decode(nullptr, llama_batch{}) == + std::numeric_limits::min()); + assert(refused_by_exit()); + llama_dart_clear_last_error(); + assert(llama_dart_model_load_from_file( + "missing.gguf", llama_model_default_params()) == nullptr); + assert(refused_by_exit()); + llama_dart_exit_call_begin(); + llama_dart_exit_call_end(); + assert(!llama_dart_exit_untrack(kLateObject)); + assert(llama_dart_exit_tracked_count() == 1); + g_call_ended.store(true); + }).detach(); + const int64_t started = now_ms(); + while (!g_call_ended.load()) { + if (now_ms() - started > 10000) { + fprintf(stderr, "a call after the exit began did not return\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +int test_exit_late_calls() { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(make_late_calls) == 0); + assert(llama_dart_exit_track(kLateObject, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + return 0; +} + std::string g_system_info; // Uses the static behind llama_print_system_info, which teardown must find @@ -770,7 +831,8 @@ llama_batch prompt(model_fixture &fixture) { } void clear_memory(model_fixture &fixture) { - assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true)); + assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true) || + refused_by_exit()); } llama_sampler *greedy_sampler() { @@ -1170,11 +1232,26 @@ void start_beat() { } } +std::atomic g_exit_began_ms{0}; + +// An exit handler that a scenario registers after the one of libllamadart, +// so that it runs right before it. Where the exit blocks no thread, the beat +// does not stop and this is how a scenario learns that the exit has begun. +void note_exit_began() { g_exit_began_ms.store(now_ms()); } + +bool teardown_waits() { + if (now_ms() - g_last_beat_ms.load() >= 200) { + return true; + } + const int64_t began = g_exit_began_ms.load(); + return !kExitBlocksThreads && began != 0 && now_ms() - began >= 200; +} + // Releases the held evaluation once teardown is waiting for it, and gives up // after ten seconds. void release_when_teardown_waits() { const int64_t started = now_ms(); - while (now_ms() - g_last_beat_ms.load() < 200) { + while (!teardown_waits()) { if (now_ms() - started > 10000) { g_released_before_teardown.store(true); break; @@ -1385,6 +1462,96 @@ int test_model_decode_outlasts_wait(const char *path) { return 0; } +std::atomic g_returned_from_main_ms{0}; + +void expect_exit_took_no_time() { + const int64_t took = now_ms() - g_returned_from_main_ms.load(); + if (took > 100) { + fprintf(stderr, "the exit took %lld ms with no call in flight\n", + static_cast(took)); + _Exit(EXIT_FAILURE); + } +} + +// On Linux an exit right after a guarded call returned takes no time: with +// nothing to free there is nothing to let the threads settle for, and a Dart +// VM aborts when its isolates run while exit() takes its time. +int test_model_exit_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(expect_exit_took_no_time) == 0); + static model_fixture fixture; + fixture = load_model(path); + llama_sampler *sampler = greedy_sampler(); + assert(decode_and_sample(fixture, sampler) >= 0); + llama_sampler_free(sampler); + g_returned_from_main_ms.store(now_ms()); + return 0; +} + +std::atomic g_worker_stop{false}; +std::atomic g_worker_done{false}; + +// What a host does that stops its worker at exit: the worker must come back. +void stop_and_join_worker() { + g_worker_stop.store(true); + const int64_t started = now_ms(); + while (!g_worker_done.load()) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the worker did not come back during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// On Linux the exit blocks no thread: a worker that frees its model when the +// host's own exit handler tells it to returns from the frees, which free +// nothing any more. +int test_model_exit_join_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + fixture = load_model(path); + std::thread([] { + while (!g_worker_stop.load()) { + sleep_ms(1); + } + llama_dart_exit_free(fixture.context); + llama_dart_exit_free(fixture.model); + if (llama_dart_exit_tracked_count() != 2) { + fprintf(stderr, "a free after the exit began freed its object\n"); + _Exit(EXIT_FAILURE); + } + g_worker_done.store(true); + }).detach(); + return 0; +} + +// The same with a worker that generates until it is told to stop: the exit +// ends its decode in flight, and every call it begins afterwards is refused. +int test_model_exit_join_generating(const char *path) { + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + static std::atomic steps{0}; + fixture = load_model(path); + std::thread([] { + llama_sampler *sampler = greedy_sampler(); + while (!g_worker_stop.load()) { + assert(decode_and_sample(fixture, sampler) >= 0); + steps.fetch_add(1); + if (refused_by_exit()) { + sleep_ms(1); + } + } + g_worker_done.store(true); + }).detach(); + while (steps.load() < 3) { + sleep_ms(1); + } + g_teardown_expected.store(true); + return 0; +} + // Exits while another thread generates on a model whose load created statics // in libllamadart that an earlier, different load had not: a CPU-only load, // then one that maps the file into GPU memory. @@ -1438,9 +1605,13 @@ int test_model_load(const char *path) { return true; }; std::thread([params] { - llama_dart_model_load_from_file(model_path, params); - fprintf(stderr, "the load returned to its caller after teardown\n"); - _Exit(EXIT_FAILURE); + const llama_model *model = + llama_dart_model_load_from_file(model_path, params); + // Where the exit blocks no thread, the cancelled load returns. + if (kExitBlocksThreads || model != nullptr) { + fprintf(stderr, "the load returned to its caller after teardown\n"); + _Exit(EXIT_FAILURE); + } }).detach(); while (!loading.load()) { sleep_ms(1); @@ -1566,6 +1737,7 @@ int test_model_free_in_flight(const char *path) { assert(llama_dart_exit_track(fixture.model, free_model_when_teardown_waits, LLAMA_DART_EXIT_STAGE_MODEL)); llama_dart_exit_set_wait_ms(30000); + assert(atexit(note_exit_began) == 0); start_beat(); std::thread([] { llama_dart_exit_free(fixture.model); }).detach(); while (!g_free_started.load()) { @@ -2457,6 +2629,9 @@ int main(int argc, char **argv) { if (scenario == "exit-in-flight") { return test_exit_in_flight(); } + if (scenario == "exit-late-calls") { + return test_exit_late_calls(); + } if (scenario == "late-static") { return test_late_static(); } @@ -2536,6 +2711,15 @@ int main(int argc, char **argv) { if (scenario == "model-decode") { return test_model_decode(first); } + if (scenario == "model-exit-idle") { + return test_model_exit_idle(first); + } + if (scenario == "model-exit-join-idle") { + return test_model_exit_join_idle(first); + } + if (scenario == "model-exit-join-generating") { + return test_model_exit_join_generating(first); + } if (scenario == "model-decode-ended") { return test_model_decode_ended(first); } From 10ef0deddf935d2106a930c497021a831f202bb9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:44:30 -0400 Subject: [PATCH 4/8] docs: record the audit fixes, the Dart rows and the lavapipe long decode Adds the Dart exit probe of those rows as a manual probe and frees the sampler of the joining scenario. --- README.md | 16 +- docs/v060_2_wrapper_rebuild.md | 242 +++++++++++++++++++------- tests/exit_teardown_test.cpp | 1 + tests/manual/dart_exit_probe.dart | 222 +++++++++++++++++++++++ tests/manual/dart_exit_probe_shim.cpp | 71 ++++++++ 5 files changed, 484 insertions(+), 68 deletions(-) create mode 100644 tests/manual/dart_exit_probe.dart create mode 100644 tests/manual/dart_exit_probe_shim.cpp diff --git a/README.md b/README.md index 227ab091..62db8184 100644 --- a/README.md +++ b/README.md @@ -296,12 +296,16 @@ the threads that were still inside it, and those crashed the process is gone. On Linux they are separate libraries, and no exit handler of `libllamadart` can be ordered before the destructor of a static that another library creates later. -- C `exit` runs the wait of teardown and frees nothing: it waits for the - calls in flight as above, cancels a model load, ends a decode or an encode - on the CPU backend (status 2, unless the context has an abort callback of - its own), and blocks the threads that reach `libllamadart` afterwards. The - exit handlers and destructors of other libraries, such as a GPU driver or - OpenBLAS, then run with no call in flight. +- C `exit` runs the wait of teardown and nothing else. It waits for the calls + in flight as above, cancels a model load and ends a decode or an encode on + the CPU backend (status 2, unless the context has an abort callback of its + own). With no call in flight it returns at once. The exit handlers and + destructors of other libraries, such as a GPU driver or OpenBLAS, then run + with no call in flight. +- It frees nothing and blocks no thread. After it, a guarded call that begins + on another thread returns its failure value with `the process is exiting` + as the last error, and `llama_dart_exit_free` frees nothing, so a host whose + own exit handler joins a worker gets it back. - The wait runs at the handler registered at the first creating call and again at the first tracked object. An exit handler that another library registers later runs before it. diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 712b3b1b..83355710 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -37,29 +37,43 @@ looks for the best backend. enables. The statics stay valid until the process is gone: also for a call that teardown does not wait for, and for one that outlasts its wait. Upstream sources are not patched. -2. C `exit()` runs the wait of exit teardown. libllamadart registers the - handler at the first creating call (`llama_dart_model_load_from_file`, - `llama_dart_init_from_model`, `llama_dart_mtmd_init_from_file`, the TTS, - speculative, MTP and n-gram init functions), so that an exit during the - first load finds one, and again when the first object is tracked. The wait is the one of - `llama_dart_exit_teardown`: up to 2 s (`llama_dart_exit_set_wait_ms`) for - the calls in flight, a model load is cancelled, then 250 ms after the last - call, and from then on every thread that reaches libllamadart is blocked. - The exit handlers and destructors of other libraries run after it. +2. C `exit()` runs the wait of exit teardown and nothing else. libllamadart + registers the handler at the first creating call + (`llama_dart_model_load_from_file`, `llama_dart_init_from_model`, + `llama_dart_mtmd_init_from_file`, the TTS, speculative, MTP and n-gram init + functions), so that an exit during the first load finds one, and again when + the first object is tracked. It waits up to 2 s + (`llama_dart_exit_set_wait_ms`) for the calls in flight and cancels a model + load. With no call in flight it returns at once: it does not let the + threads settle for 250 ms as `llama_dart_exit_teardown` does, because it + frees nothing, and because time spent inside `exit()` is not harmless (see + "Dart"). 3. The exit frees nothing. Apple frees the tracked objects because ggml-metal aborts over a live buffer. Nothing on Linux does, the issue found an exit with a model left loaded clean on CPU, Vulkan and CUDA, and a free during `exit()` would run among the exit handlers of the GPU driver in an order that nothing controls. `llama_dart_exit_teardown` called by a native host still frees. -4. While teardown waits, a decode or an encode on the CPU backend ends with - llama.cpp's status for an aborted evaluation (2). - `llama_dart_init_from_model` sets the context's abort callback for that - when the caller passes none. Without it a long decode outlasts the wait and - is still running when the exit reaches other libraries: with the BLAS - module, OpenBLAS's destructor then never returns (see "Measurements"). - llama.cpp logs three error lines for the ended decode. -5. libllamadart itself binds `__cxa_atexit` to the definition that Apple +4. The exit blocks no thread. Apple blocks every thread that reaches + libllamadart after teardown, because the objects it holds are gone. On + Linux they are not, and a blocked thread hangs a host whose own exit + handler joins it. After the wait, on a thread other than the exiting one: + - `llama_dart_exit_free` and the session free functions free nothing, and + `llama_dart_exit_track` and `llama_dart_exit_untrack` return `false`; + - a call in flight that begins returns the failure value of its function, + with `the process is exiting` as `llama_dart_last_error`, and starts + nothing: the exit no longer waits for it; + - `llama_dart_exit_call_begin` counts nothing; + - the call that the exit waited for returns to its caller. +5. While teardown waits, and from then on after an exit, a decode or an + encode on the CPU backend ends with llama.cpp's status for an aborted + evaluation (2). `llama_dart_init_from_model` sets the context's abort + callback for that when the caller passes none, and the draft contexts of + the speculative and MTP state get it too. Without it a long decode outlasts + the wait and is still running when the exit reaches other libraries: with + the BLAS module, OpenBLAS's destructor then never returns (see + "Measurements"). llama.cpp logs three error lines for the ended decode. +6. libllamadart itself binds `__cxa_atexit` to the definition that Apple uses, so a static of its own is destroyed only after the wait. `tools/validate_linux_artifact.py`, which the release runs on every Linux @@ -84,16 +98,26 @@ without frees is taken from there. The gate is not: ### What it does not cover +- A Dart process in which another isolate runs Dart code while the exit + waits for a call in flight. The Dart VM aborts + (`runtime/vm/handles_impl.h: 39: error: unreachable code`, + [llamadart#977](https://github.com/leehack/llamadart/issues/977)) when an + isolate collects garbage while C `exit()` is taking its time, whatever + takes it: a 300 ms exit handler with no llama.cpp in the process does it + 10 of 10. The wait is what fixes the crash, so it stays, and it is as short + as the call: see "Dart" for the rates. +- A call in flight that outlasts the wait and cannot be ended: a decode on a + GPU backend, which does not read the abort callback, an image or audio + evaluation, or a context with an abort callback of its own. The exit then + goes on with the call running, two seconds later than it would have, and + what the call uses of other libraries may be gone. The lavapipe decode of + 1500 tokens in "Measurements" is such a call. - An exit handler that another library registers after the two handlers above runs before the wait, under the calls in flight. A GPU driver that registers one late, during a decode for example, is in that position. Statics that llama.cpp creates late no longer matter. - A call that is not a call in flight is not waited for, as on Apple. Its statics stay valid on Linux; what it uses of other libraries may not. -- A call in flight that outlasts the wait and cannot be ended: a decode on a - GPU backend, which does not read the abort callback, an image or audio - evaluation, or a context with an abort callback of its own. The exit then - goes on with the call running. - `quick_exit` and `_exit` run no handler, as before. Neither destroys statics. - A child of `fork` that calls `exit()` runs the handler with the registry it @@ -102,12 +126,29 @@ without frees is taken from there. The gate is not: `atexit` binds to the same definition and is dropped. No backend built here registers one; a library such as the CUDA runtime, which the modules load as a library of its own, is not affected. +- The standard streams of a host built against libstdc++ older than GCC 13. + There `` gives every translation unit a static `ios_base::Init`, + and `std::cout` is flushed when the last of them is destroyed. One inside a + llama.cpp library is now never destroyed, so a host that turned off + `sync_with_stdio` loses what `std::cout` still buffers at exit (seen in the + audit with GCC 11.4 and a test library). The release builds its Linux + libraries with GCC 13, where the stream initializer lives in libstdc++, + except `libggml-hip.so` (the ROCm image has GCC 11.4), and neither the + sources of that module nor `hip/hip_runtime.h` include ``; the + other ROCm headers were not checked. A bundle built with an older GCC is + affected. +- The heap that the statics of a backend module own is not freed when ggml + unloads the module. The audit measured 544 KB after 300 calls of + `ggml_backend_load_all_from_path` on a host without a Vulkan driver, where + the Vulkan module is loaded and unloaded each time, against 36 KB before: + about 1.7 KB for each unload. llamadart loads the backends once. ### Other platforms -- musl: nothing here is specific to glibc. The definition binds at link - time, and libllamadart reaches the C library's `__cxa_atexit` through - `dlsym(RTLD_NEXT)`. No bundle is built for musl and none was run. +- musl: not supported and not run. No bundle is built for it. The audit found + that musl's `dlsym(RTLD_NEXT, "__cxa_atexit")` returns `NULL` in a library + opened with `dlopen`, so libllamadart's own definition would register + nothing there. - Android: left as it was, by `!defined(__ANDROID__)` in the two sources and `CMAKE_SYSTEM_NAME STREQUAL "Linux"` in CMake. bionic orders exit handlers the same way, but the issue has no Android measurement and nothing here ran @@ -126,17 +167,20 @@ without frees is taken from there. The gate is not: Linux arm64 container (Ubuntu 24.04, glibc 2.39, GCC 13.3) on an Apple M4 Max, the `linux-arm64-full` preset without KleidiAI: Release with link-time -optimization, OpenMP, the CPU, Vulkan and BLAS modules. A probe opens -`libllamadart.so` with `dlopen`, as Dart does, and calls C `exit()` from the -main thread while another thread is inside a guarded call. "Slow host" adds -an exit handler of the probe's own that takes 300 ms, registered before the -library is opened and so run last, as the handlers of a larger host are. -Vulkan is Mesa 25.2.8 lavapipe (`llvmpipe`, `GGML_VK_VISIBLE_DEVICES=0`, all -layers offloaded); BLAS is OpenBLAS 0.3.26. The numbers are failed runs of -10: a signal, an exit code other than 0, a failed `GGML_ASSERT`, or no exit -within 120 s. - -CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. +optimization, OpenMP, the CPU, Vulkan and BLAS modules. `v0.6.0-1` is its +source, `ceae6f7`, built in the same container. + +### Native host + +A probe opens `libllamadart.so` with `dlopen`, as Dart does, and calls C +`exit()` from the main thread while another thread is inside a guarded call. +"Slow host" adds an exit handler of the probe's own that takes 300 ms, +registered before the library is opened and so run last, as the handlers of a +larger host are. Vulkan is Mesa 25.2.8 lavapipe (`llvmpipe`, +`GGML_VK_VISIBLE_DEVICES=0`, all layers offloaded); BLAS is OpenBLAS 0.3.26. +CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. The numbers +are failed runs of 10, or of 50 where it says so: a signal, an exit code other +than 0, a failed `GGML_ASSERT`, or no exit within 120 s. | Exit | Modules | Host | `v0.6.0-1` | This rebuild | | --- | --- | --- | --- | --- | @@ -148,10 +192,9 @@ CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. | inside one decode of 1500 tokens | CPU | fast | 1 | 0 | | | CPU | slow | 10 | 0 | | | CPU, BLAS | slow | 10 | 0 | -| | Vulkan | fast | 0 | 0 | -| | Vulkan | slow | 6 | 0 | -| 100 ms into the first load | CPU | slow | 9 | 0 | -| 400 ms into the first load | CPU | slow | 6 | 0 | +| | Vulkan | fast | 0 of 50 | 2 of 50 | +| | Vulkan | slow | 24 of 50 | 2 of 50 | +| 100 ms and 400 ms into the first load | CPU | slow | 9, 6 | 0, 0 | | 200 ms and 800 ms into the first load | CPU | fast | 0, 0 | 0, 0 | | 5 ms and 60 ms into the first load | Vulkan | fast | 0, 0 | 0, 0 | | | Vulkan | slow | 10, 10 | 0, 0 | @@ -162,10 +205,21 @@ CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. | | Vulkan | fast | 3 | 0 | | model idle; everything freed; `return` from `main` with a model idle | CPU, BLAS, Vulkan | fast, slow | 0 | 0 | -`v0.6.0-1` is its source, `ceae6f7`, built in the same container. Every -failed run of it ended in a signal: `SIGSEGV`, and in five lavapipe runs -`SIGABRT` (`double free or corruption`). The scenarios that were clean before -are clean after, with the model left loaded and not freed. +Every failed run ended in a signal: `SIGSEGV`, and on lavapipe before the +change also `SIGABRT` (`double free or corruption`). The scenarios that were +clean before are clean after, with the model left loaded and not freed. + +One row is worse than before. The decode of 1500 tokens on lavapipe cannot be +ended: ggml-vulkan does not read the abort callback. It outlasts the two +seconds, and the exit then goes on under it. With a fast host that fails 2 of +50 (6 of 50 in the audit, with a backtrace in the LLVM compiler of lavapipe +under a thread that waits in `ggml_vk_flash_attn`), where it was clean 50 of +50 before, also when the exit came 2.3 s into the decode. Before, the +destructor of ggml-vulkan's device list destroyed the device at once; now the +device outlives the exit and the driver's own exit handlers meet a decode +that is still running. With a slow host the same row goes from 24 of 50 to 2 +of 50. Whether a GPU driver behaves like lavapipe here is part of what is not +verified. Two measurements on the way decided parts of the design: @@ -179,8 +233,57 @@ Two measurements on the way decided parts of the design: the 16 lavapipe scenarios it ran (10 of 10 each). That shows nothing about the NVIDIA driver, which is why the frees stay out. -On lavapipe the abort callback does not end the 1500-token decode: ggml-vulkan -does not read it. +A host whose own exit handler stops a worker and joins it, with the worker +freeing its context and model through `llama_dart_exit_free`: clean 5 of 5 +before and after. The first version of this change blocked that worker and +hung 5 of 5. + +### Dart + +The Dart VM aborts when one of its isolates collects garbage while C `exit()` +is under way +([llamadart#977](https://github.com/leehack/llamadart/issues/977)). A Dart +program with one isolate that decodes UTF-8 in a loop and an exit handler +that sleeps 300 ms, with no llama.cpp in the process, aborts 10 of 10. So +whatever the handler of libllamadart takes, it takes at that price, and it +takes time only while a guarded call is in flight. + +Dart 3.13.1, CPU. `tests/manual/dart_exit_probe.dart` calls a guarded decode +and sample per step through a small C shim, on `stories15M`; llamadart rows +are its own `test/fixtures/llama_cpp_exit_probe.dart` and a variant with an +isolate that wakes on a 5 ms timer, on llamadart `9275de8` with the bundle +under test and Qwen3.5 0.8B Q4_0. The main isolate calls C `exit()` through +FFI. Failed runs of 10, or of 30 where it says so; "First version" is +`c9bc619`, which waited 250 ms at every exit and blocked the threads that +reached libllamadart afterwards. + +| Exit | Other isolate | `v0.6.0-1` | First version | This rebuild | +| --- | --- | --- | --- | --- | +| llamadart `quit-generating` | none | 10 | 0 | 0 | +| llamadart `quit-loaded`, `quit-loading`, `return-loaded`, `kill-loading` | none | 0 | 0 | 0 | +| llamadart, right after a generation finished | 5 ms timer | 0 | 10 | 0 | +| llamadart, 1 s after a generation finished | 5 ms timer | 0 | 0 | 0 | +| llamadart, while generating | 5 ms timer | 6 | 10 | 0 | +| worker isolate generating | none | 13 of 30 | 0 | 0 of 30 | +| worker isolate generating | decoding in a loop | 13 of 30 | 10 | 3 of 30 | +| worker isolate inside one decode of 1500 tokens | decoding in a loop | 10 of 30 | 10 | 17 of 30 | +| right after a guarded call returned | decoding in a loop | 7 of 30 | 10 | 10 of 30 | +| worker isolate idle after a generation | 5 ms timer | 0 | 9 | 0 | +| worker isolate idle after a generation | decoding in a loop | 4 of 30 | 10 | 3 of 30 | +| model idle for 400 ms | decoding in a loop | 8 of 30 | 0 | 6 of 30 | +| `dart:io` `exit()` while generating; `main` returns while generating | none | 0 | 0 | 0 | + +The failures of `v0.6.0-1` while generating are the `SIGSEGV` of the issue. +Those of this rebuild are all the abort of the Dart VM. An isolate that +decodes in a loop makes the VM abort in about a fifth of the exits with a +model loaded even where libllamadart has no handler at all (19 of 90 in the +three rows of `v0.6.0-1` with no call in flight), so the rows with one +compare rates: this rebuild is at the rate of `v0.6.0-1` where no call is in +flight (19 of 90), and below it while generating. It is above it in one row, +17 of 30 against 10 of 30: an exit inside a long decode while another isolate +keeps collecting garbage. The exit waits there until the decode has ended, +which takes as long as the tensor that is being computed, and the VM aborts +in that time. ## Checks @@ -196,30 +299,44 @@ done ``` `llamadart_exit_teardown_test` now runs its model scenarios on Linux as well, -on the CPU backend module and the models it writes itself. In the container -above: +on the CPU backend module and the models it writes itself. CTest finds the +llama.cpp libraries of a Linux preset build, which keeps them in `bin/`, +without `LD_LIBRARY_PATH`. In the container above: -- The release preset: 48 of 48 CTest cases, and the 42 exit cases ten times - over. The same 42 four times in a RelWithDebInfo build with - AddressSanitizer, with no report. +- The release preset: 52 of 52 CTest cases, ten times over. - The configuration of the `wrapper-contract` lane (Debug, no OpenMP) on the - pinned upstream and on the post-v0.4.0 one: 48 of 48 each, and the 42 exit + pinned upstream and on the post-v0.4.0 one: 52 of 52 each, and the 46 exit cases five times over. +- A RelWithDebInfo build with AddressSanitizer: the 46 exit cases three times + with leak detection off, with no report. With it on, `barrier-grammar` + reports 80 bytes that llama.cpp leaks when a lazy grammar is rejected + (`llama-sampler.cpp:2777`), as before this change, and nothing else does. - The same test source against the libraries of `v0.6.0-1`: `model-decode`, `model-late-load` and `model-decode-outlasts-wait` end in `SIGSEGV`, and `model-load` and `model-free-in-flight` report that the exit did not wait, 5 of 5 each. -- Each part removed in turn fails one scenario: the abort callback - `model-decode-ended`, the handler at the first creating call `model-load`, - the handler at the first tracked object `exit-in-flight`, the exit that - frees nothing `exit`, and the static destructor object - `model-decode-outlasts-wait` (`SIGSEGV`). Without that object - `validate_linux_artifact.py` names seven libraries of the archive. +- Each part removed in turn fails a scenario: + + | Removed | Fails | + | --- | --- | + | the static destructor object | `model-decode-outlasts-wait` (`SIGSEGV`); `validate_linux_artifact.py` names seven libraries | + | the handler at the first creating call | `model-load` | + | the handler at the first tracked object | `exit-in-flight` | + | the exit that frees nothing | `exit` | + | the abort callback | `model-decode-ended` | + | the return before the 250 ms | `model-exit-idle` (260 ms against a bound of 100 ms) | + | threads not blocked after the exit | `exit-late-calls`, `model-exit-join-idle`, `model-exit-join-generating` | + | the refusal of a late call | `exit-late-calls` | `validate_exports.py --forbid-import` now reads ELF imports with `--format readelf`. With `--format nm` it reads names as Mach-O ones, without their leading underscore, and an ELF `__cxa_atexit` never matched. +No lane runs Dart or a GPU decode. `tests/manual/dart_exit_probe.dart`, with +the shim next to it, is the probe of the "Dart" table; the lavapipe rows need +a build with `GGML_VULKAN=ON`, Mesa's `mesa-vulkan-drivers` and +`GGML_VK_VISIBLE_DEVICES=0`. + macOS arm64 (Apple M4 Max), `macos-arm64-full` preset: `libllamadart.dylib` built from this tree and from `v0.6.0-1` at the same path have the same SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). @@ -235,9 +352,10 @@ SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). `quit-loaded`, `quit-generating`, `quit-loading`, `return-loaded` and dispose-then-quit scenarios of llamadart's `test/fixtures/llama_cpp_exit_probe.dart` on the `v0.6.0-2` bundle, with the - CPU, Vulkan and CUDA backends, at least 10 runs each. -- Linux x64. The measurements are arm64; `validate_wrapper.yml` runs the - scenarios on x64. + CPU, Vulkan and CUDA backends, at least 10 runs each, and an exit inside a + prompt decode that takes longer than two seconds on each GPU backend, 50 + runs, against `v0.6.0-1`. +- Linux x64 by hand. The measurements are arm64; `validate_wrapper.yml` runs + the scenarios on x64. - HIP and musl builds, Android and Windows. -- A Dart or Flutter process. The probe is C++; llamadart's own probe runs - against a published bundle. +- Flutter. The Dart rows are the standalone VM. diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index ad4526ea..d0826bc4 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -1543,6 +1543,7 @@ int test_model_exit_join_generating(const char *path) { sleep_ms(1); } } + llama_sampler_free(sampler); g_worker_done.store(true); }).detach(); while (steps.load() < 3) { diff --git a/tests/manual/dart_exit_probe.dart b/tests/manual/dart_exit_probe.dart new file mode 100644 index 00000000..89c3187d --- /dev/null +++ b/tests/manual/dart_exit_probe.dart @@ -0,0 +1,222 @@ +// Manual probe, not run by CI: C exit() through FFI from the main isolate of +// a Dart program while its isolates use libllamadart. It shows what the exit +// handler of libllamadart costs a Dart VM, which aborts when its isolates run +// while exit() takes its time (docs/v060_2_wrapper_rebuild.md). +// +// g++ -std=c++17 -shared -fPIC -Ithird_party/llama.cpp/include \ +// -Ithird_party/llama.cpp/ggml/include \ +// tests/manual/dart_exit_probe_shim.cpp -o libshim.so +// dart tests/manual/dart_exit_probe.dart libshim.so \ +// +// +// holds libllamadart.so and the backend modules. A run is clean +// when it prints EXIT_PROBE_REACHED and exits with code 0. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// An isolate that wakes every 5 ms and allocates a little, as an app with a +// heartbeat or an animation does. +void _tick(SendPort ready) { + var ticks = 0; + final bytes = utf8.encode('tick'); + Timer.periodic(const Duration(milliseconds: 5), (_) { + final junk = List.generate(2000, (i) => utf8.decode(bytes)); + if (junk.isEmpty) throw StateError('unreachable'); + if (++ticks == 3) ready.send(null); + }); +} + +// Generates as llamadart does: one guarded native step, then Dart work. +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(null); + } +} + +// Runs four steps, reports, then stays idle: llamadart's worker after a +// generation that finished. +void _generateThenIdle((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + for (var i = 0; i < 4; i++) { + step(session); + } + final keepAlive = ReceivePort(); + ready.send(keepAlive.sendPort); +} + +Future main(List args) async { + final [shimPath, bundle, scenario, model] = args; + final shim = DynamicLibrary.open(shimPath); + final openLib = shim.lookupFunction<_OpenLibN, _OpenLibD>( + 'shim_open_library', + ); + final openSession = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + ); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final sleepingAtexit = shim + .lookupFunction( + 'shim_sleeping_atexit', + ); + Future spin() async { + final ready = ReceivePort(); + await Isolate.spawn(_spin, ready.sendPort); + await ready.first; + } + + switch (scenario) { + case 'control-spin': // no native library at all + await spin(); + _cExit(); + case 'control-spin-slow-exit': // an exit handler that takes 300 ms + sleepingAtexit(300); + await spin(); + _cExit(); + case 'control-spin-slow-exit-2500': + sleepingAtexit(2500); + await spin(); + _cExit(); + case 'idle-spin': // model idle for longer than the settle time + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + step(s); + await spin(); + sleep(const Duration(milliseconds: 400)); + _cExit(); + case 'settle-spin': // exit right after a guarded call ended + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + await spin(); + step(s); + _cExit(); + case 'generating': // worker isolate alternates guarded calls and Dart + case 'generating-spin': + case 'long-decode-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario == 'long-decode-spin' ? 1500 : 8, + )); + if (scenario == 'long-decode-spin') { + await spin(); + sleep(const Duration(milliseconds: 300)); + } else { + await ready.first; + if (scenario == 'generating-spin') await spin(); + } + _cExit(); + case 'loaded-worker-idle': // llamadart's quit-loaded shape + case 'loaded-worker-idle-timer': // the same with a periodic timer in main's group + case 'loaded-worker-idle-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generateThenIdle, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + if (scenario == 'loaded-worker-idle-spin') await spin(); + if (scenario == 'loaded-worker-idle-timer') { + final ticking = ReceivePort(); + await Isolate.spawn(_tick, ticking.sendPort); + await ticking.first; + } + await ready.first; + _cExit(); + case 'dart-io-exit-generating': // dart:io exit() + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + exit(0); + case 'return-generating': // main returns while a worker generates + final ready = ReceivePort(); + final iso = await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + ready.close(); + iso.kill(priority: Isolate.immediate); + default: + throw ArgumentError.value(scenario); + } +} diff --git a/tests/manual/dart_exit_probe_shim.cpp b/tests/manual/dart_exit_probe_shim.cpp new file mode 100644 index 00000000..d973f12f --- /dev/null +++ b/tests/manual/dart_exit_probe_shim.cpp @@ -0,0 +1,71 @@ +// libllamadart behind functions that tests/manual/dart_exit_probe.dart can +// bind without the structures of llama.h. +#include "llama.h" +#include +#include +#include +#include +#include +#include +#include +#include +extern "C" { +llama_model *llama_dart_model_load_from_file(const char *, llama_model_params); +llama_context *llama_dart_init_from_model(llama_model *, llama_context_params); +int32_t llama_dart_decode(llama_context *, llama_batch); +llama_token llama_dart_sampler_sample(llama_sampler *, llama_context *, int32_t); +void llama_dart_set_log_level(int); +} +static void *g_lib; +template static F *sym(const char *n) { + void *s = dlsym(g_lib, n); + if (!s) { fprintf(stderr, "missing %s\n", n); _Exit(3); } + return reinterpret_cast(s); +} +#define BIND(name) auto *name##_ = sym(#name) +struct shim_session { llama_model *model; llama_context *ctx; llama_sampler *sampler; std::vector tokens; }; +extern "C" { +int shim_open_library(const char *bundle) { + if (g_lib) return 0; + g_lib = dlopen((std::string(bundle) + "/libllamadart.so").c_str(), RTLD_LAZY); + if (!g_lib) { fprintf(stderr, "dlopen: %s\n", dlerror()); return 1; } + BIND(llama_dart_set_log_level); BIND(llama_backend_init); BIND(ggml_backend_load_all_from_path); + llama_dart_set_log_level_(4); llama_backend_init_(); ggml_backend_load_all_from_path_(bundle); + return 0; +} +void *shim_open_session(const char *model, int tokens) { + BIND(llama_model_default_params); BIND(llama_dart_model_load_from_file); + BIND(llama_context_default_params); BIND(llama_dart_init_from_model); + BIND(llama_sampler_chain_default_params); BIND(llama_sampler_chain_init); + BIND(llama_sampler_chain_add); BIND(llama_sampler_init_greedy); + auto *s = new shim_session; + auto mp = llama_model_default_params_(); + const char *g = getenv("PROBE_GPU_LAYERS"); + mp.n_gpu_layers = g ? atoi(g) : 0; + s->model = llama_dart_model_load_from_file_(model, mp); + if (!s->model) return nullptr; + auto cp = llama_context_default_params_(); + cp.n_ctx = 2048; cp.n_batch = 2048; + s->ctx = llama_dart_init_from_model_(s->model, cp); + if (!s->ctx) return nullptr; + s->sampler = llama_sampler_chain_init_(llama_sampler_chain_default_params_()); + llama_sampler_chain_add_(s->sampler, llama_sampler_init_greedy_()); + for (int i = 0; i < tokens; ++i) s->tokens.push_back(100 + i % 400); + return s; +} +// One generation step: guarded decode, then guarded sample. +int shim_step(void *session) { + BIND(llama_get_memory); BIND(llama_memory_clear); BIND(llama_dart_decode); + BIND(llama_dart_sampler_sample); BIND(llama_batch_get_one); + auto *s = static_cast(session); + llama_memory_clear_(llama_get_memory_(s->ctx), true); + int status = llama_dart_decode_(s->ctx, llama_batch_get_one_(s->tokens.data(), (int32_t)s->tokens.size())); + if (status != 0) return status; + llama_dart_sampler_sample_(s->sampler, s->ctx, -1); + return 0; +} +void shim_sleeping_atexit(int ms) { + static int delay; delay = ms; + atexit([] { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); }); +} +} From 90fd51d7ea8408b63285f20362d6305009281127 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 14:37:44 -0400 Subject: [PATCH 5/8] fix: end the process at C exit on Linux when a call is in flight Waiting at exit for the call in flight, and then letting the exit go on, left two rows worse than v0.6.0-1: a Dart VM aborts when an isolate collects garbage while exit() takes its time (17 of 30 against 10 of 30 inside a long CPU decode), and a lavapipe decode that cannot be ended was still running when the driver's exit handlers ran (2 of 50 against 0 of 50). The exit handler, now registered with on_exit for the status, ends the process with fflush(NULL) and _exit(status) when a call is in flight on another thread, and returns at once otherwise. It no longer runs teardown, so the abort callback that ended a CPU decode while teardown waited is gone. libllamadart gets the definition of __cxa_atexit that registers nothing, like the libraries next to it, and is linked with -z nodelete because dlclose does not remove an on_exit handler; validate_linux_artifact.py checks that. --- CMakeLists.txt | 27 ++- src/llama_dart_static_destructors.c | 10 +- src/llama_dart_wrapper.cpp | 128 +++++--------- src/llama_dart_wrapper.h | 52 +++--- tests/exit_teardown_test.cpp | 236 +++++++++++++------------- tests/manual/dart_exit_probe.dart | 22 +-- tests/validate_linux_artifact_test.py | 54 +++++- tools/validate_linux_artifact.py | 20 +++ 8 files changed, 302 insertions(+), 247 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d7881bce..3f2ded07 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -189,7 +189,8 @@ endif() llamadart_attach_android_cpu_backend_score(ggml-cpu) # Adds src/llama_dart_static_destructors.c to every shared library and backend -# module that llama.cpp builds, whatever backends are enabled. +# module that llama.cpp builds, whatever backends are enabled. libllamadart +# gets it below. function(llamadart_drop_static_destructors directory) get_property(target_names DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) foreach(target_name IN LISTS target_names) @@ -215,6 +216,13 @@ endif() add_library(llamadart_lib SHARED "src/llama_dart_wrapper.cpp" "src/llama_dart_vulkan_device_info.cpp") +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_sources(llamadart_lib PRIVATE + $) + # libllamadart registers an exit handler with on_exit, which a dlclose + # does not remove, so the library must not be unloaded. + target_link_options(llamadart_lib PRIVATE -Wl,-z,nodelete) +endif() # The Vulkan device facts need only the Vulkan types: the loader is opened at # run time, so libllamadart links no Vulkan library and loads without one. set(LLAMADART_VULKAN_HEADERS_INCLUDE @@ -385,15 +393,16 @@ if (LLAMADART_BUILD_TESTS) set_tests_properties(llamadart_exit_teardown_${scenario} PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_model) endforeach() - # What only Linux does: teardown ends a decode on the CPU backend, - # the statics of llama.cpp outlive an exit, and the exit takes time - # only for a call in flight and blocks no thread. + # What only Linux does: the exit ends the process for a call in + # flight, the statics of llama.cpp outlive an exit, and an exit with + # no call in flight takes no time and blocks no thread. if (CMAKE_SYSTEM_NAME STREQUAL "Linux") - add_test(NAME llamadart_exit_teardown_exit-late-calls - COMMAND llamadart_exit_teardown_test exit-late-calls) - foreach(scenario model-decode-ended model-decode-outlasts-wait - model-exit-idle model-exit-join-idle - model-exit-join-generating) + foreach(scenario exit-late-calls exit-status) + add_test(NAME llamadart_exit_teardown_${scenario} + COMMAND llamadart_exit_teardown_test ${scenario}) + endforeach() + foreach(scenario model-unguarded-decode model-exit-idle + model-exit-join-idle model-exit-join-generating) add_test(NAME llamadart_exit_teardown_${scenario} COMMAND llamadart_exit_teardown_test ${scenario} "${exit_teardown_model}") diff --git a/src/llama_dart_static_destructors.c b/src/llama_dart_static_destructors.c index 1621ed02..cd54473d 100644 --- a/src/llama_dart_static_destructors.c +++ b/src/llama_dart_static_destructors.c @@ -1,5 +1,5 @@ -// Linked into every llama.cpp shared library of the Linux bundle, and not -// into libllamadart (CMakeLists.txt). +// Linked into every shared library of the Linux bundle: libllamadart and the +// llama.cpp libraries next to it (CMakeLists.txt). // // The C++ runtime registers the destructor of each static of a library // through __cxa_atexit. The linker binds those calls to this definition, @@ -11,8 +11,10 @@ // runs before the first of those statics is destroyed. Here the libraries are // separate, and exit handlers run in reverse order of registration: no handler // of libllamadart precedes the destructor of a static that another library -// creates later, in the middle of a model load for one. A static that is never -// destroyed also stays valid for a call that outlasts teardown's wait. +// creates later, in the middle of a model load for one. The handler that +// libllamadart does register ends the process for a call in flight that it +// counts; a static that is never destroyed stays valid for the calls that it +// does not. #if defined(__linux__) && !defined(__ANDROID__) __attribute__((visibility("hidden"), used)) int __cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index eddcbf5d..4ada57bd 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -44,19 +44,14 @@ #endif #endif -// Where C exit() runs exit teardown, or on Linux the wait of it. Android is -// left out: an exit during a call in flight has not been examined there. -#if defined(__linux__) && !defined(__ANDROID__) -#include +// On Linux with glibc, C exit() runs llama_dart_exit_at_exit. Android is left +// out: an exit during a call in flight has not been examined there. +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +#include #define LLAMA_DART_EXIT_ON_LINUX 1 #else #define LLAMA_DART_EXIT_ON_LINUX 0 #endif -#if defined(__APPLE__) || LLAMA_DART_EXIT_ON_LINUX -#define LLAMA_DART_EXIT_AT_PROCESS_EXIT 1 -#else -#define LLAMA_DART_EXIT_AT_PROCESS_EXIT 0 -#endif // Global log level (0=none, 1=debug, 2=info, 3=warn, 4=error) static std::atomic g_dart_log_level{3}; // Default to WARN @@ -743,32 +738,11 @@ static thread_local bool llama_dart_exit_teardown_thread = false; static thread_local int32_t llama_dart_exit_call_depth = 0; #if LLAMA_DART_EXIT_ON_LINUX -// Set while teardown waits for the calls in flight, and for good when it gave -// up waiting or was run by C exit(). A decode or an encode on the CPU backend -// ends then. One that outlasts the wait is still running when the exit -// reaches the handlers of other libraries, and the destructor of OpenBLAS -// never returns while its threads are at work. -static std::atomic llama_dart_exit_ending_calls{false}; - -static bool llama_dart_exit_abort_callback(void *) { - return llama_dart_exit_ending_calls.load(std::memory_order_relaxed); -} - -// Whether the teardown that this thread is about to run is the one of C -// exit(), which only waits. -static thread_local bool llama_dart_exit_only_waits = false; - -// Set, under the registry lock, when C exit() runs teardown: it then frees -// nothing. Nothing on Linux needs the objects freed, and the exit handlers of -// a GPU driver may have run already: an exit with a model left loaded is -// known to be clean, a free among those handlers is not. +// Set, under the registry lock, once C exit() has reached libllamadart. The +// exit frees nothing: nothing on Linux needs the objects freed, and the exit +// handlers of a GPU driver may have run already. An exit with a model left +// loaded is known to be clean, a free among those handlers is not. static std::atomic llama_dart_exit_keeps_objects{false}; - -static void llama_dart_exit_wait_at_exit() { - llama_dart_exit_only_waits = true; - llama_dart_exit_teardown(); - llama_dart_exit_only_waits = false; -} #endif // Called with the registry locked. Returns whether the calling thread may go @@ -788,8 +762,8 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, return true; } #if LLAMA_DART_EXIT_ON_LINUX - // Nothing was freed, so the thread holds nothing that is gone, and blocked - // here it would hang an exit handler of the host that joins it. + // The exit freed nothing, so the thread holds nothing that is gone, and + // blocked here it would hang an exit handler of the host that joins it. if (llama_dart_exit_keeps_objects.load()) { return false; } @@ -802,16 +776,16 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, #if LLAMA_DART_EXIT_ON_LINUX // Whether a call in flight that was just begun on this thread was not counted -// because C exit() has waited already. Such a call must not start work that -// the exit no longer waits for: its function throws, and the barrier returns -// the failure value. +// because C exit() has passed libllamadart already. Such a call must not +// start work under the rest of the exit: its function throws, and the barrier +// returns the failure value. static bool llama_dart_exit_began_too_late() { return llama_dart_exit_call_depth == 0 && !llama_dart_exit_teardown_thread && llama_dart_exit_keeps_objects.load(); } #endif -#if LLAMA_DART_EXIT_AT_PROCESS_EXIT +#if defined(__APPLE__) struct llama_dart_exit_static_destructor { void (*destroy)(void *); void *object; @@ -821,11 +795,7 @@ static void llama_dart_exit_destroy_static(void *argument) { const auto destructor = *static_cast(argument); free(argument); -#if LLAMA_DART_EXIT_ON_LINUX - llama_dart_exit_wait_at_exit(); -#else llama_dart_exit_teardown(); -#endif destructor.destroy(destructor.object); } @@ -871,6 +841,34 @@ __cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { } #endif +#if LLAMA_DART_EXIT_ON_LINUX +// What C exit() runs on Linux. With a call in flight on another thread it +// ends the process there, with the status of the exit and without the rest +// of the exit: what would follow is the exit handlers and destructors of +// other libraries, a GPU driver or OpenBLAS among them, which would run under +// the call. It does not wait for the call instead, because time spent inside +// exit() is not harmless either: a Dart VM aborts when one of its isolates +// collects garbage meanwhile, and 20 ms were enough for that. With no call in +// flight it returns at once and the exit goes on. +static void llama_dart_exit_at_exit(int status, void *) { + auto ®istry = llama_dart_exit_state(); + { + std::lock_guard lock(registry.mutex); + if (!registry.torn_down.exchange(true)) { + llama_dart_exit_teardown_thread = true; + llama_dart_exit_keeps_objects.store(true); + } + // A call in flight on this thread is the one that is exiting. + const int32_t own_calls = llama_dart_exit_call_depth > 0 ? 1 : 0; + if (registry.calls == own_calls) { + return; + } + } + fflush(nullptr); + _exit(status); +} +#endif + // Registers teardown to run at exit once something is tracked, so that it // does not wait for the first static of this image to be destroyed. atexit // handlers run in reverse order of registration, so this one runs after the @@ -882,20 +880,20 @@ static void llama_dart_exit_arm() { } #elif LLAMA_DART_EXIT_ON_LINUX if (!llama_dart_exit_state().armed.exchange(true)) { - atexit(llama_dart_exit_wait_at_exit); + on_exit(llama_dart_exit_at_exit, nullptr); } #endif } -// On Linux llama.cpp is not part of this image and its libraries register no -// static destructors (llama_dart_static_destructors.c), so only a handler -// runs the wait at exit, and the exit that arrives during the first creating +// On Linux llama.cpp is not part of this image and no library of the bundle +// registers static destructors (llama_dart_static_destructors.c), so only a +// handler sees the exit, and the exit that arrives during the first creating // call needs one that was registered before anything is tracked. static void llama_dart_exit_arm_creating_call() { #if LLAMA_DART_EXIT_ON_LINUX static std::atomic armed{false}; if (!armed.exchange(true)) { - atexit(llama_dart_exit_wait_at_exit); + on_exit(llama_dart_exit_at_exit, nullptr); } #endif } @@ -1096,19 +1094,6 @@ static bool llama_dart_exit_load_progress_callback(float progress, caller->callback(progress, caller->user_data); } -// On Linux, gives a context without an abort callback the one that ends its -// evaluations while teardown waits. -static void llama_dart_exit_end_evaluations_at_exit( - llama_context_params ¶ms) { -#if LLAMA_DART_EXIT_ON_LINUX - if (params.abort_callback == nullptr) { - params.abort_callback = llama_dart_exit_abort_callback; - } -#else - (void)params; -#endif -} - static void llama_dart_exit_free_model(void *object) { llama_model_free(static_cast(object)); } @@ -1210,9 +1195,6 @@ LLAMADART_API void llama_dart_exit_teardown(void) { return; } llama_dart_exit_teardown_thread = true; -#if LLAMA_DART_EXIT_ON_LINUX - llama_dart_exit_keeps_objects.store(llama_dart_exit_only_waits); -#endif const auto can_free = [®istry](const auto &tracked) { return llama_dart_exit_can_free(registry, tracked.second); }; @@ -1225,25 +1207,12 @@ LLAMADART_API void llama_dart_exit_teardown(void) { } // A call in flight on this thread cannot end while teardown runs. const int32_t own_calls = llama_dart_exit_call_depth > 0 ? 1 : 0; -#if LLAMA_DART_EXIT_ON_LINUX - llama_dart_exit_ending_calls.store(true); -#endif const bool idle = registry.idle.wait_for( lock, std::chrono::milliseconds(registry.wait_ms), [®istry, own_calls] { return registry.calls == own_calls; }); if (!idle) { return; } -#if LLAMA_DART_EXIT_ON_LINUX - // The exit frees nothing, so it has no reason to let the threads settle: - // it takes time only while a call is in flight. Time spent in exit() is - // not harmless, as a Dart VM aborts when its isolates run meanwhile. - if (llama_dart_exit_keeps_objects.load()) { - return; - } - // The free functions that run next may evaluate. - llama_dart_exit_ending_calls.store(false); -#endif registry.idle.wait_until( lock, registry.last_call_end + llama_dart_exit_settle_time, [] { return false; }); @@ -1289,7 +1258,6 @@ llama_dart_init_from_model(struct llama_model *model, struct llama_context_params params) { return llama_dart_barrier(nullptr, [model, ¶ms] { llama_dart_exit_creating_call call; - llama_dart_exit_end_evaluations_at_exit(params); return llama_dart_exit_track_created( llama_init_from_model(model, params), llama_dart_exit_free_context, LLAMA_DART_EXIT_STAGE_CONTEXT); @@ -2187,7 +2155,6 @@ static struct llama_dart_speculative *llama_dart_speculative_init_impl( context_params.embeddings = false; context_params.ctx_other = target_context; - llama_dart_exit_end_evaluations_at_exit(context_params); speculative->ctx_dft = llama_init_from_model(resolved_draft_model, context_params); if (speculative->ctx_dft == nullptr) { @@ -2439,7 +2406,6 @@ static struct llama_dart_mtp *llama_dart_mtp_init_impl( ctx_params.embeddings = false; ctx_params.ctx_other = ctx_tgt; - llama_dart_exit_end_evaluations_at_exit(ctx_params); // Owns the draft context until the handle does, so that neither a failure // nor an exception leaves it behind. std::unique_ptr draft_context( diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index c995e973..971473a4 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -354,30 +354,33 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // destructor. On Apple platforms it runs during exit, before the first static // of libllamadart is destroyed. // -// On Linux, Android excepted, C exit() runs the wait of teardown and nothing -// else. It waits for the calls in flight, for no longer than they take: with -// none in flight it returns at once. It frees nothing and blocks no thread. -// Nothing on Linux needs the objects freed, and an exit with a model left -// loaded is known to be clean, which a free among the exit handlers of a GPU -// driver is not. llama.cpp is not part of libllamadart there, and its -// libraries register no static destructors: their statics stay valid until -// the process is gone, also under a call that the wait does not cover. +// On Linux with glibc, C exit() does not run teardown. llama.cpp is not part +// of libllamadart there, and no library of the bundle registers static +// destructors: their statics stay valid until the process is gone. When the +// exit reaches libllamadart: // -// Once that wait has begun, a thread other than the exiting one gets this -// from libllamadart instead of being blocked: a call in flight that begins -// returns the failure value of its function, with "the process is exiting" -// as the last error, and starts nothing; llama_dart_exit_free frees nothing; -// llama_dart_exit_track and llama_dart_exit_untrack return false; -// llama_dart_exit_call_begin counts nothing. The call that the exit waited -// for returns to its caller. While teardown waits, and from then on after an -// exit, a decode or an encode on the CPU backend ends with the status -// llama.cpp has for an aborted one, 2, unless its context has an abort -// callback of its own. +// - With a call in flight on another thread, the process ends there, as with +// _exit: with the status of the exit and the standard streams flushed, but +// without the exit handlers and static destructors that would have run +// next, those of the host among them. What would have run next is the exit +// handlers of other libraries, a GPU driver or OpenBLAS among them, under +// the call, and waiting for the call instead is not harmless either: a +// Dart VM aborts when its isolates run while exit() takes its time. +// - With no call in flight, the exit goes on at once. Nothing is freed: +// nothing on Linux needs it, and an exit with a model left loaded is known +// to be clean, which a free among the exit handlers of a GPU driver is not. +// No thread is blocked. From then on, on a thread other than the exiting +// one, a call in flight that begins returns the failure value of its +// function, with "the process is exiting" as the last error, and starts +// nothing; llama_dart_exit_free frees nothing; llama_dart_exit_track and +// llama_dart_exit_untrack return false; llama_dart_exit_call_begin counts +// nothing. // -// The wait begins when the exit reaches the handler that libllamadart -// registers at the first creating call and again when the first object is -// tracked, so an exit handler that another library registers later runs -// before it. quick_exit and _exit run nothing. +// The exit reaches libllamadart at the handler that it registers at the first +// creating call and again when the first object is tracked, so an exit handler +// that another library registers later runs before that. libllamadart is +// linked so that dlclose does not unload it. quick_exit and _exit run +// nothing. // // Elsewhere nothing runs at exit. llama_dart_exit_teardown runs teardown, and // frees, on every platform. @@ -476,10 +479,7 @@ LLAMADART_API struct llama_model * llama_dart_model_load_from_file( struct llama_model_params params); // llama_init_from_model that tracks the context in the CONTEXT stage. Free it -// with llama_dart_exit_free. On Linux, when params has no abort callback, the -// context gets the one that ends its evaluations while teardown waits, as do -// the draft contexts that the speculative and MTP init functions create; -// llama_set_abort_callback replaces it. Blocks after teardown. +// with llama_dart_exit_free. Blocks after teardown. LLAMADART_API struct llama_context * llama_dart_init_from_model( struct llama_model * model, struct llama_context_params params); diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index d0826bc4..4e23e9a0 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -30,6 +30,11 @@ #define LLAMADART_TEST_ADDRESS_SANITIZER 1 #endif +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +#include +#include +#endif + #if defined(LLAMADART_TEST_ADDRESS_SANITIZER) #include #elif defined(__APPLE__) @@ -464,47 +469,47 @@ int test_blocked() { return 0; } -// C exit() runs teardown on Apple platforms: it frees, and blocks the threads -// that reach libllamadart afterwards. On Linux it runs the wait of teardown -// only: it frees nothing, blocks no thread and refuses the calls in flight -// that begin afterwards. Teardown there also ends a decode or an encode on -// the CPU backend while it waits, with llama.cpp's status for an aborted one. +// C exit() runs teardown on Apple platforms: it waits for the calls in +// flight, frees, and blocks the threads that reach libllamadart afterwards. +// On Linux it ends the process at once when a call is in flight on another +// thread. Otherwise it frees nothing, blocks no thread and refuses the calls +// in flight that begin afterwards. #if defined(__APPLE__) const bool kExitFreesObjects = true; const bool kExitWaitsForCalls = true; -const bool kExitBlocksThreads = true; +const bool kExitEndsProcess = false; const bool kExitRefusesLateCalls = false; -const bool kTeardownEndsEvaluations = false; -#elif defined(__linux__) && !defined(__ANDROID__) +#elif defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) const bool kExitFreesObjects = false; -const bool kExitWaitsForCalls = true; -const bool kExitBlocksThreads = false; +const bool kExitWaitsForCalls = false; +const bool kExitEndsProcess = true; const bool kExitRefusesLateCalls = true; -const bool kTeardownEndsEvaluations = true; #else const bool kExitFreesObjects = false; const bool kExitWaitsForCalls = false; -const bool kExitBlocksThreads = false; +const bool kExitEndsProcess = false; const bool kExitRefusesLateCalls = false; -const bool kTeardownEndsEvaluations = false; #endif -// Set by a scenario before the teardown that an evaluation may run into. -std::atomic g_teardown_expected{false}; +// Set by a scenario before the exit that a call may run into. +std::atomic g_exit_expected{false}; // Whether the calling thread's last call was refused because C exit() had -// waited already. +// passed libllamadart already. bool refused_by_exit() { const char *error = llama_dart_last_error(); - return kExitRefusesLateCalls && g_teardown_expected.load() && - error != nullptr && strcmp(error, "the process is exiting") == 0; + return kExitRefusesLateCalls && g_exit_expected.load() && error != nullptr && + strcmp(error, "the process is exiting") == 0; } -bool evaluated(int32_t status) { - return status == 0 || - (status == 2 && kTeardownEndsEvaluations && - g_teardown_expected.load()) || - refused_by_exit(); +// For an exit handler that a scenario registers before libllamadart registers +// its own, so that it runs after it. Where the exit ends the process for a +// call in flight, the exit never gets this far in such a scenario. +void expect_process_ended(const char *what) { + if (kExitEndsProcess) { + fprintf(stderr, "the exit went on under %s\n", what); + _Exit(EXIT_FAILURE); + } } // Where the backends are modules next to the llama.cpp libraries and not part @@ -541,14 +546,15 @@ int test_exit() { std::atomic g_call_ended{false}; void expect_call_ended_at_exit() { + expect_process_ended("a call in flight"); if (kExitWaitsForCalls && !g_call_ended.load()) { fprintf(stderr, "the exit did not wait for the call in flight\n"); _Exit(EXIT_FAILURE); } } -// The exit waits for a call in flight when objects were only tracked, with -// no creating call. +// The exit sees a call in flight when objects were only tracked, with no +// creating call: it waits for the call, or on Linux ends the process. int test_exit_in_flight() { // Registered first, so it runs after the teardown registered by tracking. assert(atexit(expect_call_ended_at_exit) == 0); @@ -575,7 +581,7 @@ char kLateObject[] = "late-object"; // exit has waited, on Linux: nothing blocks, a free frees nothing, and a call // in flight is refused before it starts. void make_late_calls() { - g_teardown_expected.store(true); + g_exit_expected.store(true); std::thread([] { llama_dart_exit_free(kLateObject); assert(recorded().empty()); @@ -613,6 +619,53 @@ int test_exit_late_calls() { return 0; } +// On Linux an exit with a call in flight on another thread ends the process +// there: with the status of the exit and the standard streams flushed, and +// without the exit handlers that would have run next. The exit is that of a +// child process, whose status and output this one reads. +int test_exit_status() { +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) + int output[2]; + assert(pipe(output) == 0); + const pid_t child = fork(); + assert(child >= 0); + if (child == 0) { + close(output[0]); + assert(dup2(output[1], STDOUT_FILENO) >= 0); + // Registered first, so it would run after the handler of libllamadart. + assert(atexit([] { _Exit(EXIT_FAILURE); }) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + static std::atomic started{false}; + std::thread([] { + llama_dart_exit_call_begin(); + started.store(true); + sleep_ms(600000); + }).detach(); + while (!started.load()) { + sleep_ms(1); + } + // A pipe is fully buffered, so this is written when the exit flushes. + printf("flushed at exit"); + exit(37); + } + close(output[1]); + const auto started = std::chrono::steady_clock::now(); + std::string text; + char buffer[64]; + for (ssize_t count; (count = read(output[0], buffer, sizeof(buffer))) > 0;) { + text.append(buffer, static_cast(count)); + } + int status = 0; + assert(waitpid(child, &status, 0) == child); + assert(WIFEXITED(status) && WEXITSTATUS(status) == 37); + assert(text == "flushed at exit"); + assert(elapsed_ms(started) < 10000); +#endif + return 0; +} + std::string g_system_info; // Uses the static behind llama_print_system_info, which teardown must find @@ -787,7 +840,6 @@ struct model_options { bool cpu_only = false; bool embeddings = false; ggml_backend_sched_eval_callback eval_callback = nullptr; - ggml_abort_callback abort_callback = nullptr; }; struct model_fixture { @@ -812,7 +864,6 @@ model_fixture load_model(const char *path, model_options options = {}) { context_params.n_ctx = 256; context_params.embeddings = options.embeddings; context_params.cb_eval = options.eval_callback; - context_params.abort_callback = options.abort_callback; fixture.context = options.tracked ? llama_dart_init_from_model(fixture.model, context_params) @@ -846,8 +897,8 @@ llama_sampler *greedy_sampler() { llama_token decode_and_sample(model_fixture &fixture, llama_sampler *sampler) { clear_memory(fixture); const int32_t status = llama_dart_decode(fixture.context, prompt(fixture)); - assert(evaluated(status)); - // A decode that teardown ended has left nothing to sample. + assert(status == 0 || refused_by_exit()); + // A decode that was refused has left nothing to sample. return status == 0 ? llama_dart_sampler_sample(sampler, fixture.context, -1) : 0; } @@ -1232,26 +1283,11 @@ void start_beat() { } } -std::atomic g_exit_began_ms{0}; - -// An exit handler that a scenario registers after the one of libllamadart, -// so that it runs right before it. Where the exit blocks no thread, the beat -// does not stop and this is how a scenario learns that the exit has begun. -void note_exit_began() { g_exit_began_ms.store(now_ms()); } - -bool teardown_waits() { - if (now_ms() - g_last_beat_ms.load() >= 200) { - return true; - } - const int64_t began = g_exit_began_ms.load(); - return !kExitBlocksThreads && began != 0 && now_ms() - began >= 200; -} - // Releases the held evaluation once teardown is waiting for it, and gives up // after ten seconds. void release_when_teardown_waits() { const int64_t started = now_ms(); - while (!teardown_waits()) { + while (now_ms() - g_last_beat_ms.load() < 200) { if (now_ms() - started > 10000) { g_released_before_teardown.store(true); break; @@ -1302,7 +1338,6 @@ int test_evaluation_wait(const char *path, void (*evaluate)(model_fixture &), llama_dart_exit_set_wait_ms(30000); held_evaluate = evaluate; g_hold_evaluation.store(true); - g_teardown_expected.store(true); std::thread([] { held_evaluate(fixture); }).detach(); while (!g_evaluation_held.load()) { sleep_ms(1); @@ -1317,11 +1352,11 @@ int test_evaluation_wait(const char *path, void (*evaluate)(model_fixture &), } void decode_prompt(model_fixture &fixture) { - assert(evaluated(llama_dart_decode(fixture.context, prompt(fixture)))); + assert(llama_dart_decode(fixture.context, prompt(fixture)) == 0); } void encode_prompt(model_fixture &fixture) { - assert(evaluated(llama_dart_encode(fixture.context, prompt(fixture)))); + assert(llama_dart_encode(fixture.context, prompt(fixture)) == 0); } // Evaluates a text chunk, which needs no mtmd context. @@ -1330,13 +1365,9 @@ void eval_text_chunk(model_fixture &fixture) { const mtmd_input_chunk *text = mtmd_input_chunks_get(chunks, 0); assert(mtmd_input_chunk_get_type(text) == MTMD_INPUT_CHUNK_TYPE_TEXT); llama_pos position = 0; - const int32_t status = llama_dart_mtmd_helper_eval_chunk_single( - nullptr, fixture.context, text, 0, 0, 16, true, &position); - if (status == 0) { - assert(position == 5); - } else { - assert(kTeardownEndsEvaluations && g_teardown_expected.load()); - } + assert(llama_dart_mtmd_helper_eval_chunk_single( + nullptr, fixture.context, text, 0, 0, 16, true, &position) == 0); + assert(position == 5); mtmd_input_chunks_free(chunks); } @@ -1373,7 +1404,7 @@ int exit_while_generating(model_fixture &fixture) { while (steps.load() < 4) { sleep_ms(1); } - g_teardown_expected.store(true); + g_exit_expected.store(true); g_exiting.store(true); return 0; } @@ -1410,52 +1441,25 @@ void finish_held_evaluation_at_exit() { } } -// On Linux teardown ends a decode in flight on the CPU backend instead of -// sitting it out: the held decode computes no tensor to the end once teardown -// waits for it. -int test_model_decode_ended(const char *path) { - static model_fixture fixture; - model_options options; - options.eval_callback = hold_then_count_evaluation; - fixture = load_model(path, options); - decode_prompt(fixture); - clear_memory(fixture); - llama_dart_exit_set_wait_ms(30000); - g_hold_evaluation.store(true); - g_teardown_expected.store(true); - std::thread([] { decode_prompt(fixture); }).detach(); - while (!g_evaluation_held.load()) { - sleep_ms(1); - } - start_beat(); - std::thread(release_when_teardown_waits).detach(); - llama_dart_exit_teardown(); - assert(!g_released_before_teardown.load()); - assert(g_computed_after_release.load() == 0); - assert(llama_dart_exit_tracked_count() == 0); - return 0; -} - -// Exits while another thread is inside a decode that outlasts teardown's -// wait. On Linux the llama.cpp libraries register no static destructors, so -// the decode computes on, with the statics the model load created, after the -// exit has run its handlers. -int test_model_decode_outlasts_wait(const char *path) { - // Registered first, so it runs after teardown and after the destructors of - // the statics that the load creates, where those are registered. +// Exits while another thread is inside a decode that is not a call in +// flight, so that the exit goes on under it. On Linux no library of the +// bundle registers static destructors, so the decode computes on, with the +// statics the model load created, after the exit has run its handlers. +int test_model_unguarded_decode(const char *path) { + // Registered first, so it runs after the handler of libllamadart and after + // the destructors of the statics that the load creates, where those are + // registered. assert(atexit(finish_held_evaluation_at_exit) == 0); static model_fixture fixture; model_options options; options.eval_callback = hold_then_count_evaluation; - // The caller's own callback, which libllamadart leaves in place: teardown - // does not end this decode. - options.abort_callback = [](void *) { return false; }; fixture = load_model(path, options); decode_prompt(fixture); clear_memory(fixture); - llama_dart_exit_set_wait_ms(100); g_hold_evaluation.store(true); - std::thread([] { decode_prompt(fixture); }).detach(); + std::thread([] { + assert(llama_decode(fixture.context, prompt(fixture)) == 0); + }).detach(); while (!g_evaluation_held.load()) { sleep_ms(1); } @@ -1473,9 +1477,9 @@ void expect_exit_took_no_time() { } } -// On Linux an exit right after a guarded call returned takes no time: with -// nothing to free there is nothing to let the threads settle for, and a Dart -// VM aborts when its isolates run while exit() takes its time. +// On Linux an exit with no call in flight takes no time in libllamadart, +// also right after a guarded call returned: a Dart VM aborts when its +// isolates run while exit() takes its time. int test_model_exit_idle(const char *path) { // Registered first, so it runs after the handler of libllamadart. assert(atexit(expect_exit_took_no_time) == 0); @@ -1527,8 +1531,10 @@ int test_model_exit_join_idle(const char *path) { return 0; } -// The same with a worker that generates until it is told to stop: the exit -// ends its decode in flight, and every call it begins afterwards is refused. +// The same with a worker that generates until it is told to stop. An exit +// that finds its decode in flight ends the process; one that falls between +// two calls goes on, every call the worker begins afterwards is refused, and +// the worker comes back. int test_model_exit_join_generating(const char *path) { assert(atexit(stop_and_join_worker) == 0); static model_fixture fixture; @@ -1549,7 +1555,7 @@ int test_model_exit_join_generating(const char *path) { while (steps.load() < 3) { sleep_ms(1); } - g_teardown_expected.store(true); + g_exit_expected.store(true); return 0; } @@ -1572,6 +1578,7 @@ int test_model_late_load(const char *path) { std::atomic g_load_resumed{false}; void expect_exit_waited_for_load() { + expect_process_ended("a load in flight"); if (kExitWaitsForCalls && !g_load_resumed.load()) { fprintf(stderr, "the exit did not wait for the load in flight\n"); _Exit(EXIT_FAILURE); @@ -1580,8 +1587,8 @@ void expect_exit_waited_for_load() { // Exits while another thread is loading the model. int test_model_load(const char *path) { - // Registered first, so it runs after teardown, which nothing but the load - // in flight makes run: nothing is tracked. + // Registered first, so it runs after the handler of libllamadart, which + // nothing but the load in flight makes run: nothing is tracked. assert(atexit(expect_exit_waited_for_load) == 0); init_backends(); static std::atomic loading{false}; @@ -1606,13 +1613,9 @@ int test_model_load(const char *path) { return true; }; std::thread([params] { - const llama_model *model = - llama_dart_model_load_from_file(model_path, params); - // Where the exit blocks no thread, the cancelled load returns. - if (kExitBlocksThreads || model != nullptr) { - fprintf(stderr, "the load returned to its caller after teardown\n"); - _Exit(EXIT_FAILURE); - } + llama_dart_model_load_from_file(model_path, params); + fprintf(stderr, "the load returned to its caller after teardown\n"); + _Exit(EXIT_FAILURE); }).detach(); while (!loading.load()) { sleep_ms(1); @@ -1715,6 +1718,7 @@ void free_model_when_teardown_waits(void *object) { } void expect_free_finished_at_exit() { + expect_process_ended("a free in flight"); if (!g_free_finished.load() || g_released_before_teardown.load()) { fprintf(stderr, "the exit did not wait for the free in flight\n"); _Exit(EXIT_FAILURE); @@ -1738,7 +1742,6 @@ int test_model_free_in_flight(const char *path) { assert(llama_dart_exit_track(fixture.model, free_model_when_teardown_waits, LLAMA_DART_EXIT_STAGE_MODEL)); llama_dart_exit_set_wait_ms(30000); - assert(atexit(note_exit_began) == 0); start_beat(); std::thread([] { llama_dart_exit_free(fixture.model); }).detach(); while (!g_free_started.load()) { @@ -2592,6 +2595,10 @@ int main(int argc, char **argv) { const std::string scenario = argc > 1 ? argv[1] : ""; const char *first = argc > 2 ? argv[2] : nullptr; const char *second = argc > 3 ? argv[3] : nullptr; + // Forks, so it runs before anything starts a thread. + if (scenario == "exit-status") { + return test_exit_status(); + } // Keeps llama.cpp's device, load and decode logs out of the test output. llama_dart_set_log_level(3); if (scenario == "dispose") { @@ -2721,11 +2728,8 @@ int main(int argc, char **argv) { if (scenario == "model-exit-join-generating") { return test_model_exit_join_generating(first); } - if (scenario == "model-decode-ended") { - return test_model_decode_ended(first); - } - if (scenario == "model-decode-outlasts-wait") { - return test_model_decode_outlasts_wait(first); + if (scenario == "model-unguarded-decode") { + return test_model_unguarded_decode(first); } if (scenario == "model-late-load") { return test_model_late_load(first); diff --git a/tests/manual/dart_exit_probe.dart b/tests/manual/dart_exit_probe.dart index 89c3187d..3bb762fb 100644 --- a/tests/manual/dart_exit_probe.dart +++ b/tests/manual/dart_exit_probe.dart @@ -10,7 +10,8 @@ // // // holds libllamadart.so and the backend modules. A run is clean -// when it prints EXIT_PROBE_REACHED and exits with code 0. +// when it prints EXIT_PROBE_REACHED and exits with code 0. Append -slow-exit +// to a scenario for a host whose own exit handler takes 300 ms. import 'dart:async'; import 'dart:convert'; import 'dart:ffi'; @@ -109,7 +110,7 @@ void _generateThenIdle((SendPort, String, String, String, int) a) { } Future main(List args) async { - final [shimPath, bundle, scenario, model] = args; + final [shimPath, bundle, requested, model] = args; final shim = DynamicLibrary.open(shimPath); final openLib = shim.lookupFunction<_OpenLibN, _OpenLibD>( 'shim_open_library', @@ -128,18 +129,19 @@ Future main(List args) async { await ready.first; } + // A scenario with -slow-exit appended has an exit handler that takes 300 ms. + // It is registered before libllamadart is opened, and so runs after the + // handler of libllamadart. + const slowExit = '-slow-exit'; + final scenario = requested.endsWith(slowExit) + ? requested.substring(0, requested.length - slowExit.length) + : requested; + if (scenario != requested) sleepingAtexit(300); + switch (scenario) { case 'control-spin': // no native library at all await spin(); _cExit(); - case 'control-spin-slow-exit': // an exit handler that takes 300 ms - sleepingAtexit(300); - await spin(); - _cExit(); - case 'control-spin-slow-exit-2500': - sleepingAtexit(2500); - await spin(); - _cExit(); case 'idle-spin': // model idle for longer than the settle time openLib(_cstr(bundle)); final s = openSession(_cstr(model), 8); diff --git a/tests/validate_linux_artifact_test.py b/tests/validate_linux_artifact_test.py index 0d504cfc..1da7b7d2 100644 --- a/tests/validate_linux_artifact_test.py +++ b/tests/validate_linux_artifact_test.py @@ -16,6 +16,7 @@ from tools.validate_linux_artifact import ( extract_archive, extract_member_safely, + is_nodelete, parse_imports, resolve_tool, validate_archive, @@ -267,9 +268,60 @@ def test_imports_are_the_undefined_dynamic_symbols(self) -> None: parse_imports(objdump, "objdump"), {"__cxa_finalize", "__cxa_atexit"} ) + def test_nodelete_is_read_from_readelf_and_objdump(self) -> None: + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n") + ) + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW NODELETE\n") + ) + self.assertTrue(is_nodelete(" FLAGS_1 0x0000000000000009\n")) + self.assertFalse(is_nodelete(" FLAGS_1 0x0000000000000001\n")) + self.assertFalse( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW\n") + ) + self.assertFalse(is_nodelete(" 0x000000000000001e (FLAGS) BIND_NOW\n")) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_libllamadart_must_not_be_unloadable(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + with tarfile.open(archive_path, "w:gz") as archive: + for name in ("libllamadart.so", "libmtmd.so.0"): + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + " printf ' 0x000000000000000e (SONAME) Library soname: [%s]\\n'" + ' "$(basename "$2")"\n' + "fi\n" + ) + tool.chmod(0o755) + + errors = validate_archive(archive_path, str(tool), "readelf") + + self.assertEqual( + errors, + [ + "libllamadart.so: is not linked with -z nodelete, so a dlclose " + "leaves its exit handler behind" + ], + ) + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") def test_a_local_library_must_not_import_cxa_atexit(self) -> None: - dynamic = " 0x000000000000000e (SONAME) Library soname: [{soname}]\n" + dynamic = ( + " 0x000000000000000e (SONAME) Library soname: [{soname}]\n" + " 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n" + ) imported = ( " 1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " "__cxa_atexit@GLIBC_2.17 (2)\n" diff --git a/tools/validate_linux_artifact.py b/tools/validate_linux_artifact.py index b2060fd8..d2aece00 100644 --- a/tools/validate_linux_artifact.py +++ b/tools/validate_linux_artifact.py @@ -100,6 +100,19 @@ def inspect_dynamic(path: Path, tool: str, mode: str) -> DynamicMetadata: return DynamicMetadata(soname=soname, needed=tuple(needed), raw=raw) +def is_nodelete(raw: str) -> bool: + """Whether readelf -d or objdump -p output has DF_1_NODELETE set.""" + for line in raw.splitlines(): + if "FLAGS_1" not in line: + continue + if "NODELETE" in line: + return True + match = re.search(r"FLAGS_1\s+(0x[0-9a-fA-F]+)\s*$", line) + if match and int(match.group(1), 16) & 0x8: + return True + return False + + def parse_imports(raw: str, mode: str) -> set[str]: imports: set[str] = set() for line in raw.splitlines(): @@ -263,6 +276,13 @@ def validate_archive(archive_path: Path, tool: str, mode: str) -> list[str]: for dependency in dynamic.needed: if dependency.startswith(LOCAL_LIBRARY_PREFIXES) and dependency not in names: errors.append(f"{name}: local DT_NEEDED dependency is absent: {dependency}") + # libllamadart registers an exit handler with on_exit, which a + # dlclose does not remove: the library must never be unloaded. + if name == "libllamadart.so" and not is_nodelete(dynamic.raw): + errors.append( + f"{name}: is not linked with -z nodelete, so a dlclose " + "leaves its exit handler behind" + ) if name.startswith(LOCAL_LIBRARY_PREFIXES): try: imports = inspect_imports(root / name, tool, mode) From a511053b6ea500f35e7b3dee6ae7d2f298559ef8 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 16:09:15 -0400 Subject: [PATCH 6/8] docs: record the exit that ends the process and its measurements Pins the exemption of the exiting thread in the late-calls scenario and adds a late slow-handler variant to the manual Dart probe. --- README.md | 37 +-- docs/v060_2_wrapper_rebuild.md | 388 +++++++++++++++++------------- tests/exit_teardown_test.cpp | 8 + tests/manual/dart_exit_probe.dart | 15 +- 4 files changed, 258 insertions(+), 190 deletions(-) diff --git a/README.md b/README.md index 62db8184..f4e3faca 100644 --- a/README.md +++ b/README.md @@ -175,8 +175,8 @@ Assets are suffixed with platform/arch, for example: - `tools/package_linux_artifact.py`: preserves Linux ELF version files and SONAME symlinks while transporting split CI artifacts. - `tools/validate_linux_artifact.py`: checks Linux archive members, symlinks, - SONAMEs, and local `DT_NEEDED` dependencies, and that no library built here - imports `__cxa_atexit`. + SONAMEs, and local `DT_NEEDED` dependencies, that no library built here + imports `__cxa_atexit`, and that `libllamadart.so` cannot be unloaded. - `tools/package_apple_xcframework.py`: packages Apple `libllamadart` slices as an SPM-compatible XCFramework zip. - `tools/apple/PrivacyInfo.xcprivacy`: privacy manifest embedded in every @@ -287,28 +287,29 @@ left of it at exit: upstream function is tracked but not freed at exit, so a caller that has not switched to the tracked functions keeps its previous exit behavior. -On Linux, Android excepted, C `exit` destroyed the statics of llama.cpp under -the threads that were still inside it, and those crashed +On Linux with glibc, C `exit` destroyed the statics of llama.cpp under the +threads that were still inside it, and those crashed ([llamadart#949](https://github.com/leehack/llamadart/issues/949)). There: -- The llama.cpp libraries of the bundle register no static destructors +- No library of the bundle registers static destructors (`src/llama_dart_static_destructors.c`), so their statics stay valid until the process is gone. On Linux they are separate libraries, and no exit handler of `libllamadart` can be ordered before the destructor of a static that another library creates later. -- C `exit` runs the wait of teardown and nothing else. It waits for the calls - in flight as above, cancels a model load and ends a decode or an encode on - the CPU backend (status 2, unless the context has an abort callback of its - own). With no call in flight it returns at once. The exit handlers and - destructors of other libraries, such as a GPU driver or OpenBLAS, then run - with no call in flight. -- It frees nothing and blocks no thread. After it, a guarded call that begins - on another thread returns its failure value with `the process is exiting` - as the last error, and `llama_dart_exit_free` frees nothing, so a host whose - own exit handler joins a worker gets it back. -- The wait runs at the handler registered at the first creating call and - again at the first tracked object. An exit handler that another library - registers later runs before it. +- C `exit` does not run teardown. With a call in flight on another thread it + ends the process at once, as `_exit` does: with the exit status and the + standard streams flushed, and without the exit handlers and destructors + that would have run next, the host's among them. Those would run under the + call, and waiting for the call is not harmless: a Dart VM aborts when its + isolates run while `exit` takes its time. +- With no call in flight the exit goes on at once. Nothing is freed and no + thread is blocked. Afterwards a guarded call that begins on another thread + returns its failure value with `the process is exiting` as the last error, + and `llama_dart_exit_free` frees nothing, so a host whose own exit handler + joins a worker gets it back. +- The handler is registered at the first creating call and again at the first + tracked object. An exit handler that another library registers later runs + before it. `libllamadart.so` is linked with `-z nodelete`. [`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) has the measurements and what is not verified. diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 83355710..0298fd78 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -30,106 +30,139 @@ looks for the best backend. ### What changes -1. The llama.cpp libraries register no static destructors. +1. No library of the bundle registers static destructors. `src/llama_dart_static_destructors.c` defines a hidden `__cxa_atexit` that - registers nothing, and `CMakeLists.txt` adds it to every shared library and - backend module under `third_party/llama.cpp`, whatever backends the build - enables. The statics stay valid until the process is gone: also for a call - that teardown does not wait for, and for one that outlasts its wait. + registers nothing, and `CMakeLists.txt` adds it to libllamadart and to + every shared library and backend module under `third_party/llama.cpp`, + whatever backends the build enables. The statics stay valid until the + process is gone, also for a call that libllamadart does not count. Upstream sources are not patched. -2. C `exit()` runs the wait of exit teardown and nothing else. libllamadart - registers the handler at the first creating call - (`llama_dart_model_load_from_file`, `llama_dart_init_from_model`, - `llama_dart_mtmd_init_from_file`, the TTS, speculative, MTP and n-gram init - functions), so that an exit during the first load finds one, and again when - the first object is tracked. It waits up to 2 s - (`llama_dart_exit_set_wait_ms`) for the calls in flight and cancels a model - load. With no call in flight it returns at once: it does not let the - threads settle for 250 ms as `llama_dart_exit_teardown` does, because it - frees nothing, and because time spent inside `exit()` is not harmless (see - "Dart"). -3. The exit frees nothing. Apple frees the tracked objects because - ggml-metal aborts over a live buffer. Nothing on Linux does, the issue - found an exit with a model left loaded clean on CPU, Vulkan and CUDA, and a - free during `exit()` would run among the exit handlers of the GPU driver in - an order that nothing controls. `llama_dart_exit_teardown` called by a - native host still frees. -4. The exit blocks no thread. Apple blocks every thread that reaches +2. libllamadart registers an exit handler with `on_exit`, which gets the exit + status: at the first creating call (`llama_dart_model_load_from_file`, + `llama_dart_init_from_model`, `llama_dart_mtmd_init_from_file`, the TTS, + speculative, MTP and n-gram init functions), so that an exit during the + first load finds one, and again when the first object is tracked. +3. With a call in flight on another thread, the handler ends the process: + `fflush(NULL)` and `_exit(status)`. That is what `exit()` from `dart:io` + does on Linux. The handlers that would have run next are those of other + libraries, a GPU driver or OpenBLAS among them, and they would run under + the call. It does not wait for the call first. An earlier version of this + change did, and time inside `exit()` turned out not to be harmless: see + "Why the exit does not wait". +4. With no call in flight the handler returns at once and the exit goes on. + It frees nothing. Apple frees the tracked objects because ggml-metal + aborts over a live buffer. Nothing on Linux does, the issue found an exit + with a model left loaded clean on CPU, Vulkan and CUDA, and a free during + `exit()` would run among the exit handlers of the GPU driver in an order + that nothing controls. `llama_dart_exit_teardown` called by a native host + still waits and frees, as on every platform. +5. The exit blocks no thread. Apple blocks every thread that reaches libllamadart after teardown, because the objects it holds are gone. On Linux they are not, and a blocked thread hangs a host whose own exit - handler joins it. After the wait, on a thread other than the exiting one: + handler joins it. Once the exit has passed libllamadart, on a thread other + than the exiting one: - `llama_dart_exit_free` and the session free functions free nothing, and `llama_dart_exit_track` and `llama_dart_exit_untrack` return `false`; - a call in flight that begins returns the failure value of its function, with `the process is exiting` as `llama_dart_last_error`, and starts - nothing: the exit no longer waits for it; - - `llama_dart_exit_call_begin` counts nothing; - - the call that the exit waited for returns to its caller. -5. While teardown waits, and from then on after an exit, a decode or an - encode on the CPU backend ends with llama.cpp's status for an aborted - evaluation (2). `llama_dart_init_from_model` sets the context's abort - callback for that when the caller passes none, and the draft contexts of - the speculative and MTP state get it too. Without it a long decode outlasts - the wait and is still running when the exit reaches other libraries: with - the BLAS module, OpenBLAS's destructor then never returns (see - "Measurements"). llama.cpp logs three error lines for the ended decode. -6. libllamadart itself binds `__cxa_atexit` to the definition that Apple - uses, so a static of its own is destroyed only after the wait. + nothing; + - `llama_dart_exit_call_begin` counts nothing. +6. `libllamadart.so` is linked with `-z nodelete`: `on_exit` handlers are not + removed by `dlclose`, so the library must stay loaded. `tools/validate_linux_artifact.py`, which the release runs on every Linux archive, fails an archive in which a library built here imports -`__cxa_atexit`. +`__cxa_atexit`, or in which `libllamadart.so` can be unloaded. + +### Why the exit does not wait + +The first two versions of this change waited at exit for the call in flight, +as Apple does, and then let the exit go on. Two rows of the measurements got +worse than `v0.6.0-1` that way: + +- A Dart VM aborts when one of its isolates collects garbage while C `exit()` + is under way (`runtime/vm/handles_impl.h: 39: error: unreachable code`, + [llamadart#977](https://github.com/leehack/llamadart/issues/977)). A Dart + program with an isolate that decodes UTF-8 in a loop and an exit handler + that sleeps 300 ms, with no llama.cpp in the process, aborts 10 of 10. An + exit inside a decode of 1500 tokens with such an isolate aborted 17 of 30 + when the exit waited for the decode to end, against 10 of 30 before the + change. Waiting 20 ms and then ending the process: 17 of 30 as well. Ending + the process at once: 0 of 30. +- A decode on a GPU backend cannot be ended, as ggml-vulkan does not read the + abort callback. On lavapipe a decode of 1500 tokens outlasted the two + seconds, and the exit that then went on under it failed 2 of 50 (6 of 50 in + the audit) where it had been clean before, with the driver's own exit + handlers meeting a decode that was still running. + +Not waiting at all, and letting the exit go on at once, does not do either: +in the audit that brought the Dart row down to 2 of 30, but OpenBLAS's +destructor then hung under a decode 4 of 10, and the lavapipe decode with a +slow host failed 26 of 50, as it did before the change. + +Both are the exit going on, or taking its time, under a call in flight, and +ending the process is what removes that. So the handler does it for every +call in flight, also for one on the CPU backend that would have ended in a +millisecond: that keeps what an exit does from depending on how long a decode +happens to take. The cost is the same in every case and is listed under "What +it does not cover". ### Why not a gate in front of every destructor [`v060_1_wrapper_rebuild.md`](v060_1_wrapper_rebuild.md) recommended a hidden `__cxa_atexit` in every library that registers each destructor behind a gate -exported by `libggml-base.so`, which libllamadart points at teardown. The wait -without frees is taken from there. The gate is not: +exported by `libggml-base.so`, which libllamadart points at teardown. Not +freeing at exit is taken from there. The gate is not: - ggml unloads a backend module that it loaded only to score it, or that failed to initialize. `dlclose` runs the destructors that the module - registered, and each would run the gate, which is teardown, in the middle of - a run. -- A destructor behind a gate still runs once the wait is over. A call that - outlasts the wait would crash as before, which was 10 of 10 for a long - decode with a slow host below. + registered, and each would run the gate in the middle of a run. +- A gate waits, which is what "Why the exit does not wait" rules out. - It would add an exported symbol to an upstream library. ### What it does not cover -- A Dart process in which another isolate runs Dart code while the exit - waits for a call in flight. The Dart VM aborts - (`runtime/vm/handles_impl.h: 39: error: unreachable code`, - [llamadart#977](https://github.com/leehack/llamadart/issues/977)) when an - isolate collects garbage while C `exit()` is taking its time, whatever - takes it: a 300 ms exit handler with no llama.cpp in the process does it - 10 of 10. The wait is what fixes the crash, so it stays, and it is as short - as the call: see "Dart" for the rates. -- A call in flight that outlasts the wait and cannot be ended: a decode on a - GPU backend, which does not read the abort callback, an image or audio - evaluation, or a context with an abort callback of its own. The exit then - goes on with the call running, two seconds later than it would have, and - what the call uses of other libraries may be gone. The lavapipe decode of - 1500 tokens in "Measurements" is such a call. -- An exit handler that another library registers after the two handlers above - runs before the wait, under the calls in flight. A GPU driver that - registers one late, during a decode for example, is in that position. - Statics that llama.cpp creates late no longer matter. -- A call that is not a call in flight is not waited for, as on Apple. Its - statics stay valid on Linux; what it uses of other libraries may not. +- An exit with a call in flight skips what the exit would have run after + libllamadart's handler: the exit handlers that were registered before it, + the host's among them, the static destructors of the host and of other + libraries, and the flush of anything but the standard C streams. A host + that needs those has to stop its calls before it exits. `std::cout` is + flushed only as far as it is synchronized with `stdout`. +- An exit handler that another library registers after the two of + libllamadart runs before them, under the calls in flight. A GPU driver that + registers one late, during a decode for example, is in that position, and + so is a slow one in a Dart process. +- A call that is not a call in flight is not counted, as on Apple: the exit + goes on under it. Its statics stay valid on Linux; what it uses of other + libraries may not. +- An exit that falls between two guarded calls of a worker finds none in + flight and goes on. The worker's next call is then refused: a native host + gets the failure value (`INT32_MIN`, -1, `NULL` or `false`) with `the + process is exiting`, where its thread used to crash or, in the first + versions of this change, to block. +- `llama_dart_exit_teardown` still blocks the threads that reach libllamadart + after it, on Linux as elsewhere, because it frees what they hold. A host + that calls it and then joins such a thread in an exit handler hangs, as + before this change. +- A Dart process in which an isolate runs Dart code during an exit that goes + on, that is one with no call in flight, still aborts in the Dart VM at the + rate it did before the change (see "Dart"). The handler of libllamadart + adds no time to such an exit. - `quick_exit` and `_exit` run no handler, as before. Neither destroys statics. - A child of `fork` that calls `exit()` runs the handler with the registry it - copied: it waits out the wait time for calls that are not its own. -- An exit handler that code inside a llama.cpp library registers with - `atexit` binds to the same definition and is dropped. No backend built here - registers one; a library such as the CUDA runtime, which the modules load - as a library of its own, is not affected. + copied: with a call in flight in the parent at the time of the fork, the + child ends as with `_exit`. +- `dlclose` no longer unloads `libllamadart.so` or the libraries it depends + on. +- An exit handler that code inside a library of the bundle registers with + `atexit` binds to the same definition as the static destructors and is + dropped. No backend built here registers one; a library such as the CUDA + runtime, which the modules load as a library of its own, is not affected. - The standard streams of a host built against libstdc++ older than GCC 13. There `` gives every translation unit a static `ios_base::Init`, and `std::cout` is flushed when the last of them is destroyed. One inside a - llama.cpp library is now never destroyed, so a host that turned off + library of the bundle is now never destroyed, so a host that turned off `sync_with_stdio` loses what `std::cout` still buffers at exit (seen in the audit with GCC 11.4 and a test library). The release builds its Linux libraries with GCC 13, where the stream initializer lives in libstdc++, @@ -145,10 +178,9 @@ without frees is taken from there. The gate is not: ### Other platforms -- musl: not supported and not run. No bundle is built for it. The audit found - that musl's `dlsym(RTLD_NEXT, "__cxa_atexit")` returns `NULL` in a library - opened with `dlopen`, so libllamadart's own definition would register - nothing there. +- musl: not supported and not run. No bundle is built for it. `on_exit` is a + glibc function, so the handler is compiled only where `__GLIBC__` is + defined; a musl build would keep its statics and do nothing at exit. - Android: left as it was, by `!defined(__ANDROID__)` in the two sources and `CMAKE_SYSTEM_NAME STREQUAL "Linux"` in CMake. bionic orders exit handlers the same way, but the issue has no Android measurement and nothing here ran @@ -186,104 +218,112 @@ than 0, a failed `GGML_ASSERT`, or no exit within 120 s. | --- | --- | --- | --- | --- | | while generating (decode and sample in a loop) | CPU | fast | 7 | 0 | | | CPU | slow | 10 | 0 | +| | CPU, BLAS | fast | 10 | 0 | | | CPU, BLAS | slow | 10 | 0 | -| | Vulkan | fast | 5 | 0 | +| | Vulkan | fast | 4 | 0 | | | Vulkan | slow | 10 | 0 | | inside one decode of 1500 tokens | CPU | fast | 1 | 0 | | | CPU | slow | 10 | 0 | +| | CPU, BLAS | fast | 6 | 0 | | | CPU, BLAS | slow | 10 | 0 | -| | Vulkan | fast | 0 of 50 | 2 of 50 | -| | Vulkan | slow | 24 of 50 | 2 of 50 | -| 100 ms and 400 ms into the first load | CPU | slow | 9, 6 | 0, 0 | +| | Vulkan | fast | 0 of 50 | 0 of 50 | +| | Vulkan | slow | 16 of 50 | 0 of 50 | +| 100 ms and 400 ms into the first load | CPU | slow | 8, 8 | 0, 0 | | 200 ms and 800 ms into the first load | CPU | fast | 0, 0 | 0, 0 | | 5 ms and 60 ms into the first load | Vulkan | fast | 0, 0 | 0, 0 | -| | Vulkan | slow | 10, 10 | 0, 0 | +| | Vulkan | slow | 10, 9 | 0, 0 | | first load, once tensors are loading | CPU, Vulkan | fast, slow | 0 | 0 | -| halfway through a second load | CPU | slow | 1 | 0 | +| halfway through a second load | CPU | slow | 5 | 0 | | | CPU, Vulkan | fast | 0 | 0 | -| `return` from `main` while generating | CPU | fast | 8 | 0 | -| | Vulkan | fast | 3 | 0 | +| `return` from `main` while generating | CPU | fast | 5 | 0 | +| | CPU | slow | 10 | 0 | +| | Vulkan | fast | 7 | 0 | +| | Vulkan | slow | 10 | 0 | | model idle; everything freed; `return` from `main` with a model idle | CPU, BLAS, Vulkan | fast, slow | 0 | 0 | +| a host handler that joins an idle worker, which frees its model | CPU | fast | 0 | 0 | +| a host handler that joins a worker that is generating | CPU | fast | 10 | 0 | -Every failed run ended in a signal: `SIGSEGV`, and on lavapipe before the -change also `SIGABRT` (`double free or corruption`). The scenarios that were -clean before are clean after, with the model left loaded and not freed. - -One row is worse than before. The decode of 1500 tokens on lavapipe cannot be -ended: ggml-vulkan does not read the abort callback. It outlasts the two -seconds, and the exit then goes on under it. With a fast host that fails 2 of -50 (6 of 50 in the audit, with a backtrace in the LLVM compiler of lavapipe -under a thread that waits in `ggml_vk_flash_attn`), where it was clean 50 of -50 before, also when the exit came 2.3 s into the decode. Before, the -destructor of ggml-vulkan's device list destroyed the device at once; now the -device outlives the exit and the driver's own exit handlers meet a decode -that is still running. With a slow host the same row goes from 24 of 50 to 2 -of 50. Whether a GPU driver behaves like lavapipe here is part of what is not -verified. - -Two measurements on the way decided parts of the design: - -- Without the abort callback, the 1500-token decode with the BLAS module - hung in OpenBLAS's destructor (`gotoblas_quit`, `blas_thread_shutdown_`) in - 6 of 10 exits and was killed after 120 s; with the callback, 0 of 10. - Without the BLAS module the same exit was clean 10 of 10 either way: the - decode outlasted the wait and ran on, with its statics intact, until the - process was gone. -- A build that also freed the tracked objects during `exit()` was clean in - the 16 lavapipe scenarios it ran (10 of 10 each). That shows nothing about - the NVIDIA driver, which is why the frees stay out. - -A host whose own exit handler stops a worker and joins it, with the worker -freeing its context and model through `llama_dart_exit_free`: clean 5 of 5 -before and after. The first version of this change blocked that worker and -hung 5 of 5. +Every failed run of `v0.6.0-1` ended in a signal: `SIGSEGV`, and on lavapipe +also `SIGABRT` (`double free or corruption`). No row of this rebuild has a +failed run, and none is worse than before. In the last row the host's handler +does not run: the process ends at libllamadart's handler, with the exit +status. In the row above it the handler runs and joins the worker, before and +after. -### Dart +Other shapes of host, from the probe of the audit, CPU with a fast host +unless it says otherwise, failed runs of 10: + +| Exit | `v0.6.0-1` | This rebuild | +| --- | --- | --- | +| from a worker thread while the main thread generates | 9 | 0 | +| from inside an evaluation callback; from inside a load progress callback | 10, 10 | 0, 0 | +| while two models generate | 10 | 0 | +| while a thread generates with the upstream `llama_decode` on a tracked context | 5 | 0 | +| while a thread generates on a model and context from the upstream functions | 8 | 0 | +| while a thread tokenizes in a loop | 2 | 0 | +| inside a long decode on a context with an abort callback of its own, BLAS, fast and slow host | 8, 10 | 0, 0 | +| after `llama_dart_exit_teardown`; after `dlclose` of libllamadart; `quick_exit`; `_exit` | 0 | 0 | +| ten load and free cycles, then right after a generation step | 9 | 3 | + +The three failed runs of the last row are not crashes. The exit fell between +two guarded calls of the worker, so it went on, the worker's next decode was +refused (`INT32_MIN`, `the process is exiting`), and that probe ends the +process with a code of its own when a decode fails. A host whose worker +treats a failed call as fatal sees that during an exit; before, the same row +crashed 9 of 10. + +The two rows that earlier versions of this change made worse are the long +decode on lavapipe with a fast host (0 of 50 before, 2 of 50 when the exit +waited two seconds and went on, 0 of 50 now) and the Dart row of "Why the +exit does not wait". -The Dart VM aborts when one of its isolates collects garbage while C `exit()` -is under way -([llamadart#977](https://github.com/leehack/llamadart/issues/977)). A Dart -program with one isolate that decodes UTF-8 in a loop and an exit handler -that sleeps 300 ms, with no llama.cpp in the process, aborts 10 of 10. So -whatever the handler of libllamadart takes, it takes at that price, and it -takes time only while a guarded call is in flight. +### Dart Dart 3.13.1, CPU. `tests/manual/dart_exit_probe.dart` calls a guarded decode and sample per step through a small C shim, on `stories15M`; llamadart rows are its own `test/fixtures/llama_cpp_exit_probe.dart` and a variant with an isolate that wakes on a 5 ms timer, on llamadart `9275de8` with the bundle under test and Qwen3.5 0.8B Q4_0. The main isolate calls C `exit()` through -FFI. Failed runs of 10, or of 30 where it says so; "First version" is -`c9bc619`, which waited 250 ms at every exit and blocked the threads that -reached libllamadart afterwards. - -| Exit | Other isolate | `v0.6.0-1` | First version | This rebuild | -| --- | --- | --- | --- | --- | -| llamadart `quit-generating` | none | 10 | 0 | 0 | -| llamadart `quit-loaded`, `quit-loading`, `return-loaded`, `kill-loading` | none | 0 | 0 | 0 | -| llamadart, right after a generation finished | 5 ms timer | 0 | 10 | 0 | -| llamadart, 1 s after a generation finished | 5 ms timer | 0 | 0 | 0 | -| llamadart, while generating | 5 ms timer | 6 | 10 | 0 | -| worker isolate generating | none | 13 of 30 | 0 | 0 of 30 | -| worker isolate generating | decoding in a loop | 13 of 30 | 10 | 3 of 30 | -| worker isolate inside one decode of 1500 tokens | decoding in a loop | 10 of 30 | 10 | 17 of 30 | -| right after a guarded call returned | decoding in a loop | 7 of 30 | 10 | 10 of 30 | -| worker isolate idle after a generation | 5 ms timer | 0 | 9 | 0 | -| worker isolate idle after a generation | decoding in a loop | 4 of 30 | 10 | 3 of 30 | -| model idle for 400 ms | decoding in a loop | 8 of 30 | 0 | 6 of 30 | -| `dart:io` `exit()` while generating; `main` returns while generating | none | 0 | 0 | 0 | - -The failures of `v0.6.0-1` while generating are the `SIGSEGV` of the issue. -Those of this rebuild are all the abort of the Dart VM. An isolate that -decodes in a loop makes the VM abort in about a fifth of the exits with a -model loaded even where libllamadart has no handler at all (19 of 90 in the -three rows of `v0.6.0-1` with no call in flight), so the rows with one -compare rates: this rebuild is at the rate of `v0.6.0-1` where no call is in -flight (19 of 90), and below it while generating. It is above it in one row, -17 of 30 against 10 of 30: an exit inside a long decode while another isolate -keeps collecting garbage. The exit waits there until the decode has ended, -which takes as long as the tensor that is being computed, and the VM aborts -in that time. +FFI. "Looping" is a second isolate that decodes UTF-8 in a loop. Failed runs +of 30 unless it says otherwise. + +| Exit | Other isolate | `v0.6.0-1` | This rebuild | +| --- | --- | --- | --- | +| llamadart `quit-generating` | none | 18 | 0 | +| llamadart `quit-loaded`, `quit-loading`, `return-loaded`, `kill-loading` | none | 0 | 0 | +| llamadart, right after a generation finished | 5 ms timer | 0 | 0 | +| llamadart, 1 s after a generation finished | 5 ms timer | 0 | 0 | +| llamadart, while generating | 5 ms timer | 25 | 0 | +| llamadart `throw-generating`, `throw-loading` (exit code 255 expected) | none | 255, 10 of 10 | 255, 10 of 10 | +| worker isolate generating | none | 15 | 0 | +| worker isolate generating | looping | 12 | 0 | +| worker isolate generating, slow host | looping | 30 | 1 | +| worker isolate inside one decode of 1500 tokens | looping | 15 of 50 | 0 of 50 | +| worker isolate inside one decode of 1500 tokens, slow host | looping | 50 of 50 | 0 of 50 | +| worker isolate idle after a generation | none | 0 | 0 | +| worker isolate idle after a generation | 5 ms timer | 0 | 0 | +| worker isolate idle after a generation | looping | 12 of 100 | 11 of 100 | +| right after a guarded call returned | looping | 36 of 100 | 24 of 100 | +| model idle for 400 ms | looping | 23 of 100 | 20 of 100 | +| `dart:io` `exit()` while generating; `main` returns while generating | none | 0 | 0 | +| worker generating; a 300 ms exit handler registered right before the exit | none | 25 | 19 | +| worker inside the long decode; the same late handler | looping | 30 | 30 | + +The failures of `v0.6.0-1` with a call in flight are the `SIGSEGV` of the +issue, or the abort of the Dart VM. All the failures of this rebuild are the +abort of the Dart VM, in exits that go on: + +- The three rows with a looping isolate and no call in flight. The VM aborts + there whether libllamadart has a handler or not, and at a rate that moves + with the load of the machine: the 100 runs of a row were taken in turns of + ten for each build, an earlier sample of 30 gave 0 to 4 for `v0.6.0-1` and 0 + to 1 for this rebuild, and the audit saw 1 of 90 and 0 of 90. The handler + returns at once in these exits and adds nothing to them. +- The one of 30 with a slow host: the exit fell between two guarded calls of + the worker, found none in flight, and went on into the 300 ms handler. +- The last two rows, where a handler that was registered after libllamadart's + runs before it and takes its 300 ms first. libllamadart cannot run before a + handler that is registered later. ## Checks @@ -311,22 +351,27 @@ without `LD_LIBRARY_PATH`. In the container above: with leak detection off, with no report. With it on, `barrier-grammar` reports 80 bytes that llama.cpp leaks when a lazy grammar is rejected (`llama-sampler.cpp:2777`), as before this change, and nothing else does. -- The same test source against the libraries of `v0.6.0-1`: `model-decode`, - `model-late-load` and `model-decode-outlasts-wait` end in `SIGSEGV`, and - `model-load` and `model-free-in-flight` report that the exit did not wait, - 5 of 5 each. +- The same test source against the libraries of `v0.6.0-1`, five runs each: + `model-decode`, `model-unguarded-decode` and `model-exit-join-generating` + end in `SIGSEGV` every time and `model-late-load` four times; + `exit-in-flight`, `exit-status`, `model-load` and `model-free-in-flight` + fail because the exit went on under a call in flight; `exit-late-calls` and + `model-exit-join-idle` fail because a free after the exit still freed. - Each part removed in turn fails a scenario: | Removed | Fails | | --- | --- | - | the static destructor object | `model-decode-outlasts-wait` (`SIGSEGV`); `validate_linux_artifact.py` names seven libraries | + | the static destructor object | `model-unguarded-decode` (`SIGSEGV`); `validate_linux_artifact.py` names the libraries | + | ending the process for a call in flight | `exit-in-flight`, `exit-status`, `model-load`, `model-free-in-flight` | | the handler at the first creating call | `model-load` | - | the handler at the first tracked object | `exit-in-flight` | - | the exit that frees nothing | `exit` | - | the abort callback | `model-decode-ended` | - | the return before the 250 ms | `model-exit-idle` (260 ms against a bound of 100 ms) | - | threads not blocked after the exit | `exit-late-calls`, `model-exit-join-idle`, `model-exit-join-generating` | + | the handler at the first tracked object | `exit-in-flight`, `exit-status`, `exit-late-calls` | + | the exit status | `exit-status` | + | the flush of the standard streams | `exit-status` | + | returning at once with no call in flight (250 ms added) | `model-exit-idle` | + | threads not blocked after the exit | `exit-late-calls`, `model-exit-join-idle` | | the refusal of a late call | `exit-late-calls` | + | the exemption of the exiting thread | `exit-late-calls` | + | `-z nodelete` | `validate_linux_artifact.py` | `validate_exports.py --forbid-import` now reads ELF imports with `--format readelf`. With `--format nm` it reads names as Mach-O ones, without @@ -340,7 +385,7 @@ a build with `GGML_VULKAN=ON`, Mesa's `mesa-vulkan-drivers` and macOS arm64 (Apple M4 Max), `macos-arm64-full` preset: `libllamadart.dylib` built from this tree and from `v0.6.0-1` at the same path have the same SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). -186 Python tests pass (183 before), and the 20 of the Linux artifact tools +186 Python tests pass (183 before), and the 22 of the Linux artifact tools (18 before). ## Not verified @@ -352,10 +397,15 @@ SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). `quit-loaded`, `quit-generating`, `quit-loading`, `return-loaded` and dispose-then-quit scenarios of llamadart's `test/fixtures/llama_cpp_exit_probe.dart` on the `v0.6.0-2` bundle, with the - CPU, Vulkan and CUDA backends, at least 10 runs each, and an exit inside a - prompt decode that takes longer than two seconds on each GPU backend, 50 - runs, against `v0.6.0-1`. + CPU, Vulkan and CUDA backends, at least 10 runs each, against `v0.6.0-1`. + The scenarios with a call in flight end in `_exit` on every backend, which + the container shows; what a GPU host adds is the exits that go on: a model + left loaded, and a handler of the driver that was registered after + libllamadart's. - Linux x64 by hand. The measurements are arm64; `validate_wrapper.yml` runs the scenarios on x64. - HIP and musl builds, Android and Windows. -- Flutter. The Dart rows are the standalone VM. +- Flutter. The Dart rows are the standalone VM, and whether a Flutter Linux + window close reaches C `exit()` with a worker inside a guarded call is not + known. If it does, the exit ends there and the engine's own exit handlers + do not run. diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 4e23e9a0..2a9ebe69 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -576,12 +576,19 @@ int test_exit_in_flight() { } char kLateObject[] = "late-object"; +llama_dart_ngram *g_created_at_exit = nullptr; // What a thread other than the exiting one gets from libllamadart once the // exit has waited, on Linux: nothing blocks, a free frees nothing, and a call // in flight is refused before it starts. void make_late_calls() { g_exit_expected.store(true); + // The exiting thread is exempt: a host's later exit handlers may still use + // libllamadart. What it creates is not tracked, and stays allocated. + g_created_at_exit = llama_dart_ngram_simple_init(4, 8); + assert(g_created_at_exit != nullptr); + assert(llama_dart_last_error() == nullptr); + assert(llama_dart_exit_tracked_count() == 1); std::thread([] { llama_dart_exit_free(kLateObject); assert(recorded().empty()); @@ -598,6 +605,7 @@ void make_late_calls() { llama_dart_exit_call_begin(); llama_dart_exit_call_end(); assert(!llama_dart_exit_untrack(kLateObject)); + assert(!llama_dart_exit_untrack(g_created_at_exit)); assert(llama_dart_exit_tracked_count() == 1); g_call_ended.store(true); }).detach(); diff --git a/tests/manual/dart_exit_probe.dart b/tests/manual/dart_exit_probe.dart index 3bb762fb..3d649301 100644 --- a/tests/manual/dart_exit_probe.dart +++ b/tests/manual/dart_exit_probe.dart @@ -11,7 +11,9 @@ // // holds libllamadart.so and the backend modules. A run is clean // when it prints EXIT_PROBE_REACHED and exits with code 0. Append -slow-exit -// to a scenario for a host whose own exit handler takes 300 ms. +// to a scenario for a host whose own exit handler takes 300 ms, or +// -late-slow-exit to a generating one for a handler that was registered after +// the one of libllamadart. import 'dart:async'; import 'dart:convert'; import 'dart:ffi'; @@ -132,11 +134,17 @@ Future main(List args) async { // A scenario with -slow-exit appended has an exit handler that takes 300 ms. // It is registered before libllamadart is opened, and so runs after the // handler of libllamadart. + // With -late-slow-exit the handler is registered right before the exit + // instead, and so runs before the handler of libllamadart. const slowExit = '-slow-exit'; - final scenario = requested.endsWith(slowExit) + const lateSlowExit = '-late-slow-exit'; + final late = requested.endsWith(lateSlowExit); + final scenario = late + ? requested.substring(0, requested.length - lateSlowExit.length) + : requested.endsWith(slowExit) ? requested.substring(0, requested.length - slowExit.length) : requested; - if (scenario != requested) sleepingAtexit(300); + if (!late && scenario != requested) sleepingAtexit(300); switch (scenario) { case 'control-spin': // no native library at all @@ -173,6 +181,7 @@ Future main(List args) async { await ready.first; if (scenario == 'generating-spin') await spin(); } + if (late) sleepingAtexit(300); _cExit(); case 'loaded-worker-idle': // llamadart's quit-loaded shape case 'loaded-worker-idle-timer': // the same with a periodic timer in main's group From 34aa37a3c98986e373dcf31bfeef80404bddcf9a Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 20:26:12 -0400 Subject: [PATCH 7/8] fix: preserve normal Linux host exit after worker shutdown --- CMakeLists.txt | 15 +- README.md | 40 +- docs/v060_2_wrapper_rebuild.md | 492 ++++----------------- src/llama_dart_wrapper.cpp | 93 +--- src/llama_dart_wrapper.h | 43 +- tests/exit_teardown_test.cpp | 118 ++--- tests/manual/dart_exit_probe_shim.cpp | 34 +- tests/manual/dart_host_shutdown_probe.dart | 163 +++++++ tests/validate_linux_artifact_test.py | 2 +- tools/validate_linux_artifact.py | 6 +- 10 files changed, 382 insertions(+), 624 deletions(-) create mode 100644 tests/manual/dart_host_shutdown_probe.dart diff --git a/CMakeLists.txt b/CMakeLists.txt index 3f2ded07..eafa2959 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -219,8 +219,8 @@ add_library(llamadart_lib SHARED if (CMAKE_SYSTEM_NAME STREQUAL "Linux") target_sources(llamadart_lib PRIVATE $) - # libllamadart registers an exit handler with on_exit, which a dlclose - # does not remove, so the library must not be unloaded. + # Held objects and native finalizer callbacks may outlive a dlclose. + # Retain the wrapper together with the owned statics. target_link_options(llamadart_lib PRIVATE -Wl,-z,nodelete) endif() # The Vulkan device facts need only the Vulkan types: the loader is opened at @@ -357,8 +357,8 @@ if (LLAMADART_BUILD_TESTS) "${exit_teardown_vocabulary_model}") set_tests_properties(llamadart_exit_teardown_barrier-grammar PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_vocabulary_model) - # Teardown runs at exit on Apple and Linux, so the scenarios that load a - # model run there. They use a model the test writes itself unless one is + # Apple automatic teardown and Linux retained statics are exercised + # with CPU models. They use a model the test writes itself unless one is # given. On Linux the backends are modules, of which the test loads the # CPU one. set(LLAMADART_EXIT_TEARDOWN_TEST_MODEL "" CACHE FILEPATH @@ -393,14 +393,15 @@ if (LLAMADART_BUILD_TESTS) set_tests_properties(llamadart_exit_teardown_${scenario} PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_model) endforeach() - # What only Linux does: the exit ends the process for a call in - # flight, the statics of llama.cpp outlive an exit, and an exit with - # no call in flight takes no time and blocks no thread. + # Linux preserves host callbacks and libc flushing. Live-worker raw + # exit cases are diagnostic CPU controls, not the host contract. if (CMAKE_SYSTEM_NAME STREQUAL "Linux") foreach(scenario exit-late-calls exit-status) add_test(NAME llamadart_exit_teardown_${scenario} COMMAND llamadart_exit_teardown_test ${scenario}) endforeach() + set_tests_properties(llamadart_exit_teardown_exit-status + PROPERTIES TIMEOUT 10) foreach(scenario model-unguarded-decode model-exit-idle model-exit-join-idle model-exit-join-generating) add_test(NAME llamadart_exit_teardown_${scenario} diff --git a/README.md b/README.md index f4e3faca..5673e10e 100644 --- a/README.md +++ b/README.md @@ -287,32 +287,20 @@ left of it at exit: upstream function is tracked but not freed at exit, so a caller that has not switched to the tracked functions keeps its previous exit behavior. -On Linux with glibc, C `exit` destroyed the statics of llama.cpp under the -threads that were still inside it, and those crashed -([llamadart#949](https://github.com/leehack/llamadart/issues/949)). There: - -- No library of the bundle registers static destructors - (`src/llama_dart_static_destructors.c`), so their statics stay valid until - the process is gone. On Linux they are separate libraries, and no exit - handler of `libllamadart` can be ordered before the destructor of a static - that another library creates later. -- C `exit` does not run teardown. With a call in flight on another thread it - ends the process at once, as `_exit` does: with the exit status and the - standard streams flushed, and without the exit handlers and destructors - that would have run next, the host's among them. Those would run under the - call, and waiting for the call is not harmless: a Dart VM aborts when its - isolates run while `exit` takes its time. -- With no call in flight the exit goes on at once. Nothing is freed and no - thread is blocked. Afterwards a guarded call that begins on another thread - returns its failure value with `the process is exiting` as the last error, - and `llama_dart_exit_free` frees nothing, so a host whose own exit handler - joins a worker gets it back. -- The handler is registered at the first creating call and again at the first - tracked object. An exit handler that another library registers later runs - before it. `libllamadart.so` is linked with `-z nodelete`. - -[`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) has the -measurements and what is not verified. +On Linux, Android excepted, owned bundle statics are retained until the +process is gone (`src/llama_dart_static_destructors.c`). C `exit` runs no +wrapper teardown or forced termination: earlier host callbacks, dependency +destructors and normal libc stream flushing proceed. `-z nodelete` keeps +held native objects and finalizer callbacks valid across `dlclose`. + +Before C exit, the host must stop and join workers and shut down its Dart +isolates or Flutter engine. Await their exit and native finalizers; a kill +request alone is insufficient. Direct C exit with live Dart isolates can +abort the VM even without llama.cpp ([#977](https://github.com/leehack/llamadart/issues/977)). +Owned static retention does not protect GPU-driver or BLAS destructors. + +[`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) describes +the host protocol, preservation regression tests and remaining qualification. On other platforms nothing runs at exit. `llama_dart_exit_teardown` runs teardown on request on every platform, frees included, and must be followed diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 0298fd78..12269501 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -1,411 +1,89 @@ -# v0.6.0-2 wrapper rebuild - -Wrapper-only changes on llama.cpp `v0.6.0` -(`d81235049384534c167caea52b85a694f6103d14`) for the native rebuild tag -`v0.6.0-2`. The exported header gains no declaration and loses none: the 85 -symbols of `v0.6.0-1` are the 85 of this rebuild. Only Linux builds change; -the macOS library built from this tree is byte-for-byte the one built from -`v0.6.0-1` (see "Checks"). - -## Exit on Linux - -Issue: [llamadart#949](https://github.com/leehack/llamadart/issues/949). A C -`exit()` while another thread is inside llama.cpp killed the process on -Linux. `exit()` destroys C++ statics that the thread still reads: - -| Frame of the crash | Static | Created | -| --- | --- | --- | -| `ggml_cpu_extra_compute_forward`, `ggml_cpu_extra_work_size` | the vector in `ggml_backend_cpu_get_extra_buffer_types` (`libggml-cpu.so`) | on first use, before the first decode | -| `ggml_backend_dev_type` under `llama_model_load_from_file` | a device of ggml's registry; not traced to one static | before the load | -| `unicode_utf8_to_byte` under `llama_vocab::impl::load` | the map in `unicode_utf8_to_byte` (`libllama.so`) | in the middle of the first model load | - -The third one is why registering an exit handler is not enough. `exit()` -runs one list of handlers and static destructors in reverse order of -registration, so no handler that libllamadart registers before a load runs -before the destructor of a static that the load creates. On Apple platforms -llama.cpp is part of `libllamadart.dylib`, and a definition of `__cxa_atexit` -inside that image orders teardown before all of them. On Linux they are -separate libraries, some of them modules that ggml loads and unloads while it -looks for the best backend. - -### What changes - -1. No library of the bundle registers static destructors. - `src/llama_dart_static_destructors.c` defines a hidden `__cxa_atexit` that - registers nothing, and `CMakeLists.txt` adds it to libllamadart and to - every shared library and backend module under `third_party/llama.cpp`, - whatever backends the build enables. The statics stay valid until the - process is gone, also for a call that libllamadart does not count. - Upstream sources are not patched. -2. libllamadart registers an exit handler with `on_exit`, which gets the exit - status: at the first creating call (`llama_dart_model_load_from_file`, - `llama_dart_init_from_model`, `llama_dart_mtmd_init_from_file`, the TTS, - speculative, MTP and n-gram init functions), so that an exit during the - first load finds one, and again when the first object is tracked. -3. With a call in flight on another thread, the handler ends the process: - `fflush(NULL)` and `_exit(status)`. That is what `exit()` from `dart:io` - does on Linux. The handlers that would have run next are those of other - libraries, a GPU driver or OpenBLAS among them, and they would run under - the call. It does not wait for the call first. An earlier version of this - change did, and time inside `exit()` turned out not to be harmless: see - "Why the exit does not wait". -4. With no call in flight the handler returns at once and the exit goes on. - It frees nothing. Apple frees the tracked objects because ggml-metal - aborts over a live buffer. Nothing on Linux does, the issue found an exit - with a model left loaded clean on CPU, Vulkan and CUDA, and a free during - `exit()` would run among the exit handlers of the GPU driver in an order - that nothing controls. `llama_dart_exit_teardown` called by a native host - still waits and frees, as on every platform. -5. The exit blocks no thread. Apple blocks every thread that reaches - libllamadart after teardown, because the objects it holds are gone. On - Linux they are not, and a blocked thread hangs a host whose own exit - handler joins it. Once the exit has passed libllamadart, on a thread other - than the exiting one: - - `llama_dart_exit_free` and the session free functions free nothing, and - `llama_dart_exit_track` and `llama_dart_exit_untrack` return `false`; - - a call in flight that begins returns the failure value of its function, - with `the process is exiting` as `llama_dart_last_error`, and starts - nothing; - - `llama_dart_exit_call_begin` counts nothing. -6. `libllamadart.so` is linked with `-z nodelete`: `on_exit` handlers are not - removed by `dlclose`, so the library must stay loaded. - -`tools/validate_linux_artifact.py`, which the release runs on every Linux -archive, fails an archive in which a library built here imports -`__cxa_atexit`, or in which `libllamadart.so` can be unloaded. - -### Why the exit does not wait - -The first two versions of this change waited at exit for the call in flight, -as Apple does, and then let the exit go on. Two rows of the measurements got -worse than `v0.6.0-1` that way: - -- A Dart VM aborts when one of its isolates collects garbage while C `exit()` - is under way (`runtime/vm/handles_impl.h: 39: error: unreachable code`, - [llamadart#977](https://github.com/leehack/llamadart/issues/977)). A Dart - program with an isolate that decodes UTF-8 in a loop and an exit handler - that sleeps 300 ms, with no llama.cpp in the process, aborts 10 of 10. An - exit inside a decode of 1500 tokens with such an isolate aborted 17 of 30 - when the exit waited for the decode to end, against 10 of 30 before the - change. Waiting 20 ms and then ending the process: 17 of 30 as well. Ending - the process at once: 0 of 30. -- A decode on a GPU backend cannot be ended, as ggml-vulkan does not read the - abort callback. On lavapipe a decode of 1500 tokens outlasted the two - seconds, and the exit that then went on under it failed 2 of 50 (6 of 50 in - the audit) where it had been clean before, with the driver's own exit - handlers meeting a decode that was still running. - -Not waiting at all, and letting the exit go on at once, does not do either: -in the audit that brought the Dart row down to 2 of 30, but OpenBLAS's -destructor then hung under a decode 4 of 10, and the lavapipe decode with a -slow host failed 26 of 50, as it did before the change. - -Both are the exit going on, or taking its time, under a call in flight, and -ending the process is what removes that. So the handler does it for every -call in flight, also for one on the CPU backend that would have ended in a -millisecond: that keeps what an exit does from depending on how long a decode -happens to take. The cost is the same in every case and is listed under "What -it does not cover". - -### Why not a gate in front of every destructor - -[`v060_1_wrapper_rebuild.md`](v060_1_wrapper_rebuild.md) recommended a hidden -`__cxa_atexit` in every library that registers each destructor behind a gate -exported by `libggml-base.so`, which libllamadart points at teardown. Not -freeing at exit is taken from there. The gate is not: - -- ggml unloads a backend module that it loaded only to score it, or that - failed to initialize. `dlclose` runs the destructors that the module - registered, and each would run the gate in the middle of a run. -- A gate waits, which is what "Why the exit does not wait" rules out. -- It would add an exported symbol to an upstream library. - -### What it does not cover - -- An exit with a call in flight skips what the exit would have run after - libllamadart's handler: the exit handlers that were registered before it, - the host's among them, the static destructors of the host and of other - libraries, and the flush of anything but the standard C streams. A host - that needs those has to stop its calls before it exits. `std::cout` is - flushed only as far as it is synchronized with `stdout`. -- An exit handler that another library registers after the two of - libllamadart runs before them, under the calls in flight. A GPU driver that - registers one late, during a decode for example, is in that position, and - so is a slow one in a Dart process. -- A call that is not a call in flight is not counted, as on Apple: the exit - goes on under it. Its statics stay valid on Linux; what it uses of other - libraries may not. -- An exit that falls between two guarded calls of a worker finds none in - flight and goes on. The worker's next call is then refused: a native host - gets the failure value (`INT32_MIN`, -1, `NULL` or `false`) with `the - process is exiting`, where its thread used to crash or, in the first - versions of this change, to block. -- `llama_dart_exit_teardown` still blocks the threads that reach libllamadart - after it, on Linux as elsewhere, because it frees what they hold. A host - that calls it and then joins such a thread in an exit handler hangs, as - before this change. -- A Dart process in which an isolate runs Dart code during an exit that goes - on, that is one with no call in flight, still aborts in the Dart VM at the - rate it did before the change (see "Dart"). The handler of libllamadart - adds no time to such an exit. -- `quick_exit` and `_exit` run no handler, as before. Neither destroys - statics. -- A child of `fork` that calls `exit()` runs the handler with the registry it - copied: with a call in flight in the parent at the time of the fork, the - child ends as with `_exit`. -- `dlclose` no longer unloads `libllamadart.so` or the libraries it depends - on. -- An exit handler that code inside a library of the bundle registers with - `atexit` binds to the same definition as the static destructors and is - dropped. No backend built here registers one; a library such as the CUDA - runtime, which the modules load as a library of its own, is not affected. -- The standard streams of a host built against libstdc++ older than GCC 13. - There `` gives every translation unit a static `ios_base::Init`, - and `std::cout` is flushed when the last of them is destroyed. One inside a - library of the bundle is now never destroyed, so a host that turned off - `sync_with_stdio` loses what `std::cout` still buffers at exit (seen in the - audit with GCC 11.4 and a test library). The release builds its Linux - libraries with GCC 13, where the stream initializer lives in libstdc++, - except `libggml-hip.so` (the ROCm image has GCC 11.4), and neither the - sources of that module nor `hip/hip_runtime.h` include ``; the - other ROCm headers were not checked. A bundle built with an older GCC is - affected. -- The heap that the statics of a backend module own is not freed when ggml - unloads the module. The audit measured 544 KB after 300 calls of - `ggml_backend_load_all_from_path` on a host without a Vulkan driver, where - the Vulkan module is loaded and unloaded each time, against 36 KB before: - about 1.7 KB for each unload. llamadart loads the backends once. - -### Other platforms - -- musl: not supported and not run. No bundle is built for it. `on_exit` is a - glibc function, so the handler is compiled only where `__GLIBC__` is - defined; a musl build would keep its statics and do nothing at exit. -- Android: left as it was, by `!defined(__ANDROID__)` in the two sources and - `CMAKE_SYSTEM_NAME STREQUAL "Linux"` in CMake. bionic orders exit handlers - the same way, but the issue has no Android measurement and nothing here ran - on Android. -- Windows: not applicable, going by the documented behavior of the C runtime - and not by a run. `exit()` ends in `ExitProcess`, which terminates - the other threads before any DLL destroys its statics, so a thread is gone - before the statics it read are destroyed. A handler in `llamadart.dll` runs - at `DLL_PROCESS_DETACH`, under the loader lock and after those threads were - terminated: it could wait for nothing, and a lock that a terminated thread - held stays held. A wait there would have to run in the host before - `ExitProcess`, which is `llama_dart_exit_teardown`'s job. No Windows crash - of this kind is known, and no lane could show one. - -## Measurements - -Linux arm64 container (Ubuntu 24.04, glibc 2.39, GCC 13.3) on an Apple M4 -Max, the `linux-arm64-full` preset without KleidiAI: Release with link-time -optimization, OpenMP, the CPU, Vulkan and BLAS modules. `v0.6.0-1` is its -source, `ceae6f7`, built in the same container. - -### Native host - -A probe opens `libllamadart.so` with `dlopen`, as Dart does, and calls C -`exit()` from the main thread while another thread is inside a guarded call. -"Slow host" adds an exit handler of the probe's own that takes 300 ms, -registered before the library is opened and so run last, as the handlers of a -larger host are. Vulkan is Mesa 25.2.8 lavapipe (`llvmpipe`, -`GGML_VK_VISIBLE_DEVICES=0`, all layers offloaded); BLAS is OpenBLAS 0.3.26. -CPU and BLAS rows use Qwen3.5 0.8B Q4_0, Vulkan rows `stories15M`. The numbers -are failed runs of 10, or of 50 where it says so: a signal, an exit code other -than 0, a failed `GGML_ASSERT`, or no exit within 120 s. - -| Exit | Modules | Host | `v0.6.0-1` | This rebuild | -| --- | --- | --- | --- | --- | -| while generating (decode and sample in a loop) | CPU | fast | 7 | 0 | -| | CPU | slow | 10 | 0 | -| | CPU, BLAS | fast | 10 | 0 | -| | CPU, BLAS | slow | 10 | 0 | -| | Vulkan | fast | 4 | 0 | -| | Vulkan | slow | 10 | 0 | -| inside one decode of 1500 tokens | CPU | fast | 1 | 0 | -| | CPU | slow | 10 | 0 | -| | CPU, BLAS | fast | 6 | 0 | -| | CPU, BLAS | slow | 10 | 0 | -| | Vulkan | fast | 0 of 50 | 0 of 50 | -| | Vulkan | slow | 16 of 50 | 0 of 50 | -| 100 ms and 400 ms into the first load | CPU | slow | 8, 8 | 0, 0 | -| 200 ms and 800 ms into the first load | CPU | fast | 0, 0 | 0, 0 | -| 5 ms and 60 ms into the first load | Vulkan | fast | 0, 0 | 0, 0 | -| | Vulkan | slow | 10, 9 | 0, 0 | -| first load, once tensors are loading | CPU, Vulkan | fast, slow | 0 | 0 | -| halfway through a second load | CPU | slow | 5 | 0 | -| | CPU, Vulkan | fast | 0 | 0 | -| `return` from `main` while generating | CPU | fast | 5 | 0 | -| | CPU | slow | 10 | 0 | -| | Vulkan | fast | 7 | 0 | -| | Vulkan | slow | 10 | 0 | -| model idle; everything freed; `return` from `main` with a model idle | CPU, BLAS, Vulkan | fast, slow | 0 | 0 | -| a host handler that joins an idle worker, which frees its model | CPU | fast | 0 | 0 | -| a host handler that joins a worker that is generating | CPU | fast | 10 | 0 | - -Every failed run of `v0.6.0-1` ended in a signal: `SIGSEGV`, and on lavapipe -also `SIGABRT` (`double free or corruption`). No row of this rebuild has a -failed run, and none is worse than before. In the last row the host's handler -does not run: the process ends at libllamadart's handler, with the exit -status. In the row above it the handler runs and joins the worker, before and -after. - -Other shapes of host, from the probe of the audit, CPU with a fast host -unless it says otherwise, failed runs of 10: - -| Exit | `v0.6.0-1` | This rebuild | -| --- | --- | --- | -| from a worker thread while the main thread generates | 9 | 0 | -| from inside an evaluation callback; from inside a load progress callback | 10, 10 | 0, 0 | -| while two models generate | 10 | 0 | -| while a thread generates with the upstream `llama_decode` on a tracked context | 5 | 0 | -| while a thread generates on a model and context from the upstream functions | 8 | 0 | -| while a thread tokenizes in a loop | 2 | 0 | -| inside a long decode on a context with an abort callback of its own, BLAS, fast and slow host | 8, 10 | 0, 0 | -| after `llama_dart_exit_teardown`; after `dlclose` of libllamadart; `quick_exit`; `_exit` | 0 | 0 | -| ten load and free cycles, then right after a generation step | 9 | 3 | - -The three failed runs of the last row are not crashes. The exit fell between -two guarded calls of the worker, so it went on, the worker's next decode was -refused (`INT32_MIN`, `the process is exiting`), and that probe ends the -process with a code of its own when a decode fails. A host whose worker -treats a failed call as fatal sees that during an exit; before, the same row -crashed 9 of 10. - -The two rows that earlier versions of this change made worse are the long -decode on lavapipe with a fast host (0 of 50 before, 2 of 50 when the exit -waited two seconds and went on, 0 of 50 now) and the Dart row of "Why the -exit does not wait". - -### Dart - -Dart 3.13.1, CPU. `tests/manual/dart_exit_probe.dart` calls a guarded decode -and sample per step through a small C shim, on `stories15M`; llamadart rows -are its own `test/fixtures/llama_cpp_exit_probe.dart` and a variant with an -isolate that wakes on a 5 ms timer, on llamadart `9275de8` with the bundle -under test and Qwen3.5 0.8B Q4_0. The main isolate calls C `exit()` through -FFI. "Looping" is a second isolate that decodes UTF-8 in a loop. Failed runs -of 30 unless it says otherwise. - -| Exit | Other isolate | `v0.6.0-1` | This rebuild | -| --- | --- | --- | --- | -| llamadart `quit-generating` | none | 18 | 0 | -| llamadart `quit-loaded`, `quit-loading`, `return-loaded`, `kill-loading` | none | 0 | 0 | -| llamadart, right after a generation finished | 5 ms timer | 0 | 0 | -| llamadart, 1 s after a generation finished | 5 ms timer | 0 | 0 | -| llamadart, while generating | 5 ms timer | 25 | 0 | -| llamadart `throw-generating`, `throw-loading` (exit code 255 expected) | none | 255, 10 of 10 | 255, 10 of 10 | -| worker isolate generating | none | 15 | 0 | -| worker isolate generating | looping | 12 | 0 | -| worker isolate generating, slow host | looping | 30 | 1 | -| worker isolate inside one decode of 1500 tokens | looping | 15 of 50 | 0 of 50 | -| worker isolate inside one decode of 1500 tokens, slow host | looping | 50 of 50 | 0 of 50 | -| worker isolate idle after a generation | none | 0 | 0 | -| worker isolate idle after a generation | 5 ms timer | 0 | 0 | -| worker isolate idle after a generation | looping | 12 of 100 | 11 of 100 | -| right after a guarded call returned | looping | 36 of 100 | 24 of 100 | -| model idle for 400 ms | looping | 23 of 100 | 20 of 100 | -| `dart:io` `exit()` while generating; `main` returns while generating | none | 0 | 0 | -| worker generating; a 300 ms exit handler registered right before the exit | none | 25 | 19 | -| worker inside the long decode; the same late handler | looping | 30 | 30 | - -The failures of `v0.6.0-1` with a call in flight are the `SIGSEGV` of the -issue, or the abort of the Dart VM. All the failures of this rebuild are the -abort of the Dart VM, in exits that go on: - -- The three rows with a looping isolate and no call in flight. The VM aborts - there whether libllamadart has a handler or not, and at a rate that moves - with the load of the machine: the 100 runs of a row were taken in turns of - ten for each build, an earlier sample of 30 gave 0 to 4 for `v0.6.0-1` and 0 - to 1 for this rebuild, and the audit saw 1 of 90 and 0 of 90. The handler - returns at once in these exits and adds nothing to them. -- The one of 30 with a slow host: the exit fell between two guarded calls of - the worker, found none in flight, and went on into the 300 ms handler. -- The last two rows, where a handler that was registered after libllamadart's - runs before it and takes its 300 ms first. libllamadart cannot run before a - handler that is registered later. - -## Checks +# v0.6.0-2 wrapper rebuild: Linux host shutdown + +llama.cpp remains v0.6.0 (`d81235049`). No wrapper export or header layout is +added. Android driver patches and image-token limits are separate work. + +## Contract + +Before a native host calls C `exit()`, it stops new work, stops and joins its +native workers, and shuts down its Dart isolates or Flutter engine. A kill +request is not completion: await each isolate's exit notification and native +finalizers before exiting. Free contexts before projectors / models. A native +call already in progress completes before its isolate can shut down. + +Linux, Android excepted, retains the statics owned by the runtime bundle. +`src/llama_dart_static_destructors.c` supplies a hidden `__cxa_atexit` that drops +owned static destructors; external libraries keep their ordinary exit behavior. +The wrapper remains linked with `-z nodelete` so held objects and finalizer +callbacks remain valid across `dlclose`. Artifact validators reject missing +retention and owned imports of `__cxa_atexit` or the pre-GCC13 iostream initializer. + +C exit registers no automatic Linux wrapper teardown or exit handler. It does +not set a late-call refusal state, flush streams early, wait, free live objects +or call `_exit`. Normal host callbacks, dependency destructors and libc stdio +flushing run in their normal order. An earlier native-host callback can still +join a worker and free its tracked objects; the wrapper does not park that +worker merely because libc exit began. + +Apple automatic teardown and explicit `llama_dart_exit_teardown` are unchanged. +Do not invoke explicit teardown before joining workers: it parks later guarded +calls, so a subsequent host join can hang. Android is unchanged. Windows / musl +hardware qualification is not established by these Linux glibc measurements. + +## Why exit must follow host shutdown + +A direct C exit with live Dart isolates is unsafe independently of llama.cpp. +With an allocating isolate and an earlier300ms host callback, the VM aborts at +`handles_impl.h:39` without loading any native model (llamadart#977). Retaining +owned statics cannot protect a GPU driver's or BLAS library's destructors either. +Direct C exit while Dart isolates or dependency-using native workers are alive +is outside this contract, including calls from an evaluation callback or an +incomplete model load. CPU raw-exit controls remain diagnostics, not support +claims. A hung native call cannot be called quiescent after a timeout; the host +must withhold normal C exit until it completes or explicitly choose its own +abrupt process-termination policy. + +The rejected candidate flushed streams and called `_exit` when a call was in +flight. It skipped earlier host callbacks, and its `fflush(NULL)` deadlocked if +a worker held a FILE lock whose earlier host callback would release it. Removing +only the flush lost buffered output. Both alternatives violate the accepted +preservation contract and are absent from this revision. + +## Validation and replay + +`llamadart_exit_teardown_exit-status` verifies exit37, the earlier callback, +buffered output, and a host callback joining a marked native worker that holds a +FILE lock. Its10s CTest timeout makes the old unconditional-flush deadlock fail. +`exit-late-calls` verifies the host callback can create and free tracked objects +without an automatic Linux refusal state. These are native compatibility +controls, without a running Dart VM. Apple teardown tests retain their contract. + +The maintained manual `tests/manual/dart_host_shutdown_probe.dart` uses worker +NativeFinalizers, per-worker onExit notifications, an allocating isolate, a +slow native call and a slow earlier host callback. Build the adjacent shim as +in `dart_exit_probe.dart`; set `PROBE_STEP_DELAY_MS=300`, then run: ```bash -cmake -S . -B build/wrapper-contract -G Ninja -DCMAKE_BUILD_TYPE=Debug \ - -DGGML_NATIVE=OFF -DGGML_OPENMP=OFF -DLLAMADART_BUILD_TESTS=ON -cmake --build build/wrapper-contract --target llamadart_exit_teardown_test -ctest --test-dir build/wrapper-contract -R exit_teardown --output-on-failure -for library in build/wrapper-contract/libllamadart.so build/wrapper-contract/bin/*.so; do - python3 tools/validate_exports.py --format readelf --tool readelf \ - --imports-only --forbid-import __cxa_atexit "$library" -done +dart tests/manual/dart_host_shutdown_probe.dart libshim.so \ + cooperative-finalizer-slow-native ``` -`llamadart_exit_teardown_test` now runs its model scenarios on Linux as well, -on the CPU backend module and the models it writes itself. CTest finds the -llama.cpp libraries of a Linux preset build, which keeps them in `bin/`, -without `LD_LIBRARY_PATH`. In the container above: - -- The release preset: 52 of 52 CTest cases, ten times over. -- The configuration of the `wrapper-contract` lane (Debug, no OpenMP) on the - pinned upstream and on the post-v0.4.0 one: 52 of 52 each, and the 46 exit - cases five times over. -- A RelWithDebInfo build with AddressSanitizer: the 46 exit cases three times - with leak detection off, with no report. With it on, `barrier-grammar` - reports 80 bytes that llama.cpp leaks when a lazy grammar is rejected - (`llama-sampler.cpp:2777`), as before this change, and nothing else does. -- The same test source against the libraries of `v0.6.0-1`, five runs each: - `model-decode`, `model-unguarded-decode` and `model-exit-join-generating` - end in `SIGSEGV` every time and `model-late-load` four times; - `exit-in-flight`, `exit-status`, `model-load` and `model-free-in-flight` - fail because the exit went on under a call in flight; `exit-late-calls` and - `model-exit-join-idle` fail because a free after the exit still freed. -- Each part removed in turn fails a scenario: - - | Removed | Fails | - | --- | --- | - | the static destructor object | `model-unguarded-decode` (`SIGSEGV`); `validate_linux_artifact.py` names the libraries | - | ending the process for a call in flight | `exit-in-flight`, `exit-status`, `model-load`, `model-free-in-flight` | - | the handler at the first creating call | `model-load` | - | the handler at the first tracked object | `exit-in-flight`, `exit-status`, `exit-late-calls` | - | the exit status | `exit-status` | - | the flush of the standard streams | `exit-status` | - | returning at once with no call in flight (250 ms added) | `model-exit-idle` | - | threads not blocked after the exit | `exit-late-calls`, `model-exit-join-idle` | - | the refusal of a late call | `exit-late-calls` | - | the exemption of the exiting thread | `exit-late-calls` | - | `-z nodelete` | `validate_linux_artifact.py` | - -`validate_exports.py --forbid-import` now reads ELF imports with -`--format readelf`. With `--format nm` it reads names as Mach-O ones, without -their leading underscore, and an ELF `__cxa_atexit` never matched. - -No lane runs Dart or a GPU decode. `tests/manual/dart_exit_probe.dart`, with -the shim next to it, is the probe of the "Dart" table; the lavapipe rows need -a build with `GGML_VULKAN=ON`, Mesa's `mesa-vulkan-drivers` and -`GGML_VK_VISIBLE_DEVICES=0`. - -macOS arm64 (Apple M4 Max), `macos-arm64-full` preset: `libllamadart.dylib` -built from this tree and from `v0.6.0-1` at the same path have the same -SHA-256, and 46 of 46 CTest cases pass (45 before; `exit-in-flight` is new). -186 Python tests pass (183 before), and the 22 of the Linux artifact tools -(18 before). - -## Not verified - -- A real Vulkan GPU and CUDA. The container has neither; lavapipe is a CPU - implementation with its own threads and exit handlers, which is a different - driver from the NVIDIA one of the issue. The run that settles it is the one - of the issue on its host (GCE L4 VM, Ubuntu 24.04, NVIDIA 580): the - `quit-loaded`, `quit-generating`, `quit-loading`, `return-loaded` and - dispose-then-quit scenarios of llamadart's - `test/fixtures/llama_cpp_exit_probe.dart` on the `v0.6.0-2` bundle, with the - CPU, Vulkan and CUDA backends, at least 10 runs each, against `v0.6.0-1`. - The scenarios with a call in flight end in `_exit` on every backend, which - the container shows; what a GPU host adds is the exits that go on: a model - left loaded, and a handler of the driver that was registered after - libllamadart's. -- Linux x64 by hand. The measurements are arm64; `validate_wrapper.yml` runs - the scenarios on x64. -- HIP and musl builds, Android and Windows. -- Flutter. The Dart rows are the standalone VM, and whether a Flutter Linux - window close reaches C `exit()` with a worker inside a guarded call is not - known. If it does, the exit ends there and the engine's own exit handlers - do not run. +Success requires exit0, `NATIVE_ACTIVE_BEFORE_KILL`, `NATIVE_CALLS_AFTER_EXIT 0`, +`NATIVE_FREE_COUNT_AFTER_EXIT 1`, `HOST_HANDLER_COMPLETED`, and `C_BUFFERED_PAYLOAD`. +`raw-control` reproduces the VM defect; `cooperative-control` verifies allocator +shutdown without loading a native bundle. Neither case requires model downloads. + +Pre-implementation prototype evidence (not qualification of this revised head): +Linuxarm64 GCC14/glibc2.41, Dart3.13.1, stories15M CPU, five repeats per case / +build, released baseline vs rejected head vs preservation prototype.60/60 +cooperative model cases and15/15 no-model cases retained callbacks / output. +30/30 active native-call cases waited314–339ms before onExit;15/15 finalizers +completed first.15/15 raw no-model controls aborted. The protocol also passed +on the released baseline, so it establishes the lifecycle boundary, not a new +native feature. The GCC13 dependencies were reused read-only; this differs +from Ubuntu24.04/GCC13 release qualification. + +Current-head CI, independent audit and exact-runtime replay are required anew. +Remaining release gates include real GPU / OpenBLAS driver shutdown, image +runtime, Flutter Linux host ordering, final published artifacts and device +qualification. No earlier raw-exit result establishes those gates. diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index 4ada57bd..c698002b 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -44,15 +44,6 @@ #endif #endif -// On Linux with glibc, C exit() runs llama_dart_exit_at_exit. Android is left -// out: an exit during a call in flight has not been examined there. -#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) -#include -#define LLAMA_DART_EXIT_ON_LINUX 1 -#else -#define LLAMA_DART_EXIT_ON_LINUX 0 -#endif - // Global log level (0=none, 1=debug, 2=info, 3=warn, 4=error) static std::atomic g_dart_log_level{3}; // Default to WARN // Track last non-CONT severity so continuation lines inherit proper level. @@ -737,13 +728,6 @@ static thread_local bool llama_dart_exit_teardown_thread = false; // Calls in flight on this thread. The registry counts the outermost one. static thread_local int32_t llama_dart_exit_call_depth = 0; -#if LLAMA_DART_EXIT_ON_LINUX -// Set, under the registry lock, once C exit() has reached libllamadart. The -// exit frees nothing: nothing on Linux needs the objects freed, and the exit -// handlers of a GPU driver may have run already. An exit with a model left -// loaded is known to be clean, a free among those handlers is not. -static std::atomic llama_dart_exit_keeps_objects{false}; -#endif // Called with the registry locked. Returns whether the calling thread may go // on to use tracked objects. Once teardown has begun, teardown waits for a @@ -761,29 +745,12 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, if (llama_dart_exit_call_depth > 0) { return true; } -#if LLAMA_DART_EXIT_ON_LINUX - // The exit freed nothing, so the thread holds nothing that is gone, and - // blocked here it would hang an exit handler of the host that joins it. - if (llama_dart_exit_keeps_objects.load()) { - return false; - } -#endif lock.unlock(); for (;;) { std::this_thread::sleep_for(std::chrono::hours(1)); } } -#if LLAMA_DART_EXIT_ON_LINUX -// Whether a call in flight that was just begun on this thread was not counted -// because C exit() has passed libllamadart already. Such a call must not -// start work under the rest of the exit: its function throws, and the barrier -// returns the failure value. -static bool llama_dart_exit_began_too_late() { - return llama_dart_exit_call_depth == 0 && !llama_dart_exit_teardown_thread && - llama_dart_exit_keeps_objects.load(); -} -#endif #if defined(__APPLE__) struct llama_dart_exit_static_destructor { @@ -841,33 +808,6 @@ __cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { } #endif -#if LLAMA_DART_EXIT_ON_LINUX -// What C exit() runs on Linux. With a call in flight on another thread it -// ends the process there, with the status of the exit and without the rest -// of the exit: what would follow is the exit handlers and destructors of -// other libraries, a GPU driver or OpenBLAS among them, which would run under -// the call. It does not wait for the call instead, because time spent inside -// exit() is not harmless either: a Dart VM aborts when one of its isolates -// collects garbage meanwhile, and 20 ms were enough for that. With no call in -// flight it returns at once and the exit goes on. -static void llama_dart_exit_at_exit(int status, void *) { - auto ®istry = llama_dart_exit_state(); - { - std::lock_guard lock(registry.mutex); - if (!registry.torn_down.exchange(true)) { - llama_dart_exit_teardown_thread = true; - llama_dart_exit_keeps_objects.store(true); - } - // A call in flight on this thread is the one that is exiting. - const int32_t own_calls = llama_dart_exit_call_depth > 0 ? 1 : 0; - if (registry.calls == own_calls) { - return; - } - } - fflush(nullptr); - _exit(status); -} -#endif // Registers teardown to run at exit once something is tracked, so that it // does not wait for the first static of this image to be destroyed. atexit @@ -878,25 +818,10 @@ static void llama_dart_exit_arm() { if (!llama_dart_exit_state().armed.exchange(true)) { atexit(llama_dart_exit_teardown); } -#elif LLAMA_DART_EXIT_ON_LINUX - if (!llama_dart_exit_state().armed.exchange(true)) { - on_exit(llama_dart_exit_at_exit, nullptr); - } #endif } -// On Linux llama.cpp is not part of this image and no library of the bundle -// registers static destructors (llama_dart_static_destructors.c), so only a -// handler sees the exit, and the exit that arrives during the first creating -// call needs one that was registered before anything is tracked. -static void llama_dart_exit_arm_creating_call() { -#if LLAMA_DART_EXIT_ON_LINUX - static std::atomic armed{false}; - if (!armed.exchange(true)) { - on_exit(llama_dart_exit_at_exit, nullptr); - } -#endif -} + static bool llama_dart_exit_insert(void *object, void (*free_fn)(void *), int32_t stage, void *uses_first = nullptr, @@ -997,11 +922,6 @@ static void llama_dart_exit_begin_call(bool creating) { struct llama_dart_exit_call { llama_dart_exit_call() { llama_dart_exit_call_begin(); -#if LLAMA_DART_EXIT_ON_LINUX - if (llama_dart_exit_began_too_late()) { - throw std::runtime_error("the process is exiting"); - } -#endif } ~llama_dart_exit_call() { llama_dart_exit_call_end(); } llama_dart_exit_call(const llama_dart_exit_call &) = delete; @@ -1012,18 +932,7 @@ struct llama_dart_exit_call { // when nothing is tracked yet. struct llama_dart_exit_creating_call { llama_dart_exit_creating_call() { - llama_dart_exit_arm_creating_call(); llama_dart_exit_begin_call(true); -#if LLAMA_DART_EXIT_ON_LINUX - if (llama_dart_exit_began_too_late()) { - { - auto ®istry = llama_dart_exit_state(); - std::lock_guard lock(registry.mutex); - --registry.creating_calls; - } - throw std::runtime_error("the process is exiting"); - } -#endif } ~llama_dart_exit_creating_call() { { diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 971473a4..46cfa036 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -354,36 +354,23 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // destructor. On Apple platforms it runs during exit, before the first static // of libllamadart is destroyed. // -// On Linux with glibc, C exit() does not run teardown. llama.cpp is not part -// of libllamadart there, and no library of the bundle registers static -// destructors: their statics stay valid until the process is gone. When the -// exit reaches libllamadart: +// On Linux, Android excepted, owned bundle statics are retained until the +// process is gone. C exit() runs no wrapper handler: normal host callbacks, +// dependency destructors and libc stream flushing proceed without a forced +// _exit, an automatic free, a wait or late-call refusal. // -// - With a call in flight on another thread, the process ends there, as with -// _exit: with the status of the exit and the standard streams flushed, but -// without the exit handlers and static destructors that would have run -// next, those of the host among them. What would have run next is the exit -// handlers of other libraries, a GPU driver or OpenBLAS among them, under -// the call, and waiting for the call instead is not harmless either: a -// Dart VM aborts when its isolates run while exit() takes its time. -// - With no call in flight, the exit goes on at once. Nothing is freed: -// nothing on Linux needs it, and an exit with a model left loaded is known -// to be clean, which a free among the exit handlers of a GPU driver is not. -// No thread is blocked. From then on, on a thread other than the exiting -// one, a call in flight that begins returns the failure value of its -// function, with "the process is exiting" as the last error, and starts -// nothing; llama_dart_exit_free frees nothing; llama_dart_exit_track and -// llama_dart_exit_untrack return false; llama_dart_exit_call_begin counts -// nothing. +// Before a native host calls C exit(), it must stop and join its workers and +// shut down its Dart isolates / Flutter engine. Await isolate exit and native +// finalizer completion, not just a kill request. A direct C exit() with live +// Dart isolates can abort the VM even without llama.cpp (llamadart#977). +// Retaining owned statics does not protect a GPU driver's or BLAS library's +// destructors. Do not call explicit teardown before joining workers: teardown +// parks later guarded calls and can deadlock a host join. // -// The exit reaches libllamadart at the handler that it registers at the first -// creating call and again when the first object is tracked, so an exit handler -// that another library registers later runs before that. libllamadart is -// linked so that dlclose does not unload it. quick_exit and _exit run -// nothing. -// -// Elsewhere nothing runs at exit. llama_dart_exit_teardown runs teardown, and -// frees, on every platform. +// libllamadart remains loaded across dlclose so held native objects and their +// finalizer callbacks stay valid. quick_exit and _exit run no cleanup. +// Elsewhere nothing changes. llama_dart_exit_teardown explicitly frees on +// every platform; automatic Apple exit teardown remains as described above. // // Objects are tracked, before the creating call returns, by // llama_dart_model_load_from_file, llama_dart_init_from_model, diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 2a9ebe69..0e0785f5 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -471,9 +471,8 @@ int test_blocked() { // C exit() runs teardown on Apple platforms: it waits for the calls in // flight, frees, and blocks the threads that reach libllamadart afterwards. -// On Linux it ends the process at once when a call is in flight on another -// thread. Otherwise it frees nothing, blocks no thread and refuses the calls -// in flight that begin afterwards. +// Linux retains owned statics and leaves normal libc exit untouched. +// Hosts stop workers and the managed runtime before C exit. #if defined(__APPLE__) const bool kExitFreesObjects = true; const bool kExitWaitsForCalls = true; @@ -482,8 +481,8 @@ const bool kExitRefusesLateCalls = false; #elif defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) const bool kExitFreesObjects = false; const bool kExitWaitsForCalls = false; -const bool kExitEndsProcess = true; -const bool kExitRefusesLateCalls = true; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; #else const bool kExitFreesObjects = false; const bool kExitWaitsForCalls = false; @@ -578,59 +577,42 @@ int test_exit_in_flight() { char kLateObject[] = "late-object"; llama_dart_ngram *g_created_at_exit = nullptr; -// What a thread other than the exiting one gets from libllamadart once the -// exit has waited, on Linux: nothing blocks, a free frees nothing, and a call -// in flight is refused before it starts. +// An earlier host callback still owns normal wrapper cleanup. No Dart VM +// is active here, and no wrapper teardown has begun. void make_late_calls() { - g_exit_expected.store(true); - // The exiting thread is exempt: a host's later exit handlers may still use - // libllamadart. What it creates is not tracked, and stays allocated. + assert(llama_dart_exit_tracked_count() == 1); g_created_at_exit = llama_dart_ngram_simple_init(4, 8); assert(g_created_at_exit != nullptr); assert(llama_dart_last_error() == nullptr); - assert(llama_dart_exit_tracked_count() == 1); - std::thread([] { - llama_dart_exit_free(kLateObject); - assert(recorded().empty()); - assert(!llama_dart_exit_track(name("later"), free_named, - LLAMA_DART_EXIT_STAGE_MODEL)); - assert(llama_dart_exit_tracked_count() == 1); - assert(llama_dart_decode(nullptr, llama_batch{}) == - std::numeric_limits::min()); - assert(refused_by_exit()); - llama_dart_clear_last_error(); - assert(llama_dart_model_load_from_file( - "missing.gguf", llama_model_default_params()) == nullptr); - assert(refused_by_exit()); - llama_dart_exit_call_begin(); - llama_dart_exit_call_end(); - assert(!llama_dart_exit_untrack(kLateObject)); - assert(!llama_dart_exit_untrack(g_created_at_exit)); - assert(llama_dart_exit_tracked_count() == 1); - g_call_ended.store(true); - }).detach(); - const int64_t started = now_ms(); - while (!g_call_ended.load()) { - if (now_ms() - started > 10000) { - fprintf(stderr, "a call after the exit began did not return\n"); - _Exit(EXIT_FAILURE); - } - sleep_ms(1); - } + assert(llama_dart_exit_tracked_count() == 2); + llama_dart_exit_free(g_created_at_exit); + llama_dart_exit_free(kLateObject); + assert(llama_dart_exit_tracked_count() == 0); + assert(recorded() == std::vector{"late-object"}); } int test_exit_late_calls() { - // Registered first, so it runs after the handler of libllamadart. assert(atexit(make_late_calls) == 0); assert(llama_dart_exit_track(kLateObject, free_named, LLAMA_DART_EXIT_STAGE_MODEL)); return 0; } -// On Linux an exit with a call in flight on another thread ends the process -// there: with the status of the exit and the standard streams flushed, and -// without the exit handlers that would have run next. The exit is that of a -// child process, whose status and output this one reads. +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +std::atomic status_worker_stop{false}; +std::thread *status_worker = nullptr; +FILE *status_locked_stream = nullptr; +void status_host_callback() { + status_worker_stop.store(true); + status_worker->join(); + printf(";host handler ran"); +} +#endif + +// Normal C exit preserves its status, earlier callbacks and buffered output. +// A host callback releases a FILE lock held by a marked native worker: an +// unconditional fflush before that callback would hang. This native-only +// compatibility control does not authorize live-Dart-isolate C exit. int test_exit_status() { #if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) int output[2]; @@ -640,26 +622,26 @@ int test_exit_status() { if (child == 0) { close(output[0]); assert(dup2(output[1], STDOUT_FILENO) >= 0); - // Registered first, so it would run after the handler of libllamadart. - assert(atexit([] { _Exit(EXIT_FAILURE); }) == 0); + assert(atexit(status_host_callback) == 0); static char object[] = "object"; assert(llama_dart_exit_track(object, free_named, LLAMA_DART_EXIT_STAGE_MODEL)); + status_locked_stream = tmpfile(); + assert(status_locked_stream != nullptr); static std::atomic started{false}; - std::thread([] { + status_worker = new std::thread([] { llama_dart_exit_call_begin(); + flockfile(status_locked_stream); started.store(true); - sleep_ms(600000); - }).detach(); - while (!started.load()) { - sleep_ms(1); - } - // A pipe is fully buffered, so this is written when the exit flushes. + while (!status_worker_stop.load()) sleep_ms(1); + funlockfile(status_locked_stream); + llama_dart_exit_call_end(); + }); + while (!started.load()) sleep_ms(1); printf("flushed at exit"); exit(37); } close(output[1]); - const auto started = std::chrono::steady_clock::now(); std::string text; char buffer[64]; for (ssize_t count; (count = read(output[0], buffer, sizeof(buffer))) > 0;) { @@ -668,8 +650,7 @@ int test_exit_status() { int status = 0; assert(waitpid(child, &status, 0) == child); assert(WIFEXITED(status) && WEXITSTATUS(status) == 37); - assert(text == "flushed at exit"); - assert(elapsed_ms(started) < 10000); + assert(text == "flushed at exit;host handler ran"); #endif return 0; } @@ -1530,8 +1511,8 @@ int test_model_exit_join_idle(const char *path) { } llama_dart_exit_free(fixture.context); llama_dart_exit_free(fixture.model); - if (llama_dart_exit_tracked_count() != 2) { - fprintf(stderr, "a free after the exit began freed its object\n"); + if (llama_dart_exit_tracked_count() != 0) { + fprintf(stderr, "host worker cleanup left tracked objects\n"); _Exit(EXIT_FAILURE); } g_worker_done.store(true); @@ -1737,6 +1718,24 @@ void expect_free_finished_at_exit() { // Metal aborts in its static destructor when the exit does not wait for the // free; without Metal the check at exit shows it. int test_model_free_in_flight(const char *path) { +#if defined(__linux__) && !defined(__ANDROID__) + // Linux waits in the host, before libc exit / dependency destructors. + assert(atexit([] { assert(g_free_finished.load()); }) == 0); + auto fixture = load_model(path); + llama_dart_exit_free(fixture.context); + assert(llama_dart_exit_track(fixture.model, [](void *object) { + g_free_started.store(true); + sleep_ms(300); + llama_model_free(static_cast(object)); + g_free_finished.store(true); + }, LLAMA_DART_EXIT_STAGE_MODEL)); + std::thread worker([fixture] { llama_dart_exit_free(fixture.model); }); + while (!g_free_started.load()) sleep_ms(1); + worker.join(); + assert(g_free_finished.load()); + assert(llama_dart_exit_tracked_count() == 0); + return 0; +#else // Registered first, so it runs after teardown and after the Metal device, // which the load creates, is destroyed. assert(atexit(expect_free_finished_at_exit) == 0); @@ -1757,6 +1756,7 @@ int test_model_free_in_flight(const char *path) { } assert(llama_dart_exit_tracked_count() == 0); return 0; +#endif } // Evaluates an image prompt chunk by chunk, as the Dart side does. diff --git a/tests/manual/dart_exit_probe_shim.cpp b/tests/manual/dart_exit_probe_shim.cpp index d973f12f..481623dc 100644 --- a/tests/manual/dart_exit_probe_shim.cpp +++ b/tests/manual/dart_exit_probe_shim.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -15,8 +16,11 @@ llama_context *llama_dart_init_from_model(llama_model *, llama_context_params); int32_t llama_dart_decode(llama_context *, llama_batch); llama_token llama_dart_sampler_sample(llama_sampler *, llama_context *, int32_t); void llama_dart_set_log_level(int); +void llama_dart_exit_free(void *); } static void *g_lib; +static std::atomic active_calls{0}; +static std::atomic free_count{0}; template static F *sym(const char *n) { void *s = dlsym(g_lib, n); if (!s) { fprintf(stderr, "missing %s\n", n); _Exit(3); } @@ -45,7 +49,7 @@ void *shim_open_session(const char *model, int tokens) { s->model = llama_dart_model_load_from_file_(model, mp); if (!s->model) return nullptr; auto cp = llama_context_default_params_(); - cp.n_ctx = 2048; cp.n_batch = 2048; + cp.n_ctx = 2048; cp.n_batch = 2048; cp.n_threads = 3; cp.n_threads_batch = 3; s->ctx = llama_dart_init_from_model_(s->model, cp); if (!s->ctx) return nullptr; s->sampler = llama_sampler_chain_init_(llama_sampler_chain_default_params_()); @@ -55,6 +59,9 @@ void *shim_open_session(const char *model, int tokens) { } // One generation step: guarded decode, then guarded sample. int shim_step(void *session) { + struct active_guard { active_guard() { ++active_calls; } ~active_guard() { --active_calls; } } guard; + const char *delay = getenv("PROBE_STEP_DELAY_MS"); + if (delay) { fprintf(stderr, "NATIVE_STEP_STARTED\n"); std::this_thread::sleep_for(std::chrono::milliseconds(atoi(delay))); } BIND(llama_get_memory); BIND(llama_memory_clear); BIND(llama_dart_decode); BIND(llama_dart_sampler_sample); BIND(llama_batch_get_one); auto *s = static_cast(session); @@ -68,4 +75,29 @@ void shim_sleeping_atexit(int ms) { static int delay; delay = ms; atexit([] { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); }); } + +int shim_free_count() { return free_count.load(); } +int shim_active_calls() { return active_calls.load(); } +void shim_register_host() { + atexit([] { + fprintf(stderr, "HOST_HANDLER_STARTED\n"); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + fprintf(stderr, "HOST_HANDLER_COMPLETED\n"); + }); +} +void shim_buffer_output() { + static char buffer[4096]; + setvbuf(stdout, buffer, _IOFBF, sizeof(buffer)); + fputs("C_BUFFERED_PAYLOAD\n", stdout); +} +void shim_close_session(void *session) { + BIND(llama_sampler_free); BIND(llama_dart_exit_free); + auto *s = static_cast(session); + llama_sampler_free_(s->sampler); + llama_dart_exit_free_(s->ctx); + llama_dart_exit_free_(s->model); + delete s; + ++free_count; + fprintf(stderr, "NATIVE_SESSION_FREE_COMPLETED\n"); +} } diff --git a/tests/manual/dart_host_shutdown_probe.dart b/tests/manual/dart_host_shutdown_probe.dart new file mode 100644 index 00000000..6b226fcc --- /dev/null +++ b/tests/manual/dart_host_shutdown_probe.dart @@ -0,0 +1,163 @@ +// Manual Linux host-shutdown probe. Build dart_exit_probe_shim.cpp as described +// in dart_exit_probe.dart, then run with PROBE_STEP_DELAY_MS=300: +// dart tests/manual/dart_host_shutdown_probe.dart +// cooperative-finalizer-slow-native verifies a native call is active before +// kill, all worker exits / finalizers complete, and normal C exit preserves +// the earlier host callback and buffered output. raw-control is the known +// Dart VM diagnostic; cooperative-control requires no native bundle. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// Generates as llamadart does: one guarded native step, then Dart work. +final class _ProbeAnchor implements Finalizable {} + +final _anchors = []; +final _finalizers = []; + +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final anchor = _ProbeAnchor(); + final finalizer = NativeFinalizer( + shim.lookup)>>( + 'shim_close_session', + ), + ); + _anchors.add(anchor); + _finalizers.add(finalizer); + finalizer.attach(anchor, session); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(session.address); + } +} + +Future main(List args) async { + final [shimPath, bundle, scenario, model] = args; + final shim = DynamicLibrary.open(shimPath); + final registerHost = shim.lookupFunction( + 'shim_register_host', + ); + final bufferOutput = shim.lookupFunction( + 'shim_buffer_output', + ); + final freeCount = shim.lookupFunction( + 'shim_free_count', + ); + final activeCalls = shim.lookupFunction( + 'shim_active_calls', + ); + registerHost(); // Registered before the native bundle; must still run later. + final exited = []; + final stopped = >[]; + final isolates = []; + Future spawnWorker( + void Function(T) entry, + T arg, + ReceivePort ready, + ) async { + final onExit = ReceivePort(); + exited.add(onExit); + stopped.add(onExit.first); + isolates.add(await Isolate.spawn(entry, arg, onExit: onExit.sendPort)); + final value = await ready.first; + ready.close(); + return value; + } + + int? sessionAddress; + if (!scenario.contains('control')) { + final ready = ReceivePort(); + sessionAddress = await spawnWorker(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario.contains('long') ? 1500 : 8, + ), ready) as int; + } + final spinning = ReceivePort(); + await spawnWorker(_spin, spinning.sendPort, spinning); + if (!scenario.startsWith('raw')) { + if (scenario.contains('slow-native')) { + final deadline = DateTime.now().add(const Duration(seconds: 3)); + while (activeCalls() == 0 && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 1)); + } + if (activeCalls() == 0) throw StateError('slow native call not active'); + stdout.writeln('NATIVE_ACTIVE_BEFORE_KILL'); + } + final watch = Stopwatch()..start(); + for (final isolate in isolates) { + isolate.kill(priority: Isolate.immediate); + } + await Future.wait(stopped).timeout(const Duration(seconds: 20)); + for (final port in exited) { + port.close(); + } + stdout.writeln('ALL_WORKERS_EXITED ${watch.elapsedMicroseconds}'); + stdout.writeln('NATIVE_CALLS_AFTER_EXIT ${activeCalls()}'); + if (activeCalls() != 0) + throw StateError('native call survived worker exit'); + stdout.writeln('NATIVE_FREE_COUNT_AFTER_EXIT ${freeCount()}'); + if (sessionAddress != null && freeCount() != 1) + throw StateError('native finalizer not completed before onExit'); + } + bufferOutput(); + _cExit(); +} diff --git a/tests/validate_linux_artifact_test.py b/tests/validate_linux_artifact_test.py index 1da7b7d2..809da6cf 100644 --- a/tests/validate_linux_artifact_test.py +++ b/tests/validate_linux_artifact_test.py @@ -312,7 +312,7 @@ def test_libllamadart_must_not_be_unloadable(self) -> None: errors, [ "libllamadart.so: is not linked with -z nodelete, so a dlclose " - "leaves its exit handler behind" + "can unload held native objects and finalizer callbacks" ], ) diff --git a/tools/validate_linux_artifact.py b/tools/validate_linux_artifact.py index d2aece00..6a2ec076 100644 --- a/tools/validate_linux_artifact.py +++ b/tools/validate_linux_artifact.py @@ -276,12 +276,12 @@ def validate_archive(archive_path: Path, tool: str, mode: str) -> list[str]: for dependency in dynamic.needed: if dependency.startswith(LOCAL_LIBRARY_PREFIXES) and dependency not in names: errors.append(f"{name}: local DT_NEEDED dependency is absent: {dependency}") - # libllamadart registers an exit handler with on_exit, which a - # dlclose does not remove: the library must never be unloaded. + # Held objects / finalizer callbacks may outlive dlclose. + # Keep the wrapper together with its owned statics. if name == "libllamadart.so" and not is_nodelete(dynamic.raw): errors.append( f"{name}: is not linked with -z nodelete, so a dlclose " - "leaves its exit handler behind" + "can unload held native objects and finalizer callbacks" ) if name.startswith(LOCAL_LIBRARY_PREFIXES): try: From 3687c58f1c060e621a57bb0c986ecc06eb69484b Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 20:33:51 -0400 Subject: [PATCH 8/8] docs: match Linux artifact validator contract --- docs/v060_2_wrapper_rebuild.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 12269501..d3dcf359 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -16,7 +16,7 @@ Linux, Android excepted, retains the statics owned by the runtime bundle. owned static destructors; external libraries keep their ordinary exit behavior. The wrapper remains linked with `-z nodelete` so held objects and finalizer callbacks remain valid across `dlclose`. Artifact validators reject missing -retention and owned imports of `__cxa_atexit` or the pre-GCC13 iostream initializer. +retention and owned imports of `__cxa_atexit`. C exit registers no automatic Linux wrapper teardown or exit handler. It does not set a late-call refusal state, flush streams early, wait, free live objects