Skip to content

Commit 9584c67

Browse files
[CP-stable][flutter_tools] Safely handle non-JSON messages in test stream parsers (#192419)
This pull request is created by [automatic cherry pick workflow](https://github.com/flutter/flutter/blob/main/docs/releases/Flutter-Cherrypick-Process.md#automatically-creates-a-cherry-pick-request) Please fill in the form below, and a flutter domain expert will evaluate this cherry pick request. ### Issue Link: #191898 ### Impact Description: Top crash in Flutter 3.47.1 accounting for 245 crashes (11.7% share of top crashes). When a test runner process or browser socket dumps unformatted non-JSON error output (such as dynamic library loading errors or missing snapshot warnings) directly onto the test communication stream or WebSocket, `_ChunkedJsonParser` throws an unhandled `FormatException: Unexpected character (at character 1)`, terminating the `flutter test` CLI process. ### Changelog Description: [flutter/191898] When remote test processes emit plain-text error output on all platforms, prevent flutter_tools from crashing with an unhandled FormatException. ### Workaround: None. Any test execution where a child runner or socket prints plain text instead of JSON fatal crashes the test runner CLI. ### Risk: ### Test Coverage: ### Validation Steps: Run `flutter test test/general.shard/flutter_platform_test.dart` and `flutter test test/commands.shard/hermetic/flutter_web_platform_test.dart`. Specifically, `pipeHarnessToRemote safely ignores non-JSON string and logs warning` validates that plain text received over the stream logs a warning/trace without crashing the process, and subsequent valid JSON packets are processed normally.
1 parent 5743177 commit 9584c67

3 files changed

Lines changed: 81 additions & 19 deletions

File tree

‎packages/flutter_tools/lib/src/test/flutter_platform.dart‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@ class FlutterPlatform extends PlatformPlugin {
721721
'test $ourTestCount: connected to test device, now awaiting test result',
722722
);
723723

724-
await _pipeHarnessToRemote(
724+
await pipeHarnessToRemote(
725725
id: ourTestCount,
726726
harnessChannel: testHarnessChannel,
727727
remoteChannel: remoteChannel,
@@ -889,9 +889,10 @@ class _AsyncError {
889889
///
890890
/// The returned future completes when either side is closed, which also
891891
/// indicates when the tests have finished.
892-
Future<void> _pipeHarnessToRemote({
892+
@visibleForTesting
893+
Future<void> pipeHarnessToRemote({
893894
required int id,
894-
required StreamChannel<dynamic> harnessChannel,
895+
required StreamChannel<Object?> harnessChannel,
895896
required StreamChannel<String> remoteChannel,
896897
}) async {
897898
globals.printTrace('test $id: Waiting for test harness or tests to finish');
@@ -902,10 +903,18 @@ Future<void> _pipeHarnessToRemote({
902903
) {
903904
globals.printTrace('test $id: Test process is no longer needed by test harness');
904905
}),
905-
remoteChannel.stream.map<dynamic>(json.decode).pipe(harnessChannel.sink).then<void>((
906-
void value,
907-
) {
908-
globals.printTrace('test $id: Test harness is no longer needed by test process');
909-
}),
906+
remoteChannel.stream
907+
.map<Object?>(json.decode)
908+
.handleError((Object error) {
909+
final formatException = error as FormatException;
910+
globals.printWarning(
911+
'Received unexpected non-JSON output from test runner: ${formatException.source}',
912+
);
913+
globals.printTrace('test $id: JSON decoding failed: $formatException');
914+
}, test: (error) => error is FormatException)
915+
.pipe(harnessChannel.sink)
916+
.then<void>((void value) {
917+
globals.printTrace('test $id: Test harness is no longer needed by test process');
918+
}),
910919
]);
911920
}

‎packages/flutter_tools/lib/src/test/flutter_web_platform.dart‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,7 @@ window.\$dartLoader.loader.nextAttempt();
699699
hostUrl,
700700
completer.future,
701701
headless: !_config.pauseAfterLoad,
702+
logger: _logger,
702703
);
703704
}
704705

@@ -760,7 +761,7 @@ class OneOffHandler {
760761
class BrowserManager {
761762
/// Creates a new BrowserManager that communicates with [_browser] over
762763
/// [webSocket].
763-
BrowserManager._(this._browser, this._runtime, WebSocketChannel webSocket) {
764+
BrowserManager._(this._browser, this._runtime, WebSocketChannel webSocket, this._logger) {
764765
// The duration should be short enough that the debugging console is open as
765766
// soon as the user is done setting breakpoints, but long enough that a test
766767
// doing a lot of synchronous work doesn't trigger a false positive.
@@ -777,16 +778,24 @@ class BrowserManager {
777778
// the browser is still running code which means the user isn't debugging.
778779
_channel = MultiChannel<dynamic>(
779780
webSocket.cast<String>().transform(jsonDocument).changeStream((Stream<Object?> stream) {
780-
return stream.map((Object? message) {
781-
if (!_closed) {
782-
_timer.reset();
783-
}
784-
for (final RunnerSuiteController controller in _controllers) {
785-
controller.setDebugging(false);
786-
}
781+
return stream
782+
.handleError((Object error) {
783+
final formatException = error as FormatException;
784+
_logger.printWarning(
785+
'Received unexpected non-JSON message from browser WebSocket: ${formatException.source}',
786+
);
787+
_logger.printTrace('JSON decode error: $formatException');
788+
}, test: (error) => error is FormatException)
789+
.map((Object? message) {
790+
if (!_closed) {
791+
_timer.reset();
792+
}
793+
for (final RunnerSuiteController controller in _controllers) {
794+
controller.setDebugging(false);
795+
}
787796

788-
return message;
789-
});
797+
return message;
798+
});
790799
}),
791800
);
792801

@@ -797,6 +806,7 @@ class BrowserManager {
797806
/// The browser instance that this is connected to via [_channel].
798807
final Chromium _browser;
799808
final Runtime _runtime;
809+
final Logger _logger;
800810

801811
/// The channel used to communicate with the browser.
802812
///
@@ -856,6 +866,7 @@ class BrowserManager {
856866
Runtime runtime,
857867
Uri url,
858868
Future<WebSocketChannel> future, {
869+
required Logger logger,
859870
bool debug = false,
860871
bool headless = true,
861872
List<String> webBrowserFlags = const <String>[],
@@ -888,7 +899,7 @@ class BrowserManager {
888899
if (completer.isCompleted) {
889900
return;
890901
}
891-
completer.complete(BrowserManager._(chrome, runtime, webSocket));
902+
completer.complete(BrowserManager._(chrome, runtime, webSocket, logger));
892903
},
893904
onError: (Object error, StackTrace stackTrace) {
894905
chrome.close();

‎packages/flutter_tools/test/general.shard/flutter_platform_test.dart‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,48 @@ void main() {
246246
expect(flutterPlatform.testAssetDirectory, '/build/test');
247247
expect(flutterPlatform.icudtlPath, equals('ghi'));
248248
});
249+
250+
testUsingContext('pipeHarnessToRemote safely ignores non-JSON string and logs warning', () async {
251+
final harnessController = StreamChannelController<Object?>();
252+
final remoteController = StreamChannelController<String>();
253+
254+
final Future<void> pipeFuture = pipeHarnessToRemote(
255+
id: 0,
256+
harnessChannel: harnessController.foreign,
257+
remoteChannel: remoteController.foreign,
258+
);
259+
260+
final receivedFromRemote = <Object?>[];
261+
harnessController.local.stream.listen(receivedFromRemote.add);
262+
263+
// Send non-JSON error string from remote channel followed by valid JSON.
264+
remoteController.local.sink.add(
265+
'Loading dynamic library failed: dlopen(/opt/homebrew/share/flutter/bin/cache/libflutter.dylib)',
266+
);
267+
remoteController.local.sink.add('{"valid": true}');
268+
269+
await pumpEventQueue();
270+
271+
await remoteController.local.sink.close();
272+
await harnessController.local.sink.close();
273+
274+
await pipeFuture;
275+
276+
expect(
277+
receivedFromRemote,
278+
equals(<Object?>[
279+
<String, Object?>{'valid': true},
280+
]),
281+
);
282+
final logger = globals.logger as BufferLogger;
283+
expect(
284+
logger.warningText,
285+
contains(
286+
'Received unexpected non-JSON output from test runner: Loading dynamic library failed: dlopen',
287+
),
288+
);
289+
expect(logger.traceText, contains('test 0: JSON decoding failed:'));
290+
});
249291
});
250292

251293
group('generateTestBootstrap', () {

0 commit comments

Comments
 (0)