From ba4b0d7525f78f54beb89d70c3109a2e528e7c48 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 19:05:50 -0400 Subject: [PATCH 1/8] fix: start a LiteRT-LM generation requested right after a cancel A cancelled LiteRT-LM generation keeps running until its native run stops. On native, a subscription cancel cleared the Dart guard at once while the worker kept generationInFlight set, so the next generation got the worker's 'state' error; after cancelGeneration() the Dart guard itself rejected it. On Web, the active conversation cleared only in the generator's finally. Each path surfaced a raw StateError, wrapped by LlamaEngine as LlamaInferenceException('Generation failed'). A generation requested while a cancelled run is still stopping now waits for it, then starts: on native until the worker's terminal response, on Web until the cancelled run's stream ends. cancelGeneration(), dispose() and model or context teardown end a waiting generation without running it. A subscription cancel cancels only its own run. Overlapping a generation that was not cancelled, or queueing a second one, throws LlamaStateException. A cancel before the request reaches the worker, or before the Web prompt is sent, now ends the stream without running it. Closes #656 --- CHANGELOG.md | 8 + .../backends/litert_lm/litert_lm_backend.dart | 335 ++++++----- .../litert_lm/litert_lm_backend_web.dart | 123 +++- .../litert_lm/litert_lm_backend_test.dart | 480 ++++++++++++++- .../litert_lm/litert_lm_backend_web_test.dart | 545 ++++++++++++++++++ website/docs/changelog/recent-releases.md | 8 + .../docs/guides/generation-and-streaming.md | 11 +- 7 files changed, 1338 insertions(+), 172 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e09024cbf..f31b5ec0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## Unreleased + +- Start a LiteRT-LM generation requested right after a cancel, on native and + Web, once the cancelled run stops, instead of failing with a wrapped + `StateError` (`generation is already in progress`). An overlap with a + running generation that was not cancelled now throws `LlamaStateException` + ([#656](https://github.com/leehack/llamadart/issues/656)). + ## 0.13.0 - Pair this release with Apple companions `llamadart_llama_cpp_flutter`, diff --git a/lib/src/backends/litert_lm/litert_lm_backend.dart b/lib/src/backends/litert_lm/litert_lm_backend.dart index 645a24c79..b97a9cb07 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend.dart @@ -45,6 +45,8 @@ class LiteRtLmBackend Future? _disposeFuture; int _workerGeneration = 0; void Function([Object? error])? _activeGenerationCleanup; + _WorkerGeneration? _runningGeneration; + _QueuedGeneration? _queuedGeneration; final Map> _pendingRequests = {}; final String? _preferredBackend; final void Function(SendPort) _workerEntryPoint; @@ -196,95 +198,15 @@ class LiteRtLmBackend String prompt, GenerationParams params, { List? parts, - }) { - late final StreamController> controller; - ReceivePort? responsePort; - var cleanedUp = false; - var activeGeneration = false; - - void cleanup([Object? error]) { - if (cleanedUp) { - return; - } - cleanedUp = true; - responsePort?.close(); - if (!controller.isClosed) { - if (error != null) controller.addError(error); - unawaited(controller.close()); - } - if (_activeGenerationCleanup == cleanup) { - _activeGenerationCleanup = null; - } - } - - controller = StreamController>( - onListen: () { - if (_activeGenerationCleanup != null) { - controller.addError( - StateError('LiteRT-LM generation is already in progress.'), - ); - cleanup(); - return; - } - - final port = ReceivePort(); - responsePort = port; - port.listen((message) { - if (cleanedUp) { - return; - } - if (message is LiteRtLmTokenResponse) { - controller.add(message.bytes); - } else if (message is LiteRtLmDoneResponse) { - cleanup(); - } else if (message is LiteRtLmErrorResponse) { - controller.addError(_exceptionForErrorResponse(message)); - cleanup(); - } - }); - - activeGeneration = true; - _activeGenerationCleanup = cleanup; - unawaited(() async { - try { - await _ensureIsolate(); - // Re-check after the await: a cancel during _ensureIsolate() runs - // cleanup(), which closes the response port and may clear - // _sendPort. Capture the port and guard in one synchronous step so - // we never send a generate request to a closed port (which would - // orphan a generation on the worker) or dereference a null port. - final sendPort = _sendPort; - if (cleanedUp || sendPort == null) { - cleanup(); - return; - } - sendPort.send( - LiteRtLmGenerateRequest( - contextHandle, - prompt, - params, - port.sendPort, - parts: parts, - ), - ); - } catch (error, stackTrace) { - if (!controller.isClosed) { - controller.addError(error, stackTrace); - } - cleanup(); - } - }()); - }, - onCancel: () { - if (activeGeneration) { - cancelGeneration(); - } - cleanup(); - }, - ); - - return controller.stream; - } + }) => _generateOnWorker( + (sendPort) => LiteRtLmGenerateRequest( + contextHandle, + prompt, + params, + sendPort, + parts: parts, + ), + ); @override Stream> generateChat( @@ -302,104 +224,165 @@ class LiteRtLmBackend String? targetLangCode, DateTime? templateNow, }) { - late final StreamController> controller; - ReceivePort? responsePort; - var cleanedUp = false; - var activeGeneration = false; final nativeTools = tools ?.map((tool) => tool.toJson()) .toList(growable: false); + return _generateOnWorker( + (sendPort) => LiteRtLmGenerateChatRequest( + contextHandle, + messages, + params, + sendPort, + tools: nativeTools, + toolChoice: toolChoice, + parallelToolCalls: parallelToolCalls, + enableThinking: enableThinking, + chatTemplateKwargs: chatTemplateKwargsWithLanguageCodes( + chatTemplateKwargs, + sourceLangCode: sourceLangCode, + targetLangCode: targetLangCode, + ), + templateNow: templateNow, + ), + ); + } + + /// Streams the worker generation that [buildRequest] describes. + /// + /// A generation listened to while a cancelled one is still running on the + /// worker waits for that run's terminal response, then starts. + Stream> _generateOnWorker( + LiteRtLmWorkerRequest Function(SendPort responsePort) buildRequest, + ) { + late final StreamController> controller; + _WorkerGeneration? generation; + _QueuedGeneration? queued; + var closed = false; - void cleanup([Object? error]) { - if (cleanedUp) { + void close([Object? error]) { + if (closed) { return; } - cleanedUp = true; - responsePort?.close(); + closed = true; if (!controller.isClosed) { if (error != null) controller.addError(error); unawaited(controller.close()); } - if (_activeGenerationCleanup == cleanup) { + if (_activeGenerationCleanup == close) { _activeGenerationCleanup = null; } } + void start() { + final port = ReceivePort(); + final current = _WorkerGeneration(port); + generation = current; + _runningGeneration = current; + _activeGenerationCleanup = close; + port.listen((message) { + if (message is LiteRtLmTokenResponse) { + if (!closed) controller.add(message.bytes); + } else if (message is LiteRtLmDoneResponse) { + close(); + _finishGeneration(current); + } else if (message is LiteRtLmErrorResponse) { + close(_exceptionForErrorResponse(message)); + _finishGeneration(current); + } + }); + + unawaited(() async { + try { + await _ensureIsolate(); + // Re-check after the await: a cancel during _ensureIsolate() may + // have closed this stream or cleared _sendPort. Capture the port and + // guard in one synchronous step so a cancelled generation never + // reaches the worker and a closed port is never sent to. + final sendPort = _sendPort; + if (closed || current.cancelRequested || sendPort == null) { + close(); + _finishGeneration(current); + return; + } + sendPort.send(buildRequest(port.sendPort)); + } catch (error, stackTrace) { + if (!closed && !controller.isClosed) { + controller.addError(error, stackTrace); + } + close(); + _finishGeneration(current); + } + }()); + } + controller = StreamController>( onListen: () { - if (_activeGenerationCleanup != null) { - controller.addError( - StateError('LiteRT-LM generation is already in progress.'), + final running = _runningGeneration; + if (_queuedGeneration != null || + (running != null && !running.cancelRequested)) { + close( + LlamaStateException( + 'LiteRT-LM generation is already in progress. Cancel it or ' + 'wait for its stream to end before starting another.', + ), ); - cleanup(); return; } - - final port = ReceivePort(); - responsePort = port; - port.listen((message) { - if (cleanedUp) { - return; - } - if (message is LiteRtLmTokenResponse) { - controller.add(message.bytes); - } else if (message is LiteRtLmDoneResponse) { - cleanup(); - } else if (message is LiteRtLmErrorResponse) { - controller.addError(_exceptionForErrorResponse(message)); - cleanup(); - } - }); - - activeGeneration = true; - _activeGenerationCleanup = cleanup; - unawaited(() async { - try { - await _ensureIsolate(); - final sendPort = _sendPort; - if (cleanedUp || sendPort == null) { - cleanup(); - return; - } - sendPort.send( - LiteRtLmGenerateChatRequest( - contextHandle, - messages, - params, - port.sendPort, - tools: nativeTools, - toolChoice: toolChoice, - parallelToolCalls: parallelToolCalls, - enableThinking: enableThinking, - chatTemplateKwargs: chatTemplateKwargsWithLanguageCodes( - chatTemplateKwargs, - sourceLangCode: sourceLangCode, - targetLangCode: targetLangCode, - ), - templateNow: templateNow, - ), - ); - } catch (error, stackTrace) { - if (!controller.isClosed) { - controller.addError(error, stackTrace); - } - cleanup(); - } - }()); + if (running == null) { + start(); + return; + } + final waiting = _QueuedGeneration(start, close); + queued = waiting; + _queuedGeneration = waiting; }, onCancel: () { - if (activeGeneration) { - cancelGeneration(); + final current = generation; + if (current == null) { + if (_queuedGeneration == queued) { + _queuedGeneration = null; + } + } else if (identical(_runningGeneration, current) && + !current.cancelRequested) { + // Raises only this run's cancel, so a generation queued behind it + // still starts once the worker reports that the run stopped. + current.cancelRequested = true; + unawaited(_cancelGeneration()); } - cleanup(); + close(); }, ); return controller.stream; } + /// Releases [generation] after its terminal response, or when it never + /// reached the worker, and starts the generation queued behind it. + void _finishGeneration(_WorkerGeneration generation) { + generation.responsePort.close(); + if (!identical(_runningGeneration, generation)) { + return; + } + _runningGeneration = null; + final queued = _queuedGeneration; + if (queued == null) { + return; + } + _queuedGeneration = null; + queued.start(); + } + + /// Ends the generation waiting for a cancelled run without starting it. + void _closeQueuedGeneration([Object? error]) { + final queued = _queuedGeneration; + _queuedGeneration = null; + queued?.close(error); + } + @override void cancelGeneration() { + _runningGeneration?.cancelRequested = true; + _closeQueuedGeneration(); unawaited(_cancelGeneration()); } @@ -603,6 +586,8 @@ class LiteRtLmBackend Future _disposeWorker() async { _disposed = true; + _runningGeneration?.cancelRequested = true; + _closeQueuedGeneration(); await _cancelGeneration(); _activeGenerationCleanup?.call(); @@ -882,9 +867,14 @@ class LiteRtLmBackend void _killWorker() { if (_pendingRequests.isNotEmpty) _nativeSettlementUnverified = true; - _activeGenerationCleanup?.call( - _nativeSettlementUnverified ? _unsettledWorkerError() : null, - ); + final generationError = _nativeSettlementUnverified + ? _unsettledWorkerError() + : null; + _activeGenerationCleanup?.call(generationError); + _closeQueuedGeneration(generationError); + // A killed worker sends no terminal response for the running generation. + _runningGeneration?.responsePort.close(); + _runningGeneration = null; // A killed worker cannot reply. Closing its callers' ports alone would // leave their futures pending, while leaving ports open retains the VM. // This settles Dart requests only; an in-flight native call may still be @@ -916,10 +906,12 @@ class LiteRtLmBackend ); Future _cancelActiveGeneration() async { + _closeQueuedGeneration(); final cleanup = _activeGenerationCleanup; if (cleanup == null) { return; } + _runningGeneration?.cancelRequested = true; await _cancelGeneration(); cleanup(); } @@ -998,3 +990,26 @@ class LiteRtLmBackend return backend; } } + +/// A generation sent to the worker, tracked until its terminal response even +/// after its stream closes. +final class _WorkerGeneration { + /// Receives the worker's responses for this generation. + final ReceivePort responsePort; + + /// Whether this generation was cancelled. + bool cancelRequested = false; + + _WorkerGeneration(this.responsePort); +} + +/// A generation waiting for the worker to finish a cancelled run. +final class _QueuedGeneration { + /// Sends the generation to the worker. + final void Function() start; + + /// Ends the generation's stream without output, or with [error]. + final void Function([Object? error]) close; + + _QueuedGeneration(this.start, this.close); +} diff --git a/lib/src/backends/litert_lm/litert_lm_backend_web.dart b/lib/src/backends/litert_lm/litert_lm_backend_web.dart index e3814705d..4411add86 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend_web.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend_web.dart @@ -66,6 +66,8 @@ class LiteRtLmBackend _LiteRtLmWebEngine? _engine; _LiteRtLmWebConversation? _activeConversation; + _LiteRtLmWebRun? _activeRun; + _LiteRtLmWebRun? _queuedRun; LlamaLogLevel _logLevel = LlamaLogLevel.warn; bool _isReady = false; bool _hasContext = false; @@ -244,6 +246,7 @@ class LiteRtLmBackend _requireContextHandle(contextHandle); _hasContext = false; _contextHandle = null; + _closeQueuedRun(); final conversation = _activeConversation; _activeConversation = null; if (conversation != null) { @@ -263,7 +266,68 @@ class LiteRtLmBackend String prompt, GenerationParams params, { List? parts, - }) async* { + }) { + final run = _LiteRtLmWebRun(); + late final StreamController> controller; + StreamSubscription>? subscription; + controller = StreamController>( + onListen: () { + if (_activeRun == null) { + _startRun(run); + } else if (_cancelRequested && _queuedRun == null) { + _queuedRun = run; + } else { + controller + ..addError( + LlamaStateException( + 'LiteRT-LM web generation is already in progress. Cancel it ' + 'or wait for its stream to end before starting another.', + ), + ) + ..close(); + return; + } + subscription = _generateRun(run, contextHandle, prompt, params, parts) + .listen( + controller.add, + onError: controller.addError, + onDone: () { + _finishRun(run); + unawaited(controller.close()); + }, + ); + }, + onPause: () => subscription?.pause(), + onResume: () => subscription?.resume(), + onCancel: () { + if (identical(_queuedRun, run)) { + _closeQueuedRun(); + } else if (identical(_activeRun, run)) { + // Cancels only this run, so a generation queued behind it still + // starts once it ends. + _cancelActiveRun(); + } + // Nobody listens any more, so an error the cancelled run ends with + // has no caller to reach. + return subscription + ?.cancel() + .catchError((Object _) {}) + .whenComplete(() => _finishRun(run)); + }, + ); + return controller.stream; + } + + /// Runs one generation for [generate]. + /// + /// A queued [run] waits until the cancelled run ahead of it ends. + Stream> _generateRun( + _LiteRtLmWebRun run, + int contextHandle, + String prompt, + GenerationParams params, + List? parts, + ) async* { final engine = _requireContextHandle(contextHandle); if (parts?.any((part) => part is LlamaVideoContent) ?? false) { throw UnsupportedError( @@ -280,11 +344,10 @@ class LiteRtLmBackend if (params.maxTokens <= 0) { return; } - if (_activeConversation != null) { - throw StateError('LiteRT-LM web generation is already in progress.'); + if (!identical(_activeRun, run) && !await run.admission.future) { + return; } - _cancelRequested = false; final conversation = await engine .createConversation(_createConversationConfig(params)) .toDart; @@ -294,13 +357,16 @@ class LiteRtLmBackend .where((sequence) => sequence.isNotEmpty) .toList(growable: false); try { + if (_cancelRequested) { + return; + } final stream = _withScopedConsoleGuardedStream( _streamConversation(conversation, prompt), ); await for (final chunk in _applyStopSequences( stream, stopSequences, - onStop: cancelGeneration, + onStop: _cancelActiveRun, )) { if (_cancelRequested) { break; @@ -315,8 +381,37 @@ class LiteRtLmBackend } } - @override - void cancelGeneration() { + void _startRun(_LiteRtLmWebRun run) { + _activeRun = run; + _cancelRequested = false; + } + + /// Ends [run] and starts the generation queued behind it. + void _finishRun(_LiteRtLmWebRun run) { + if (identical(_queuedRun, run)) { + _queuedRun = null; + } + if (!identical(_activeRun, run)) { + return; + } + _activeRun = null; + final queued = _queuedRun; + if (queued == null) { + return; + } + _queuedRun = null; + _startRun(queued); + queued.admission.complete(true); + } + + /// Ends the generation waiting for a cancelled run without starting it. + void _closeQueuedRun() { + final queued = _queuedRun; + _queuedRun = null; + queued?.admission.complete(false); + } + + void _cancelActiveRun() { _cancelRequested = true; try { _activeConversation?.cancel(); @@ -325,6 +420,12 @@ class LiteRtLmBackend } } + @override + void cancelGeneration() { + _cancelActiveRun(); + _closeQueuedRun(); + } + @override Future> tokenize( int modelHandle, @@ -896,6 +997,7 @@ class LiteRtLmBackend } Future _disposeEngine() async { + _closeQueuedRun(); final conversation = _activeConversation; _activeConversation = null; if (conversation != null) { @@ -1393,6 +1495,13 @@ class LiteRtLmBackend } } +/// One [LiteRtLmBackend.generate] call. +final class _LiteRtLmWebRun { + /// Completes with true when a queued run may start, or false when it ends + /// without starting. + final Completer admission = Completer(); +} + @JS() extension type _LiteRtLmConsoleGuard._(JSObject _) implements JSObject { external void restore(); diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index c95e93881..047297692 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1118,7 +1118,7 @@ void main() { await expectLater( backend.generate(1, 'second', const GenerationParams()).drain(), throwsA( - isA().having( + isA().having( (error) => error.message, 'message', contains('already in progress'), @@ -1548,6 +1548,377 @@ void main() { worker.close(); } }); + group('a generation started after a cancel', () { + const params = GenerationParams(streamBatchTokenThreshold: 1); + late _CancellableRunService service; + late LiteRtLmBackend backend; + + setUp(() async { + service = _CancellableRunService(); + backend = LiteRtLmBackend( + initialSendPort: await _startWorkerInCurrentIsolate(service), + ); + }); + + tearDown(() async { + service.finishAll(); + await backend.dispose(); + }); + + test('waits for a run stopped by cancelGeneration, then starts', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(service.runs, hasLength(1)); + expect(second.error, isNull); + + firstRun.finish(); + await first.done; + expect(first.error, isNull); + expect(first.text, 'first;'); + + final secondRun = await service.started(1); + expect(secondRun.prompt, 'second'); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'waits for a run stopped by a subscription cancel, then starts', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + await first.subscription.cancel(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(service.runs, hasLength(1)); + expect(service.cancelCount, greaterThanOrEqualTo(1)); + expect(second.error, isNull); + + firstRun.finish(); + final secondRun = await service.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }, + ); + + test('waits for a native chat run stopped by cancelGeneration', () async { + final first = _CollectedGeneration( + backend.generateChat(1, [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'chat'), + ], params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(service.runs, hasLength(1)); + + firstRun.finish(); + await first.done; + expect(first.error, isNull); + final secondRun = await service.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test('a cancel before the request reaches the worker ends the stream ' + 'without running it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + backend.cancelGeneration(); + await first.done; + expect(first.error, isNull); + expect(first.text, isEmpty); + expect(service.runs, isEmpty); + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await service.started(0); + expect(secondRun.prompt, 'second'); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'a cancel after completion does not affect the next generation', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + (await service.started(0)).finish(); + await first.done; + expect(first.text, 'first;'); + + backend.cancelGeneration(); + await _settle(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await service.started(1); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }, + ); + + test('repeated cancels queue the next generation once', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend + ..cancelGeneration() + ..cancelGeneration(); + await first.subscription.cancel(); + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(service.runs, hasLength(1)); + + firstRun.finish(); + final secondRun = await service.started(1); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + expect(service.runs, hasLength(2)); + }); + + test('a subscription cancel of the cancelled run does not end the ' + 'generation queued behind it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await first.subscription.cancel(); + await _settle(); + expect(second.isDone, isFalse); + + firstRun.finish(); + final secondRun = await service.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'cancelGeneration ends a queued generation without running it', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + backend.cancelGeneration(); + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + + firstRun.finish(); + await first.done; + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + final thirdRun = await service.started(1); + expect(thirdRun.prompt, 'third'); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(service.runs.map((run) => run.prompt), ['first', 'third']); + }, + ); + + test( + 'a subscription cancel of a queued generation leaves the queue', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + await second.subscription.cancel(); + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + await _settle(); + expect(third.error, isNull); + + firstRun.finish(); + final thirdRun = await service.started(1); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(service.runs.map((run) => run.prompt), ['first', 'third']); + }, + ); + + test('dispose ends a queued generation without running it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + + final disposed = backend.dispose(); + firstRun.finish(); + await disposed; + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + expect(service.runs, hasLength(1)); + }); + + test('overlapping a generation that was not cancelled throws ' + 'LlamaStateException', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await second.done; + expect( + second.error, + isA().having( + (error) => error.message, + 'message', + contains('already in progress'), + ), + ); + + firstRun.finish(); + await first.done; + expect(first.error, isNull); + expect(first.text, 'first;'); + expect(service.runs, hasLength(1)); + }); + + test('a second generation queued behind a cancel throws ' + 'LlamaStateException', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await third.done; + expect(third.error, isA()); + + firstRun.finish(); + final secondRun = await service.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + expect(service.runs.map((run) => run.prompt), ['first', 'second']); + }); + }); + + test('LlamaEngine starts a generation requested right after ' + 'cancelGeneration', () async { + final worker = _FakeLiteRtLmWorker( + tokenizeResponse: const [], + detokenizeResponse: '', + holdGeneration: true, + generationChunks: [utf8.encode('Hi')], + ); + final backend = LiteRtLmBackend(initialSendPort: worker.sendPort); + final engine = LlamaEngine(backend); + + try { + await engine.loadModel(modelFile.path); + final firstDone = Completer(); + final first = engine + .generate('first') + .listen( + (_) {}, + onError: firstDone.completeError, + onDone: firstDone.complete, + ); + await worker.generateReceived.future; + + engine.cancelGeneration(); + final second = engine.generate('second').join(); + await _settle(); + expect( + worker.requests.whereType(), + hasLength(1), + ); + + worker.releaseGeneration(); + await firstDone.future; + await first.cancel(); + expect(await second, 'Hi'); + expect( + worker.requests.whereType().map( + (request) => request.prompt, + ), + ['first', 'second'], + ); + } finally { + worker.releaseGeneration(); + await backend.dispose(); + worker.close(); + } + }); } String _expectedAutoLiteRtLmBackend() { @@ -1797,3 +2168,110 @@ void _exitOnCancelWorker(SendPort port) { } }); } + +Future _settle() => + Future.delayed(const Duration(milliseconds: 20)); + +Future _startWorkerInCurrentIsolate(LiteRtLmService service) async { + final receivePort = ReceivePort(); + runLiteRtLmWorkerForTesting( + receivePort.sendPort, + service, + exitOnDispose: false, + ); + final sendPort = await receivePort.first as SendPort; + receivePort.close(); + sendPort.send(LiteRtLmWorkerHandshake(LlamaLogLevel.warn)); + return sendPort; +} + +final class _CollectedGeneration { + _CollectedGeneration(Stream> stream) { + subscription = stream.listen( + (bytes) { + _bytes.addAll(bytes); + if (!_firstChunk.isCompleted) _firstChunk.complete(); + }, + onError: (Object error) => this.error = error, + onDone: _done.complete, + ); + } + + late final StreamSubscription> subscription; + final List _bytes = []; + final Completer _firstChunk = Completer(); + final Completer _done = Completer(); + Object? error; + + String get text => utf8.decode(_bytes); + bool get isDone => _done.isCompleted; + Future get firstChunk => + _firstChunk.future.timeout(const Duration(seconds: 2)); + Future get done => _done.future.timeout(const Duration(seconds: 2)); +} + +final class _ServiceRun { + _ServiceRun(this.prompt); + + final String prompt; + final Completer _stopped = Completer(); + + void finish() { + if (!_stopped.isCompleted) _stopped.complete(); + } +} + +/// Streams one token per run, then holds the run open until the test calls +/// [_ServiceRun.finish], like a native run that takes time to stop after a +/// cancel. +class _CancellableRunService extends LiteRtLmService { + final List<_ServiceRun> runs = <_ServiceRun>[]; + final List> _started = List.generate( + 8, + (_) => Completer<_ServiceRun>(), + ); + int cancelCount = 0; + + Future<_ServiceRun> started(int index) => + _started[index].future.timeout(const Duration(seconds: 2)); + + void finishAll() { + for (final run in runs) { + run.finish(); + } + } + + Stream> _run(String prompt) async* { + final run = _ServiceRun(prompt); + runs.add(run); + _started[runs.length - 1].complete(run); + yield utf8.encode('$prompt;'); + await run._stopped.future; + } + + @override + Stream> generate( + int contextHandle, + String prompt, + GenerationParams params, { + List? parts, + }) => _run(prompt); + + @override + Stream> generateChat( + int contextHandle, + List messages, + GenerationParams params, { + List>? tools, + ToolChoice toolChoice = ToolChoice.auto, + bool parallelToolCalls = false, + bool enableThinking = true, + Map? chatTemplateKwargs, + DateTime? templateNow, + }) => _run(messages.last.content); + + @override + void cancelGeneration() { + cancelCount += 1; + } +} diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 82d3c59dd..9bb02cc18 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1,6 +1,7 @@ @TestOn('browser') library; +import 'dart:async'; import 'dart:convert'; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; @@ -1319,6 +1320,382 @@ void main() { }, ); + group('a generation started after a cancel', () { + const params = GenerationParams(maxTokens: 16); + late _QueueFakeEngine fake; + late LiteRtLmBackend backend; + + Future load({bool rejectOnCancel = false}) async { + fake = _installQueueFakeEngine(rejectOnCancel: rejectOnCancel); + backend = LiteRtLmBackend(); + const modelParams = ModelParams(); + await backend.modelLoadFromUrl( + 'https://example.com/model.litertlm', + modelParams, + ); + await backend.contextCreate(1, modelParams); + } + + setUp(load); + + tearDown(() async { + fake.finishAll(); + await backend.dispose(); + }); + + test('waits for a run stopped by cancelGeneration, then starts', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + expect(firstRun.cancelCalls, 1); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(fake.runs, hasLength(1)); + expect(second.error, isNull); + + firstRun.finish(); + await first.done; + expect(first.error, isNull); + expect(first.text, 'first;'); + + final secondRun = await fake.started(1); + expect(secondRun.prompt, 'second'); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'waits for a run stopped by a subscription cancel, then starts', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + final firstCancelled = first.subscription.cancel(); + expect(firstRun.cancelCalls, 1); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(fake.runs, hasLength(1)); + expect(second.error, isNull); + + firstRun.finish(); + await firstCancelled; + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }, + ); + + test('a subscription cancel whose runtime rejects the pending read ' + 'neither surfaces that error nor blocks the next generation', () async { + await backend.dispose(); + await load(rejectOnCancel: true); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + await first.subscription.cancel(); + expect(firstRun.cancelCalls, 1); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test('a cancel before the first token ends the stream without sending ' + 'the prompt', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + backend.cancelGeneration(); + await first.done; + expect(first.error, isNull); + expect(first.text, isEmpty); + expect(fake.runs, isEmpty); + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await fake.started(0); + expect(secondRun.prompt, 'second'); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'a cancel after completion does not affect the next generation', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + (await fake.started(0)).finish(); + await first.done; + expect(first.text, 'first;'); + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await fake.started(1); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + expect(secondRun.cancelCalls, 0); + }, + ); + + test('repeated cancels queue the next generation once', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend + ..cancelGeneration() + ..cancelGeneration(); + final firstCancelled = first.subscription.cancel(); + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(fake.runs, hasLength(1)); + + firstRun.finish(); + await firstCancelled; + final secondRun = await fake.started(1); + await second.firstChunk; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + expect(fake.runs, hasLength(2)); + }); + + test('a stop sequence in the cancelled run does not end the generation ' + 'queued behind it', () async { + final first = _CollectedGeneration( + backend.generate( + 1, + 'first', + const GenerationParams(maxTokens: 16, stopSequences: ['#']), + ), + ); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + + // A one-character stop sequence holds no text back, so the tail's + // match reaches onStop before the cancelled run's loop breaks. + firstRun.finish(tail: '#'); + await first.done; + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test( + 'cancelGeneration ends a queued generation without running it', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + backend.cancelGeneration(); + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + + firstRun.finish(); + await first.done; + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + final thirdRun = await fake.started(1); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(fake.runs.map((run) => run.prompt), ['first', 'third']); + }, + ); + + test( + 'a subscription cancel of a queued generation leaves the queue', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + await second.subscription.cancel(); + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + await _settle(); + expect(third.error, isNull); + + firstRun.finish(); + final thirdRun = await fake.started(1); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(fake.runs.map((run) => run.prompt), ['first', 'third']); + }, + ); + + test('dispose ends a queued generation without running it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + + await backend.dispose(); + firstRun.finish(); + await first.done; + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + expect(fake.runs, hasLength(1)); + }); + + test('overlapping a generation that was not cancelled throws ' + 'LlamaStateException', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await second.done; + expect( + second.error, + isA().having( + (error) => error.message, + 'message', + contains('already in progress'), + ), + ); + + firstRun.finish(); + await first.done; + expect(first.error, isNull); + expect(first.text, 'first;'); + expect(fake.runs, hasLength(1)); + }); + + test('a second generation queued behind a cancel throws ' + 'LlamaStateException', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await third.done; + expect(third.error, isA()); + + firstRun.finish(); + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + expect(fake.runs.map((run) => run.prompt), ['first', 'second']); + }); + }); + + test('LlamaEngine starts a Web generation requested right after ' + 'cancelGeneration', () async { + final fake = _installQueueFakeEngine(); + final engine = LlamaEngine(LiteRtLmBackend()); + try { + await engine.loadModel('https://example.com/model.litertlm'); + final firstDone = Completer(); + final first = engine + .generate('first') + .listen( + (_) {}, + onError: firstDone.completeError, + onDone: firstDone.complete, + ); + final firstRun = await fake.started(0); + await firstRun.holding; + + engine.cancelGeneration(); + final second = engine.generate('second').join(); + await _settle(); + expect(fake.runs, hasLength(1)); + + firstRun.finish(); + await firstDone.future; + await first.cancel(); + (await fake.started(1)).finish(); + expect(await second, 'second;'); + } finally { + fake.finishAll(); + await engine.dispose(); + } + }); + group('ModelParams.device', () { const url = 'https://example.com/gemma-4-E2B-it-web.litertlm'; late List createdBackends; @@ -1565,3 +1942,171 @@ void _clearGlobals() { globalContext.delete('__llamadartLiteRtLmLogLevel'.toJS); globalContext.delete('__llamadartInstallLiteRtLmConsoleGuard'.toJS); } + +Future _settle() => + Future.delayed(const Duration(milliseconds: 20)); + +final class _CollectedGeneration { + _CollectedGeneration(Stream> stream) { + subscription = stream.listen( + (bytes) { + _bytes.addAll(bytes); + if (!_firstChunk.isCompleted) _firstChunk.complete(); + }, + onError: (Object error) => this.error = error, + onDone: _done.complete, + ); + } + + late final StreamSubscription> subscription; + final List _bytes = []; + final Completer _firstChunk = Completer(); + final Completer _done = Completer(); + Object? error; + + String get text => utf8.decode(_bytes); + Future get firstChunk => + _firstChunk.future.timeout(const Duration(seconds: 2)); + Future get done => _done.future.timeout(const Duration(seconds: 2)); +} + +/// One `sendMessageStreaming` run: it streams `'$prompt;'`, then holds its +/// next read until [finish], like a runtime that takes time to stop after a +/// cancel. +final class _QueueFakeRun { + _QueueFakeRun(this.prompt); + + final String prompt; + final Completer _tail = Completer(); + final Completer _holding = Completer(); + int cancelCalls = 0; + + /// Completes once the reader waits on the read that [finish] ends. + Future get holding => + _holding.future.timeout(const Duration(seconds: 2)); + + /// Ends the run, first emitting [tail] when given. + void finish({String? tail}) { + if (!_tail.isCompleted) _tail.complete(tail); + } +} + +final class _QueueFakeEngine { + _QueueFakeEngine({required this.rejectOnCancel}); + + /// Whether `cancel()` rejects the held read, as `@litert-lm/core` 0.18.0 + /// does with its cancelled status. + final bool rejectOnCancel; + final List<_QueueFakeRun> runs = <_QueueFakeRun>[]; + final List> _started = List.generate( + 8, + (_) => Completer<_QueueFakeRun>(), + ); + + Future<_QueueFakeRun> started(int index) => + _started[index].future.timeout(const Duration(seconds: 2)); + + void finishAll() { + for (final run in runs) { + run.finish(); + } + } + + JSObject _conversation() { + _QueueFakeRun? run; + final conversation = JSObject(); + conversation.setProperty( + 'sendMessageStreaming'.toJS, + ((String prompt) { + final current = run = _QueueFakeRun(prompt); + runs.add(current); + _started[runs.length - 1].complete(current); + return _streamOf(current); + }).toJS, + ); + conversation.setProperty( + 'cancel'.toJS, + (() { + final current = run; + if (current == null) return; + current.cancelCalls += 1; + if (rejectOnCancel && !current._tail.isCompleted) { + current._tail.completeError(StateError('Task cancelled')); + } + }).toJS, + ); + conversation.setProperty( + 'delete'.toJS, + (() => Future.value(null).toJS).toJS, + ); + return conversation; + } + + JSObject _streamOf(_QueueFakeRun run) { + final stream = JSObject(); + stream.setProperty( + 'getReader'.toJS, + (() { + var reads = 0; + var tailSent = false; + final reader = JSObject(); + JSObject result({String? text}) { + final result = JSObject(); + result.setProperty('done'.toJS, (text == null).toJS); + if (text != null) { + result.setProperty('value'.toJS, _messageChunk(text)); + } + return result; + } + + reader.setProperty( + 'read'.toJS, + (() { + if (reads++ == 0) { + return Future.value( + result(text: '${run.prompt};'), + ).toJS; + } + if (!run._holding.isCompleted) run._holding.complete(); + return run._tail.future.then((tail) { + if (tail == null || tailSent) return result(); + tailSent = true; + return result(text: tail); + }).toJS; + }).toJS, + ); + reader.setProperty( + 'cancel'.toJS, + (() => Future.value(null).toJS).toJS, + ); + reader.setProperty('releaseLock'.toJS, (() {}).toJS); + return reader; + }).toJS, + ); + return stream; + } +} + +_QueueFakeEngine _installQueueFakeEngine({bool rejectOnCancel = false}) { + final fake = _QueueFakeEngine(rejectOnCancel: rejectOnCancel); + final engineClass = JSObject(); + engineClass.setProperty( + 'create'.toJS, + ((JSObject settings) { + final engine = JSObject(); + engine.setProperty( + 'createConversation'.toJS, + ((JSObject config) => Future.value( + fake._conversation(), + ).toJS).toJS, + ); + engine.setProperty( + 'delete'.toJS, + (() => Future.value(null).toJS).toJS, + ); + return Future.value(engine).toJS; + }).toJS, + ); + globalContext.setProperty('LiteRtLmEngine'.toJS, engineClass); + return fake; +} diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 978bdf0b3..0db4b8faa 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,14 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- Start a LiteRT-LM generation requested right after a cancel, on native and + Web, once the cancelled run stops, instead of failing with a wrapped + `StateError` (`generation is already in progress`). An overlap with a + running generation that was not cancelled now throws `LlamaStateException` + ([#656](https://github.com/leehack/llamadart/issues/656)). + ## 0.13.0 - Pair this release with Apple companions `llamadart_llama_cpp_flutter`, diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index cdc1c9b9b..a4a1d6364 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -376,10 +376,13 @@ once, even before the first token. On native llama.cpp, a cancel during text prompt evaluation takes effect at the next prompt micro-batch (`ModelParams.microBatchSize` tokens), or at the next -batch (`ModelParams.batchSize` tokens) with speculative decoding. A generation -started while a cancelled one is still stopping waits for it to stop, then -runs. Starting one while another is running and not cancelled throws -`LlamaStateException`. +batch (`ModelParams.batchSize` tokens) with speculative decoding. + +On native llama.cpp and on LiteRT-LM, native and Web, a generation started +while a cancelled one is still stopping waits for it to stop, then runs. +`cancelGeneration()` or disposing the engine ends a waiting generation without +running it. Starting one while another is running and not cancelled, or while +one is already waiting, throws `LlamaStateException`. ## Tokenization helpers From 08a5660ecc86f748a4d9f4d3ebe716e7bdcab322 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 20:01:32 -0400 Subject: [PATCH 2/8] test: cover LiteRT-LM queued-generation teardown paths Add regression tests for the branches the independent audit of #1114 found unguarded: a worker exit ends a generation queued behind a cancel; modelFree, contextFree and modelLoad end a queued native generation; a worker startup timeout releases the generation slot; Web contextFree ends a queued run; and a Web subscription cancel drops a later createConversation failure. Note in the cross-platform validation guide that LiteRT-LM now defines the restart and overlap contract, with the validation cases tracked in #1115. --- doc/cross_platform_validation.md | 19 ++-- .../litert_lm/litert_lm_backend_test.dart | 104 +++++++++++++++++- .../litert_lm/litert_lm_backend_web_test.dart | 62 ++++++++++- 3 files changed, 173 insertions(+), 12 deletions(-) diff --git a/doc/cross_platform_validation.md b/doc/cross_platform_validation.md index 1863ec730..d4985765a 100644 --- a/doc/cross_platform_validation.md +++ b/doc/cross_platform_validation.md @@ -1673,14 +1673,17 @@ timings; a missed precondition is NOT_RUN, never PASS. | `C12.grammar` | Raw request with GBNF `root ::= "unterminated` | Native: `LlamaInferenceException` `llama.cpp failed to initialize the requested grammar sampler.`; Web: `LlamaInferenceException` whose details contain `(invalid grammar)`; then a request completes | GGUF quick core | | `C07.tools.auto_text` | `ToolChoice.auto` with `get_weather` on the hello prompt ([#654](https://github.com/leehack/llamadart/issues/654)) | Text finish matching the hello regex, no tool call | `tools` selection | -Only native llama.cpp defines restart and overlap, so GGUF Web records both as -NOT_RUN. LiteRT profiles omit them (`litert_restart_contract_undefined`, -[#656](https://github.com/leehack/llamadart/issues/656)) and `C12.grammar` -(`litert_grammar_unsupported`: LiteRT-LM rejects every grammar). C07.tools -version 3 also binds the hello fixture its recovery uses. On Web, a required -trial rejected with the documented `LlamaUnsupportedException` for a lazy -required-tool grammar counts as that trial's result; elsewhere the rejection -stays ERROR. Catalog 1 to 4 reports keep their inventories, C07.tools version 2 +Of the GGUF runtimes, only native llama.cpp defines restart and overlap, so +GGUF Web records both as NOT_RUN. LiteRT-LM defines both on native and Web +since [#656](https://github.com/leehack/llamadart/issues/656), but LiteRT +profiles still omit them (`litert_restart_contract_undefined`) until their +cases are enabled and qualified +([#1115](https://github.com/leehack/llamadart/issues/1115)). LiteRT profiles +also omit `C12.grammar` (`litert_grammar_unsupported`: LiteRT-LM rejects every +grammar). C07.tools version 3 also binds the hello fixture its recovery uses. +On Web, a required trial rejected with the documented +`LlamaUnsupportedException` for a lazy required-tool grammar counts as that +trial's result; elsewhere the rejection stays ERROR. Catalog 1 to 4 reports keep their inventories, C07.tools version 2 and fixtures; a catalog 5 case in them fails the report. The `chat-gguf-*` and `gemma4-gguf-*` profiles select `focused` with `tools`. diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index 047297692..6e34a1112 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1822,6 +1822,35 @@ void main() { expect(service.runs, hasLength(1)); }); + for (final teardown in ['modelFree', 'contextFree', 'modelLoad']) { + test('$teardown ends a queued generation without running it', () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + final settled = switch (teardown) { + 'modelFree' => backend.modelFree(1), + 'contextFree' => backend.contextFree(1), + _ => backend.modelLoad(modelFile.path, const ModelParams()), + }.then((_) {}, onError: (Object _) {}); + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + + firstRun.finish(); + await settled; + await _settle(); + expect(service.runs.map((run) => run.prompt), ['first']); + }); + } + test('overlapping a generation that was not cancelled throws ' 'LlamaStateException', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); @@ -1872,6 +1901,60 @@ void main() { }); }); + test('a worker exit ends a generation queued behind a cancel', () async { + final backend = LiteRtLmBackend(workerEntryPoint: _exitOnCancelWorker); + const params = GenerationParams(streamBatchTokenThreshold: 1); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration(backend.generate(1, 'second', params)); + await first.done; + await second.done; + expect(first.error, isA()); + expect(second.error, isA()); + expect(second.text, isEmpty); + await expectLater(backend.dispose(), throwsA(isA())); + }); + + test('a worker startup timeout releases the generation slot', () async { + final backend = LiteRtLmBackend(workerEntryPoint: _silentWorker); + const params = GenerationParams(); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + await first.doneWithin(const Duration(seconds: 10)); + expect(first.error, isA()); + + // The retry makes its own startup attempt instead of waiting behind the + // failed one. + final second = _CollectedGeneration(backend.generate(1, 'second', params)); + await second.doneWithin(const Duration(seconds: 10)); + expect(second.error, isA()); + await backend.dispose(); + }, timeout: const Timeout(Duration(seconds: 40))); + + test('a worker exit during startup releases the generation slot', () async { + final backend = LiteRtLmBackend(workerEntryPoint: _exitBeforeHandshake); + const params = GenerationParams(); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + await first.done; + expect(first.error, isA()); + + final second = _CollectedGeneration(backend.generate(1, 'second', params)); + await second.done; + expect( + second.error, + isA().having( + (error) => error.message, + 'message', + allOf( + contains('native cleanup was confirmed'), + isNot(contains('already in progress')), + ), + ), + ); + await expectLater(backend.dispose(), throwsA(isA())); + }); + test('LlamaEngine starts a generation requested right after ' 'cancelGeneration', () async { final worker = _FakeLiteRtLmWorker( @@ -2112,6 +2195,10 @@ class _FakeLiteRtLmWorker { void _exitBeforeHandshake(SendPort port) => Isolate.exit(); +void _silentWorker(SendPort port) { + ReceivePort(); +} + void _loggingWorkerEntry(SendPort port) { runLiteRtLmWorkerForTesting(port, _LoggingLiteRtLmService()); } @@ -2207,7 +2294,9 @@ final class _CollectedGeneration { bool get isDone => _done.isCompleted; Future get firstChunk => _firstChunk.future.timeout(const Duration(seconds: 2)); - Future get done => _done.future.timeout(const Duration(seconds: 2)); + Future get done => doneWithin(const Duration(seconds: 2)); + + Future doneWithin(Duration limit) => _done.future.timeout(limit); } final class _ServiceRun { @@ -2274,4 +2363,17 @@ class _CancellableRunService extends LiteRtLmService { void cancelGeneration() { cancelCount += 1; } + + @override + Future loadModel( + String path, + api.ModelParams params, { + String? backendOverride, + }) async => 1; + + @override + void freeModel(int modelHandle) {} + + @override + void freeContext(int contextHandle) {} } diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 289f5b1a6..e3e71c2d2 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1526,6 +1526,28 @@ void main() { expect(second.text, 'second;'); }); + test('a subscription cancel drops a later createConversation failure ' + 'and frees the slot', () async { + final gate = Completer(); + fake.failNextConversation = gate.future; + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + await _settle(); + + final firstCancelled = first.subscription.cancel(); + gate.complete(); + await firstCancelled; + expect(first.error, isNull); + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await fake.started(0); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + test('a cancel before the first token ends the stream without sending ' 'the prompt', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); @@ -1715,6 +1737,29 @@ void main() { expect(fake.runs, hasLength(1)); }); + test('contextFree ends a queued generation without running it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + + await backend.contextFree(1); + await second.done; + expect(second.error, isNull); + expect(second.text, isEmpty); + + firstRun.finish(); + await first.done; + await _settle(); + expect(fake.runs, hasLength(1)); + }); + test('overlapping a generation that was not cancelled throws ' 'LlamaStateException', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); @@ -2165,6 +2210,9 @@ final class _QueueFakeEngine { /// does with its cancelled status. final bool rejectOnCancel; final List<_QueueFakeRun> runs = <_QueueFakeRun>[]; + + /// When set, the next `createConversation` waits for it, then rejects. + Future? failNextConversation; final List> _started = List.generate( 8, (_) => Completer<_QueueFakeRun>(), @@ -2179,6 +2227,16 @@ final class _QueueFakeEngine { } } + Future _createConversation() async { + final gate = failNextConversation; + failNextConversation = null; + if (gate != null) { + await gate; + throw StateError('createConversation failed'); + } + return _conversation(); + } + JSObject _conversation() { _QueueFakeRun? run; final conversation = JSObject(); @@ -2263,9 +2321,7 @@ _QueueFakeEngine _installQueueFakeEngine({bool rejectOnCancel = false}) { final engine = JSObject(); engine.setProperty( 'createConversation'.toJS, - ((JSObject config) => Future.value( - fake._conversation(), - ).toJS).toJS, + ((JSObject config) => fake._createConversation().toJS).toJS, ); engine.setProperty( 'delete'.toJS, From 5584f8b6cb576329645d8e71a461e0e8848b43a2 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 20:48:04 -0400 Subject: [PATCH 3/8] test: guard remaining LiteRT-LM generation slot branches Cover the branches the re-audit of #1114 found unguarded: a worker error frees the native slot, including for a run queued behind a cancelled run that fails; a token after a subscription cancel is dropped; a generation after a worker exit during a cancelled run reports the unsettled worker; a Web subscription cancel of the cancelled run keeps the run queued behind it; and ending a queued Web run keeps the slot while the cancelled run is still streaming. Reflow the validation guide paragraph touched by the previous commit. --- doc/cross_platform_validation.md | 5 +- .../litert_lm/litert_lm_backend_test.dart | 94 +++++++++++++++++++ .../litert_lm/litert_lm_backend_web_test.dart | 54 +++++++++++ 3 files changed, 151 insertions(+), 2 deletions(-) diff --git a/doc/cross_platform_validation.md b/doc/cross_platform_validation.md index d4985765a..c0e63eaf5 100644 --- a/doc/cross_platform_validation.md +++ b/doc/cross_platform_validation.md @@ -1683,8 +1683,9 @@ also omit `C12.grammar` (`litert_grammar_unsupported`: LiteRT-LM rejects every grammar). C07.tools version 3 also binds the hello fixture its recovery uses. On Web, a required trial rejected with the documented `LlamaUnsupportedException` for a lazy required-tool grammar counts as that -trial's result; elsewhere the rejection stays ERROR. Catalog 1 to 4 reports keep their inventories, C07.tools version 2 -and fixtures; a catalog 5 case in them fails the report. +trial's result; elsewhere the rejection stays ERROR. Catalog 1 to 4 reports +keep their inventories, C07.tools version 2 and fixtures; a catalog 5 case in +them fails the report. The `chat-gguf-*` and `gemma4-gguf-*` profiles select `focused` with `tools`. Their C07 fixtures are reference-qualified against unmodified upstream diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index 6e34a1112..532e90b09 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1851,6 +1851,66 @@ void main() { }); } + test('a generation the worker fails frees the slot', () async { + service.failPrompt = 'boom'; + final first = _CollectedGeneration(backend.generate(1, 'boom', params)); + await first.done; + expect(first.error, isA()); + + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await service.started(0); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test('a cancelled run that ends with a worker error starts the ' + 'generation queued behind it', () async { + service.failAfterFinish = true; + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + firstRun.finish(); + await first.done; + expect(first.error, isA()); + + final secondRun = await service.started(1); + service.failAfterFinish = false; + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test('a token after a subscription cancel is dropped', () async { + service.tokenAfterFinish = true; + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + await first.subscription.cancel(); + firstRun.finish(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + final secondRun = await service.started(1); + service.tokenAfterFinish = false; + secondRun.finish(); + await second.done; + expect(first.text, 'first;'); + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + test('overlapping a generation that was not cancelled throws ' 'LlamaStateException', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); @@ -1917,6 +1977,28 @@ void main() { await expectLater(backend.dispose(), throwsA(isA())); }); + test('a generation after a worker exit during a cancelled run reports the ' + 'unsettled worker', () async { + final backend = LiteRtLmBackend(workerEntryPoint: _exitOnCancelWorker); + const params = GenerationParams(streamBatchTokenThreshold: 1); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + await first.firstChunk; + + backend.cancelGeneration(); + await first.done; + final second = _CollectedGeneration(backend.generate(1, 'second', params)); + await second.done; + expect( + second.error, + isA().having( + (error) => error.message, + 'message', + contains('native cleanup was confirmed'), + ), + ); + await expectLater(backend.dispose(), throwsA(isA())); + }); + test('a worker startup timeout releases the generation slot', () async { final backend = LiteRtLmBackend(workerEntryPoint: _silentWorker); const params = GenerationParams(); @@ -2321,6 +2403,15 @@ class _CancellableRunService extends LiteRtLmService { ); int cancelCount = 0; + /// A prompt whose run fails before it starts. + String? failPrompt; + + /// Whether a finished run fails instead of ending normally. + bool failAfterFinish = false; + + /// Whether a finished run streams one more token before it ends. + bool tokenAfterFinish = false; + Future<_ServiceRun> started(int index) => _started[index].future.timeout(const Duration(seconds: 2)); @@ -2331,11 +2422,14 @@ class _CancellableRunService extends LiteRtLmService { } Stream> _run(String prompt) async* { + if (prompt == failPrompt) throw StateError('native failure'); final run = _ServiceRun(prompt); runs.add(run); _started[runs.length - 1].complete(run); yield utf8.encode('$prompt;'); await run._stopped.future; + if (tokenAfterFinish) yield utf8.encode('late;'); + if (failAfterFinish) throw StateError('native failure after finish'); } @override diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index e3e71c2d2..fcbbae747 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1650,6 +1650,59 @@ void main() { expect(second.text, 'second;'); }); + test('a subscription cancel of the cancelled run does not end the ' + 'generation queued behind it', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + final firstCancelled = first.subscription.cancel(); + await _settle(); + expect(second.isDone, isFalse); + + firstRun.finish(); + await firstCancelled; + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + + test('ending a queued run keeps the slot while the cancelled run is still ' + 'streaming', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + backend.cancelGeneration(); + await second.done; + + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await _settle(); + expect(fake.runs, hasLength(1)); + + firstRun.finish(); + await first.done; + final thirdRun = await fake.started(1); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + }); + test( 'cancelGeneration ends a queued generation without running it', () async { @@ -2177,6 +2230,7 @@ final class _CollectedGeneration { Object? error; String get text => utf8.decode(_bytes); + bool get isDone => _done.isCompleted; Future get firstChunk => _firstChunk.future.timeout(const Duration(seconds: 2)); Future get done => _done.future.timeout(const Duration(seconds: 2)); From 8af50e25790f39f56e547c01e3bb0278ea926765 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 21:33:31 -0400 Subject: [PATCH 4/8] test: guard LiteRT-LM queue release and teardown cancel marks Cover the remaining branches the re-audit of #1114 found unguarded: a queued native generation that started and finished leaves the queue; a generation started during modelFree, contextFree or modelLoad waits for the run they cancel; and a queued Web run ended by cancelGeneration never creates a conversation. The late-token test now checks that the late token was actually streamed, and the group tearDown disposes before releasing held runs so a failed test cannot start a queued generation. --- .../litert_lm/litert_lm_backend_test.dart | 92 ++++++++++++++++++- .../litert_lm/litert_lm_backend_web_test.dart | 27 ++++++ 2 files changed, 116 insertions(+), 3 deletions(-) diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index 532e90b09..22f63aa24 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1561,8 +1561,11 @@ void main() { }); tearDown(() async { + // Dispose first: it ends any queued generation before the held runs + // finish, so a test that failed with one queued cannot start it here. + final disposed = backend.dispose(); service.finishAll(); - await backend.dispose(); + await disposed; }); test('waits for a run stopped by cancelGeneration, then starts', () async { @@ -1851,6 +1854,79 @@ void main() { }); } + test( + 'a queued generation that started and finished leaves the queue', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + firstRun.finish(); + final secondRun = await service.started(1); + await second.firstChunk; + + // Queueing behind the now-running second generation must see an empty + // queue; a stale entry would reject this third one. + backend.cancelGeneration(); + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + await _settle(); + expect(third.error, isNull); + + secondRun.finish(); + await second.done; + final thirdRun = await service.started(2); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(service.runs.map((run) => run.prompt), [ + 'first', + 'second', + 'third', + ]); + }, + timeout: const Timeout(Duration(seconds: 10)), + ); + + for (final teardown in ['modelFree', 'contextFree', 'modelLoad']) { + test('a generation started during $teardown waits for the run it ' + 'cancels', () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + final settled = switch (teardown) { + 'modelFree' => backend.modelFree(1), + 'contextFree' => backend.contextFree(1), + _ => backend.modelLoad(modelFile.path, const ModelParams()), + }.then((_) {}, onError: (Object _) {}); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + expect(second.error, isNull); + + firstRun.finish(); + await settled; + final secondRun = await service.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }); + } + test('a generation the worker fails frees the slot', () async { service.failPrompt = 'boom'; final first = _CollectedGeneration(backend.generate(1, 'boom', params)); @@ -1906,7 +1982,11 @@ void main() { service.tokenAfterFinish = false; secondRun.finish(); await second.done; - expect(first.text, 'first;'); + expect( + service.lateTokens, + 1, + reason: 'the late token reached the worker', + ); expect(second.error, isNull); expect(second.text, 'second;'); }); @@ -2412,6 +2492,9 @@ class _CancellableRunService extends LiteRtLmService { /// Whether a finished run streams one more token before it ends. bool tokenAfterFinish = false; + /// How many tokens finished runs streamed after [_ServiceRun.finish]. + int lateTokens = 0; + Future<_ServiceRun> started(int index) => _started[index].future.timeout(const Duration(seconds: 2)); @@ -2428,7 +2511,10 @@ class _CancellableRunService extends LiteRtLmService { _started[runs.length - 1].complete(run); yield utf8.encode('$prompt;'); await run._stopped.future; - if (tokenAfterFinish) yield utf8.encode('late;'); + if (tokenAfterFinish) { + lateTokens += 1; + yield utf8.encode('late;'); + } if (failAfterFinish) throw StateError('native failure after finish'); } diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index fcbbae747..78eeddbfa 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1769,6 +1769,29 @@ void main() { }, ); + test('a queued run ended by cancelGeneration never creates a ' + 'conversation', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + final created = fake.conversationsCreated; + fake.failNextConversation = Future.value(); + backend.cancelGeneration(); + await second.done; + await _settle(); + expect(second.error, isNull); + expect(second.text, isEmpty); + expect(fake.conversationsCreated, created); + fake.failNextConversation = null; + }); + test('dispose ends a queued generation without running it', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); final firstRun = await fake.started(0); @@ -2267,6 +2290,9 @@ final class _QueueFakeEngine { /// When set, the next `createConversation` waits for it, then rejects. Future? failNextConversation; + + /// How many times `createConversation` was called. + int conversationsCreated = 0; final List> _started = List.generate( 8, (_) => Completer<_QueueFakeRun>(), @@ -2282,6 +2308,7 @@ final class _QueueFakeEngine { } Future _createConversation() async { + conversationsCreated += 1; final gate = failNextConversation; failNextConversation = null; if (gate != null) { From b42acb9676e431deced5ab0184beb1f4fdc91e79 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 21:58:18 -0400 Subject: [PATCH 5/8] test: cover spurious worker cancels, dispose-time requests and Web run release Add tests that a completed native generation sends the worker no cancel, then or on a later modelFree; that a subscription cancel after cancelGeneration sends no second cancel; that a generation requested during dispose reports the disposed backend; and, on Web, that a generation started from the previous one's onDone starts and that a queued run ending before admission does not hold the slot. --- .../litert_lm/litert_lm_backend_test.dart | 90 +++++++++++++++++++ .../litert_lm/litert_lm_backend_web_test.dart | 55 ++++++++++++ 2 files changed, 145 insertions(+) diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index 22f63aa24..d48f8c891 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1096,6 +1096,67 @@ void main() { } }); + test('a completed generation sends the worker no cancel, then or on a ' + 'later modelFree', () async { + final worker = _FakeLiteRtLmWorker( + tokenizeResponse: const [], + detokenizeResponse: '', + generationChunks: [utf8.encode('Hi')], + ); + final backend = LiteRtLmBackend(initialSendPort: worker.sendPort); + + try { + final output = await backend + .generate(1, 'first', const GenerationParams()) + .expand((bytes) => bytes) + .toList(); + expect(utf8.decode(output), 'Hi'); + await _settle(); + expect( + worker.requests.whereType(), + isEmpty, + ); + + await backend.modelFree(1); + expect( + worker.requests.whereType(), + isEmpty, + ); + } finally { + await backend.dispose(); + worker.close(); + } + }); + + test('a subscription cancel after cancelGeneration sends no second worker ' + 'cancel', () async { + final worker = _FakeLiteRtLmWorker( + tokenizeResponse: const [], + detokenizeResponse: '', + holdGeneration: true, + ); + final backend = LiteRtLmBackend(initialSendPort: worker.sendPort); + + try { + final subscription = backend + .generate(1, 'first', const GenerationParams()) + .listen((_) {}); + await worker.generateReceived.future; + + backend.cancelGeneration(); + await subscription.cancel(); + await _settle(); + expect( + worker.requests.whereType(), + hasLength(1), + ); + } finally { + worker.releaseGeneration(); + await backend.dispose(); + worker.close(); + } + }); + test('rejects concurrent generation before touching worker', () async { final worker = _FakeLiteRtLmWorker( tokenizeResponse: const [], @@ -1927,6 +1988,35 @@ void main() { }); } + test( + 'a generation requested during dispose reports the disposed backend', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await service.started(0); + await first.firstChunk; + + final disposed = backend.dispose(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + firstRun.finish(); + await disposed; + await second.done; + expect( + second.error, + isA().having( + (error) => error.message, + 'message', + contains('disposed'), + ), + ); + expect(service.runs, hasLength(1)); + }, + ); + test('a generation the worker fails frees the slot', () async { service.failPrompt = 'boom'; final first = _CollectedGeneration(backend.generate(1, 'boom', params)); diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 78eeddbfa..13b31fd99 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1792,6 +1792,61 @@ void main() { fake.failNextConversation = null; }); + test( + 'a generation started from the previous one\'s onDone starts', + () async { + final firstEnded = Completer<_CollectedGeneration>(); + backend + .generate(1, 'first', params) + .listen( + (_) {}, + onDone: () => firstEnded.complete( + _CollectedGeneration(backend.generate(1, 'second', params)), + ), + ); + (await fake.started(0)).finish(); + final second = await firstEnded.future.timeout( + const Duration(seconds: 2), + ); + final secondRun = await fake.started(1); + secondRun.finish(); + await second.done; + expect(second.error, isNull); + expect(second.text, 'second;'); + }, + ); + + test( + 'a queued run that ends before admission does not hold the slot', + () async { + final first = _CollectedGeneration( + backend.generate(1, 'first', params), + ); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', const GenerationParams(maxTokens: 0)), + ); + await second.done; + expect(second.error, isNull); + + firstRun.finish(); + await first.done; + await _settle(); + final third = _CollectedGeneration( + backend.generate(1, 'third', params), + ); + final thirdRun = await fake.started(1); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + }, + ); + test('dispose ends a queued generation without running it', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); final firstRun = await fake.started(0); From 69249a336aec507ec04507d235507db2595786b7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 22:12:05 -0400 Subject: [PATCH 6/8] test: cover Web queue release timing and subscription cancel completion Add Web tests that a generation requested right after cancelGeneration ends the queued one takes its place, that an admitted queued run leaves the queue, and that a subscription cancel completes only after its run releases the conversation. --- .../litert_lm/litert_lm_backend_web_test.dart | 76 ++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 13b31fd99..2d373ce76 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1847,6 +1847,74 @@ void main() { }, ); + test('a generation requested right after cancelGeneration ends the ' + 'queued one takes its place', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + backend.cancelGeneration(); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await _settle(); + expect(third.error, isNull); + + firstRun.finish(); + final thirdRun = await fake.started(1); + thirdRun.finish(); + await third.done; + expect(second.text, isEmpty); + expect(third.error, isNull); + expect(third.text, 'third;'); + }); + + test('an admitted queued run leaves the queue', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + firstRun.finish(); + final secondRun = await fake.started(1); + await second.firstChunk; + await secondRun.holding; + + backend.cancelGeneration(); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await _settle(); + expect(third.error, isNull); + + secondRun.finish(); + final thirdRun = await fake.started(2); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + }); + + test('a subscription cancel completes after its run releases the ' + 'conversation', () async { + await backend.dispose(); + await load(rejectOnCancel: true); + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + await first.subscription.cancel(); + expect(fake.conversationsDeleted, 1); + }); + test('dispose ends a queued generation without running it', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); final firstRun = await fake.started(0); @@ -2348,6 +2416,9 @@ final class _QueueFakeEngine { /// How many times `createConversation` was called. int conversationsCreated = 0; + + /// How many conversations were deleted. + int conversationsDeleted = 0; final List> _started = List.generate( 8, (_) => Completer<_QueueFakeRun>(), @@ -2398,7 +2469,10 @@ final class _QueueFakeEngine { ); conversation.setProperty( 'delete'.toJS, - (() => Future.value(null).toJS).toJS, + (() { + conversationsDeleted += 1; + return Future.value(null).toJS; + }).toJS, ); return conversation; } From b128705e09fb3e334caf9da815f6590d8ae09c03 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 22:24:40 -0400 Subject: [PATCH 7/8] test: check that pausing a LiteRT-LM Web stream pauses its run --- .../litert_lm/litert_lm_backend_web_test.dart | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 2d373ce76..428a36be9 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -1915,6 +1915,25 @@ void main() { expect(fake.conversationsDeleted, 1); }); + test('pausing the stream pauses the run', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await fake.started(0); + await first.firstChunk; + await firstRun.holding; + + first.subscription.pause(); + firstRun.finish(tail: 'more;'); + await _settle(); + expect(first.text, 'first;'); + expect(fake.conversationsDeleted, 0, reason: 'the paused run waits'); + + first.subscription.resume(); + await first.done; + expect(first.error, isNull); + expect(first.text, 'first;more;'); + expect(fake.conversationsDeleted, 1); + }); + test('dispose ends a queued generation without running it', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); final firstRun = await fake.started(0); From 4068683ebab756c23a82bf7a2f562f81d6c40d87 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 22:48:34 -0400 Subject: [PATCH 8/8] test: cover native queue clearing and onCancel cleanup Add tests that a generation requested right after cancelGeneration ends the queued one takes its place, that modelFree after a subscription cancel sends no second worker cancel, and rework the admitted-queue test so a stale queue entry fails it at once instead of looping, as the group's first test. --- .../litert_lm/litert_lm_backend_test.dart | 138 ++++++++++++------ 1 file changed, 95 insertions(+), 43 deletions(-) diff --git a/test/unit/backends/litert_lm/litert_lm_backend_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_test.dart index d48f8c891..f59f33cee 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_test.dart @@ -1157,6 +1157,40 @@ void main() { } }); + test( + 'modelFree after a subscription cancel sends no second worker cancel', + () async { + final worker = _FakeLiteRtLmWorker( + tokenizeResponse: const [], + detokenizeResponse: '', + holdGeneration: true, + ); + final backend = LiteRtLmBackend(initialSendPort: worker.sendPort); + + try { + final subscription = backend + .generate(1, 'first', const GenerationParams()) + .listen((_) {}); + await worker.generateReceived.future; + + await subscription.cancel(); + await _settle(); + final freed = backend.modelFree(1); + await _settle(); + expect( + worker.requests.whereType(), + hasLength(1), + ); + worker.releaseGeneration(); + await freed; + } finally { + worker.releaseGeneration(); + await backend.dispose(); + worker.close(); + } + }, + ); + test('rejects concurrent generation before touching worker', () async { final worker = _FakeLiteRtLmWorker( tokenizeResponse: const [], @@ -1629,6 +1663,41 @@ void main() { await disposed; }); + // A stale queue entry would make the finished second generation start + // again from every finish, a microtask loop that starves the isolate, so + // this checks the queue while the second generation is still running. + test('an admitted queued generation leaves the queue', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + firstRun.finish(); + final secondRun = await service.started(1); + await second.firstChunk; + + await second.subscription.cancel(); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await _settle(); + expect(third.error, isNull); + + secondRun.finish(); + final thirdRun = await service.started(2); + thirdRun.finish(); + await third.done; + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(service.runs.map((run) => run.prompt), [ + 'first', + 'second', + 'third', + ]); + }, timeout: const Timeout(Duration(seconds: 10))); + test('waits for a run stopped by cancelGeneration, then starts', () async { final first = _CollectedGeneration(backend.generate(1, 'first', params)); final firstRun = await service.started(0); @@ -1915,49 +1984,6 @@ void main() { }); } - test( - 'a queued generation that started and finished leaves the queue', - () async { - final first = _CollectedGeneration( - backend.generate(1, 'first', params), - ); - final firstRun = await service.started(0); - await first.firstChunk; - - backend.cancelGeneration(); - final second = _CollectedGeneration( - backend.generate(1, 'second', params), - ); - await _settle(); - firstRun.finish(); - final secondRun = await service.started(1); - await second.firstChunk; - - // Queueing behind the now-running second generation must see an empty - // queue; a stale entry would reject this third one. - backend.cancelGeneration(); - final third = _CollectedGeneration( - backend.generate(1, 'third', params), - ); - await _settle(); - expect(third.error, isNull); - - secondRun.finish(); - await second.done; - final thirdRun = await service.started(2); - thirdRun.finish(); - await third.done; - expect(third.error, isNull); - expect(third.text, 'third;'); - expect(service.runs.map((run) => run.prompt), [ - 'first', - 'second', - 'third', - ]); - }, - timeout: const Timeout(Duration(seconds: 10)), - ); - for (final teardown in ['modelFree', 'contextFree', 'modelLoad']) { test('a generation started during $teardown waits for the run it ' 'cancels', () async { @@ -2017,6 +2043,32 @@ void main() { }, ); + test('a generation requested right after cancelGeneration ends the ' + 'queued one takes its place', () async { + final first = _CollectedGeneration(backend.generate(1, 'first', params)); + final firstRun = await service.started(0); + await first.firstChunk; + + backend.cancelGeneration(); + final second = _CollectedGeneration( + backend.generate(1, 'second', params), + ); + await _settle(); + backend.cancelGeneration(); + final third = _CollectedGeneration(backend.generate(1, 'third', params)); + await _settle(); + expect(third.error, isNull); + + firstRun.finish(); + final thirdRun = await service.started(1); + thirdRun.finish(); + await third.done; + expect(second.text, isEmpty); + expect(third.error, isNull); + expect(third.text, 'third;'); + expect(service.runs.map((run) => run.prompt), ['first', 'third']); + }); + test('a generation the worker fails frees the slot', () async { service.failPrompt = 'boom'; final first = _CollectedGeneration(backend.generate(1, 'boom', params));