diff --git a/CHANGELOG.md b/CHANGELOG.md index cd63fa67e..7309734ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,11 @@ `CPU`, LiteRT-LM under `ComputeDevice.auto` uses its GPU backend instead of the CPU, and the Web applies its GPU safety caps and CPU fallback ([#920](https://github.com/leehack/llamadart/issues/920)). +- 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 diff --git a/doc/cross_platform_validation.md b/doc/cross_platform_validation.md index 1863ec730..c0e63eaf5 100644 --- a/doc/cross_platform_validation.md +++ b/doc/cross_platform_validation.md @@ -1673,15 +1673,19 @@ 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 -and fixtures; a catalog 5 case in them fails the report. +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`. Their C07 fixtures are reference-qualified against unmodified upstream 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 37f5c1893..f77b42cad 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend_web.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend_web.dart @@ -67,6 +67,8 @@ class LiteRtLmBackend _LiteRtLmWebEngine? _engine; _LiteRtLmWebConversation? _activeConversation; + _LiteRtLmWebRun? _activeRun; + _LiteRtLmWebRun? _queuedRun; LlamaLogLevel _logLevel = LlamaLogLevel.warn; bool _isReady = false; bool _hasContext = false; @@ -245,6 +247,7 @@ class LiteRtLmBackend _requireContextHandle(contextHandle); _hasContext = false; _contextHandle = null; + _closeQueuedRun(); final conversation = _activeConversation; _activeConversation = null; if (conversation != null) { @@ -264,7 +267,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( @@ -281,11 +345,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; @@ -295,13 +358,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; @@ -316,8 +382,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(); @@ -326,6 +421,12 @@ class LiteRtLmBackend } } + @override + void cancelGeneration() { + _cancelActiveRun(); + _closeQueuedRun(); + } + @override Future> tokenize( int modelHandle, @@ -905,6 +1006,7 @@ class LiteRtLmBackend } Future _disposeEngine() async { + _closeQueuedRun(); final conversation = _activeConversation; _activeConversation = null; if (conversation != null) { @@ -1402,6 +1504,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..f59f33cee 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,101 @@ 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( + '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 [], @@ -1118,7 +1213,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 +1643,669 @@ 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 { + // 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 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); + 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)); + }); + + 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']); + }); + } + + 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 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 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)); + 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( + service.lateTokens, + 1, + reason: 'the late token reached the worker', + ); + 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)); + 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('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 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(); + 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( + 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() { @@ -1741,6 +2499,10 @@ class _FakeLiteRtLmWorker { void _exitBeforeHandshake(SendPort port) => Isolate.exit(); +void _silentWorker(SendPort port) { + ReceivePort(); +} + void _loggingWorkerEntry(SendPort port) { runLiteRtLmWorkerForTesting(port, _LoggingLiteRtLmService()); } @@ -1797,3 +2559,143 @@ 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 => doneWithin(const Duration(seconds: 2)); + + Future doneWithin(Duration limit) => _done.future.timeout(limit); +} + +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; + + /// 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; + + /// 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)); + + void finishAll() { + for (final run in runs) { + run.finish(); + } + } + + 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) { + lateTokens += 1; + yield utf8.encode('late;'); + } + if (failAfterFinish) throw StateError('native failure after finish'); + } + + @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; + } + + @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 34dec7300..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 @@ -1,6 +1,7 @@ @TestOn('browser') library; +import 'dart:async'; import 'dart:convert'; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; @@ -1423,6 +1424,645 @@ 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 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)); + 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('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 { + 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('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( + '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('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('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); + 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('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)); + 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; @@ -1732,3 +2372,193 @@ final class _ResultObserver extends LlamaOperationObserver { @override void onEnd(api.LlamaOperationResult result) => results.add(result); } + +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); + 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)); +} + +/// 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>[]; + + /// When set, the next `createConversation` waits for it, then rejects. + Future? failNextConversation; + + /// 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>(), + ); + + Future<_QueueFakeRun> started(int index) => + _started[index].future.timeout(const Duration(seconds: 2)); + + void finishAll() { + for (final run in runs) { + run.finish(); + } + } + + Future _createConversation() async { + conversationsCreated += 1; + final gate = failNextConversation; + failNextConversation = null; + if (gate != null) { + await gate; + throw StateError('createConversation failed'); + } + return _conversation(); + } + + 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, + (() { + conversationsDeleted += 1; + return 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) => fake._createConversation().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 2a41a1b8a..09e1b6cfb 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -36,6 +36,11 @@ For canonical full release notes, use: `CPU`, LiteRT-LM under `ComputeDevice.auto` uses its GPU backend instead of the CPU, and the Web applies its GPU safety caps and CPU fallback ([#920](https://github.com/leehack/llamadart/issues/920)). +- 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 diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 37545ee10..4fc74ee5a 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -374,10 +374,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