Skip to content

Commit 5b4192f

Browse files
committed
[flutter_tools] Shut down isolates in --experimental-faster-testing when suite channels close
When running multiple test files with `--experimental-faster-testing`, lightweight engine isolates remained alive because `IsolateChannel` ports lack an EOF disconnect signal on the child isolate. This caused isolates and native threads to accumulate across suites. Notify the child test isolate when the suite runner closes the channel sink, and invoke native `ForceShutdownIsolate` followed by `Isolate.exit()` once the suite channel completes. Also unregister port names from `IsolateNameServer` and remove closed channels from the root isolate spawner map. Fixes flutter#146603
1 parent 66b3ad9 commit 5b4192f

2 files changed

Lines changed: 89 additions & 5 deletions

File tree

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

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ import 'dart:ui';
352352
import 'package:ffi/ffi.dart';
353353
import 'package:flutter_test/flutter_test.dart';
354354
import 'package:stream_channel/isolate_channel.dart';
355+
import 'package:stream_channel/stream_channel.dart';
355356
import 'package:test_api/backend.dart'; // flutter_ignore: test_api_import
356357
''');
357358

@@ -406,6 +407,13 @@ import 'package:test_api/backend.dart'; // flutter_ignore: test_api_import
406407
buffer.writeln();
407408

408409
buffer.writeln(r'''
410+
/// Shuts down the lightweight engine isolate from the native side.
411+
///
412+
/// Sets `Isolate._mayExit = true` in the engine, permitting `Isolate.exit()`
413+
/// to terminate the isolate and trigger native shell deletion in `tester_main.cc`.
414+
@Native<Void Function()>(symbol: 'ForceShutdownIsolate')
415+
external void _forceShutdownIsolate();
416+
409417
@Native<Void Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'Spawn')
410418
external void _spawn(Pointer<Utf8> entrypoint, Pointer<Utf8> route);
411419
@@ -424,10 +432,19 @@ void spawn({required SendPort port, String entrypoint = 'main', String route = '
424432
void createChannelAndConnect(String path, String name, Function testMain) {
425433
goldenFileComparator = LocalFileComparator(Uri.parse(path));
426434
autoUpdateGoldenFiles = $autoUpdateGoldenFiles;
435+
final SendPort sendPort = IsolateNameServer.lookupPortByName(name)!;
436+
// Clean up global port mapping once resolved.
437+
IsolateNameServer.removePortNameMapping(name);
427438
final IsolateChannel<dynamic> channel = IsolateChannel<dynamic>.connectSend(
428-
IsolateNameServer.lookupPortByName(name)!,
439+
sendPort,
429440
);
430-
channel.pipe(RemoteListener.start(() => testMain));
441+
final StreamChannel<Object?> suiteChannel = RemoteListener.start(() => testMain);
442+
channel.pipe(suiteChannel);
443+
// Shut down the isolate and its native engine shell when the suite finishes.
444+
suiteChannel.sink.done.whenComplete(() {
445+
_forceShutdownIsolate();
446+
Isolate.exit();
447+
});
431448
}
432449
433450
@pragma('vm:entry-point')
@@ -610,10 +627,22 @@ class SpawnPlugin extends PlatformPlugin {
610627
final String correctedPath = ${platform.isWindows ? r'"/$path"' : 'path'};
611628
await launchIsolate(correctedPath);
612629
613-
final StreamChannel<dynamic> channel = _channels[pathToImport(correctedPath)]!;
614-
final RunnerSuiteController controller = deserializeSuite(correctedPath, platform,
630+
final StreamChannel<dynamic> rawChannel = _channels.remove(pathToImport(correctedPath))!;
631+
final StreamController<dynamic> controller = StreamController<dynamic>(sync: true);
632+
controller.stream.listen(
633+
rawChannel.sink.add,
634+
onError: rawChannel.sink.addError,
635+
onDone: () {
636+
// package:test reserves channel 0 on its MultiChannel for suite control
637+
// messages. Transmitting 'close' notifies RemoteListener to shut down.
638+
rawChannel.sink.add(<Object?>[0, <String, Object?>{'type': 'close'}]);
639+
rawChannel.sink.close();
640+
},
641+
);
642+
final StreamChannel<dynamic> channel = StreamChannel<dynamic>(rawChannel.stream, controller.sink);
643+
final RunnerSuiteController suiteController = deserializeSuite(correctedPath, platform,
615644
suiteConfig, const PluginEnvironment(), channel, message);
616-
return controller.suite;
645+
return suiteController.suite;
617646
}
618647
}
619648
''');

‎packages/flutter_tools/test/commands.shard/hermetic/test_test.dart‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,61 @@ const List<String> packageTestArgs = <String>[
877877
},
878878
);
879879

880+
testUsingContext(
881+
'Configures isolate teardown in generated spawners when --experimental-faster-testing is set',
882+
() async {
883+
final testCommand = TestCommand(toolContext: toolContext);
884+
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
885+
886+
var caughtToolExit = false;
887+
await asyncGuard<void>(
888+
() => commandRunner.run(const <String>[
889+
'test',
890+
'--no-pub',
891+
'--experimental-faster-testing',
892+
'--',
893+
'test/fake_test.dart',
894+
'test/fake_test_2.dart',
895+
]),
896+
onError: (Object error) async {
897+
expect(error, isA<ToolExit>());
898+
expect((error as ToolExit).message, contains('The Dart compiler exited unexpectedly.'));
899+
caughtToolExit = true;
900+
901+
final Directory spawnerDir = fs.directory(
902+
fs.path.join('build', 'isolate_spawning_tester'),
903+
);
904+
final File childSourceFile = spawnerDir.childFile('child_test_isolate_spawner.dart');
905+
final File rootSourceFile = spawnerDir.childFile('root_test_isolate_spawner.dart');
906+
907+
expect(childSourceFile.existsSync(), true);
908+
final String childSource = childSourceFile.readAsStringSync();
909+
expect(
910+
childSource,
911+
contains('/// Shuts down the lightweight engine isolate from the native side.'),
912+
);
913+
expect(childSource, contains('external void _forceShutdownIsolate();'));
914+
expect(childSource, contains('_forceShutdownIsolate();'));
915+
expect(childSource, contains('Isolate.exit();'));
916+
expect(childSource, contains('suiteChannel.sink.done.whenComplete'));
917+
expect(childSource, contains('IsolateNameServer.removePortNameMapping(name);'));
918+
919+
expect(rootSourceFile.existsSync(), true);
920+
final String rootSource = rootSourceFile.readAsStringSync();
921+
expect(rootSource, contains("<String, Object?>{'type': 'close'}"));
922+
expect(rootSource, contains('_channels.remove(pathToImport(correctedPath))!'));
923+
},
924+
);
925+
expect(caughtToolExit, true);
926+
},
927+
overrides: <Type, Generator>{
928+
AnsiTerminal: () => _FakeTerminal(),
929+
FileSystem: () => fs,
930+
ProcessManager: () => FakeProcessManager.any(),
931+
DeviceManager: () => _FakeDeviceManager(<Device>[]),
932+
},
933+
);
934+
880935
testUsingContext(
881936
'Verbose prints phase timings',
882937
() async {

0 commit comments

Comments
 (0)