diff --git a/Cargo.lock b/Cargo.lock index 5519b55d85..6f4ac730c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2159,6 +2159,8 @@ dependencies = [ "image", "interpreted-executor", "log", + "migration-formats", + "migration-nodes", "preprocessor", "serde_json", "tokio", @@ -5101,6 +5103,21 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001" +[[package]] +name = "regression" +version = "0.0.0" +dependencies = [ + "clap", + "document-format", + "fern", + "graphene-cli", + "image", + "log", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "renderdoc-sys" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index a37fc21b28..4e240967ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ members = [ "tools/third-party-licenses", "tools/editor-message-tree", "tools/node-docs", + "tools/regression", "tools/web-editor-driver", ] default-members = [ diff --git a/document/format/src/lib.rs b/document/format/src/lib.rs index a9ea58d51d..8cbb170239 100644 --- a/document/format/src/lib.rs +++ b/document/format/src/lib.rs @@ -85,6 +85,8 @@ pub struct Gdd { /// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer /// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network. pub(crate) network_view_settings: std::collections::BTreeMap>, + /// Whether opening ran a format step or node migration, and so rewrote the working copy. + pub(crate) migrated: bool, } /// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed @@ -198,6 +200,7 @@ impl Gdd { manifest, view_settings: session_state.view_settings, network_view_settings: session_state.network_view_settings, + migrated: false, }; #[cfg(feature = "migrations")] @@ -206,6 +209,7 @@ impl Gdd { if format_outcome.is_some() || migrated_nodes { gdd.manifest.format_version = gdd.manifest.format_version.max(manifest::SUPPORTED_FORMAT_VERSION); gdd.persist_all()?; + gdd.migrated = true; } } @@ -235,6 +239,7 @@ impl Gdd { manifest, view_settings: std::collections::BTreeMap::new(), network_view_settings: std::collections::BTreeMap::new(), + migrated: false, }) } } @@ -278,6 +283,11 @@ impl Gdd { &self.manifest } + /// Whether opening ran a format step or node migration, and so rewrote the working copy. + pub fn migrated(&self) -> bool { + self.migrated + } + pub fn layout(&self) -> &L { &self.layout } diff --git a/document/format/tests/migrations.rs b/document/format/tests/migrations.rs index 7fb43ea718..2fbdb9cae5 100644 --- a/document/format/tests/migrations.rs +++ b/document/format/tests/migrations.rs @@ -51,12 +51,14 @@ fn opening_migrates_nodes_and_persists_the_result() { assert!(migrated.registry().resources.contains_key(&target.id), "the target declaration is a registered resource"); assert_eq!(migrated.declarations(&migrated).await[&target.id], target.proto, "its bytes are stored"); assert_eq!(migrated.manifest().format_version, manifest::SUPPORTED_FORMAT_VERSION); + assert!(migrated.migrated()); // The rewritten history persisted, so a reopen has nothing left to migrate let registry = migrated.registry().clone(); let (working, layout) = migrated.into_storage(); let reopened = GddV1::open_in(working, layout).await.unwrap(); assert!(reopened.registry().value_equal(®istry)); + assert!(!reopened.migrated()); }); } diff --git a/node-graph/graphene-cli/Cargo.toml b/node-graph/graphene-cli/Cargo.toml index dfd48b93b3..cb4178fb33 100644 --- a/node-graph/graphene-cli/Cargo.toml +++ b/node-graph/graphene-cli/Cargo.toml @@ -25,8 +25,10 @@ graphene-std = { workspace = true } interpreted-executor = { workspace = true } graph-craft = { workspace = true, features = ["loading"] } preprocessor = { workspace = true } -document-format = { workspace = true, features = ["zip", "xz"] } +document-format = { workspace = true, features = ["zip", "xz", "migrations"] } document-container = { workspace = true, features = ["zip", "xz"] } +migration-formats = { workspace = true } +migration-nodes = { workspace = true } # Workspace dependencies log = { workspace = true } diff --git a/node-graph/graphene-cli/src/export.rs b/node-graph/graphene-cli/src/export.rs index baf14fa72e..c002215c29 100644 --- a/node-graph/graphene-cli/src/export.rs +++ b/node-graph/graphene-cli/src/export.rs @@ -61,7 +61,7 @@ pub fn detect_file_type(path: &Path) -> Result { } /// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha. -enum RenderedFrame { +pub enum RenderedFrame { Svg(String), Raster { data: Vec, width: u32, height: u32 }, } @@ -152,7 +152,7 @@ fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DV } /// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type. -async fn render_frame( +pub async fn render_frame( executor: &DynamicExecutor, wgpu_executor: &wgpu_executor::WgpuExecutor, settings: ExportSettings, diff --git a/node-graph/graphene-cli/src/lib.rs b/node-graph/graphene-cli/src/lib.rs new file mode 100644 index 0000000000..72ee0068ea --- /dev/null +++ b/node-graph/graphene-cli/src/lib.rs @@ -0,0 +1,200 @@ +//! Opens, compiles, and renders Graphite documents without the editor. A `.gdd` opens through the format steps and node migrations +//! this crate links, so every binary built on it reads documents the way the current build writes them. + +pub mod dump; +pub mod export; + +use document_container::AnyContainer; +use document_container::backends::memory::MemoryBackend; +use document_format::{GddV1, GddV1Layout}; +use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; +use graph_craft::document::{NodeId, NodeNetwork}; +use graph_craft::graphene_compiler::Compiler; +use graph_craft::proto::ProtoNetwork; +use graph_craft::util::load_network; +use graphene_std::application_io::ApplicationIo; +use graphene_std::runtime::{AsyncRuntime, Spawn, Task}; +use interpreted_executor::dynamic_executor::DynamicExecutor; +use interpreted_executor::util::wrap_network_in_scope; +use std::collections::HashMap; +use std::error::Error; +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +// Referenced so the linker keeps their self-registering migrations +use migration_formats as _; +use migration_nodes as _; + +/// A document as the CLI loads it: the runtime network, plus the `.gdd` it came from, if any. +pub struct OpenedDocument { + pub gdd: Option, + pub network: NodeNetwork, + /// What `dump` shows for each node and network, when asked for. + pub names: Option, String>>, +} + +/// Open a `.gdd` from its archive bytes into memory, running the migrations this crate links. +pub async fn open_gdd(archive: &[u8]) -> Result> { + let container = AnyContainer::Memory(MemoryBackend::new()); + let gdd = GddV1::open_from_archive(archive, container, GddV1Layout) + .await + .map_err(|error| format!("Failed to open document: {error}"))?; + Ok(gdd) +} + +/// Open `path` by extension: `.gdd` as an archive, anything else as a legacy `.graphite` document. `with_names` also collects its display names. +pub async fn open_document(path: &Path, with_names: bool) -> Result> { + let is_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd")); + + if !is_gdd { + let document_string = std::fs::read_to_string(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; + return Ok(OpenedDocument { + gdd: None, + network: load_network(&document_string), + names: with_names.then(|| dump::legacy_names(&document_string)), + }); + } + + let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?; + let gdd = open_gdd(&archive).await?; + let declarations = gdd.declarations(&gdd).await; + let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?; + let references = networks.into_iter().filter_map(|network| Some((network.network_path, network.reference?))); + let names = nodes.into_iter().filter_map(|node| Some(([node.network_path, vec![node.local_id]].concat(), node.display_name?))); + let names = with_names.then(|| references.chain(names).filter(|(_, name)| !name.is_empty()).collect()); + Ok(OpenedDocument { gdd: Some(gdd), network, names }) +} + +/// A document compiled against a GPU context, ready to turn into a [`Renderer`]. +pub struct CompiledDocument { + pub proto_network: ProtoNetwork, + application_io: Arc, + runtime: AsyncRuntime, + spawner: Arc, +} + +/// Compile `document` against a fresh GPU context, resolving its resources from its `.gdd`. +pub async fn compile_document(document: OpenedDocument) -> Result> { + log::info!("Creating GPU context"); + let mut application_io = PlatformApplicationIo::new().await; + if let Some(gdd) = &document.gdd { + application_io.inject_resource_proxy(Box::new(gdd.resource_proxy())); + } + let application_io = Arc::new(application_io); + if let Some(executor) = application_io.gpu_executor() { + let info = executor.context().adapter.get_info(); + log::info!("Rendering on {} ({:?}, {:?}, driver {})", info.name, info.backend, info.device_type, info.driver); + } + + let editor_api = Arc::new(PlatformEditorApi { + application_io: Some(application_io.clone()), + }); + let spawner = Arc::new(TokioSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + + let mut network = wrap_network_in_scope(document.network, editor_api, runtime.handle()); + + // A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store + let preprocessor = preprocessor::Preprocessor::new(); + let preprocessed = match &document.gdd { + Some(gdd) => preprocessor.preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|resource| resource.hash)), + None => preprocessor.preprocess(&mut network, &|_| None), + }; + preprocessed.map_err(|error| format!("Failed to expand network: {error:?}"))?; + + let compiled_network = Compiler {}.compile_single(network)?; + for warning in &compiled_network.warnings { + eprintln!("{warning:?}"); + } + + Ok(CompiledDocument { + proto_network: compiled_network.network, + application_io, + runtime, + spawner, + }) +} + +impl CompiledDocument { + pub fn into_renderer(self) -> Result> { + let executor = DynamicExecutor::new(self.proto_network).map_err(|errors| { + let messages: Vec = errors.iter().map(|error| format!("{error:?}")).collect(); + messages.join("\n") + })?; + self.runtime.retain_sources(executor.sources()); + + let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone(); + let polling = Arc::new(AtomicBool::new(true)); + let still_polling = polling.clone(); + std::thread::spawn(move || { + while still_polling.load(Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_nanos(10)); + if let Err(error) = device.poll(wgpu::PollType::Poll) { + log::error!("Polling the GPU device failed: {error}"); + } + } + }); + + Ok(Renderer { + executor, + application_io: self.application_io, + runtime: self.runtime, + spawner: self.spawner, + polling, + }) + } +} + +/// Executes a compiled document, polling its GPU device until dropped. +pub struct Renderer { + pub executor: DynamicExecutor, + pub runtime: AsyncRuntime, + pub spawner: Arc, + application_io: Arc, + polling: Arc, +} + +impl Renderer { + pub fn wgpu_executor(&self) -> &wgpu_executor::WgpuExecutor { + self.application_io.gpu_executor().expect("a renderer is only built with a GPU executor") + } + + /// Fit `settings` to the artwork, unless they give a size. + pub async fn frame(&self, settings: export::ExportSettings) -> Result> { + settings.framed(&self.executor, &self.runtime, &self.spawner).await + } + + /// Render one frame at `animation_time`. + pub async fn render(&self, settings: export::ExportSettings, animation_time: std::time::Duration) -> Result> { + export::render_frame(&self.executor, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await + } +} + +impl Drop for Renderer { + fn drop(&mut self) { + self.polling.store(false, Ordering::Relaxed); + } +} + +/// Runs the tasks nodes spawn on tokio, so an export can wait for them to settle. +#[derive(Default)] +pub struct TokioSpawner(Mutex>>); + +impl Spawn for TokioSpawner { + fn spawn(&self, task: Task) { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(tokio::spawn(task)); + } +} + +impl TokioSpawner { + /// Wait for every spawned task. Returns whether there were any. + pub async fn join(&self) -> bool { + let tasks = std::mem::take(&mut *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + let pending = !tasks.is_empty(); + for task in tasks { + let _ = task.await; + } + pending + } +} diff --git a/node-graph/graphene-cli/src/main.rs b/node-graph/graphene-cli/src/main.rs index 1ecbc77df7..963c86e649 100644 --- a/node-graph/graphene-cli/src/main.rs +++ b/node-graph/graphene-cli/src/main.rs @@ -1,23 +1,8 @@ -mod dump; -mod export; - use clap::{Args, Parser, Subcommand}; -use document_container::AnyContainer; -use document_container::backends::memory::MemoryBackend; -use document_format::{GddV1, GddV1Layout}; use fern::colors::{Color, ColoredLevelConfig}; -use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; -use graph_craft::document::*; -use graph_craft::graphene_compiler::Compiler; -use graph_craft::proto::ProtoNetwork; -use graph_craft::util::load_network; -use graphene_std::application_io::ApplicationIo; -use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task}; -use interpreted_executor::dynamic_executor::DynamicExecutor; -use interpreted_executor::util::wrap_network_in_scope; +use graphene_cli::{compile_document, dump, export, open_document}; use std::error::Error; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; #[derive(Debug, Parser)] #[clap(name = "graphene-cli", version)] @@ -108,14 +93,10 @@ struct GlobalOpts { async fn main() -> Result<(), Box> { let app = App::parse(); - let log_level = app.global_opts.verbose; + init_logging(app.global_opts.verbose); - init_logging(log_level); - - let document_path = match app.command { - Command::Compile { ref document, .. } => document, - Command::Export { ref document, .. } => document, - Command::ExtractLegacyDoc { ref document } => document, + let document_path = match &app.command { + Command::Compile { document, .. } | Command::Export { document, .. } | Command::ExtractLegacyDoc { document } => document, Command::ListNodeIdentifiers => { let mut nodes: Vec<_> = graphene_std::registry::NODE_METADATA.lock().unwrap().keys().cloned().collect(); nodes.sort_by_key(|x| x.as_str().to_string()); @@ -126,79 +107,31 @@ async fn main() -> Result<(), Box> { } }; - // Load the document by extension: `.gdd` opens the new archive format, anything else is treated as a - // legacy `.graphite` document. The legacy path has no `Gdd`, so resources fall back to the default registry. - let is_gdd = document_path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd")); + let print = matches!(app.command, Command::Compile { format: Some(_), .. }); + let mut document = open_document(document_path, print).await?; - let gdd = if is_gdd { - let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?; - let container = AnyContainer::Memory(MemoryBackend::new()); - let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout) - .await - .map_err(|error| format!("Failed to open document: {error}"))?; - Some(gdd) - } else { - None - }; - - if let Command::ExtractLegacyDoc { ref document } = app.command { - let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) }; + if let Command::ExtractLegacyDoc { document: path } = &app.command { + let Some(gdd) = &document.gdd else { + return Err("ExtractLegacyDoc requires a .gdd document".into()); + }; let Some(legacy_doc) = gdd.read_legacy_document().await else { return Err("gdd file did not contain a legacy .graphite document".into()); }; - let mut new_path = document.clone(); - new_path.set_extension("graphite"); + let new_path = path.with_extension("graphite"); std::fs::write(&new_path, legacy_doc).map_err(|error| format!("Failed to write .graphite file: {error}"))?; eprintln!("Saved file to {}", new_path.to_string_lossy()); return Ok(()); } - // Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document. - let print = matches!(app.command, Command::Compile { format: Some(_), .. }); - let (node_network, names) = match &gdd { - Some(gdd) => { - let declarations = gdd.declarations(gdd).await; - let (node_network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?; - let references = networks.into_iter().filter_map(|network| Some((network.network_path, network.reference?))); - let names = nodes.into_iter().filter_map(|node| Some(([node.network_path, vec![node.local_id]].concat(), node.display_name?))); - (node_network, print.then(|| references.chain(names).filter(|(_, name)| !name.is_empty()).collect())) - } - None => { - let document_string = std::fs::read_to_string(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?; - (load_network(&document_string), print.then(|| dump::legacy_names(&document_string))) - } - }; - let document = names.map(|names| dump::document(&node_network, names)); - - log::info!("Creating GPU context"); - let mut application_io = PlatformApplicationIo::new().await; - if let Some(gdd) = &gdd { - application_io.inject_resource_proxy(Box::new(gdd.resource_proxy())); - } - - // Convert application_io to Arc first - let application_io_arc = Arc::new(application_io); - - // Clone the application_io Arc before borrowing to extract executor - let application_io_for_api = application_io_arc.clone(); - - // Get reference to wgpu executor and clone device handle - let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap(); - let device = wgpu_executor_ref.context().device.clone(); - - let editor_api = Arc::new(PlatformEditorApi { - application_io: Some(application_io_for_api), - }); - let spawner = Arc::new(TokioSpawner::default()); - let runtime = AsyncRuntime::new(spawner.clone()); - let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?; + let dump_document = document.names.take().map(|names| dump::document(&document.network, names)); + let compiled = compile_document(document).await?; match app.command { Command::Compile { format, upstream, downstream, depth, .. } => { - if let Some((format, document)) = format.zip(document) { - dump::print(&proto_graph, &document, format, upstream.as_deref(), downstream.as_deref(), depth)?; + if let Some((format, dump_document)) = format.zip(dump_document) { + dump::print(&compiled.proto_network, &dump_document, format, upstream.as_deref(), downstream.as_deref(), depth)?; } } Command::Export { @@ -212,48 +145,36 @@ async fn main() -> Result<(), Box> { duration, .. } => { - // Spawn thread to poll GPU device - std::thread::spawn(move || { - loop { - std::thread::sleep(std::time::Duration::from_nanos(10)); - device.poll(wgpu::PollType::Poll).unwrap(); - } - }); - - // Detect output file type let file_type = export::detect_file_type(&output)?; - - // Create executor - let executor = create_executor(proto_graph)?; - runtime.retain_sources(executor.sources()); - if fps <= 0. { return Err("Fps number must be positive".into()); } - // Perform export based on file type, where a multi-frame export to a format besides GIF becomes a numbered image sequence + let renderer = compiled.into_renderer()?; + let (executor, wgpu_executor, runtime, spawner) = (&renderer.executor, renderer.wgpu_executor(), &renderer.runtime, renderer.spawner.as_ref()); + + // A multi-frame export to a format besides GIF becomes a numbered image sequence let settings = export::ExportSettings { file_type, scale, size: (width, height), transparent, framing: None, - } - .framed(&executor, &runtime, &spawner) - .await?; + }; + let settings = renderer.frame(settings).await?; let animation = export::AnimationParams::new(fps, frames, duration); if file_type == export::FileType::Gif { - export::export_gif(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?; + export::export_gif(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?; } else if animation.frames > 1 { if file_type == export::FileType::Ico { return Err("ICO can't be exported as an image sequence".into()); } - export::export_image_sequence(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?; + export::export_image_sequence(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?; } else { - export::export_document(&executor, wgpu_executor_ref, output, settings, &runtime, &spawner).await?; + export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?; } } - _ => unreachable!("All other commands should be handled before this match statement is run"), + Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } => unreachable!("Handled before compiling"), } Ok(()) @@ -287,50 +208,3 @@ fn init_logging(log_level: u8) { .apply() .unwrap(); } - -fn compile_graph(network: NodeNetwork, editor_api: Arc, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result> { - let preprocessor = preprocessor::Preprocessor::new(); - - let mut network = wrap_network_in_scope(network, editor_api, runtime); - - // A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store, so it - // preprocesses against an empty registry (matching the pre-`.gdd` CLI behavior). - match gdd { - Some(gdd) => preprocessor - .preprocess(&mut network, &|resource_id| gdd.registry().resources.get(&resource_id).and_then(|r| r.hash)) - .expect("Failed to expand network"), - None => { preprocessor.preprocess(&mut network, &|_| None) }.expect("Failed to expand network"), - } - - let compiler = Compiler {}; - let compiled_network = compiler.compile_single(network)?; - for warning in &compiled_network.warnings { - eprintln!("{warning:?}"); - } - Ok(compiled_network.network) -} - -fn create_executor(proto_network: ProtoNetwork) -> Result> { - let executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?; - Ok(executor) -} - -#[derive(Default)] -pub(crate) struct TokioSpawner(Mutex>>); - -impl Spawn for TokioSpawner { - fn spawn(&self, task: Task) { - self.0.lock().unwrap().push(tokio::spawn(task)); - } -} - -impl TokioSpawner { - pub(crate) async fn join(&self) -> bool { - let tasks = std::mem::take(&mut *self.0.lock().unwrap()); - let pending = !tasks.is_empty(); - for task in tasks { - let _ = task.await; - } - pending - } -} diff --git a/node-graph/rfcs/document-format-migrations.md b/node-graph/rfcs/document-format-migrations.md index 0ce89bb56d..dd57085ee2 100644 --- a/node-graph/rfcs/document-format-migrations.md +++ b/node-graph/rfcs/document-format-migrations.md @@ -450,6 +450,8 @@ Every migration ships with: - **Fixtures.** Small source graphs built in the test and assertions on the migrated result. - **The commutation property.** For generated histories `H` over the source declaration, including concurrent branches, `replay(rewrite(H)) == M(replay(H))`. This is the definition of a correct rewrite, so a migration that passes it needs no hand-written history tests. The generator also produces the reachable source states that expose `unrepresentable` failures. +Whole documents are covered by a regression corpus: a separate git repository of `.gdd` documents with reference renders at chosen animation times, which `cargo run regression check` renders and compares within a per-document tolerance. `add` and `bless` record references, and `upgrade` rewrites documents (by default `demo-artwork/*.gdd`) through the migrations of the current build, so a migration shows up in the corpus as a document change whose renders still match. + ## Crate layout ``` diff --git a/tools/cargo-run/src/lib.rs b/tools/cargo-run/src/lib.rs index a400362db6..e5f8e4b182 100644 --- a/tools/cargo-run/src/lib.rs +++ b/tools/cargo-run/src/lib.rs @@ -11,6 +11,7 @@ pub enum Action { Explore(Option), Drive, Migration, + Regression, } pub enum Target { @@ -54,6 +55,16 @@ impl Task { }); } + // Everything after `regression` belongs to the document regression tool + if args.first() == Some(&"regression") { + return Some(Task { + action: Action::Regression, + target: Target::Cli, + profile: Profile::Default, + args: args[1..].iter().map(|s| s.to_string()).collect(), + }); + } + let split = args.iter().position(|a| *a == "--").unwrap_or(args.len()); let passthru_args = args[split..].iter().skip(1).map(|s| s.to_string()).collect(); let args = &args[..split]; diff --git a/tools/cargo-run/src/main.rs b/tools/cargo-run/src/main.rs index 30c9364cb3..5e7252481d 100644 --- a/tools/cargo-run/src/main.rs +++ b/tools/cargo-run/src/main.rs @@ -19,6 +19,7 @@ fn usage() { println!(" explore Open an assortment of tools for exploring the codebase"); println!(" drive Drive the web editor in an isolated browser (see `cargo run drive help`)"); println!(" migration Freeze the stored format or scaffold node migrations (see `cargo run migration help`)"); + println!(" regression Upgrade documents and check renders of the regression corpus (see `cargo run regression help`)"); println!(" help Show this message"); println!(":"); println!(" [web] Web app (default)"); @@ -53,7 +54,10 @@ fn main() -> ExitCode { return drive(&task); } if matches!(task.action, Action::Migration) { - return migration(&task); + return delegate("migration-snapshot", &task); + } + if matches!(task.action, Action::Regression) { + return delegate("regression", &task); } if let Err(e) = run_task(&task) { @@ -106,8 +110,8 @@ fn drive(task: &Task) -> ExitCode { } // Exits with the tool's own status, so CI reads a failed check from it -fn migration(task: &Task) -> ExitCode { - let tool = cmd!("cargo", "run", "--quiet", "--package", "migration-snapshot", "--").args(&task.args).unchecked(); +fn delegate(package: &str, task: &Task) -> ExitCode { + let tool = cmd!("cargo", "run", "--quiet", "--package", package, "--").args(&task.args).unchecked(); match Expression::run(&tool) { Ok(output) => ExitCode::from(output.status.code().and_then(|code| u8::try_from(code).ok()).unwrap_or(1)), Err(e) => { @@ -161,7 +165,7 @@ fn run_task(task: &Task) -> Result<(), Error> { profile = match action { Action::Run => &Profile::Debug, Action::Build => &Profile::Release, - Action::Explore(_) | Action::Drive | Action::Migration => unreachable!(), + Action::Explore(_) | Action::Drive | Action::Migration | Action::Regression => unreachable!(), } } @@ -188,7 +192,7 @@ fn run_task(task: &Task) -> Result<(), Error> { (Action::Build, Target::Cli, Profile::Debug) => cmd!("cargo", "build", "-p", "graphene-cli").run()?, (Action::Build, Target::Cli, Profile::Release | Profile::Default) => cmd!("cargo", "build", "-r", "-p", "graphene-cli").run()?, - (Action::Explore(_) | Action::Drive | Action::Migration, _, _) => unreachable!(), + (Action::Explore(_) | Action::Drive | Action::Migration | Action::Regression, _, _) => unreachable!(), } Ok(()) } diff --git a/tools/regression/Cargo.toml b/tools/regression/Cargo.toml new file mode 100644 index 0000000000..d7bb5c66c6 --- /dev/null +++ b/tools/regression/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "regression" +description = "Upgrades Graphite documents through their migrations and checks renders of a document corpus against reference images" +version.workspace = true +license.workspace = true +authors.workspace = true +edition.workspace = true +repository.workspace = true +readme.workspace = true +homepage.workspace = true +rust-version.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +# Local dependencies +graphene-cli = { path = "../../node-graph/graphene-cli" } +document-format = { workspace = true, features = ["zip", "xz", "migrations"] } + +# Workspace dependencies +clap = { workspace = true, features = ["derive"] } +fern = { workspace = true } +image = { workspace = true } +log = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true } diff --git a/tools/regression/src/compare.rs b/tools/regression/src/compare.rs new file mode 100644 index 0000000000..73d976f731 --- /dev/null +++ b/tools/regression/src/compare.rs @@ -0,0 +1,82 @@ +//! Compares a render to its reference pixel by pixel. + +use crate::corpus::Tolerance; +use image::RgbaImage; + +pub enum Comparison { + Matches, + SizeChanged { + reference: (u32, u32), + actual: (u32, u32), + }, + /// More pixels than the tolerance allows differ, highlighted in `diff`. + Differs { + differing: usize, + total: usize, + diff: RgbaImage, + }, +} + +/// O(pixels). +pub fn compare(reference: &RgbaImage, actual: &RgbaImage, tolerance: Tolerance) -> Comparison { + if reference.dimensions() != actual.dimensions() { + return Comparison::SizeChanged { + reference: reference.dimensions(), + actual: actual.dimensions(), + }; + } + + // Differing pixels show red over a faded copy of the reference, so they stand out in context + let mut diff = RgbaImage::new(actual.width(), actual.height()); + let mut differing = 0; + for ((expected, rendered), marked) in reference.pixels().zip(actual.pixels()).zip(diff.pixels_mut()) { + let largest_difference = expected.0.iter().zip(rendered.0).map(|(a, b)| a.abs_diff(b)).max().unwrap_or_default(); + if largest_difference > tolerance.channel { + differing += 1; + *marked = image::Rgba([255, 0, 0, 255]); + } else { + let [red, green, blue, alpha] = expected.0; + let luminance = ((red as u32 * 3 + green as u32 * 6 + blue as u32) / 10) as u8; + *marked = image::Rgba([luminance, luminance, luminance, alpha / 4]); + } + } + + let total = (actual.width() * actual.height()) as usize; + if differing as f64 > tolerance.pixels * total as f64 { + Comparison::Differs { differing, total, diff } + } else { + Comparison::Matches + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn image_of(pixels: &[[u8; 4]]) -> RgbaImage { + RgbaImage::from_raw(pixels.len() as u32, 1, pixels.concat()).unwrap() + } + + #[test] + fn small_differences_and_few_pixels_are_tolerated() { + let reference = image_of(&[[10, 10, 10, 255]; 4]); + let close = image_of(&[[12, 9, 10, 255]; 4]); + assert!(matches!(compare(&reference, &close, Tolerance::default()), Comparison::Matches)); + + let one_off = image_of(&[[10, 10, 10, 255], [10, 10, 10, 255], [10, 10, 10, 255], [200, 10, 10, 255]]); + let lenient = Tolerance { channel: 2, pixels: 0.25 }; + assert!(matches!(compare(&reference, &one_off, lenient), Comparison::Matches)); + + let Comparison::Differs { differing, total, diff } = compare(&reference, &one_off, Tolerance::default()) else { + panic!("one pixel in four exceeds the default tolerance"); + }; + assert_eq!((differing, total), (1, 4)); + assert_eq!(diff.get_pixel(3, 0).0, [255, 0, 0, 255]); + } + + #[test] + fn a_size_change_never_matches() { + let comparison = compare(&image_of(&[[0; 4]; 2]), &image_of(&[[0; 4]; 3]), Tolerance::default()); + assert!(matches!(comparison, Comparison::SizeChanged { reference: (2, 1), actual: (3, 1) })); + } +} diff --git a/tools/regression/src/corpus.rs b/tools/regression/src/corpus.rs new file mode 100644 index 0000000000..174e503176 --- /dev/null +++ b/tools/regression/src/corpus.rs @@ -0,0 +1,121 @@ +//! The regression corpus: a directory, usually a git repository of its own, holding `.gdd` documents and the images they must render. +//! +//! ```text +//! corpus.json Which documents to render, how, and how closely they must match +//! documents/.gdd +//! references//