diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 8c2f0168..f2f38ff0 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -150,6 +150,9 @@ jobs: # found" and prove nothing. env: VAPOURBOX_WORKER: ${{ github.workspace }}/worker/target/debug/vapourbox-worker + # A failing output conformance case keeps its output, job and log + # here, uploaded below (task #99). + VAPOURBOX_CONFORMANCE_KEEP: ${{ github.workspace }}/conformance-failures # Not @Tags(['gpu']): the hosted runners have no GPU (dart_test.yaml). # `sweep` tests are also `heavy`; each leg takes its own. run: >- @@ -163,6 +166,18 @@ jobs: if: ${{ !cancelled() && matrix.suite == 'heavy' && steps.build.outcome == 'success' }} run: cd worker && cargo test --test subtitle_integration_test -- --ignored --nocapture + - name: Failing conformance cases (task #99) + # Each failing case of integration_output_conformance_test.dart: its + # output file, job and log, so an intermittent failure can be measured + # offline. + if: ${{ failure() && matrix.suite == 'heavy' }} + uses: actions/upload-artifact@v5 + with: + name: conformance-failures-${{ matrix.asset }} + path: conformance-failures/ + if-no-files-found: ignore + retention-days: 14 + - name: Format sweep results # Every row's outcome, time and differences (integration_format_sweep_test.dart). if: ${{ always() && matrix.suite == 'sweep' }} @@ -289,6 +304,9 @@ jobs: # `flutter test`, where the running executable is the test runner. env: VAPOURBOX_WORKER: ${{ github.workspace }}\worker\target\debug\vapourbox-worker.exe + # A failing output conformance case keeps its output, job and log + # here, uploaded below (task #99). + VAPOURBOX_CONFORMANCE_KEEP: ${{ github.workspace }}/conformance-failures # Not @Tags(['gpu']): the hosted runners have no GPU (dart_test.yaml). # `sweep` tests are also `heavy`; each leg takes its own. run: >- @@ -302,6 +320,18 @@ jobs: if: ${{ !cancelled() && matrix.suite == 'heavy' && steps.build.outcome == 'success' }} run: cd worker && cargo test --test subtitle_integration_test -- --ignored --nocapture + - name: Failing conformance cases (task #99) + # Each failing case of integration_output_conformance_test.dart: its + # output file, job and log, so an intermittent failure can be measured + # offline. + if: ${{ failure() && matrix.suite == 'heavy' }} + uses: actions/upload-artifact@v5 + with: + name: conformance-failures-${{ matrix.asset }} + path: conformance-failures/ + if-no-files-found: ignore + retention-days: 14 + - name: Format sweep results # Every row's outcome, time and differences (integration_format_sweep_test.dart). if: ${{ always() && matrix.suite == 'sweep' }} @@ -415,6 +445,9 @@ jobs: # found" and prove nothing. env: VAPOURBOX_WORKER: ${{ github.workspace }}/worker/target/debug/vapourbox-worker + # A failing output conformance case keeps its output, job and log + # here, uploaded below (task #99). + VAPOURBOX_CONFORMANCE_KEEP: ${{ github.workspace }}/conformance-failures # Not @Tags(['gpu']): the hosted runners have no GPU (dart_test.yaml). # `sweep` tests are also `heavy`; each leg takes its own. run: >- @@ -428,6 +461,18 @@ jobs: if: ${{ !cancelled() && matrix.suite == 'heavy' && steps.build.outcome == 'success' }} run: cd worker && cargo test --test subtitle_integration_test -- --ignored --nocapture + - name: Failing conformance cases (task #99) + # Each failing case of integration_output_conformance_test.dart: its + # output file, job and log, so an intermittent failure can be measured + # offline. + if: ${{ failure() && matrix.suite == 'heavy' }} + uses: actions/upload-artifact@v5 + with: + name: conformance-failures-${{ matrix.asset }} + path: conformance-failures/ + if-no-files-found: ignore + retention-days: 14 + - name: Format sweep results # Every row's outcome, time and differences (integration_format_sweep_test.dart). if: ${{ always() && matrix.suite == 'sweep' }} diff --git a/.github/workflows/repro-output-conformance.yml b/.github/workflows/repro-output-conformance.yml new file mode 100644 index 00000000..1c623136 --- /dev/null +++ b/.github/workflows/repro-output-conformance.yml @@ -0,0 +1,202 @@ +name: Reproduce an output conformance flake (macOS) + +# Task #99: AV1-into-MP4 cases of integration_output_conformance_test.dart +# failed now and then on the macOS x64 nightly (99 pictures for 100; a case +# that hung past the test's 3 minutes). This runs the suspects in a loop on +# the nightly's runners, layer by layer. Phases (space-separated `phases`): +# versions the bundle's FFmpeg, SVT-AV1 and AV1 decoders (B0) +# b1 the cases matching `name`, `iterations` times each, in one +# flutter test process (VAPOURBOX_CONFORMANCE_REPEAT) +# b1load every mp4+av1 case, `load_iterations` times each, with every +# core but one busy, as nightly's concurrent test files are +# b2 the encoder alone: one job's captured Y4M fed to its exact +# encoder command `replays` times, from a file and throttled, +# then 4 at once under load (scripts/replay_encoder.py) +# b3 the test's own decodes of that output (and of any output b1 +# kept failing), `replays` times per decoder variant +# (scripts/measure_decode.py) +# Scripts: docs/reports/task-99-av1-conformance-flake/scripts. Every failing +# case's output, job and log are uploaded (VAPOURBOX_CONFORMANCE_KEEP). +# +# Dispatch it, or push a change to this file on a `stuart/99-probe-*` +# branch: a workflow that is not on the default branch cannot be dispatched, +# and a push then runs it with the defaults below. + +on: + workflow_dispatch: + inputs: + name: + description: 'b1: --name regex of the cases to loop' + default: 'mp4\+av1/passthrough/delayed-avi/(untrimmed|near-start)' + iterations: + description: 'b1: runs of each case' + default: '60' + load_iterations: + description: 'b1load: runs of each mp4+av1 case under load' + default: '15' + replays: + description: 'b2/b3: runs per mode or decoder variant' + default: '300' + phases: + description: 'Space-separated: versions b1 b1load b2 b3' + default: 'versions b1 b1load b2 b3' + push: + branches: ['stuart/99-probe-*'] + paths: ['.github/workflows/repro-output-conformance.yml'] + +permissions: + contents: read + actions: read + +jobs: + repro: + strategy: + fail-fast: false + matrix: + include: + - {arch: x64, runner: macos-15-intel, asset: macos-x64} + - {arch: x64, runner: macos-15-intel, asset: macos-x64-v2} + # The control: arm64 never failed these cases. + - {arch: arm64, runner: macos-15, asset: macos-arm64} + name: repro (${{ matrix.asset }}) + runs-on: ${{ matrix.runner }} + timeout-minutes: 200 + env: + VAPOURBOX_DEPS_DIR: ${{ github.workspace }}/deps/macos-${{ matrix.arch }} + VAPOURBOX_WORKER: ${{ github.workspace }}/worker/target/debug/vapourbox-worker + NAME: ${{ inputs.name || 'mp4\+av1/passthrough/delayed-avi/(untrimmed|near-start)' }} + ITER: ${{ inputs.iterations || '60' }} + LOAD_ITER: ${{ inputs.load_iterations || '15' }} + REPLAYS: ${{ inputs.replays || '300' }} + PHASES: ${{ inputs.phases || 'versions b1 b1load b2 b3' }} + S: ${{ github.workspace }}/docs/reports/task-99-av1-conformance-flake/scripts + R: ${{ github.workspace }}/repro-out + steps: + - uses: actions/checkout@v5 + + - name: Resolve deps tag + id: deps + run: | + TAG=$(python3 -c "import json;print(json.load(open('app/assets/deps-version.json'))['releaseTag'])") + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "ver=${TAG#deps-v}" >> "$GITHUB_OUTPUT" + + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: false + pub-cache-path: ${{ runner.temp }}/pub-cache + + - uses: dtolnay/rust-toolchain@stable + + - name: Download dependencies (${{ matrix.asset }}) + env: + GH_TOKEN: ${{ github.token }} + run: | + bash .github/scripts/install-deps-bundle.sh "${{ matrix.asset }}" \ + "${{ steps.deps.outputs.tag }}" "${{ steps.deps.outputs.ver }}" "deps/macos-${{ matrix.arch }}" + xattr -cr "deps/macos-${{ matrix.arch }}" 2>/dev/null || true + + - name: Build worker and generate Dart serialization + run: | + (cd worker && cargo build) + cd app && flutter pub get && dart run build_runner build --delete-conflicting-outputs + + - name: B0 versions + if: contains(env.PHASES, 'versions') + run: | + mkdir -p "$R" + FF="$VAPOURBOX_DEPS_DIR/ffmpeg/ffmpeg"; [ -x "$FF" ] || FF=$(find "$VAPOURBOX_DEPS_DIR" -name ffmpeg -type f -perm +111 | head -1) + { + echo "cpu: $(sysctl -n machdep.cpu.brand_string) cores $(sysctl -n hw.ncpu)" + "$FF" -hide_banner -version | head -3 + "$FF" -hide_banner -buildconf | grep -iE 'svt|dav1d|aom' || true + echo "AV1 decoders:"; "$FF" -hide_banner -decoders | grep -i av1 + echo "SVT-AV1 banner:" + SVT_LOG=4 "$FF" -hide_banner -v info -f lavfi -i testsrc2=s=160x120:r=25:d=0.2 \ + -c:v libsvtav1 -preset 10 -f null - 2>&1 | grep -iE 'svt|version|lib' | head -12 + echo "decoder ffmpeg picks for AV1:" + "$FF" -hide_banner -v error -y -f lavfi -i testsrc2=s=160x120:r=25:d=0.2 -c:v libsvtav1 "$RUNNER_TEMP/v.mp4" + "$FF" -hide_banner -nostats -v verbose -i "$RUNNER_TEMP/v.mp4" -f null - 2>&1 | grep -E 'Stream #0:0 ->|dav1d|libaom' | head -5 + } 2>&1 | tee "$R/versions.txt" + + - name: B1 the cases in a loop + if: contains(env.PHASES, 'b1 ') || endsWith(env.PHASES, 'b1') + run: | + mkdir -p "$R/kept-b1" + cd app + VAPOURBOX_CONFORMANCE_REPEAT=$ITER VAPOURBOX_CONFORMANCE_KEEP="$R/kept-b1" \ + flutter test --tags heavy test/integration_output_conformance_test.dart \ + --name "$NAME" --reporter compact --file-reporter "json:$R/b1.json" > "$R/b1.log" 2>&1 || true + tail -5 "$R/b1.log" + python3 "$S/summarize_flutter_json.py" "$R/b1.json" "B1 $NAME x$ITER" | tee "$R/b1-summary.txt" + + - name: B1 every mp4+av1 case under load + if: contains(env.PHASES, 'b1load') + run: | + mkdir -p "$R/kept-b1load" + N=$(sysctl -n hw.ncpu); for i in $(seq $((N - 1))); do yes > /dev/null & done + cd app + VAPOURBOX_CONFORMANCE_REPEAT=$LOAD_ITER VAPOURBOX_CONFORMANCE_KEEP="$R/kept-b1load" \ + flutter test --tags heavy test/integration_output_conformance_test.dart \ + --name 'mp4\+av1/' --reporter compact --file-reporter "json:$R/b1load.json" > "$R/b1load.log" 2>&1 || true + pkill yes || true + tail -5 "$R/b1load.log" + python3 "$S/summarize_flutter_json.py" "$R/b1load.json" "B1 load mp4+av1 x$LOAD_ITER" | tee "$R/b1load-summary.txt" + + - name: B2 the encoder alone + if: contains(env.PHASES, 'b2') + run: | + VS="$VAPOURBOX_DEPS_DIR/vapoursynth" + bash "$S/capture-vspipe-stdout.sh" install "$VS" "$R/capture" + (cd app && VAPOURBOX_CONFORMANCE_KEEP="$R/kept-b2" VAPOURBOX_CONFORMANCE_KEEP_ALL=1 \ + flutter test --tags heavy test/integration_output_conformance_test.dart \ + --plain-name 'mp4+av1/passthrough/delayed-avi/untrimmed' --reporter compact) || true + bash "$S/capture-vspipe-stdout.sh" uninstall "$VS" + Y4M=$(ls "$R"/capture/run.*/out.y4m | head -1) + LOG=$(ls "$R"/kept-b2/*/log.txt | head -1) + echo "y4m $Y4M ($(wc -c < "$Y4M") bytes), log $LOG" + FF="$VAPOURBOX_DEPS_DIR/ffmpeg/ffmpeg"; FP="$VAPOURBOX_DEPS_DIR/ffmpeg/ffprobe" + for mode in file throttled; do + python3 -I "$S/replay_encoder.py" --log "$LOG" --y4m "$Y4M" --ffmpeg "$FF" --ffprobe "$FP" \ + --out "$R/b2-$mode" --runs "$REPLAYS" --mode "$mode" | tee "$R/b2-$mode.txt" + done + N=$(sysctl -n hw.ncpu); for i in $(seq $((N - 1))); do yes > /dev/null & done + python3 -I "$S/replay_encoder.py" --log "$LOG" --y4m "$Y4M" --ffmpeg "$FF" --ffprobe "$FP" \ + --out "$R/b2-load" --runs "$REPLAYS" --mode throttled --parallel 4 | tee "$R/b2-load.txt" + pkill yes || true + rm -rf "$R/capture" + + - name: B3 the test's own decodes + if: contains(env.PHASES, 'b3') + run: | + FF="$VAPOURBOX_DEPS_DIR/ffmpeg/ffmpeg"; FP="$VAPOURBOX_DEPS_DIR/ffmpeg/ffprobe" + GOOD=$(ls "$R"/kept-b2/*/*.mp4 2>/dev/null | head -1) + BAD=$(ls "$R"/kept-b1*/*/*.mp4 2>/dev/null | head -1) + for f in $GOOD $BAD; do + tag=$( [ "$f" = "$GOOD" ] && echo good || echo bad ) + python3 -I "$S/measure_decode.py" --file "$f" --ffmpeg "$FF" --ffprobe "$FP" \ + --out "$R/b3-$tag" --runs "$REPLAYS" | tee "$R/b3-$tag.txt" + N=$(sysctl -n hw.ncpu); for i in $(seq $((N - 1))); do yes > /dev/null & done + python3 -I "$S/measure_decode.py" --file "$f" --ffmpeg "$FF" --ffprobe "$FP" \ + --out "$R/b3-$tag-load" --runs "$REPLAYS" --parallel 4 | tee "$R/b3-$tag-load.txt" + pkill yes || true + done + + - name: Summary + if: always() + run: | + for f in "$R"/versions.txt "$R"/*summary.txt "$R"/b2-*.txt "$R"/b3-*.txt; do + [ -f "$f" ] && { echo "=== $(basename "$f")"; tail -30 "$f"; } + done + + - name: Upload + if: always() + uses: actions/upload-artifact@v5 + with: + name: repro-output-conformance-${{ matrix.asset }} + path: | + repro-out/ + !repro-out/capture/ + if-no-files-found: ignore + retention-days: 14 diff --git a/CLAUDE.md b/CLAUDE.md index 74a13c5a..063413bb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2784,6 +2784,21 @@ table. Rules: `flutter test --tags heavy test/integration_output_conformance_test.dart --plain-name 'avi/convert-aac/delayed-avi/near-start'`. The shared measuring helpers are `test/support/av_sync.dart`. + **Every subprocess the matrix runs is bounded (task #99)**: + `test/support/bounded_process.dart`'s `runBounded` kills it at its limit + and names it, the job's limit (`jobTimeout`) is below the case's + (`caseTimeout`), and a hang is sampled (`describeHang`: `sample` on + macOS, gdb on Linux) before its tree is killed; never `Process.run` there + (`conformance_timeouts_test.dart`). A failing case prints its job log + tail, packet and decoded counts and the job, and is kept under + `$VAPOURBOX_CONFORMANCE_KEEP` (the nightly uploads it as + `conformance-failures-`); `VAPOURBOX_CONFORMANCE_REPEAT=N` runs + each case N times in one process, which + `.github/workflows/repro-output-conformance.yml` uses to loop a case on + the nightly's runners. The two `mp4+av1` failures of 2026-11-19/21 on + macOS x64 did not reproduce in 960 case runs, 1,800 encoder replays + and 9,600 decodes there (docs/reports/task-99-av1-conformance-flake); + never retry a case or list an intermittent one in `knownFailures`. ### Audio Restoration @@ -3436,6 +3451,13 @@ cd worker && cargo run --release -- --config test_job.json > (task #64). The worker now probes the format, but only the assertion makes > a test fail if its depth stops reaching the pass. +> **A heavy test that runs a detector or several encodes states its +> timeout, sized by the slowest platform (macOS x64's 4-core runner).** +> package:test's default is 30 s; `--detect-native` on a small ProRes took +> 23-30 s there and failed 8 nightly legs (task #99, as task #95 did for +> Descale). Don't raise the default in `dart_test.yaml`: it would hide real +> hangs everywhere. + > **The heavy tests run the worker BINARY, not the library**, and > `app/lib/**/*.g.dart` is gitignored — **run `cargo build` before the heavy > suite** and `dart run build_runner build` before any Dart test, or you'll diff --git a/app/test/conformance_timeouts_test.dart b/app/test/conformance_timeouts_test.dart new file mode 100644 index 00000000..5be0958f --- /dev/null +++ b/app/test/conformance_timeouts_test.dart @@ -0,0 +1,115 @@ +/// Time limits in the heavy tests (task #99), checked in the push gate. +/// +/// - `runBounded` kills a process at its limit and names it, rather than +/// waiting forever as `Process.run` does. +/// - The output conformance matrix's job limit is below its case limit, so +/// a hung job is killed and reported with where it hung, not cut off by +/// the test's bare TimeoutException. +/// - Each test of `integration_reserved_colour_tags_test.dart` that runs +/// the worker, a detector or ffmpeg states its timeout: on the macOS x64 +/// runner `--detect-native` took 23-30 s there and failed 8 nightly legs +/// at package:test's 30 s default. Its per-detect limit fits twice in it. +library; + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/bounded_process.dart'; + +String _read(String name) => + File(p.join(Directory.current.path, 'test', name)).readAsStringSync().replaceAll('\r\n', '\n'); + +Duration _const(String source, String name) { + final m = RegExp('const $name = (?:Timeout\\()?Duration\\((minutes|seconds): (\\d+)\\)') + .firstMatch(source); + expect(m, isNotNull, reason: 'no `const $name = Duration(...)`'); + final n = int.parse(m!.group(2)!); + return m.group(1) == 'minutes' ? Duration(minutes: n) : Duration(seconds: n); +} + +/// Each `test(` in [source] with its body, up to the next top-level `test(` +/// or `group(` at the same indent. +Iterable<(String, String)> _tests(String source) sync* { + final starts = RegExp(r'^(\s*)test\(\s*(.)(.*?)\2', multiLine: true).allMatches(source).toList(); + for (var i = 0; i < starts.length; i++) { + final end = i + 1 < starts.length ? starts[i + 1].start : source.length; + yield (starts[i].group(3)!, source.substring(starts[i].start, end)); + } +} + +void main() { + test('runBounded kills a process at its limit and names it', () async { + final (exe, args) = Platform.isWindows + ? ('powershell', ['-NoProfile', '-Command', 'Start-Sleep -Seconds 30']) + : ('sleep', ['30']); + final watch = Stopwatch()..start(); + Object? error; + try { + await runBounded(exe, args, label: 'a sleep', timeout: const Duration(seconds: 1)); + } catch (e) { + error = e; + } + expect(error, isA()); + expect('$error', contains('a sleep: still running after 1 s, killed')); + expect('$error', contains(exe)); + expect(watch.elapsed, lessThan(const Duration(seconds: 25)), + reason: 'it waited for the process instead of killing it'); + }); + + test('runBounded returns what Process.run would', () async { + final r = Platform.isWindows + ? await runBounded('cmd', ['/c', 'echo hi'], label: 'echo') + : await runBounded('sh', ['-c', 'echo hi; echo err >&2; exit 3'], label: 'echo'); + expect('${r.stdout}'.trim(), 'hi'); + if (!Platform.isWindows) { + expect('${r.stderr}'.trim(), 'err'); + expect(r.exitCode, 3); + } + }); + + test('describeHang names the tree and keeps to its budget', () async { + if (Platform.isWindows) return; // no ps, no stacks + final proc = await Process.start('sh', ['-c', 'sleep 30 & sleep 30; wait']); + try { + await Future.delayed(const Duration(milliseconds: 300)); + final watch = Stopwatch()..start(); + final report = await describeHang(proc.pid, + budget: const Duration(seconds: 6), perProcess: const Duration(seconds: 4)); + expect(report, contains('process tree at the timeout')); + expect(report, contains('sleep 30')); + expect(watch.elapsed, lessThan(const Duration(seconds: 15)), + reason: 'the report outran its budget'); + } finally { + await Process.run('pkill', ['-P', '${proc.pid}']); // the sleeps, first + proc.kill(ProcessSignal.sigkill); + } + }); + + test('the conformance matrix kills a hung job before the case times out', () { + final s = _read('integration_output_conformance_test.dart'); + final job = _const(s, 'jobTimeout'), kase = _const(s, 'caseTimeout'); + // The job's limit leaves time to sample the tree and print the evidence. + expect(job + const Duration(seconds: 20), lessThan(kase)); + expect(s, contains('WorkerHarness.runJob(job, label: c.id, timeout: jobTimeout)')); + expect(s, contains('timeout: const Timeout(caseTimeout)')); + expect(s, isNot(contains('Process.run(')), + reason: 'every subprocess of the matrix is bounded (runBounded)'); + }); + + test('every reserved-colour-tags test that runs something states its timeout', () { + final s = _read('integration_reserved_colour_tags_test.dart'); + final whole = _const(s, '_timeout'), detect = _const(s, '_detectLimit'); + expect(detect * 2, lessThan(whole), reason: 'each test runs two detects'); + var checked = 0; + for (final (name, body) in _tests(s)) { + if (!RegExp(r'_detect\(|runJob\(|runPreview\(|_ffmpeg\(').hasMatch(body)) continue; + checked++; + expect(body, contains('timeout: _timeout'), reason: '"$name" runs something with the 30 s default'); + } + expect(checked, greaterThanOrEqualTo(7)); + expect(s, isNot(contains('Process.run(\n WorkerHarness.workerPath')), + reason: 'the detectors run bounded'); + }); +} diff --git a/app/test/integration_audio_restoration_test.dart b/app/test/integration_audio_restoration_test.dart index d6a2a5e5..770cba15 100644 --- a/app/test/integration_audio_restoration_test.dart +++ b/app/test/integration_audio_restoration_test.dart @@ -299,7 +299,8 @@ void main() { if (container == 'mov') expect(first['codec_tag_string'], 'in24', reason: label); expect(await s32(out), orderedEquals(expected), reason: '$label: the same samples as the MKV reference'); } - }); + // Several encodes: up to 31 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); test('subtitles are transcribed from the restored sound, so cues follow the offset', () async { // CI provisions Whisper; locally, VAPOURBOX_FETCH_WHISPER=1 installs the diff --git a/app/test/integration_avi_audio_seek_test.dart b/app/test/integration_avi_audio_seek_test.dart index 9b8eaa1c..217fa107 100644 --- a/app/test/integration_avi_audio_seek_test.dart +++ b/app/test/integration_avi_audio_seek_test.dart @@ -210,7 +210,8 @@ void main() { // the sound was 1.28 s off. expect(lag, isNotNull, reason: 'the in-point\'s sound is not near the picture: $starts'); expect(lag!.abs(), lessThanOrEqualTo(40), reason: 'lag $lag samples, $starts'); - }); + // Up to 25 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); } for (final start in [1, 2, 3, 20]) { diff --git a/app/test/integration_avi_copy_trim_test.dart b/app/test/integration_avi_copy_trim_test.dart index 90984645..f2c464eb 100644 --- a/app/test/integration_avi_copy_trim_test.dart +++ b/app/test/integration_avi_copy_trim_test.dart @@ -186,7 +186,8 @@ void main() { // Before the fix: 137-375 ms late. expect(_syncLag(source, sound, start, vs), 0); expect(_maxDiffFromInPoint(source, sound, start, vs), 0); - }); + // Up to 29 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); } // Half a packet, plus a millisecond for the AVI demuxer's own timestamps. diff --git a/app/test/integration_frame_mapping_test.dart b/app/test/integration_frame_mapping_test.dart index 18e71c34..0ff11b29 100644 --- a/app/test/integration_frame_mapping_test.dart +++ b/app/test/integration_frame_mapping_test.dart @@ -290,7 +290,8 @@ void main() { expect(_progressTotals(r), everyElement(n), reason: 'issue #134: a total left at the source count pins ' 'progress at 100% with no ETA for the rest of the encode'); - }); + // Up to 28 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); test('a custom frame rate is the exact rate typed in', () async { // Issue #129. 59.94 typed in must run at 60000/1001, not 2997/50: from diff --git a/app/test/integration_output_conformance_test.dart b/app/test/integration_output_conformance_test.dart index 0b6a3cf4..12adb6d2 100644 --- a/app/test/integration_output_conformance_test.dart +++ b/app/test/integration_output_conformance_test.dart @@ -18,6 +18,7 @@ @Tags(['heavy']) library; +import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; @@ -37,6 +38,7 @@ import 'package:vapourbox/services/timestamp_continuity_service.dart'; import 'package:vapourbox/services/tool_locator.dart'; import 'support/av_sync.dart'; +import 'support/bounded_process.dart'; import 'support/output_matrix.dart'; import 'support/worker_harness.dart'; @@ -87,10 +89,11 @@ class _Source { /// across containers that packetise the same frames differently (a TS PES /// holds several MP2 frames, Matroska one each). Future _payload(String path) async { - final r = await Process.run( + final r = await runBounded( WorkerHarness.ffmpegPath, ['-v', 'error', '-i', path, '-map', '0:a:0', '-c', 'copy', '-f', 'data', '-'], - stdoutEncoding: null, + label: 'the sound payload copy', + binaryStdout: true, environment: WorkerHarness.ffmpegEnv, ); expect(r.exitCode, 0, reason: '${r.stderr}'); @@ -98,11 +101,12 @@ Future _payload(String path) async { } Future _samples(String path, {String? decoder}) async { - final r = await Process.run( + final r = await runBounded( WorkerHarness.ffmpegPath, ['-v', 'error', if (decoder != null) ...['-c:a', decoder], '-i', path, '-map', '0:a:0', '-ac', '1', '-f', 'f32le', '-'], - stdoutEncoding: null, + label: 'the sample decode', + binaryStdout: true, environment: WorkerHarness.ffmpegEnv, ); final bytes = Uint8List.fromList(r.stdout as List); @@ -269,10 +273,97 @@ String? _byteRun(Uint8List out, Uint8List src) { '(the longest match: $best bytes, at $bestAt)'; } +/// Each case's limit, and its job's: the job's is below the case's, so a +/// hung job is killed as a tree and reported with where it hung (task #99), +/// not cut off by the test's bare TimeoutException with its processes left +/// running. `conformance_timeouts_test.dart` (push gate) holds the order. +const caseTimeout = Duration(minutes: 3); +const jobTimeout = Duration(seconds: 150); + +/// Encodes [c] and checks the output; on any failure prints what tells an +/// encoder that lost a picture from a decoder that did, or a pipeline that +/// did ([_evidence]), and keeps the output in `$VAPOURBOX_CONFORMANCE_KEEP`. Future _check(MatrixCase c, _Source s) async { - final r = await WorkerHarness.runJob(_job(c, s).toJson(), label: c.id); - expect(r.success, isTrue, reason: '1. the job: ${r.error}'); - final out = r.outputPath!; + final job = _job(c, s).toJson(); + final r = await WorkerHarness.runJob(job, label: c.id, timeout: jobTimeout); + try { + expect(r.success, isTrue, reason: '1. the job: ${r.error}'); + await _checkOutput(c, s, r.outputPath!); + } catch (_) { + await _evidence(c, job, r); + rethrow; + } + // `VAPOURBOX_CONFORMANCE_KEEP_ALL=1` keeps passing cases too: the repro + // workflow replays a good job's encoder from them (task #99). + if (Platform.environment['VAPOURBOX_CONFORMANCE_KEEP_ALL'] == '1') { + await _evidence(c, job, r, failed: false); + } +} + +/// What a failed case leaves behind for its diagnosis (task #99): the job's +/// log tail (vspipe's "Output N frames", the encoder's last lines), the +/// output's video packet count beside the frames ffprobe and an ffmpeg +/// decode count, the decoder ffmpeg chose, and the job. With +/// `$VAPOURBOX_CONFORMANCE_KEEP` set, the output and the job are copied +/// there (nightly uploads it). +Future _evidence(MatrixCase c, Map job, JobResult r, + {bool failed = true}) async { + final b = StringBuffer('--- evidence for ${c.id} (task #99) ---\n'); + b.writeln('job: ${r.success ? 'succeeded' : 'failed: ${r.error}'} in ${r.duration.inMilliseconds} ms'); + final out = r.outputPath ?? '${job['outputPath']}'; + for (final l in r.logs) { + if (l.contains('Output ') && l.contains(' frames')) b.writeln('vspipe: $l'); + } + final tail = r.logs.length > 40 ? r.logs.sublist(r.logs.length - 40) : r.logs; + b.writeln('job log, last ${tail.length} lines:'); + for (final l in tail) { + b.writeln(' ${l.length > 400 ? '${l.substring(0, 400)}…' : l}'); + } + if (File(out).existsSync()) { + try { + final v = await WorkerHarness.ffprobeJson([ + '-v', 'error', '-select_streams', 'v:0', '-count_packets', '-count_frames', + '-show_entries', 'stream=codec_name,nb_frames,nb_read_packets,nb_read_frames', + '-of', 'json', out, + ], timeout: const Duration(seconds: 60)); + b.writeln('video stream: ${(v['streams'] as List).firstOrNull}'); + } catch (e) { + b.writeln('ffprobe count: $e'); + } + try { + final d = await runBounded( + WorkerHarness.ffmpegPath, + ['-hide_banner', '-nostats', '-v', 'info', '-i', out, '-map', '0:v:0', '-f', 'null', '-'], + label: 'the evidence decode', + timeout: const Duration(seconds: 60), + environment: WorkerHarness.ffmpegEnv, + ); + for (final l in '${d.stderr}'.split('\n')) { + if (l.contains('Stream #0:') && l.contains('->') || l.contains('frames decoded') || + l.contains('frames encoded') || l.contains('frame=')) { + b.writeln('ffmpeg decode: ${l.trim()}'); + } + } + } catch (e) { + b.writeln('ffmpeg decode: $e'); + } + } else { + b.writeln('no output file at $out'); + } + b.writeln('job: ${jsonEncode(job)}'); + final keep = Platform.environment['VAPOURBOX_CONFORMANCE_KEEP']; + if (keep != null && keep.isNotEmpty) { + final dir = Directory(p.join(keep, c.id.replaceAll(RegExp(r'[^A-Za-z0-9]+'), '_'))) + ..createSync(recursive: true); + if (File(out).existsSync()) File(out).copySync(p.join(dir.path, p.basename(out))); + File(p.join(dir.path, 'job.json')).writeAsStringSync(jsonEncode(job)); + File(p.join(dir.path, 'log.txt')).writeAsStringSync('${b.toString()}\n${r.logs.join('\n')}'); + b.writeln('kept in ${dir.path}'); + } + if (failed) print(b); +} + +Future _checkOutput(MatrixCase c, _Source s, String out) async { // 1. The header wrote: one video stream and the expected sound. final streams = await WorkerHarness.ffprobeJson([ @@ -389,8 +480,14 @@ void main() { av1 = await WorkerHarness.hasEncoder('libsvtav1'); }); - for (final c in cases) { - test(c.id, () async { + // `VAPOURBOX_CONFORMANCE_REPEAT=N` registers each case N times, for + // reproducing an intermittent one in one process + // (`repro-output-conformance.yml`, task #99). Never a retry: each run is + // its own test and its own verdict. + final repeat = int.tryParse(Platform.environment['VAPOURBOX_CONFORMANCE_REPEAT'] ?? '') ?? 1; + final runs = [for (final c in cases) for (var k = 1; k <= repeat; k++) (c, k)]; + for (final (c, run) in runs) { + test(repeat == 1 ? c.id : '${c.id} (run $run of $repeat)', () async { if (c.video == VideoCodec.av1 && !av1) { markTestSkipped('no libsvtav1 in this FFmpeg'); return; @@ -409,7 +506,7 @@ void main() { expect(failure, isNotNull, reason: 'a known failure ($known) now passes: remove it from knownFailures'); print(' known failure ($known): $failure'); - }, timeout: const Timeout(Duration(minutes: 3))); + }, timeout: const Timeout(caseTimeout)); } // Found by the matrix: a reset whose first part's sound ends off the @@ -444,10 +541,11 @@ void main() { test('a copy the container cannot hold is refused before any work (task #49)', () async { final opus = p.join(_outDir, 'opus_source.mkv'); - final made = await Process.run( + final made = await runBounded( WorkerHarness.ffmpegPath, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc2=s=160x120:r=25:d=1', '-f', 'lavfi', '-i', 'sine=d=1:sample_rate=48000', '-c:v', 'ffv1', '-c:a', 'libopus', opus], + label: 'making the Opus source', environment: WorkerHarness.ffmpegEnv, ); expect(made.exitCode, 0, reason: '${made.stderr}'); diff --git a/app/test/integration_reserved_colour_tags_test.dart b/app/test/integration_reserved_colour_tags_test.dart index c455ff1b..94e607d1 100644 --- a/app/test/integration_reserved_colour_tags_test.dart +++ b/app/test/integration_reserved_colour_tags_test.dart @@ -34,6 +34,7 @@ import 'package:vapourbox/models/video_job.dart'; import 'package:vapourbox/models/source_model.dart'; import 'package:vapourbox/services/preview_generator.dart'; +import 'support/bounded_process.dart'; import 'support/worker_harness.dart'; String get _outDir => p.join(WorkerHarness.outputDir, 'reserved_colour_tags'); @@ -118,16 +119,34 @@ Future<(Uint8List?, String)> _ffmpeg(List args) async { return (out.readAsBytesSync(), ''); } +/// Every test here that runs the worker, a detector or ffmpeg states its +/// limit, sized by the slowest platform: `--detect-native` on a 15-frame +/// 720x480 ProRes took 23-30 s on the 4-core macOS x64 runner beside other +/// heavy files, past package:test's 30 s default (task #99, as task #95 did +/// for the Descale test). `conformance_timeouts_test.dart` checks it. +const _timeout = Timeout(Duration(minutes: 5)); + +/// One detector run's limit, below the test's (two runs each): a hang is +/// killed and named with the stderr it reached (`NATIVE_RES_STAGE:` lines +/// for `--detect-native`) instead of hitting the test's timeout. +const _detectLimit = Duration(minutes: 2); + Future> _detect(String flag, VideoJob job) async { final config = File(p.join(_outDir, '${job.id}.json')); await config.writeAsString(jsonEncode(job.toJson())); try { - final r = await Process.run( + final r = await runBounded( WorkerHarness.workerPath, [flag, '--config', config.path], + label: flag, + timeout: _detectLimit, environment: WorkerHarness.workerEnv, workingDirectory: File(WorkerHarness.workerPath).parent.path, ); + final stages = const LineSplitter() + .convert(r.stderr.toString()) + .where((l) => l.contains('NATIVE_RES_STAGE:')); + if (stages.isNotEmpty) print(' $flag ${job.id}: ${stages.map((l) => l.split('NATIVE_RES_STAGE:').last.trim()).join('; ')}'); final line = const LineSplitter() .convert(r.stdout.toString()) .lastWhere((l) => l.trim().startsWith('{'), orElse: () => '{}'); @@ -204,7 +223,7 @@ void main() { reason: s.path, ); } - }); + }, timeout: _timeout); test('thumbnail: fails without the fix, succeeds with it', () async { List args({String? tagFix}) => PreviewGenerator.thumbnailArgs( @@ -217,25 +236,25 @@ void main() { expect(broken, isNull, reason: 'the fixture no longer reproduces the bug'); final (fixed, err) = await _ffmpeg(args(tagFix: prores422.tagFix)); expect(fixed, isNotNull, reason: err); - }); + }, timeout: _timeout); test('--detect-crop reports exactly what it reports on the twin', () async { final report = await _detect('--detect-crop', prores422.job('crop')); final twin = await _detect('--detect-crop', twin422.job('crop_twin')); expect(report, twin); - }); + }, timeout: _timeout); test('--detect-native reports exactly what it reports on the twin', () async { final report = await _detect('--detect-native', prores422.job('native')); final twin = await _detect('--detect-native', twin422.job('native_twin')); expect(report, twin); - }); + }, timeout: _timeout); test('--detect-noise-halo reports exactly what it reports on the twin', () async { final report = await _detect('--detect-noise-halo', prores422.job('nh')); final twin = await _detect('--detect-noise-halo', twin422.job('nh_twin')); expect(report, twin); - }); + }, timeout: _timeout); test('preview renders the twin\'s picture (422 and converted 4444a)', () async { for (final (s, t) in [(prores422, twin422), (prores4444a, twin4444a)]) { @@ -252,7 +271,7 @@ void main() { reason: s.path, ); } - }); + }, timeout: _timeout); test('a 4444-with-alpha encode (converting decoder) equals the twin\'s', () async { final job = await WorkerHarness.runJob(prores4444a.job('enc').toJson(), @@ -262,5 +281,5 @@ void main() { label: 'encode twin 4444a'); expect(twin.success, isTrue, reason: '${twin.error}\n${twin.logs.join('\n')}'); expect(await _framesMd5(job.outputPath!), await _framesMd5(twin.outputPath!)); - }); + }, timeout: _timeout); } diff --git a/app/test/integration_source_grid_test.dart b/app/test/integration_source_grid_test.dart index cfad1b81..334a5ffa 100644 --- a/app/test/integration_source_grid_test.dart +++ b/app/test/integration_source_grid_test.dart @@ -258,7 +258,8 @@ void main() { expect(r.success, isTrue, reason: r.error); expect(await _lumaHashes(r.outputPath!, []), ref.slotHashes(0, ref.slots.length - 1)); - }); + // A whole-source encode: up to 24 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); for (final n in f.frames) { test('frame $n: the preview, the Original and a trim from it are slot ' @@ -305,7 +306,8 @@ void main() { expect(r.success, isTrue, reason: r.error); expect(await _lumaHashes(r.outputPath!, []), ref.slotHashes(0, ref.slots.length - 1)); - }); + // A whole-source encode: up to 24 s on macOS x64 (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); } }); diff --git a/app/test/integration_video_start_offset_test.dart b/app/test/integration_video_start_offset_test.dart index 9733469c..b7ee956b 100644 --- a/app/test/integration_video_start_offset_test.dart +++ b/app/test/integration_video_start_offset_test.dart @@ -511,7 +511,9 @@ void main() { await check('Convert AAC ${quality.name}${trim ? ', trimmed' : ''}', job(name, AudioMode.convert, quality, trim: trim), mustOvershoot: must); } - }); + // Four encodes: 11-30 s on the 4-core macOS x64 runner beside other + // heavy files, past package:test's 30 s default (task #99). + }, timeout: const Timeout(Duration(minutes: 5))); test('a 256 kbps mono AAC source copied into AVI: every beep on its flash', () async { await Directory(_outDir).create(recursive: true); @@ -529,7 +531,7 @@ void main() { await check('Passthrough of 256 kbps mono AAC', VideoJob.fromJson({...copied.toJson(), 'inputPath': source}), mustOvershoot: true); - }); + }, timeout: const Timeout(Duration(minutes: 5))); }); // Task #43: a source whose sound ffmpeg encoded (AAC, MP3 in MKV/MP4) diff --git a/app/test/support/av_sync.dart b/app/test/support/av_sync.dart index da359568..79deecbe 100644 --- a/app/test/support/av_sync.dart +++ b/app/test/support/av_sync.dart @@ -10,6 +10,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; +import 'bounded_process.dart'; import 'worker_harness.dart'; /// Width x height of the first video stream. @@ -40,11 +41,12 @@ Future<({List flashes, List beeps, double videoStart})> events( pts.add(pts.isEmpty ? 0 : pts.last); } } - final luma = await Process.run( + final luma = await runBounded( WorkerHarness.ffmpegPath, ['-v', 'quiet', '-i', path, '-map', '0:v:0', '-fps_mode', 'passthrough', '-f', 'rawvideo', '-pix_fmt', 'gray', '-'], - stdoutEncoding: null, + label: 'the luma decode', + binaryStdout: true, environment: WorkerHarness.ffmpegEnv, ); final y = luma.stdout as List; @@ -72,10 +74,11 @@ Future> beepOnsets(String path) async { 'frame=pts_time,nb_samples:stream=sample_rate', '-of', 'json', path, ]); final rate = int.parse('${(af['streams'] as List).first['sample_rate']}'); - final pcm = await Process.run( + final pcm = await runBounded( WorkerHarness.ffmpegPath, ['-v', 'quiet', '-i', path, '-map', '0:a:0', '-ac', '1', '-f', 'f32le', '-'], - stdoutEncoding: null, + label: 'the sound decode', + binaryStdout: true, environment: WorkerHarness.ffmpegEnv, ); final bytes = Uint8List.fromList(pcm.stdout as List); diff --git a/app/test/support/bounded_process.dart b/app/test/support/bounded_process.dart new file mode 100644 index 00000000..f36f0b9c --- /dev/null +++ b/app/test/support/bounded_process.dart @@ -0,0 +1,178 @@ +/// Subprocesses with a time limit, for the heavy tests (task #99). +/// +/// `Process.run` waits forever. In the output conformance matrix a measuring +/// ffprobe or a hung job ran into the test's own 3-minute timeout, which +/// names nothing, kills nothing, and leaves the stuck process tree running +/// beside the next case. [runBounded] kills the process (and its group) at +/// its limit and throws a [BoundedTimeout] naming the command; before the +/// kill, [describeHang] records where each process of the tree is stuck +/// (macOS `sample`, Linux `gdb` when present), so a hang in CI says which +/// process hung and in what. +library; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:vapourbox/services/process_tree.dart'; + +/// A [runBounded] process that outlived its limit. [hang] is what +/// [describeHang] found before it was killed. +class BoundedTimeout implements Exception { + BoundedTimeout(this.label, this.limit, this.command, this.hang, [this.stderrTail = '']); + + final String label; + final Duration limit; + final String command; + final String hang; + + /// The last lines the process wrote to stderr before it was killed. + final String stderrTail; + + @override + String toString() => '$label: still running after ${limit.inSeconds} s, killed: ' + '$command${stderrTail.isEmpty ? '' : '\nits stderr ended:\n$stderrTail'}' + '${hang.isEmpty ? '' : '\n$hang'}'; +} + +/// Runs [executable] like `Process.run`, but kills it after [timeout] and +/// throws a [BoundedTimeout] naming [label] and the command. `stdout` is a +/// [String] (UTF-8) unless [binaryStdout], then a [Uint8List]. +/// +/// The default limit is generous on purpose: the heavy tests measure small +/// files, so a bounded run only trips on a hang, never on a slow machine. +Future runBounded( + String executable, + List arguments, { + required String label, + Duration timeout = const Duration(seconds: 120), + Map? environment, + String? workingDirectory, + bool binaryStdout = false, +}) async { + final process = await Process.start(executable, arguments, + environment: environment, workingDirectory: workingDirectory); + final out = BytesBuilder(copy: false); + final err = BytesBuilder(copy: false); + final outDone = process.stdout.listen(out.add).asFuture(); + final errDone = process.stderr.listen(err.add).asFuture(); + final int code; + try { + code = await process.exitCode.timeout(timeout); + } on TimeoutException { + final hang = await describeHang(process.pid); + await ProcessTree.killTree(process, ProcessSignal.sigkill); + final lines = utf8.decode(err.toBytes(), allowMalformed: true).trimRight().split('\n'); + throw BoundedTimeout(label, timeout, _command(executable, arguments), hang, + lines.sublist(lines.length > 20 ? lines.length - 20 : 0).join('\n')); + } + await Future.wait([outDone, errDone]); + final stdoutBytes = out.takeBytes(); + return ProcessResult( + process.pid, + code, + binaryStdout ? stdoutBytes : utf8.decode(stdoutBytes, allowMalformed: true), + utf8.decode(err.takeBytes(), allowMalformed: true), + ); +} + +String _command(String exe, List args) => + [exe, ...args].map((a) => a.contains(' ') ? "'$a'" : a).join(' '); + +/// [pid] and every process under it, as `(pid, command)`, parents first. +/// Empty on Windows (no `ps`). +Future> processTree(int pid) async { + if (Platform.isWindows) return []; + final ps = await Process.run('ps', ['-A', '-o', 'pid=,ppid=,command=']); + if (ps.exitCode != 0) return []; + final children = >{}; + final command = {}; + for (final line in (ps.stdout as String).split('\n')) { + final m = RegExp(r'^\s*(\d+)\s+(\d+)\s+(.*)$').firstMatch(line); + if (m == null) continue; + final p = int.parse(m.group(1)!), pp = int.parse(m.group(2)!); + command[p] = m.group(3)!; + children.putIfAbsent(pp, () => []).add(p); + } + if (!command.containsKey(pid)) return []; + final out = <(int, String)>[]; + final queue = [pid]; + while (queue.isNotEmpty) { + final p = queue.removeAt(0); + out.add((p, command[p] ?? '?')); + queue.addAll(children[p] ?? const []); + } + return out; +} + +/// Where each process under [pid] is stuck, for a hang's report: the tree +/// (`ps`), then each process's threads' stacks: macOS `sample 2`, +/// Linux `gdb -batch -ex 'thread apply all bt'` when gdb is installed. +/// Nothing on Windows. Never throws: a report that fails says why. +Future describeHang(int pid, + {int maxLinesEach = 120, + Duration budget = const Duration(seconds: 20), + Duration perProcess = const Duration(seconds: 10)}) async { + try { + final tree = await processTree(pid); + if (tree.isEmpty) return ''; + final b = StringBuffer('process tree at the timeout:\n'); + for (final (p, c) in tree) { + b.writeln(' $p ${c.length > 300 ? '${c.substring(0, 300)}…' : c}'); + } + // The whole report has [budget]: a hung job's is taken inside the 30 s + // between the job's limit and the case's (conformance_timeouts_test). + final deadline = DateTime.now().add(budget); + for (final (p, c) in tree) { + final name = c.split(' ').first.split('/').last; + final left = deadline.difference(DateTime.now()); + if (left < const Duration(seconds: 3)) { + b.writeln('--- $p $name: not sampled (the ${budget.inSeconds} s budget was used) ---'); + continue; + } + final List cmd; + if (Platform.isMacOS) { + cmd = ['sample', '$p', '2', '-mayDie']; + } else if (Platform.isLinux) { + cmd = ['gdb', '-batch', '-p', '$p', '-ex', 'thread apply all bt']; + } else { + continue; + } + final String text; + try { + text = await _runKilledAt(cmd, left < perProcess ? left : perProcess); + } on ProcessException { + b.writeln('(no ${cmd.first}: no stacks)'); + break; + } + final lines = text.split('\n').where((l) => l.trim().isNotEmpty).toList(); + // `sample`'s call graph starts at "Call graph:"; its header is noise. + final start = lines.indexWhere((l) => l.startsWith('Call graph:')); + final body = start < 0 ? lines : lines.sublist(start); + b.writeln('--- $p $name ---'); + b.writeln((body.length > maxLinesEach ? [...body.take(maxLinesEach), '…'] : body) + .join('\n')); + } + return b.toString(); + } catch (e) { + return '(could not describe the hang: $e)'; + } +} + +/// [cmd]'s stdout and stderr, the process killed if it outlives [limit] +/// (a `sample` or `gdb` that hangs must not hold the report). +Future _runKilledAt(List cmd, Duration limit) async { + final proc = await Process.start(cmd.first, cmd.sublist(1)); + final out = StringBuffer(); + final a = proc.stdout.transform(utf8.decoder).listen(out.write).asFuture(); + final e = proc.stderr.transform(utf8.decoder).listen(out.write).asFuture(); + try { + await proc.exitCode.timeout(limit); + } on TimeoutException { + proc.kill(ProcessSignal.sigkill); + out.writeln('(${cmd.first} killed after ${limit.inSeconds} s)'); + } + await Future.wait([a, e]).timeout(const Duration(seconds: 2), onTimeout: () => []); + return out.toString(); +} diff --git a/app/test/support/worker_harness.dart b/app/test/support/worker_harness.dart index 5fbf7eda..28af0308 100644 --- a/app/test/support/worker_harness.dart +++ b/app/test/support/worker_harness.dart @@ -40,6 +40,8 @@ import 'package:vapourbox/services/whisper_addon_manager.dart'; import 'package:vapourbox/services/dependency_manager.dart' show DepsVersionInfo, DependencyManager; +import 'bounded_process.dart'; + /// Static entry point used by every integration test's `setUpAll`/helpers. class WorkerHarness { WorkerHarness._(); @@ -474,10 +476,14 @@ class WorkerHarness { final exitCode = await process.exitCode.timeout( timeout, onTimeout: () async { + // Where each process of the tree is stuck, before it is killed + // (task #99: a hung job used to say nothing at all). + final hang = await describeHang(process.pid); // The whole tree: on Windows killing the worker alone leaves its // vspipe running a network on every core, starving later tests. await ProcessTree.killTree(process, ProcessSignal.sigkill); - throw TimeoutException('$label timed out after ${timeout.inSeconds}s'); + throw TimeoutException( + '$label timed out after ${timeout.inSeconds}s${hang.isEmpty ? '' : '\n$hang'}'); }, ); stopwatch.stop(); @@ -584,8 +590,13 @@ class WorkerHarness { } /// Run ffprobe and return decoded JSON. - static Future> ffprobeJson(List args) async { - final result = await Process.run(ffprobePath, args, environment: ffmpegEnv); + /// + /// Bounded (task #99): a measuring ffprobe that hangs is killed after + /// [timeout] and named, rather than holding the test to its own limit. + static Future> ffprobeJson(List args, + {Duration timeout = const Duration(seconds: 120)}) async { + final result = await runBounded(ffprobePath, args, + label: 'ffprobe', timeout: timeout, environment: ffmpegEnv); if (result.exitCode != 0) { throw Exception('ffprobe failed: ${result.stderr}'); } diff --git a/docs/ENGINEERING_NOTES.md b/docs/ENGINEERING_NOTES.md index 3c2b4c03..87f319d1 100644 --- a/docs/ENGINEERING_NOTES.md +++ b/docs/ENGINEERING_NOTES.md @@ -6347,3 +6347,36 @@ did every 8-bit one with High Precision. Task #79 found it. "Double-rate"). Report: [docs/reports/task-89-qtgmc-mask-high-bit-depth](reports/task-89-qtgmc-mask-high-bit-depth/index.html). + +### AV1-into-MP4 conformance failures on macOS x64: not reproduced, made diagnosable (task #99, 2026-11-22) + +Task #94 saw four `mp4+av1` cases of the output conformance matrix fail on the +macOS x64 nightly, each differently. Reading every nightly heavy job since +11-16: the two "white frames at [1.12]" failures (11-16, 11-17) were task +#58's `pipe_source` fault (17-31 other near-start cases in every container +failed with them), and 11-18's SIGSEGVs task #68's vspipe race. Two remain: +`mp4+av1/passthrough/delayed-avi/near-start` past the test's 3 minutes +(11-19, rc1) and `…/untrimmed` with 99 pictures for 100 (11-21, rc2), both +x64-v2; about 2 in 10 legs, never elsewhere. + +- **Not reproduced** on the nightly's `macos-15-intel` runners + (`repro-output-conformance.yml`, run 44992968756), either tier: the two + cases 60 times each, every `mp4+av1` case 15 times with the CPU busy, the + encoder alone 900 times from the captured Y4M (from a file, throttled as + vspipe writes, 4 at once under load: always 100 packets, one hash), and + the test's decodes 4,800 times (100 every time; libdav1d, single thread, + libaom). SVT-AV1 is 4.2.0 and dav1d 1.5.4 on both arches. At the nightly's + rate about 8 failures were expected, so its trigger is something the loop + lacks, most likely the other heavy files running beside it. +- **So the next one explains itself:** every subprocess of the matrix is + bounded (`runBounded`), the job's limit is below the case's and a hang is + sampled before its tree is killed, a failing case prints its log tail, + packet and decoded counts and job, and the nightly uploads its output + (`VAPOURBOX_CONFORMANCE_KEEP`). The worker logs its encoder arguments. No + retry; no `knownFailures` entry for an intermittent case. +- **Found on the way:** 8 macOS x64 legs had failed on package:test's 30 s + default timeout, not on any fault: `--detect-native` on the reserved-tag + ProRes (23-30 s there) and task #41's AAC test. Those and five more tests + measured at 23-31 s state 5 minutes now; the detectors are bounded at 2. + +Report: [docs/reports/task-99-av1-conformance-flake](reports/task-99-av1-conformance-flake/index.html). diff --git a/docs/reports/README.md b/docs/reports/README.md index a6e1b363..012b36d3 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -69,6 +69,7 @@ to it. | 2026-11-22 | [Task #89: QTGMC InputType 2/3 at more than 8 bits](task-89-qtgmc-mask-high-bit-depth/index.html) | Fixed in the template: havsfunc's QTGMC runs MVTools' `mv.Mask` (ProgSADMask) on InputType 2/3 at Placebo–Medium, and Mask refuses any clip above 8 bits, so every 10–16-bit job (and every High Precision one) failed. `havsfunc_mask_any_depth` runs it on an 8-bit stand-in with `ml × 2^(bits−8)`: kind 1 never reads the clip's pixels, and MVTools takes the SAD shift from the clip but the scene-change thresholds from the vectors. 10-bit vs 8-bit output 0.16 levels (Slow/Medium), 0.07 (Placebo), below the Mask-off control (0.28 / 0.12); 8-bit unchanged (0 / 0); the factor sweep's minimum is ×4 at 10 bits and ×256 at 16. A correction is kept visible: the mask is exact only where SADs scale exactly (pel 1; pel 2's interpolation rounds per depth). macOS arm64 only, synthetic low bits | | 2026-11-22 | [Task #100: 4:4:0 sources decoded as 4:4:4](task-100-440-sources/index.html) | Fixed in the worker: the pipe-format classifier put 4:4:0 (some JPEG/MJPEG cameras) with 4:2:2, judging one axis, so the decoder halved its horizontal chroma (1-px colour columns: mean 70 levels off, the columns gone; testsrc2 1.78 / 21 against a one-step 4:4:4 rendering). It is piped as 4:4:4 now: 0 / 0, an encode bit-identical to ffmpeg's own 4:4:4 decode, and an odd-width 4:4:0 source runs. Output change: "Match source" makes 4:4:4 from such a source (was 4:2:2). A property test checks both axes for every code. Synthetic fixtures, macOS arm64 | | 2026-11-22 | [Task #103: Linux VapourSynth linked zimg master at build time](task-103-linux-zimg-pin/index.html) | Fixed in the deps (1.18.0-rc3 Linux assets replaced): R78's `subprojects/zimg.wrap` (`revision = HEAD`) is what Linux VapourSynth links, because its `meson setup` never receives `PKG_CONFIG_PATH`. zimg master's `e2e43d09` (graphengine update) made every resize abort ("double free or corruption", 617 of 6861 sweep rows). The wrap is pinned to 67e06032 and `libvapoursynth.so.4` is byte-identical to rc2's again. A correction is kept visible: pinning the script's own zimg clone first changed nothing (that library is unused). Graphengine cause not bisected (task #109); arm64 built but not tested | +| 2026-11-22 | [Task #99: AV1-into-MP4 conformance failures on the macOS x64 nightly](task-99-av1-conformance-flake/index.html) | Not reproduced; made diagnosable. Two of the four failures were tasks #58 and #68 (fixed); the other two (a 3-minute hang, 99 pictures for 100) did not recur in 960 case runs, 1,800 encoder replays and 9,600 decodes on the nightly's Intel runners (SVT-AV1 4.2.0 deterministic, decoders agree). Every matrix subprocess is now bounded, a hang sampled, a failing case's evidence printed and its output kept. Also: 8 macOS x64 legs had failed on the 30 s default timeout (`--detect-native`, task #41's AAC test); slow tests now state theirs. Hosted runners only | | 2026-11-22 | [Task #98: per-thread buffer maps in DFTTest, LGhost, CTMF, TCanny, EEDI3m](task-98-per-thread-buffer-maps/index.html) | Fixed in the deps (1.18.0-rc3): five plugins fill or check per-thread buffer maps with no lock and abort vspipe (`unordered_map::at`, 0xC0000409 on Windows); DFTTest's is the nightly knlmeanscl flake. Each is built from a pinned commit with our locking patch on every platform: 14-20 of 20 1000-instance graphs aborted (EEDI3m 0 of 10, not reproduced) unpatched, none patched; output identical on macOS arm64 and x64. M1 only; Windows DLLs built but run only in CI | | 2026-11-22 | [Task #97: sources stored off the chroma grid](task-97-off-grid-sources/index.html) | Fixed: a 4:2:0 source with an odd width or height (VP9, AV1, MJPEG, FFV1, ProRes 4:2:2 odd width…) failed every preview and encode (VapourSynth refuses the clip). `pipe_source` pads it onto the grid with the last column / row repeated, the encoder crops it back where it can store the size (FFV1, AV1, ProRes; bit-exact) and gives x264/x265/HuffYUV/v210/hardware encoders the next size up. FFmpeg's `pad` can't do it (floors odd widths); its RGB conversion of an odd-height 4:2:0 frame stretches the chroma (3.4 levels). macOS arm64 only | | 2026-11-21 | [Task #88: the script's YUV ↔ RGB on bt2020c, chroma-derived-* and ictcp](task-88-zimg-colour-tags/index.html) | Fixed what #76 filed: zimg refuses `2020cl`, `chromancl`, `chromacl` and `ictcp` from the matrix alone, so Borders (every job with bars), RIFE, AI upscaling, Face Restoration and Colourisation failed on such a source. The script now names the whole colour space, transfer and primaries on both sides: chroma-derived-nc exact (0 codes from H.273), ictcp PQ exact (≤ 1 from BT.2100), HLG zimg's display-referred form (5x closer than the stand-in); bt2020c, chroma-derived-c and SDR ictcp read as NCL, because zimg's CL turns grey 128 into Y′ 434 (BT.2020: 504) and refuses PQ/HLG. Round trips ≤ 1 code; other tags byte-identical. A correction (a re-randomised probe picture) is kept visible. macOS arm64 measured; the push-gate check runs everywhere | diff --git a/docs/reports/task-99-av1-conformance-flake/index.html b/docs/reports/task-99-av1-conformance-flake/index.html new file mode 100644 index 00000000..81e68766 --- /dev/null +++ b/docs/reports/task-99-av1-conformance-flake/index.html @@ -0,0 +1,114 @@ + + + + + +AV1 conformance flake + + + +

AV1-into-MP4 conformance failures on the macOS x64 nightly: not reproduced, now diagnosable

+

Task #99, 2026-11-22. Nightly logs of 2026-11-16 to 2026-11-21 read on every platform; the repro run on GitHub's macos-15-intel runners (Intel Core i7-8700B, 4 vCPUs) with both x64 CPU tiers and a macos-15 arm64 control, deps 1.18.0-rc3.

+ +

Outcome

+
    +
  • Two of the task's four failures were already fixed. The "white frames at [1.12]" failures of 11-16 and 11-17 were not AV1's: the same jobs failed 17 to 31 other near-start cases in every container with the same message, task #58's dropped-frame fault in pipe_source (fixed 11-18). The 11-18 vspipe SIGSEGVs were task #68's teardown race (fixed in deps 1.18.0-rc1).
  • +
  • Two remain unexplained, both mp4+av1/passthrough/delayed-avi on the x64-v2 tier: a case that ran past the test's 3 minutes (11-19, rc1) and one that counted 99 pictures for 100 (11-21, rc2). Every other heavy job since #58 and #68 passed all 451 cases: two failures in about 10 macOS x64 legs, none on arm64, Windows or Linux.
  • +
  • Not reproduced, layer by layer. On each x64 tier: the two cases 60 times each, every mp4+av1 case 15 times with every core but one busy, the encoder alone 900 times from the captured Y4M, and the test's own decodes of that output 4,800 times: no failure, no hang, one video hash. 2,760 encodes and 9,600 decodes on x64 in all, and as many on the arm64 control per leg.
  • +
  • The encoder is deterministic and the decoders agree. SVT-AV1 4.2.0 (the same library version in the x64 and arm64 FFmpeg 9.0.2) wrote 100 packets and the same bytes in all 900 replays per leg, from a file, throttled one frame per 10 ms as vspipe writes, and 4 at once under load. ffprobe's and ffmpeg's decodes counted 100 pictures with libdav1d 1.5.4 (FFmpeg's choice), single-threaded, and with libaom.
  • +
  • What changed: the next failure explains itself. Every subprocess of the matrix is bounded (60–150 s), a hang is sampled (sample on macOS, gdb on Linux) and its tree killed before the test's timeout, a failing case prints its job log tail (vspipe's "Output N frames"), the output's packet count beside two decoders' frame counts, the decoder used and the job, and the nightly uploads the output, job and log (conformance-failures-<bundle>). The worker now logs its encoder arguments, so a kept job can be replayed. No retry was added, and no case is in knownFailures: that list is for cases that fail every time.
  • +
  • Also fixed (Step D): eight macOS x64 heavy legs failed on package:test's 30 s default timeout, not on a fault: --detect-native on the reserved-colour-tags fixtures (23–30 s there) and task #41's AAC test (11–30 s). They and five more tests measured at 23–31 s on that runner now state a 5-minute timeout, and the detectors run bounded at 2 minutes.
  • +
+ +

The failures in the nightlies

+ + + + + + + +
Run (job)Date, commitBundleFailureCause
43909344002 (133446658134)11-16, dc9e36ce1.17.0-rc2, x64-v2mp4+av1/passthrough/reset-ps/near-start: white frames at [1.12]Task #58 finding 4; 17 other near-start cases in mp4, mov, mkv and avi failed the same way in that job
44127090331 (134193727710)11-17, 84df4d901.17.0-rc3, x64mp4+av1/restore/late-video/near-start: white frames at [1.12]The same; 19 other near-start cases (and 2 vspipe SIGSEGVs). Run 44089342398 failed 26 and 31
44342418084 (134935675943)11-18, 48bca80e1.17.0-rc3, x64mkv/restore-convert-aac/delayed-avi/untrimmed, avi/restore-convert-aac/late-video/mid: vspipe SIGSEGVTask #68 (vspipe R78 teardown race); not in the task's table
44515333102 (135529807721)11-19, c6448e161.18.0-rc1, x64-v2mp4+av1/passthrough/delayed-avi/near-start: TimeoutException after 3 min (other cases: 1.6–2 s)Not reproduced
44869849455 (136741691095)11-21, 426cccba1.18.0-rc2, x64-v2mp4+av1/passthrough/delayed-avi/untrimmed: 2. pictures, expected 100, actual 99Not reproduced
+

The task description's "every other container/codec row passes in the same jobs" holds only for the last two. What they rule out: pipe_source repeats its last frame past the end of its input and, since task #58, raises on a frame asked for after it was dropped, so vspipe writes the script's 100 frames or fails; a 99 is lost between vspipe's stdout and ffprobe -count_frames (the encoder, the MP4 muxer, or the test's decode). Check 2 failed before check 3 counted packets, so which one was not recorded. The hang's job had a 5-minute limit of its own and the test 3, so the test's TimeoutException fired first, named nothing and killed nothing.

+ +

Versions

+ + + + + +
macOS x64 (both tiers)macOS arm64
FFmpegmartin-riedl 9.0.2, build 1789931006martin-riedl 9.0.2, build 1789931890 (pinned since 11-22; the same binary every bundle up to rc2 shipped)
SVT-AV1v4.2.0, built 2026-09-20 (Apple LLVM 14.0.0)v4.2.0, built 2026-09-20
AV1 decoderslibdav1d 1.5.4 (FFmpeg's choice), libaom-av1, native av1 (hardware only: fails without a hwaccel)
+

The plan's guess that arm64 might carry a different SVT-AV1 was wrong: same version, same build date.

+ +

What was run

+

Run 44992968756 of repro-output-conformance.yml, one job per bundle, each phase in a fresh process. "Load" is yes > /dev/null on every core but one.

+ + + + + + + + +
PhaseWhatmacos-x64macos-x64-v2macos-arm64
B1…/delayed-avi/untrimmed and …/near-start, 60 times each, one flutter test process120 / 120 pass120 / 120120 / 120
B1 loadevery mp4+av1 case (24), 15 times each, under load360 / 360360 / 360360 / 360
B2 filethe untrimmed job's encoder, its captured Y4M from a file, 300 runs300 × 100 packets, 1 hash300 × 100, 1 hash300 × 100, 1 hash
B2 throttledthe same, one frame every 10 ms, 300 runs300 × 100, 1 hash300 × 100, 1 hash300 × 100, 1 hash
B2 loadthrottled, 4 at once, under load, 300 runs300 × 100, 1 hash300 × 100, 1 hash300 × 100, 1 hash
B3B2's output: ffprobe -count_frames and the luma decode of check 4, 300 each per variant (default, -threads 1, libdav1d, libaom), alone and 4 at once under load4,800 × 100, no hang4,800 × 1004,800 × 100
+

The x64 hash differs from arm64's (fb07a314… against d3cbb654…), as SIMD paths do; within an architecture it never varied. The encoder took 0.13–0.49 s a run from a file and 2.6–5.5 s throttled; nothing approached the 60 s hang limit.

+

Against the nightly: about 24 AV1 cases a leg and 2 failures in about 10 legs is roughly one in 120 case runs. At that rate B1 alone (960 x64 case runs) would have expected about 8. So what the nightly has and this did not is the cause or its trigger: other heavy test files running beside the matrix (the AI passes use several GB and every core for minutes; the format sweep runs on another leg) rather than CPU load alone. Not measured: memory pressure, and the 11-19/11-21 bundles (rc1, rc2), whose FFmpeg is byte-identical to rc3's on x64.

+ +

The nightly on this branch

+

Nightly run 44998535692 (2026-11-22, platform=macos, on the probe branch, which holds this branch's code without the docs commit):

+ + + + + + +
LegOutput conformanceStep D tests (reserved tags, video start offset, audio restoration, AVI copy trim, AVI audio seek, source grid, frame mapping)Other failures
macos-x64 heavy448 / 448all passFace Restoration's setUpAll: 12 min timeout installing its three add-ons
macos-x64-v2 heavy448 / 448all passColourisation's setUpAll: 12 min timeout installing DDColor + DeOldify (1.1 GB)
macos-arm64 heavypasspassnone
macos-x64 sweep––4 add-on variants: Failed host lookup: 'github.com' while downloading
+

Both cases of the 11-19/11-21 failures (mp4+av1/passthrough/delayed-avi/untrimmed and near-start) passed on both x64 tiers; no case printed evidence or kept an output. Every other failure in the run is an add-on download from github.com during a network fault the sweep leg's DNS error shows, not anything this branch changed (the arm64 legs and the x64-v2 sweep installed the same add-ons in time).

+ +

Step D: heavy tests cut off by the 30 s default

+

Every saved macOS x64 heavy leg from 11-16 to 11-21 (13 legs) read for TimeoutException after 0:00:30: 8 legs had one, always one of two tests. Durations below are the gap between a test's result line and the previous one in the same file (files run concurrently, tests in a file in order), so they include a little queueing; the maximum over the legs that ran it.

+ + + + + + + + + + +
TestMax on macOS x64Failed at 30 sNow
integration_reserved_colour_tags: --detect-native reports exactly what it reports on the twin30.5 s (passing legs 23.3–29.6; other platforms 6.6–23.5)8 legs5 min, each detect bounded at 2 min
integration_reserved_colour_tags: --detect-noise-halo …26.2 s05 min (every test in the file that runs anything)
integration_video_start_offset: mono AAC over 768 bytes (task #41), converted at High and Very High30.3 s2 legs5 min (and its copy test)
integration_audio_restoration: beside ProRes or v210, and in AVI, … 24-bit PCM30.7 s05 min
integration_avi_copy_trim: PCM trimmed into AVI from frame N28.7 s05 min
integration_frame_mapping: frame rate conversion retimes by the reduced ratio27.6 s05 min
integration_avi_audio_seek: the chirp copied to MKV from frame N25.4 s05 min
integration_source_grid: the app counts the frames the encode produces (both whole-source encodes)23.7 s05 min
+

Every other test above 20 s there already states a timeout. No change to dart_test.yaml's default: a longer default would hide real hangs everywhere. conformance_timeouts_test.dart (push gate) keeps the reserved-colour-tags file's timeouts and the matrix's job < case limits in place.

+ +

Limits

+
    +
  • Hosted runners only, one run per bundle; the nightly's own conditions were not reproduced beyond what its run on this branch shows.
  • +
  • The 99-picture case's file was not kept (the nightly did not keep outputs then), so whether it held 99 packets is unknown.
  • +
  • "Load" was CPU only. Memory pressure, disk contention and other processes' GPU use were not simulated.
  • +
+ +

Scripts

+ +

The test side: VAPOURBOX_CONFORMANCE_REPEAT=N registers each case N times in one process (each its own test and verdict); VAPOURBOX_CONFORMANCE_KEEP=<dir> keeps a failing case's output, job and log, and VAPOURBOX_CONFORMANCE_KEEP_ALL=1 passing ones too.

+ + diff --git a/docs/reports/task-99-av1-conformance-flake/scripts/capture-vspipe-stdout.sh b/docs/reports/task-99-av1-conformance-flake/scripts/capture-vspipe-stdout.sh new file mode 100644 index 00000000..7dec1272 --- /dev/null +++ b/docs/reports/task-99-av1-conformance-flake/scripts/capture-vspipe-stdout.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Keep what vspipe writes to the encoder (task #99, B2). +# +# capture-vspipe-stdout.sh install +# Moves the bundle's vspipe-bin to vspipe-bin.real and puts a script in +# its place (the worker runs vspipe-bin itself) that runs the real one +# and copies its stdout, the Y4M the encoder reads, to +# /run.*/out.y4m, with its script and exit status. +# capture-vspipe-stdout.sh uninstall +# +# The copy goes through `tee`, so the encoder still reads vspipe as it runs. +set -uo pipefail +cmd="$1"; VSDIR="$2" +case "$cmd" in +install) + CAP="$3"; mkdir -p "$CAP" + [ -f "$VSDIR/vspipe-bin.real" ] || mv "$VSDIR/vspipe-bin" "$VSDIR/vspipe-bin.real" + cat > "$VSDIR/vspipe-bin" < "\$d/rc" +exit "\$rc" +EOF + chmod +x "$VSDIR/vspipe-bin" + echo "capture script installed in $VSDIR" + ;; +uninstall) + [ -f "$VSDIR/vspipe-bin.real" ] && mv -f "$VSDIR/vspipe-bin.real" "$VSDIR/vspipe-bin" + ;; +esac diff --git a/docs/reports/task-99-av1-conformance-flake/scripts/measure_decode.py b/docs/reports/task-99-av1-conformance-flake/scripts/measure_decode.py new file mode 100644 index 00000000..2cefdf13 --- /dev/null +++ b/docs/reports/task-99-av1-conformance-flake/scripts/measure_decode.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Decode one output many times the way the conformance test does (task #99, B3). + + measure_decode.py --file --ffmpeg --ffprobe + --out [--runs 500] [--parallel 1] [--hang 60] + +Per variant, --runs times: `ffprobe -count_frames` (the test's check 2, +`countFrames`) and the luma decode of check 4 (`events`: rawvideo gray to +stdout, counted in pictures). Variants: FFmpeg's own choice of decoder, the +same with `-threads 1`, and each AV1 decoder this FFmpeg has forced with +`-c:v`. A run still going after --hang seconds is sampled and killed. + +Prints, per variant, how many runs counted each number of pictures and how +many hung. The question it answers: does the test's own decode of a good +file ever count one picture short, or block? +""" +import argparse +import collections +import os +import re +import subprocess +from concurrent.futures import ThreadPoolExecutor + + +def run(cmd, hang): + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + out, err = p.communicate(timeout=hang) + return p.returncode, out, err, "" + except subprocess.TimeoutExpired: + s = subprocess.run(["sample", str(p.pid), "2", "-mayDie"], capture_output=True, + text=True, timeout=30).stdout + p.kill() + out, err = p.communicate() + return -9, out, err, s[s.find("Call graph:"):][:20000] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--file", required=True) + ap.add_argument("--ffmpeg", required=True) + ap.add_argument("--ffprobe", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--runs", type=int, default=500) + ap.add_argument("--parallel", type=int, default=1) + ap.add_argument("--hang", type=float, default=60) + o = ap.parse_args() + os.makedirs(o.out, exist_ok=True) + f = o.file + wh = subprocess.run([o.ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", + "stream=width,height", "-of", "csv=p=0", f], + capture_output=True, text=True).stdout.strip().split(",") + size = int(wh[0]) * int(wh[1]) + decs = subprocess.run([o.ffmpeg, "-hide_banner", "-decoders"], capture_output=True, + text=True).stdout + av1 = [m.group(1) for m in re.finditer(r"^\s*V\S*\s+(\S*av1\S*)\s", decs, re.M)] + print(f"AV1 decoders in this ffmpeg: {av1}") + variants = [("default", []), ("threads1", ["-threads", "1"])] + variants += [(f"c:v {d}", ["-c:v", d]) for d in av1] + + def probe(extra): + rc, out, err, hung = run([o.ffprobe, "-v", "error", *extra, "-select_streams", "v:0", + "-count_frames", "-show_entries", "stream=nb_read_frames", + "-of", "csv=p=0", f], o.hang) + return ("probe", rc, out.decode().strip(), hung, err.decode()[-300:]) + + def luma(extra): + rc, out, err, hung = run([o.ffmpeg, "-v", "error", *extra, "-i", f, "-map", "0:v:0", + "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", + "gray", "-"], o.hang) + return ("luma", rc, str(len(out) // size), hung, err.decode()[-300:]) + + with open(os.path.join(o.out, "results.tsv"), "w") as tsv: + tsv.write("variant\tcheck\trc\tpictures\thung\n") + for name, extra in variants: + with ThreadPoolExecutor(o.parallel) as ex: + rows = list(ex.map(lambda _: probe(extra), range(o.runs))) + rows += list(ex.map(lambda _: luma(extra), range(o.runs))) + for kind in ("probe", "luma"): + rs = [r for r in rows if r[0] == kind] + c = collections.Counter(r[2] for r in rs) + hung = sum(1 for r in rs if r[3]) + fails = sum(1 for r in rs if r[1] != 0) + print(f"{name:14} {kind:5}: pictures {dict(c)}; nonzero exit {fails}; hung {hung}") + for r in rs: + tsv.write(f"{name}\t{kind}\t{r[1]}\t{r[2]}\t{bool(r[3])}\n") + for k, r in enumerate([r for r in rs if r[3] or r[1] != 0][:3]): + with open(os.path.join(o.out, f"bad_{name.replace(' ', '_').replace(':', '-')}_{kind}_{k}.txt"), + "w") as fh: + fh.write(f"rc {r[1]} pictures {r[2]}\n{r[4]}\n{r[3]}") + + +if __name__ == "__main__": + main() diff --git a/docs/reports/task-99-av1-conformance-flake/scripts/replay_encoder.py b/docs/reports/task-99-av1-conformance-flake/scripts/replay_encoder.py new file mode 100644 index 00000000..a83afe7f --- /dev/null +++ b/docs/reports/task-99-av1-conformance-flake/scripts/replay_encoder.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Replay one job's encoder ffmpeg many times from its captured Y4M (task #99, B2). + + replay_encoder.py --log --y4m --ffmpeg + --ffprobe --out [--runs 300] + [--parallel 1] [--mode file|throttled] [--hang 60] + + is the worker's stdout as the conformance test keeps it +(`VAPOURBOX_CONFORMANCE_KEEP`, log.txt): its `Encoder args: [...]` line is the +encoder command (worker/src/pipeline_executor.rs). is what vspipe wrote +for that job (capture-vspipe-stdout.sh). Each run feeds the Y4M to the same +command on stdin, either as fast as ffmpeg reads (`file`) or one frame at a +time with a short sleep, as vspipe does under load (`throttled`), and records: +exit status, wall time, the output's video packet count +(`ffprobe -count_packets`) and an MD5 of the video packets +(`-map 0:v -c copy -f md5`). A run still going after --hang seconds is +sampled (macOS `sample`) and killed. + +Writes /results.tsv and prints a summary: how many runs wrote each packet +count, how many distinct video hashes there were, and every non-zero exit or +hang. The question it answers: does the encoder alone ever write fewer +packets than frames in, or block? +""" +import argparse +import collections +import json +import os +import subprocess +import sys +import tempfile +import threading +import time +from concurrent.futures import ThreadPoolExecutor + + +def encoder_args(log_path): + for line in open(log_path, encoding="utf-8", errors="replace"): + line = line.strip() + msg = line + try: + msg = json.loads(line).get("message", "") + except ValueError: + pass + if msg.startswith("Encoder args: "): + return json.loads(msg[len("Encoder args: "):]) + sys.exit(f"no 'Encoder args:' line in {log_path}") + + +def y4m_frames(path): + """The Y4M stream split into its header and its frames (FRAME + payload).""" + data = open(path, "rb").read() + head_end = data.index(b"\n") + 1 + head = data[:head_end].decode() + w = h = None + cs = "420" + for tok in head.split()[1:]: + if tok[0] == "W": + w = int(tok[1:]) + elif tok[0] == "H": + h = int(tok[1:]) + elif tok[0] == "C": + cs = tok[1:] + depth = 2 if "p1" in cs else 1 + chroma = {"420": 0.5, "422": 1.0, "444": 2.0}.get(cs[:3], 0.5) + size = int(w * h * (1 + chroma) * depth) + frames = [] + i = head_end + while i < len(data): + nl = data.index(b"\n", i) + 1 + frames.append(data[i:nl + size]) + i = nl + size + return data[:head_end], frames + + +def prepare(args, tmp, run_dir): + """The command for one run: stdin for `-i -`, its own output and progress + file, and an empty FFMETADATA file where the job's has gone.""" + a = list(args) + out = os.path.join(run_dir, "out" + os.path.splitext(a[-1])[1]) + a[-1] = out + for k in range(len(a) - 1): + if a[k] == "-progress": + a[k + 1] = os.path.join(run_dir, "progress.txt") + if a[k] == "-i" and a[k + 1] != "-" and not os.path.exists(a[k + 1]): + if "vb_metadata_" in a[k + 1]: + meta = os.path.join(tmp, "metadata.txt") + with open(meta, "w") as f: + f.write(";FFMETADATA1\n") + a[k + 1] = meta + else: + sys.exit(f"input {a[k + 1]} is gone: replay a job whose inputs remain") + return a, out + + +def feed(proc, header, frames, mode): + try: + proc.stdin.write(header) + for f in frames: + proc.stdin.write(f) + if mode == "throttled": + proc.stdin.flush() + time.sleep(0.01) + proc.stdin.close() + except BrokenPipeError: + pass + + +def sample(pid): + try: + r = subprocess.run(["sample", str(pid), "2", "-mayDie"], capture_output=True, + text=True, timeout=30) + return r.stdout[r.stdout.find("Call graph:"):][:20000] + except Exception as e: # noqa: BLE001 + return f"(sample failed: {e})" + + +def one(i, a, ffmpeg, ffprobe, header, frames, mode, out_root, hang, tmp): + run_dir = os.path.join(out_root, f"run{i:04d}") + os.makedirs(run_dir, exist_ok=True) + cmd, out = prepare(a, tmp, run_dir) + env = dict(os.environ, SVT_LOG="2") + t0 = time.time() + proc = subprocess.Popen([ffmpeg] + cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, env=env) + errbuf = [] + te = threading.Thread(target=lambda: errbuf.append(proc.stderr.read())) + te.start() + tf = threading.Thread(target=feed, args=(proc, header, frames, mode)) + tf.start() + hung = "" + try: + rc = proc.wait(timeout=hang) + except subprocess.TimeoutExpired: + hung = sample(proc.pid) + proc.kill() + rc = proc.wait() + tf.join() + te.join() + wall = time.time() - t0 + packets, md5 = -1, "" + if os.path.exists(out): + p = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-count_packets", + "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", out], + capture_output=True, text=True, timeout=120) + packets = int(p.stdout.strip() or -1) + m = subprocess.run([ffmpeg, "-v", "error", "-i", out, "-map", "0:v", "-c", "copy", + "-f", "md5", "-"], capture_output=True, text=True, timeout=120) + md5 = m.stdout.strip().replace("MD5=", "") + if rc == 0 and not hung and packets == len(frames): + # Keep only what tells a bad run apart; a good run's output is noise. + for f in os.listdir(run_dir): + os.remove(os.path.join(run_dir, f)) + os.rmdir(run_dir) + else: + with open(os.path.join(run_dir, "stderr.txt"), "wb") as f: + f.write(b"".join(errbuf)) + if hung: + with open(os.path.join(run_dir, "sample.txt"), "w") as f: + f.write(hung) + return i, rc, round(wall, 3), packets, md5, bool(hung) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--y4m", required=True) + ap.add_argument("--ffmpeg", required=True) + ap.add_argument("--ffprobe", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--runs", type=int, default=300) + ap.add_argument("--parallel", type=int, default=1) + ap.add_argument("--mode", choices=["file", "throttled"], default="file") + ap.add_argument("--hang", type=float, default=60) + o = ap.parse_args() + os.makedirs(o.out, exist_ok=True) + args = encoder_args(o.log) + header, frames = y4m_frames(o.y4m) + tmp = tempfile.mkdtemp() + print(f"encoder: {' '.join(args)}") + print(f"input: {len(frames)} frames; {o.runs} runs, {o.parallel} at once, {o.mode}") + rows = [] + with ThreadPoolExecutor(o.parallel) as ex: + futs = [ex.submit(one, i, args, o.ffmpeg, o.ffprobe, header, frames, o.mode, o.out, + o.hang, tmp) for i in range(o.runs)] + for f in futs: + rows.append(f.result()) + with open(os.path.join(o.out, "results.tsv"), "w") as f: + f.write("run\trc\twall_s\tpackets\tmd5\thung\n") + for r in rows: + f.write("\t".join(map(str, r)) + "\n") + counts = collections.Counter(r[3] for r in rows) + hashes = collections.Counter(r[4] for r in rows if r[3] == len(frames)) + walls = sorted(r[2] for r in rows) + print(f"packets written: {dict(counts)} (frames in: {len(frames)})") + print(f"distinct video hashes among full outputs: {len(hashes)} {dict(hashes)}") + print(f"wall s: min {walls[0]} median {walls[len(walls) // 2]} max {walls[-1]}") + bad = [r for r in rows if r[1] != 0 or r[5] or r[3] != len(frames)] + print(f"bad runs: {len(bad)} of {len(rows)}") + for r in bad[:20]: + print(f" run {r[0]}: rc {r[1]} packets {r[3]} hung {r[5]} wall {r[2]}") + + +if __name__ == "__main__": + main() diff --git a/docs/reports/task-99-av1-conformance-flake/scripts/summarize_flutter_json.py b/docs/reports/task-99-av1-conformance-flake/scripts/summarize_flutter_json.py new file mode 100644 index 00000000..2d283482 --- /dev/null +++ b/docs/reports/task-99-av1-conformance-flake/scripts/summarize_flutter_json.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Count a `flutter test --file-reporter json:` run's results (task #99). + + summarize_flutter_json.py [