Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ dart test -p chrome --exclude-tags local-only
through `LlamaCppObjectCalls` or `ExitTeardownApi`. Teardown waits only for
those guarded calls; any other call in flight at a direct C `exit()` is
unprotected (`doc/llama_cpp_exit_teardown.md`).
- In `lib/src/backends/stable_diffusion/`, every native call of an image
worker goes through `StableDiffusionCalls`, and Dart gives
stable-diffusion.cpp no callback. A call on an `sd_ctx_t` that can run
longer than 250 ms needs an `sd_dart_` wrapper in `stable-diffusion-native`
first (same doc, "Image models").
- Generated files that should not count toward coverage carry
`// coverage:ignore-file`.
- Tests close the ports, streams and controllers they open.
Expand Down
18 changes: 16 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,26 @@
heads still allocated at exit
([#813](https://github.com/leehack/llamadart/issues/813),
[llamadart-native#96](https://github.com/leehack/llamadart-native/issues/96)).
Image models, and a native host's C `exit()` while llamadart is working,
are not covered.
A native host's C `exit()` while a llama.cpp call is running is not covered.
- Update the default llama.cpp runtime to `leehack/llamadart-native@v0.5.0-2`,
a rebuild of llama.cpp `v0.5.0` whose Apple XCFramework carries a privacy
manifest (File Timestamp, reason `C617.1`). A runtime older than `v0.5.0-1`
keeps the previous exit behavior and logs a warning at the first model load.
- Fix a process aborting when a Dart program dies of an error, or a Flutter
macOS app quits or hot restarts, while an image model loads or generates,
and a macOS Metal process aborting in ggml-metal when a native host exits
with an image model loaded: the stable_diffusion runtime now records
progress instead of calling back into Dart, and frees the image models
still allocated at exit
([stable-diffusion-native#10](https://github.com/leehack/stable-diffusion-native/issues/10)).
Image progress events now arrive up to about 50 ms after the runtime
reports them. A quit during an image generation waits for the generation
to finish; dispose the engine first to quit at once.
- Update the stable_diffusion runtime to
`leehack/stable-diffusion-native@v0.2.0-1`, a rebuild of the same
stable-diffusion.cpp commit whose Apple XCFramework carries a privacy
manifest (File Timestamp, reasons `C617.1` and `3B52.1`). Image generation
needs this runtime or a later one.
- Documented that LiteRT-LM on iOS has run on a device only on iOS 18.3.2;
iOS 16.4 remains the declared, untested deployment floor
([#831](https://github.com/leehack/llamadart/issues/831)).
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,10 @@ An app bound for the App Store should use the companion for each runtime it
ships: an Apple privacy manifest reaches an app inside a SwiftPM XCFramework,
never in the dylibs the build hook bundles. The llama.cpp XCFramework carries
one from `llamadart-native` `v0.5.0-1`, which `llamadart_llama_cpp_flutter`
releases after `0.0.20` link; the pinned stable_diffusion XCFramework carries
none. An app that runs llama.cpp or stable_diffusion on the hook path, or
releases after `0.0.20` link; the stable_diffusion XCFramework carries one
from `stable-diffusion-native` `v0.2.0-1`, which
`llamadart_stable_diffusion_flutter` releases after `0.0.1` link. An app that
runs llama.cpp or stable_diffusion on the hook path, or
whose embedded `llama.framework` or `stable_diffusion.framework` has no
`PrivacyInfo.xcprivacy`, declares
`NSPrivacyAccessedAPICategoryFileTimestamp` in its own `PrivacyInfo.xcprivacy`
Expand Down
152 changes: 151 additions & 1 deletion doc/llama_cpp_exit_teardown.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ since a projector points at its model.
| `exit()` from `dart:io` | Runs no static destructors: no teardown and no abort. |
| C `exit()` while an isolate is still running (through FFI, or a native host that skips the engine shutdown) | Covered only while the isolate is idle, freeing an object, or inside a guarded call that returns within two seconds. Inside an unguarded call it is a use after free; inside a longer guarded call ggml-metal aborts. |

Image models are not covered: stable-diffusion.cpp has no such teardown.
Image models have their own registry in `libstable-diffusion`: see
"Image models".

## Rule for new code

Expand All @@ -90,6 +91,11 @@ must not race exit teardown goes through `LlamaCppObjectCalls` or
in `llamadart-native` first; calling the upstream function leaves the call
unprotected at a direct C `exit()`.

Every native call of an image worker goes through `StableDiffusionCalls`. A
new call on an `sd_ctx_t` that can run longer than the 250 ms settle time
(`generate_video`, `sd_ctx_load_control_net`, an upscaler) needs an
`sd_dart_` wrapper in `stable-diffusion-native` first.

## Tests

- `test/unit/backends/llama_cpp/exit_teardown_api_test.dart`: the stage
Expand Down Expand Up @@ -120,3 +126,147 @@ unprotected at a direct C `exit()`.
projector, model.
- `native-exit-teardown` in `doc/testing_matrix.md`: local-only process exits
on Metal, including a C `exit` while a service with a projector disposes.

## Image models

`libstable-diffusion` (`stable-diffusion-native` `v0.2.0-1` and later) keeps a
registry of its own and frees what is left of it during C `exit` on Apple
platforms, like libllamadart. The two libraries embed separate copies of
ggml and tear down independently. The native contract is
`src/sd_dart_wrapper.h` in `stable-diffusion-native`.

### Dart side

`lib/src/backends/stable_diffusion/stable_diffusion_calls.dart` holds every
native call an image worker makes, so a worker can run on a recording
stand-in:

- `sd_dart_new_sd_ctx` creates the context and tracks it inside the call.
`sd_dart_generate_image` is the generation teardown cancels and waits for.
`sd_dart_cancel_generation` cancels from the calling isolate and does
nothing for a context that was already freed. `sd_dart_exit_free` frees a
tracked context once; it is also the free function of the worker's
`IsolateShutdownReleases` hold.
- `sd_dart_progress_enable` and `sd_dart_progress_read`: see "Image
progress".
- Upstream calls that return at once: `sd_ctx_params_init`,
`sd_ctx_supports_image_generation` and `sd_get_model_version_name` right
after the load, `sd_img_gen_params_init` and `free_sd_images`.

`StableDiffusionCalls.tryResolve` binds the six `sd_dart_` functions through
the addresses it resolves, all or nothing. There is no fallback to the
upstream functions, unlike the llama.cpp backend: without the recorder a
runtime reports progress only through a Dart callback, which is the abort the
recorder removes, and without the callback the engine would report a
generation as successful while it emits none of the documented progress
events. `probeStableDiffusionRuntime` therefore reports such a runtime as
unavailable and names `v0.2.0-1`
(`StableDiffusionCalls.minimumNativeRelease`), and
`StableDiffusionImageWorker.start` throws the same
`LlamaUnsupportedException`. No supported configuration reaches an older
runtime: the hook downloads the pinned archives by checksum, this runtime has
no tag or path override, and the build rejects an Apple companion whose pin
differs from the core pin.

`sd_dart_exit_teardown`, `sd_dart_exit_call_begin`, `sd_dart_exit_call_end`,
`sd_dart_exit_track` and `sd_dart_exit_untrack` are excluded from the
bindings (`ffigen_stable_diffusion.yaml`): none is safe from an isolate that
can be killed. `sd_dart_exit_set_wait_ms` is bound and not called; the
runtime's default waits apply.

### What teardown waits for

- With no call in flight it frees the tracked contexts at once.
- While `sd_dart_new_sd_ctx` or `sd_dart_generate_image` is in flight it
waits up to 15 seconds and asks the generation to cancel every 20 ms.
stable-diffusion.cpp reads a cancel only before a sampling step and before
the decode of each image, and a load cannot be cancelled, so the wait is as
long as the phase that is running. A phase that outlasts the 15 seconds
makes teardown free nothing, and ggml-metal aborts as before.
- It waits up to two seconds for an `sd_dart_exit_free` in flight, and gives
a thread 250 ms after its last such call, which covers the short upstream
calls after a load.
- The two runtimes wait one after the other: with a llama.cpp call and an
image generation both in flight an exit can take about 17.5 seconds.

### Which exits are covered for image models

Measured on an M4 Max on Metal with SDXS and SD-Turbo; "before" is native
`v0.2.0` with the Dart progress callback.

| Exit | Before | Now |
| --- | --- | --- |
| Dart program returns from `main`, or dies of an unhandled error, with a model idle | Clean: the worker isolate's hold frees the context | The same |
| Dart program dies of an unhandled error while a model loads or generates | VM abort in the progress callback | Clean, once the native call returns. Nothing cancels the generation: the process ends when the generation does |
| Flutter macOS quit (`-[NSApplication terminate:]`) with a model idle | Clean | Clean |
| Flutter macOS quit while generating | VM abort in the progress callback | Clean, after the whole generation: the engine shuts the isolates down before C `exit`, so teardown's cancel never runs |
| Flutter macOS quit inside a load | VM abort in the progress callback | Clean: teardown frees the context the killed worker never held |
| Flutter hot restart inside a load, then quit | Crash at the restart (`Callback invoked after it has been deleted`) | Clean: the context of the discarded isolate stays tracked and teardown frees it |
| C `exit()` while the worker isolate is alive (through FFI, or a native host that skips the engine shutdown), model idle, loading or generating | ggml-metal abort | Clean within the waits above; a phase longer than 15 seconds aborts as before |
| `exit()` from `dart:io` | No static destructors run: no abort | The same |

So the 15 second wait applies only to a direct C `exit()`. A Dart or Flutter
exit waits for the native call itself, however long the generation is, which
is why the guides still tell apps to dispose an `ImageGenerationEngine` from
`onExitRequested`. A Flutter hot restart during a generation waits the same
way: the restart happens once the generation has finished. The wait after a
quit, a hot restart or an unhandled error is the rest of the generation; the
times measured with SDXS and SD-Turbo are examples, not a bound. A
one-argument native cancel that could run as a `NativeFinalizer` of the
calling isolate would let llamadart cancel a generation on those paths;
`sd_dart_cancel_generation` takes two arguments.

### Image progress

stable-diffusion.cpp reports progress through one process-wide callback on
the thread that loads or generates. A Dart callback there cannot be made
safe: the VM may already be shutting down, and the process aborts with
`GetFfiCallbackMetadata called after shutdown`. The runtime instead records
the reports in a ring, and Dart reads them:

- `StableDiffusionImageWorker.start` calls `sd_dart_progress_enable` on the
calling isolate before it spawns the worker. The first call registers the
recorder, unsynchronized, so it has to precede any load; it also keeps the
runtime from printing progress bars. Nothing in llamadart calls
`sd_set_progress_callback`, which would replace the recorder.
- `generate` asks for the newest sequence number before it sends the
request, reads the reports after it every 50 ms and once more after the
reply, and calls `onProgress(step, steps)` for each in order. One poll
makes at most 64 reads of 64 reports, which is the 4095 reports the runtime
keeps, so a runtime that reports faster than it is read cannot hold the
calling isolate.
- Reports are numbered. When the first report of a read does not follow the
last one read, the runtime dropped the ones in between: the worker delivers
what is left in order and logs one warning with the count. A request at
the limits (`maxCount` images of `maxSteps` steps) records 2416 reports, so
one generation cannot overflow on its own; a second isolate generating at
the same time could, and so could a tiled decode, which llamadart does not
request but stable-diffusion.cpp falls back to when a decode fails with
`GGML_STATUS_ALLOC_FAILED`. The effect is at most that warning and a gap
in the progress events.
- Reports are process-wide, loads included. The engine's one-operation guard
keeps one isolate from mixing two operations; two isolates that generate at
once each see both runs' reports.
- stable-diffusion.cpp clears a cancel request when a generation starts. A
cancel that arrived before then is applied again by each poll until the
generation ends, so it lands at most one poll interval after the runtime
started, whether or not a report arrives.

### Tests

- `test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart`: the
lookup requests the six names and resolves nothing when one is missing;
each member calls the function exported under its own name; the generated
bindings leave out the five unbound functions and mark only
`sd_dart_progress_read` as a leaf call.
- `test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart`:
the worker's two isolates on `test/support/fake_stable_diffusion_runtime.dart`,
with a progress timer the test fires by hand. The whole call sequence of
each isolate is compared for a load, a generation, a batch of three, a
cancel before the runtime starts and one during a generation, dispose, a
failed load, a model that cannot generate images and a runtime without the
functions.
- The root package does not bundle the runtime, so no default-CI test
resolves the real exports. `image-exit-teardown` in
`doc/testing_matrix.md` does, locally on Metal, along with the process
exits.
33 changes: 33 additions & 0 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ Pick targeted rows based on the touched surface:
| Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export |
| Decision engine, decision head, or safetensors reader | `decision-model-smoke` |
| Image generation API or `stable_diffusion` runtime | `image-generation-smoke`, `native-hook-bundles` |
| `stable_diffusion` runtime pin, image worker native calls, progress polling, exit or isolate shutdown | `image-exit-teardown`, `image-generation-smoke` |
| Chat-app image screen or image model downloads | `chat-app-image-generation-smoke` |
| Chat-app microphone transcription flow | `chat-app-microphone-transcription-smoke` |
| Chat-app live LiteRT-LM dictation | `litert-lm-asr-smoke`, `chat-app-live-speech-smoke` |
Expand Down Expand Up @@ -573,6 +574,38 @@ enables `quit-decision` (one with a decision head loaded).
`dart:io`'s `exit` is not one of the scenarios: it does not run the static
destructors that make ggml-metal abort.

### Image model exit teardown

```bash
dart run tool/testing/run_local_e2e.dart --scenario image-exit-teardown \
--model-path /path/to/sdxs-512-tinySDdistilled_Q8_0.gguf
```

This local-only macOS row runs in `example/basic_app`, which opts into the
stable_diffusion runtime. It runs
`example/basic_app/test/fixtures/image_exit_probe.dart` as a child process and
ends it while an image model is alive on Metal: C `exit` through FFI from the
main isolate with the model idle, generating, loading, or already disposed;
an unhandled error while generating or loading; and an isolate killed inside
the native load. Each run must reach its exit point, print neither
`GGML_ASSERT` nor `GetFfiCallbackMetadata`, and end with exit code 0, or 255
for the unhandled errors. The loading scenarios time a second load of the
model and exit halfway through a third, because the first load of a process
also sets up Metal. As in the llama.cpp row, the C `exit` scenarios model a
native host that exits without shutting Dart down, not a Flutter quit
([exit teardown](llama_cpp_exit_teardown.md#image-models)).

The row also checks that each `sd_dart_` function `StableDiffusionCalls`
looks up resolves to the runtime's own export of that name, which default CI
cannot (the root package does not bundle the runtime), and that batches of
two and three images report every sampling step in order and end with the
`decoding` event.

`IMAGE_EXIT_RUNS` sets the runs of each exit scenario (default 3). A run fails
when the process is still alive after two minutes. `quit-both-loaded`, a C
`exit` with a llama.cpp model loaded as well, is reported as skipped unless
`IMAGE_EXIT_GGUF` names a GGUF chat model the GPU loads.

### Native prompt-evaluation cancel

```bash
Expand Down
1 change: 1 addition & 0 deletions example/basic_app/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies:
sqlite_vector: ^0.9.85

dev_dependencies:
ffi: ^2.1.0
lints: ^6.1.0
test: ^1.26.3

Expand Down
Loading
Loading