From 845b0f1e55599f559c298203e4ec5e0c05e9fa68 Mon Sep 17 00:00:00 2001 From: Strycher Date: Fri, 25 Sep 2026 00:28:44 -0400 Subject: [PATCH] fix(#711): drain serial on each callback; never drop bytes silently Two app-side halves of the #702 fix. The native USB service read one 8 KB chunk per flserial callback, which left the rest of a burst waiting in the native ring. It now drains until the ring is empty, bounded at 32 reads (the ring's 256 KB) so a stuck read cannot spin. The frame decoder skipped bytes it could not frame (noise, an oversized length) without a word, so when bytes were lost upstream, whole frames vanished with no trace. It now counts them and keeps the first 16; the native USB, web USB and TCP services log each batch as an error with the count and a hex sample (SAFELANE 6). The web service shares the decoder, so it gets the same logging, matching the plan's "all transports" intent. Tests cover no report on clean input, noise before a frame, an oversized header, take-once, the capped sample and reset; with the count disabled, 4 fail. Epic #702. Co-Authored-By: Claude Opus 5.5 --- .../tcp_transport_service_native.dart | 4 + lib/services/usb_serial_frame_codec.dart | 49 +++++++++++- lib/services/usb_serial_service_native.dart | 16 +++- lib/services/usb_serial_service_web.dart | 6 ++ .../services/usb_serial_frame_codec_test.dart | 77 +++++++++++++++++++ 5 files changed, 148 insertions(+), 4 deletions(-) diff --git a/lib/services/tcp_transport_service_native.dart b/lib/services/tcp_transport_service_native.dart index a6db99b5..a6911f1d 100644 --- a/lib/services/tcp_transport_service_native.dart +++ b/lib/services/tcp_transport_service_native.dart @@ -167,6 +167,10 @@ class TcpTransportService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + _debugLogService?.error('TCP ${skipped.describe()}', tag: 'TCP'); + } } void _handleSocketError(Object error, [StackTrace? stackTrace]) { diff --git a/lib/services/usb_serial_frame_codec.dart b/lib/services/usb_serial_frame_codec.dart index 0b7b39a7..4a936ec6 100644 --- a/lib/services/usb_serial_frame_codec.dart +++ b/lib/services/usb_serial_frame_codec.dart @@ -37,13 +37,58 @@ class UsbSerialDecodedPacket { bool get isRxFrame => frameStart == usbSerialRxFrameStart; } +/// Bytes the decoder could not frame and discarded (#711). Lost bytes mean +/// lost frames, so callers log this as an error rather than drop it quietly. +class UsbSerialSkipReport { + const UsbSerialSkipReport({required this.count, required this.sample}); + + final int count; + + /// The first discarded bytes, for the log. + final List sample; + + String describe() { + final hex = sample + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(' '); + return 'discarded $count byte(s) that could not be framed ' + '(first: $hex${count > sample.length ? ' ...' : ''})'; + } +} + class UsbSerialFrameDecoder { + static const int _skipSampleLength = 16; + final List _rxBuffer = []; int _startIndex = 0; + int _skipped = 0; + final List _skipSample = []; void reset() { _rxBuffer.clear(); _startIndex = 0; + _skipped = 0; + _skipSample.clear(); + } + + /// Returns what was discarded since the last call, or null if nothing was. + UsbSerialSkipReport? takeSkipReport() { + if (_skipped == 0) return null; + final report = UsbSerialSkipReport( + count: _skipped, + sample: List.unmodifiable(_skipSample), + ); + _skipped = 0; + _skipSample.clear(); + return report; + } + + void _skipByte() { + _skipped++; + if (_skipSample.length < _skipSampleLength) { + _skipSample.add(_rxBuffer[_startIndex]); + } + _startIndex++; } List ingest(Uint8List bytes) { @@ -63,7 +108,7 @@ class UsbSerialFrameDecoder { if (_rxBuffer[_startIndex] != usbSerialRxFrameStart && _rxBuffer[_startIndex] != usbSerialTxFrameStart) { - _startIndex++; + _skipByte(); _compactBufferIfNeeded(); continue; } @@ -77,7 +122,7 @@ class UsbSerialFrameDecoder { final payloadLength = _rxBuffer[_startIndex + 1] | (_rxBuffer[_startIndex + 2] << 8); if (payloadLength > usbSerialMaxPayloadLength) { - _startIndex++; + _skipByte(); _compactBufferIfNeeded(); continue; } diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 44059199..fcb01aa0 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -421,10 +421,16 @@ class UsbSerialService { unawaited(disconnect().whenComplete(_closeFrameController)); } + // One readList() returns at most 8 KB, so a single read per callback left + // the rest of a burst waiting in the native ring (#702, #711). Drain it, + // bounded to the ring's 256 KB so a stuck read can never spin forever. + static const int _maxReadsPerCallback = 32; + void _handleSerialData(FlSerialEventArgs event) { try { - final bytes = event.serial.readList(); - if (bytes.isNotEmpty) { + for (var i = 0; i < _maxReadsPerCallback; i++) { + final bytes = event.serial.readList(); + if (bytes.isEmpty) break; _ingestRawBytes(Uint8List.fromList(bytes)); } } catch (error, stack) { @@ -465,6 +471,12 @@ class UsbSerialService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + final message = 'USB serial ${skipped.describe()}'; + debugPrint(message); + _debugLogService?.error(message, tag: 'USB Serial'); + } } void _addFrame(Uint8List payload) { diff --git a/lib/services/usb_serial_service_web.dart b/lib/services/usb_serial_service_web.dart index 5261308d..f476f228 100644 --- a/lib/services/usb_serial_service_web.dart +++ b/lib/services/usb_serial_service_web.dart @@ -546,6 +546,12 @@ class UsbSerialService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + final message = 'USB serial ${skipped.describe()}'; + debugPrint(message); + _debugLogService?.error(message, tag: 'USB Serial'); + } } void _addFrame(Uint8List payload) { diff --git a/test/services/usb_serial_frame_codec_test.dart b/test/services/usb_serial_frame_codec_test.dart index 5d91d05b..7686818c 100644 --- a/test/services/usb_serial_frame_codec_test.dart +++ b/test/services/usb_serial_frame_codec_test.dart @@ -164,4 +164,81 @@ void main() { expect(packets.single.isRxFrame, isTrue); expect(packets.single.payload, orderedEquals([0x88])); }); + + group('skip report (#711): discarded bytes are never silent', () { + test('clean input reports nothing', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest( + Uint8List.fromList([usbSerialRxFrameStart, 0x01, 0x00, 0x55]), + ); + + expect(decoder.takeSkipReport(), isNull); + }); + + test('counts and samples noise before a frame', () { + final decoder = UsbSerialFrameDecoder(); + final packets = decoder.ingest( + Uint8List.fromList([ + 0xAA, + 0xBB, + usbSerialRxFrameStart, + 0x01, + 0x00, + 0x55, + ]), + ); + + expect(packets.single.payload, orderedEquals([0x55])); + final report = decoder.takeSkipReport()!; + expect(report.count, 2); + expect(report.sample, orderedEquals([0xAA, 0xBB])); + expect(report.describe(), contains('discarded 2 byte(s)')); + expect(report.describe(), contains('aa bb')); + }); + + test('counts an oversized header and still decodes the next frame', () { + final decoder = UsbSerialFrameDecoder(); + final oversized = usbSerialMaxPayloadLength + 1; + final packets = decoder.ingest( + Uint8List.fromList([ + usbSerialRxFrameStart, + oversized & 0xff, + (oversized >> 8) & 0xff, + usbSerialRxFrameStart, + 0x01, + 0x00, + 0x44, + ]), + ); + + expect(packets.single.payload, orderedEquals([0x44])); + expect(decoder.takeSkipReport()!.count, 3); + }); + + test('a report is taken once, then cleared', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList([0x01, 0x02])); + + expect(decoder.takeSkipReport()!.count, 2); + expect(decoder.takeSkipReport(), isNull); + }); + + test('the sample is capped, the count is not', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList(List.filled(40, 0x00))); + + final report = decoder.takeSkipReport()!; + expect(report.count, 40); + expect(report.sample, hasLength(16)); + expect(report.describe(), endsWith('...)')); + }); + + test('reset clears a pending report', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList([0x01])); + decoder.reset(); + + expect(decoder.takeSkipReport(), isNull); + }); + }); }