diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0a4f106f..85b70841 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -181,7 +181,8 @@ jobs: # CHANGELOG.md is generated from the git history by `cargo xtask # changelog`, so a released section that disagrees with the tags is a # mistake, not a style choice. The icon PNGs and THIRD_PARTY.md (D491) - # are generated too, and the `generated` lane checks all three. + # are generated too, as is docs/DECISIONS_BY_AREA.md (D539), and the + # `generated` lane checks all four. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/CLAUDE.md b/CLAUDE.md index 7b0f12c1..9ce90acf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,14 +38,14 @@ cargo xtask credits [--check] # THIRD_PARTY.md (Abou cargo xtask decisions [--check] # docs/DECISIONS_BY_AREA.md, the decisions by crate (D539) cargo xtask rc --zip --symbols # release-candidate harness on a real Windows machine (D537) cargo run --profile release-fast -p strobe-app # optimised and incremental: iterate with this, not --release (D487) -cargo test --workspace # everything +cargo test --workspace --all-features # everything cargo clippy --workspace --all-targets --all-features -- -D warnings cargo fmt --all -- --check cargo clippy -p strobe-io --no-default-features --all-targets -- -D warnings # Linux; the build with MIDI off cargo clippy -p strobe-forge --no-default-features --all-targets -- -D warnings # the forge without its LLM client -cargo clippy -p strobe-web --target wasm32-unknown-unknown -- -D warnings # Linux; the browser engine (D544) -cargo clippy --workspace --exclude strobe-script --exclude strobe-app --exclude strobe-shadertoy --all-targets --all-features --target x86_64-pc-windows-msvc -- -D warnings -cargo clippy -p strobe-shadertoy --no-default-features --all-targets --target x86_64-pc-windows-msvc -- -D warnings +cargo clippy -p strobe-web -p strobe-gfx --no-default-features --target wasm32-unknown-unknown -- -D warnings # Linux; the browser engine (D544, D552) +cargo clippy --workspace --exclude strobe-script --exclude strobe-app --exclude strobe-shadertoy --exclude strobe-forge --all-targets --all-features --target x86_64-pc-windows-msvc -- -D warnings +cargo clippy -p strobe-shadertoy -p strobe-forge --no-default-features --all-targets --target x86_64-pc-windows-msvc -- -D warnings cargo run --release -p strobe-bench -- --size 1280x720 # benchmark + frames ``` @@ -53,9 +53,10 @@ All of these are clean on the branch, and CI enforces them. A warning is a build failure. CI's jobs run `cargo --locked xtask ci --strict `, so `cargo xtask ci` runs the same commands: the lanes `fmt`, `lint` (actionlint and shellcheck on Linux, PSScriptAnalyzer on Windows, D541), -`check` (clippy; on Linux also `strobe-io`, `strobe-audio` and -`strobe-shadertoy` without their default features, `strobe-web` for -wasm32, rustdoc and the Windows cross-check), `test`, `deny`, `generated` +`check` (clippy; on Linux also `strobe-io`, `strobe-audio`, +`strobe-shadertoy` and `strobe-forge` without their default features, +`strobe-web` and `strobe-gfx` for wasm32, rustdoc and the Windows +cross-check), `test`, `deny`, `generated` (changelog, brand, credits, decisions), `render` (Linux: Xvfb, the scene library and the corpus gate, D534), `build` (Windows: the optimised binaries), `package` (Windows: the release zip, unpacked and checked, @@ -75,9 +76,9 @@ edited by hand. Releases follow the order in `CONTRIBUTING.md`: write the section with `--release` first, tag after, never move a tag. The Windows cross-check excludes `strobe-script`, and `strobe-app` with -it because the app depends on the script crate. `strobe-shadertoy` is checked -separately without its `net` feature, whose TLS (`ring`) also compiles C -for MSVC (D110); `cargo xtask ci` runs both steps. QuickJS is C, and +it because the app depends on the script crate. `strobe-shadertoy` and `strobe-forge` are +checked separately without their `net` and `llm` features, whose TLS +(`ring`) also compiles C for MSVC (D110); `cargo xtask ci` runs both steps. QuickJS is C, and compiling it for MSVC needs the Windows SDK, so only a real Windows build checks those two for Windows: CI's `windows` job, or the T480. The app has no `#[cfg(windows)]` code of its own (its Windows branches are `cfg!` diff --git a/crates/strobe-bench/README.md b/crates/strobe-bench/README.md index de643586..a08865af 100644 --- a/crates/strobe-bench/README.md +++ b/crates/strobe-bench/README.md @@ -44,8 +44,8 @@ Every flag is defined in the clap `Cli`: | Flag | Default | Meaning | |---|---|---| | `--library ` | `scenes` | Folder of scene folders. | -| `--size WxH` | `640x360` | Render resolution. | -| `--frames ` | `60` | Timed frames per scene. | +| `--size WxH` | `640x360` | Render resolution, each edge 1 to 16384. | +| `--frames ` | `60` | Timed frames per scene, at least 1. | | `--warmup ` | `90` | Untimed frames first, so feedback scenes have history. | | `--scales ` | `1` | Render scales to time every scene at, comma-separated fractions of `--size` (`1,0.75,0.5`). The first gives the frames, the contact sheet and the main table; with more than one, `results.md` adds each scene's mean frame time per scale (D496). | | `--start ` | `2.0` | Scene time at the first frame. | @@ -56,11 +56,15 @@ Every flag is defined in the clap `Cli`: | `--probe` | off | Instead of benchmarking, clear, draw into and read back targets at a ladder of sizes plus `--size`, and print the viewport the driver keeps. Writes `probe.md` (D296). | | `--share` | off | Instead of benchmarking, time preparing a `--size` picture for Spout and NDI (a fixed-size draw, blackout, the UYVY pack and its asynchronous readback) against the first cut's synchronous readback, and check the NDI ring's pacing at 60 Hz. Writes `share.md` (D573). | | `--readback` | off | Instead of benchmarking, check the `textureFinalPass` readback on this context (latency, cost, a busy GPU, a resize, a lost context). Writes `readback.md` (D245). | +| `--post` | off | Instead of benchmarking, time the output post stage (the meta controls) at `--size`: skipped at neutral, invert alone, every pixel control at once. Writes `post.md` (C-01). | +| `--meta ` | none | Meta control values each saved frame is drawn through, `name=value` pairs joined by commas, a colour as three values joined by `:` (`hue=0.75,low_color=1:0:0`), in the stored `0..1` range (D578). Only the PNG goes through the meta stage; the timings and the all-black check use the scene's own frame. | | `--api desktop\|gles` | unset | Dialect for headless (desktop by default). In window mode the backend decides, and a contradiction with `--gl` is an error (D72). | | `--full` | off | RGBA32F instead of the default RGBA16F for `FLOAT` passes. | | `--shared` | off | One shared program per scene with a `PASSINDEX` uniform, instead of one specialised program per pass. | | `--filter ` | none | Only scenes whose folder name contains the text. | -| `--out ` | `target/bench` | Output folder: `.png`, `contact-sheet.png`, `results.md`. | +| `--out ` | `target/bench` | Output folder: `.png`, `contact-sheet.png`, `results.md`; or the one report a mode writes (`probe.md`, `post.md`, `share.md`, `readback.md`). | + +`--probe`, `--post`, `--share` and `--readback` are modes: at most one at a time. Environment: `STROBE_LOG` filters the renderer's log lines on stderr; `STROBE_GL_DEBUG=1` shows the driver's own messages; `STROBE_GL_TRACE=1` records @@ -84,7 +88,7 @@ folders as artifacts (D56). Numbers and method are in ## Testing -The crate has no tests of its own. Running it is the test: +Running it is the main test: ```bash apt-get install -y libegl1 libegl-mesa0 mesa-utils # headless Mesa llvmpipe @@ -95,7 +99,12 @@ cargo run --release -p strobe-bench -- --size 640x360 --frames 10 --warmup 60 -- Open `target/bench/contact-sheet.png` to check the visuals. On a machine with no GPU the context is llvmpipe: the timings are CPU rasterisation, but the ranking between scenes and the before/after delta of a change are meaningful. -It has no `#[test]` functions, so `cargo test -p strobe-bench` only compiles it. +`cargo test -p strobe-bench` runs the unit tests: the argument parsing, the +p95, the exit verdict (a scene failing at any `--scales` scale, no scene at +all, a context that drew nothing) and the readback checks' verdicts, plus two +on a headless context (an earlier scene's GL error does not fail the next; the +probe's start state is read before its rows). Those skip without EGL unless +`STROBE_REQUIRE_HEADLESS_GL` is set. ## Design notes @@ -125,11 +134,13 @@ IDs given here; a gap with no ID is by design, with its decision named. desktop's RX 580, TORNADO's GTX 1080 Ti (ANGLE's backends included) and the venue mini-PC's Vega 3. The other baseline is llvmpipe in a cloud container. `--scales 1,0.75,0.5` adds a render-scale sweep table (D496). -- **A failed scene fails the run.** A scene that fails to compile is printed - as `FAILED`, recorded in `results.md` and left out of the contact sheet. - After every frame and the report are written, the process exits non-zero - with `N of M scenes failed: `, which is what fails CI's bench step - (D56). +- **A failed scene fails the run.** A scene that fails to compile, raises + a GL error or cannot save its frame, at the first scale or any other + `--scales` scale, is printed as `FAILED`, recorded in `results.md` and + left out of the contact sheet. After every frame and the report are + written, the process exits non-zero with `N of M scenes failed: `, + which is what fails CI's bench step (D56). A run that benchmarks no scene + fails too. - No scripts run, by design (D239): `11-script-orbits` renders as a still with default controls, and `results.md` says so and marks such scenes `*`; `cargo xtask corpus` runs scripts. The audio textures come from the diff --git a/crates/strobe-bench/src/main.rs b/crates/strobe-bench/src/main.rs index eb20276c..db645774 100644 --- a/crates/strobe-bench/src/main.rs +++ b/crates/strobe-bench/src/main.rs @@ -76,7 +76,8 @@ use strobe_scene::control::ControlBank; #[derive(Parser, Debug)] #[command( name = "strobe-bench", - about = "Render and time every scene in a library" + about = "Render and time every scene in a library", + group = clap::ArgGroup::new("mode").multiple(false) )] struct Cli { /// Folder of scene folders. @@ -85,8 +86,8 @@ struct Cli { /// Render resolution, WIDTHxHEIGHT. #[arg(long, default_value = "640x360")] size: String, - /// Timed frames per scene. - #[arg(long, default_value_t = 60)] + /// Timed frames per scene, at least one. + #[arg(long, default_value_t = 60, value_parser = clap::value_parser!(u32).range(1..))] frames: u32, /// Untimed frames first, so feedback scenes have history. #[arg(long, default_value_t = 90)] @@ -149,24 +150,24 @@ struct Cli { /// Check the `textureFinalPass` readback on this context (latency, /// cost, busy GPU, resize, lost context) instead of benchmarking the /// library; writes `readback.md` (C-04). - #[arg(long)] + #[arg(long, group = "mode")] readback: bool, /// Time preparing a `--size` picture for Spout and NDI (the share /// stage's scaled draw, blackout, the UYVY pack and its asynchronous /// readback) against the first cut's synchronous readback, instead of /// benchmarking the library; writes `share.md` (M-06, D573). - #[arg(long)] + #[arg(long, group = "mode")] share: bool, /// Time the output post stage, the meta controls, at `--size`: skipped /// at neutral, invert alone, and every pixel control at once, instead /// of benchmarking the library; writes `post.md` (C-01). - #[arg(long)] + #[arg(long, group = "mode")] post: bool, /// Probe the driver at a ladder of sizes (plus `--size`) instead of /// benchmarking: does it clear, draw into and read back a target, and /// what viewport does it keep. Writes `probe.md`. For a machine whose /// frames come out black (D296). - #[arg(long)] + #[arg(long, group = "mode")] probe: bool, } @@ -244,6 +245,8 @@ struct Row { p95_ms: f64, max_ms: f64, image: Option, + /// The scene's own frame, before any `--meta`, had a lit pixel. + drew: bool, error: Option, } @@ -342,10 +345,14 @@ fn run( }; } if cli.post { - let report = post::run(gl, caps, context, size)?; + let (report, passed) = post::run(gl, caps, context, size)?; println!("{report}"); std::fs::write(cli.out.join("post.md"), &report)?; - return Ok(()); + return if passed { + Ok(()) + } else { + Err(anyhow!("the post stage raised a GL error; see post.md")) + }; } if cli.share { let (report, passed) = share::run(gl, caps, context, size)?; @@ -369,6 +376,7 @@ fn run( } let mut rows = Vec::new(); let mut sweep: Vec<(String, Vec>)> = Vec::new(); + let mut scale_failures: Vec = Vec::new(); for dir in strobe_scene::load::scan(&cli.library)? { let name = strobe_scene::load::folder_title(&dir); if cli @@ -383,6 +391,10 @@ fn run( let mut means = vec![row.error.is_none().then_some(row.mean_ms)]; for &scale in &scales[1..] { let at = bench_scene(gl, caps, &dir, &name, scaled(size, scale), options, cli); + if let Some(error) = &at.error { + println!("{name:<28} FAILED at scale {scale}: {error}"); + scale_failures.push(format!("{name} at scale {scale}")); + } means.push(at.error.is_none().then_some(at.mean_ms)); } sweep.push((name.clone(), means)); @@ -398,11 +410,18 @@ fn run( 1000.0 / row.mean_ms.max(0.001) ), } + let mut row = row; if let Some(image) = &row.image { if is_black(image) { println!("{name:<28} warning: the frame is all black"); } - image.save(cli.out.join(format!("{name}.png")))?; + // A frame that cannot be saved fails its scene, not the run + // before the report is written. + let path = cli.out.join(format!("{name}.png")); + if let Err(error) = image.save(&path) { + println!("{name:<28} FAILED: saving {}: {error}", path.display()); + row.error = Some(format!("saving {}: {error}", path.display())); + } } rows.push(row); } @@ -421,17 +440,32 @@ fn run( // Every frame and the report are written first, so a failing run still // leaves its evidence; then the exit status says it failed, which is // what lets CI's bench step catch a scene that no longer compiles (D56). - let failed: Vec<&str> = rows + verdict(&rows, &scale_failures) +} + +/// The run's exit status from its rows and the failures at the sweep's +/// other scales. +fn verdict(rows: &[Row], scale_failures: &[String]) -> Result<()> { + if rows.is_empty() { + return Err(anyhow!( + "no scene was benchmarked: `--library` holds no scene folder, or \ + `--filter` matched none" + )); + } + let mut failed: Vec<&str> = rows .iter() .filter(|row| row.error.is_some()) .map(|row| row.name.as_str()) .collect(); + failed.extend(scale_failures.iter().map(String::as_str)); // A context that draws nothing still times: on the projector mini-PC, // a hidden window in a Windows service's session 0 gave all-black // frames at a tenth of the real frame time, and the run looked fine. - // Every frame black means no number in the report is real. - let images: Vec<&image::RgbaImage> = rows.iter().filter_map(|row| row.image.as_ref()).collect(); - if !images.is_empty() && images.iter().all(|image| is_black(image)) { + // Every frame black means no number in the report is real. The + // scene's own frame decides, not the saved one: `--meta master=0` + // darkens every PNG of a context that drew. + let rendered: Vec<&Row> = rows.iter().filter(|row| row.error.is_none()).collect(); + if !rendered.is_empty() && rendered.iter().all(|row| !row.drew) { return Err(anyhow!( "every frame is all black, so the context drew nothing and the \ timings are not real (a window in a session nobody sees, such as \ @@ -446,7 +480,7 @@ fn run( Err(anyhow!( "{} of {} scenes failed: {}", failed.len(), - rows.len(), + rows.len() + scale_failures.len(), failed.join(", ") )) } @@ -462,21 +496,21 @@ fn is_black(image: &image::RgbaImage) -> bool { /// `--scales`: fractions of the size, each in `0.05..=1` (a scale above 1 /// is a bigger `--size`). fn parse_scales(text: &str) -> Result> { - let scales = text - .split(',') + // `split` yields at least one part, and an empty one fails to parse, + // so the result is never empty. + text.split(',') .map(|part| { - let scale: f32 = part.trim().parse()?; + let scale: f32 = part + .trim() + .parse() + .map_err(|e| anyhow!("--scales: `{}` is not a scale: {e}", part.trim()))?; if (0.05..=1.0).contains(&scale) { Ok(scale) } else { Err(anyhow!("a scale must be between 0.05 and 1, got {scale}")) } }) - .collect::>>()?; - if scales.is_empty() { - return Err(anyhow!("--scales needs at least one scale")); - } - Ok(scales) + .collect() } /// `size` times `scale`, each edge at least one pixel. @@ -485,7 +519,7 @@ fn scaled(size: [i32; 2], scale: f32) -> [i32; 2] { } /// The render-scale sweep as a Markdown table: each scene's mean frame -/// time at each scale, and what the smallest saves against the first. +/// time at each scale, and what the last scale saves against the first. fn sweep_table(sweep: &[(String, Vec>)], scales: &[f32], size: [i32; 2]) -> String { let mut out = String::new(); let _ = writeln!( @@ -526,11 +560,26 @@ fn sweep_table(sweep: &[(String, Vec>)], scales: &[f32], size: [i32; out } +/// `WIDTHxHEIGHT`, each edge `1..=16384`: GL's guaranteed texture size on +/// any machine this targets is far below that, and the gradient `--post` +/// and `--share` build is `w * h * 4` bytes before the driver is asked. fn parse_size(text: &str) -> Result<[i32; 2]> { + const LARGEST: i32 = 16384; let (w, h) = text .split_once(['x', 'X']) - .ok_or_else(|| anyhow!("size must be WIDTHxHEIGHT, got {text}"))?; - Ok([w.trim().parse()?, h.trim().parse()?]) + .ok_or_else(|| anyhow!("a size must be WIDTHxHEIGHT, got `{text}`"))?; + let edge = |part: &str| -> Result { + let value: i32 = part + .trim() + .parse() + .map_err(|e| anyhow!("size `{text}`: `{}`: {e}", part.trim()))?; + if (1..=LARGEST).contains(&value) { + Ok(value) + } else { + Err(anyhow!("size `{text}`: each edge must be 1 to {LARGEST}")) + } + }; + Ok([edge(w)?, edge(h)?]) } /// The player's finished frame drawn through the meta stage with the @@ -569,6 +618,10 @@ fn bench_scene( options: Options, cli: &Cli, ) -> Row { + // Start clean: an earlier scene that failed part-way (a refused + // allocation before an incomplete framebuffer) returns before its own + // check and leaves its error flag for this one to read. + gl.clear_errors(); let script = dir.join("script.js").is_file(); let failed = |error: String| Row { name: name.to_string(), @@ -579,6 +632,7 @@ fn bench_scene( p95_ms: 0.0, max_ms: 0.0, image: None, + drew: false, error: Some(error), }; let scene = match SceneFolder::load(dir) { @@ -631,7 +685,7 @@ fn bench_scene( let mut level_trail = vec![[0.0_f32; 4]; TRAIL_TEXELS]; let dt = 1.0 / 60.0; let mut times = Vec::with_capacity(cli.frames as usize); - for frame in 0..u64::from(cli.warmup + cli.frames) { + for frame in 0..frame_count(cli.warmup, cli.frames) { let time = cli.start + frame as f32 * dt; strobe_scene::synthetic::fill(time, &mut audio); strobe_scene::synthetic::fill_textures( @@ -661,26 +715,29 @@ fn bench_scene( } } if let Some(code) = gl.error() { + // The first is reported; the rest are cleared so they are not the + // next scene's. + gl.clear_errors(); return failed(format!("GL error 0x{code:x}")); } // A scene that pins its final pass (D280) renders at its own size. let [width, height] = player.render_size(); + let own = player.read_output(); + let drew = own.as_chunks::<4>().0.iter().any(|px| px[..3] != [0, 0, 0]); let pixels = match &cli.meta { - None => player.read_output(), + None => own, Some(spec) => match meta_frame(gl, caps, &player, spec) { Ok(pixels) => pixels, Err(error) => return failed(format!("--meta: {error}")), }, }; - let image = image::RgbaImage::from_raw(width as u32, height as u32, pixels); + let Some(image) = image::RgbaImage::from_raw(width as u32, height as u32, pixels) else { + return failed(format!("the frame read back is not {width}x{height}")); + }; times.sort_by(f64::total_cmp); let mean_ms = times.iter().sum::() / times.len().max(1) as f64; - let p95_ms = times - .get(((times.len() as f64) * 0.95) as usize) - .or(times.last()) - .copied() - .unwrap_or(0.0); + let p95_ms = p95(×); Row { name: name.to_string(), script, @@ -689,11 +746,26 @@ fn bench_scene( mean_ms, p95_ms, max_ms: times.last().copied().unwrap_or(0.0), - image, + drew, + image: Some(image), error: None, } } +/// The 95th percentile of `sorted` (ascending), or 0 when it is empty. +fn p95(sorted: &[f64]) -> f64 { + // Nearest rank: the smallest sample with 95% of them at or below it. + // `floor(n * 0.95)` as an index is one rank too high, and the maximum + // whenever there are fewer than 20 samples, as in CI's 10-frame run. + let rank = ((sorted.len() as f64) * 0.95).ceil() as usize; + sorted.get(rank.saturating_sub(1)).copied().unwrap_or(0.0) +} + +/// How many frames a scene renders: the warm-up and the timed ones. +fn frame_count(warmup: u32, frames: u32) -> u64 { + u64::from(warmup) + u64::from(frames) +} + /// Thumbnails of every rendered scene in a grid, five across. fn write_contact_sheet(rows: &[Row], path: &Path) -> Result<()> { const THUMB: [u32; 2] = [320, 180]; @@ -818,4 +890,169 @@ mod tests { assert!(!is_black(&one), "one lit pixel is not black"); Ok(()) } + + fn row(name: &str, error: Option<&str>, image: [u8; 3], drew: bool) -> Row { + Row { + name: name.to_string(), + script: false, + compile_ms: 1.0, + blocked_ms: 1.0, + mean_ms: 1.0, + p95_ms: 1.0, + max_ms: 1.0, + image: error.is_none().then(|| { + image::RgbaImage::from_pixel(2, 2, image::Rgba([image[0], image[1], image[2], 255])) + }), + drew, + error: error.map(str::to_string), + } + } + + /// A headless context, or `None` (after saying so) when none exists here. + pub(crate) fn headless() -> Result> { + match strobe_gfx::Headless::new(Api::DesktopCore33) { + Ok(headless) => Ok(Some(headless)), + Err(error) if std::env::var_os("STROBE_REQUIRE_HEADLESS_GL").is_none() => { + strobe_gfx::skip::note(format_args!("no headless context ({error})")); + Ok(None) + } + Err(error) => Err(anyhow!("headless context required: {error}")), + } + } + + #[test] + fn an_error_an_earlier_scene_left_does_not_fail_the_next() -> Result<()> { + let Some(headless) = headless()? else { + return Ok(()); + }; + let gl = headless.gl(); + let caps = Caps::from_info(gl.info()); + let library = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scenes"); + let Some(dir) = strobe_scene::load::scan(&library)?.into_iter().next() else { + return Err(anyhow!("no scene in {}", library.display())); + }; + let cli = Cli::try_parse_from(["strobe-bench", "--frames", "1", "--warmup", "0"])?; + // GL_INVALID_VALUE, as a scene that failed in `finish` after a + // refused allocation leaves behind. + gl.viewport(-1, -1); + let row = bench_scene(gl, &caps, &dir, "next", [32, 18], Options::default(), &cli); + assert!(row.error.is_none(), "a good scene passes: {:?}", row.error); + Ok(()) + } + + #[test] + fn p95_is_the_nearest_rank_not_the_maximum() -> Result<()> { + let twenty: Vec = (1..=20).map(f64::from).collect(); + assert!( + (p95(&twenty) - 19.0).abs() < 1e-9, + "p95 of 1..=20 is 19, got {}", + p95(&twenty) + ); + let hundred: Vec = (1..=100).map(f64::from).collect(); + assert!( + (p95(&hundred) - 95.0).abs() < 1e-9, + "p95 of 1..=100 is 95, got {}", + p95(&hundred) + ); + assert!( + (p95(&[7.0]) - 7.0).abs() < 1e-9, + "one sample is its own p95" + ); + assert!(p95(&[]).abs() < 1e-9, "no samples is zero"); + Ok(()) + } + + #[test] + fn the_frame_count_does_not_overflow() -> Result<()> { + assert_eq!( + frame_count(u32::MAX, 2), + u64::from(u32::MAX) + 2, + "warm-up plus frames is summed in u64" + ); + Ok(()) + } + + #[test] + fn a_failure_at_another_scale_fails_the_run() -> Result<()> { + let rows = [row("a", None, [9, 9, 9], true)]; + assert!(verdict(&rows, &[]).is_ok(), "a clean run passes"); + let failures = ["a at 0.5: GL error 0x505".to_string()]; + let Err(error) = verdict(&rows, &failures) else { + return Err(anyhow!( + "a scene that fails at a sweep scale must fail the run" + )); + }; + assert!( + error.to_string().contains("a at 0.5"), + "names the scale: {error}" + ); + Ok(()) + } + + #[test] + fn a_run_that_benchmarks_no_scene_fails() -> Result<()> { + assert!( + verdict(&[], &[]).is_err(), + "no scene matched, so nothing was measured" + ); + Ok(()) + } + + #[test] + fn meta_that_darkens_the_saved_frame_is_not_a_dead_context() -> Result<()> { + // `--meta master=0`: the PNG is black, the scene drew. + let rows = [row("a", None, [0, 0, 0], true)]; + assert!(verdict(&rows, &[]).is_ok(), "the scene's own frame was lit"); + let dead = [row("a", None, [0, 0, 0], false)]; + assert!( + verdict(&dead, &[]).is_err(), + "a scene frame that is black still fails" + ); + Ok(()) + } + + #[test] + fn a_size_must_be_two_positive_edges() -> Result<()> { + assert_eq!(parse_size("640x360")?, [640, 360], "plain"); + assert_eq!(parse_size(" 64 X 36 ")?, [64, 36], "spaces and capital X"); + for bad in ["0x0", "640x-360", "1280x", "x720", "100000x100000", "640"] { + let Err(error) = parse_size(bad) else { + return Err(anyhow!("{bad} must be refused")); + }; + assert!( + error.to_string().contains(bad), + "the error names `{bad}`: {error}" + ); + } + Ok(()) + } + + #[test] + fn a_bad_scale_says_which_part() -> Result<()> { + assert_eq!(parse_scales("1, 0.5")?, vec![1.0, 0.5], "two scales"); + for bad in ["1,,0.5", "0", "1.5", "NaN", "-1", "half"] { + let Err(error) = parse_scales(bad) else { + return Err(anyhow!("{bad} must be refused")); + }; + assert!(error.to_string().contains("scale"), "`{bad}`: {error}"); + } + Ok(()) + } + + #[test] + fn zero_frames_and_two_modes_are_refused() -> Result<()> { + assert!( + Cli::try_parse_from(["strobe-bench", "--frames", "0"]).is_err(), + "zero timed frames would report made-up numbers" + ); + assert!( + Cli::try_parse_from(["strobe-bench", "--probe", "--readback"]).is_err(), + "two modes at once would run only the first" + ); + assert!( + Cli::try_parse_from(["strobe-bench", "--readback"]).is_ok(), + "one mode is fine" + ); + Ok(()) + } } diff --git a/crates/strobe-bench/src/post.rs b/crates/strobe-bench/src/post.rs index 0a317d87..ed481898 100644 --- a/crates/strobe-bench/src/post.rs +++ b/crates/strobe-bench/src/post.rs @@ -50,8 +50,10 @@ fn everything() -> MetaValues { } } -/// Runs the rows and returns the report. -pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, size: [i32; 2]) -> Result { +/// Runs the rows and returns the report, and whether no GL error was +/// raised (the timings of a pass the driver refused are not its cost). +pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, size: [i32; 2]) -> Result<(String, bool)> { + gl.clear_errors(); let [width, height] = size; let pixels: Vec = (0..height) .flat_map(|y| { @@ -114,5 +116,10 @@ pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, size: [i32; 2]) -> Result } writeln!(report, "| {label} | {best:.3} |")?; } - Ok(report) + let error = gl.error(); + if let Some(code) = error { + gl.clear_errors(); + writeln!(report, "\nGL error 0x{code:x} after the run.")?; + } + Ok((report, error.is_none())) } diff --git a/crates/strobe-bench/src/probe.rs b/crates/strobe-bench/src/probe.rs index a3009cae..1e365c34 100644 --- a/crates/strobe-bench/src/probe.rs +++ b/crates/strobe-bench/src/probe.rs @@ -26,8 +26,8 @@ //! //! A row with `clear` full and `draw` empty means the driver drops draws but //! not clears. A viewport that comes back smaller than asked means it clamps -//! to the drawable. Both full means this size is fine. Rows are in -//! ascending size, so the first bad one is the limit. Run it with different +//! to the drawable. Both full means this size is fine. Rows are sorted +//! by pixel count, so the first bad one is the limit. Run it with different //! `--window-size` values to see whether the limit moves with the window. //! //! This is a diagnostic: it queries the driver freely, which the frame loop @@ -84,6 +84,11 @@ pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, extra: [i32; 2]) -> Resul if !sizes.contains(&extra) { sizes.push(extra); } + sizes.sort_by_key(|[w, h]| i64::from(*w) * i64::from(*h)); + // The state the context arrived with, read before the first row's + // `plain_state` and `viewport` change it: a window-sized scissor or + // viewport is what this line exists to show (D296). + let start_state = (gl.viewport_box(), gl.scissor_box(), gl.scissor_enabled()); let mut rows = Vec::new(); let mut failures = Vec::new(); for size in sizes { @@ -114,9 +119,9 @@ pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, extra: [i32; 2]) -> Resul let _ = writeln!( out, "- Start state: viewport {:?}, scissor box {:?}, scissor test {}, max viewport {:?}, max texture {}\n", - gl.viewport_box(), - gl.scissor_box(), - if gl.scissor_enabled() { "ON" } else { "off" }, + start_state.0, + start_state.1, + if start_state.2 { "ON" } else { "off" }, gl.max_viewport_dims(), caps.info.max_texture_size, ); @@ -311,6 +316,23 @@ mod tests { Ok(()) } + #[test] + fn the_start_state_is_the_one_the_context_had_before_the_probe() -> Result<()> { + let Some(headless) = crate::tests::headless()? else { + return Ok(()); + }; + let gl = headless.gl(); + let caps = Caps::from_info(gl.info()); + // A viewport no probe row uses, as a window-sized one would be. + gl.viewport(24, 24); + let (report, _) = run(gl, &caps, "test", [16, 16])?; + assert!( + report.contains("Start state: viewport [0, 0, 24, 24]"), + "the start state is read before the rows change it:\n{report}" + ); + Ok(()) + } + #[test] fn the_ladder_straddles_the_sizes_seen_to_fail() -> Result<()> { for size in [[160, 90], [200, 90], [160, 120], [1920, 1080]] { diff --git a/crates/strobe-bench/src/readback.rs b/crates/strobe-bench/src/readback.rs index 7091308d..7dcef570 100644 --- a/crates/strobe-bench/src/readback.rs +++ b/crates/strobe-bench/src/readback.rs @@ -29,8 +29,8 @@ //! above a millisecond. //! 3. **Busy GPU.** The same heavy scene with no `glFinish`: the age of the //! picture is recorded per frame (never newer than two frames, never -//! going backwards), with the CPU time of each `render` call, which -//! must not grow into a stall. +//! going backwards, and at least one picture arriving), with the CPU +//! time of each `render` call, reported for a person to judge. //! 4. **Resize.** A resize drops the old picture, and the new size reads //! back. //! 5. **Lost context.** With the context marked lost, dropping a player @@ -84,13 +84,16 @@ struct Check { /// (Markdown) and whether all of them passed. pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, size: [i32; 2]) -> Result<(String, bool)> { gl.clear_errors(); - let checks = vec![ - latency(gl, caps)?, - cost(gl, caps, size)?, - busy(gl, caps, size)?, - resize(gl, caps)?, - lost(gl, caps)?, - ]; + let mut checks = vec![latency(gl, caps)?]; + // `latency` checks the error flag itself; the others would not see a + // GL error they raised, so each is followed by a look. + for check in [cost, busy] { + checks.push(check(gl, caps, size)?); + errors(gl, &mut checks); + } + checks.push(resize(gl, caps)?); + errors(gl, &mut checks); + checks.push(lost(gl, caps)?); let mut report = String::new(); writeln!(report, "# textureFinalPass readback check\n")?; writeln!( @@ -108,6 +111,19 @@ pub(crate) fn run(gl: &Gl, caps: &Caps, context: &str, size: [i32; 2]) -> Result Ok((report, passed)) } +/// Fails the last check in `checks` if a GL error is pending, and clears +/// the rest so the next check starts clean. +fn errors(gl: &Gl, checks: &mut [Check]) { + let Some(code) = gl.error() else { + return; + }; + gl.clear_errors(); + if let Some(check) = checks.last_mut() { + check.passed = false; + let _ = write!(check.detail, "; GL error 0x{code:x}"); + } +} + /// A scene folder from a shader alone. fn scene(shader: &str) -> Result { Ok(SceneFolder { @@ -130,7 +146,8 @@ fn player(gl: &Gl, caps: &Caps, shader: &str, size: [i32; 2], on: bool) -> Resul /// Renders frame `frame` with a silent room. fn render(player: &mut ScenePlayer, controls: &ControlBank, frame: u64) { - let audio = vec![0.0; SCALARS.len()]; + // On the stack: `busy` times this call. + let audio = [0.0; SCALARS.len()]; player.render(&FrameInputs { time: frame as f32 / 60.0, frame, @@ -263,6 +280,7 @@ fn busy(gl: &Gl, caps: &Caps, size: [i32; 2]) -> Result { ages.push(old as f64); } gl.finish(); + let problems = busy_problems(problems, ages.len()); let (call_mean, call_max) = mean_max(&calls); let (age_mean, age_max) = mean_max(&ages); let dropped = player.final_pass_dropped(); @@ -281,6 +299,18 @@ fn busy(gl: &Gl, caps: &Caps, size: [i32; 2]) -> Result { }) } +/// The busy check's problems, given how many frames showed a picture. +fn busy_problems(mut problems: Vec, arrived: usize) -> Vec { + // A driver whose fences never signal without `glFinish` is exactly the + // busy case; an empty run must not read as a clean one. + if arrived == 0 { + problems.push(format!( + "no picture arrived in {TIMED_FRAMES} frames without glFinish" + )); + } + problems +} + fn resize(gl: &Gl, caps: &Caps) -> Result { let controls = ControlBank::new(Vec::new())?; let mut player = player(gl, caps, LIGHT, [128, 72], true)?; @@ -344,6 +374,45 @@ mod tests { Ok(()) } + #[test] + fn a_gl_error_after_a_check_fails_it() -> Result<()> { + let Some(headless) = crate::tests::headless()? else { + return Ok(()); + }; + let gl = headless.gl(); + gl.clear_errors(); + let mut checks = [Check { + name: "Cost", + passed: true, + detail: String::from("measured"), + }]; + errors(gl, &mut checks); + assert!(checks[0].passed, "no error, no change"); + gl.viewport(-1, -1); + errors(gl, &mut checks); + assert!(!checks[0].passed, "the error fails the check"); + assert!( + checks[0].detail.contains("GL error 0x501"), + "{}", + checks[0].detail + ); + assert!( + gl.error().is_none(), + "the flag is cleared for the next check" + ); + Ok(()) + } + + #[test] + fn a_busy_run_where_no_picture_arrives_fails() -> Result<()> { + assert!( + !busy_problems(Vec::new(), 0).is_empty(), + "nothing arriving without glFinish is the failure the check exists for" + ); + assert!(busy_problems(Vec::new(), 5).is_empty(), "pictures arrived"); + Ok(()) + } + #[test] fn the_scenes_parse() -> Result<()> { scene(LIGHT)?; diff --git a/crates/strobe-bench/src/share.rs b/crates/strobe-bench/src/share.rs index b4478d04..1825bc75 100644 --- a/crates/strobe-bench/src/share.rs +++ b/crates/strobe-bench/src/share.rs @@ -21,7 +21,8 @@ //! The rows: //! //! 1. Spout at the picture's size: the picture's own texture, no draw. -//! 2. Spout at a fixed 1920x1080: one scaled draw. +//! 2. Spout at a fixed size other than the picture's (1280x720, or +//! 1920x1080 when `--size` is 1280x720): one scaled draw. //! 3. Blackout: one clear. //! 4. NDI: the UYVY pack and its asynchronous readback, with the frames //! until the first picture arrives. diff --git a/crates/strobe-diag/README.md b/crates/strobe-diag/README.md index 12098d17..b6b966f0 100644 --- a/crates/strobe-diag/README.md +++ b/crates/strobe-diag/README.md @@ -13,8 +13,8 @@ and the `--diagnose` system report. - **Depends on:** no other Strobe crate. Third-party: `log`, `dirs`, `crash-handler` and `minidumper` (and `anyhow` for tests). - **Depended on by:** `strobe-app`, which installs it; the `strobe-bench`, - `strobe-import` and `strobe-projector` binaries, for their stderr log and - the data directory. `strobe-gfx` and the other libraries use only the + `strobe-forge` and `strobe-projector` binaries, for their stderr log, and + `strobe-shadertoy`'s `strobe-import` for the data directory. `strobe-gfx` and the other libraries use only the `log` facade, and the app installs the backend, so the dependency direction stays one-way ([`ARCHITECTURE.md`](../../docs/ARCHITECTURE.md), "Diagnostics wiring"). @@ -37,7 +37,7 @@ and the `--diagnose` system report. | `logger` | The `log` backend. `recent_lines(n)`, `records_written()` (one atomic load, so a UI can tell when to refresh), `flush(timeout)`. Keeps the newest 10 session logs and a 2000-line ring. | | `filter::Filter` | `STROBE_LOG` parsing: `debug`, `strobe_gfx=trace,warn`, most specific directive wins. | | `context` | Session facts every report includes: `set`, `get`, `note_frame`, `note_pass`, and keys such as `GL_RENDERER`, `GL_BACKEND` and `SCENE`. | -| `failure::{Failure, Subsystem, report}` | Structured records: `Subsystem` is `Shader`, `Audio`, `Import`, `Context`, `Script`, `Playlist` or `Io`; `Failure::new(..).scene(..).message(..).action(..)`. `failure::recent(n)` returns the last 100. | +| `failure::{Failure, Subsystem, report}` | Structured records: `Subsystem` is `Shader`, `Audio`, `Import`, `Context`, `Script`, `Playlist`, `Io`, `Arguments` or `Diagnostics`; `Failure::new(..).scene(..).message(..).action(..)`. `failure::recent(n)` returns the last 100. | | `panic_hook` | `install_panic_hook()` (called by `init`); writes a report with backtrace, context, failures and log tail. | | `crash` | `run_monitor_if_requested(args)` and `start_monitor()` for out-of-process native crash capture; `MonitorHandle::wait_connected`. | | `notify` | `set_notifier(..)` and `CrashNotice`: how a person is told. | @@ -56,8 +56,12 @@ use strobe_diag::context; use strobe_diag::failure::{self, Failure, Subsystem}; fn main() { + // A real app registers its message box first, with + // `strobe_diag::notify::set_notifier`: the monitor reports with it. // If this process was launched as the crash monitor, run that and exit. - if strobe_diag::crash::run_monitor_if_requested(std::env::args()) { + // `args_os`, not `args`: `args` panics on an argument that is not + // Unicode, before the panic hook exists. + if strobe_diag::crash::run_monitor_if_requested(std::env::args_os()) { return; } let session = strobe_diag::init(); // logger, panic hook, system probe diff --git a/crates/strobe-diag/src/context.rs b/crates/strobe-diag/src/context.rs index ef1a5c12..787cf592 100644 --- a/crates/strobe-diag/src/context.rs +++ b/crates/strobe-diag/src/context.rs @@ -216,6 +216,7 @@ mod tests { const THREAD: &str = "context-display-panic"; static HOOK_SAW_FREE_LOCK: AtomicBool = AtomicBool::new(false); static HOOK_RAN: AtomicBool = AtomicBool::new(false); + let _turn = crate::test_turns::panic_hook(); let previous: Arc>> = Arc::new(Mutex::new(Some(std::panic::take_hook()))); diff --git a/crates/strobe-diag/src/crash.rs b/crates/strobe-diag/src/crash.rs index 7a99a296..007aaf7f 100644 --- a/crates/strobe-diag/src/crash.rs +++ b/crates/strobe-diag/src/crash.rs @@ -45,7 +45,8 @@ //! //! ## What the app must do //! -//! 1. First thing in `main()`, before anything else: +//! 1. First thing in `main()`, after only [`notify::set_notifier`] (the +//! monitor reports with it): //! `if run_monitor_if_requested(std::env::args_os()) { return; }` //! 2. On the **main thread**, call [`start_monitor`] and keep the returned //! handle alive until exit. Attaching on the main thread is what gives @@ -67,8 +68,9 @@ //! //! ## Platform notes //! -//! The socket is a Linux abstract-namespace socket, or a Unix-domain socket -//! file in the temp directory elsewhere. On Windows that needs Windows 10 +//! The socket is a Linux abstract-namespace socket, or elsewhere a +//! Unix-domain socket file in [`paths::sockets_dir`] (the temp directory +//! when that path is too long for a socket name). On Windows that needs Windows 10 //! version 1803 or later. `std::process::abort()` on Windows compiles to a //! fast-fail that bypasses exception filters, so an abort there leaves no //! minidump; a *panic* still leaves its text report, which is written @@ -125,6 +127,11 @@ const FAILURE_TAIL: usize = 20; const FAILURE_SEPARATOR: char = '\u{1e}'; /// Message kinds on the minidumper channel (user kinds start at 0). +/// The most bytes one crash message carries. `minidumper` asks for +/// messages well under 64 KiB: on Linux a bigger one fails outright, and +/// on Windows' stream socket the server reads it in one call. +const MESSAGE_CAP: usize = 32 * 1024; + const KIND_CONTEXT: u32 = 1; const KIND_FAILURES: u32 = 2; const KIND_LOG: u32 = 3; @@ -322,10 +329,30 @@ where false } +/// The file in the crashes folder the monitor's own trouble is appended to. +const MONITOR_LOG: &str = "monitor.log"; + /// The monitor has no logger of its own (it must not rotate the app's -/// session logs away), so its own trouble goes to stderr. +/// session logs away), so its own trouble goes to `crashes/monitor.log` +/// (and to its stderr, which the app nulls). fn write_stderr(message: &str) { + write_trouble(&paths::crashes_dir(), message); +} + +/// Writes the monitor's own trouble where it can be read. +fn write_trouble(dir: &Path, message: &str) { + // The monitor's stderr is null (it must not flash a console over the + // show), so the file is the copy anyone will read. Best effort both. writeln!(std::io::stderr(), "{message}").ok(); + let written = fs::create_dir_all(dir).and_then(|()| { + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(dir.join(MONITOR_LOG))?; + writeln!(file, "{} {message}", crate::clock::Utc::now().iso()) + }); + // Nowhere else to say it: the stderr copy above was the other try. + written.ok(); } fn run_monitor(name: &str) { @@ -406,15 +433,17 @@ impl MonitorState { // An abort that followed a panic: the panic hook already wrote and // announced the report. Point it at the dump and stay quiet. if let Some(panic_report) = &self.received.panic_report { - if let Some(dump) = &dump { - append( - panic_report, - &format!( - "\nMinidump of the abort that followed: {}\n", - file_name(dump) - ), - ); - } + let line = match (&dump, &dump_error) { + (Some(dump), _) => format!( + "\nMinidump of the abort that followed: {}\n", + file_name(dump) + ), + (None, Some(error)) => { + format!("\nMinidump of the abort that followed NOT WRITTEN: {error}\n") + } + (None, None) => String::new(), + }; + append(panic_report, &line); return None; } @@ -432,7 +461,7 @@ impl MonitorState { .and_then(|stem| report::write_text(dir, &stem, &report.render())), }; let report_path = written - .map_err(|error| write_stderr(&format!("strobe crash monitor: report: {error}"))) + .map_err(|error| write_trouble(dir, &format!("strobe crash monitor: report: {error}"))) .ok(); Some(CrashNotice { kind: CrashKind::Native, @@ -453,6 +482,24 @@ impl MonitorHandler { fn state(&self) -> std::sync::MutexGuard<'_, MonitorState> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } + + /// Claims the dump's stem (the panic report's, when one came first) + /// and creates its file in `dir`. + fn create_in(dir: &Path, state: &mut MonitorState) -> std::io::Result<(File, PathBuf)> { + let stem = match state + .received + .panic_report + .as_deref() + .and_then(Path::file_stem) + { + Some(stem) => stem.to_string_lossy().into_owned(), + None => report::claim_stem(dir)?, + }; + let path = dir.join(format!("{stem}.dmp")); + let file = File::create(&path)?; + state.stem = Some(stem); + Ok((file, path)) + } } fn append(path: &Path, text: &str) { @@ -466,19 +513,16 @@ fn append(path: &Path, text: &str) { impl ServerHandler for MonitorHandler { fn create_minidump_file(&self) -> Result<(File, PathBuf), std::io::Error> { let mut state = self.state(); - let stem = match state - .received - .panic_report - .as_deref() - .and_then(Path::file_stem) - { - Some(stem) => stem.to_string_lossy().into_owned(), - None => report::claim_stem(&self.dir)?, - }; - let path = self.dir.join(format!("{stem}.dmp")); - let file = File::create(&path)?; - state.stem = Some(stem); - Ok((file, path)) + // `minidumper` never calls `on_minidump_created` when this fails, + // so the failure is recorded here or the crash leaves no trace. + let created = Self::create_in(&self.dir, &mut state); + if let Err(error) = &created { + state.dump = Some(Err(format!( + "the dump file could not be made in {}: {error}", + self.dir.display() + ))); + } + created } /// Records the outcome and stops the server. The report and the notice @@ -522,7 +566,6 @@ impl ServerHandler for MonitorHandler { pub struct MonitorHandle { _handler: CrashHandler, child: Arc>, - pid: u32, /// Dropping this stops the watcher thread; see [`watch_monitor`]. stop_watch: Option>, client: Arc>, @@ -548,11 +591,6 @@ impl MonitorHandle { } self.is_connected() } - - /// The monitor process id. - pub fn monitor_pid(&self) -> u32 { - self.pid - } } impl Drop for MonitorHandle { @@ -612,13 +650,11 @@ pub fn start_monitor() -> Option { child.id() ); spawn_connector(Arc::clone(&client), name); - let pid = child.id(); let child = Arc::new(Mutex::new(child)); let stop_watch = spawn_watcher(Arc::clone(&child)); Some(MonitorHandle { _handler: handler, child, - pid, stop_watch, client, }) @@ -780,9 +816,40 @@ fn spawn_connector(slot: Arc>, name: String) { } } +/// The newest of `parts` joined by `separator` (old behaviour: all). +fn newest_within(parts: &[String], separator: &str, cap: usize) -> String { + // Oldest parts go first; the newest is what the crash is about. + let mut kept = 0_usize; + let mut bytes = 0_usize; + for part in parts.iter().rev() { + let more = part.len() + if kept == 0 { 0 } else { separator.len() }; + if bytes + more > cap { + break; + } + bytes += more; + kept += 1; + } + if kept == 0 { + // One part bigger than the cap: its end, cut on a char boundary. + let Some(last) = parts.last() else { + return String::new(); + }; + let mut start = last.len().saturating_sub(cap); + while !last.is_char_boundary(start) { + start += 1; + } + return last[start..].to_string(); + } + parts[parts.len() - kept..].join(separator) +} + /// Runs in the compromised context. Sends what the monitor needs to write /// a useful report, then asks it for the minidump. It takes no lock it -/// might have to wait for (`try_*` everywhere), and never logs. +/// might have to wait for (`try_*` everywhere), and never logs. It does +/// allocate (formatting, the snapshots) and `ping` waits for the monitor +/// without a timeout: a crash inside the allocator with its lock held +/// would stop here before the dump is asked for. Asking first would lose +/// the report's context, which the monitor reads before it dumps. fn on_crash(client: &OnceLock, crash: &CrashContext) -> CrashEventResult { let Some(client) = client.get() else { return CrashEventResult::Handled(false); @@ -800,13 +867,20 @@ fn on_crash(client: &OnceLock, crash: &CrashContext) -> CrashEventResult .collect(); // Inside the crash handler: each message is best effort. client - .send_message(KIND_FAILURES, failures.join(&FAILURE_SEPARATOR.to_string())) + .send_message( + KIND_FAILURES, + newest_within(&failures, &FAILURE_SEPARATOR.to_string(), MESSAGE_CAP), + ) .ok(); // Inside the crash handler: each message is best effort. client .send_message( KIND_LOG, - logger::try_recent_lines(panic_hook::LOG_TAIL).join("\n"), + newest_within( + &logger::try_recent_lines(panic_hook::LOG_TAIL), + "\n", + MESSAGE_CAP, + ), ) .ok(); if let Some(path) = panic_hook::last_report() { @@ -1044,6 +1118,7 @@ mod tests { #[test] fn a_lost_monitor_becomes_one_diagnostics_failure() -> Result<()> { + let _turn = crate::test_turns::failures(); report_monitor_gone("exit status: 7"); let reported = failure::recent(failure::KEPT) .iter() @@ -1059,6 +1134,98 @@ mod tests { Ok(()) } + #[test] + fn a_dump_file_that_cannot_be_made_is_still_reported() -> Result<()> { + let base = + std::env::temp_dir().join(format!("strobe-diag-test-{}-nodump", std::process::id())); + fs::create_dir_all(&base)?; + // A file where the crashes folder should be: nothing can go in it. + let blocker = base.join("not-a-dir"); + fs::write(&blocker, b"")?; + let handler = MonitorHandler { + dir: blocker.join("crashes"), + connected: Arc::new(AtomicBool::new(true)), + state: Arc::new(Mutex::new(MonitorState::default())), + }; + handler + .state() + .received + .apply(KIND_CRASH_INFO, b"native crash: SIGSEGV"); + let created = handler.create_minidump_file(); + let notice = handler.state().finish(&handler.dir); + fs::remove_dir_all(&base)?; + assert!(created.is_err(), "the dump file cannot be made"); + let notice = notice.ok_or_else(|| anyhow!("the crash must still be announced"))?; + assert!(notice.dump.is_none(), "there is no dump"); + assert!(notice.summary.contains("SIGSEGV"), "{}", notice.summary); + Ok(()) + } + + #[test] + fn a_dump_that_failed_after_a_panic_is_written_into_its_report() -> Result<()> { + let dir = + std::env::temp_dir().join(format!("strobe-diag-test-{}-panicdump", std::process::id())); + fs::create_dir_all(&dir)?; + let panic_report = dir.join("crash-20261008-120002.txt"); + fs::write(&panic_report, "panic report\n")?; + let mut state = MonitorState::default(); + state + .received + .apply(KIND_PANIC_REPORT, panic_report.to_string_lossy().as_bytes()); + state.dump = Some(Err("disk full".to_string())); + let notice = state.finish(&dir); + let text = fs::read_to_string(&panic_report)?; + fs::remove_dir_all(&dir)?; + assert!(notice.is_none(), "the panic hook already told the person"); + assert!( + text.contains("NOT WRITTEN") && text.contains("disk full"), + "the report says the dump failed and why:\n{text}" + ); + Ok(()) + } + + #[test] + fn a_crash_message_keeps_the_newest_parts_within_the_cap() -> Result<()> { + let lines: Vec = (0..200) + .map(|i| format!("{i:04} {}", "x".repeat(1019))) + .collect(); + let text = newest_within(&lines, "\n", MESSAGE_CAP); + assert!( + text.len() <= MESSAGE_CAP, + "{} bytes is over the cap", + text.len() + ); + assert!( + text.ends_with(lines[199].as_str()), + "the newest line is kept" + ); + assert!(text.starts_with("0"), "whole lines only: {}", &text[..8]); + let small = newest_within(&lines[..2], "\n", MESSAGE_CAP); + assert_eq!( + small, + format!("{}\n{}", lines[0], lines[1]), + "under the cap, all of it" + ); + let one = newest_within(&["y".repeat(MESSAGE_CAP + 10)], "\n", MESSAGE_CAP); + assert!(one.len() <= MESSAGE_CAP, "one huge part is cut to the cap"); + Ok(()) + } + + #[test] + fn the_monitors_trouble_is_written_to_a_file() -> Result<()> { + let dir = + std::env::temp_dir().join(format!("strobe-diag-test-{}-trouble", std::process::id())); + fs::create_dir_all(&dir)?; + write_trouble(&dir, "strobe crash monitor: report: denied"); + let text = fs::read_to_string(dir.join(MONITOR_LOG)).unwrap_or_default(); + fs::remove_dir_all(&dir)?; + assert!( + text.contains("report: denied"), + "the stderr nobody reads is not the only copy: {text:?}" + ); + Ok(()) + } + #[test] fn the_report_and_notice_come_from_the_recorded_dump() -> Result<()> { let dir = diff --git a/crates/strobe-diag/src/failure.rs b/crates/strobe-diag/src/failure.rs index 51da9476..62960320 100644 --- a/crates/strobe-diag/src/failure.rs +++ b/crates/strobe-diag/src/failure.rs @@ -4,7 +4,7 @@ // path, phase, root error and recovery action, logged in one // greppable shape and kept in a bounded ring for the UI. // -// Dependencies: log; strobe_diag::context (via reports) +// Dependencies: log // ============================================================================ //! Actionable failures. @@ -264,10 +264,6 @@ mod tests { use super::*; use anyhow::Result; - /// The tests that fill the shared list take turns, so one cannot evict - /// what another is checking. - static SERIAL: Mutex<()> = Mutex::new(()); - #[test] fn a_failure_renders_in_the_documented_shape() -> Result<()> { let failure = Failure::new(Subsystem::Shader, "link") @@ -318,7 +314,7 @@ mod tests { #[test] fn reported_failures_are_kept_in_order_and_bounded() -> Result<()> { - let _turn = SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _turn = crate::test_turns::failures(); for index in 0..(KEPT + 5) { report(Failure::new(Subsystem::Script, "eval").message(format!("boom {index}"))); } @@ -335,7 +331,7 @@ mod tests { #[test] fn a_failure_that_keeps_coming_back_does_not_push_the_others_out() -> Result<()> { - let _turn = SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _turn = crate::test_turns::failures(); report( Failure::new(Subsystem::Shader, "link") .scene("flood-test-cathedral") diff --git a/crates/strobe-diag/src/lib.rs b/crates/strobe-diag/src/lib.rs index c9541046..f1aad05c 100644 --- a/crates/strobe-diag/src/lib.rs +++ b/crates/strobe-diag/src/lib.rs @@ -26,7 +26,8 @@ //! - [`diag`]: the `--diagnose` report. //! //! [`init`] wires up the first four in the right order. The only unsafe -//! code is one call in [`native`]. +//! code is in [`native`]: the crash handler's callback, and on Windows the +//! power request. //! //! ## Integration, in order //! @@ -71,6 +72,29 @@ pub mod system; pub use panic_hook::install_panic_hook; +/// Locks the tests of this crate share across modules, so one test cannot +/// pull process-wide state from under another running in parallel. +#[cfg(test)] +pub(crate) mod test_turns { + use std::sync::{Mutex, MutexGuard, PoisonError}; + + /// The process's one panic hook: a test that swaps it must not run + /// while another installs ours, or the restore drops ours for good. + static PANIC_HOOK: Mutex<()> = Mutex::new(()); + + /// The shared list of recent failures: a test that floods it must not + /// evict what another is looking for. + static FAILURES: Mutex<()> = Mutex::new(()); + + pub(crate) fn panic_hook() -> MutexGuard<'static, ()> { + PANIC_HOOK.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub(crate) fn failures() -> MutexGuard<'static, ()> { + FAILURES.lock().unwrap_or_else(PoisonError::into_inner) + } +} + use std::path::PathBuf; /// What [`init`] set up. diff --git a/crates/strobe-diag/src/logger.rs b/crates/strobe-diag/src/logger.rs index 480cf512..07ddff4d 100644 --- a/crates/strobe-diag/src/logger.rs +++ b/crates/strobe-diag/src/logger.rs @@ -53,9 +53,9 @@ use std::fs::{self, File, OpenOptions}; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TrySendError, sync_channel}; use std::sync::{Arc, Mutex, OnceLock, PoisonError}; -use std::time::{Duration, SystemTime}; +use std::time::{Duration, Instant, SystemTime}; /// Records kept in the in-memory ring. pub const RING_LINES: usize = 2000; @@ -108,6 +108,31 @@ enum Message { Flush(SyncSender<()>), } +/// Asks the writer behind `sink` to flush and waits up to `timeout` for it. +fn request_flush(sink: &SyncSender, timeout: Duration) -> bool { + const RETRY: Duration = Duration::from_millis(2); + let deadline = Instant::now() + timeout; + let (ack_tx, ack_rx) = sync_channel(1); + // A full queue is the log storm before a crash, or the burst before a + // clean exit: the writer is behind, so wait for room until the + // deadline rather than give up with thousands of lines unwritten. + let mut message = Message::Flush(ack_tx); + loop { + match sink.try_send(message) { + Ok(()) => break, + Err(TrySendError::Full(back)) if Instant::now() < deadline => { + message = back; + std::thread::sleep(RETRY); + } + Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => return false, + } + } + match ack_rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(()) => true, + Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => false, + } +} + /// The `log::Log` implementation. Use [`init`] to install the global one; /// construct directly only in tests. #[derive(Debug)] @@ -183,11 +208,6 @@ impl Logger { self.path.as_deref() } - /// The filter in force. - pub fn filter(&self) -> &Filter { - &self.filter - } - /// The newest `count` records, oldest first. pub fn recent(&self, count: usize) -> Vec { let ring = self.ring.lock().unwrap_or_else(PoisonError::into_inner); @@ -217,14 +237,7 @@ impl Logger { let Some(sink) = &self.sink else { return true; }; - let (ack_tx, ack_rx) = sync_channel(1); - if sink.try_send(Message::Flush(ack_tx)).is_err() { - return false; - } - match ack_rx.recv_timeout(timeout) { - Ok(()) => true, - Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => false, - } + request_flush(sink, timeout) } /// Records pushed since the logger started, including those the ring @@ -347,7 +360,10 @@ fn open_session_file(dir: &Path) -> std::io::Result<(File, PathBuf)> { /// many were deleted. Age is the file's modification time, not the timestamp /// in its name: after a clock reset (a dead CMOS battery, no NTP) the newest /// logs carry the oldest-looking names, and name order would delete them -/// first (D397). Deletion failures (a log still open elsewhere) are skipped. +/// first (D397). Deletion failures are skipped. A log another Strobe process +/// still has open is not protected: Linux and Windows (Rust opens files +/// with `FILE_SHARE_DELETE`) both let it be deleted, so it is the count, +/// [`KEEP_LOGS`], that keeps a recent session's log. pub fn prune_old_logs(dir: &Path, keep: usize) -> usize { let Ok(entries) = fs::read_dir(dir) else { return 0; @@ -553,6 +569,31 @@ mod tests { use super::*; use anyhow::{Result, anyhow}; + #[test] + fn a_flush_waits_for_room_in_a_full_queue() -> Result<()> { + let (sink, lines) = sync_channel(1); + sink.try_send(Message::Line(Arc::from("queued")))?; + let writer = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(50)); + // The writer catches up: the queued line, then the flush. + for message in lines.iter() { + match message { + Message::Flush(ack) => { + let _ = ack.send(()); + return; + } + Message::Line(_) | Message::FileLine(_) => {} + } + } + }); + let flushed = request_flush(&sink, Duration::from_secs(5)); + // Closing the queue ends the stand-in writer whatever happened. + drop(sink); + let _ = writer.join(); + assert!(flushed, "a full queue is a reason to wait, not to give up"); + Ok(()) + } + fn scratch(name: &str) -> PathBuf { std::env::temp_dir().join(format!("strobe-diag-test-{}-{name}", std::process::id())) } diff --git a/crates/strobe-diag/src/native.rs b/crates/strobe-diag/src/native.rs index b38cc0e8..628b8d6f 100644 --- a/crates/strobe-diag/src/native.rs +++ b/crates/strobe-diag/src/native.rs @@ -40,9 +40,11 @@ where // in a compromised context, where calling non-async-signal-safe // functions or taking locks the crashed thread holds can deadlock or // misbehave. Its sole caller, `crash::start_monitor`, passes a closure - // that takes no lock without `try_lock`, performs no blocking I/O - // except writes to an already-connected local socket and a log flush - // that is bounded by a timeout, and never unwinds. The function itself + // that takes no lock without `try_lock`, does its I/O on an + // already-connected local socket (one `ping` waits for the monitor's + // reply) plus a log flush bounded by a timeout, and never unwinds. It + // does allocate, so a crash inside the allocator can stall it: that is + // a lost report, not memory unsafety (see `crash::on_crash`). The function itself // has no other preconditions: the closure is `Send + Sync + 'static` // by its bounds, so it may be called from any thread for the life of // the process. diff --git a/crates/strobe-diag/src/notify.rs b/crates/strobe-diag/src/notify.rs index 52d8b332..2167d322 100644 --- a/crates/strobe-diag/src/notify.rs +++ b/crates/strobe-diag/src/notify.rs @@ -81,8 +81,9 @@ pub fn is_unattended() -> bool { } /// Runs the notifier, if any and if someone is watching. A notifier that -/// panics must not take the crash path down with it, so the call is -/// isolated. +/// panics is caught here only in a build that unwinds and outside a panic +/// hook: under `panic = "abort"` (every release build) or inside the panic +/// hook, a panicking notifier aborts the process, so it must not panic. pub(crate) fn notify(notice: &CrashNotice) { if is_unattended() { return; diff --git a/crates/strobe-diag/src/panic_hook.rs b/crates/strobe-diag/src/panic_hook.rs index 2eb3490c..97442a4b 100644 --- a/crates/strobe-diag/src/panic_hook.rs +++ b/crates/strobe-diag/src/panic_hook.rs @@ -22,9 +22,11 @@ //! location to stderr); //! 5. run the app's notifier. //! -//! A panic inside the hook (or a second thread panicking while the first is -//! reporting) skips straight to the previous hook, so reporting can never -//! recurse or deadlock. +//! A second thread panicking while the first is reporting skips straight to +//! the previous hook, so reporting never recurses or deadlocks across +//! threads. A panic inside the hook on the same thread is not caught at +//! all: the standard library aborts at once ("panicked while processing +//! panic"), so the hook must not panic. //! //! When the process then aborts, the native handler in [`crate::crash`] //! fires for the abort signal and writes a minidump. It reuses this @@ -39,6 +41,7 @@ use std::panic::PanicHookInfo; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; /// Log records included in a crash report. pub const LOG_TAIL: usize = 200; @@ -48,13 +51,24 @@ const FAILURE_TAIL: usize = 20; static INSTALLED: AtomicBool = AtomicBool::new(false); static REPORTING: AtomicBool = AtomicBool::new(false); -static LAST_REPORT: Mutex> = Mutex::new(None); +static LAST_REPORT: Mutex> = Mutex::new(None); /// Where the most recent panic report was written, if a panic has been /// reported. Never blocks: the native crash handler calls this from a /// compromised context. pub fn last_report() -> Option { - LAST_REPORT.try_lock().ok()?.clone() + fresh(LAST_REPORT.try_lock().ok()?.as_ref()?, Instant::now()) +} + +/// The report's path when it was written recently enough to be the panic +/// a native abort now follows. +fn fresh(entry: &(PathBuf, Instant), now: Instant) -> Option { + // Under `panic = "abort"` the abort follows the report at once. A dev + // build can catch a panic and run on; a native crash hours later is + // not that panic's, and must get its own report and notice. + const RECENT: Duration = Duration::from_secs(30); + let (path, written) = entry; + (now.saturating_duration_since(*written) <= RECENT).then(|| path.clone()) } /// Installs the panic hook, chaining to whatever hook was set before. @@ -125,7 +139,8 @@ fn handle(info: &PanicHookInfo<'_>, dir: &std::path::Path) -> Option { log::error!(target: "strobe_diag::panic", "crash report written to {}", path.display()); - *LAST_REPORT.lock().unwrap_or_else(PoisonError::into_inner) = Some(path.clone()); + *LAST_REPORT.lock().unwrap_or_else(PoisonError::into_inner) = + Some((path.clone(), Instant::now())); Some(path) } Err(error) => { @@ -148,11 +163,32 @@ mod tests { use anyhow::{Result, anyhow}; use std::fs; + #[test] + fn an_old_panic_report_is_not_claimed_by_a_later_native_crash() -> Result<()> { + let written = Instant::now(); + let entry = (PathBuf::from("crash-20261008-120003.txt"), written); + assert_eq!( + fresh(&entry, written + Duration::from_secs(1)), + Some(entry.0.clone()), + "the abort right after a panic finds its report" + ); + let later = written + .checked_add(Duration::from_secs(3600)) + .ok_or_else(|| anyhow!("clock overflow"))?; + assert_eq!( + fresh(&entry, later), + None, + "a dev build's caught panic an hour ago is not this crash's report" + ); + Ok(()) + } + #[test] fn a_panic_leaves_a_report_with_message_location_thread_and_backtrace() -> Result<()> { let dir = std::env::temp_dir().join(format!("strobe-diag-test-{}-panic", std::process::id())); let target = dir.clone(); + let _turn = crate::test_turns::panic_hook(); install_with(move || target.clone()); context::set("test.panic", "context-survives"); diff --git a/crates/strobe-web/README.md b/crates/strobe-web/README.md index 53201662..244ffcff 100644 --- a/crates/strobe-web/README.md +++ b/crates/strobe-web/README.md @@ -70,11 +70,13 @@ IDs given here; a gap with no ID is by design, with its decision named. scenes compile and play, an edit's error marks its line, a scripted scene runs in the worker, share links round-trip. Other browsers and phones are not yet tried (backlog W-02). -- A `MEDIA` folder (an image sequence), the Shadertoy audio texture and the - meta controls are not in the browser; `IMAGES`, `#include`, - `textureFinalPass` and presets are (D554), and so are cube maps and a still - `MEDIA` picture from pictures the visitor adds (D564). An include of lygia - or hg_sdf works only when the scene holds the file (backlog W-01). +- A `MEDIA` folder (an image sequence) and the meta controls are not in the + browser; `IMAGES`, `#include`, `textureFinalPass` and presets are (D554), + cube maps and a still `MEDIA` picture from pictures the visitor adds + (D564), and the Shadertoy audio texture from live audio (D577). An include + of lygia or hg_sdf works only when the scene holds the file, and Generate + controls measures a cube-map or still-`MEDIA` scene without its pictures + (backlog W-01). - The native tests skip where there is no headless EGL, as on Windows; CI's Linux job runs them, and its `check` lane clippies this crate and strobe-gfx for `wasm32-unknown-unknown` (D544, D552). CI's `site` job diff --git a/crates/strobe-web/src/lib.rs b/crates/strobe-web/src/lib.rs index 59a187cc..5cea1d4d 100644 --- a/crates/strobe-web/src/lib.rs +++ b/crates/strobe-web/src/lib.rs @@ -4,7 +4,8 @@ // WebGL2 canvas, compiled to wasm for the website's /play page. // // Dependencies: strobe-gfx (without `native`), strobe-scene, strobe-audio -// (without `capture`); wasm-bindgen, web-sys (wasm32 only) +// (without `capture`), strobe-autocontrol, serde_json; +// wasm-bindgen, js-sys, web-sys, log (wasm32 only) // ============================================================================ //! The engine behind the website's shader sandbox (D524). @@ -20,7 +21,7 @@ //! //! ```text //! cargo build -p strobe-web --target wasm32-unknown-unknown --profile release-web -//! wasm-bindgen --target web --out-dir site/public/engine target/wasm32-unknown-unknown/release-web/strobe_web.wasm +//! wasm-bindgen --target web --no-typescript --out-dir site/public/generated/engine target/wasm32-unknown-unknown/release-web/strobe_web.wasm //! ``` //! //! which `npm run engine` in `site/` does. diff --git a/crates/strobe-web/src/sandbox.rs b/crates/strobe-web/src/sandbox.rs index 36b2eea4..4aef113c 100644 --- a/crates/strobe-web/src/sandbox.rs +++ b/crates/strobe-web/src/sandbox.rs @@ -6,7 +6,7 @@ // // Dependencies: strobe-gfx (player), strobe-scene (scene, controls, // presets, synthetic audio), strobe-audio (analyser), -// serde_json +// strobe-autocontrol (Generate controls), serde_json // ============================================================================ //! The sandbox engine. @@ -103,6 +103,8 @@ struct Audio { source: AudioSource, analyzer: Analyzer, scalars: Vec, + /// [`silent_scalars`], made once: silence is copied in each frame. + silent: Vec, spectrum: Vec<[f32; 4]>, level_trail: Vec<[f32; 4]>, /// The analyser's Shadertoy texture bytes while live, empty otherwise @@ -126,6 +128,7 @@ impl Audio { source: AudioSource::Synthetic, analyzer: Analyzer::new(sample_rate), scalars: silent_scalars(), + silent: silent_scalars(), spectrum: vec![SILENT_TEXEL; SPECTRUM_TEXELS], level_trail: vec![[0.0; 4]; TRAIL_TEXELS], shadertoy: Vec::new(), @@ -153,7 +156,8 @@ impl Audio { self.shadertoy.clone_from(&frame.shadertoy); } AudioSource::Silent => { - self.scalars = silent_scalars(); + // In place: a frame path does not allocate. + self.scalars.clone_from(&self.silent); self.spectrum.fill(SILENT_TEXEL); self.level_trail.fill([0.0; 4]); self.shadertoy.clear(); @@ -179,7 +183,10 @@ pub struct FrameRequest { pub dt: f32, /// Frames since the scene started. pub frame: u64, - /// The mouse, already in render pixels with the origin bottom-left. + /// The mouse in canvas pixels with the origin bottom-left (`muv` and + /// `muvc` are recomputed): [`Sandbox::frame`] maps it into the picture + /// through [`canvas_mouse`], which differs from the canvas for a scene + /// that pins its size (D280). pub mouse: Mouse, /// The wall clock, for `strobe_Date`. pub unix_seconds: f64, @@ -189,7 +196,10 @@ pub struct FrameRequest { pub struct Sandbox { gl: Gl, caps: Caps, + /// The canvas, which the picture is presented into. size: [i32; 2], + /// The largest render side: the driver's texture limit, at most 8192. + limit: i32, scene: Option, audio: Audio, /// A Generate controls in progress. Dropping it cancels it. @@ -212,11 +222,14 @@ fn generate_options() -> GenerateOptions { impl Sandbox { /// A sandbox drawing into `gl`'s default framebuffer at `size` pixels. pub fn new(gl: Gl, size: [i32; 2], sample_rate: u32) -> Self { + const MAX: i32 = 8192; let caps = Caps::from_info(gl.info()); + let limit = caps.info.max_texture_size.clamp(1, MAX); Self { gl, caps, size: clamp_size(size), + limit, scene: None, audio: Audio::new(sample_rate), generating: None, @@ -261,7 +274,7 @@ impl Sandbox { &self.gl, &self.caps, &scene, - self.size, + fit_size(self.size, self.limit), Options::default(), &extras, ) @@ -292,9 +305,10 @@ impl Sandbox { } /// What the loaded scene names that is not here, as a JSON array of - /// lines: an `IMAGES` picture the page has not added, a cube map or - /// `MEDIA`, which the browser does not load. `[]` when nothing is - /// missing or with no scene. + /// lines: an `IMAGES` picture, cube face or still `MEDIA` picture the + /// page has not added or that would not decode, and a `MEDIA` folder, + /// which the browser does not play. `[]` when nothing is missing or + /// with no scene. pub fn notes_json(&self) -> String { let notes = self.scene.as_ref().map_or(&[][..], |scene| &scene.notes); json!(notes).to_string() @@ -339,8 +353,8 @@ impl Sandbox { /// Applies a preset's text to the scene's controls as targets, as the /// app does (a smoothed control eases to it). Returns what could not be - /// applied, one line each. Its meta channel is ignored: the sandbox has - /// no meta controls. + /// applied, one line each. Its meta and media channels are ignored: the + /// sandbox has no meta controls and no media picker. pub fn apply_preset(&mut self, text: &str) -> Result, String> { let mut preset = Preset::from_text(text).map_err(|e| format!("preset: {e}"))?; preset.channels.meta = false; @@ -595,7 +609,7 @@ impl Sandbox { if let Some(scene) = &mut self.scene { scene .player - .resize_keeping(size) + .resize_keeping(fit_size(size, self.limit)) .map_err(|e| e.to_string())?; } self.size = size; @@ -629,10 +643,11 @@ impl Sandbox { level_trail: &self.audio.level_trail, shadertoy: Some(&self.audio.shadertoy), }); + let mouse = canvas_mouse(request.mouse, self.size, scene.player.render_size()); scene.player.render(&FrameInputs { time: request.time, frame: request.frame, - mouse: request.mouse, + mouse, audio: &self.audio.scalars, controls: &scene.controls, transitions: &scene.transitions, @@ -640,8 +655,9 @@ impl Sandbox { scene.player.present(self.size); } - /// The finished frame as RGBA8, top row first: the page's thumbnail - /// and the tests' look at the picture. Empty with no scene. + /// The finished frame as RGBA8, top row first: the native tests' look at + /// the picture (the page takes its thumbnails from the canvas). Empty + /// with no scene. pub fn read_output(&self) -> Vec { self.scene .as_ref() @@ -652,7 +668,9 @@ impl Sandbox { pub fn render_size(&self) -> [i32; 2] { self.scene .as_ref() - .map_or(self.size, |scene| scene.player.render_size()) + .map_or(fit_size(self.size, self.limit), |scene| { + scene.player.render_size() + }) } } @@ -674,9 +692,10 @@ fn progress_json(job: &Job) -> String { } /// A path's file name: the page keeps no folders, so a picture a scene -/// names by `images/sky.png` is found as `sky.png` too. +/// names by `images/sky.png` (or `images\sky.png`, as a scene written on +/// Windows may) is found as `sky.png` too. fn base_name(path: &str) -> &str { - path.rsplit('/').next().unwrap_or(path) + path.rsplit(['/', '\\']).next().unwrap_or(path) } /// Uploads each picture the scene names that the page holds, found by the @@ -779,8 +798,91 @@ pub fn extra_type(dims: usize) -> Option { } } -/// A canvas size the player accepts: at least one pixel, at most 8192. +/// A canvas size: at least one pixel each way. fn clamp_size(size: [i32; 2]) -> [i32; 2] { - const MAX: i32 = 8192; - size.map(|n| n.clamp(1, MAX)) + size.map(|n| n.max(1)) +} + +/// `size` as a render size the driver can allocate: each side `1..=limit`, +/// scaled down whole so the picture keeps its shape (`present` letterboxes +/// it into the canvas). WebGL 2 promises only 2048 and many GPUs 4096; a +/// fullscreen canvas on a wide screen is more. +pub fn fit_size(size: [i32; 2], limit: i32) -> [i32; 2] { + let [w, h] = clamp_size(size); + let limit = limit.max(1); + let longest = w.max(h); + if longest <= limit { + return [w, h]; + } + let scale = f64::from(limit) / f64::from(longest); + [w, h].map(|n| ((f64::from(n) * scale).round() as i32).clamp(1, limit)) +} + +/// The script uniforms the worker reported, `[[name, dims], ...]`, as the +/// player declares them. +pub fn parse_extras(json: &str) -> Result, String> { + // Refused, not skipped: `set_script_uniforms` takes four floats per + // uniform in this order, so a dropped one would shift every later one. + serde_json::from_str::>(json) + .map_err(|e| format!("script uniforms: {e}"))? + .into_iter() + .map(|(name, dims)| match extra_type(dims) { + Some(ty) => Ok((name, ty)), + None => Err(format!( + "script uniform `{name}` has {dims} components; 1 to 4 are allowed" + )), + }) + .collect() +} + +/// The page's pointer, in canvas pixels with the origin bottom-left, in +/// the render pixels of a picture `present` letterboxes into the canvas. +pub fn canvas_mouse(mouse: Mouse, canvas: [i32; 2], render: [i32; 2]) -> Mouse { + // As the app's `mouse::to_render` does for the window, and as + // `ScenePlayer::present` draws: scaled to fit, centred. + let (cw, ch) = (canvas[0].max(1) as f32, canvas[1].max(1) as f32); + let (w, h) = (render[0].max(1) as f32, render[1].max(1) as f32); + let scale = (cw / w).min(ch / h); + let (left, bottom) = ((cw - w * scale) / 2.0, (ch - h * scale) / 2.0); + let to_render = |x: f32, y: f32| { + [ + ((x - left) / scale).clamp(0.0, w), + ((y - bottom) / scale).clamp(0.0, h), + ] + }; + let [x, y] = to_render(mouse.mouse[0], mouse.mouse[1]); + // The click's sign says whether a button is held; zero is no click yet. + let [cx, cy] = if mouse.mouse[2] == 0.0 && mouse.mouse[3] == 0.0 { + [0.0, 0.0] + } else { + let sign = if mouse.mouse[2] < 0.0 || mouse.mouse[3] < 0.0 { + -1.0 + } else { + 1.0 + }; + to_render(mouse.mouse[2].abs(), mouse.mouse[3].abs()).map(|v| v * sign) + }; + Mouse { + mouse: [x, y, cx, cy], + click: mouse.click, + muv: [x / w, y / h], + muvc: [(x - 0.5 * w) / h, (y - 0.5 * h) / h], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_picture_is_found_by_its_file_name_whichever_separator() -> anyhow::Result<()> { + assert_eq!(base_name("sky.png"), "sky.png", "a bare name"); + assert_eq!(base_name("images/sky.png"), "sky.png", "a folder, slash"); + assert_eq!( + base_name(r"images\sky.png"), + "sky.png", + "a folder written on Windows" + ); + Ok(()) + } } diff --git a/crates/strobe-web/src/web.rs b/crates/strobe-web/src/web.rs index a0d128c0..84fad320 100644 --- a/crates/strobe-web/src/web.rs +++ b/crates/strobe-web/src/web.rs @@ -3,7 +3,8 @@ // Description: The wasm-bindgen surface the /play page calls: a canvas's // WebGL2 context wrapped as a Sandbox. // -// Dependencies: wasm-bindgen, js-sys, web-sys; crate::sandbox +// Dependencies: wasm-bindgen, js-sys, web-sys, serde_json, log; +// strobe-gfx, strobe-scene; crate::sandbox // ============================================================================ //! The JavaScript API. @@ -13,7 +14,7 @@ //! come back as `Err(string)`, which wasm-bindgen throws as a JavaScript //! exception the page catches and shows in the editor. -use crate::sandbox::{AudioSource, FrameRequest, Sandbox, extra_type}; +use crate::sandbox::{AudioSource, FrameRequest, Sandbox, parse_extras}; use strobe_gfx::Mouse; use strobe_gfx::gl::Gl; use wasm_bindgen::JsCast; @@ -120,12 +121,7 @@ impl Engine { assets: JsValue, extras: &str, ) -> Result { - let extras: Vec<(String, strobe_scene::assemble::ExtraType)> = - serde_json::from_str::>(extras) - .map_err(|e| format!("script uniforms: {e}"))? - .into_iter() - .filter_map(|(name, dims)| extra_type(dims).map(|ty| (name, ty))) - .collect(); + let extras = parse_extras(extras)?; let file = |name: &str| file_text(&files, name); let asset = |name: &str| asset_bytes(&assets, name); self.sandbox.load(title, file, asset, extras) @@ -178,8 +174,9 @@ impl Engine { .generate_apply(title, |name| file_text(&files, name), choices) } - /// What the scene names that is not here (a picture not added, a cube - /// map), as a JSON array of lines. + /// What the scene names that is not here (a picture, cube face or + /// `MEDIA` still not added or not decodable, a `MEDIA` folder), as a + /// JSON array of lines. #[wasm_bindgen(js_name = notesJson)] pub fn notes_json(&self) -> String { self.sandbox.notes_json() @@ -233,7 +230,10 @@ impl Engine { self.sandbox.control_outputs_json() } - /// The script uniforms the scene was built with, as JSON. + /// The script uniforms the scene was built with, as JSON. Declared in + /// the page's `engine.ts` but not called there today; kept for the + /// page's debugging and checked by the native tests through + /// `Sandbox::extras_json`. #[wasm_bindgen(js_name = extrasJson)] pub fn extras_json(&self) -> String { self.sandbox.extras_json() @@ -310,11 +310,12 @@ impl Engine { } /// Draws one frame. `mouse` is `[x, y, click x, click y, left, right, - /// middle]` in render pixels from the bottom left, the click position - /// negated while no button is held, as `_mouse` wants it. + /// middle]` in canvas pixels from the bottom left, the click position + /// negated while no button is held, as `_mouse` wants it; the sandbox + /// maps it into the picture. #[expect( clippy::too_many_arguments, - reason = "a flat call keeps the per-frame crossing allocation-free" + reason = "flat numbers cross the JS boundary without building an object each frame" )] pub fn frame( &mut self, diff --git a/crates/strobe-web/tests/sandbox.rs b/crates/strobe-web/tests/sandbox.rs index 878889d9..dd10bcaa 100644 --- a/crates/strobe-web/tests/sandbox.rs +++ b/crates/strobe-web/tests/sandbox.rs @@ -5,7 +5,8 @@ // // Dependencies: anyhow, serde_json; strobe-web (sandbox), strobe-gfx // (headless context, the app's player), strobe-scene (scene -// folders, presets); the corpus gate's fixture scenes +// folders, presets), strobe-autocontrol (the app's generate), +// strobe-audio (the analyser); the corpus gate's fixture scenes // ============================================================================ //! The sandbox's behaviour the /play page depends on, without a browser. @@ -30,7 +31,9 @@ use serde_json::{Value, json}; use strobe_autocontrol::{Options as GenerateOptions, generate, rewritten_files}; use strobe_gfx::{Api, Caps, Headless}; use strobe_scene::SceneFolder; -use strobe_web::sandbox::{AudioSource, FrameRequest, Sandbox, extra_type}; +use strobe_web::sandbox::{ + AudioSource, FrameRequest, Sandbox, canvas_mouse, extra_type, fit_size, parse_extras, +}; fn headless() -> Result> { match Headless::new(Api::Gles30) { @@ -78,6 +81,103 @@ fn draw(sandbox: &mut Sandbox, frame: u64) { }); } +#[test] +fn silence_allocates_nothing_per_frame() -> Result<()> { + let Some(headless) = headless()? else { + return Ok(()); + }; + let mut sandbox = Sandbox::new(headless.gl().clone(), SIZE, 48_000); + sandbox.set_audio_source(AudioSource::Silent); + draw(&mut sandbox, 0); + let before = sandbox.audio_scalars().as_ptr(); + draw(&mut sandbox, 1); + let after = sandbox.audio_scalars().as_ptr(); + assert_eq!( + before, after, + "the silent scalars are written in place, not reallocated" + ); + Ok(()) +} + +#[test] +fn the_canvas_is_fitted_to_the_drivers_texture_limit() -> Result<()> { + assert_eq!(fit_size([640, 360], 4096), [640, 360], "within the limit"); + assert_eq!(fit_size([0, -5], 4096), [1, 1], "at least a pixel"); + assert_eq!( + fit_size([5120, 1440], 4096), + [4096, 1152], + "a canvas over the limit keeps its shape" + ); + assert_eq!(fit_size([2048, 9000], 2048), [466, 2048], "either side"); + Ok(()) +} + +#[test] +fn a_bad_script_uniform_size_is_refused_not_dropped() -> Result<()> { + let extras = parse_extras(r#"[["a",2],["b",1]]"#).map_err(|e| anyhow!(e))?; + assert_eq!(extras.len(), 2, "both declared"); + assert!( + parse_extras(r#"[["a",5],["b",1]]"#).is_err(), + "dropping `a` would shift `b` onto `a`'s values" + ); + Ok(()) +} + +#[test] +fn the_pointer_follows_a_letterboxed_picture() -> Result<()> { + // A scene pinned to 32x18 shown in a 64x18 canvas: the picture spans + // canvas x 16..48. The page sends canvas pixels. + let at = |x: f32, y: f32| strobe_gfx::Mouse { + mouse: [x, y, 0.0, 0.0], + click: [0.0; 3], + muv: [0.0; 2], + muvc: [0.0; 2], + }; + let left = canvas_mouse(at(16.0, 9.0), [64, 18], [32, 18]); + assert!( + left.mouse[0].abs() < 1e-3, + "the picture's left edge is x 0: {:?}", + left.mouse + ); + assert!( + left.muv[0].abs() < 1e-3 && (left.muv[1] - 0.5).abs() < 1e-3, + "muv {:?}", + left.muv + ); + let centre = canvas_mouse(at(32.0, 9.0), [64, 18], [32, 18]); + assert!( + (centre.mouse[0] - 16.0).abs() < 1e-3, + "the centre: {:?}", + centre.mouse + ); + assert!( + centre.muvc[0].abs() < 1e-3, + "muvc centred: {:?}", + centre.muvc + ); + let outside = canvas_mouse(at(4.0, 9.0), [64, 18], [32, 18]); + assert!( + outside.mouse[0].abs() < 1e-3, + "clamped to the picture: {:?}", + outside.mouse + ); + let mut clicked = at(48.0, 18.0); + clicked.mouse[2] = -48.0; + clicked.mouse[3] = -18.0; + let released = canvas_mouse(clicked, [64, 18], [32, 18]); + assert!( + (released.mouse[2] + 32.0).abs() < 1e-3 && (released.mouse[3] + 18.0).abs() < 1e-3, + "a released click keeps its sign: {:?}", + released.mouse + ); + let same = canvas_mouse(at(10.0, 5.0), [32, 18], [32, 18]); + assert!( + (same.mouse[0] - 10.0).abs() < 1e-3, + "no letterbox, no change" + ); + Ok(()) +} + #[test] fn a_scene_loads_draws_and_its_controls_move_it() -> Result<()> { let Some(headless) = headless()? else { @@ -801,13 +901,18 @@ fn a_scene_folders_picture_and_the_pages_are_measured_alike() -> Result<()> { (name == "mark.png").then(|| mark.clone()) }) .map_err(|e| anyhow!(e))?; - let review = loop { + // Bounded, as `generate_steps` is: a job that never ends fails the test + // instead of hanging CI. + let mut review = None; + for _ in 0..50_000_000_u64 { let answer: Value = serde_json::from_str(&sandbox.generate_step().map_err(|e| anyhow!(e))?)?; if answer["state"] == "done" { - break answer; + review = Some(answer); + break; } - }; + } + let review = review.ok_or_else(|| anyhow!("the generation never finished"))?; let mut listed = names(&review); listed.sort(); let mut kept = app.report.kept.clone(); diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index db1f18e4..b3d62f04 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "xtask" -description = "The workspace's own tooling: `cargo xtask ci`, `changelog`, `credits`, `bench`, `symbolicate` and `brand`." +description = "The workspace's own tooling: `cargo xtask ci`, `changelog`, `credits`, `decisions`, `bench`, `corpus`, `package`, `package-check`, `rc`, `sbom-native`, `symbolicate` and `brand`." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/xtask/README.md b/crates/xtask/README.md index ef43d1bd..2268a9e1 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -10,8 +10,11 @@ is built, linted and tested by the same `--workspace` commands as the rest. - **Depends on:** `clap`, `anyhow`, `serde_json` (`cargo metadata` for `credits`), `sha2` (the native DLLs' hashes, D536) and `resvg` (the - icons). It shells out to `cargo`, `rustc` and `git`, and optionally - `cargo-deny`. + icons). It shells out to `cargo`, `rustc` and `git`, and, for the lanes + and commands that need them, `cargo-deny`, `xvfb-run`, `actionlint`, + `shellcheck`, `powershell`, `npm`, `wasm-bindgen`, `tar`, `taskkill` + (or `ps` and `kill`, to stop a step's whole process tree at its + timeout), `dump_syms` and `minidump-stackwalk`. - **Depended on by:** nothing. It is a binary with no library API. - **Does not:** link against any other Strobe crate, or parse `strobe-bench`'s flags (they are forwarded untouched). The `xtask` alias in @@ -85,15 +88,18 @@ Flags, from the clap definitions: [`docs/DEBUGGING.md`](../../docs/DEBUGGING.md). - `brand`: `--check`. Renders `icon-small.svg` at 16-32 px and `icon.svg` at 48-512 px with resvg (no fonts, so the bytes depend only on - `Cargo.lock`), and packs `icon.ico`. See D190 and + `Cargo.lock`), packs `icon.ico`, and renders the banner, the lockups, the + maskable icon and the social preview. See D190 and [`assets/brand/README.md`](../../assets/brand/README.md). Environment: `cargo xtask ci` sets `STROBE_REQUIRE_HEADLESS_GL=1` for the test step on Linux (unless you already set it or pass `--allow-gl-skip`), so a missing Mesa EGL fails loudly instead of every renderer test skipping. On Linux it also sets `STROBE_TEST_LAN=1` (unless you set it), so the few tests that bind -every interface run; elsewhere they skip unless you set it, because on Windows -that bind makes the firewall ask about each new test binary (D503). It also +every interface run; it sets it on any CI runner too, which is why the Windows +job runs them. On a person's Windows machine they skip unless you set it, +because there that bind makes the firewall ask about each new test binary +(D503). It also honours `CARGO` and `RUSTC` if set. `clippy no-midi` is `cargo clippy -p strobe-io --no-default-features @@ -101,12 +107,15 @@ honours `CARGO` and `RUSTC` if set. feature, which `--all-features` never builds. It runs on Linux only and is skipped, with that reason, elsewhere. -Some steps skip with a stated reason and the command that enables them: the -Windows clippy when the `x86_64-pc-windows-msvc` standard library is not -installed (`rustup target add x86_64-pc-windows-msvc`; `rust-toolchain.toml` -lists the target) or the host is already that target, and `cargo-deny` when it -is not installed (`cargo install cargo-deny --locked`). The Windows step -excludes `strobe-script` and `strobe-app` (D63). +Some steps report `MISSING` with the command that enables them, which makes +the run "partial" and fails it under `--strict`: the Windows clippy when the +`x86_64-pc-windows-msvc` standard library is not installed (`rustup target add +x86_64-pc-windows-msvc`; `rust-toolchain.toml` lists the target), and +`cargo-deny` when it is not installed (`cargo install cargo-deny --locked`). +The Windows step is `n/a` on a host that is already that target. It excludes +`strobe-script` and `strobe-app` (D63), and `strobe-shadertoy` and +`strobe-forge`, which a second step checks without their TLS features (D110). +A step that runs past its timeout is stopped with everything it started. `CHANGELOG.md` is generated: never edit it by hand. The release order is in [`CONTRIBUTING.md`](../../CONTRIBUTING.md): bump the version, write the diff --git a/crates/xtask/src/ci.rs b/crates/xtask/src/ci.rs index 9ee6cdf5..a4fd52de 100644 --- a/crates/xtask/src/ci.rs +++ b/crates/xtask/src/ci.rs @@ -4,9 +4,10 @@ // named lanes with the host policy in Rust, a strict mode for CI // and a doctor that lists what this machine can run. // -// Dependencies: clap, anyhow, std::process; crate::changelog, crate::brand -// and crate::credits (the in-process changelog, icon and -// credits checks) +// Dependencies: clap, anyhow, std::process; crate::changelog, crate::brand, +// crate::credits and crate::decisions (the in-process +// generated-file checks), crate::package (the package lane), +// crate::process (stopping a step at its timeout) // ============================================================================ //! `cargo xtask ci`: what CI runs, without the push, and what CI runs, full @@ -27,8 +28,8 @@ //! | `lint` | Linux: actionlint over the workflows and shellcheck over the `.sh` scripts; Windows: PSScriptAnalyzer over the `.ps1` scripts (D541) | `rustfmt`, `windows` | //! | `check` | clippy `-D warnings` over the workspace; on Linux also `strobe-io`, `strobe-audio`, `strobe-shadertoy` and `strobe-forge` each without its default feature, `strobe-web` and `strobe-gfx` for `wasm32-unknown-unknown` (D544, D552), rustdoc with `-D warnings`, and the Windows cross-check (D541); on macOS the portable crates only | each platform job | //! | `test` | `cargo test --workspace --all-features`; on macOS the portable crates | each platform job | -//! | `deny` | `cargo deny check` | `cargo-deny` | -//! | `generated` | the changelog, icon and credits checks | `changelog` | +//! | `deny` | `cargo deny --locked check` | `cargo-deny` | +//! | `generated` | the changelog, icon, credits and decisions checks | `changelog` | //! | `render` | Linux: the app on Xvfb, auto-controls on a window context, the scene library in both GLSL dialects, the corpus gate (D534) | `linux` | //! | `build` | Windows: the `release-fast` binaries, and with `--shipping` the fat-LTO `release` ones | `windows` | //! | `package` | Windows: the release zip from that build, unpacked outside the checkout and checked (D537) | `windows` | @@ -155,7 +156,7 @@ enum Lane { Test, /// cargo-deny. Deny, - /// The changelog, icon and credits checks. + /// The changelog, icon, credits and decisions checks. Generated, /// The app, auto-controls and scene library on a real GL driver (Linux). Render, @@ -484,7 +485,9 @@ fn plan(lanes: &[Lane], args: &Args, machine: &Machine, tree: Option) -> if args.no_deny { Action::NotHere("--no-deny".to_owned()) } else if machine.deny { - cargo(machine, &["deny", "check"]) + // `--locked` is cargo-deny's global flag: its metadata + // step must not rewrite a stale lockfile either. + cargo(machine, &["deny", "--locked", "check"]) } else { Action::Missing { why: "cargo-deny is not installed".to_owned(), @@ -1166,7 +1169,7 @@ fn execute_all(steps: &[Step], strict: bool, machine: &Machine) -> Result<()> { if failure.is_some() && not_run > 0 { let _ = writeln!(summary, " not run {not_run} step(s) after the failure"); } - if let Some(skips) = skips_note(&machine.skip_log) { + if let Some(skips) = skips_for(steps, &machine.skip_log) { summary.push_str(&skips); } println!("\n{summary}"); @@ -1202,6 +1205,17 @@ fn step_summary(summary: &str) { } } +/// The skip note for a run of `steps`: none unless the run tested, since +/// the log is cleared only when the test lane runs and an older one is +/// another run's. +fn skips_for(steps: &[Step], log: &Path) -> Option { + steps + .iter() + .any(|step| step.lane == Lane::Test) + .then(|| skips_note(log)) + .flatten() +} + /// How many tests skipped and why, from the log the GPU tests wrote /// (`test\treason` per line), or nothing when none did. A skipped test /// passed the harness, so this is the only place the difference shows. @@ -1351,11 +1365,10 @@ fn wait(mut child: Child, timeout: Option, program: &str) -> Outcome { if let Some(limit) = timeout && started.elapsed() > limit { - // Killed because it ran too long; the failure says so whether or - // not the kill itself worked. - let _ = child.kill(); - // Reaps it; the outcome is the timeout either way. - let _ = child.wait(); + // Killed because it ran too long, with whatever it started + // (Xvfb under xvfb-run, the test binary under cargo); the + // failure says so whether or not the kill itself worked. + crate::process::kill_tree(&mut child); return Outcome::Failed(format!( "{program} ran past its {} minute timeout and was stopped", limit.as_secs() / 60 @@ -1454,7 +1467,10 @@ fn lint_lane(steps: &mut Vec, machine: &Machine) { )); } Host::Windows => { - let files: Vec = powershell.iter().map(|f| format!("'{f}'")).collect(); + let files: Vec = powershell + .iter() + .map(|f| crate::package::ps_quote(f)) + .collect(); // Every rule at warning and above, but one: these scripts are // run by a person at a console (install, network setup, the // ANGLE fetch), and what they print is meant for that person, @@ -1694,6 +1710,34 @@ mod tests { ); } + #[test] + fn a_run_without_tests_does_not_report_an_old_skip_log() -> Result<()> { + let dir = std::env::temp_dir().join(format!("xtask-skips-{}", std::process::id())); + std::fs::create_dir_all(&dir)?; + let log = dir.join("test-skips.log"); + std::fs::write(&log, "render::a\tno headless context (EGL)\n")?; + let render = plan( + &[Lane::Render], + &args(&[Lane::Render]), + &machine(Host::Linux), + None, + ); + let test = plan( + &[Lane::Test], + &args(&[Lane::Test]), + &machine(Host::Linux), + None, + ); + let (without, with) = (skips_for(&render, &log), skips_for(&test, &log)); + std::fs::remove_dir_all(&dir)?; + assert!( + without.is_none(), + "an earlier run's skips are not this run's: {without:?}" + ); + assert!(with.is_some(), "a run with the test lane reports its skips"); + Ok(()) + } + #[test] fn every_dependency_resolving_cargo_command_is_locked() { for host in [Host::Linux, Host::Windows, Host::MacOs] { @@ -1709,9 +1753,9 @@ mod tests { if program.starts_with("npm") { continue; } - let resolving = args - .iter() - .any(|a| ["build", "clippy", "test", "run"].contains(&a.as_str())); + let resolving = args.iter().any(|a| { + ["build", "clippy", "test", "run", "doc", "deny"].contains(&a.as_str()) + }); assert!( !resolving || args.iter().any(|a| a == "--locked"), "{host:?} {}: {}", diff --git a/crates/xtask/src/credits.rs b/crates/xtask/src/credits.rs index c269cb22..c8e46be1 100644 --- a/crates/xtask/src/credits.rs +++ b/crates/xtask/src/credits.rs @@ -27,9 +27,9 @@ //! One row per crate name, without its version, so a patch bump does not //! change the file and only a crate that arrives, leaves or changes //! licence does. -//! - **Shipped beside** is the ANGLE runtime the release zip carries next -//! to `strobe.exe`, with the Electron version read from -//! `scripts/native-deps.json` (D536). +//! - **Shipped beside** is the native runtime the release zip carries next +//! to `strobe.exe`: ANGLE, with the Electron version read from +//! `scripts/native-deps.json` (D536), and Spout's library (D576). //! //! `THIRD_PARTY.md` is committed, readable on GitHub, and compiled into the //! app, which draws its tables on the About page. `--check` regenerates it @@ -469,7 +469,8 @@ fn notices_text(packages: &[Package]) -> Result { licence and source, and the licence and notice files its package carries. Identical \ texts are printed once, at the end, and referred to by number.\n\n\ The ANGLE, Direct3D compiler and Vulkan loader DLLs beside strobe.exe come from \ - Electron; their notices are in LICENSES.chromium.html.\n\n\ + Electron; their notices are in LICENSES.chromium.html. SpoutLibrary.dll comes from \ + Spout; its licence is in LICENSE.spout.txt.\n\n\ Strobe itself is MIT with the Commons Clause: see LICENSE.\n" ); for package in packages { diff --git a/crates/xtask/src/main.rs b/crates/xtask/src/main.rs index 554cae5b..01675b53 100644 --- a/crates/xtask/src/main.rs +++ b/crates/xtask/src/main.rs @@ -1,11 +1,12 @@ // ============================================================================ // Module: xtask (binary crate root) // Description: The workspace's own tooling behind `cargo xtask`: the local -// CI runner, the changelog and credits generators, the bench -// shortcut, crash-dump symbolication, and the icon renderer. +// CI runner, the changelog, credits and decisions generators, +// the bench and corpus shortcuts, the release zip and its +// checks, crash-dump symbolication, and the icon renderer. // // Dependencies: clap, anyhow; modules brand, changelog, ci, credits, bench, -// corpus, decisions, native, package, rc, symbolicate +// corpus, decisions, native, package, process, rc, symbolicate // ============================================================================ //! `cargo xtask`: the repository's tooling, written in the repository's @@ -38,8 +39,9 @@ //! with no library API, so nothing links against it. //! //! Every command is run from the workspace root regardless of where it is -//! invoked: the root is baked in at compile time from this crate's -//! manifest directory, and the process changes into it before doing +//! invoked: the root comes from this crate's manifest directory (cargo's +//! `CARGO_MANIFEST_DIR` at run time, the compile-time one as the fallback; +//! see `workspace_root`), and the process changes into it before doing //! anything. That is what lets `cargo xtask ci` work from inside //! `crates/strobe-gfx`. @@ -52,6 +54,7 @@ mod credits; mod decisions; mod native; mod package; +mod process; mod rc; mod symbolicate; @@ -75,10 +78,11 @@ struct Cli { /// One subcommand per job. #[derive(Subcommand, Debug)] enum Command { - /// Run locally exactly what CI runs: fmt, clippy, the no-MIDI strobe-io - /// clippy (Linux), tests, the Windows cross-check, cargo-deny and the - /// changelog, icon and credits checks. Stops at the first failure and - /// says which step it was. + /// Run locally what CI runs, as lanes: fmt, lint, check (clippy, the + /// no-default-feature and wasm builds, rustdoc, the Windows + /// cross-check), test, deny, generated (changelog, icon, credits, + /// decisions), render, build, package and site, each where this host's + /// CI job runs it. Stops at the first failure and says which step it was. Ci(ci::Args), /// Regenerate CHANGELOG.md from the git history. Changelog { diff --git a/crates/xtask/src/native.rs b/crates/xtask/src/native.rs index ea3ec802..c5cf52df 100644 --- a/crates/xtask/src/native.rs +++ b/crates/xtask/src/native.rs @@ -72,7 +72,7 @@ pub(crate) fn sha256(path: &Path) -> Result { /// The bundles the manifest pins, each a download whose files ship beside /// `strobe.exe`: ANGLE (D536) and Spout's library (D576). -pub(crate) const BUNDLES: [&str; 2] = ["angle", "spout"]; +const BUNDLES: [&str; 2] = ["angle", "spout"]; /// The pinned files of every bundle: `(name, sha256)` pairs. pub(crate) fn pinned_files(manifest: &Value) -> Result> { @@ -129,7 +129,7 @@ pub(crate) fn run(args: &Args) -> Result<()> { /// Adds one component per pinned file in `dir` to `sbom`, after checking /// each file's hash against the pin. Returns how many were added. -pub(crate) fn add_components(sbom: &mut Value, manifest: &Value, dir: &Path) -> Result { +fn add_components(sbom: &mut Value, manifest: &Value, dir: &Path) -> Result { let mut components = Vec::new(); for bundle in BUNDLES { // A manifest without a bundle (a test's) describes what it has. diff --git a/crates/xtask/src/package.rs b/crates/xtask/src/package.rs index 8adb5887..f36d1f3d 100644 --- a/crates/xtask/src/package.rs +++ b/crates/xtask/src/package.rs @@ -19,7 +19,8 @@ //! //! - **the file list**: the program, the native DLLs (ANGLE's four and //! Spout's library, D576) and each bundle's licence file, the scene library (every scene in `scenes/`), README, LICENSE, -//! THIRD_PARTY.md and the full notices, and nothing else; +//! THIRD_PARTY.md and the full notices, and nothing else at the top +//! level (inside `scenes/` only the library's scenes are looked for); //! - **the native DLLs** against `scripts/native-deps.json` (D536); //! - **the notices** are the generated file, not an empty one; //! - **the version resource** on `strobe.exe` names the workspace version, @@ -522,7 +523,7 @@ fn find(dir: &Path, name: &str) -> Option { /// `strobe.exe --diagnose` with its files kept in `diag`, its report /// returned. A minute is far more than it needs. -pub(crate) fn run_diagnose(exe: &Path, diag: &Path) -> Result { +fn run_diagnose(exe: &Path, diag: &Path) -> Result { std::fs::create_dir_all(diag)?; let report = diag.join("diagnose.out"); let child = Command::new(exe) @@ -553,25 +554,30 @@ pub(crate) fn wait( return Ok(status); } if started.elapsed() > limit { - // It is being abandoned; the error says so whether or not the - // kill landed. - let _ = child.kill(); - // Reaps it. - let _ = child.wait(); + // It is being abandoned, with whatever it started; the error + // says so whether or not the kill landed. + crate::process::kill_tree(&mut child); bail!("still running after {} s; stopped", limit.as_secs()); } std::thread::sleep(Duration::from_millis(100)); } } -/// The `FileVersion` of a Windows executable's version resource, read by +/// `text` as a single-quoted PowerShell string. +pub(crate) fn ps_quote(text: &str) -> String { + // A single-quoted string is literal except for `'`, which is doubled: + // `C:\Users\O'Brien` would otherwise end the string mid-path. + format!("'{}'", text.replace('\'', "''")) +} + +/// The `ProductVersion` of a Windows executable's version resource, read by /// PowerShell (`.VersionInfo`), which knows the resource format. fn file_version(exe: &Path) -> Result { let output = Command::new("powershell") .args(["-NoProfile", "-NonInteractive", "-Command"]) .arg(format!( - "(Get-Item -LiteralPath '{}').VersionInfo.ProductVersion", - exe.display() + "(Get-Item -LiteralPath {}).VersionInfo.ProductVersion", + ps_quote(&exe.display().to_string()) )) .output() .context("failed to run PowerShell")?; @@ -687,7 +693,7 @@ impl Pe { /// The DLLs a PE file imports directly, from its import directory (the /// second data directory): one `IMAGE_IMPORT_DESCRIPTOR` of 20 bytes per /// DLL, its name's RVA at byte 12, ended by an all-zero descriptor. -pub(crate) fn imports(exe: &Path) -> Result> { +fn imports(exe: &Path) -> Result> { let image = Pe::read(exe)?; let (rva, _) = image.directory(1)?; if rva == 0 { @@ -761,7 +767,7 @@ fn is_windows_dll(name: &str) -> bool { /// debugger asks a symbol store for. Reads the optional header's debug data /// directory, maps its RVA through the section table, and finds the /// CodeView entry. -pub(crate) fn codeview(exe: &Path) -> Result<([u8; 16], u32)> { +fn codeview(exe: &Path) -> Result<([u8; 16], u32)> { let image = Pe::read(exe)?; let pe = &image.bytes; // The debug directory is the seventh data directory. @@ -789,7 +795,7 @@ pub(crate) fn codeview(exe: &Path) -> Result<([u8; 16], u32)> { /// The GUID in a PDB's information stream (stream 1), read through the MSF /// 7.0 container: the superblock, the block map, the stream directory. -pub(crate) fn pdb_guid(pdb: &Path) -> Result<[u8; 16]> { +fn pdb_guid(pdb: &Path) -> Result<[u8; 16]> { const MAGIC: &[u8] = b"Microsoft C/C++ MSF 7.00\r\n\x1aDS\0\0\0"; let file = std::fs::read(pdb)?; if file.get(..MAGIC.len()) != Some(MAGIC) { @@ -837,6 +843,17 @@ pub(crate) fn pdb_guid(pdb: &Path) -> Result<[u8; 16]> { mod tests { use super::*; + #[test] + fn an_apostrophe_in_a_path_is_quoted_for_powershell() -> Result<()> { + assert_eq!(ps_quote(r"C:\Temp\x.exe"), r"'C:\Temp\x.exe'", "plain"); + assert_eq!( + ps_quote(r"C:\Users\O'Brien\x.exe"), + r"'C:\Users\O''Brien\x.exe'", + "a quote inside a single-quoted string is doubled" + ); + Ok(()) + } + #[test] fn a_built_program_and_its_pdb_share_a_guid() -> Result<()> { // The xtask binary running these tests is a PE with a PDB beside it diff --git a/crates/xtask/src/process.rs b/crates/xtask/src/process.rs new file mode 100644 index 00000000..86b23200 --- /dev/null +++ b/crates/xtask/src/process.rs @@ -0,0 +1,154 @@ +// ============================================================================ +// Module: xtask::process +// Description: Stopping a step that ran past its timeout: the process and +// every process it started, not the direct child alone. +// +// Dependencies: std::process; ps and kill (Unix), taskkill (Windows) +// ============================================================================ + +//! Killing a process tree. +//! +//! `Child::kill` stops only the process xtask started. A CI step is often a +//! wrapper: `xvfb-run` is a shell script that starts `Xvfb` and the app, +//! and `cargo test` waits on a test binary. Killing the wrapper leaves the +//! rest running, holding the step's output open (and, on Windows, files +//! under `target/` locked) after xtask has called the step stopped. +//! +//! On Windows `taskkill /T` stops the tree. Elsewhere the descendants are +//! read from `ps` before anything is killed, then all of them get +//! `SIGKILL` at once, so none can start another in between. The child is +//! not moved to a process group of its own: that would keep it running +//! when a person presses Ctrl+C at the terminal. + +use std::process::{Child, Command, Stdio}; + +/// Kills `child` and everything it started, best effort, and reaps it. +pub(crate) fn kill_tree(child: &mut Child) { + let pid = child.id(); + if cfg!(windows) { + // `/T` takes the tree, `/F` without asking. Best effort: the kill + // below still stops the child if taskkill is missing. + let _ = Command::new("taskkill") + .args(["/T", "/F", "/PID", &pid.to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } else { + let below = descendants(&process_table(), pid); + if !below.is_empty() { + let mut kill = Command::new("kill"); + kill.arg("-KILL").args(below.iter().map(u32::to_string)); + // A process that already exited cannot be killed, which is fine. + let _ = kill.stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + } + // Fails only when the child has already exited, as wanted. + let _ = child.kill(); + // Reaps it; the caller reports the timeout either way. + let _ = child.wait(); +} + +/// The processes below `root` in a `(pid, parent)` table, any depth. +fn descendants(table: &[(u32, u32)], root: u32) -> Vec { + let mut found: Vec = Vec::new(); + let mut frontier = vec![root]; + while let Some(parent) = frontier.pop() { + for &(pid, ppid) in table { + if ppid == parent && pid != root && !found.contains(&pid) { + found.push(pid); + frontier.push(pid); + } + } + } + found +} + +/// Every process's `(pid, parent)`, from `ps`; empty when it cannot say. +fn process_table() -> Vec<(u32, u32)> { + let Ok(output) = Command::new("ps") + .args(["-A", "-o", "pid=", "-o", "ppid="]) + .output() + else { + return Vec::new(); + }; + String::from_utf8_lossy(&output.stdout) + .lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::{Result, anyhow}; + use std::time::{Duration, Instant}; + + #[test] + fn descendants_are_found_at_any_depth_and_nothing_else() -> Result<()> { + let table = [(10, 1), (11, 10), (12, 11), (13, 10), (20, 1), (21, 20)]; + let mut found = descendants(&table, 10); + found.sort_unstable(); + assert_eq!(found, vec![11, 12, 13], "children and grandchildren"); + assert!(descendants(&table, 12).is_empty(), "a leaf has none"); + // A table with a loop (a pid reused mid-read) must still end. + assert_eq!(descendants(&[(5, 6), (6, 5)], 5), vec![6], "a loop ends"); + Ok(()) + } + + /// Whether `pid` is a live process (a zombie is not). + fn alive(pid: &str) -> bool { + Command::new("ps") + .args(["-o", "stat=", "-p", pid]) + .output() + .ok() + .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned()) + .is_some_and(|stat| !stat.is_empty() && !stat.starts_with('Z')) + } + + #[test] + fn a_grandchild_is_stopped_with_its_parent() -> Result<()> { + if cfg!(windows) { + // taskkill /T is Windows' own; the Unix path is what needs proof. + return Ok(()); + } + let dir = std::env::temp_dir().join(format!("xtask-tree-{}", std::process::id())); + std::fs::create_dir_all(&dir)?; + let pidfile = dir.join("pid"); + let mut child = Command::new("sh") + .arg("-c") + .arg(format!( + "sleep 30 & echo $! > '{}'; wait", + pidfile.display() + )) + .stdout(Stdio::null()) + .spawn()?; + let started = Instant::now(); + let pid = loop { + let text = std::fs::read_to_string(&pidfile).unwrap_or_default(); + if !text.trim().is_empty() { + break text.trim().to_owned(); + } + if started.elapsed() > Duration::from_secs(10) { + kill_tree(&mut child); + return Err(anyhow!("the shell never started its sleep")); + } + std::thread::sleep(Duration::from_millis(20)); + }; + kill_tree(&mut child); + // Init may take a moment to reap the orphan. + let gone = (0..50).any(|_| { + std::thread::sleep(Duration::from_millis(20)); + !alive(&pid) + }); + if !gone { + // Leave nothing behind whatever the verdict. + let _ = Command::new("kill").args(["-KILL", &pid]).status(); + } + std::fs::remove_dir_all(&dir)?; + assert!(gone, "the grandchild {pid} outlived the kill"); + Ok(()) + } +} diff --git a/docs/DEBUGGING.md b/docs/DEBUGGING.md index 25451ed6..809ddc22 100644 --- a/docs/DEBUGGING.md +++ b/docs/DEBUGGING.md @@ -24,6 +24,7 @@ they never touch a real profile). Inside it: | `logs/` | One session log per run, newest first, the last 10 kept (ordered by file modification time, so a clock reset does not delete the newest, D397). A file stops at 64 MiB with a line saying so (D380); the console and crash reports keep the newest lines. The first lines say the build, the filter, and any filter directive that did not parse. Times are seconds since process start. | | `crashes/crash-*.txt` | A readable report: the panic or crash summary, the session context (GL renderer, backend, scene, render size, frame count), recent structured failures, and the tail of the log. | | `crashes/crash-*.dmp` | A minidump of a *native* crash (a driver access violation, a stack overflow, an abort), written by a second process. A panic has a `.txt` only, and a panic followed by `panic = "abort"` shares one stem. The newest 20 `.txt`/`.dmp` pairs are kept; older ones are deleted at start-up, by file modification time, not by the name (D396). Copy a crash you want to keep out of the folder. | +| `crashes/monitor.log` | The crash monitor's own trouble, appended only when there is some: it could not listen, a dump file or a report could not be written. The monitor's stderr goes nowhere (no console over the show), so this is the one place that says why a crash left no report. A dump that could not be made still gets a `.txt` and a notice saying so. | | `run/` | The crash monitor's socket file (Windows and macOS). Linux uses an abstract socket with no file. | `strobe --diagnose` prints a report of the machine, build, GL and audio diff --git a/docs/IMPLEMENTATION_BACKLOG.md b/docs/IMPLEMENTATION_BACKLOG.md index 553e45b3..ea55b4ab 100644 --- a/docs/IMPLEMENTATION_BACKLOG.md +++ b/docs/IMPLEMENTATION_BACKLOG.md @@ -48,6 +48,7 @@ ### R-04 Crash diagnostics and symbolication in packaged build - **Status:** Done on the T480 (Task 22): `STROBE_FAULT=crash@120` on the packaged `strobe.exe` wrote a minidump and report, and `cargo xtask symbolicate` with no `--symbols` found the packaged PDB and named `strobe_app::fault::recurse() [fault.rs : 170]`. **From the downloaded v0.2.0 archive too (Task 50, 2026-10-27):** the crash drill exited `0xC00000FD`, and `cargo xtask symbolicate` with the release's own `strobe.pdb` (`--symbols` takes the file) named `strobe_app::fault::recurse()` at `fault.rs:170` and `:173`. The crash report and that run's log hold no secret. Left: the same secret audit on a machine with paired remote clients and a trust file, which the T480 does not have, so "none found" there is weak evidence. The release-candidate harness repeats the drill on every candidate (D537); its 2026-11-04 run symbolicated to `fault.rs:170` again (D544). + **Left from the strobe-diag review (2026-12-02):** the native crash handler allocates and its `ping` waits without a timeout before it asks for the dump, so a crash inside the allocator with its lock held loses the dump (asking first would lose the report's context; it needs the monitor to keep reading after the dump); a second thread panicking while the first writes its report aborts the process under `panic = "abort"`, which can cut the first report short; a report is written in place, not to a temporary file renamed into place, so a reader can see it half-written; and `context::note_pass` is not called by the renderer, so reports carry no `pass` line. Fixed then: a dump file that cannot be made is reported, the monitor's own errors go to `crashes/monitor.log`, crash messages stay under the socket's limit, a stale panic report no longer claims a later crash, and a flush waits for room in a full queue. - **Work:** reproduce the crash demo from the packaged release, check diagnostic directory permissions and dump retention, verify matching PDB archive and symbolicate using the shipped build ID. - **Acceptance:** a packaged-build dump symbolicates to useful function and source locations; secrets and tokens are absent from diagnostic output. @@ -105,6 +106,7 @@ - The crash monitor logs a refused connection (os error 10061) and then connects about 31 ms later, every run, so the first line reads like a failure. - Under ANGLE the control window's title reads empty where native reads "Strobe". - `diagnose.txt` is one fixed path, so a second run overwrites the first. + **Left from the xtask review (2026-12-02):** `package-check` and `rc` compare a zip's scene list, DLL pins and notices with the checkout's, so checking an older release from a newer checkout fails falsely (the version check already reads the zip's own, D544); the lint lane's file list is empty when `git ls-files` fails, which lints nothing and passes; a staging folder that cannot be removed is reused silently; and the temporary folders `package-check` and `rc` unpack into are not deleted. - **Work:** fix or explain each: the resume message's order, a bad thumbnail logged once and shown as missing, the monitor's first try retried before it is logged, the title set on both backends, and whether `diagnose.txt` keeps the previous one. - **Acceptance:** a clean packaged run on the T480 logs none of the first three, and the title reads "Strobe" on both backends (read with EnumWindows or a screenshot, not `MainWindowTitle`). @@ -503,8 +505,9 @@ - **Generate controls (D558).** The button in `/play`, with progress, Cancel, the app's review (keep or drop, rename, re-range, effect, audio ideas) and Undo. `strobe_autocontrol::Job` runs the pipeline one step per animation frame, and the scene keeps playing. Accepted controls are an edit in the editor, so they autosave, share and export. Native tests compare it with the app's `generate`; Playwright (`tests/e2e/play-generate.spec.ts`) runs it in Chromium. - **Cube maps and a still `MEDIA` picture (D564, 2026-11-07).** Their pictures are files the visitor adds, as `IMAGES` are (Add image takes several at once, for six faces), cut and checked by the app's own `cubemap_from_bytes` and uploaded by `ScenePlayer::replace_cubemap`, or decoded and uploaded at once with no thread by `ScenePlayer::replace_media_still`. strobe-web's `cube-faces` and `media-still` fixtures draw byte for byte what the app draws from the folder (headless GLES); Playwright adds them in Chromium. - **The Shadertoy audio texture (D577, 2026-12-01).** Live audio uploads the analyser's browser-matched bytes, as the app's capture does. Synthetic and silent leave the texture to the player's resample of the spectrum, and silence reads 0 and 128 as on Shadertoy. A strobe-web test requires the app's picture byte for byte for the same tone (headless GLES). The same change fixed the app: with no device or after a fallback from capture, Shadertoy imports saw a silent or frozen texture while every other input moved. - - **Left:** a `MEDIA` folder (an image sequence), which plays in the app only and is named as such; lygia and hg_sdf, which only resolve when the scene holds those files; and meta controls (a preset's meta channel is ignored). -- **Work:** the meta controls. + - **Pointer, canvas limit, review (2026-12-02).** A scene that pins its size gets the pointer through its letterbox, as the app maps the window's (`sandbox::canvas_mouse`); a canvas larger than the driver's texture limit renders at the largest size of the same shape and is letterboxed (`sandbox::fit_size`); silence no longer allocates each frame; a script uniform of a size the player cannot declare is refused rather than dropped (strobe-web's native tests). + - **Left:** a `MEDIA` folder (an image sequence), which plays in the app only and is named as such; lygia and hg_sdf, which only resolve when the scene holds those files; meta controls (a preset's meta and media channels are ignored); Generate controls measuring a cube-map or still-`MEDIA` scene with its pictures (`strobe_autocontrol::Job` takes `IMAGES` only, so it measures them black where the app's `generate` loads them); and restoring after a lost WebGL context, where the page replays every control's value through `setControl`, which presses each bang once. +- **Work:** the meta controls; the cube and media pictures for `Job`; a restore that sets values without pressing bangs. - **Acceptance:** a scene with an image input and one with an include play the same in the sandbox and the app (met on llvmpipe's GLES, D554); `C-04`'s textureFinalPass scene answers in the browser (met in Chromium, D554); a cube-map scene and a `MEDIA` scene play in the browser (met for a still on llvmpipe's GLES and in Chromium, D564). ### W-02 Browsers, devices and context loss diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 12047fba..323c8e09 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -34,7 +34,7 @@ which backend proved a claim. | `strobe-playlist` | Stage 1, pure core: model, inheritance, TOML, generator, timeline, playback clock, resume (D73-D77). **Stage 2, in the app (D150-D158):** `--playlist` and the LIST pane, precompile with progress, scenes parked at 1x1, warm-up at a quarter of the pixels, the compositor (crossfade, fade-through-black, custom GLSL), real Hold, extend, restart, skip-section and Next/Prev, NOW/NEXT and remaining time, Generate, Save, a file watcher, resume every 5 s, the wall-clock anchor | Unit tests and 4-hour soaks; stage 2 on headless GL in both dialects (`crates/strobe-app/tests/show.rs`) and under Xvfb with llvmpipe. T480 Task 14: the transition demo closed with 0 runtime compiles, transitions at 60 fps costing about 0.5 ms of GPU | | Brand | Parametric Flow guidelines and concept mark (lnorton89/strobe#6); the default theme in the brand palette, the window and taskbar icon, the title-bar mark, and icon PNGs and `.ico` rendered from SVG with a CI check (D190); the `.exe` resource icon and version block (D241, D244); the wordmark, lockups, one-colour mark, README banner and social preview (D256). Open: a person's look at Explorer and the taskbar (R-06) | Xvfb screenshots; the T480 reads the exes' icon group and version block (Tasks 32 and 33) | | Website (`site/`) | Static Next.js 16 export adapted from the Cinnabar site, themed to the brand guide (D523): home, download, guide, scenes, compatibility, architecture and roadmap pages, the last four rendered from `docs/` and `scenes/` at build time; social cards rendered by Metaplate; fonts self-hosted; the release read from GitHub at build and again in the browser, so a new release shows with no deploy (D557); light and dark themes. Deployed by hand to Cloudflare with `npm run deploy:cf` (D525, first on 2026-10-30); CI builds it, with its lint, typecheck and unit tests, on every pull request that can reach it (D552); deploys from CI are open (W-03) | Locally: lint, typecheck, unit tests, and the Playwright suite (axe in both themes, 390 px overflow, focus traps, a stubbed new release, no console errors) on headless Chromium | -| Sandbox (`/play`, `strobe-web`) | Shadertoy-style sandbox on the website (D524): Strobe's own player compiled to wasm on WebGL2 (the ES 3.00 dialect ANGLE uses), CodeMirror editor for every scene file with errors on their lines, recompile as you type keeping the last good picture, the controls panel, the synthetic track, microphone or a file through `strobe-audio`, `script.js` in a Web Worker behind a shim of the API, autosave, share links with the scene in the URL fragment, `.synScene` zip export and import, the library's scenes to open; pictures a visitor adds for `IMAGES`, `#include` of the scene's own files, `textureFinalPass` through the app's asynchronous readback, and presets as `presets/.json` (D554); Generate controls with progress, Cancel, the app's review and Undo, run a step per animation frame while the scene keeps playing (D558). A lost WebGL context recovers without a reload (D559). From image, a gallery of playing scenes from a picture out of a template library, with CLIP in the browser, a free reading on Workers AI and a visitor's own LLM by OpenRouter sign-in or API key (D560, deployed; not yet run against real providers, W-04). cube maps and a still `MEDIA` picture from pictures the visitor adds (D564). A short share link shows a frame of its scene and the scene's title where it is pasted, sent by the browser that shares it (D565; unit-tested, not yet deployed or seen in a link preview). The Shadertoy audio texture is the analyser's own bytes with live audio, as in the app (D577). Open: a `MEDIA` sequence and meta controls (W-01); other browsers (W-02); deploys from CI (W-03) | CI's `site` job (D552): the engine built and bound, and Playwright plays a library scene and marks an error in headless Chromium, and takes the library's scene with no controls through Generate controls' progress and Cancel, and a lighter library scene with its controls baked in through review, accept and undo (D558), and forces a lost context and its recovery (D559). Chromium in the desktop app's pane: all the library's scenes compile and play (18 at the time, D524), an error marks its line, the scripted scene runs, a share link reopens; native tests on headless GLES skip on Windows | +| Sandbox (`/play`, `strobe-web`) | Shadertoy-style sandbox on the website (D524): Strobe's own player compiled to wasm on WebGL2 (the ES 3.00 dialect ANGLE uses), CodeMirror editor for every scene file with errors on their lines, recompile as you type keeping the last good picture, the controls panel, the synthetic track, microphone or a file through `strobe-audio`, `script.js` in a Web Worker behind a shim of the API, autosave, share links with the scene in the URL fragment, `.synScene` zip export and import, the library's scenes to open; pictures a visitor adds for `IMAGES`, `#include` of the scene's own files, `textureFinalPass` through the app's asynchronous readback, and presets as `presets/.json` (D554); Generate controls with progress, Cancel, the app's review and Undo, run a step per animation frame while the scene keeps playing (D558). A lost WebGL context recovers without a reload (D559). From image, a gallery of playing scenes from a picture out of a template library, with CLIP in the browser, a free reading on Workers AI and a visitor's own LLM by OpenRouter sign-in or API key (D560, deployed; not yet run against real providers, W-04). cube maps and a still `MEDIA` picture from pictures the visitor adds (D564). A short share link shows a frame of its scene and the scene's title where it is pasted, sent by the browser that shares it (D565; unit-tested, not yet deployed or seen in a link preview). The Shadertoy audio texture is the analyser's own bytes with live audio, as in the app (D577). A scene that pins its size gets the pointer through its letterbox, and a canvas past the driver's texture limit renders at the largest size of its shape (review, 2026-12-02). Open: a `MEDIA` sequence and meta controls (W-01); other browsers (W-02); deploys from CI (W-03) | CI's `site` job (D552): the engine built and bound, and Playwright plays a library scene and marks an error in headless Chromium, and takes the library's scene with no controls through Generate controls' progress and Cancel, and a lighter library scene with its controls baked in through review, accept and undo (D558), and forces a lost context and its recovery (D559). Chromium in the desktop app's pane: all the library's scenes compile and play (18 at the time, D524), an error marks its line, the scripted scene runs, a share link reopens; native tests on headless GLES skip on Windows | | `strobe-io` | Show control (D170-D179): MIDI input and OSC on two worker threads feeding one bounded queue, drained once per scene frame; the mapping model (source to target, range, curve, invert, button mode, soft takeover), learn with conflict detection, the six target states, the built-in `/strobe/...` OSC space, the Performance Macro set, `show-control.json`. Presets and fav slots in `strobe-scene`. In the app: the MAP pane, the macro strip, the preset row, cue `preset`, configurable hotkeys | Unit tests with no devices, real UDP over loopback, `tests/show.rs` on headless GL in both dialects, and the app under Xvfb with hand-built OSC datagrams and a real click on Learn. **No MIDI hardware has touched it** (the parser and the mapper are tested from recorded bytes). Bug sweep 2026-10-17: nested OSC arrays refused (D370), presses with no release fire every time (D371), a lost device lets go of its held pads (D372), a narrowed fader picks up at the end of its reach (D373), twin controllers and fav slot 0 fixed. Follow-ups: the build with MIDI off is clippy-checked in CI and `cargo xtask ci`, the OSC listener binds again after a socket error with a bounded backoff (D374), a double beyond the f32 range is clamped (D375), a hand-edited macro counter at `u32::MAX` recovers (D376) | | Scenes | Seventeen original scenes: ten over five GPU-load tiers, one scripted, one circuit-board animation (lnorton89/strobe#11), and five audio-reactive show pieces (D276-D279, D439) | llvmpipe, the T480, TORNADO, the RX 580 and the venue mini-PC | | `strobe-remote` | The opt-in LAN remote (D250-D254): typed protocol, bounded bridge, listener, phone page; pairing is an approval at the host with no code, for phones by name and for desktops (D468, D469), and each paired device is listed by that name with its kind, address, paired and last-seen times (D500); Strobes find each other on UDP 47813 (D468); full desktop control (D275) and venue mode with a trust file (D288, D294) | Socket tests in `tests/server.rs`; the phone page in a browser against a local host; two Strobes finding and approving each other on TORNADO; venue mode on loopback on the mini-PC, **not yet across two machines, and no real phone yet** (L-07) |