From 7eda940fcab9b75e565614acc8d7f2acc33cbf7a Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:25:29 +0100 Subject: [PATCH 01/14] test(core_data): a new outage starts with the handshake bound that last succeeded Probe 7: outages of 22.5 / 25.5 / 55.5 s for accepts of 12 / 15 / 25 s, because the bound restarted at 10 s after each successful reconnection. The round-8 spec "a new outage starts again at 10 s" is changed: with the same slow server (15 s) the next outage needs one attempt and lasts about the accept delay. New guard: after a fast accept the bound is back to 10 s. --- ...n_remote_data_source_slow_accept_test.dart | 55 ++++++++++++++++--- .../test/helpers/fake_websocket_client.dart | 5 ++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart index a4e2987..1a51530 100644 --- a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart +++ b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart @@ -124,8 +124,11 @@ void main() { }); // Revue PR #21 (commit 1250d05) : une seule poignée de main à la fois. + // Tour 9 (sonde 7 : coupures de 22,5 / 25,5 / 55,5 s pour des accueils de + // 12 / 15 / 25 s) : la nouvelle coupure ne repart plus à 10 s, elle part + // de la borne qui a réussi la dernière fois. test('une tentative à la fois ; à expiration le canal est fermé et jamais ' - 'réutilisé ; une nouvelle coupure repart à 10 s', () { + 'réutilisé ; la coupure suivante part de la borne qui a réussi', () { fakeAsync((FakeAsync async) { final DataSourceBench b = DataSourceBench(async); b.mic.acceptDelay = const Duration(seconds: 15); @@ -159,10 +162,11 @@ void main() { async.elapse(const Duration(seconds: 30)); expect(b.mic.connections, hasLength(2), reason: 'reconnecté'); - // Nouvelle coupure : la borne repart à 10 s. + // Nouvelle coupure, même serveur lent (15 s) : la première tentative + // attend la borne qui a réussi (20 s) ; la coupure ≈ l'accueil. final Duration secondDrop = async.elapsed; b.mic.drop(); - for (int id = 1000; id < 1150; id++) { + for (int id = 1000; id < 1250; id++) { b.tick( id, voiced: {AudioSource.input: id % 50 < 40}, @@ -171,16 +175,51 @@ void main() { final List again = b.mic.connectAttempts .where((Duration t) => t >= secondDrop) .toList(); - expect(again.length, greaterThanOrEqualTo(2)); + expect(again, hasLength(1), reason: 'une seule tentative suffit'); + expect(b.mic.connections, hasLength(3), reason: 'reconnecté'); expect( - again[1] - again[0], - lessThanOrEqualTo(const Duration(milliseconds: 11500)), - reason: 'première borne de la nouvelle coupure : 10 s', + b.mic.connectionOpenedAt.last - secondDrop, + lessThanOrEqualTo(const Duration(milliseconds: 16500)), + reason: 'coupure ≈ délai d accueil (15 s)', ); + }); + }); + + test('après un accueil rapide, la borne revient à 10 s', () { + fakeAsync((FakeAsync async) { + final DataSourceBench b = DataSourceBench(async); + async.elapse(const Duration(seconds: 1)); + int id = 0; + void outage(Duration accept, int seconds) { + b.mic + ..acceptDelay = accept + ..drop(); + for (int i = 0; i < seconds * 10; i++, id++) { + b.tick( + id, + voiced: {AudioSource.input: id % 50 < 40}, + ); + } + } + + outage(const Duration(seconds: 15), 40); // apprend 20 s + outage(const Duration(seconds: 2), 10); // accueil rapide + final Duration thirdDrop = async.elapsed; + outage(const Duration(seconds: 15), 40); + + final List attempts = b.mic.connectAttempts + .where((Duration t) => t >= thirdDrop) + .toList(); + expect(attempts.length, greaterThanOrEqualTo(2)); expect( - again[1] - again[0], + attempts[1] - attempts[0], greaterThanOrEqualTo(const Duration(seconds: 10)), ); + expect( + attempts[1] - attempts[0], + lessThanOrEqualTo(const Duration(milliseconds: 11500)), + reason: 'borne revenue à 10 s', + ); }); }); } diff --git a/packages/core_data/test/helpers/fake_websocket_client.dart b/packages/core_data/test/helpers/fake_websocket_client.dart index 349bb74..c64f048 100644 --- a/packages/core_data/test/helpers/fake_websocket_client.dart +++ b/packages/core_data/test/helpers/fake_websocket_client.dart @@ -37,6 +37,9 @@ final class FakeWebSocketClient extends WebSocketClient { /// Numéros reçus, connexion par connexion. final List> connections = >[]; + /// Heure (horloge du test) de chaque connexion établie. + final List connectionOpenedAt = []; + /// Messages reçus, connexion par connexion. final List> connectionMessages = >[]; @@ -115,6 +118,8 @@ final class FakeWebSocketClient extends WebSocketClient { throw const SocketException('Connection refused'); } _connected = true; + final Duration? openedAt = now?.call(); + if (openedAt != null) connectionOpenedAt.add(openedAt); _generation++; _pendingUtterances.clear(); _currentUtterance = []; From ff12d92050f1fb86420f0ceaa66961c521dbf446 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:25:46 +0100 Subject: [PATCH 02/14] test(app): gap markers of one source never overlap; touching or nested gaps merge into one --- .../services/gap_marker_merge_test.dart | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 apps/app_macos/test/application/services/gap_marker_merge_test.dart diff --git a/apps/app_macos/test/application/services/gap_marker_merge_test.dart b/apps/app_macos/test/application/services/gap_marker_merge_test.dart new file mode 100644 index 0000000..193bd16 --- /dev/null +++ b/apps/app_macos/test/application/services/gap_marker_merge_test.dart @@ -0,0 +1,96 @@ +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Tour 9, point 2 (sonde 7, scénario Dlag sans rattrapage, son système) : +// trois pertes déclarées au même instant (348,56 s), dans cet ordre : +// 1:58–2:04, 2:12–2:14, puis 1:51–2:35 qui contient les deux autres. Trois +// repères se chevauchaient dans la note. +// +// Attendu : les repères d'une source ne se chevauchent jamais. Une perte +// dans un repère encore ouvert, ou qui le touche, l'étend : un seul repère, +// l'union des intervalles ; le rattrapage planifie cette union une fois. +void main() { + List markers(LiveServiceHarness h, AudioSource s) => + h.segments + .of(s) + .where( + (TranscriptSegmentEntity x) => + x.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + + void gap(LiveServiceHarness h, int startMs, int endMs) => + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.output, + startMs: h.t0 + startMs, + endMs: h.t0 + endMs, + ), + ); + + test('séquence enregistrée : un seul repère 00:01:51 – 00:02:35, planifié ' + 'une fois', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 348)); + gap(h, 118530, 124000); // 00:01:58 – 00:02:04 + gap(h, 132830, 134000); // 00:02:12 – 00:02:14 + gap(h, 111630, 155000); // 00:01:51 – 00:02:35 + async.elapse(const Duration(seconds: 1)); + + final TranscriptSegmentEntity marker = markers( + h, + AudioSource.output, + ).single; + expect(marker.timestampMs, 111630); + expect(marker.text, matches(RegExp(r'00:01:51\s*[–-]\s*00:02:35'))); + + final plan = GapBackfillService.plan(h.segments.store.values.toList()); + expect(plan.where((p) => p.source == AudioSource.output), hasLength(1)); + }); + }); + + test('une perte qui touche un repère ouvert l étend ; une perte à part ' + 'garde son propre repère', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 200)); + gap(h, 60000, 70000); + gap(h, 70000, 80000); // touche la fin du premier + gap(h, 150000, 160000); // à part + async.elapse(const Duration(seconds: 1)); + + final List found = markers(h, AudioSource.output) + ..sort((a, b) => a.timestampMs.compareTo(b.timestampMs)); + expect(found, hasLength(2)); + expect(found[0].text, matches(RegExp(r'00:01:00\s*[–-]\s*00:01:20'))); + expect(found[1].text, matches(RegExp(r'00:02:30\s*[–-]\s*00:02:40'))); + }); + }); + + test('les repères de deux sources différentes ne fusionnent pas', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 200)); + gap(h, 60000, 70000); + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.input, + startMs: h.t0 + 65000, + endMs: h.t0 + 75000, + ), + ); + async.elapse(const Duration(seconds: 1)); + + expect(markers(h, AudioSource.output), hasLength(1)); + expect(markers(h, AudioSource.input), hasLength(1)); + }); + }); +} From a99b649c90857779e5079d8463c99855d9dfbbe9 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:26:44 +0100 Subject: [PATCH 03/14] test(app): a sealed sentence ends at the gap start whatever order its writes complete in --- .../services/restamp_write_order_test.dart | 85 +++++++++++++++++++ .../test/helpers/live_service_fakes.dart | 16 ++-- 2 files changed, 95 insertions(+), 6 deletions(-) create mode 100644 apps/app_macos/test/application/services/restamp_write_order_test.dart diff --git a/apps/app_macos/test/application/services/restamp_write_order_test.dart b/apps/app_macos/test/application/services/restamp_write_order_test.dart new file mode 100644 index 0000000..3b977a6 --- /dev/null +++ b/apps/app_macos/test/application/services/restamp_write_order_test.dart @@ -0,0 +1,85 @@ +import 'dart:async'; + +import 'package:core_data/datasources/remote/transcription.remote.data_source.dart'; +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Tour 9, point 3 (revue de `_onAudioGap`) : une phrase scellée est rangée, +// puis re-rangée à l'heure du début de la perte ; la seconde écriture n'est +// pas chaînée après la première. Si la première (heure d'arrivée) se +// termine après, elle écrase la bonne heure. +// +// Dépôt lent : chaque écriture attend qu'on la libère ; on les libère dans +// l'ordre inverse. Le segment rangé doit finir à l'heure du début de la +// perte, jamais à l'heure d'arrivée, quel que soit l'ordre de fin. +void main() { + for (final bool lastFirst in [true, false]) { + test('la phrase scellée finit à l heure de la perte (écritures libérées ' + '${lastFirst ? 'de la dernière à la première' : 'dans l ordre'})', () { + fakeAsync((FakeAsync async) { + final _SlowRepository repo = _SlowRepository(); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 306)); + h.fakeRemote.emitDelta( + AudioSource.input, + 'La boulangère a nettoyé le kiosque à journaux malgré le vent ' + 'froid, puis la', + ); + async.elapse(const Duration(seconds: 3)); // provisoire : en attente + h.fakeRemote.emitControl(AudioSource.input, utteranceLostEventType); + async.elapse(const Duration(milliseconds: 100)); // scellée : en attente + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.input, + startMs: h.t0 + 148048, + endMs: h.t0 + 165000, + ), + ); + async.elapse(const Duration(milliseconds: 100)); + + repo.releaseAll(lastFirst: lastFirst); + async.elapse(const Duration(seconds: 1)); + repo.releaseAll(lastFirst: lastFirst); // écritures chaînées ensuite + async.elapse(const Duration(seconds: 1)); + repo.releaseAll(lastFirst: lastFirst); + async.elapse(const Duration(seconds: 1)); + + final TranscriptSegmentEntity sealed = repo.store.values.singleWhere( + (TranscriptSegmentEntity s) => s.text.startsWith('La boulangère'), + ); + expect( + sealed.timestampMs, + 148048, + reason: 'heure du début de la perte', + ); + }); + }); + } +} + +/// Dépôt dont chaque écriture attend d'être libérée. +class _SlowRepository extends InMemoryTranscriptRepository { + final List> _held = >[]; + + @override + Future save(TranscriptSegmentEntity segment) async { + final Completer gate = Completer(); + _held.add(gate); + await gate.future; + return super.save(segment); + } + + void releaseAll({required bool lastFirst}) { + final List> now = List>.of(_held); + _held.clear(); + for (final Completer c in lastFirst ? now.reversed : now) { + c.complete(); + } + } +} diff --git a/apps/app_macos/test/helpers/live_service_fakes.dart b/apps/app_macos/test/helpers/live_service_fakes.dart index 31e8ef0..967c171 100644 --- a/apps/app_macos/test/helpers/live_service_fakes.dart +++ b/apps/app_macos/test/helpers/live_service_fakes.dart @@ -319,7 +319,7 @@ final class InMemorySessionRepository implements SessionRepository { /// Dépôt en mémoire au contrat du port : `save` remplace un segment de même /// id (en gardant sa place), `deleteById` le retire. -final class InMemoryTranscriptRepository implements TranscriptRepository { +class InMemoryTranscriptRepository implements TranscriptRepository { final Map store = {}; @@ -384,14 +384,18 @@ final class FakeWavRecorder extends WavRecorder { /// Monte le vrai [LiveTranscriptionService] sur les faux ci-dessus. final class LiveServiceHarness { - LiveServiceHarness(this.async, {TranscriptionRemoteDataSource? remote}) - : process = FakeProcessManagerChannel(now: () => async.elapsed), - remote = remote ?? FakeTranscriptionRemoteDataSource() { + LiveServiceHarness( + this.async, { + TranscriptionRemoteDataSource? remote, + InMemoryTranscriptRepository? segments, + }) : process = FakeProcessManagerChannel(now: () => async.elapsed), + remote = remote ?? FakeTranscriptionRemoteDataSource(), + segments = segments ?? InMemoryTranscriptRepository() { transcription = TranscriptionService( startSessionUseCase: StartSessionUseCase(sessionRepository: sessions), stopSessionUseCase: StopSessionUseCase(sessionRepository: sessions), saveTranscriptSegmentUseCase: SaveTranscriptSegmentUseCase( - transcriptRepository: segments, + transcriptRepository: this.segments, ), ); service = LiveTranscriptionService( @@ -412,7 +416,7 @@ final class LiveServiceHarness { final FakeAudioCaptureChannel audio = FakeAudioCaptureChannel(); final TranscriptionRemoteDataSource remote; final InMemorySessionRepository sessions = InMemorySessionRepository(); - final InMemoryTranscriptRepository segments = InMemoryTranscriptRepository(); + final InMemoryTranscriptRepository segments; final List recorders = []; late final TranscriptionService transcription; late final LiveTranscriptionService service; From 0f751cc7e82a53e6cd5ea49e658308b03e928304 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:30:16 +0100 Subject: [PATCH 04/14] fix(core_data): a new outage starts with the handshake bound that last worked Why: the bound restarted at 10 s after each successful reconnection, so a slow server cost one failed attempt per outage (probe 7: outages of 22.5 / 25.5 / 55.5 s for accepts of 12 / 15 / 25 s). What: per source, a successful reconnection records its bound when the accept took longer than 10 s, and 10 s when it was faster; a new outage starts from it. Still one attempt at a time, doubled after an expiry, 60 s at most. The accept speed is measured with a timer so it follows fake time in tests. How proven: slow_accept specs green (same slow server: one attempt, outage about the accept delay; after a fast accept back to 10 s), connect timeout and client specs green. --- ...transcription.remote.data_source.impl.dart | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart index e24d4dc..5667372 100644 --- a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart +++ b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart @@ -335,12 +335,22 @@ final class TranscriptionRemoteDataSourceImpl _unacked[source]! ..sentEvictionsLost() ..resetSent(); - final _Outage outage = _Outage(); + // La borne qui a réussi la dernière fois pour cette source : un serveur + // lent l'est encore (sonde 7 : repartir de 10 s coûtait une tentative + // ratée par coupure). + final _Outage outage = _Outage() + ..slowAccepts = _learnedSlowAccepts[source]!; _outages[source] = outage; _connectionStateSubject.add(domain.ConnectionState.connecting); _scheduleReconnect(source, outage); } + // Par source : nombre de doublements de la borne qui a réussi en dernier. + final Map _learnedSlowAccepts = { + AudioSource.input: 0, + AudioSource.output: 0, + }; + Duration _handshakeBound(int slowAccepts) { final Duration bound = WebSocketClient.connectTimeout * (1 << math.min(slowAccepts, 3)); @@ -361,6 +371,12 @@ final class TranscriptionRemoteDataSourceImpl final WebSocketClient client = _client(source); final Duration bound = _handshakeBound(outage.slowAccepts); client.handshakeTimeout = bound; + // Vrai si l'accueil prend plus que la première borne (10 s). + bool slowAccept = false; + final Timer slowMark = Timer( + WebSocketClient.connectTimeout, + () => slowAccept = true, + ); try { // Une seule tentative à la fois : la suivante ne part qu'une fois // celle-ci finie ou expirée. Une poignée de main sans fin est @@ -368,6 +384,7 @@ final class TranscriptionRemoteDataSourceImpl // ne jamais rendre la main). await client.connect(_url).timeout(bound); } on TimeoutException { + slowMark.cancel(); // Accueil lent, pas refus : on réessaie tout de suite, plus patient, // sans ajouter d'attente à celle déjà subie. if (identical(_outages[source], outage)) { @@ -376,11 +393,16 @@ final class TranscriptionRemoteDataSourceImpl } return; } catch (_) { + slowMark.cancel(); if (identical(_outages[source], outage)) { _scheduleReconnect(source, outage); } return; } + slowMark.cancel(); + // Retenir ce qui a marché : la borne de cette tentative si l'accueil a + // été lent, la première (10 s) sinon. + _learnedSlowAccepts[source] = slowAccept ? outage.slowAccepts : 0; // Session close ou relancée pendant la connexion. if (!identical(_outages[source], outage)) return; From 8d95c8399381aa524acf1bfb19745933640f8648 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:32:13 +0100 Subject: [PATCH 05/14] fix(app): one marker per overlapping loss; per-segment write chain Why: three losses declared at the same instant left three nested markers in the note (probe 7), and the re-stamp of a sealed sentence was not chained after its first save: with a slow write the sentence ended at its arrival time instead of the gap start. What: - _writeGapMarker is the only writer of gap markers: a loss touching or overlapping markers of the same source merges them into one, the union, under the first marker's id; the others are removed from the database and the screen. Sources never merge. - Writes are chained per segment id (_chainWrite), so the last intended value of a segment always lands last; _savePartial, the re-stamp and marker merges go through it. How proven: gap_marker_merge and restamp_write_order specs green (both completion orders); sealed_partial_time and late_done_after_gap green; services suite green (899). --- .../services/live_transcription.service.dart | 95 ++++++++++++++++--- 1 file changed, 80 insertions(+), 15 deletions(-) diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index 375dc3e..463b36c 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -409,6 +409,7 @@ final class LiveTranscriptionService { _log.info('Audio subscription active, en attente de chunks...'); _running = true; _lossOfPhrase.clear(); + _gapMarkers.clear(); _lastSealed.clear(); _provisionalTimer = Timer.periodic( const Duration(seconds: 1), @@ -864,20 +865,85 @@ final class LiveTranscriptionService { when startMs < sealed.timestampMs) { _savePartial(sealed.copyWith(timestampMs: startMs)); } + _writeGapMarker( + session, + gap.source, + startMs, + _offsetOf(session, gap.endMs), + ); + } + + // Repères de perte écrits dans cette session, par source, dans l'ordre : + // (id, début, fin) en heures de réunion. + final Map> _gapMarkers = + >{}; + + /// Seul endroit qui écrit un repère de perte. Les repères d'une source ne + /// se chevauchent jamais (sonde 7 : trois repères emboîtés) : une perte + /// qui touche ou recoupe des repères de la même source les fusionne en un + /// seul, l'union, sous l'id du premier ; les autres sont retirés. + void _writeGapMarker( + SessionEntity session, + AudioSource source, + int start, + int end, + ) { + final List<({String id, int start, int end})> markers = _gapMarkers + .putIfAbsent(source, () => <({String id, int start, int end})>[]); + final List<({String id, int start, int end})> touched = markers + .where( + (({String id, int start, int end}) m) => + m.start <= end && start <= m.end, + ) + .toList(); + int from = start; + int to = end; + for (final ({String id, int start, int end}) m in touched) { + if (m.start < from) from = m.start; + if (m.end > to) to = m.end; + } + final String id = touched.isEmpty + ? _newSegmentId(session, source) + : touched.first.id; + for (final ({String id, int start, int end}) m in touched.skip(1)) { + _chainWrite(m.id, () async { + await _transcriptionService.discardProvisional(m.id); + _transcriptionService.segmentsStream.add( + List.from( + _transcriptionService.segmentsStream.value, + )..removeWhere((TranscriptSegmentEntity x) => x.id == m.id), + ); + }); + } + markers + ..removeWhere(touched.contains) + ..add((id: id, start: from, end: to)); final TranscriptSegmentEntity marker = TranscriptSegmentEntity( - id: _newSegmentId(session, gap.source), + id: id, sessionId: session.id, - source: gap.source, - text: gapMarkerText(startMs, _offsetOf(session, gap.endMs)), - timestampMs: startMs, + source: source, + text: gapMarkerText(from, to), + timestampMs: from, createdAt: clock.now(), ); - _log.warning('Audio non transcrit: ${marker.text} (${gap.source.name})'); + _log.warning('Audio non transcrit: ${marker.text} (${source.name})'); + _savePartial(marker); + } + + // Écritures chaînées par id de segment : la dernière valeur voulue est + // toujours écrite en dernier (revue : un re-rangement non chaîné pouvait + // être écrasé par la première écriture, plus lente). + final Map> _segmentWrites = >{}; + + void _chainWrite(String id, Future Function() write) { late final Future task; - task = _transcriptionService - .saveSegment(marker) - .then((_) => _sortAndDedupeSegments()) - .whenComplete(() => _pendingFinalizations.remove(task)); + task = (_segmentWrites[id] ?? Future.value()) + .then((_) => write()) + .whenComplete(() { + _pendingFinalizations.remove(task); + if (identical(_segmentWrites[id], task)) _segmentWrites.remove(id); + }); + _segmentWrites[id] = task; _pendingFinalizations.add(task); } @@ -1144,12 +1210,11 @@ final class LiveTranscriptionService { {}; void _savePartial(TranscriptSegmentEntity segment, {Future? after}) { - late final Future task; - task = (after ?? Future.value()) - .then((_) => _transcriptionService.saveSegment(segment)) - .then((_) => _sortAndDedupeSegments()) - .whenComplete(() => _pendingFinalizations.remove(task)); - _pendingFinalizations.add(task); + _chainWrite(segment.id, () async { + await after; + await _transcriptionService.saveSegment(segment); + _sortAndDedupeSegments(); + }); } static final RegExp _wordChar = RegExp(r'[\p{L}\p{N}]', unicode: true); From e249fef9dcad993f124cc910c05f1705f36af8b8 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:55:17 +0100 Subject: [PATCH 06/14] test(app): the backfill plans one interval per union of stored overlapping markers (probe 7) --- ...gap_backfill_overlapping_markers_test.dart | 140 +++++++++++ .../test/fixtures/probe7_overlap.dart | 236 ++++++++++++++++++ 2 files changed, 376 insertions(+) create mode 100644 apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart create mode 100644 apps/app_macos/test/fixtures/probe7_overlap.dart diff --git a/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart b/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart new file mode 100644 index 0000000..590ae0f --- /dev/null +++ b/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart @@ -0,0 +1,140 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/wav_recorder.dart'; + +import '../../fixtures/probe7_overlap.dart'; +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 1 : le repère provisoire (mis à jour chaque seconde, +// id `__pending`) s'écrit sans passer par la fusion, et +// `GapBackfillService.plan` croit ce qui est rangé. Après un arrêt brutal +// pendant une coupure, des repères qui se chevauchent peuvent donc être sur +// le disque. Le rattrapage doit s'en sortir seul. +// +// État rangé de la sonde 7 (Dlag sans rattrapage, son système) : 1:51–2:35 +// contient 1:58–2:04 et 2:12–2:14 ; plus un repère provisoire 2:40–3:10 +// qui recoupe le repère final 2:45–4:59. +// +// Attendu : un intervalle par union, chaque phrase une seule fois, dans +// l'ordre, aucun repère de l'union laissé, les segments dans l'union +// remplacés une fois (`replacedIds`). +void main() { + const String sessionId = probe7SessionId; + final TranscriptSegmentEntity provisional = TranscriptSegmentEntity( + id: '${sessionId}_output_pending', + sessionId: sessionId, + source: AudioSource.output, + text: LiveTranscriptionService.gapMarkerText(160000, 190000), + timestampMs: 160000, + createdAt: DateTime(2026, 11, 24), + ); + + List stored() => [ + for (final Probe7Segment s in probe7SystemStored) + TranscriptSegmentEntity( + id: s.id, + sessionId: sessionId, + source: AudioSource.output, + text: s.text, + timestampMs: s.timestampMs, + createdAt: DateTime(2026, 11, 24), + ), + provisional, + ]; + + bool isMarker(TranscriptSegmentEntity s) => + s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix); + + test('le plan donne un intervalle par union, et remplace une fois les ' + 'segments de l union', () { + final plan = + GapBackfillService.plan( + stored(), + ).where((p) => p.source == AudioSource.output).toList() + ..sort((a, b) => a.startMs.compareTo(b.startMs)); + + expect(plan, hasLength(3), reason: '0:18–1:15, 1:51–2:35, 2:40–4:59'); + final int margin = GapBackfillService.margin.inMilliseconds; + expect(plan[1].startMs, lessThanOrEqualTo(111630 - margin)); + expect(plan[2].startMs, lessThanOrEqualTo(160000 - margin)); + final List replaced = [ + for (final p in plan) ...p.replacedIds, + ]; + expect(replaced.toSet(), hasLength(replaced.length), reason: 'une fois'); + expect(replaced, contains('${sessionId}_output_18')); + }); + + test('après le rattrapage : chaque phrase une fois, dans l ordre, plus ' + 'aucun repère de ces unions', () async { + final Directory dir = await Directory.systemTemp.createTemp( + 'oats_overlapping_markers_', + ); + addTearDown(() => dir.delete(recursive: true)); + final WavRecorder recorder = WavRecorder(); + await recorder.open('${dir.path}/${sessionId}_system.wav'); + for (int c = 0; c < 3200; c++) { + final Uint8List chunk = Uint8List(3200); + final ByteData d = ByteData.sublistView(chunk); + for (int o = 0; o < 3200; o += 2) { + d.setInt16(o, c * 4 + 2, Endian.little); + } + await recorder.append(chunk); + } + await recorder.close(); + final InMemoryTranscriptRepository repo = InMemoryTranscriptRepository(); + for (final TranscriptSegmentEntity s in stored()) { + await repo.save(s); + } + + await GapBackfillService( + transcriber: _Recorded(), + transcripts: repo, + isRecording: () => false, + ).backfill(sessionId, recordingsDirectory: dir.path); + + final List lines = repo.of(AudioSource.output) + ..sort((a, b) => a.timestampMs.compareTo(b.timestampMs)); + expect( + lines.where( + (TranscriptSegmentEntity s) => isMarker(s) && s.timestampMs >= 100000, + ), + isEmpty, + reason: 'repères des deux unions retirés', + ); + int last = -1; + for (final ({int atMs, String text}) p in probe7SystemRecovered.where( + (({int atMs, String text}) p) => p.atMs >= 100000, + )) { + final String clause = p.text.split(',').first; + final List at = [ + for (int i = 0; i < lines.length; i++) + if (lines[i].text.contains(clause)) i, + ]; + expect(at, hasLength(1), reason: '« $clause » une seule fois'); + expect(at.single, greaterThan(last), reason: '« $clause » dans l ordre'); + last = at.single; + } + }); +} + +/// Texte du rattrapage enregistré, choisi par l'heure du PCM demandé (chaque +/// échantillon d'un pas de 100 ms vaut numéro × 4 + piste). +final class _Recorded implements PcmTranscriber { + @override + Future> transcribe(Uint8List pcm) async { + final int v = ByteData.sublistView(pcm).getInt16(0, Endian.little); + final int startMs = (v ~/ 4) * 100; + final int endMs = startMs + pcm.length ~/ 32; + return <({int offsetMs, String text})>[ + for (final ({int atMs, String text}) p in probe7SystemRecovered) + if (p.atMs >= startMs - 1500 && p.atMs < endMs) + (offsetMs: p.atMs - startMs, text: p.text), + ]; + } +} diff --git a/apps/app_macos/test/fixtures/probe7_overlap.dart b/apps/app_macos/test/fixtures/probe7_overlap.dart new file mode 100644 index 0000000..a7d6932 --- /dev/null +++ b/apps/app_macos/test/fixtures/probe7_overlap.dart @@ -0,0 +1,236 @@ +// GÉNÉRÉ depuis la sonde 7 (scratchpad/probe/live7) : état rangé en fin de +// scénario Dlag SANS rattrapage (svc_Dlag_nobf.jsonl), son système, et +// texte rendu par le rattrapage du même audio dans le scénario Dlag +// (svc_Dlag.jsonl). Copié tel quel. + +typedef Probe7Segment = ({String id, int timestampMs, String text}); + +const String probe7SessionId = '1795396098594'; + +/// Segments système rangés (repères compris) à la fin de Dlag sans +/// rattrapage : 1:51–2:35 contient 1:58–2:04 et 2:12–2:14. +const List probe7SystemStored = [ + ( + id: '1795396098594_output_1', + timestampMs: 30, + text: + 'The baker cleaned the old greenhouse without telling anyone, and then the librarian cleaned the bus shelter with a lot of patience.', + ), + ( + id: '1795396098594_output_3', + timestampMs: 9030, + text: + 'Le libraire a rangé la fontaine ronde malgré le vent froid, puis la gardienne a réparé la vieille barrière pour la rentrée des classes.', + ), + (id: '1795396098594_output_5', timestampMs: 18730, text: 'The'), + ( + id: '1795396098594_output_7', + timestampMs: 18730, + text: 'Transcription interrompue : 00:00:18 – 00:01:15', + ), + ( + id: '1795396098594_output_11', + timestampMs: 74330, + text: + 'Graph the green bench despite the cold wind, and then the postman cleaned the green bench despite the cold wind.', + ), + ( + id: '1795396098594_output_12', + timestampMs: 83730, + text: + 'Le libraire a décoré le kiosque à journaux malgré le vent froid, puis la gardienne a nettoyé le portail pour la rentrée des classes.', + ), + ( + id: '1795396098594_output_14', + timestampMs: 92830, + text: + 'The librarian painted the old greenhouse for the start of school, and then the baker measured the round fountain before the evening rain.', + ), + ( + id: '1795396098594_output_16', + timestampMs: 101930, + text: + 'La voisine a nettoyé le kiosque à journaux avant la pluie du soir, puis le maire a mesuré le portail avec beaucoup de patience.', + ), + ( + id: '1795396098594_output_22', + timestampMs: 111630, + text: 'Transcription interrompue : 00:01:51 – 00:02:35', + ), + ( + id: '1795396098594_output_18', + timestampMs: 118530, + text: + 'The mayor painted the stone wall during the village fair, and then the gardener moved the bus shelter before the evening', + ), + ( + id: '1795396098594_output_20', + timestampMs: 118530, + text: 'Transcription interrompue : 00:01:58 – 00:02:04', + ), + ( + id: '1795396098594_output_21', + timestampMs: 132830, + text: 'Transcription interrompue : 00:02:12 – 00:02:14', + ), + ( + id: '1795396098594_output_26', + timestampMs: 156930, + text: + 'La gardienne a déplacé la vieille barrière avant la pluie de soir, puis la gardienne a nettoyé le kiosque à journaux sous un ciel gris.', + ), + ( + id: '1795396098594_output_27', + timestampMs: 165830, + text: 'The teacher cleaned', + ), + ( + id: '1795396098594_output_29', + timestampMs: 165830, + text: 'Transcription interrompue : 00:02:45 – 00:04:59', + ), +]; + +/// Texte rendu par le rattrapage du même audio (Dlag), heures de réunion. +const List<({int atMs, String text})> +probe7SystemRecovered = <({int atMs, String text})>[ + ( + atMs: 17714, + text: + 'The librarian tidied the small cabin with a lot of patience, and then the postman painted the old greenhouse with a lot of patience.', + ), + ( + atMs: 27314, + text: + 'La boulangère a décoré le portail sans prévenir personne, puis le jardinier a mesuré le banc vert avant la pluie du soir.', + ), + ( + atMs: 36114, + text: + 'The librarian photographed the garden gate despite the cold wind, and then the baker moved the green bench for the start of school.', + ), + ( + atMs: 45514, + text: + 'Le facteur a mesuré la fontaine ronde malgré le vent froid, puis le facteur a photographié le lavoir pendant la fête du village.', + ), + ( + atMs: 54114, + text: + 'The mayor measured the round fountain without telling anyone, and then the gardener photographed the old greenhouse without telling anyone.', + ), + ( + atMs: 63414, + text: + 'Lo veo a fotob vacío y el kiosque a journaux por la rentrée des classes, puis la boulangère a repeint la cabane avant la pluie du soir.', + ), + ( + atMs: 72614, + text: + 'The baker photographed the green bench despite the cold wind, and then the postman cleaned the green bench despite the cold wind.', + ), + ( + atMs: 110614, + text: + 'The mayor painted the stone wall during the village fair, and then the gardener moved the bus shelter before the evening rain.', + ), + ( + atMs: 119214, + text: + 'Le libraire a nettoyé le kiosque à journaux avec beaucoup de patience, puis la voisine a nettoyé le kiosque à journaux au lever du soleil.', + ), + ( + atMs: 128014, + text: + 'The librarian decorated the old greenhouse with a lot of patience, and then the teacher painted the round fountain with a lot of patience.', + ), + ( + atMs: 137714, + text: + 'La boulangère a décoré la cabane pendant la fête du village, puis le libraire a rangé la fontaine ronde avec beaucoup de patience.', + ), + ( + atMs: 146514, + text: + 'The baker painted the old greenhouse at sunrise, and then the librarian painted the small cabin with a lot of patience.', + ), + ( + atMs: 155814, + text: + 'La gardienne a déplacé la vieille barrière avant la pluie du soir, puis la gardienne a nettoyé le kiosque à journaux sous un ciel gris.', + ), + ( + atMs: 164814, + text: + 'The teacher cleaned the round fountain without telling anyone, and then the postman repaired the round fountain despite the cold wind.', + ), + ( + atMs: 173714, + text: + 'La boulangère a basuré la cabane malgré le vent froid, puis le libraire a basuré la cabane avec beaucoup de patience.', + ), + ( + atMs: 182414, + text: + 'The librarian repaired the wooden fence with a lot of patience, and then my neighbor photographed the stone wall at sunrise.', + ), + ( + atMs: 192514, + text: + 'La musicienne a rangé le kiosque à journaux sous un ciel gris, puis la boulangère a repeint le portail pendant la fête du village.', + ), + ( + atMs: 201814, + text: + 'The painter moved the small cabin without telling anyone, and then the gardener painted the round fountain for the start of school.', + ), + ( + atMs: 211114, + text: + 'La musicienne a basuré la cabane sous un ciel gris, puis le libraire a réparé la fontaine ronde pendant la fête du village.', + ), + ( + atMs: 219614, + text: + 'The Gognatided the Green Bench before the evening rain, and then the librarian repaired the old greenhouse without telling anyone.', + ), + ( + atMs: 229814, + text: + 'L\'omère a basuré le kiosque à journaux pour la rentrée des classes, puis le facteur a déplacé la cabane malgré le vent froid.', + ), + ( + atMs: 239114, + text: + 'The teacher painted the bus shelter before the evening rain, and then the postman painted the old greenhouse without telling anyone.', + ), + ( + atMs: 249114, + text: + 'Le libraire a repeint le kiosque à journaux pour la rentrée des classes, puis le jardinier a déplacé la serre sans prévenir personne.', + ), + ( + atMs: 258114, + text: + 'The librarian photographed the green bench despite the cold wind, and then the postman repaired the bus shelter under a grey sky.', + ), + ( + atMs: 267914, + text: + 'La gardienne allait soigner le lavoir avant la pluie du soir, puis le libraire a photographié la cabane sans prévenir personne.', + ), + ( + atMs: 277014, + text: + 'The painter measured the small cabin without telling anyone, and then the mayor measured the garden gate without telling anyone.', + ), + ( + atMs: 286214, + text: + 'Le jardinier a réparé la vieille barrière sous un ciel gris, puis le libraire a rangé la vieille barrière au lever du soleil.', + ), + ( + atMs: 294814, + text: 'The painter repaired the small cabin during the village fair, and', + ), +]; From 9725890e242a169fab15743977c053bc7e2c902f Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:55:45 +0100 Subject: [PATCH 07/14] test(app): after a merge the live screen lists exactly one marker of the union --- .../services/gap_marker_merge_test.dart | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/apps/app_macos/test/application/services/gap_marker_merge_test.dart b/apps/app_macos/test/application/services/gap_marker_merge_test.dart index 193bd16..935070b 100644 --- a/apps/app_macos/test/application/services/gap_marker_merge_test.dart +++ b/apps/app_macos/test/application/services/gap_marker_merge_test.dart @@ -54,6 +54,20 @@ void main() { final plan = GapBackfillService.plan(h.segments.store.values.toList()); expect(plan.where((p) => p.source == AudioSource.output), hasLength(1)); + + // Revue PR #25, point 4 : l'écran aussi ne liste qu'un repère. + final List listed = h + .transcription + .segmentsStream + .value + .where( + (TranscriptSegmentEntity x) => + x.source == AudioSource.output && + x.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + expect(listed, hasLength(1), reason: 'un seul repère à l écran'); + expect(listed.single.text, marker.text); }); }); From 2568ba8800340584389e6cd8e14939755366a511 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:56:09 +0100 Subject: [PATCH 08/14] test(app): provisional and final markers never overlap; a withdrawn provisional never merges with a later loss --- .../provisional_marker_merge_test.dart | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 apps/app_macos/test/application/services/provisional_marker_merge_test.dart diff --git a/apps/app_macos/test/application/services/provisional_marker_merge_test.dart b/apps/app_macos/test/application/services/provisional_marker_merge_test.dart new file mode 100644 index 0000000..156e40d --- /dev/null +++ b/apps/app_macos/test/application/services/provisional_marker_merge_test.dart @@ -0,0 +1,141 @@ +import 'package:core_data/datasources/remote/impl/transcription.remote.data_source.impl.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 2, en séance (vraie source distante, sockets +// factices) : le repère provisoire de la coupure en cours et le repère +// final d'une perte de la même source qui se touchent ne laissent jamais +// deux repères ; un repère provisoire retiré (coupure finie sans perte) ne +// fusionne pas avec une perte PLUS TARDIVE (sinon de l'audio transcrit +// serait déclaré perdu). +void main() { + late FakeAsync clock; + late FakeVoxSocket mic; + late LiveServiceHarness h; + + void setUpIn(FakeAsync async) { + clock = async; + final FakeVoxServer server = FakeVoxServer(); + mic = FakeVoxSocket(server); + h = LiveServiceHarness( + async, + remote: TranscriptionRemoteDataSourceImpl( + micClient: mic, + systemClient: FakeVoxSocket(server), + ), + )..start(outputEnabled: false); + } + + int id = 0; + + /// Parole continue du micro, [seconds] s, en 100 ms. + void speak(int seconds, {void Function()? eachSecond}) { + for (int i = 0; i < seconds * 10; i++, id++) { + h.audio.emit(chunk(AudioSource.input, id, timestampMs: h.t0 + id * 100)); + clock.elapse(const Duration(milliseconds: 100)); + if (i % 10 == 9) eachSecond?.call(); + } + } + + List<(int, int)> markerIntervals() { + final List<(int, int)> out = <(int, int)>[]; + for (final TranscriptSegmentEntity s in h.segments.of(AudioSource.input)) { + if (!s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix)) { + continue; + } + final ({String markerId, AudioSource source, int startMs, int endMs})? p = + GapBackfillService.plan([s]) + .map( + (g) => ( + markerId: g.markerId, + source: g.source, + startMs: g.startMs, + endMs: g.endMs, + ), + ) + .firstOrNull; + if (p != null) out.add((p.startMs, p.endMs)); + } + return out; + } + + bool overlapOrTouch(List<(int, int)> xs) { + // Les intervalles du plan sont élargis de la marge des deux côtés. + final int slack = 2 * GapBackfillService.margin.inMilliseconds; + for (int i = 0; i < xs.length; i++) { + for (int j = i + 1; j < xs.length; j++) { + if (xs[i].$1 <= xs[j].$2 - slack && xs[j].$1 <= xs[i].$2 - slack) { + return true; + } + } + } + return false; + } + + test('coupure plus longue que le tampon : le repère provisoire et le ' + 'repère final ne coexistent jamais en se recoupant', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + speak(10); + mic + ..refusing = true + ..drop(); + final List seen = []; + void check() { + final List<(int, int)> xs = markerIntervals(); + if (overlapOrTouch(xs)) seen.add('${async.elapsed}: $xs'); + } + + speak(150, eachSecond: check); // le tampon déborde + mic.refusing = false; + speak(60, eachSecond: check); // reconnexion, renvoi, perte déclarée + + expect(seen, isEmpty, reason: 'repères qui se recoupent : $seen'); + expect(markerIntervals(), hasLength(1)); + }); + }); + + test('un repère provisoire retiré ne fusionne pas avec une perte plus ' + 'tardive', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + speak(10); + mic + ..refusing = true + ..drop(); + speak(5); // courte coupure : repère provisoire + mic.refusing = false; + speak(30); // tout est livré : le provisoire est retiré + expect(markerIntervals(), isEmpty, reason: 'rien n a été perdu'); + + final int lateOutageMs = id * 100; + mic + ..refusing = true + ..drop(); + speak(150); + mic.refusing = false; + speak(60); + + final List<(int, int)> xs = markerIntervals(); + expect(xs, hasLength(1)); + // La perte peut commencer avant la seconde coupure (la phrase en vol, + // sans réponse, est perdue avec elle : 30 s au plus), jamais à la + // première, toute livrée. + expect( + xs.single.$1 + GapBackfillService.margin.inMilliseconds, + greaterThanOrEqualTo(lateOutageMs - 31000), + reason: 'la perte ne remonte pas à la première coupure', + ); + expect( + xs.single.$1 + GapBackfillService.margin.inMilliseconds, + greaterThan(45000), + ); + }); + }); +} From e9661c5e8c43d69e1e738b37c40d778750a69791 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:56:54 +0100 Subject: [PATCH 09/14] test(app): the union marker is stored even after a failed write; siblings go only after the union --- .../gap_marker_merge_atomic_test.dart | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart diff --git a/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart b/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart new file mode 100644 index 0000000..aab18cd --- /dev/null +++ b/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart @@ -0,0 +1,138 @@ +import 'dart:async'; + +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 3 : la fusion des repères n'est pas atomique (les +// retraits des repères englobés et l'écriture de l'union passent par des +// chaînes différentes ; une écriture ratée plus tôt pour le même id fait +// sauter l'union). Attendu, avec un dépôt qui échoue une fois : +// - l'union est quand même rangée, aucun intervalle ne reste sans repère ; +// - l'écriture suivante d'un id passe même si la précédente a échoué ; +// - les repères englobés ne sont retirés qu'une fois l'union rangée. +// +// Pertes : A 1:00–1:10, B 1:30–1:40, puis C 1:05–1:35 qui touche les deux : +// union 1:00–1:40. +void main() { + final RegExp union = RegExp(r'00:01:00\s*[–-]\s*00:01:40'); + + List markers(InMemoryTranscriptRepository repo) => + repo + .of(AudioSource.output) + .where( + (TranscriptSegmentEntity s) => + s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + + void gaps(LiveServiceHarness h, FakeAsync async, {bool third = true}) { + for (final (int, int) g in <(int, int)>[ + (60000, 70000), + (90000, 100000), + if (third) (65000, 95000), + ]) { + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.output, + startMs: h.t0 + g.$1, + endMs: h.t0 + g.$2, + ), + ); + async.elapse(const Duration(milliseconds: 200)); + } + } + + test('la première écriture du repère échoue : l union est quand même ' + 'rangée sous un seul repère', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + failOnce: (TranscriptSegmentEntity s) => s.text.contains('00:01:10'), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 5)); + + expect(repo.failures, 1, reason: 'le dépôt a bien échoué une fois'); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); + + test('l écriture de l union échoue une fois : elle est rangée quand même, ' + 'aucun intervalle sans repère', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + failOnce: (TranscriptSegmentEntity s) => union.hasMatch(s.text), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 30)); + + expect(repo.failures, 1); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); + + test('les repères englobés restent tant que l union n est pas rangée', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + hold: (TranscriptSegmentEntity s) => union.hasMatch(s.text), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 5)); + + // L'union attend : 1:30–1:40 doit toujours avoir son repère. + expect( + markers( + repo, + ).where((TranscriptSegmentEntity s) => s.text.contains('00:01:30')), + hasLength(1), + reason: 'retiré avant que l union soit rangée', + ); + + repo.release(); + async.elapse(const Duration(seconds: 5)); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); +} + +/// Dépôt qui échoue une fois sur la première écriture qui vérifie +/// [failOnce], ou retient les écritures qui vérifient [hold]. +class _FlakyRepository extends InMemoryTranscriptRepository { + _FlakyRepository({this.failOnce, this.hold}); + + final bool Function(TranscriptSegmentEntity s)? failOnce; + final bool Function(TranscriptSegmentEntity s)? hold; + int failures = 0; + final Completer _gate = Completer(); + + void release() { + if (!_gate.isCompleted) _gate.complete(); + } + + @override + Future save(TranscriptSegmentEntity segment) async { + if (failures == 0 && (failOnce?.call(segment) ?? false)) { + failures++; + throw Exception('disque plein'); + } + if (hold?.call(segment) ?? false) await _gate.future; + return super.save(segment); + } +} From e0958b49232a552429d8a17c11b1194854a0fbd6 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 03:57:05 +0100 Subject: [PATCH 10/14] test(core_data): a new session starts again with the 10 s handshake bound --- ...n_remote_data_source_slow_accept_test.dart | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart index 1a51530..68b7668 100644 --- a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart +++ b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart @@ -222,4 +222,50 @@ void main() { ); }); }); + + // Revue PR #25, point 5 : l'app vit des jours dans la barre de menus ; la + // borne apprise ne doit pas survivre à la séance. Une nouvelle note + // (connexion de début de séance) repart à 10 s. + test('une nouvelle séance repart à 10 s, quoi que la précédente ait ' + 'appris', () { + fakeAsync((FakeAsync async) { + final DataSourceBench b = DataSourceBench(async); + async.elapse(const Duration(seconds: 1)); + int id = 0; + void outage(int seconds) { + b.mic + ..acceptDelay = const Duration(seconds: 15) + ..drop(); + for (int i = 0; i < seconds * 10; i++, id++) { + b.tick( + id, + voiced: {AudioSource.input: id % 50 < 40}, + ); + } + } + + outage(40); // apprend 20 s + b.dataSource.disconnect(); // fin de la note + async.elapse(const Duration(hours: 6)); + b.mic.acceptDelay = Duration.zero; + b.dataSource.connect(systemAudioEnabled: false); // nouvelle note + async.elapse(const Duration(seconds: 1)); + + final Duration drop = async.elapsed; + outage(40); + final List attempts = b.mic.connectAttempts + .where((Duration t) => t >= drop) + .toList(); + expect(attempts.length, greaterThanOrEqualTo(2)); + expect( + attempts[1] - attempts[0], + greaterThanOrEqualTo(const Duration(seconds: 10)), + ); + expect( + attempts[1] - attempts[0], + lessThanOrEqualTo(const Duration(milliseconds: 11500)), + reason: 'borne de départ de la séance : 10 s', + ); + }); + }); } From 25db0ce2813b3f9aa70f8bef4a04a86496cc4a71 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 04:02:20 +0100 Subject: [PATCH 11/14] fix(app): the backfill plans one interval per union of stored markers Why: the provisional marker is written outside the live merge, and a kill during an outage can leave overlapping markers on disk (probe 7); plan() trusted what was stored and planned nested intervals twice. What: plan() merges the gap markers of one source that overlap or touch into unions: one interval under the first marker, the end of the latest; the absorbed markers go into replacedIds and are removed when the union is recovered. The extension of an interval to the next intact segment stops where the next union of the source starts, so no audio is transcribed twice. The end-edge exception uses the union's end. How proven: gap_backfill_overlapping_markers (probe-7 stored state) green; time edges, edge exception, backfill, overlap, sealed partial and marker merge specs green (39). --- .../services/gap_backfill.service.dart | 107 ++++++++++++++++-- 1 file changed, 97 insertions(+), 10 deletions(-) diff --git a/apps/app_macos/lib/application/services/gap_backfill.service.dart b/apps/app_macos/lib/application/services/gap_backfill.service.dart index 5d17e6d..a92fbe4 100644 --- a/apps/app_macos/lib/application/services/gap_backfill.service.dart +++ b/apps/app_macos/lib/application/services/gap_backfill.service.dart @@ -90,17 +90,80 @@ final class GapBackfillService { /// (jusqu'au segment intact suivant, 30 s au plus). Les autres sources, /// les segments hors fenêtre et les passages non transcrits ne sont /// jamais touchés. + /// + /// Les repères rangés d'une source qui se recoupent ou se touchent (un + /// repère provisoire et un final après un arrêt brutal, sonde 7) forment + /// une union : un seul intervalle, sous le premier repère ; les autres + /// repères de l'union sont dans [BackfillGap.replacedIds] et partent quand + /// l'union est retrouvée. static List plan( List segments, { List dictated = const [], }) => [ - for (final TranscriptSegmentEntity s in segments) - if (_isGapMarker(s)) - if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) - if (!_insideDictation(s, m, dictated)) - ..._planMarker(s, _ms(m, 4), segments, dictated), + for (final _MarkerUnion u in _unions(segments, dictated)) + for (final BackfillGap g in _planMarker( + u.first, + u.end, + segments, + dictated, + endLimit: u.nextStart, + )) + ( + markerId: g.markerId, + source: g.source, + startMs: g.startMs, + endMs: g.endMs, + replacedIds: [...g.replacedIds, ...u.others], + ), ]; + /// Unions des repères de perte d'une même source (début, fin), hors + /// dictée, triées par début. + static List<_MarkerUnion> _unions( + List segments, + List dictated, + ) { + final List<({TranscriptSegmentEntity marker, int end})> markers = + <({TranscriptSegmentEntity marker, int end})>[ + for (final TranscriptSegmentEntity s in segments) + if (_isGapMarker(s)) + if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) + if (!_insideDictation(s, m, dictated)) + (marker: s, end: _ms(m, 4)), + ]..sort( + ( + ({TranscriptSegmentEntity marker, int end}) a, + ({TranscriptSegmentEntity marker, int end}) b, + ) => a.marker.timestampMs.compareTo(b.marker.timestampMs), + ); + final List<_MarkerUnion> unions = <_MarkerUnion>[]; + for (final ({TranscriptSegmentEntity marker, int end}) m in markers) { + _MarkerUnion? open; + for (final _MarkerUnion u in unions.reversed) { + if (u.first.source == m.marker.source && + m.marker.timestampMs <= u.end) { + open = u; + break; + } + } + if (open == null) { + unions.add(_MarkerUnion(m.marker, m.end)); + } else { + open.others.add(m.marker.id); + if (m.end > open.end) open.end = m.end; + } + } + for (int i = 0; i < unions.length; i++) { + for (int j = i + 1; j < unions.length; j++) { + if (unions[j].first.source == unions[i].first.source) { + unions[i].nextStart = unions[j].first.timestampMs; + break; + } + } + } + return unions; + } + /// Un segment qui commence à moins de [edgeTolerance] d'un bord de la /// perte appartient à la phrase coupée (le texte arrive ~1 s après /// l'audio ; sonde 5 : au plus 1,2 s après le début, 1 s avant la fin). @@ -119,8 +182,9 @@ final class GapBackfillService { TranscriptSegmentEntity marker, int lostEnd, List segments, - List dictated, - ) { + List dictated, { + int? endLimit, + }) { final int tolerance = edgeTolerance.inMilliseconds; final List live = segments @@ -156,6 +220,11 @@ final class GapBackfillService { : last + _afterReplacedSpan.inMilliseconds; if (cover > end) end = cover; } + // Le prolongement s'arrête où commence l'union suivante de la source : + // son audio est retranscrit par elle (jamais deux fois). + if (endLimit != null && end > endLimit) { + end = endLimit > lostEnd ? endLimit : lostEnd; + } if (start < 0) start = 0; final List ids = [ for (final TranscriptSegmentEntity x in replaced) x.id, @@ -322,9 +391,14 @@ final class GapBackfillService { // (gap_backfill_overlap_test) : on la garde et on retire le doublon. // Tout ce qui commence avant la fin reste remplacé, quel que soit son // texte (sonde 5). - final int? lostEnd = _markerTimes.firstMatch(marker.text) == null - ? null - : _ms(_markerTimes.firstMatch(marker.text)!, 4); + // Fin de l'union : celle du plus tardif de ses repères. + final int? lostEnd = [ + for (final TranscriptSegmentEntity s in segments) + if ((s.id == marker.id || gap.replacedIds.contains(s.id)) && + _isGapMarker(s)) + if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) + _ms(m, 4), + ].fold(null, (int? a, int b) => a == null || b > a ? b : a); final TranscriptSegmentEntity? edge = lostEnd == null ? null : (segments @@ -524,3 +598,16 @@ final class GapBackfillService { /// Issue d'un morceau de repère. enum _Part { noAudio, unavailable, failed, nothingNew, saved } + +/// Union de repères de perte d'une source : le premier (par début), la fin +/// la plus tardive, et les autres repères qu'elle absorbe. +class _MarkerUnion { + _MarkerUnion(this.first, this.end); + + final TranscriptSegmentEntity first; + int end; + + /// Début de l'union suivante de la même source, s'il y en a une. + int? nextStart; + final List others = []; +} From 1942a78ea596405f7b8bc34ec35feda7250bdc1a Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 04:04:36 +0100 Subject: [PATCH 12/14] fix(app): a merged gap marker is stored before its siblings go Why: the union of overlapping losses and the removal of the absorbed markers ran on different chains, and a failed earlier write for an id skipped every later write for it: an interval could be left with no marker. What: the union write waits for pending writes of the absorbed markers, saves the union (retried 1, 2, 4, 8 s; saveSegment now says whether it stored), and only then removes the siblings. _chainWrite logs a failed write and still runs the next one for that id. How proven: gap_marker_merge_atomic (failing and held repository) green with gap_marker_merge, restamp_write_order and sealed_partial_time (11); core_domain 58 green. --- .../services/live_transcription.service.dart | 50 +++++++++++++++---- .../services/transcription.service.dart | 35 +++++++------ 2 files changed, 59 insertions(+), 26 deletions(-) diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index 463b36c..17192f1 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -905,16 +905,9 @@ final class LiveTranscriptionService { final String id = touched.isEmpty ? _newSegmentId(session, source) : touched.first.id; - for (final ({String id, int start, int end}) m in touched.skip(1)) { - _chainWrite(m.id, () async { - await _transcriptionService.discardProvisional(m.id); - _transcriptionService.segmentsStream.add( - List.from( - _transcriptionService.segmentsStream.value, - )..removeWhere((TranscriptSegmentEntity x) => x.id == m.id), - ); - }); - } + final List absorbed = [ + for (final ({String id, int start, int end}) m in touched.skip(1)) m.id, + ]; markers ..removeWhere(touched.contains) ..add((id: id, start: from, end: to)); @@ -927,7 +920,39 @@ final class LiveTranscriptionService { createdAt: clock.now(), ); _log.warning('Audio non transcrit: ${marker.text} (${source.name})'); - _savePartial(marker); + // Atomique pour l'utilisateur : l'union est rangée d'abord (réessayée si + // l'écriture échoue), les repères absorbés ne partent qu'ensuite ; aucun + // intervalle ne reste sans repère. + final List> absorbedWrites = >[ + for (final String other in absorbed) ?_segmentWrites[other], + ]; + _chainWrite(id, () async { + await Future.wait(absorbedWrites); + if (!await _saveWithRetry(marker)) return; + _sortAndDedupeSegments(); + for (final String other in absorbed) { + await _transcriptionService.discardProvisional(other); + _transcriptionService.segmentsStream.add( + List.from( + _transcriptionService.segmentsStream.value, + )..removeWhere((TranscriptSegmentEntity x) => x.id == other), + ); + } + }); + } + + // Un repère qui ne se range pas est réessayé : 1, 2, 4, 8 s. + static const int _markerWriteAttempts = 5; + + Future _saveWithRetry(TranscriptSegmentEntity segment) async { + for (int attempt = 0; attempt < _markerWriteAttempts; attempt++) { + if (attempt > 0) { + await Future.delayed(Duration(seconds: 1 << (attempt - 1))); + } + if (await _transcriptionService.saveSegment(segment)) return true; + } + _log.error('Repère non rangé après $_markerWriteAttempts essais'); + return false; } // Écritures chaînées par id de segment : la dernière valeur voulue est @@ -937,8 +962,11 @@ final class LiveTranscriptionService { void _chainWrite(String id, Future Function() write) { late final Future task; + // Une écriture ratée plus tôt pour cet id n'empêche pas la suivante. task = (_segmentWrites[id] ?? Future.value()) + .catchError((Object e) => _log.error('Écriture de $id ratée', e)) .then((_) => write()) + .catchError((Object e) => _log.error('Écriture de $id ratée', e)) .whenComplete(() { _pendingFinalizations.remove(task); if (identical(_segmentWrites[id], task)) _segmentWrites.remove(id); diff --git a/packages/core_domain/lib/domain/services/transcription.service.dart b/packages/core_domain/lib/domain/services/transcription.service.dart index d3c1c10..cbdfafe 100644 --- a/packages/core_domain/lib/domain/services/transcription.service.dart +++ b/packages/core_domain/lib/domain/services/transcription.service.dart @@ -88,23 +88,28 @@ final class TranscriptionService { /// Sauvegarde un segment de transcription et met a jour le stream. /// /// Un segment de meme id (provisoire) est remplace, en base et a l'ecran. - Future saveSegment(TranscriptSegmentEntity segment) async { + /// + /// Rend vrai si le segment est rangé. + Future saveSegment(TranscriptSegmentEntity segment) async { final ResultState result = await _saveTranscriptSegmentUseCase.execute(segment); - result.when( - success: (TranscriptSegmentEntity savedSegment) { - final List currentSegments = - List.from(segmentsStream.value) - ..removeWhere( - (TranscriptSegmentEntity s) => s.id == savedSegment.id, - ); - currentSegments.add(savedSegment); - segmentsStream.add(currentSegments); - }, - failure: (Exception e) { - _log.error('Erreur sauvegarde segment', e); - }, - ); + return result.when( + success: (TranscriptSegmentEntity savedSegment) { + final List currentSegments = + List.from(segmentsStream.value) + ..removeWhere( + (TranscriptSegmentEntity s) => s.id == savedSegment.id, + ); + currentSegments.add(savedSegment); + segmentsStream.add(currentSegments); + return true; + }, + failure: (Exception e) { + _log.error('Erreur sauvegarde segment', e); + return false; + }, + ) ?? + false; } /// Sauve en base la phrase en cours, sans la montrer : l'ecran garde son From f0f236962b3d2b878c75fd10aa601ca63cbf0ba0 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 04:04:36 +0100 Subject: [PATCH 13/14] fix(core_data): a new session starts again at the 10 s handshake bound Why: the app lives in the menu bar for days; a slow server learned in one session made every later session wait up to 60 s for a dead socket. What: connect() resets the learned slow-accept count of both sources. How proven: transcription_remote_data_source_slow_accept green (7). --- .../remote/impl/transcription.remote.data_source.impl.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart index 5667372..1043fd2 100644 --- a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart +++ b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart @@ -150,6 +150,9 @@ final class TranscriptionRemoteDataSourceImpl _systemConnected = systemAudioEnabled; _clearOutages(); _resetUtteranceState(); + // Une nouvelle séance repart de la borne de 10 s : l'app vit des jours + // dans la barre des menus, un serveur lent d'hier ne compte plus. + _learnedSlowAccepts.updateAll((_, _) => 0); if (_closedSubscriptions.isEmpty) { _closedSubscriptions ..add(_mic.onClosed.listen((_) => _onSocketClosed(AudioSource.input))) From a30d74c9c7e02a34ef58607c30d0e2e509b8d6fc Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 04:09:13 +0100 Subject: [PATCH 14/14] docs(app): name the ceiling of the gap marker retry Why: five attempts then a logged give-up is a deliberate shortcut; Stop may wait up to 15 s more on a failing disk. What: ponytail comment only. How proven: analyze clean. --- .../lib/application/services/live_transcription.service.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index 17192f1..b0cdb4e 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -942,6 +942,8 @@ final class LiveTranscriptionService { } // Un repère qui ne se range pas est réessayé : 1, 2, 4, 8 s. + // ponytail: 5 essais (15 s, Stop attend au pire autant) puis abandon + // journalisé ; file durable si un disque plein doit tenir plus longtemps. static const int _markerWriteAttempts = 5; Future _saveWithRetry(TranscriptSegmentEntity segment) async {