Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test: add shared recording reliability checks

Richie McIlroy9d68bb3a3be2
diff --git a/.github/workflows/sync-tests.yml b/.github/workflows/sync-tests.yml
index 658ce494c..9cf79ce2f 100644
--- a/.github/workflows/sync-tests.yml
+++ b/.github/workflows/sync-tests.yml
@@ -26,6 +26,9 @@ on:
- "crates/editor/**"
- "crates/audio/**"
- "crates/media-info/**"
+ - "crates/project/**"
+ - "scripts/recording-reliability.py"
+ - "scripts/test-recording-reliability.py"
- ".github/workflows/sync-tests.yml"
concurrency:
@@ -67,6 +70,11 @@ jobs:
with:
node-version: 24
+ - name: Setup Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.13"
+
- name: Native dependencies
env:
RUST_TARGET_TRIPLE: ${{ runner.os == 'Linux' && 'x86_64-unknown-linux-gnu' || runner.os == 'Windows' && 'x86_64-pc-windows-msvc' || 'aarch64-apple-darwin' }}
@@ -77,6 +85,12 @@ jobs:
shell: pwsh
run: Add-Content -Path $env:GITHUB_PATH -Value "${{ github.workspace }}\\target\\ffmpeg\\bin"
+ - name: Recording metadata and harness regression tests
+ shell: bash
+ run: |
+ cargo test --locked -p cap-project --lib
+ python -B scripts/test-recording-reliability.py
+
- name: Install software Vulkan driver (Linux)
if: runner.os == 'Linux'
run: |
diff --git a/scripts/recording-reliability.md b/scripts/recording-reliability.md
new file mode 100644
index 000000000..b31ad93be
--- /dev/null
+++ b/scripts/recording-reliability.md
@@ -0,0 +1,123 @@
+# Recording reliability: research, design and verification
+
+Research date: 2026-08-30. Source baseline: official `cap-v0.5.9`, `c6b83804d2e9fa8757b75268e573b8ff113141bb`. Audited candidate: `526dc80bf5429f7729b66d0291802b65cfeb48c7`, PR #2172. This document distinguishes design requirements from implemented behavior and measured results. It is not a release approval.
+
+## Decision
+
+Keep the existing fragmented capture formats, codec choices, native capture adapters and project schema. Do not replace Cap's recording engine or introduce a new container as a reliability fix. The smallest defensible changes protect metadata, reject incomplete uploads, preserve retry information and remove unnecessary work only after testing its safety invariant.
+
+Use one shared lifecycle contract across Tauri, GPUI and the CLI on macOS, Windows and Linux. Share state transitions, finalization rules, recovery rules, upload completion semantics and test assertions. Keep capture APIs, device handling, filesystem persistence and process supervision platform-specific.
+
+Local recording completion and cloud availability must be separate states. Network latency, an expired session or a server outage must not prevent a successfully captured recording from becoming a usable local recording. They must not trigger deletion of the last usable local copy.
+
+No software can guarantee that uncommitted samples survive power loss, that a failed drive retains data, or that an offline computer finishes uploading. The enforceable promise is: preserve every committed recoverable fragment; never silently discard a requested track; never report an incomplete save/upload as complete; retain enough durable state to retry; and make partial recovery or required user action visible.
+
+## What OBS demonstrates
+
+OBS writes recoverable media during capture. Its hybrid MP4/MOV approach retains fragmentation while recording, then adds a conventional index and adjusts headers at completion. This avoids a full remux of the media payload in that specific container design. It also documents compatibility and codec differences between containers. Cap already uses init segments plus fragmented media, so the relevant lesson is preserving recoverability during recording, not replacing Cap's working project format. [OBS format guide](https://obsproject.com/kb/audio-video-formats-guide), [hybrid format documentation](https://obsproject.com/kb/hybrid-mp4), [OBS technical explanation](https://obsproject.com/blog/obs-studio-hybrid-mp4).
+
+The source inspection is pinned to OBS 32.2.2, commit `ba2f32bdf791005443988a4955e963663e16b1ed`. Its MP4 finalizer flushes the final fragment, writes the complete index and adjusts headers. Its output layer distinguishes a stop timestamp from finalization and waits for the buffered writer to drain. The writer batches I/O, bounds its queue and propagates output errors. These are useful design patterns, not evidence that another application or every storage device is infallible. [MP4 finalizer](https://github.com/obsproject/obs-studio/blob/ba2f32bdf791005443988a4955e963663e16b1ed/plugins/obs-outputs/mp4-mux.c#L2955), [output lifecycle](https://github.com/obsproject/obs-studio/blob/ba2f32bdf791005443988a4955e963663e16b1ed/plugins/obs-outputs/mp4-output.c#L453), [buffered writer](https://github.com/obsproject/obs-studio/blob/ba2f32bdf791005443988a4955e963663e16b1ed/libobs/util/buffered-file-serializer.c).
+
+FFmpeg also documents that fragmented MP4 remains decodable after interrupted writing, unlike a conventional unfinished MP4. That depends on a usable initialization segment and complete fragments; it does not preserve bytes that never reached storage. Cap's existing fragments are therefore a sound foundation. Adopting OBS's hybrid muxer or FFmpeg's equivalent would require separate codec, timestamp, editor, export, upload and old-project compatibility work, and is not recommended for this repair. [FFmpeg MOV/MP4 fragmentation documentation](https://ffmpeg.org/ffmpeg-formats.html#mov_002c-mp4_002c-ismv).
+
+## Source audit findings
+
+| Risk | Current behavior at the audited candidate | Required change |
+| --- | --- | --- |
+| Canonical metadata can become empty or partial | `RecordingMeta::save_for_project` truncates and writes the existing JSON file. A write failure can make raw media undiscoverable to ordinary recovery. This also exists in 0.5.9. | Serialize first; write and sync a unique sibling temporary file; atomically replace the canonical file. Preserve the original on every pre-publication failure. Keep the schema unchanged. |
+| An incomplete Instant upload can be accepted | Tauri can complete a manifest after exhausting retries for some segments, provided some video uploaded. Its caller can then run upload-complete actions and local auto-deletion. | Withhold completion while any segment or upload task failed. Preserve the resumable upload identity and local media. Include failed audio/init segments, short reads and worker failures. |
+| GPUI can strand retry information | A transient failure can replace a resumable upload variant with `Failed`; GPUI has no equivalent comprehensive startup resume scan. | Keep retry identity and failure information independently; reconcile outstanding uploads on startup and network/auth recovery. Do not solve this by retrying forever inside Stop. |
+| Stop includes cloud work in GPUI | `ActiveRecording::stop` awaits segment completion, thumbnail upload or full-file upload, and cleanup. | Finish capture and local publication first. Run cloud work under a managed persistent queue; report uploading/retry state separately. |
+| Queue admission is treated as completed upload | `/api/upload/recording-complete` can acknowledge queued or already-processing work before final mux verification. | Distinguish accepted, processing and verified remote-ready. Only verified final readiness can permit local retention cleanup. |
+| Live upload completion lacks a complete capture-success contract | A received-event inventory cannot identify an event never emitted. Live Tauri completion can race recorder failure, and historical Instant metadata does not always retain requested audio intent. | Bind final publication to successful capture/local finalization and a persisted expected inventory. Do not infer missing historical audio intent from a nullable sample rate. |
+| Aborting an upload is not the same as joining its workers | External cancellation of a parent uploader can leave independently spawned children running. | Own cancellation and join child work before claiming quiescence or deleting media; a normal-path drain alone does not prove cancellation safety. |
+| Publication durability is incompletely specified | Recovery syncs files and journals, but its multi-file rename transaction does not consistently persist parent-directory changes. | Define ordered platform-specific durability operations and test interruption/reordering at each transition before claiming power-loss safety. |
+| Some Windows checkpoint flushes use read-only handles | Fragment helpers open files for reading before `sync_all`, sometimes only logging or discarding failure. Windows requires write access for `FlushFileBuffers`. | Use a supported writable handle at the writer boundary and propagate a failed required checkpoint. Native Windows verification is required. |
+| Successful encoder completion is not universal device quiescence | Some macOS/non-Windows source stop errors or timeouts are logged; a clean output token does not prove every device/preview writer has exited. | Preserve generation/ownership checks and explicit quiescence acknowledgement. Do not use the existing token to bypass all source protection. |
+| Normal Stop repeatedly reads/copies the entire recording | Studio performs four full input snapshots, a private copy, remux/validation and publication; Instant also copies and scans. | First remove only provably redundant work. A later read-only-source finalizer must leave original fragments unchanged until commit. |
+
+Relevant source seams: `crates/project/src/meta.rs`; `crates/recording/src/recovery.rs`; `crates/recording/src/fragmentation/mod.rs`; `crates/enc-ffmpeg/src/mux/{fragment_manifest,segmented_stream,dash_audio,segmented_audio}.rs`; `apps/desktop/src-tauri/src/{recording,upload}.rs`; `apps/desktop-gpui/src/{recording,upload,session}.rs`; `apps/web/app/api/upload/[...route]/recording-complete.ts`.
+
+## Shared safety contract
+
+### Capture and local save
+
+1. Allocate a unique recording generation and persist its requested tracks and recovery identity before treating capture as started. A camera/microphone requested by the user is not an optional success condition merely because its device later fails.
+2. Keep initialization data and completed fragments discoverable. Publish a fragment as complete only after the encoder/muxer closes it and the required storage checkpoint succeeds. Keep the currently incomplete fragment distinguishable from committed fragments.
+3. Use bounded queues. Track dropped frames, audio discontinuities, device loss and encoder failures explicitly. Silent audio is not proof that the requested audio path worked.
+4. On Stop, stop accepting capture samples at a defined boundary, drain owned encoder work, close writers and acknowledge quiescence. Keep capture stopped, local saving and uploading distinguishable in the UI.
+5. Read sealed source fragments without modifying them when producing a final output. Write output and new metadata separately on the same filesystem. Validate expected track inventory, time ranges, packet structure and output decodability at appropriate boundaries.
+6. Install a new generation through a recoverable transaction. Commit metadata only when its referenced outputs exist. Preserve the previous generation and recovery evidence until installation is confirmed.
+7. Treat post-commit cleanup failure as retained cleanup work, not a failed recording. Never turn a usable saved video into an error because a disposable temporary directory could not be removed.
+8. On recovery, retain originals and identify any loss explicitly. A recovered video missing requested audio may be offered as a partial recovered copy; it must not be silently labelled a complete original recording.
+
+The proposed source/output separation is not yet a drop-in optimization. The current `finalize_staged` deletes and renames its working inputs. Passing original fragments to it would remove the isolation that currently prevents destructive failures. Similarly, hard links are not independent backups when either name can still be written. A clone optimization needs a real filesystem capability check and safe fallback; ReFS block cloning is not a portable NTFS solution.
+
+### Upload and retention
+
+Use persistent per-recording upload state: video identity, local artifact generation, expected tracks/segments, completed parts, retry state and final acknowledgement. Keep this separate from local recording completeness. The same recording must not acquire duplicate remote identities because a successful response was lost.
+
+Every expected segment must either be acknowledged or remain pending. An empty, truncated or unreadable segment is a failure; a worker panic is a failure; a successful subset is not the entire recording. Refresh expired signed URLs and auth when appropriate, retry transient failures with bounded backoff, and retain an actionable paused state for permanent failures.
+
+Multipart completion must be reconciled, not guessed from a status code. S3 documents that a complete-multipart response can contain an error despite an HTTP 200 status; official SDKs handle that condition. ETags are not universally full-object checksums. Where supported, provide and verify the correct checksum/size contract rather than assuming every S3-compatible provider has identical features. [S3 multipart completion](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html), [S3 upload integrity](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity-upload.html).
+
+The server must distinguish manifest acceptance from a verified final object. A durable final-ready receipt should bind the video ID, generation, object identity, byte length and expected media properties. Repeating completion after an ambiguous response must reconcile the same job/object. A server-side mux failure must leave local data and the upload ledger available for retry. The existing `already-complete` response checks the `desktopMP4` source marker; it does not independently verify object size, checksum or track inventory. Polling that response alone is not the proposed deletion certificate.
+
+Auto-deletion is a separate retention operation after remote-ready confirmation. It must be cancellable, resumable, scoped to the exact completed generation, and prevented while a local editor/export/recovery still needs the data. If verification times out, retain the local copy and show why. Avoid keeping unlimited invisible backups: provide explicit retention/accounting and warn about storage pressure without silently sacrificing the last copy.
+
+S3 provides strong read-after-write consistency for objects and HEAD metadata, but that does not make Cap's database, queue, mux worker, CDN and local state one transaction. Each boundary needs idempotent reconciliation. [S3 consistency model](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html#ConsistencyModel).
+
+### Persistence is an OS adapter, not a shared assumption
+
+On Linux, file `fsync` does not by itself persist its directory entry; relevant directories must also be synced. On macOS, storage barriers and full synchronization have different costs and guarantees. On Windows, writable handles, sharing modes, replacement behavior and flush semantics must be handled explicitly. Do not label a sequence of file renames a single atomic transaction or equate process-kill tests with power-loss tests. [Linux fsync](https://man7.org/linux/man-pages/man2/fsync.2.html), [Apple fsync](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html), [Apple storage guidance](https://developer.apple.com/videos/play/wwdc2019/419/), [Windows FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers), [Windows MoveFileExW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw).
+
+SQLite's crash-testing approach is a useful model for a persistence harness: inject failures at storage transitions and validate the recovered state. It is not a reason to migrate Cap's project format to a database in this repair. Keep application-error tests, process termination tests and simulated storage write-loss/reordering tests as separate evidence classes. [SQLite atomic commit and crash testing](https://www.sqlite.org/atomiccommit.html), [SQLite testing](https://www.sqlite.org/testing.html).
+
+## Performance without weakening preservation
+
+The measured candidate is not yet at 0.5.9 parity. A Linux 120-second Studio pair took 537.342 ms versus 362.396 ms from Stop to process exit. Windows 12-second Instant pairs took 446.028 versus 405.319 ms and 473.999 versus 376.941 ms from capture-thread completion to process exit. These are different boundaries and limited samples, not universal latency distributions. The Linux project occupied about 141 MB versus 70 MB because original media was retained.
+
+The original PR introduced the private copy and repeated full snapshots. Current repairs reduced decoding and temporary-write overhead, but retained the complete-media copy. A slow disk or long recording magnifies that work. Do not remove preservation merely to match a stopwatch.
+
+Apply optimizations in increasing order of risk:
+
+1. Avoid probing fragments whose probe result is discarded because they are already represented by a validated manifest. Keep fallback behavior for incomplete/unreadable manifests.
+2. Test whether the immediate post-copy original snapshot is redundant with the initial source, independently read staged copy and final source snapshot. Exercise mutations at each boundary before removing a scan.
+3. Measure copy-on-write cloning where available, with fallback that preserves isolation; do not assume all supported filesystems support it or that deferred allocation cannot fail later.
+4. If needed, introduce a narrowly eligible finalizer with separate source/output roots, preserving the existing publication transaction and conservative recovery fallback. Prove ownership/sealing rather than trusting a status enum or size/mtime alone.
+5. Move cloud work off Stop only together with persistent retry and visible cloud state. Background work without restart reconciliation is not a reliability improvement.
+
+Track Stop request → capture acknowledgement → local output ready → editor interactive separately from upload accepted → final object ready. Measure bytes read/written and peak disk demand as well as elapsed time. A debug build, workload mismatch or skipped audio assertion cannot establish release parity.
+
+## Consistent real-recording harness
+
+The adjacent `recording-reliability.py` is the portable entry point for clean local recording checks. It requires explicit binaries, an explicit screen/window target and a fresh output root. It records executable hashes and keeps recordings and failure logs. It must not sign applications, discover or delete the user's production library, start development servers, reset devices, change permissions or upload real user recordings.
+
+Run the same assertion schema on all three OSes. A VM proves its guest capture and filesystem paths, not every physical microphone/camera/GPU. Missing devices, silent stimuli, unavailable editor controls or inaccessible cloud environments are `PENDING`, not `PASS`. Requested audio must be present and demonstrably non-silent; A/V synchronization needs an independently measurable flash/tone or equivalent stimulus, not just container timestamps.
+
+| Scenario family | Required evidence |
+| --- | --- |
+| Clean Instant and Studio | Start/stop events, complete local metadata, expected tracks, duration/cadence, full decode, project validation |
+| Pause/resume and repeated Stop | Ordered transitions, no double completion/deletion, no unexpected gaps, stable media identity |
+| Camera/mic/system audio combinations | Exact requested track inventory, visible camera content, audible stimulus, independent A/V onset and drift |
+| App or muxer crash during recording | Complete fragments retained; fresh-process recovery; decoded recovered duration accounts for the last committed fragment |
+| Crash during local publication | Inject at each rename/checkpoint; old or new generation remains recoverable, with no false Complete |
+| Low space/write failure | Scoped ENOSPC/EIO injection or disposable bounded filesystem; no filling the user's disk; originals retained |
+| Sleep, device loss and permission loss | Visible degradation/failure, controlled stop, recoverable data, no frozen success state |
+| Offline/timeout/expired credentials | Local save unaffected; upload remains retryable across restart; no local auto-deletion |
+| Failed or truncated segment | No final manifest acknowledgement or completion action until the entire required inventory is verified |
+| Lost multipart-complete response | Same remote object/job reconciled; no duplicate video or abandoned local state |
+| Server mux failure | No remote-ready claim; local media retained; retry produces a verified playable final object |
+| Upload and application restart | Durable queue reconstructs work and resumes without re-recording |
+| Studio editor and export | Editor reveals/focuses; seeks/playback work; exported output fully decodes with requested media |
+| Old 0.5.9 projects | Original bytes unchanged; valid legacy omissions remain supported; editing/export match baseline |
+| Long/load/thermal runs | Stable memory and storage growth, measured drops, bounded Stop latency, no recording-length-dependent redundant work |
+| Cleanup and retention | Only the owned completed generation is removed after remote verification; cleanup failure does not negate save success |
+
+Record exact source/build identity, OS/filesystem, requested inputs, fixture identity, timing boundaries, all assertions, skipped reasons and cleanup ownership. Compare candidate and 0.5.9 in alternating orders with the same workload; use enough repetitions to expose variance. Do not impose an arbitrary threshold after seeing a result. Physical power failure, physical device disconnect and prolonged workloads need their own explicit runs.
+
+## Implementation and release gates
+
+First changes are deliberately bounded: atomic recording metadata replacement, fail-closed Tauri segment completion, and a common local recording oracle. They do not implement the entire lifecycle described above. In particular, background GPUI upload/restart reconciliation, final-object-based deletion, filesystem durability ordering and strict performance parity remain separate work until verified.
+
+Before release: all required native scenarios must pass on the final source/build; every false-success/data-loss finding must be fixed; 0.5.9 projects and supported recording combinations must remain compatible; performance comparisons must meet the agreed parity requirement; and a fresh independent/Greptile review must cover the final changes. A review score or green CI job cannot replace missing native or cloud evidence.
diff --git a/scripts/recording-reliability.py b/scripts/recording-reliability.py
new file mode 100644
index 000000000..6060d2a50
--- /dev/null
+++ b/scripts/recording-reliability.py
@@ -0,0 +1,471 @@
+#!/usr/bin/env python3
+import argparse
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import platform
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import time
+
+
+STATUSES = {"PASS", "FAIL", "PENDING"}
+RESERVE_BYTES = 2 * 1024**3
+MAX_LOG_BYTES = 16 * 1024**2
+UNTESTED = {
+ "crash_recovery": "No owned process kill or fresh-process recovery was exercised.",
+ "publication_faults": "No remux, write, rename or storage failure was injected.",
+ "upload_restart": "No upload, restart, retry or remote playback was exercised.",
+ "gui_editor": "CLI recording does not prove visible Start/Stop or editor auto-open.",
+ "av_sync": "No independently measured visual/audio onset or drift stimulus.",
+ "visual_content": "Frame counts do not prove moving, nonblack screen/camera content.",
+ "stop_latency": "Foreground --duration does not expose the Stop request boundary.",
+ "performance_parity": "Command lifetime is descriptive, not a Stop latency parity gate.",
+ "export": "This initial clean-capture runner does not exercise export.",
+}
+
+
+def sha256(path):
+ digest = hashlib.sha256()
+ with Path(path).open("rb") as source:
+ for block in iter(lambda: source.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def write_json(path, value):
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ with temporary.open("x", encoding="utf-8") as output:
+ json.dump(value, output, indent=2, allow_nan=False)
+ output.write("\n")
+ output.flush()
+ os.fsync(output.fileno())
+ temporary.replace(path)
+
+
+def requirement(status, reason, **evidence):
+ if status not in STATUSES:
+ raise ValueError("Unknown requirement status")
+ return {"status": status, "reason": reason, **evidence}
+
+
+def aggregate(rows):
+ values = [row["status"] for row in rows]
+ if not values or any(value not in STATUSES for value in values):
+ return "FAIL"
+ if "FAIL" in values:
+ return "FAIL"
+ return "PENDING" if "PENDING" in values else "PASS"
+
+
+def strict_json(text):
+ def invalid_constant(value):
+ raise ValueError(f"Invalid JSON numeric constant: {value}")
+
+ def unique_pairs(pairs):
+ result = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError(f"Duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+ return json.loads(text, parse_constant=invalid_constant, object_pairs_hook=unique_pairs)
+
+
+def capture_events(text, project):
+ events = [strict_json(line) for line in text.splitlines() if line.strip()]
+ if not all(isinstance(event, dict) for event in events):
+ raise ValueError("Recording JSONL contains a non-object")
+ if any(event.get("type") == "error" or event.get("error") for event in events):
+ raise ValueError("Recording emitted an error event")
+ if [event.get("type") for event in events] != ["started", "stopped"]:
+ raise ValueError("Expected exactly one started event followed by one stopped event")
+ for event in events:
+ if Path(event.get("path", "")).resolve() != project:
+ raise ValueError("Recording event references a different project")
+ if not events[0].get("recordingId") or not isinstance(events[0].get("pid"), int):
+ raise ValueError("Started event has no recording identity")
+ if events[1].get("recordingMetaExists") is not True:
+ raise ValueError("Stopped event does not confirm saved metadata")
+ return events
+
+
+def finite_number(value):
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as error:
+ raise ValueError("Missing or invalid media measurement") from error
+ if not math.isfinite(number):
+ raise ValueError("Non-finite media measurement")
+ return number
+
+
+def media_metrics(probe, expected_duration, fps, kind):
+ streams = probe.get("streams", [])
+ matching = [stream for stream in streams if stream.get("codec_type") == kind]
+ if not matching:
+ raise ValueError(f"Missing {kind} stream")
+ measurements = []
+ for stream in matching:
+ duration = finite_number(stream.get("duration", probe.get("format", {}).get("duration")))
+ frames = int(stream.get("nb_read_frames", "0"))
+ tolerance = max(1.0, expected_duration * 0.1)
+ if not expected_duration - tolerance <= duration <= expected_duration + 2:
+ raise ValueError(f"{kind} duration {duration} does not match {expected_duration}s")
+ if frames < 2:
+ raise ValueError(f"{kind} stream has fewer than two decoded frames")
+ if kind == "video":
+ if int(stream.get("width", 0)) <= 0 or int(stream.get("height", 0)) <= 0:
+ raise ValueError("Video has invalid dimensions")
+ if frames / duration < fps * 0.8:
+ raise ValueError("Video decoded cadence is below 80% of requested fps")
+ measurements.append({"stream": stream, "durationSeconds": duration, "decodedFrames": frames})
+ return measurements
+
+
+def audio_levels(stderr):
+ levels = re.findall(r"RMS level dB:\s*(-?inf|[-+0-9.eE]+)", stderr)
+ if not levels:
+ raise ValueError("Audio analysis produced no RMS measurement")
+ audible = [float(level) for level in levels if level not in {"inf", "-inf"}]
+ if not audible or not all(math.isfinite(level) for level in audible) or max(audible) <= -60:
+ raise ValueError("Requested audio is silent or below the -60 dBFS RMS floor")
+ return {"maximumRmsDbfs": max(audible), "floorDbfs": -60}
+
+
+def contained_file(path, project):
+ supplied = Path(path)
+ if not supplied.is_absolute():
+ supplied = project / supplied
+ resolved = supplied.resolve(strict=True)
+ if not resolved.is_relative_to(project) or not resolved.is_file() or resolved.stat().st_size == 0:
+ raise ValueError("Media must be a nonempty file inside the owned project")
+ for part in [supplied, *supplied.parents]:
+ if part == project.parent:
+ break
+ if part.is_symlink():
+ raise ValueError("Project media may not traverse symbolic links")
+ return resolved
+
+
+def project_media(report, project, mode, camera, mic, system_audio):
+ if report.get("valid") is not True or report.get("error") or report.get("problems") or report.get("missing"):
+ raise ValueError("CLI project validation is not clean")
+ if report.get("recordingType") != mode or Path(report.get("projectPath", "")).resolve() != project:
+ raise ValueError("Project validation identity differs from the requested recording")
+ checks = report.get("checks")
+ if not isinstance(checks, list):
+ raise ValueError("Project validation has no checks")
+ roles = {"output": "video"} if mode == "instant" else {"displayVideo": "video"}
+ if mode == "studio":
+ roles.update({role: kind for role, kind, wanted in [
+ ("camera", "video", camera), ("mic", "audio", mic), ("systemAudio", "audio", system_audio)
+ ] if wanted})
+ files = []
+ for role, kind in roles.items():
+ selected = [check for check in checks if check.get("role") == role and check.get("required") is True and check.get("exists") is True]
+ if len(selected) != 1:
+ raise ValueError(f"Expected exactly one required {role} track, found {len(selected)}")
+ files.append({"role": role, "kind": kind, "path": str(contained_file(selected[0]["path"], project))})
+ return files
+
+
+WINDOWS_ADAPTER = r'''
+param([string]$Request)
+$ErrorActionPreference = "Stop"
+$q = [IO.File]::ReadAllText($Request) | ConvertFrom-Json
+$owned = $null
+$r = [ordered]@{exitCode=$null;timedOut=$false;forcedCleanup=$false;cleanupComplete=$false;error=$null}
+try {
+ Add-Type -Path $q.source
+ $owned = [CapOwnedProcess]::Start($q.binary,$q.arguments,$q.directory,$q.stdout,$q.stderr)
+ $r.pid = $owned.Id
+ $clock = [Diagnostics.Stopwatch]::StartNew()
+ while (-not $owned.WaitForExit(100)) {
+ if ($clock.Elapsed.TotalSeconds -ge $q.timeout) { $r.timedOut=$true; break }
+ $drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($q.directory))
+ if ($drive.AvailableFreeSpace -lt $q.reserve) { throw "Storage reserve reached" }
+ foreach ($path in @($q.stdout,$q.stderr)) {
+ if ((Get-Item -LiteralPath $path).Length -gt $q.logLimit) { throw "Log limit reached" }
+ }
+ }
+ $r.cleanupComplete = $owned.WaitForEmpty(2000)
+ if (-not $r.cleanupComplete) {
+ $r.forcedCleanup = $true
+ $owned.TerminateOwnedTree()
+ $r.cleanupComplete = $owned.WaitForEmpty(5000)
+ }
+ if ($owned.WaitForExit(1000)) { $r.exitCode = $owned.ExitCode }
+ $r.activeAfterCleanup = $owned.ActiveProcesses
+} catch { $r.error = [string]$_ } finally {
+ if ($owned) {
+ try { if ($owned.ActiveProcesses -ne 0) { $r.forcedCleanup=$true; $owned.TerminateOwnedTree(); $r.cleanupComplete=$owned.WaitForEmpty(5000) } }
+ catch { $r.error = [string]$_; $r.cleanupComplete=$false }
+ finally { $owned.Dispose() }
+ }
+ [IO.File]::WriteAllText($q.result,($r | ConvertTo-Json -Depth 5))
+}
+if ($r.error -or $r.timedOut -or $r.forcedCleanup -or -not $r.cleanupComplete -or $r.exitCode -ne 0) { exit 1 }
+'''
+
+
+class Runner:
+ def __init__(self, root, deadline, binaries, windows_source=None):
+ self.root = root
+ self.deadline = deadline
+ self.binaries = binaries
+ self.windows_source = windows_source
+ self.commands = []
+
+ def run(self, name, arguments, timeout=90):
+ if time.monotonic() >= self.deadline:
+ raise RuntimeError("Run deadline reached; no further commands launched")
+ if sha256(arguments[0]) != self.binaries[str(arguments[0])]:
+ raise RuntimeError("An explicitly pinned executable changed")
+ stdout, stderr = self.root / f"{name}.stdout", self.root / f"{name}.stderr"
+ timeout = min(timeout, self.deadline - time.monotonic())
+ start = time.monotonic_ns()
+ env = dict(os.environ, CAP_NO_MODIFY_PATH="1")
+ result = {"name": name, "arguments": list(map(str, arguments)), "stdout": str(stdout), "stderr": str(stderr)}
+ if os.name == "nt":
+ result.update(self.run_windows(name, arguments, stdout, stderr, timeout, env))
+ else:
+ with stdout.open("xb") as out, stderr.open("xb") as err:
+ process = subprocess.Popen(arguments, cwd=self.root, env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=err, start_new_session=True)
+ result.update(pid=process.pid, timedOut=False, forcedCleanup=False, cleanupComplete=False)
+ try:
+ while process.poll() is None:
+ if (time.monotonic_ns() - start) / 1e9 >= timeout:
+ result["timedOut"] = True
+ break
+ if shutil.disk_usage(self.root).free < RESERVE_BYTES:
+ result["error"] = "Storage reserve reached"
+ break
+ if any(path.stat().st_size > MAX_LOG_BYTES for path in [stdout, stderr]):
+ result["error"] = "Command log limit reached"
+ break
+ time.sleep(0.05)
+ finally:
+ try:
+ os.killpg(process.pid, 0)
+ except ProcessLookupError:
+ result["cleanupComplete"] = True
+ else:
+ result["forcedCleanup"] = True
+ os.killpg(process.pid, signal.SIGKILL)
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ result["cleanupComplete"] = False
+ else:
+ try:
+ os.killpg(process.pid, 0)
+ except ProcessLookupError:
+ result["cleanupComplete"] = True
+ result["exitCode"] = process.returncode
+ result["commandLifetimeSeconds"] = (time.monotonic_ns() - start) / 1e9
+ result["timingBoundary"] = "Command launch through observed exit and owned cleanup; not Stop latency"
+ result["passed"] = result.get("exitCode") == 0 and result.get("cleanupComplete") is True and not result.get("timedOut") and not result.get("forcedCleanup") and not result.get("error")
+ if any(path.exists() and path.stat().st_size > MAX_LOG_BYTES for path in [stdout, stderr]):
+ result.update(passed=False, error="Command log exceeded the bounded parser limit")
+ self.commands.append(result)
+ write_json(self.root / f"{name}.command.json", result)
+ if not result["passed"]:
+ raise RuntimeError(f"Command failed or cleanup was incomplete: {name}")
+ return stdout.read_text(encoding="utf-8", errors="strict"), stderr.read_text(encoding="utf-8", errors="replace")
+
+ def run_windows(self, name, arguments, stdout, stderr, timeout, env):
+ if not self.windows_source:
+ raise RuntimeError("Windows requires --windows-job-source with the reviewed CapOwnedProcess launcher")
+ if sha256(self.windows_source) != self.binaries[str(self.windows_source)]:
+ raise RuntimeError("Windows process supervisor source changed")
+ adapter = self.root / f"{name}.ps1"
+ adapter.write_text(WINDOWS_ADAPTER, encoding="utf-8")
+ request, receipt = self.root / f"{name}.request.json", self.root / f"{name}.job.json"
+ write_json(request, {"source": str(self.windows_source), "binary": str(arguments[0]), "arguments": subprocess.list2cmdline(list(map(str, arguments[1:]))), "directory": str(self.root), "stdout": str(stdout), "stderr": str(stderr), "timeout": timeout, "result": str(receipt), "reserve": RESERVE_BYTES, "logLimit": MAX_LOG_BYTES})
+ powershell = Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
+ with (self.root / f"{name}.supervisor.log").open("xb") as log:
+ process = subprocess.Popen([str(powershell), "-NoProfile", "-NonInteractive", "-File", str(adapter), str(request)], env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=log)
+ try:
+ process.wait(timeout=timeout + 30)
+ except BaseException:
+ process.kill()
+ process.wait(timeout=5)
+ raise
+ if not receipt.is_file():
+ raise RuntimeError("Windows supervisor produced no cleanup receipt")
+ return strict_json(receipt.read_text(encoding="utf-8-sig"))
+
+
+def checked_json(stdout, stderr):
+ if re.search(r"\bERROR\b|^error:", stderr, re.MULTILINE):
+ raise ValueError("CLI emitted an error log")
+ value = strict_json(stdout)
+ if not isinstance(value, dict):
+ raise ValueError("Expected a JSON object")
+ return value
+
+
+def check_media(runner, args, prefix, media):
+ path = Path(media["path"])
+ before = sha256(path)
+ stdout, stderr = runner.run(prefix + "-probe", [str(args.ffprobe), "-v", "error", "-count_frames", "-show_streams", "-show_format", "-of", "json", str(path)])
+ if stderr.strip():
+ raise ValueError("FFprobe emitted an error while counting decoded frames")
+ probe = strict_json(stdout)
+ metrics = media_metrics(probe, args.duration, args.fps, media["kind"])
+ _, errors = runner.run(prefix + "-decode", [str(args.ffmpeg), "-v", "error", "-nostdin", "-xerror", "-err_detect", "explode+crccheck", "-i", str(path), "-map", "0:v?", "-map", "0:a?", "-f", "null", "-"], 120)
+ if errors.strip():
+ raise ValueError("Full decode emitted errors")
+ audio = [stream for stream in probe["streams"] if stream.get("codec_type") == "audio"]
+ needs_audio = media["kind"] == "audio" or (media["role"] == "output" and (args.mic or args.system_audio))
+ levels = []
+ if needs_audio:
+ media_metrics(probe, args.duration, args.fps, "audio")
+ for index in range(len(audio)):
+ _, analysis = runner.run(prefix + f"-audio-{index}", [str(args.ffmpeg), "-hide_banner", "-v", "info", "-nostdin", "-xerror", "-i", str(path), "-map", f"0:a:{index}", "-af", "astats=metadata=0:reset=0", "-f", "null", "-"], 120)
+ levels.append(audio_levels(analysis))
+ after = sha256(path)
+ if before != after:
+ raise ValueError("Read-only media verification changed the artifact")
+ return {**media, "bytes": path.stat().st_size, "sha256Before": before, "sha256After": after, "measurements": metrics, "audio": levels}
+
+
+def run_case(runner, args, label, binary, head, mode):
+ project = runner.root / f"{label}-{mode}.cap"
+ row = {"label": label, "head": head, "mode": mode, "project": str(project), "requirements": {key: requirement("PENDING", reason) for key, reason in UNTESTED.items()}}
+ for key in ["clean_local", "decodability", "requested_tracks"]:
+ row["requirements"][key] = requirement("PENDING", "Not executed")
+ try:
+ if shutil.disk_usage(runner.root).free < RESERVE_BYTES + max(512 * 1024**2, int(args.duration * 8 * 1024**2)):
+ raise RuntimeError("Insufficient free space above the 2 GiB reserve and capture allowance")
+ health = checked_json(*runner.run(label + "-" + mode + "-doctor", [str(binary), "doctor", "--json"], 30))
+ if health.get("captureReady") is not True or health.get("automations", {}).get("enabledCount") != 0:
+ raise RuntimeError("Capture readiness or absence of recording-finished automations is unproved")
+ command = [str(binary), "record", "start", "--mode", mode, "--path", str(project), "--duration", str(args.duration), "--fps", str(args.fps), "--json"]
+ command.extend(["--window", args.window] if args.window else ["--screen", args.screen])
+ for flag, value in [("--mic", args.mic), ("--camera", args.camera)]:
+ if value:
+ command.extend([flag, value])
+ if args.system_audio:
+ command.append("--system-audio")
+ stdout, stderr = runner.run(label + "-" + mode + "-capture", command, args.duration + 90)
+ if re.search(r"\bERROR\b|^error:", stderr, re.MULTILINE):
+ raise ValueError("Recording emitted an error log")
+ row["events"] = capture_events(stdout, project)
+ report = checked_json(*runner.run(label + "-" + mode + "-validate", [str(binary), "project", "validate", str(project), "--json"], 30))
+ files = project_media(report, project, mode, args.camera, args.mic, args.system_audio)
+ row["requirements"]["clean_local"] = requirement("PASS", "Started/stopped events and project validation confirmed local completion")
+ row["media"] = [check_media(runner, args, f"{label}-{mode}-{index}", media) for index, media in enumerate(files)]
+ row["requirements"]["decodability"] = requirement("PASS", "Full decode, duration, decoded frame count and file identity checks passed")
+ if mode == "instant" and (args.camera or (args.mic and args.system_audio)):
+ row["requirements"]["requested_tracks"] = requirement("PENDING", "Composited camera or mixed audio requires an independent per-source stimulus oracle; encoded audio was still checked for non-silence")
+ else:
+ row["requirements"]["requested_tracks"] = requirement("PASS", "Requested separate tracks exist; requested audio passed non-silence checks")
+ except (OSError, ValueError, RuntimeError, TypeError, KeyError, subprocess.SubprocessError) as error:
+ row["error"] = str(error)
+ for key in ["clean_local", "decodability", "requested_tracks"]:
+ if row["requirements"][key]["status"] == "PENDING":
+ row["requirements"][key] = requirement("FAIL", str(error))
+ row["status"] = aggregate(row["requirements"].values())
+ write_json(runner.root / f"{label}-{mode}.json", row)
+ return row
+
+
+def arguments(argv=None):
+ parser = argparse.ArgumentParser(description="Retained real-CLI recording evidence. Exit 0=all requirements PASS, 1=FAIL, 2=required coverage PENDING. No signing, upload, servers or library cleanup.")
+ for flag in ["cap", "ffmpeg", "ffprobe", "root"]:
+ parser.add_argument("--" + flag, required=True, type=Path)
+ parser.add_argument("--head", required=True, help="Explicit source identity; recorded as an assertion, not inferred from the executable")
+ target = parser.add_mutually_exclusive_group(required=True)
+ target.add_argument("--window")
+ target.add_argument("--screen")
+ parser.add_argument("--mode", choices=["instant", "studio", "both"], default="both")
+ parser.add_argument("--duration", type=float, default=12)
+ parser.add_argument("--fps", type=int, default=30)
+ parser.add_argument("--mic")
+ parser.add_argument("--camera")
+ parser.add_argument("--system-audio", action="store_true")
+ parser.add_argument("--baseline-cap", type=Path)
+ parser.add_argument("--baseline-head")
+ parser.add_argument("--iterations", type=int, default=1)
+ parser.add_argument("--budget-seconds", type=int, default=600)
+ parser.add_argument("--windows-job-source", type=Path)
+ args = parser.parse_args(argv)
+ if not math.isfinite(args.duration) or not 3 <= args.duration <= 60 or not 1 <= args.fps <= 120:
+ parser.error("Duration must be 3–60 seconds and fps 1–120")
+ if not 1 <= args.iterations <= 3 or not 60 <= args.budget_seconds <= 1800:
+ parser.error("Iterations must be 1–3 and total budget 60–1800 seconds")
+ if bool(args.baseline_cap) != bool(args.baseline_head):
+ parser.error("--baseline-cap and --baseline-head must be supplied together")
+ if os.name == "nt" and not args.windows_job_source:
+ parser.error("Windows requires an explicitly supplied reviewed --windows-job-source")
+ return args
+
+
+def main(argv=None):
+ args = arguments(argv)
+ root = args.root.absolute()
+ if root.exists() or root.is_symlink() or not root.parent.is_dir() or root.parent.resolve() != root.parent:
+ raise ValueError("--root must be a fresh absent directory under a real existing parent")
+ identities = {}
+ for field in ["cap", "baseline_cap", "ffmpeg", "ffprobe", "windows_job_source"]:
+ path = getattr(args, field)
+ if path:
+ path = path.resolve(strict=True)
+ if not path.is_file():
+ raise ValueError(f"{field} must be an explicit file")
+ setattr(args, field, path)
+ identities[str(path)] = sha256(path)
+ planned = []
+ for iteration in range(args.iterations):
+ builds = [("candidate", args.cap, args.head)]
+ if args.baseline_cap:
+ builds.insert(0, ("baseline", args.baseline_cap, args.baseline_head))
+ if iteration % 2:
+ builds.reverse()
+ for name, binary, head in builds:
+ for mode in (["studio", "instant"] if args.mode == "both" else [args.mode]):
+ planned.append({"label": f"{iteration + 1}-{name}", "binary": str(binary), "head": head, "mode": mode})
+ root.mkdir(mode=0o700)
+ manifest = {"schemaVersion": 1, "createdUtc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "platform": platform.platform(), "root": str(root), "candidateHeadAsserted": args.head, "baselineHeadAsserted": args.baseline_head, "binarySha256Before": identities, "plannedCases": planned, "requested": {"window": args.window, "screen": args.screen, "camera": args.camera, "mic": args.mic, "systemAudio": args.system_audio, "fps": args.fps, "durationSeconds": args.duration}, "sourceIdentityVerifiedByRunner": False, "packageProof": False}
+ write_json(root / "manifest.json", manifest)
+ runner = Runner(root, time.monotonic() + args.budget_seconds, identities, args.windows_job_source)
+ rows = []
+ try:
+ for case in planned:
+ rows.append(run_case(runner, args, case["label"], case["binary"], case["head"], case["mode"]))
+ if time.monotonic() >= runner.deadline:
+ raise RuntimeError("Run budget exhausted; remaining cases are unexecuted")
+ except BaseException as error:
+ rows.append({"status": "FAIL", "error": f"Runner interrupted: {error}"})
+ completed = {(row.get("label"), row.get("mode")) for row in rows}
+ for case in planned:
+ if (case["label"], case["mode"]) not in completed:
+ rows.append({**case, "status": "PENDING", "reason": "Planned case was not executed before interruption/deadline"})
+ after = {}
+ for path in identities:
+ try:
+ after[path] = sha256(path)
+ except OSError:
+ after[path] = None
+ if after != identities:
+ rows.append({"status": "FAIL", "error": "A pinned executable or supervisor source changed during the run"})
+ summary = {**manifest, "binarySha256After": after, "status": aggregate(rows), "cases": rows, "commands": runner.commands, "recordingsRetained": True, "stopLatencyMeasured": False}
+ write_json(root / "summary.json", summary)
+ print(json.dumps({"status": summary["status"], "summary": str(root / "summary.json")}, allow_nan=False))
+ return {"PASS": 0, "FAIL": 1, "PENDING": 2}[summary["status"]]
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except (OSError, ValueError, RuntimeError) as error:
+ print(f"recording-reliability: {error}", file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/test-recording-reliability.py b/scripts/test-recording-reliability.py
new file mode 100644
index 000000000..e37431d40
--- /dev/null
+++ b/scripts/test-recording-reliability.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+import importlib.util
+import json
+from pathlib import Path
+import sys
+import tempfile
+import time
+import unittest
+
+
+SPEC = importlib.util.spec_from_file_location("reliability", Path(__file__).with_name("recording-reliability.py"))
+reliability = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(reliability)
+
+
+class RecordingReliabilityTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name).resolve()
+ self.project = self.root / "fixture.cap"
+ self.project.mkdir()
+ self.video = self.project / "display.mp4"
+ self.video.write_bytes(b"nonempty owned fixture")
+
+ def events(self, **stopped):
+ return "\n".join(json.dumps(event) for event in [
+ {"type": "started", "recordingId": "fixture", "pid": 123, "path": str(self.project)},
+ {"type": "stopped", "path": str(self.project), "recordingMetaExists": True, **stopped},
+ ])
+
+ def report(self, **overrides):
+ return {"valid": True, "projectPath": str(self.project), "recordingType": "studio", "checks": [
+ {"role": "displayVideo", "path": str(self.video), "exists": True, "required": True}
+ ], **overrides}
+
+ def probe(self, **stream):
+ return {"format": {"duration": "12"}, "streams": [
+ {"codec_type": "video", "width": 1920, "height": 1080, "nb_read_frames": "360", **stream}
+ ]}
+
+ def test_complete_events_require_order_and_saved_metadata(self):
+ self.assertEqual(len(reliability.capture_events(self.events(), self.project)), 2)
+ for text in [self.events(recordingMetaExists=False), "\n".join(reversed(self.events().splitlines())), self.events() + "\n" + self.events().splitlines()[1]]:
+ with self.subTest(text=text), self.assertRaises(ValueError):
+ reliability.capture_events(text, self.project)
+
+ def test_error_event_cannot_be_hidden_by_successful_stop(self):
+ text = self.events() + '\n{"type":"error","error":"disk write failed"}'
+ with self.assertRaises(ValueError):
+ reliability.capture_events(text, self.project)
+
+ def test_malformed_json_duplicate_keys_and_nonfinite_values_rejected(self):
+ for text in ['{"valid":false,"valid":true}', '{"duration":NaN}', "[]\n{}", "not json"]:
+ with self.subTest(text=text), self.assertRaises(ValueError):
+ reliability.strict_json(text)
+
+ def test_success_event_cannot_reference_a_different_project(self):
+ with self.assertRaises(ValueError):
+ reliability.capture_events(self.events(path=str(self.root / "other.cap")), self.project)
+
+ def test_zero_exit_and_error_log_is_not_clean_json(self):
+ with self.assertRaises(ValueError):
+ reliability.checked_json('{"valid":true}', "2026-08-30 ERROR encoder trailer failed")
+
+ def test_missing_requested_tracks_fail_even_if_cli_valid_is_true(self):
+ for requested in [("camera", None, False), (None, "mic", False), (None, None, True)]:
+ with self.subTest(requested=requested), self.assertRaises(ValueError):
+ reliability.project_media(self.report(), self.project, "studio", *requested)
+
+ def test_existing_video_is_not_a_camera_or_audio_substitute(self):
+ files = reliability.project_media(self.report(), self.project, "studio", None, None, False)
+ self.assertEqual(files[0]["role"], "displayVideo")
+ self.assertEqual(files[0]["path"], str(self.video))
+
+ def test_invalid_project_report_cannot_pass_from_existing_files(self):
+ for override in [{"valid": False}, {"problems": ["still recording"]}, {"missing": ["mic.ogg"]}, {"error": "failure"}]:
+ with self.subTest(override=override), self.assertRaises(ValueError):
+ reliability.project_media(self.report(**override), self.project, "studio", None, None, False)
+
+ def test_empty_artifact_and_path_escape_rejected(self):
+ self.video.write_bytes(b"")
+ with self.assertRaises(ValueError):
+ reliability.contained_file(self.video, self.project)
+ outside = self.root / "outside.mp4"
+ outside.write_bytes(b"private sentinel")
+ with self.assertRaises(ValueError):
+ reliability.contained_file(outside, self.project)
+ self.assertEqual(outside.read_bytes(), b"private sentinel")
+
+ def test_symlink_inside_project_cannot_hide_outside_artifact(self):
+ linked = self.project / "linked.mp4"
+ try:
+ linked.symlink_to(self.video)
+ except OSError:
+ self.skipTest("Creating symlinks is unavailable on this test host")
+ with self.assertRaises(ValueError):
+ reliability.contained_file(linked, self.project)
+
+ def test_duration_frozen_frame_count_and_missing_stream_rejected(self):
+ for probe in [self.probe(duration="1"), self.probe(nb_read_frames="2"), self.probe(width=0), self.probe(codec_type="audio"), self.probe(duration="nan")]:
+ with self.subTest(probe=probe), self.assertRaises(ValueError):
+ reliability.media_metrics(probe, 12, 30, "video")
+ self.assertEqual(reliability.media_metrics(self.probe(), 12, 30, "video")[0]["decodedFrames"], 360)
+
+ def test_silent_audio_is_not_a_pass(self):
+ for stderr in ["", "RMS level dB: -inf", "RMS level dB: -80.0"]:
+ with self.subTest(stderr=stderr), self.assertRaises(ValueError):
+ reliability.audio_levels(stderr)
+ self.assertEqual(reliability.audio_levels("RMS level dB: -24.5")["maximumRmsDbfs"], -24.5)
+
+ def test_pending_and_failed_requirements_cannot_become_success(self):
+ self.assertEqual(reliability.aggregate([]), "FAIL")
+ self.assertEqual(reliability.aggregate([{"status": "PASS"}, {"status": "PENDING"}]), "PENDING")
+ self.assertEqual(reliability.aggregate([{"status": "PASS"}, {"status": "FAIL"}]), "FAIL")
+ self.assertEqual(reliability.aggregate([{"status": "unknown"}]), "FAIL")
+
+ def test_existing_root_is_never_replaced(self):
+ sentinel = self.root / "keep.txt"
+ sentinel.write_text("keep me", encoding="utf-8")
+ with self.assertRaises(ValueError):
+ reliability.main(["--cap", sys.executable, "--ffmpeg", sys.executable, "--ffprobe", sys.executable, "--head", "test", "--root", str(self.root), "--window", "explicit-owned-window", "--windows-job-source", __file__])
+ self.assertEqual(sentinel.read_text(encoding="utf-8"), "keep me")
+
+ @unittest.skipIf(sys.platform == "win32", "POSIX process-group test; Windows requires the reviewed Job Object source")
+ def test_owned_timeout_cannot_be_reported_as_success(self):
+ binary = str(Path(sys.executable).resolve())
+ runner = reliability.Runner(self.root, time.monotonic() + 10, {binary: reliability.sha256(binary)})
+ with self.assertRaises(RuntimeError):
+ runner.run("timeout", [binary, "-c", "import time; time.sleep(30)"], 0.1)
+ receipt = runner.commands[0]
+ self.assertTrue(receipt["timedOut"])
+ self.assertTrue(receipt["forcedCleanup"])
+ self.assertTrue(receipt["cleanupComplete"])
+ self.assertFalse(receipt["passed"])
+
+ @unittest.skipIf(sys.platform == "win32", "POSIX process supervision test")
+ def test_nonzero_child_with_success_json_remains_failed(self):
+ binary = str(Path(sys.executable).resolve())
+ runner = reliability.Runner(self.root, time.monotonic() + 10, {binary: reliability.sha256(binary)})
+ with self.assertRaises(RuntimeError):
+ runner.run("exit-error", [binary, "-c", "print('{\"valid\":true}'); raise SystemExit(7)"], 2)
+ self.assertEqual(runner.commands[0]["exitCode"], 7)
+ self.assertFalse(runner.commands[0]["passed"])
+
+
+if __name__ == "__main__":
+ unittest.main()