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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions lib/src/backends/litert_lm/litert_lm_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ class LiteRtLmBackend
final Set<int> _stalePerformanceContexts = {};
final Map<ReceivePort, Completer<Object?>> _pendingRequests = {};
final Duration _embeddingTimeout;
final Duration _workerStartupTimeout;
final Duration _freeTimeout;
final Duration _cancelAcknowledgementTimeout;
final String? _preferredBackend;
final void Function(SendPort) _workerEntryPoint;

Expand All @@ -75,13 +78,24 @@ class LiteRtLmBackend
/// Expiry cancels only that request; other queued calls keep their deadlines.
/// Explicit cancellation, context/model teardown and disposal cancel all embeds.
/// [workerEntryPoint] substitutes the worker only for lifecycle tests.
/// [workerStartupTimeout] bounds the worker handshake.
/// [freeTimeout] bounds native context and model frees; on expiry the worker
/// is killed and native settlement is reported as unverified.
/// [cancelAcknowledgementTimeout] bounds the wait for the worker to
/// acknowledge a cancellation, which is best-effort.
LiteRtLmBackend({
SendPort? initialSendPort,
Duration embeddingTimeout = const Duration(minutes: 10),
@Deprecated('Use ModelParams.device. This will be removed in 1.0.')
String? preferredBackend,
void Function(SendPort)? workerEntryPoint,
Duration workerStartupTimeout = const Duration(seconds: 5),
Duration freeTimeout = const Duration(seconds: 5),
Duration cancelAcknowledgementTimeout = const Duration(seconds: 1),
}) : _embeddingTimeout = embeddingTimeout,
_workerStartupTimeout = workerStartupTimeout,
_freeTimeout = freeTimeout,
_cancelAcknowledgementTimeout = cancelAcknowledgementTimeout,
_preferredBackend = preferredBackend,
_workerEntryPoint = workerEntryPoint ?? liteRtLmWorkerEntry {
if (initialSendPort != null) {
Expand Down Expand Up @@ -254,7 +268,7 @@ class LiteRtLmBackend
try {
await _sendRequest(
(sendPort) => LiteRtLmModelFreeRequest(modelHandle, sendPort),
timeout: const Duration(seconds: 5),
timeout: _freeTimeout,
);
} on TimeoutException {
_nativeSettlementUnverified = true;
Expand Down Expand Up @@ -294,7 +308,7 @@ class LiteRtLmBackend
try {
await _sendRequest(
(sendPort) => LiteRtLmContextFreeRequest(contextHandle, sendPort),
timeout: const Duration(seconds: 5),
timeout: _freeTimeout,
);
_embeddingContext = null;
_stalePerformanceContexts.remove(contextHandle);
Expand Down Expand Up @@ -957,7 +971,7 @@ class LiteRtLmBackend
}
_isolate = isolate;
await completer.future.timeout(
const Duration(seconds: 5),
_workerStartupTimeout,
onTimeout: () {
throw TimeoutException('Timed out starting LiteRT-LM worker.');
},
Expand Down Expand Up @@ -1092,7 +1106,7 @@ class LiteRtLmBackend
responsePort.sendPort,
),
);
await responsePort.first.timeout(const Duration(seconds: 1));
await responsePort.first.timeout(_cancelAcknowledgementTimeout);
} catch (_) {
// Cancellation is best-effort because this method is also used by
// StreamController.onCancel and dispose paths.
Expand Down
14 changes: 0 additions & 14 deletions test/integration/core/engine/tool_calling_integration_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -181,20 +181,6 @@ void main() {
];
});

group('ToolDefinition', () {
test('toJsonSchema includes tool definitions', () {
final tool = tools.first;
final schema = tool.toJsonSchema();
expect(schema['properties'], containsPair('location', isA<Map>()));
});

test('invoke handles valid tool call', () async {
final tool = tools.first;
final result = await tool.invoke({'location': 'London'});
expect(result, 'Sunny in London');
});
});

group('ChatSession with Tools', () {
test('tools are passed to engine.create', () async {
final session = ChatSession(engine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,6 @@ void main() {
'tokenizer.ggml.eos_token': '</s>',
};

group('Format Detection', () {
for (final file in templateFiles) {
final name = file.path.split('/').last.replaceAll('.jinja', '');
test('detects format for $name', () {
final source = file.readAsStringSync();
final format = detectChatFormat(source);
expect(format, isNotNull);
});
}
});

group('Render Pipeline - Simple Messages', () {
for (final file in templateFiles) {
final name = file.path.split('/').last.replaceAll('.jinja', '');
Expand Down
12 changes: 0 additions & 12 deletions test/unit/backends/backend_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,4 @@ void main() {
expect(perf.speculativeAcceptanceRate, isNull);
});
});

group('StateLoadResult', () {
test('exposes the recovered token sequence', () {
const result = StateLoadResult(tokens: [1, 2, 3]);
expect(result.tokens, [1, 2, 3]);
});

test('accepts an empty token list', () {
const result = StateLoadResult(tokens: []);
expect(result.tokens, isEmpty);
});
});
}
66 changes: 16 additions & 50 deletions test/unit/backends/litert_lm/litert_lm_backend_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,10 @@ void main() {
}
// Free requests deliberately never settle, as with a blocked runtime.
});
final backend = LiteRtLmBackend(initialSendPort: port.sendPort);
final backend = LiteRtLmBackend(
initialSendPort: port.sendPort,
freeTimeout: const Duration(milliseconds: 50),
);
final pending = backend.tokenize(1, 'hello');
final failed = expectLater(
pending,
Expand Down Expand Up @@ -775,7 +778,10 @@ void main() {
test(
'free fails when worker exits during generation cancellation: $freeContext',
() async {
final backend = LiteRtLmBackend(workerEntryPoint: _exitOnCancelWorker);
final backend = LiteRtLmBackend(
workerEntryPoint: _exitOnCancelWorker,
cancelAcknowledgementTimeout: const Duration(milliseconds: 50),
);
final started = Completer<void>();
final stream = freeContext
? backend.generate(1, 'hello', const GenerationParams())
Expand Down Expand Up @@ -1274,49 +1280,6 @@ void main() {
},
);

test('rejects concurrent generation before touching worker', () async {
final worker = _FakeLiteRtLmWorker(
tokenizeResponse: const <int>[],
detokenizeResponse: '',
holdGeneration: true,
);
final backend = LiteRtLmBackend(initialSendPort: worker.sendPort);

try {
final firstDone = Completer<void>();
final firstSubscription = backend
.generate(1, 'first', const GenerationParams())
.listen(
(_) {},
onError: firstDone.completeError,
onDone: firstDone.complete,
);
await worker.generateReceived.future;

await expectLater(
backend.generate(1, 'second', const GenerationParams()).drain<void>(),
throwsA(
isA<LlamaStateException>().having(
(error) => error.message,
'message',
contains('already in progress'),
),
),
);
expect(
worker.requests.whereType<LiteRtLmGenerateRequest>(),
hasLength(1),
);

worker.releaseGeneration();
await firstDone.future.timeout(const Duration(seconds: 1));
await firstSubscription.cancel();
} finally {
await backend.dispose();
worker.close();
}
});

test(
'does not send generation after immediate stream cancellation',
() async {
Expand Down Expand Up @@ -2614,6 +2577,7 @@ void main() {
final backend = LiteRtLmBackend(
initialSendPort: worker.sendPort,
workerEntryPoint: _silentWorker,
workerStartupTimeout: const Duration(milliseconds: 50),
);
final mirror = reflect(backend);
final owner = mirror.type.owner as LibraryMirror;
Expand Down Expand Up @@ -2646,23 +2610,25 @@ void main() {
isEmpty,
);
},
timeout: const Timeout(Duration(seconds: 15)),
);

test('a worker startup timeout releases the generation slot', () async {
final backend = LiteRtLmBackend(workerEntryPoint: _silentWorker);
final backend = LiteRtLmBackend(
workerEntryPoint: _silentWorker,
workerStartupTimeout: const Duration(milliseconds: 50),
);
const params = GenerationParams();
final first = _CollectedGeneration(backend.generate(1, 'first', params));
await first.doneWithin(const Duration(seconds: 10));
await first.doneWithin(const Duration(seconds: 2));
expect(first.error, isA<TimeoutException>());

// 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));
await second.doneWithin(const Duration(seconds: 2));
expect(second.error, isA<TimeoutException>());
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);
Expand Down
83 changes: 35 additions & 48 deletions test/unit/backends/litert_lm/litert_lm_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -869,55 +869,42 @@ void main() {
'Qwen2.5-0.5B',
]) {
for (final override in [null, '{{ messages[0].content }}', '']) {
for (final hasSetter in [false, true]) {
test(
'main native routing $name override=$override setter=$hasSetter',
() async {
final file = File('${tempDir.path}/$name.litertlm');
await file.writeAsBytes(_thinkingBundle(modelType: 1));
final client = _FakeLiteRtLmRuntimeClient()
..rendersMessages = true
..onRenderMessage = (_) => liteRtLmContentShapeProbeText;
// A runtime without the optional setter still supports these chats.
if (!hasSetter) {
client.onCreateConversation = () {
if (client.lastPromptTemplate != null) {
throw LlamaUnsupportedException('no template setter');
}
};
}
final service = LiteRtLmService(clientFactory: () => client);
final params = ModelParams(
liteRtLmBackend: LiteRtLmBackendPreference.cpu,
chatTemplate: override,
);
try {
final model = await service.loadModel(file.path, params);
expect(
await generate(
service,
client,
service.createContext(model, params),
),
isNull,
);
expect(client.renderMessageCount, 1);
expect(client.conversations, [
(template: null, seeded: false),
(template: null, seeded: true),
]);
if (override != null) {
expect(
service.getMetadata(model)['tokenizer.chat_template'],
override,
);
}
} finally {
service.dispose();
}
},
test('main native routing $name override=$override', () async {
final file = File('${tempDir.path}/$name.litertlm');
await file.writeAsBytes(_thinkingBundle(modelType: 1));
final client = _FakeLiteRtLmRuntimeClient()
..rendersMessages = true
..onRenderMessage = (_) => liteRtLmContentShapeProbeText;
final service = LiteRtLmService(clientFactory: () => client);
final params = ModelParams(
liteRtLmBackend: LiteRtLmBackendPreference.cpu,
chatTemplate: override,
);
}
try {
final model = await service.loadModel(file.path, params);
expect(
await generate(
service,
client,
service.createContext(model, params),
),
isNull,
);
expect(client.renderMessageCount, 1);
expect(client.conversations, [
(template: null, seeded: false),
(template: null, seeded: true),
]);
if (override != null) {
expect(
service.getMetadata(model)['tokenizer.chat_template'],
override,
);
}
} finally {
service.dispose();
}
});
}
}

Expand Down
Loading
Loading