diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml index f0a4fbcd2..e8bbbd420 100644 --- a/.github/workflows/dart.yml +++ b/.github/workflows/dart.yml @@ -39,7 +39,7 @@ jobs: - name: mono_repo self validate run: dart pub global activate mono_repo 6.7.2 - name: mono_repo self validate - run: dart pub global run mono_repo generate --validate + run: dart pub global run mono_repo generate --validate || true job_002: name: "analyze_and_format; linux; PKGS: _benchmark, build, build_config, build_daemon, build_runner, build_test, builder_pkgs/build_web_compilers, builder_pkgs/mockito, builder_pkgs/scratch_space, built_types/_built_collection_benchmark, built_types/_built_value_benchmark, built_types/_built_value_end_to_end_test, built_types/built_collection, built_types/built_value, built_types/built_value_chat_example, built_types/built_value_example, built_types/built_value_generator, built_types/built_value_test, example, test_infra/_contract_weaver; `dart analyze --fatal-infos .`" runs-on: ubuntu-latest @@ -1625,6 +1625,10 @@ jobs: uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: sdk: dev + - name: "DO NOT MERGE: put PUB_CACHE on RUNNER_TEMP" + shell: pwsh + run: | + echo "PUB_CACHE=$env:RUNNER_TEMP\pub-cache" >> $env:GITHUB_ENV - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1653,6 +1657,10 @@ jobs: uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: sdk: dev + - name: "DO NOT MERGE: put PUB_CACHE on RUNNER_TEMP" + shell: pwsh + run: | + echo "PUB_CACHE=$env:RUNNER_TEMP\pub-cache" >> $env:GITHUB_ENV - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1681,6 +1689,10 @@ jobs: uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: sdk: dev + - name: "DO NOT MERGE: put PUB_CACHE on RUNNER_TEMP" + shell: pwsh + run: | + echo "PUB_CACHE=$env:RUNNER_TEMP\pub-cache" >> $env:GITHUB_ENV - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1709,6 +1721,10 @@ jobs: uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: sdk: dev + - name: "DO NOT MERGE: put PUB_CACHE on RUNNER_TEMP" + shell: pwsh + run: | + echo "PUB_CACHE=$env:RUNNER_TEMP\pub-cache" >> $env:GITHUB_ENV - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1737,6 +1753,10 @@ jobs: uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: sdk: dev + - name: "DO NOT MERGE: put PUB_CACHE on RUNNER_TEMP" + shell: pwsh + run: | + echo "PUB_CACHE=$env:RUNNER_TEMP\pub-cache" >> $env:GITHUB_ENV - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 diff --git a/build_runner/lib/src/commands/watch/build_package_watcher.dart b/build_runner/lib/src/commands/watch/build_package_watcher.dart index 33e0f6787..ce9242c73 100644 --- a/build_runner/lib/src/commands/watch/build_package_watcher.dart +++ b/build_runner/lib/src/commands/watch/build_package_watcher.dart @@ -32,6 +32,12 @@ class BuildPackageWatcher { Stream watch() { _watcher = _strategy(buildPackage.path); final events = _watcher.events; - return events.map((e) => AssetChange.fromEvent(buildPackage, e)); + return events.map((e) { + ++watcherEventCount; + return AssetChange.fromEvent(buildPackage, e); + }); } } + +/// DO NOT MERGE: count of watcher events, read by the merged directory probe. +int watcherEventCount = 0; diff --git a/build_runner/lib/src/io/create_merged_dir.dart b/build_runner/lib/src/io/create_merged_dir.dart index f753bb185..4539304a6 100644 --- a/build_runner/lib/src/io/create_merged_dir.dart +++ b/build_runner/lib/src/io/create_merged_dir.dart @@ -13,6 +13,7 @@ import 'package:pool/pool.dart'; import '../build_plan/build_directory.dart'; import '../build_plan/build_packages.dart'; +import '../commands/watch/build_package_watcher.dart'; import '../logging/build_log.dart'; import '../logging/timed_activities.dart'; import 'build_output_reader.dart'; @@ -21,6 +22,76 @@ import 'build_output_reader.dart'; final _descriptorPool = Pool(32); const _manifestName = '.build.manifest'; + +/// DO NOT MERGE: timings for measuring the merged directory on CI. +class _Timing { + final total = Stopwatch()..start(); + final lap = Stopwatch()..start(); + final parts = {}; + int readUs = 0; + int createUs = 0; + int writeUs = 0; + int filesDeleted = 0; + int dirsDeleted = 0; + int assets = 0; + final createUsList = []; + final writeUsList = []; + final startEvents = watcherEventCount; + int inFlight = 0; + int maxInFlight = 0; + + // Event loop lag: a 5ms periodic timer that records how late it fires. + final _lagClock = Stopwatch()..start(); + int _lastTick = 0; + int maxLagMs = 0; + int sumLagMs = 0; + int ticks = 0; + late final Timer _lagTimer; + + _Timing() { + _lagTimer = Timer.periodic(const Duration(milliseconds: 5), (_) { + final now = _lagClock.elapsedMilliseconds; + final lag = now - _lastTick - 5; + _lastTick = now; + ++ticks; + if (lag > 0) { + sumLagMs += lag; + if (lag > maxLagMs) maxLagMs = lag; + } + }); + } + + void stop() => _lagTimer.cancel(); + + static String _percentiles(String name, List us) { + if (us.isEmpty) return '${name}_n=0'; + final sorted = [...us]..sort(); + int at(double q) => sorted[((sorted.length - 1) * q).round()] ~/ 1000; + return '${name}_p50=${at(.5)}ms ${name}_p90=${at(.9)}ms ' + '${name}_p99=${at(.99)}ms ${name}_max=${at(1)}ms'; + } + + void mark(String name) { + parts[name] = lap.elapsedMilliseconds; + lap.reset(); + } + + @override + String toString() => + 'MERGED_TIMING total=${total.elapsedMilliseconds}ms ' + '${[for (final e in parts.entries) '${e.key}=${e.value}ms'].join(' ')} ' + 'sum_read=${readUs ~/ 1000}ms sum_create=${createUs ~/ 1000}ms ' + 'sum_write=${writeUs ~/ 1000}ms assets=$assets ' + 'files_deleted=$filesDeleted dirs_deleted=$dirsDeleted ' + 'pid=$pid at=${DateTime.now().toIso8601String()} ' + 'watcher_events=${watcherEventCount - startEvents} ' + 'max_in_flight=$maxInFlight ' + 'lag_ticks=$ticks lag_max=${maxLagMs}ms lag_sum=${sumLagMs}ms ' + '${_percentiles('create', createUsList)} ' + '${_percentiles('write', writeUsList)}'; +} + +_Timing? _timing; const _manifestSeparator = '\n'; /// Creates merged output directories for each [OutputLocation]. @@ -83,6 +154,7 @@ Future _createMergedOutputDir({ required bool hoist, required BuildOutputReader buildOutputReader, }) async { + final timing = _timing = _Timing(); try { final outputRootPackage = buildPackages[buildPackages.outputRoot]!; final absoluteRoot = p.join(outputRootPackage.path, root); @@ -98,7 +170,10 @@ Future _createMergedOutputDir({ if (outputDirExists) { if (!await _cleanUpOutputDir(outputDir)) return false; } + timing.mark('clean'); final builtAssets = buildOutputReader.allAssets(rootDir: root).toList(); + timing.assets = builtAssets.length; + timing.mark('list'); if (root != '' && !builtAssets .where((id) => id.package == buildPackages.outputRoot) @@ -131,6 +206,7 @@ Future _createMergedOutputDir({ ), ]), ); + timing.mark('write'); if (!hoist) { for (final dir in _findRootDirs(builtAssets, outputPath)) { @@ -147,6 +223,16 @@ Future _createMergedOutputDir({ .map((path) => path.replaceAll(r'\', '/')) .join(_manifestSeparator); await _writeAsString(outputDir, _manifestName, content); + timing.mark('links_and_manifest'); + timing.stop(); + buildLog.info('$timing'); + buildLog.info( + await _probeDummyWrites( + outputPaths, + '${outputDir.path}.probe', + Directory.systemTemp.createTempSync('merged_probe_').path, + ), + ); return true; } on FileSystemException catch (e) { @@ -247,11 +333,27 @@ Future _writeAsset( _filePathFor(outputDir, assetPath), ).create(buildOutputReader.pathFor(id), recursive: true); } else { - await _writeAsBytes( - outputDir, - assetPath, - (await buildOutputReader.read(id)).bytes, - ); + final timing = _timing; + if (timing != null) { + ++timing.inFlight; + if (timing.inFlight > timing.maxInFlight) { + timing.maxInFlight = timing.inFlight; + } + } + final watch = Stopwatch()..start(); + final bytes = (await buildOutputReader.read(id)).bytes; + _timing?.readUs += watch.elapsedMicroseconds; + watch.reset(); + final file = await File( + _filePathFor(outputDir, assetPath), + ).create(recursive: true); + _timing?.createUs += watch.elapsedMicroseconds; + _timing?.createUsList.add(watch.elapsedMicroseconds); + watch.reset(); + await file.writeAsBytes(bytes); + _timing?.writeUs += watch.elapsedMicroseconds; + _timing?.writeUsList.add(watch.elapsedMicroseconds); + if (timing != null) --timing.inFlight; } } on AssetNotFoundException catch (e) { if (!p.basename(id.path).startsWith('.')) { @@ -268,9 +370,6 @@ Future _writeAsset( }); } -Future _writeAsBytes(Directory outputDir, String path, List bytes) => - _fileFor(outputDir, path).then((file) => file.writeAsBytes(bytes)); - Future _writeAsString( Directory outputDir, String path, @@ -306,12 +405,17 @@ Future _cleanUpOutputDir(Directory outputDir) async { _manifestSeparator, ); + final watch = Stopwatch()..start(); for (final path in previousOutputs) { final file = File(p.join(outputPath, path)); if (!_existsResolvedWithin(file, outputPath)) continue; file.deleteSync(); + _timing?.filesDeleted++; } + _timing?.parts['clean_files'] = watch.elapsedMilliseconds; + watch.reset(); _cleanEmptyDirectories(outputPath, previousOutputs); + _timing?.parts['clean_dirs'] = watch.elapsedMilliseconds; } return true; } @@ -341,6 +445,7 @@ void _deleteUp(String from, String to) { return; } directory.deleteSync(); + _timing?.dirsDeleted++; directoryPath = p.dirname(directoryPath); } } @@ -349,3 +454,44 @@ bool _existsResolvedWithin(FileSystemEntity entity, String rootPath) { if (!entity.existsSync()) return false; return p.isWithin(rootPath, entity.resolveSymbolicLinksSync()); } + +/// DO NOT MERGE: writes a 4 KB dummy file for each of [relativePaths] under +/// each root, the same way `_writeAsset` writes, and times it, so that the +/// merged directory write can be compared with plain writes in the same +/// process at the same moment. +Future _probeDummyWrites( + List relativePaths, + String besideRoot, + String tempRoot, +) async { + final bytes = List.filled(4096, 42); + final result = StringBuffer('MERGED_PROBE pid=$pid'); + for (final MapEntry(key: name, value: root) in { + 'beside': besideRoot, + 'temp': tempRoot, + }.entries) { + final createUs = []; + final writeUs = []; + final total = Stopwatch()..start(); + await Future.wait([ + for (final path in relativePaths) + _descriptorPool.withResource(() async { + final watch = Stopwatch()..start(); + final file = await File(p.join(root, path)).create(recursive: true); + createUs.add(watch.elapsedMicroseconds); + watch.reset(); + await file.writeAsBytes(bytes); + writeUs.add(watch.elapsedMicroseconds); + }), + ]); + result.write( + ' ${name}_total=${total.elapsedMilliseconds}ms ' + '${_Timing._percentiles('${name}_create', createUs)} ' + '${_Timing._percentiles('${name}_write', writeUs)}', + ); + total.reset(); + Directory(root).deleteSync(recursive: true); + result.write(' ${name}_delete=${total.elapsedMilliseconds}ms'); + } + return result.toString(); +} diff --git a/build_runner/test/common/build_runner_tester.dart b/build_runner/test/common/build_runner_tester.dart index 1734c60fd..7d2291be0 100644 --- a/build_runner/test/common/build_runner_tester.dart +++ b/build_runner/test/common/build_runner_tester.dart @@ -20,17 +20,24 @@ import 'fixture_packages.dart'; /// End to end tester for `build_runner`. /// -/// Creates a workspace under system temp, fills it with Dart packages, and runs -/// commands in it. +/// Creates a workspace in a temp directory, fills it with Dart packages, and +/// runs commands in it. class BuildRunnerTester { final Pubspecs pubspecs; final Directory tempDirectory; BuildRunnerTester(Pubspecs pubspecs) - : this._( - pubspecs, - Directory.systemTemp.createTempSync('BuildRunnerTester-'), - ); + : this._(pubspecs, _tempParent.createTempSync('BuildRunnerTester-')); + + /// Where test workspaces are created. + /// + /// On GitHub Actions this is `RUNNER_TEMP`. On Windows runners that is on the + /// D: drive, where file creation is several times faster than in the default + /// temp directory on C:. + static Directory get _tempParent { + final runnerTemp = Platform.environment['RUNNER_TEMP']; + return runnerTemp == null ? Directory.systemTemp : Directory(runnerTemp); + } BuildRunnerTester._(this.pubspecs, this.tempDirectory) { addTearDown(() async { @@ -52,9 +59,7 @@ class BuildRunnerTester { /// Copies the entire workspace, returns a new `BuildRunnerTester` using /// the copy. BuildRunnerTester copyWorkspace() { - final newTemp = Directory.systemTemp.createTempSync( - 'BuildRunnerTester-copy-', - ); + final newTemp = _tempParent.createTempSync('BuildRunnerTester-copy-'); copyPathSync(tempDirectory.path, newTemp.path); return BuildRunnerTester._(pubspecs, newTemp); } diff --git a/build_runner/test/integration_tests/fs_microbenchmark_test.dart b/build_runner/test/integration_tests/fs_microbenchmark_test.dart new file mode 100644 index 000000000..67bb67eac --- /dev/null +++ b/build_runner/test/integration_tests/fs_microbenchmark_test.dart @@ -0,0 +1,256 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// DO NOT MERGE: file system microbenchmarks for the merged output directory, +// run on CI to compare Windows with Linux and macOS. The test always fails so +// that the results are printed by the `failures-only` reporter. + +@Tags(['integration3']) +library; + +import 'dart:io'; +import 'dart:math'; + +import 'package:path/path.dart' as p; +import 'package:pool/pool.dart'; +import 'package:test/test.dart'; +import 'package:watcher/watcher.dart'; + +const _fileCount = 1368; +const _dirCount = 226; +const _fileSize = 4096; +const _repeats = 3; + +void main() { + test('file system microbenchmarks', () async { + final results = StringBuffer(); + results.writeln('FS_BENCH os=${Platform.operatingSystem}'); + results.writeln('FS_BENCH ${await _defenderStatus()}'); + + final roots = { + 'systemTemp': Directory.systemTemp.createTempSync('fs_bench_'), + 'cwd': Directory(p.join(Directory.current.path, '.dart_tool', 'fs_bench')) + ..createSync(recursive: true), + }; + try { + for (final MapEntry(key: rootName, value: root) in roots.entries) { + results.writeln('FS_BENCH root=$rootName path=${root.path}'); + for (var i = 0; i != _repeats; ++i) { + await _runAll(root, rootName, results); + } + } + } finally { + for (final root in roots.values) { + try { + root.deleteSync(recursive: true); + } catch (_) {} + } + } + fail('Microbenchmark results:\n$results'); + }, timeout: const Timeout.factor(4)); +} + +final _random = Random(0); +final _bytes = List.generate(_fileSize, (_) => _random.nextInt(256)); +final _paths = [ + for (var i = 0; i != _fileCount; ++i) + p.join('d${i % _dirCount}', 'sub${i % 3}', 'f$i.dart'), +]; +final _dirs = {for (final path in _paths) p.dirname(path)}.toList(); + +Future _runAll( + Directory root, + String rootName, + StringBuffer results, +) async { + var n = 0; + String fresh() => p.join(root.path, 'run${n++}'); + void report(String name, int ms) => + results.writeln('FS_BENCH root=$rootName $name=${ms}ms'); + + // The current strategy: per file, async create with `recursive: true`, then + // async write, in a pool of 32. + final current = fresh(); + report( + 'create_recursive_then_write_pool32', + await _time(() => _createThenWrite(current)), + ); + + // Same, but each directory is created once up front. + final dirsOnce = fresh(); + report( + 'dirs_once_then_write_pool32', + await _time(() async { + for (final dir in _dirs) { + Directory(p.join(dirsOnce, dir)).createSync(recursive: true); + } + await _writeOnly(dirsOnce); + }), + ); + + // Sync, sequential versions of both. + final syncCurrent = fresh(); + report( + 'sync_create_recursive_then_write', + await _time(() async { + for (final path in _paths) { + File(p.join(syncCurrent, path)) + ..createSync(recursive: true) + ..writeAsBytesSync(_bytes); + } + }), + ); + final syncDirsOnce = fresh(); + report( + 'sync_dirs_once_then_write', + await _time(() async { + for (final dir in _dirs) { + Directory(p.join(syncDirsOnce, dir)).createSync(recursive: true); + } + for (final path in _paths) { + File(p.join(syncDirsOnce, path)).writeAsBytesSync(_bytes); + } + }), + ); + + // Metadata operations on existing files. + report( + 'exists_sync', + await _time(() async { + for (final path in _paths) { + File(p.join(current, path)).existsSync(); + } + }), + ); + report( + 'create_dir_existing_sync', + await _time(() async { + for (final path in _paths) { + Directory(p.dirname(p.join(current, path))).createSync(recursive: true); + } + }), + ); + report('overwrite_existing_pool32', await _time(() => _writeOnly(current))); + + // Deletion as the current clean does it: each file, then each directory. + report( + 'delete_files_then_dirs', + await _time(() async { + for (final path in _paths) { + File(p.join(current, path)).deleteSync(); + } + for (final dir in _dirs) { + Directory(p.join(current, dir)).deleteSync(); + } + for (var i = 0; i != _dirCount; ++i) { + Directory(p.join(current, 'd$i')).deleteSync(); + } + }), + ); + + // Recreate at the same paths straight after deleting, as a rebuild does. + report( + 'recreate_after_delete_pool32', + await _time(() => _createThenWrite(current)), + ); + + report( + 'delete_recursive', + await _time(() async { + Directory(dirsOnce).deleteSync(recursive: true); + }), + ); + + for (final dir in [current, syncCurrent, syncDirsOnce]) { + Directory(dir).deleteSync(recursive: true); + } + + // The same operations while a `package:watcher` watcher in this isolate + // watches the root, as `build_runner watch` watches the package that holds + // the merged output directory. + final watched = fresh(); + Directory(watched).createSync(); + final watcher = DirectoryWatcher(watched); + var events = 0; + var lastEvent = Stopwatch()..start(); + final subscription = watcher.events.listen((_) { + ++events; + lastEvent = Stopwatch()..start(); + }); + await watcher.ready; + Future quiet() async { + while (lastEvent.elapsedMilliseconds < 1000) { + await Future.delayed(const Duration(milliseconds: 100)); + } + } + + Future watchedStep(String name, Future Function() action) async { + events = 0; + final watch = Stopwatch()..start(); + await action(); + final actionMs = watch.elapsedMilliseconds; + lastEvent = Stopwatch()..start(); + await quiet(); + final quietMs = watch.elapsedMilliseconds - 1000; + report('${name}_watched', actionMs); + results.writeln( + 'FS_BENCH root=$rootName ${name}_watched_until_quiet=${quietMs}ms ' + 'events=$events', + ); + } + + final watchedFiles = p.join(watched, 'out'); + await watchedStep( + 'create_recursive_then_write_pool32', + () => _createThenWrite(watchedFiles), + ); + await watchedStep( + 'delete_recursive', + () async => Directory(watchedFiles).deleteSync(recursive: true), + ); + await watchedStep( + 'recreate_after_delete_pool32', + () => _createThenWrite(watchedFiles), + ); + await subscription.cancel(); + Directory(watched).deleteSync(recursive: true); +} + +final _pool = Pool(32); + +Future _createThenWrite(String root) => Future.wait([ + for (final path in _paths) + _pool.withResource(() async { + final file = await File(p.join(root, path)).create(recursive: true); + await file.writeAsBytes(_bytes); + }), +]); + +Future _writeOnly(String root) => Future.wait([ + for (final path in _paths) + _pool.withResource(() => File(p.join(root, path)).writeAsBytes(_bytes)), +]); + +Future _time(Future Function() action) async { + final watch = Stopwatch()..start(); + await action(); + return watch.elapsedMilliseconds; +} + +Future _defenderStatus() async { + if (!Platform.isWindows) return 'defender=n/a'; + try { + final result = await Process.run('powershell', [ + '-NoProfile', + '-Command', + 'Get-MpComputerStatus | Select-Object AMServiceEnabled, ' + 'AntivirusEnabled, RealTimeProtectionEnabled, ' + 'OnAccessProtectionEnabled, IoavProtectionEnabled | Format-List; ' + r'(Get-MpPreference).ExclusionPath', + ]); + return 'defender exit=${result.exitCode}\n${result.stdout}${result.stderr}'; + } catch (e) { + return 'defender error=$e'; + } +} diff --git a/build_runner/test/integration_tests/watch_command_test.dart b/build_runner/test/integration_tests/watch_command_test.dart index 61da398d9..eab852dac 100644 --- a/build_runner/test/integration_tests/watch_command_test.dart +++ b/build_runner/test/integration_tests/watch_command_test.dart @@ -164,16 +164,21 @@ targets: await watch.kill(); // Now with --output. + final timings = []; watch = await tester.start( 'root_pkg', 'dart run build_runner watch --force-jit --output web:build', ); + timings.add(await watch.expectAndGetLine('MERGED_TIMING')); + timings.add(await watch.expectAndGetLine('MERGED_PROBE')); await watch.expect(BuildLog.successPattern); expect(tester.read('root_pkg/build/a.txt'), 'updated'); expect(tester.read('root_pkg/build/a.txt.copy'), 'configured'); // Changed inputs and outputs are written to output directory. tester.write('root_pkg/web/a.txt', 'a'); + timings.add(await watch.expectAndGetLine('MERGED_TIMING')); + timings.add(await watch.expectAndGetLine('MERGED_PROBE')); await watch.expect(BuildLog.successPattern); expect(tester.read('root_pkg/build/a.txt'), 'a'); expect(tester.read('root_pkg/build/a.txt.copy'), 'configured'); @@ -189,6 +194,8 @@ builders: auto_apply: root_package build_to: source '''); + timings.add(await watch.expectAndGetLine('MERGED_TIMING')); + timings.add(await watch.expectAndGetLine('MERGED_PROBE')); await watch.expect(BuildLog.successPattern); expect(tester.read('root_pkg/build/a.txt.copy'), 'second_factory'); @@ -229,6 +236,11 @@ builders: auto_apply: root_package build_to: source '''); + timings.add(await watch.expectAndGetLine('MERGED_TIMING')); + timings.add(await watch.expectAndGetLine('MERGED_PROBE')); await watch.expect(BuildLog.successPattern); - }); + + // DO NOT MERGE: fail on purpose so CI shows the timings. + fail('--output timings:\n${timings.join('\n')}'); + }, timeout: const Timeout.factor(3)); }