Skip to content

Commit 2ad63ee

Browse files
authored
fix(dart-sdk): deliver the in-flight Whisper batch on stop (#22395)
## What changed and why Fixes #22393 `WhisperTranscriber` in the Dart device SDK (`sdks/device/dart`) hands each full batch to the injected runner without awaiting it (`unawaited(_flush())`), and `_flush` drops the runner's result when it resolves after `stop()` has set `_stopped`. `stop()` only transcribes the buffered tail. So stopping while a batch is being transcribed loses that batch's transcript, up to `batchSeconds` of audio (5 s by default), and `stop()` returns before the batch finishes. The TypeScript and React Native SDKs had the same stopped-flag check; #20407 and #13619 fixed it there, and #21577 is the Python counterpart. - Batches now run one at a time in input order. Each waits for the previous one to settle, including after a failure. - `stop()` queues the buffered tail behind the batches already accepted. It completes after invoking the transcript callbacks. Repeated calls share the same completion, including any tail failure. The transcriber ignores PCM appended after stopping begins. - Background runner failures still reach the caller's Dart zone and allow later batches to run. A tail failure reaches the caller through `stop()`. - The refreshed branch uses the Dart Device SDK test workflow and CI budget already on main from #22347. ## Product invariants affected none ## How it was verified - Ran the contributor's original two regression cases against current main `dea64c4b` with Flutter 3.44.5. Both failed on the missing in-flight callback, once with a buffered tail and once at an exact batch boundary. - Ran `flutter test --no-pub --reporter expanded` in `sdks/device/dart`. All 25 package tests passed, including the four stop regressions. The tests use the public SDK and controlled runners with synthetic PCM. - Compared SDK analyzer output on the two versions using `flutter analyze --no-pub --no-fatal-infos --no-fatal-warnings`. Both report the same four pre-existing diagnostics and zero errors. ## Tests `sdks/device/dart/test/whisper_stop_test.dart` covers queued and in-flight batches followed by the buffered tail, an exact batch boundary, ignored PCM after stop, repeated stop with a tail failure, and a background failure followed by a successful tail. ## UI evidence UI-Evidence: none -- Dart device SDK library change with no UI; the regression tests above cover the behaviour ## Failure class (fixes) Failure-Class: new ## Failure-class transition narrative New class `FC-stop-discards-in-flight-batch` in the `work-bounded-resumable` family. The same stopped-flag check on an in-flight batch shipped in the TypeScript (#12964), React Native (#13618), Python (#21577) and Dart device SDKs. - Violated contract: a batching transcriber must deliver the result of every batch it accepted before stop, including one whose runner call is still in flight when stop is called. - Canonical guard: batches run one at a time in input order, every result is delivered, new input stops at the start of `stop()`, and every caller waits on the same drain. `whisper_stop_test.dart` holds the runner's result pending across `stop()`. - Evidence: the merged TypeScript and React Native fixes #20407 and #13619, and this PR.
2 parents 07f193a + a3502d8 commit 2ad63ee

4 files changed

Lines changed: 164 additions & 10 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"schema_version": 1,
3+
"id": "FC-stop-discards-in-flight-batch",
4+
"family": "work-bounded-resumable",
5+
"violated_contract": "A batching transcriber must deliver the result of every batch it accepted before stop, including a batch whose runner call is still in flight when stop is called. The Dart device SDK's WhisperTranscriber started each full batch without awaiting it and dropped any result that resolved after stop() had set its stopped flag, while stop() transcribed only the buffered tail. A session stopped during a 5 s batch lost that batch's transcript and kept only the tail. The TypeScript (#12964) and React Native (#13618) SDKs shipped the same stopped-flag check on the in-flight result.",
6+
"canonical_prevention": "Run batches one at a time in input order, each starting after the previous one has settled even if it failed, and deliver every runner result regardless of the stopped flag, which only gates new input. stop() queues the buffered tail behind the batches already accepted, and where it returns a future it completes only after the queue has drained. A regression test holds the runner's result pending across stop() and asserts that the in-flight transcript is delivered before the tail and before stop() completes.",
7+
"canonical_prevention_artifact": [
8+
"sdks/device/dart/test/whisper_stop_test.dart"
9+
],
10+
"evidence_prs": [13619, 20407],
11+
"scope_hints": [
12+
"sdks/device/dart/lib/stt/",
13+
"sdks/device/typescript/src/stt/",
14+
"sdks/react-native/src/stt/",
15+
"sdks/python/omi/stt/"
16+
],
17+
"status": "open"
18+
}

‎sdks/device/dart/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ See `sdks/device/STT.md`.
3434
`ready` (for example 1013 `capacity_full` or `service_not_ready`), `appendPcm` and `stop` throw an
3535
`SttStreamClosedException` carrying the close code and reason, so callers can retry or switch engines.
3636

37+
For Whisper, await `stop()` before closing the transcript consumer. It calls the
38+
transcript handler for accepted batches and the buffered tail in input order.
39+
Repeated calls await the same drain, including any failure while transcribing
40+
the tail.
41+
3742
## Tests
3843

3944
Run `flutter test` in this directory. The STT tests drive the transcribers through an in-memory WebSocket

‎sdks/device/dart/lib/stt/stt.dart‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -214,37 +214,48 @@ class ParakeetTranscriber implements StreamingTranscriber {
214214
}
215215

216216
/// Feature-gated Whisper via injected runner.
217+
///
218+
/// Batches run in input order. [stop] drains queued audio and the buffered tail
219+
/// before completing. All calls to [stop] share that completion.
217220
class WhisperTranscriber implements StreamingTranscriber {
218221
WhisperTranscriber({required this.runner, required this.onTranscript, this.batchSeconds = 5});
219222

220223
final FutureOr<String> Function(Uint8List pcm) runner;
221224
final TranscriptHandler onTranscript;
222225
final int batchSeconds;
223226
final BytesBuilder _buf = BytesBuilder(copy: false);
224-
bool _stopped = false;
227+
Future<void> _previousBatch = Future<void>.value();
228+
Future<void>? _stopFuture;
225229

226230
@override
227231
void appendPcm(Uint8List chunk) {
228-
if (_stopped) return;
232+
if (_stopFuture != null) return;
229233
_buf.add(chunk);
230234
final target = batchSeconds * 16000 * 2;
231235
if (_buf.length >= target) {
232236
unawaited(_flush());
233237
}
234238
}
235239

236-
Future<void> _flush({bool deliverWhenStopped = false}) async {
240+
Future<void> _flush() async {
237241
final pcm = Uint8List.fromList(_buf.takeBytes());
238-
if (pcm.isEmpty) return;
239-
final text = await runner(pcm);
240-
if ((!_stopped || deliverWhenStopped) && text.isNotEmpty) onTranscript(text);
242+
// The queue advances after a batch settles, while the caller of this
243+
// flush still observes its own error.
244+
final previous = _previousBatch;
245+
final done = Completer<void>();
246+
_previousBatch = done.future;
247+
try {
248+
await previous;
249+
if (pcm.isEmpty) return;
250+
final text = await runner(pcm);
251+
if (text.isNotEmpty) onTranscript(text);
252+
} finally {
253+
done.complete();
254+
}
241255
}
242256

243257
@override
244-
Future<void> stop() async {
245-
_stopped = true;
246-
await _flush(deliverWhenStopped: true);
247-
}
258+
Future<void> stop() => _stopFuture ??= _flush();
248259
}
249260

250261
StreamingTranscriber createTranscriber({
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import 'dart:async';
2+
import 'dart:typed_data';
3+
4+
import 'package:flutter_test/flutter_test.dart';
5+
import 'package:omi_device/omi_device.dart';
6+
7+
void main() {
8+
test('whisper stop drains in-flight and queued batches before the buffered tail', () async {
9+
final events = <String>[];
10+
final batchLengths = <int>[];
11+
final batchStarts = <int>[];
12+
final firstBatch = Completer<String>();
13+
final secondBatch = Completer<String>();
14+
FutureOr<String> runner(Uint8List pcm) {
15+
batchLengths.add(pcm.length);
16+
batchStarts.add(pcm.first);
17+
if (batchLengths.length == 1) return firstBatch.future;
18+
if (batchLengths.length == 2) return secondBatch.future;
19+
return 'tail';
20+
}
21+
22+
final transcriber = WhisperTranscriber(runner: runner, onTranscript: events.add, batchSeconds: 1);
23+
24+
// One second of 16 kHz PCM16 fills a batch; the runner is still transcribing it when stop() is called.
25+
final secondPcm = Uint8List(32000);
26+
secondPcm[0] = 2;
27+
transcriber.appendPcm(Uint8List(32000));
28+
transcriber.appendPcm(secondPcm);
29+
transcriber.appendPcm(Uint8List.fromList([3, 0]));
30+
await Future<void>.delayed(Duration.zero);
31+
expect(batchLengths, [32000]);
32+
33+
final stopping = transcriber.stop().then((_) => events.add('stopped'));
34+
transcriber.appendPcm(Uint8List(32000));
35+
firstBatch.complete('first');
36+
await Future<void>.delayed(Duration.zero);
37+
expect(batchLengths, [32000, 32000]);
38+
expect(events, ['first']);
39+
40+
secondBatch.complete('second');
41+
await stopping;
42+
43+
expect(batchLengths, [32000, 32000, 2]);
44+
expect(batchStarts, [0, 2, 3]);
45+
expect(events, ['first', 'second', 'tail', 'stopped']);
46+
});
47+
48+
test('whisper stop at a batch boundary still delivers the batch being transcribed', () async {
49+
final events = <String>[];
50+
final batch = Completer<String>();
51+
final transcriber = WhisperTranscriber(runner: (_) => batch.future, onTranscript: events.add, batchSeconds: 1);
52+
53+
transcriber.appendPcm(Uint8List(32000));
54+
await Future<void>.delayed(Duration.zero);
55+
final stopping = transcriber.stop().then((_) => events.add('stopped'));
56+
batch.complete('full batch');
57+
await stopping;
58+
59+
expect(events, ['full batch', 'stopped']);
60+
});
61+
62+
test('repeated whisper stop calls share the buffered tail failure', () async {
63+
final tail = Completer<String>();
64+
final error = StateError('tail runner failed');
65+
final batches = <Uint8List>[];
66+
final transcriber = WhisperTranscriber(
67+
runner: (pcm) {
68+
batches.add(pcm);
69+
return tail.future;
70+
},
71+
onTranscript: (_) => fail('The failing tail must not produce a transcript'),
72+
);
73+
74+
transcriber.appendPcm(Uint8List.fromList([1, 0]));
75+
final failures = Future.wait([
76+
expectLater(transcriber.stop(), throwsA(same(error))),
77+
expectLater(transcriber.stop(), throwsA(same(error))),
78+
]);
79+
await Future<void>.delayed(Duration.zero);
80+
tail.completeError(error);
81+
await failures;
82+
83+
await expectLater(transcriber.stop(), throwsA(same(error)));
84+
expect(batches, [
85+
[1, 0],
86+
]);
87+
});
88+
89+
test('whisper stop drains the tail after a background batch fails', () async {
90+
final firstStarted = Completer<void>();
91+
final backgroundErrors = <Object>[];
92+
final transcripts = <String>[];
93+
final error = StateError('background runner failed');
94+
late final Completer<String> firstBatch;
95+
late final WhisperTranscriber transcriber;
96+
runZonedGuarded(() {
97+
firstBatch = Completer<String>();
98+
transcriber = WhisperTranscriber(
99+
runner: (pcm) {
100+
if (pcm.length < 32000) return 'tail';
101+
firstStarted.complete();
102+
return firstBatch.future;
103+
},
104+
onTranscript: transcripts.add,
105+
batchSeconds: 1,
106+
);
107+
transcriber.appendPcm(Uint8List(32000));
108+
}, (error, _) => backgroundErrors.add(error));
109+
110+
await firstStarted.future;
111+
transcriber.appendPcm(Uint8List.fromList([1, 0]));
112+
final stopping = transcriber.stop();
113+
firstBatch.completeError(error);
114+
await stopping;
115+
await Future<void>.delayed(Duration.zero);
116+
117+
expect(backgroundErrors, [same(error)]);
118+
expect(transcripts, ['tail']);
119+
});
120+
}

0 commit comments

Comments
 (0)