diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ae34acdf8..891fa6396 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -42,7 +42,7 @@ jobs: with: submodules: true - name: CI reporting contracts - run: node --test .github/scripts/test_prepare_test_reports.cjs + run: node --test .github/scripts/test_prepare_test_reports.cjs tools/test_measured_report.cjs - uses: dtolnay/rust-toolchain@stable with: components: rustfmt diff --git a/README.md b/README.md index e9c8b8857..d45b1b99c 100644 --- a/README.md +++ b/README.md @@ -2056,6 +2056,76 @@ There are a few important things to keep in mind when working on the project: execution time, and total wall time separately: precompilation makes the execution phase much faster but adds preparation that is only recovered by a sufficiently large or repeated filter. +### Local measured execution bundles + +`tools/measured-report.cjs` captures narrowly selected existing tests; it does not change the +configuration classification report or run a compatibility campaign. Use the repository toolchain +and Node 22.14.0 (strictly enforced for installed-package controls); the API suite's independent +target version is recorded from the vendored `NODE_VERSION`, validated against its configuration +by the existing harness. Run from the checkout with no concurrent source edits: + +```sh +node tools/measured-report.cjs plan tmp/measured api-1 api parallel__test_path_basename_js +node tools/measured-report.cjs run tmp/measured api-1 +node tools/measured-report.cjs plan tmp/measured installed-1 installed node_modules_app__popular_pure_js__test_01_cjs_utilities_cjs +node tools/measured-report.cjs run tmp/measured installed-1 +node tools/measured-report.cjs plan tmp/measured bundled-1 bundled ajv/test-01-basic.js +node tools/measured-report.cjs run tmp/measured bundled-1 +node tools/measured-report.cjs assemble tmp/measured +node tools/measured-report.cjs verify tmp/measured +node tools/measured-report.cjs render tmp/measured/report.json +``` + +`plan` discovers generated cases before shared guest setup; tag/static-test filters are unsupported. +It retains fixture/configuration and lockfile inputs, including a superset of the API harness's +vendored helpers, fixtures and ESM siblings. `run` refuses changed inputs or toolchain versions +and records individual retries and prerequisite, +Node-control and guest phases, along with raw CTRF and stdout/stderr. It never rewrites an execution; +use a new execution ID for a rerun. Installed planning and execution also refuse fixture files absent from retained inputs, including +untracked/ignored helpers or a local `node_modules` tree, rather than copying them into evidence. +Bundled runs use a fresh `tmp/measured-` directory +and the root Cargo target cache; they build the current generator and execute the existing fixture's +Rollup output with Node and Wasmtime. Each execution uses a unique generated Cargo library name +while sharing the dependency cache, so builds cannot overwrite another fixture's output before +publication. The execution-owned `component.wasm` copy is hashed, executed and retained. No +producer-owned build lock needs recovery after interruption. +Execution-specific Cargo outputs accumulate in the shared target cache. When no builds are +running, reclaim that regenerable WASM cache with `cargo clean --target-dir target --target wasm32-wasip2`; +this does not remove the authoritative component copies retained in evidence bundles. +Only use offline fixtures without credentials. + +The version-1 bundle's `plan.json` declares expected executions/cases; `selection.json` selects +whole executions, independently of their observed outcomes. An optional final JSON metadata-file +argument to `plan` sets `consumer`, `artifactRole`, `lane`, `workflowRun`, `workflowAttempt`, and +`behaviorCases`. Coverage defaults to `unclassified`, which never qualifies as properly implemented. +After inspecting the selected assertions, declare behavior case IDs explicitly, for example +`{"behaviorCases":["ajv/test-01-basic.js"]}` for the bundled smoke. Unknown IDs are rejected. +Discovery does not mechanically classify import-only checks: reviewers must exclude those from +behavior declarations. A declaration is audited input, not automatic proof of assertion quality. +Same-lane/profile reruns are retained but not selected automatically: explicitly select complete +execution IDs with `select ...`. A missing selected rerun remains incomplete; it never +borrows earlier green cases. Assembly and verification reject overlapping selected case keys across +lanes instead of counting them twice or choosing a preferred outcome. Select whole non-overlapping +executions; unselected evidence remains retained. Existing CI artifact selection is unchanged. + +Each execution has an identity-bound `component.json`, immutable attempt `start.json`/`finish.json` +records and numbered phase records/logs. Missing completion stays `not-run`; a failed prerequisite +is `blocked`, not a guest failure. Configured or runtime skips retain their reason. Sealed execution +`evidence.json` and bundle `checksums.json` detect missing/corrupted evidence; these are integrity +checks, not signatures. Assembly rejects duplicate/conflicting identities and cross-artifact mixing. + +Normalized `report.json` is authoritative; Markdown uses only that JSON and never inserts fresh +timestamps. Reports separate all six outcomes, non-flaky/flaky passes and attempt totals. Fail-then-pass +is `pass` with `flaky: true`, excluded from every "properly implemented" numerator but kept in the +selected denominator. Only explicitly declared non-flaky behavior assertions with sealed completed +evidence qualify; unclassified checks never qualify. Reviewers must exclude import-only checks from +behavior declarations; discovery does not detect their assertion quality. Incomplete selected evidence +is explicit. These counts describe selected +local assertions, not full Node support, Golem recovery/durability or shipped qualification. + +The bundle is portable local evidence, not an uploader or permanent archive. Keep raw bundles out +of Git. Test the producer contract with `node --test tools/test_measured_report.cjs`. + ## Acknowledgements The builtin JS modules are based on the work of several other projects: diff --git a/tests/common/measured.rs b/tests/common/measured.rs new file mode 100644 index 000000000..84d54df6e --- /dev/null +++ b/tests/common/measured.rs @@ -0,0 +1,353 @@ +//! Opt-in execution evidence for tools/measured-report.cjs. Never changes retry policy. +use anyhow::Context; +use serde_json::{Value, json}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +fn directory() -> Option { + std::env::var_os("WASM_RQUICKJS_MEASURE_DIR").map(PathBuf::from) +} + +fn write(path: &Path, value: &Value) -> anyhow::Result<()> { + let bytes = serde_json::to_vec_pretty(value)?; + // Workers may rediscover the same inventory concurrently. Publish only complete bytes. + let parent = + camino::Utf8Path::from_path(path.parent().unwrap()).context("non-UTF8 evidence path")?; + let mut file = camino_tempfile::NamedUtf8TempFile::new_in(parent)?; + file.write_all(&bytes)?; + match file.persist_noclobber(path) { + Ok(_) => (), + Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => { + anyhow::ensure!( + fs::read(path)? == bytes, + "conflicting evidence: {}", + path.display() + ); + } + Err(error) => return Err(error.error.into()), + } + Ok(()) +} + +pub fn node_compat_input_roots() -> anyhow::Result<()> { + if let Some(dir) = directory() { + write( + &dir.join("input-roots.json"), + &json!(super::NODE_COMPAT_INPUT_ROOTS), + )?; + } + Ok(()) +} + +pub fn register( + name: &str, + fixture: &str, + runner_prefix: &str, + classification: &str, + reason: Option<&str>, + timeout_seconds: u64, + max_attempts: usize, +) { + let Some(dir) = directory() else { return }; + let filter = std::env::var("WASM_RQUICKJS_MEASURE_FILTER").expect("measurement filter"); + let runner_name = format!("{runner_prefix}::{name}"); + if !runner_name.contains(&filter) { + return; + } + let inventory = dir.join("inventory"); + fs::create_dir_all(&inventory).expect("create measurement inventory"); + write(&inventory.join(format!("{}.json", blake3::hash(name.as_bytes()))), &json!({ + "id": name, "runnerName": runner_name, "fixture": fixture, + "classification": classification, "skipReason": reason.or_else(|| (classification != "runnable").then_some(classification)), + "timeoutSeconds": timeout_seconds, "maxAttempts": max_attempts, + "coverage": "unclassified" + })).expect("record measurement inventory"); +} + +pub fn component(path: &Path, features: &str) -> anyhow::Result<()> { + if let Some(dir) = directory() { + write( + &dir.join("component.json"), + &json!({ + "identity": fs::read_to_string(dir.join("identity.txt"))?, + "algorithm": "blake3", "digest": blake3::hash(&fs::read(path)?).to_hex().as_str(), + "features": features + }), + )?; + } + Ok(()) +} + +pub struct Prerequisite { + dir: Option, + identity: String, + phase: String, +} + +impl Prerequisite { + pub fn start(phase: &str) -> anyhow::Result { + let dir = directory().map(|root| { + root.join("prerequisites") + .join(format!("{phase}-{}", std::process::id())) + }); + let identity = if let Some(dir) = &dir { + fs::create_dir_all(dir)?; + let identity = fs::read_to_string(directory().unwrap().join("identity.txt"))?; + write( + &dir.join("start.json"), + &json!({ + "identity": identity, "phase": phase, "startedAt": chrono::Utc::now().to_rfc3339() + }), + )?; + identity + } else { + String::new() + }; + Ok(Self { + dir, + identity, + phase: phase.into(), + }) + } + + pub fn finish(self, result: anyhow::Result) -> anyhow::Result { + if let Some(dir) = &self.dir { + write( + &dir.join("finish.json"), + &json!({ + "identity": self.identity, "phase": self.phase, + "outcome": if result.is_ok() { "pass" } else { "fail" }, + "reason": result.as_ref().err().map(|error| format!("{error:#}")), + "finishedAt": chrono::Utc::now().to_rfc3339() + }), + )?; + } + result + } +} + +pub struct Attempt { + dir: Option, + identity: String, + case: String, + ordinal: usize, + phase: String, + step: usize, + timed_out: bool, + skip_reason: Option, +} + +impl Attempt { + pub fn is_enabled(&self) -> bool { + self.dir.is_some() + } + + pub fn start(case: &str) -> anyhow::Result { + let mut attempt = Self { + dir: None, + identity: String::new(), + case: case.into(), + ordinal: 0, + phase: String::new(), + step: 0, + timed_out: false, + skip_reason: None, + }; + if let Some(root) = directory() { + let parent = root + .join("attempts") + .join(blake3::hash(case.as_bytes()).to_hex().as_str()); + fs::create_dir_all(&parent)?; + for ordinal in 1.. { + let dir = parent.join(format!("{ordinal:04}")); + match fs::create_dir(&dir) { + Ok(()) => { + attempt.dir = Some(dir); + attempt.ordinal = ordinal; + break; + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + } + attempt.identity = fs::read_to_string(root.join("identity.txt"))?; + attempt.record( + "start.json", + json!({"startedAt": chrono::Utc::now().to_rfc3339()}), + )?; + } + attempt.phase("setup")?; + Ok(attempt) + } + + fn record(&self, file: &str, mut value: Value) -> anyhow::Result<()> { + if let Some(dir) = &self.dir { + value["identity"] = self.identity.clone().into(); + value["caseId"] = self.case.clone().into(); + value["ordinal"] = self.ordinal.into(); + write(&dir.join(file), &value)?; + } + Ok(()) + } + + fn end_phase(&self, outcome: &str, reason: &str) -> anyhow::Result<()> { + if self.step != 0 { + self.record( + &format!("phase-{:04}-finish.json", self.step), + json!({ + "phase": self.phase, "outcome": outcome, "reason": reason, + "finishedAt": chrono::Utc::now().to_rfc3339() + }), + )?; + } + Ok(()) + } + + pub fn phase(&mut self, phase: &str) -> anyhow::Result<()> { + if self.dir.is_none() { + return Ok(()); + } + self.end_phase("pass", "")?; + self.phase = phase.into(); + self.step += 1; + self.record( + &format!("phase-{:04}-start.json", self.step), + json!({ + "phase": phase, "startedAt": chrono::Utc::now().to_rfc3339() + }), + ) + } + + pub fn logs(&self, stdout: &str, stderr: &str) -> anyhow::Result<()> { + if let Some(dir) = &self.dir { + for (suffix, text) in [("stdout", stdout), ("stderr", stderr)] { + let path = dir.join(format!("phase-{:04}-{suffix}.txt", self.step)); + OpenOptions::new() + .write(true) + .create_new(true) + .open(path)? + .write_all(text.as_bytes())?; + } + } + Ok(()) + } + + pub fn timed_out(&mut self) { + self.timed_out = true; + } + + pub fn returned(&mut self, result: &anyhow::Result>) { + if let Err(error) = result { + self.timed_out |= error.chain().any(|cause| { + matches!( + cause.downcast_ref::(), + Some(wasmtime::Trap::Interrupt) + ) + }); + } + if let Ok(Some(wasmtime::component::Val::String(value))) = result + && value.starts_with("SKIP:") + { + self.skip_reason = Some(value.clone()); + } + } + + pub fn finish(&self, result: &anyhow::Result<()>) -> anyhow::Result<()> { + if self.dir.is_none() { + return Ok(()); + } + let reason = result + .as_ref() + .err() + .map(|e| format!("{e:#}")) + .unwrap_or_else(|| self.skip_reason.clone().unwrap_or_default()); + let outcome = if result.is_ok() && self.skip_reason.is_some() { + "skip" + } else if result.is_ok() { + "pass" + } else if self.phase != "guest" { + "blocked" + } else if self.timed_out + || result.as_ref().err().is_some_and(|error| { + error.chain().any(|cause| { + matches!( + cause.downcast_ref::(), + Some(wasmtime::Trap::Interrupt) + ) + }) + }) + { + "timeout" + } else { + "fail" + }; + self.end_phase( + if outcome == "blocked" { + "fail" + } else { + outcome + }, + &reason, + )?; + self.record("finish.json", json!({ + "outcome": outcome, "reason": reason, "failedPhase": if result.is_err() { Some(&self.phase) } else { None }, + "finishedAt": chrono::Utc::now().to_rfc3339() + })).context("finish measured attempt") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test_r::test] + fn epoch_interrupt_retains_timeout() { + // Isolate measurement environment variables from concurrent harness tests. + if std::env::var_os("MEASURE_TRAP_CAPTURE_CHILD").is_none() { + let dir = camino_tempfile::Utf8TempDir::new().unwrap(); + fs::write(dir.path().join("identity.txt"), "probe").unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "common::measured::tests::epoch_interrupt_retains_timeout", + ]) + .env("MEASURE_TRAP_CAPTURE_CHILD", "1") + .env("WASM_RQUICKJS_MEASURE_DIR", dir.path()) + .env("WASM_RQUICKJS_MEASURE_FILTER", "no-measured-inventory") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); + return; + } + for (case, error, expected) in [ + ( + "interrupt", + anyhow::Error::new(wasmtime::Trap::Interrupt).context("guest invocation"), + "timeout", + ), + ("assertion", anyhow::anyhow!("assertion failed"), "fail"), + ] { + let mut attempt = Attempt::start(case).unwrap(); + attempt.phase("guest").unwrap(); + let formatted = format!("Invocation error: {error}"); + let returned = Err(error); + attempt.returned(&returned); + attempt.logs("", "").unwrap(); + // The API runner formats the invocation error, losing the original chain. + attempt.finish(&Err(anyhow::anyhow!(formatted))).unwrap(); + let finish = directory() + .unwrap() + .join("attempts") + .join(blake3::hash(case.as_bytes()).to_hex().as_str()) + .join("0001/finish.json"); + let value: Value = serde_json::from_slice(&fs::read(finish).unwrap()).unwrap(); + assert_eq!(value["outcome"], expected); + } + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 67303e9fa..f4abb7f22 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,5 @@ pub mod js_subtest_parser; +pub mod measured; pub mod test_server; use crate::common::WasmSource::Precompiled; @@ -3214,6 +3215,16 @@ pub fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> anyho Ok(()) } +// Guest setup owns these roots; measured discovery publishes the same superset. +const NODE_COMPAT_INPUT_ROOTS: [&str; 6] = [ + "tests/node_compat/common-shim", + "tests/node_compat/suite/common", + "tests/node_compat/suite/fixtures", + "tests/node_compat/fixtures", + "tests/node_compat/suite/sqlite", + "tests/node_compat/suite/es-module", +]; + /// Copy a vendored Node.js test file and common shims into a temp directory. /// /// Sets up the directory layout expected by the node-compat-runner: @@ -3223,6 +3234,14 @@ pub fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> anyho /// - `/home/node/test/fixtures/` — fixture data files (recursively copied) /// - `/home/node/test/sqlite/` — vendored sqlite test helpers, when present pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> anyhow::Result<()> { + let [ + shim_root, + vendored_common_root, + vendored_fixtures_root, + fixtures_root, + sqlite_root, + esm_root, + ] = NODE_COMPAT_INPUT_ROOTS; // Parse the suite name from the relative path (e.g., "parallel/test-foo.js" → "parallel") let suite = test_rel_path.split('/').next().unwrap_or("parallel"); @@ -3243,9 +3262,9 @@ pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> any // Some vendored ESM tests import sibling test files with relative specifiers. // The split runner still executes one configured test at a time, but those // relative imports need the original suite directory shape. - let src_suite_dir = std::path::Path::new("tests/node_compat/suite").join(suite); + let src_suite_dir = std::path::Path::new(esm_root); if suite == "es-module" && src_suite_dir.exists() { - for entry in fs::read_dir(&src_suite_dir)? { + for entry in fs::read_dir(src_suite_dir)? { let entry = entry?; if entry.file_type()?.is_file() { let file_name = entry.file_name(); @@ -3259,18 +3278,18 @@ pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> any } // Copy the common shim - let src_shim = "tests/node_compat/common-shim/index.js"; + let src_shim = format!("{shim_root}/index.js"); let dst_shim = common_dir.join("index.js"); fs::copy(src_shim, &dst_shim)?; // Copy the common ESM shim if it exists - let src_shim_mjs = "tests/node_compat/common-shim/index.mjs"; - if std::path::Path::new(src_shim_mjs).exists() { + let src_shim_mjs = format!("{shim_root}/index.mjs"); + if std::path::Path::new(&src_shim_mjs).exists() { fs::copy(src_shim_mjs, common_dir.join("index.mjs"))?; } // Copy all additional common shims from common-shim directory - let shim_dir = std::path::Path::new("tests/node_compat/common-shim"); + let shim_dir = std::path::Path::new(shim_root); if shim_dir.exists() { for entry in fs::read_dir(shim_dir)? { let entry = entry?; @@ -3288,7 +3307,7 @@ pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> any // Copy vendored ESM common helpers and the trace_events helper that are not replaced by // local shims. - let vendored_common_dir = std::path::Path::new("tests/node_compat/suite/common"); + let vendored_common_dir = std::path::Path::new(vendored_common_root); if vendored_common_dir.exists() { for entry in fs::read_dir(vendored_common_dir)? { let entry = entry?; @@ -3311,13 +3330,13 @@ pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> any let fixtures_dst = test_root.join("fixtures"); // First copy vendored suite fixtures - let vendored_fixtures_src = std::path::Path::new("tests/node_compat/suite/fixtures"); + let vendored_fixtures_src = std::path::Path::new(vendored_fixtures_root); if vendored_fixtures_src.exists() { copy_dir_recursive(vendored_fixtures_src, fixtures_dst.as_std_path())?; } // Then overlay with our custom fixtures (take priority over vendored ones) - let fixtures_src = std::path::Path::new("tests/node_compat/fixtures"); + let fixtures_src = std::path::Path::new(fixtures_root); if fixtures_src.exists() { copy_dir_recursive(fixtures_src, fixtures_dst.as_std_path())?; } @@ -3327,7 +3346,7 @@ pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> any } // Shared sqlite test helpers, such as `require('../sqlite/next-db.js')` - let vendored_sqlite_src = std::path::Path::new("tests/node_compat/suite/sqlite"); + let vendored_sqlite_src = std::path::Path::new(sqlite_root); if vendored_sqlite_src.exists() { copy_dir_recursive(vendored_sqlite_src, test_root.join("sqlite").as_std_path())?; } diff --git a/tests/node_compat.rs b/tests/node_compat.rs index 58a4dc5db..f88ae371a 100644 --- a/tests/node_compat.rs +++ b/tests/node_compat.rs @@ -37,9 +37,21 @@ async fn compiled_node_compat_full() -> CompiledTest { } else { common::FeatureCombination::FullNoLoggingWithGolemAndTypeScript }; - CompiledTest::new_with_features(path, true, feature_combination) - .await - .expect("Failed to compile node-compat-runner") + let evidence = common::measured::Prerequisite::start("component-build") + .expect("record measured prerequisite"); + let compiled = evidence + .finish(CompiledTest::new_with_features(path, true, feature_combination).await) + .expect("Failed to compile node-compat-runner"); + common::measured::component( + compiled.wasm_path().as_std_path(), + if common::truthy_env("WASM_RQUICKJS_TEST_NET_WRITE_PROFILING") { + "node-compat-net-write-profiling" + } else { + "full-no-logging-golem-typescript" + }, + ) + .expect("record measured component"); + compiled } /// Each worker materialises its own `FullPreparedComponent` (which owns @@ -51,8 +63,12 @@ async fn compiled_node_compat_full() -> CompiledTest { fn prepare_node_compat_full( #[tagged_as("node_compat_full_compiled")] compiled: &CompiledTest, ) -> Arc { + let evidence = common::measured::Prerequisite::start("component-prepare") + .expect("record measured prerequisite"); Arc::new(FullPreparedComponent(Arc::new( - GolemPreparedComponent::new(compiled.wasm_path()).expect("Failed to prepare component"), + evidence + .finish(GolemPreparedComponent::new(compiled.wasm_path())) + .expect("Failed to prepare component"), ))) } @@ -627,6 +643,7 @@ fn shard_tag(name: &str) -> String { #[test_gen] fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { + common::measured::node_compat_input_roots().expect("record guest setup input roots"); let entries = load_node_compat_config("tests/node_compat/config.jsonc").expect("Failed to load config"); @@ -640,6 +657,15 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { if !entry.split || entry.subtests.is_empty() { // Non-split: one Rust test per file (unchanged behavior) + common::measured::register( + &file_test_name, + &path, + concat!(module_path!(), "::gen_node_compat_tests"), + entry.category.label(), + entry.reason.as_deref(), + test_timeout_secs, + if entry.flaky { 2 } else { 1 }, + ); let props = TestProperties { is_ignored: entry.category.should_ignore_in_runner(), tags: vec![shard_tag(&file_test_name)], @@ -652,7 +678,7 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { }; r.add_async_test( - file_test_name, + file_test_name.clone(), props, Some(vec![dependency_name.clone()]), move |deps| { @@ -663,27 +689,45 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { .expect("FullPreparedComponent type mismatch"); let prepared = prepared.as_ref().as_ref().0.clone(); let path = path.clone(); + let case = file_test_name.clone(); Box::pin(async move { - let mut instance = TestInstance::from_golem_prepared(&prepared).await?; - instance.set_epoch_deadline(test_timeout_secs); - setup_node_compat_test_files(instance.temp_dir_path(), &path)?; - - let guest_path = format!("/home/node/test/{}", path); - let test_future = async { - let (result, stdout, stderr) = instance - .invoke_and_capture_output_with_stderr( - None, - "run-test", - &[Val::String(guest_path)], - ) - .await; - - handle_test_result(result, &stdout, &stderr) - }; - match timeout(Duration::from_secs(test_timeout_secs), test_future).await { - Ok(result) => result, - Err(_) => Err(timeout_error(&instance, test_timeout_secs)), + let mut evidence = common::measured::Attempt::start(&case)?; + let result = async { + let mut instance = TestInstance::from_golem_prepared(&prepared).await?; + instance.set_epoch_deadline(test_timeout_secs); + setup_node_compat_test_files(instance.temp_dir_path(), &path)?; + + evidence.phase("guest")?; + let guest_path = format!("/home/node/test/{}", path); + let test_future = async { + let (result, stdout, stderr) = instance + .invoke_and_capture_output_with_stderr( + None, + "run-test", + &[Val::String(guest_path)], + ) + .await; + + evidence.logs(&stdout, &stderr)?; + evidence.returned(&result); + handle_test_result(result, &stdout, &stderr) + }; + match timeout(Duration::from_secs(test_timeout_secs), test_future).await + { + Ok(result) => result, + Err(_) => { + evidence.timed_out(); + evidence.logs( + &instance.read_stdout().unwrap_or_default(), + &instance.read_stderr().unwrap_or_default(), + )?; + Err(timeout_error(&instance, test_timeout_secs)) + } + } } + .await; + evidence.finish(&result)?; + result }) }, ); @@ -720,6 +764,15 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { for subtest in &entry.subtests { let test_name = format!("{}__{}", file_test_name, subtest.name); + common::measured::register( + &test_name, + &path, + concat!(module_path!(), "::gen_node_compat_tests"), + subtest.category.label(), + subtest.reason.as_deref(), + test_timeout_secs, + if subtest.flaky { 2 } else { 1 }, + ); let is_ignored = subtest.category.should_ignore_in_runner(); let props = TestProperties { is_ignored, @@ -744,7 +797,7 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { } }; r.add_async_test( - test_name, + test_name.clone(), props, Some(vec![dependency_name.clone()]), move |deps| { @@ -757,56 +810,75 @@ fn gen_node_compat_tests(r: &mut DynamicTestRegistration) { let path = path.clone(); let source = source.clone(); let discovery_clone = discovery_clone.clone(); + let case = test_name.clone(); Box::pin(async move { - let mut instance = TestInstance::from_golem_prepared(&prepared).await?; - instance.set_epoch_deadline(test_timeout_secs); - setup_node_compat_test_files(instance.temp_dir_path(), &path)?; - - // Rewrite the test file to isolate the target subtest - let rewritten = match &discovery_clone { - Some(DiscoveryData::Block(blocks)) => { - rewrite_for_block_with_options( - &source, - blocks, - subtest_index, - isolate_block_subtests, - ) - } - Some(DiscoveryData::NodeTest(tests)) => { - rewrite_for_node_test(&source, tests, subtest_index) + let mut evidence = common::measured::Attempt::start(&case)?; + let result = async { + let mut instance = + TestInstance::from_golem_prepared(&prepared).await?; + instance.set_epoch_deadline(test_timeout_secs); + setup_node_compat_test_files(instance.temp_dir_path(), &path)?; + + // Rewrite the test file to isolate the target subtest + let rewritten = match &discovery_clone { + Some(DiscoveryData::Block(blocks)) => { + rewrite_for_block_with_options( + &source, + blocks, + subtest_index, + isolate_block_subtests, + ) + } + Some(DiscoveryData::NodeTest(tests)) => { + rewrite_for_node_test(&source, tests, subtest_index) + } + None => source.clone(), + }; + + // Write the rewritten file to the temp dir + let test_filename = path.rsplit('/').next().unwrap_or(&path); + let suite = path.split('/').next().unwrap_or("parallel"); + let rewritten_path = instance + .temp_dir_path() + .join("home") + .join("node") + .join("test") + .join(suite) + .join(test_filename); + fs::write(&rewritten_path, &rewritten)?; + + evidence.phase("guest")?; + let guest_path = format!("/home/node/test/{}", path); + let test_future = async { + let (result, stdout, stderr) = instance + .invoke_and_capture_output_with_stderr( + None, + "run-test", + &[Val::String(guest_path)], + ) + .await; + + evidence.logs(&stdout, &stderr)?; + evidence.returned(&result); + handle_test_result(result, &stdout, &stderr) + }; + match timeout(Duration::from_secs(test_timeout_secs), test_future) + .await + { + Ok(result) => result, + Err(_) => { + evidence.timed_out(); + evidence.logs( + &instance.read_stdout().unwrap_or_default(), + &instance.read_stderr().unwrap_or_default(), + )?; + Err(timeout_error(&instance, test_timeout_secs)) + } } - None => source.clone(), - }; - - // Write the rewritten file to the temp dir - let test_filename = path.rsplit('/').next().unwrap_or(&path); - let suite = path.split('/').next().unwrap_or("parallel"); - let rewritten_path = instance - .temp_dir_path() - .join("home") - .join("node") - .join("test") - .join(suite) - .join(test_filename); - fs::write(&rewritten_path, &rewritten)?; - - let guest_path = format!("/home/node/test/{}", path); - let test_future = async { - let (result, stdout, stderr) = instance - .invoke_and_capture_output_with_stderr( - None, - "run-test", - &[Val::String(guest_path)], - ) - .await; - - handle_test_result(result, &stdout, &stderr) - }; - match timeout(Duration::from_secs(test_timeout_secs), test_future).await - { - Ok(result) => result, - Err(_) => Err(timeout_error(&instance, test_timeout_secs)), } + .await; + evidence.finish(&result)?; + result }) }, ); diff --git a/tests/runtime/node_modules_apps.rs b/tests/runtime/node_modules_apps.rs index 9abf4a616..b7cf66e78 100644 --- a/tests/runtime/node_modules_apps.rs +++ b/tests/runtime/node_modules_apps.rs @@ -22,9 +22,21 @@ const FLAKY_MAX_ATTEMPTS: usize = 3; #[test_dep(tagged_as = "node_modules_app_runner", scope = Cloneable)] async fn compiled_node_modules_app_runner() -> CompiledTest { let path = Utf8Path::new("examples/runtime/node-modules-app-runner"); - CompiledTest::new_with_features(path, true, crate::common::FeatureCombination::FullNoLogging) - .await - .expect("Failed to compile node-modules-app-runner") + let evidence = crate::common::measured::Prerequisite::start("component-build") + .expect("record measured prerequisite"); + let compiled = evidence + .finish( + CompiledTest::new_with_features( + path, + true, + crate::common::FeatureCombination::FullNoLogging, + ) + .await, + ) + .expect("Failed to compile node-modules-app-runner"); + crate::common::measured::component(compiled.wasm_path().as_std_path(), "full-no-logging") + .expect("record measured component"); + compiled } struct PreparedNodeModulesApp { @@ -37,20 +49,38 @@ struct InstalledNodeModulesAppTemplate { app_dir: Utf8PathBuf, } -fn install_node_modules_app(app_name: &str, app_dir: &Utf8Path) -> anyhow::Result<()> { - let status = Command::new("npm") +fn install_node_modules_app( + app_name: &str, + app_dir: &Utf8Path, + evidence: &crate::common::measured::Attempt, +) -> anyhow::Result<()> { + let mut command = Command::new("npm"); + command .arg("ci") .arg("--install-links") .arg("--ignore-scripts") .arg("--no-audit") .arg("--no-fund") - .current_dir(app_dir) - .status()?; + .current_dir(app_dir); + let status = if evidence.is_enabled() { + let output = command.output()?; + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + print!("{stdout}"); + eprint!("{stderr}"); + evidence.logs(&stdout, &stderr)?; + output.status + } else { + command.status()? + }; anyhow::ensure!(status.success(), "npm ci failed for {app_name}"); Ok(()) } -fn prepare_uncached_node_modules_app(app_name: &str) -> anyhow::Result { +fn prepare_uncached_node_modules_app( + app_name: &str, + evidence: &crate::common::measured::Attempt, +) -> anyhow::Result { let source_dir = Utf8Path::new("tests") .join("node_modules_apps") .join("apps") @@ -59,7 +89,7 @@ fn prepare_uncached_node_modules_app(app_name: &str) -> anyhow::Result anyhow::Result anyhow::Result> { static INSTALLED_APPS: OnceLock< Mutex>>, @@ -81,6 +112,7 @@ fn installed_node_modules_app_template( .lock() .unwrap(); if let Some(app) = installed_apps.get(app_name) { + evidence.logs("Reused process-local npm ci template", "")?; return Ok(app.clone()); } drop(installed_apps); @@ -102,11 +134,12 @@ fn installed_node_modules_app_template( .lock() .unwrap(); if let Some(app) = installed_apps.get(app_name) { + evidence.logs("Reused process-local npm ci template", "")?; return Ok(app.clone()); } drop(installed_apps); - let prepared = prepare_uncached_node_modules_app(app_name)?; + let prepared = prepare_uncached_node_modules_app(app_name, evidence)?; let template = Arc::new(InstalledNodeModulesAppTemplate { _temp_dir: prepared._temp_dir, app_dir: prepared.app_dir, @@ -119,8 +152,11 @@ fn installed_node_modules_app_template( Ok(template) } -fn prepare_node_modules_app(app_name: &str) -> anyhow::Result { - let template = installed_node_modules_app_template(app_name)?; +fn prepare_node_modules_app( + app_name: &str, + evidence: &crate::common::measured::Attempt, +) -> anyhow::Result { + let template = installed_node_modules_app_template(app_name, evidence)?; let temp_dir = Utf8TempDir::new()?; let app_dir = temp_dir.path().join("app"); copy_dir_recursive(template.app_dir.as_std_path(), app_dir.as_std_path())?; @@ -212,7 +248,11 @@ fn ensure_node_supports_require_esm() -> anyhow::Result { Ok(version) } -fn verify_with_node(app: &PreparedNodeModulesApp, test_file: &str) -> anyhow::Result<()> { +fn verify_with_node( + app: &PreparedNodeModulesApp, + test_file: &str, + evidence: &crate::common::measured::Attempt, +) -> anyhow::Result<()> { let node_version = ensure_node_supports_require_esm()?; println!("Verifying node_modules app baseline with Node.js {node_version}"); let output = Command::new("node") @@ -220,6 +260,10 @@ fn verify_with_node(app: &PreparedNodeModulesApp, test_file: &str) -> anyhow::Re .arg(test_file) .current_dir(&app.app_dir) .output()?; + evidence.logs( + &String::from_utf8_lossy(&output.stdout), + &String::from_utf8_lossy(&output.stderr), + )?; anyhow::ensure!( output.status.success(), "Node baseline failed for {}:\n[stdout]\n{}\n[stderr]\n{}", @@ -235,13 +279,17 @@ async fn run_node_modules_app_test( app_name: &str, test_file: &str, timeout_secs: u64, + evidence: &mut crate::common::measured::Attempt, ) -> anyhow::Result<()> { - let baseline_app = prepare_node_modules_app(app_name)?; - verify_with_node(&baseline_app, test_file)?; + evidence.phase("installation")?; + let baseline_app = prepare_node_modules_app(app_name, evidence)?; + evidence.phase("host-control")?; + verify_with_node(&baseline_app, test_file, evidence)?; + evidence.phase("guest-setup")?; let mut instance = TestInstance::new(compiled_test.wasm_path()).await?; - let guest_app = prepare_node_modules_app(app_name)?; + let guest_app = prepare_node_modules_app(app_name, evidence)?; let mounted_app_dir = instance.temp_dir_path().join("app"); fs::create_dir_all(&mounted_app_dir)?; copy_dir_recursive( @@ -252,11 +300,13 @@ async fn run_node_modules_app_test( // Fixture preparation is host-side setup and can be expensive under concurrent // group9 load. The deadline should bound guest execution, not app copying. instance.set_epoch_deadline(timeout_secs); + evidence.phase("guest")?; let guest_test_path = format!("/app/{test_file}"); let (result, stdout, stderr) = instance .invoke_and_capture_output_with_stderr(None, "run-test", &[Val::String(guest_test_path)]) .await; + evidence.logs(&stdout, &stderr)?; let result = result?; println!("Output:\n{}", stdout); if !stderr.trim().is_empty() { @@ -296,13 +346,22 @@ fn gen_node_modules_app_tests(r: &mut DynamicTestRegistration) { let timeout_secs = test.timeout_secs; let flaky = test.flaky; let generated_test_name = test_name(&app, &test); + crate::common::measured::register( + &generated_test_name, + &format!("{app_name}/{test_file}"), + concat!(module_path!(), "::gen_node_modules_app_tests"), + test.category.label(), + test.reason.as_deref(), + timeout_secs, + if flaky { FLAKY_MAX_ATTEMPTS } else { 1 }, + ); let props = TestProperties { is_ignored: test.category.should_ignore_in_runner(), ..TestProperties::unit_test() }; r.add_async_test( - generated_test_name, + generated_test_name.clone(), props, Some(vec![dependency_name.clone()]), move |deps| { @@ -313,18 +372,22 @@ fn gen_node_modules_app_tests(r: &mut DynamicTestRegistration) { .expect("CompiledTest type mismatch"); let app_name = app_name.clone(); let test_file = test_file.clone(); + let case = generated_test_name.clone(); Box::pin(async move { let max_attempts = if flaky { FLAKY_MAX_ATTEMPTS } else { 1 }; let mut last_err = None; for attempt in 1..=max_attempts { - match run_node_modules_app_test( + let mut evidence = crate::common::measured::Attempt::start(&case)?; + let result = run_node_modules_app_test( compiled_test.as_ref(), &app_name, &test_file, timeout_secs, + &mut evidence, ) - .await - { + .await; + evidence.finish(&result)?; + match result { Ok(()) => return Ok(()), Err(e) => { if flaky && attempt < max_attempts { diff --git a/tools/measured-report.cjs b/tools/measured-report.cjs new file mode 100644 index 000000000..9ce122873 --- /dev/null +++ b/tools/measured-report.cjs @@ -0,0 +1,564 @@ +#!/usr/bin/env node +// Local evidence only. No agents, uploads, classification changes or CI selection changes. +'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { spawnSync } = require('node:child_process'); +const assert = require('node:assert/strict'); + +const ROOT = path.resolve(__dirname, '..'); +const OUTCOMES = ['pass', 'fail', 'skip', 'timeout', 'blocked', 'not-run']; +const PROFILES = ['api', 'installed', 'bundled']; +const text = file => fs.readFileSync(file, 'utf8'); +const read = file => JSON.parse(text(file)); +const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +const sorted = value => Array.isArray(value) ? value.map(sorted) : value && typeof value === 'object' + ? Object.fromEntries(Object.keys(value).sort().map(key => [key, sorted(value[key])])) : value; +const json = value => JSON.stringify(sorted(value), null, 2) + '\n'; +const save = (file, value, flag = 'wx') => fs.writeFileSync(file, json(value), { flag }); +const now = () => new Date().toISOString(); +const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0; +const relative = (root, file) => path.relative(root, file).split(path.sep).join('/'); +const id = value => { assert.match(value, /^[a-zA-Z0-9_-]+$/, 'unsafe execution ID'); return value; }; +function files(dir, fixtureInputs = false) { + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => compare(a.name, b.name)) + .flatMap(item => { + const file = path.join(dir, item.name); + if (item.isSymbolicLink()) { + assert(fixtureInputs, 'symlink in evidence'); + assert(fs.realpathSync(file).startsWith(path.join(ROOT, 'tests/node_compat') + path.sep), 'fixture link leaves fixture tree'); + } + return fs.statSync(file).isDirectory() ? files(file, fixtureInputs) : [file]; + }); +} +function apiInputs(cases, roots) { + // Guest setup publishes its own input roots; retain their superset, including ignored files. + const inputs = new Set(['tests/node_compat/suite/NODE_VERSION', ...cases.map(item => `tests/node_compat/suite/${item.fixture}`)]); + assert(Array.isArray(roots) && roots.length, 'missing guest setup input roots'); + for (const directory of roots) { + assert(typeof directory === 'string' && directory.startsWith('tests/node_compat/'), 'invalid guest setup input root'); + for (const file of files(within(ROOT, directory), true)) inputs.add(relative(ROOT, file)); + } + return [...inputs].sort(); +} +function checkInstalledInputs(entry) { + for (const fixture of new Set(entry.cases.map(item => item.fixture.split('/')[0]))) { + const root = within(ROOT, `tests/node_modules_apps/apps/${fixture}`); + for (const file of files(root)) { + const input = `inputs/${relative(ROOT, file)}`; + assert(Object.hasOwn(entry.inputs, input), `uncaptured installed fixture input: ${input}`); + } + } +} +function within(root, relative) { + assert(typeof relative === 'string' && relative && !relative.includes('\\') && !path.isAbsolute(relative)); + assert(!relative.split('/').some(part => !part || part === '.' || part === '..'), 'unsafe evidence path'); + const file = path.join(root, relative); + let current = root; + for (const part of relative.split('/')) { + current = path.join(current, part); + if (fs.existsSync(current)) assert(!fs.lstatSync(current).isSymbolicLink(), 'symlink in evidence'); + } + return file; +} +function checksums(dir, exclude = []) { + return Object.fromEntries(files(dir).map(file => [relative(dir, file), hash(fs.readFileSync(file))]) + .filter(([relative]) => !exclude.includes(relative))); +} +function checkDigests(dir, expected, exact = false, exclude = []) { + assert(expected && typeof expected === 'object' && !Array.isArray(expected), 'missing checksums'); + for (const [relative, digest] of Object.entries(expected)) { + assert.match(digest, /^[0-9a-f]{64}$/); + assert.equal(hash(fs.readFileSync(within(dir, relative))), digest, `digest mismatch: ${relative}`); + } + if (exact) assert.deepEqual(checksums(dir, exclude), expected, 'missing or unclaimed evidence'); +} +function commandVersion(command, args) { + const result = spawnSync(command, args, { cwd: ROOT, encoding: 'utf8' }); + return result.status === 0 ? result.stdout.trim() : 'unavailable'; +} +function toolchain(profile) { + return { producerNode: process.version, rustc: commandVersion('rustc', ['--version']), + cargo: commandVersion('cargo', ['--version']), + ...(profile === 'api' ? { apiTarget: text(path.join(ROOT, 'tests/node_compat/suite/NODE_VERSION')).trim() } + : { nodeControl: commandVersion('node', ['--version']), npm: commandVersion('npm', ['--version']) }), + ...(profile === 'bundled' ? { wasmtime: commandVersion('wasmtime', ['--version']) } : {}) }; +} +function source() { + const revision = commandVersion('git', ['rev-parse', 'HEAD']); + assert.match(revision, /^[0-9a-f]{40}$/); + const patch = spawnSync('git', ['diff', '--binary', 'HEAD'], { cwd: ROOT }); + assert.equal(patch.status, 0); + // Include the producer even before its first commit; never copy arbitrary untracked files. + const producer = ['tools/measured-report.cjs', 'tests/common/measured.rs', 'tests/common/mod.rs', + 'tests/node_compat.rs', 'tests/runtime/node_modules_apps.rs'].map(file => [file, hash(fs.readFileSync(path.join(ROOT, file)))]); + return { revision, dirtyPatchSha256: hash(patch.stdout), producerInputs: Object.fromEntries(producer) }; +} +function validatePlan(plan) { + assert.equal(plan.schemaVersion, 1); + assert(Array.isArray(plan.executions)); + const ids = new Set(); + for (const entry of plan.executions) { + id(entry.id); assert(!ids.has(entry.id), 'duplicate execution'); ids.add(entry.id); + assert(PROFILES.includes(entry.profile), 'unknown profile'); + assert([entry.consumer, entry.artifactRole, entry.lane, entry.workflowRun].every(value => typeof value === 'string' && value)); + assert(Number.isSafeInteger(entry.workflowAttempt) && entry.workflowAttempt >= 1); + assert.match(entry.source.revision, /^[0-9a-f]{40}$/); + assert(Array.isArray(entry.cases) && entry.cases.length, 'empty expected inventory'); + assert(Array.isArray(entry.behaviorCases) && new Set(entry.behaviorCases).size === entry.behaviorCases.length, 'invalid behavior declaration'); + assert(entry.behaviorCases.every(name => entry.cases.some(item => item.id === name && item.coverage !== 'import')), 'unknown/import-only behavior declaration'); + const cases = new Set(); + for (const item of entry.cases) { + assert(typeof item.id === 'string' && item.id && !cases.has(item.id), 'duplicate/invalid case ID'); cases.add(item.id); + assert(item.runnerName && item.fixture && ['unclassified', 'behavior', 'import'].includes(item.coverage)); + assert(typeof item.classification === 'string' && item.classification); + if (item.classification !== 'runnable') assert(item.skipReason, 'skip needs reason'); + assert(Number.isSafeInteger(item.maxAttempts) && item.maxAttempts > 0); + assert(Number.isFinite(item.timeoutSeconds) && item.timeoutSeconds > 0); + } + } +} +function environment(entry, dir) { + return { ...process.env, CARGO_INCREMENTAL: '0', WASM_RQUICKJS_MEASURE_DIR: dir, + WASM_RQUICKJS_MEASURE_FILTER: entry.filter, + ...(entry.profile === 'installed' ? { NODE_MODULES_APP_STRICT_NODE_BASELINE: '1' } : {}) }; +} +function harness(entry, extra) { + return ['tools/dev-test.sh', 'stock', 'fast-run', entry.profile === 'api' ? 'node_compat' : 'runtime', entry.filter, ...extra]; +} +function execute(dir, name, command, cwd, env, timeoutSeconds = 0, binding = {}, publication = null) { + const startedAt = now(); + save(path.join(dir, `${name}-start.json`), { ...binding, command, startedAt, timeoutSeconds }); + const stdout = fs.openSync(path.join(dir, `${name}-stdout.txt`), 'wx'); + const stderr = fs.openSync(path.join(dir, `${name}-stderr.txt`), 'wx'); + let result; + let publicationError = null; + try { + result = spawnSync(command[0], command.slice(1), { cwd, env, stdio: ['ignore', stdout, stderr], + ...(timeoutSeconds ? { timeout: timeoutSeconds * 1000, killSignal: 'SIGKILL' } : {}) }); + } catch (error) { result = { status: null, signal: null, error }; } + finally { + fs.closeSync(stdout); fs.closeSync(stderr); + } + if (publication && result.status === 0) { + try { fs.copyFileSync(publication.source, publication.destination, fs.constants.COPYFILE_EXCL); } + catch (error) { publicationError = error.message; } + } + const finish = { ...binding, command, startedAt, finishedAt: now(), exitCode: result.status, + signal: result.signal, error: result.error?.message || null, publicationError, + outcome: result.error?.code === 'ETIMEDOUT' ? 'timeout' : result.status === 0 && !publicationError ? 'pass' : 'fail' }; + if (binding.phase === 'guest' && finish.outcome === 'pass') { + const last = text(path.join(dir, `${name}-stdout.txt`)).trim().split(/\r?\n/).at(-1); + try { finish.returned = JSON.parse(last); } catch { finish.returned = last; } + if (typeof finish.returned !== 'string' || !finish.returned.startsWith('PASS')) { + finish.outcome = 'fail'; finish.error = 'guest run() did not return PASS'; + } + } + save(path.join(dir, `${name}-finish.json`), finish); + return finish; +} + +function plan(bundle, executionId, profile, filter, metadata = {}) { + id(executionId); assert(PROFILES.includes(profile)); assert(filter && !filter.startsWith('-'), 'a narrow filter is required'); + assert(!filter.startsWith(':tag:'), 'select generated case names, not tags'); + assert(Object.keys(metadata).every(key => ['consumer', 'artifactRole', 'lane', 'workflowRun', 'workflowAttempt', 'behaviorCases'].includes(key)), 'unknown metadata'); + fs.mkdirSync(bundle, { recursive: true }); + const planFile = path.join(bundle, 'plan.json'); + const existing = fs.existsSync(planFile) ? read(planFile) : { schemaVersion: 1, executions: [] }; + assert(!existing.executions.some(entry => entry.id === executionId), 'execution already planned'); + const dir = path.join(bundle, 'executions', executionId); + fs.mkdirSync(dir, { recursive: true }); + const entry = { id: executionId, profile, filter, consumer: 'local-wasmtime', artifactRole: 'candidate', + lane: profile, workflowRun: 'local', workflowAttempt: 1, behaviorCases: [], ...metadata, source: source(), + toolchain: toolchain(profile), + runner: { host: 'stock', profile: 'fast-run', component: profile === 'api' ? 'full-no-logging-golem-typescript' : 'full-no-logging' } }; + assert(Object.values(entry.toolchain).every(value => value !== 'unavailable'), 'install the recorded toolchain before planning'); + if (profile === 'bundled') { + assert.match(filter, /^[a-zA-Z0-9_-]+\/test-\d[^/]*\.js$/, 'select an existing offline behavior fixture'); + assert(fs.existsSync(path.join(ROOT, 'tests/libraries', filter))); + entry.runner = { host: 'wasmtime-cli', profile: 'debug-unoptimized', component: 'full-no-logging-p3' }; + entry.cases = [{ id: filter, runnerName: filter, fixture: filter, classification: 'runnable', skipReason: null, + coverage: 'unclassified', maxAttempts: 1, timeoutSeconds: 60 }]; + } else { + const discovery = execute(dir, 'discovery', ['bash', ...harness(entry, ['--list'])], ROOT, environment(entry, dir)); + assert.equal(discovery.outcome, 'pass', 'inventory discovery failed; see raw discovery logs'); + entry.cases = files(path.join(dir, 'inventory')).map(read).sort((a, b) => compare(a.id, b.id)); + const listed = text(path.join(dir, 'discovery-stdout.txt')).split(/\r?\n/).filter(line => /^\S+::\S+$/.test(line)).sort(); + assert.deepEqual(listed, entry.cases.map(item => item.runnerName).sort(), 'filter selects tests outside measured inventory'); + } + const inputs = new Set(['Cargo.toml', 'Cargo.lock', 'tools/dev-test.sh', + 'crates/wasm-rquickjs/skeleton/Cargo.toml_', 'crates/wasm-rquickjs/skeleton/Cargo.lock', + ...Object.keys(entry.source.producerInputs)]); + if (profile === 'api') { + inputs.add('tests/node_compat/config.jsonc'); inputs.add('tests/node_compat/vendor.sh'); + entry.apiInputRoots = read(path.join(dir, 'input-roots.json')); + entry.apiInputs = apiInputs(entry.cases, entry.apiInputRoots); + for (const file of entry.apiInputs) inputs.add(file); + } else { + if (profile === 'installed') inputs.add('tests/node_modules_apps/config.jsonc'); + const fixtures = new Set(entry.cases.map(item => item.fixture.split('/')[0])); + for (const fixture of fixtures) { + const prefix = `tests/${profile === 'installed' ? 'node_modules_apps/apps' : 'libraries'}/${fixture}/`; + const result = spawnSync('git', ['ls-files', '-z', '--', prefix], { cwd: ROOT, encoding: 'utf8' }); + assert.equal(result.status, 0); + for (const file of result.stdout.split('\0').filter(Boolean)) if (profile === 'installed' || !file.endsWith('results.md')) inputs.add(file); + } + } + entry.inputs = {}; + for (const relative of [...inputs].sort()) { + const destination = within(dir, `inputs/${relative}`); + fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.copyFileSync(path.join(ROOT, relative), destination, fs.constants.COPYFILE_EXCL); + entry.inputs[`inputs/${relative}`] = hash(fs.readFileSync(destination)); + } + if (profile === 'installed') checkInstalledInputs(entry); + existing.executions.push(entry); + validatePlan(existing); + save(planFile, existing, 'w'); + fs.writeFileSync(path.join(dir, 'identity.txt'), hash(json(entry)), { flag: 'wx' }); + const selectionFile = path.join(bundle, 'selection.json'); + const selection = fs.existsSync(selectionFile) ? read(selectionFile) : []; + // Reruns stay retained but must be selected explicitly, never picked by outcome. + if (!existing.executions.some(old => old.id !== entry.id && old.profile === profile && old.lane === entry.lane && + old.artifactRole === entry.artifactRole && old.consumer === entry.consumer)) selection.push(entry.id); + save(selectionFile, selection, 'w'); + return entry; +} + +function runBundled(entry, dir) { + const [library, fixture] = entry.filter.split('/'); + const work = path.join(ROOT, 'tmp', `measured-${entry.id}`); + assert(!fs.existsSync(work), 'fixture work directory already exists'); + fs.mkdirSync(work, { recursive: true }); + const app = path.join(work, 'app'); fs.mkdirSync(app); + for (const relative of Object.keys(entry.inputs)) { + const prefix = `inputs/tests/libraries/${library}/`; + if (relative.startsWith(prefix)) { + const destination = within(app, relative.slice(prefix.length)); + fs.mkdirSync(path.dirname(destination), { recursive: true }); fs.copyFileSync(within(dir, relative), destination); + } + } + const attemptDir = path.join(dir, 'attempts', 'bundled', '0001'); fs.mkdirSync(attemptDir, { recursive: true }); + const identity = hash(json(entry)); + const componentName = `measured_${identity}`; + const binding = { identity, caseId: entry.filter, ordinal: 1 }; + save(path.join(attemptDir, 'start.json'), { ...binding, startedAt: now() }); + const bundle = path.join(app, 'dist', fixture.replace('.js', '.bundle.js')); + const component = path.join(work, 'component'); + const wasm = path.join(dir, 'component.wasm'); + const guestRoot = path.join(work, 'guest'); fs.mkdirSync(guestRoot); + const phases = [ + ['installation', ['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], app], + ['bundling', ['node', 'node_modules/rollup/dist/bin/rollup', '-c', 'rollup.config.mjs'], app], + ['host-control', ['node', 'run-node.mjs', `./dist/${path.basename(bundle)}`], app], + ['producer-build', ['cargo', 'build', '--locked', '--bin', 'wasm-rquickjs', '--features', 'wasm-rquickjs/external-skeleton'], ROOT], + ['generation', [path.join(ROOT, 'target/debug/wasm-rquickjs'), 'generate-wrapper-crate', '--js', bundle, + '--wit', path.join(app, 'wit'), '--output', component], ROOT], + ['component-build', ['cargo', 'build', '--locked', '--target', 'wasm32-wasip2', + '--no-default-features', '--features', 'full-no-logging-p3'], component], + ['guest', ['wasmtime', 'run', '--wasm', 'component-model', '--wasm', 'component-model-async', + '-S', 'cli', '-S', 'p3', '-S', 'http', '-S', 'inherit-network', '--dir', `${guestRoot}::/`, '--invoke', 'run()'], ROOT], + ]; + let final = { outcome: 'pass', reason: '', failedPhase: null }; + for (let i = 0; i < phases.length; i++) { + const [phase, command, cwd] = phases[i]; + let publication = null; + if (phase === 'component-build') { + // Cargo's lock ends before publication. Give each execution its own output name, + // so another fixture cannot overwrite it between build, copy, hash and invocation. + const manifest = path.join(component, 'Cargo.toml'); + const generated = text(manifest); + assert(generated.includes('[lib]\n'), 'generated library manifest missing'); + fs.writeFileSync(manifest, generated.replace('[lib]\n', `[lib]\nname = "${componentName}"\n`)); + publication = { source: path.join(ROOT, 'target', 'wasm32-wasip2', 'debug', `${componentName}.wasm`), destination: wasm }; + } + if (phase === 'guest') { + save(path.join(dir, 'component.json'), { identity, algorithm: 'sha256', digest: hash(fs.readFileSync(wasm)), features: entry.runner.component }); + command.push(wasm); + } + const prefix = `phase-${String(i + 1).padStart(4, '0')}`; + const result = execute(attemptDir, prefix, command, cwd, { ...process.env, CARGO_INCREMENTAL: '0', CARGO_TARGET_DIR: path.join(ROOT, 'target') }, + phase === 'guest' ? entry.cases[0].timeoutSeconds : 1800, { ...binding, phase }, publication); + if (result.outcome !== 'pass') { + final = { outcome: phase === 'guest' ? result.outcome : 'blocked', reason: `failed ${phase}: ${result.publicationError || result.error || result.exitCode}`, failedPhase: phase }; + break; + } + } + save(path.join(attemptDir, 'finish.json'), { ...binding, ...final, finishedAt: now() }); + return final; +} + +function checkLiveInputs(entry, dir) { + assert.deepEqual(source(), entry.source, 'source changed since inventory; plan a new execution'); + assert.deepEqual(toolchain(entry.profile), entry.toolchain, 'toolchain changed since inventory; plan a new execution'); + if (entry.profile === 'api') assert.deepEqual(apiInputs(entry.cases, entry.apiInputRoots), entry.apiInputs, 'supporting fixture inventory changed'); + if (entry.profile === 'installed') checkInstalledInputs(entry); + checkDigests(dir, entry.inputs); + for (const [relative, digest] of Object.entries(entry.inputs)) { + // Input symlinks are dereferenced just as fs::copy does in guest setup; retained evidence has no symlinks. + assert.equal(hash(fs.readFileSync(path.join(ROOT, relative.slice('inputs/'.length)))), digest, 'fixture input changed since inventory'); + } +} +function run(bundle, executionId) { + const manifest = read(path.join(bundle, 'plan.json')); validatePlan(manifest); + const entry = manifest.executions.find(item => item.id === executionId); assert(entry, 'unknown execution'); + const dir = path.join(bundle, 'executions', id(executionId)); + checkLiveInputs(entry, dir); + assert.equal(text(path.join(dir, 'identity.txt')), hash(json(entry))); + save(path.join(dir, 'run-start.json'), { identity: hash(json(entry)), toolchain: toolchain(entry.profile), startedAt: now() }); + let result; + if (entry.profile === 'bundled') { + result = runBundled(entry, dir); + } else { + result = execute(dir, 'harness', ['bash', ...harness(entry, ['--format', 'ctrf', '--logfile', path.join(dir, 'ctrf.json')])], ROOT, environment(entry, dir)); + } + checkLiveInputs(entry, dir); + save(path.join(dir, 'run-finish.json'), { identity: hash(json(entry)), ...result, finishedAt: now() }); + save(path.join(dir, 'evidence.json'), checksums(dir, ['evidence.json'])); + return result; +} + +function totals(cases) { + const result = Object.fromEntries(OUTCOMES.map(outcome => [outcome, cases.filter(item => item.outcome === outcome).length])); + result.selected = cases.length; + result.flakyPasses = cases.filter(item => item.outcome === 'pass' && item.flaky).length; + result.nonFlakyPasses = result.pass - result.flakyPasses; + result.properlyImplemented = cases.filter(item => item.qualified).length; + result.properlyImplementedPercent = cases.length ? Number((100 * result.properlyImplemented / cases.length).toFixed(2)) : 0; + result.attempts = cases.reduce((sum, item) => sum + item.attempts.length, 0); + return result; +} +function normalize(bundle) { + const plan = read(path.join(bundle, 'plan.json')); validatePlan(plan); + const selection = read(path.join(bundle, 'selection.json')); + assert(Array.isArray(selection) && new Set(selection).size === selection.length, 'duplicate selection'); + assert(selection.every(value => plan.executions.some(entry => entry.id === value)), 'unknown selected execution'); + const groups = new Set(); + const executions = [...plan.executions].sort((a, b) => compare(a.id, b.id)).map(entry => { + const dir = path.join(bundle, 'executions', entry.id); + const identity = hash(json(entry)); + const selected = selection.includes(entry.id); + const group = json([entry.artifactRole, entry.consumer, entry.profile, entry.lane]); + if (selected) { assert(!groups.has(group), 'multiple selected executions for one lane/profile/artifact role'); groups.add(group); } + const sealed = fs.existsSync(path.join(dir, 'evidence.json')); + if (sealed) checkDigests(dir, read(path.join(dir, 'evidence.json')), true, ['evidence.json']); + checkDigests(dir, entry.inputs); + const component = fs.existsSync(path.join(dir, 'component.json')) ? read(path.join(dir, 'component.json')) : null; + if (component) { + assert.equal(component.identity, identity, 'cross-artifact component'); assert.match(component.digest, /^[0-9a-f]{64}$/); + assert(['sha256', 'blake3'].includes(component.algorithm)); + assert.equal(component.features, entry.runner.component, 'component feature mismatch'); + if (entry.profile === 'bundled') { + assert.equal(component.algorithm, 'sha256'); + assert.equal(component.digest, hash(fs.readFileSync(path.join(dir, 'component.wasm'))), 'published component digest mismatch'); + } + } + // Before publication, identify the planned artifact without execution/lane/retry identity. + const artifact = component?.digest || `unbuilt:${hash(json([entry.artifactRole, entry.source, entry.runner.component]))}`; + const runStart = fs.existsSync(path.join(dir, 'run-start.json')) ? read(path.join(dir, 'run-start.json')) : null; + if (runStart) { + assert.equal(runStart.identity, identity, 'cross-execution start'); + assert.deepEqual(runStart.toolchain, entry.toolchain, 'execution toolchain mismatch'); + } + const runFinish = fs.existsSync(path.join(dir, 'run-finish.json')) ? read(path.join(dir, 'run-finish.json')) : null; + if (runFinish) { + assert.equal(runFinish.identity, identity, 'cross-execution result'); + assert(runStart && Date.parse(runFinish.finishedAt) >= Date.parse(runStart.startedAt), 'completion without valid run start'); + } + if (entry.profile !== 'bundled') { + const inventory = files(path.join(dir, 'inventory')).map(read).sort((a, b) => compare(a.id, b.id)); + assert.deepEqual(inventory, [...entry.cases].sort((a, b) => compare(a.id, b.id)), 'inventory drift'); + } + const prerequisites = files(path.join(dir, 'prerequisites')).filter(file => path.basename(file) === 'start.json').map(file => { + const start = read(file); + assert.equal(start.identity, identity, 'cross-execution prerequisite'); + assert(runStart && Date.parse(start.startedAt) >= Date.parse(runStart.startedAt), 'prerequisite without run start'); + const finishFile = path.join(path.dirname(file), 'finish.json'); + const finish = fs.existsSync(finishFile) ? read(finishFile) : null; + if (finish) { + assert.equal(finish.identity, identity); assert.equal(finish.phase, start.phase); + assert(['pass', 'fail'].includes(finish.outcome)); + assert(Date.parse(finish.finishedAt) >= Date.parse(start.startedAt)); + if (finish.outcome === 'fail') assert(finish.reason); + } + return { ...start, ...finish, outcome: finish?.outcome || 'not-run', evidence: relative(bundle, file) }; + }); + for (const file of files(path.join(dir, 'prerequisites')).filter(file => path.basename(file) === 'finish.json')) { + assert(fs.existsSync(path.join(path.dirname(file), 'start.json')), 'prerequisite completion without start'); + } + const starts = files(path.join(dir, 'attempts')).filter(file => path.basename(file) === 'start.json'); + const attempts = starts.map(startFile => { + const start = read(startFile); const attemptDir = path.dirname(startFile); + assert(runStart, 'attempt without execution start'); + assert.equal(start.identity, identity, 'cross-artifact attempt'); + assert(Number.isSafeInteger(start.ordinal) && start.ordinal > 0); + assert(entry.cases.some(item => item.id === start.caseId), 'unknown case ID'); + const finishFile = path.join(attemptDir, 'finish.json'); + const finish = fs.existsSync(finishFile) ? read(finishFile) : null; + if (finish) { + assert.equal(finish.identity, identity); assert.equal(finish.caseId, start.caseId); assert.equal(finish.ordinal, start.ordinal); + assert(OUTCOMES.includes(finish.outcome) && finish.outcome !== 'not-run'); + assert(Date.parse(finish.finishedAt) >= Date.parse(start.startedAt), 'contradictory attempt times'); + if (finish.outcome !== 'pass') assert(finish.reason, 'missing failure/skip reason'); + } + const phaseStarts = files(attemptDir).filter(file => /phase-\d+-start\.json$/.test(file)); + const phases = phaseStarts.map((file, index) => { + assert.equal(path.basename(file), `phase-${String(index + 1).padStart(4, '0')}-start.json`, 'missing/duplicate phase'); + const phaseStart = read(file); + assert.equal(phaseStart.identity, identity); assert.equal(phaseStart.caseId, start.caseId); assert.equal(phaseStart.ordinal, start.ordinal); + const phaseFinishFile = file.replace('-start.json', '-finish.json'); + const end = fs.existsSync(phaseFinishFile) ? read(phaseFinishFile) : null; + if (end) { + assert.equal(end.identity, identity); assert.equal(end.caseId, start.caseId); assert.equal(end.ordinal, start.ordinal); + assert.equal(end.phase, phaseStart.phase); assert(OUTCOMES.includes(end.outcome)); + assert(Date.parse(end.finishedAt) >= Date.parse(phaseStart.startedAt)); + } + const prefix = file.slice(0, -'-start.json'.length); + const logs = ['stdout', 'stderr'].map(kind => `${prefix}-${kind}.txt`).filter(fs.existsSync) + .map(log => ({ path: relative(bundle, log), sha256: hash(fs.readFileSync(log)) })); + return { ...phaseStart, ...end, outcome: end?.outcome || 'not-run', logs }; + }); + for (const file of files(attemptDir).filter(file => /phase-\d+-finish\.json$/.test(file))) { + assert(fs.existsSync(file.replace('-finish.json', '-start.json')), 'phase completion without start'); + } + if (finish) { + assert(phases.length && phases.every(phase => phase.outcome !== 'not-run'), 'completion with unfinished phase'); + const last = phases.at(-1); + assert(phases.slice(0, -1).every(phase => phase.outcome === 'pass'), 'continued after failed phase'); + if (finish.outcome === 'blocked') assert(['fail', 'timeout'].includes(last.outcome), 'blocked without prerequisite failure'); + else assert.equal(last.outcome, finish.outcome, 'contradictory terminal phase'); + assert.equal(last.phase === 'guest', finish.outcome !== 'blocked', 'prerequisite/guest outcome mismatch'); + assert.equal(finish.failedPhase, ['pass', 'skip'].includes(finish.outcome) ? null : last.phase, 'incorrect failed phase'); + } + let preceding = start.startedAt; + for (const phase of phases) { + assert(Date.parse(phase.startedAt) >= Date.parse(preceding), 'phase precedes attempt/previous phase'); + if (phase.finishedAt) { + if (finish) assert(Date.parse(phase.finishedAt) <= Date.parse(finish.finishedAt), 'phase after attempt completion'); + preceding = phase.finishedAt; + } + } + if (finish?.outcome === 'pass') assert(phases.length && phases.every(phase => phase.outcome === 'pass') && + phases.some(phase => phase.phase === 'guest' && phase.logs.length === 2), 'pass without completed guest evidence'); + return { ...start, ...finish, outcome: finish?.outcome || 'not-run', reason: finish ? finish.reason : 'interrupted attempt', + evidence: relative(bundle, startFile), phases }; + }); + // Orphan completions are invalid, not silently discarded as missing starts. + for (const file of files(path.join(dir, 'attempts')).filter(file => path.basename(file) === 'finish.json')) { + assert(fs.existsSync(path.join(path.dirname(file), 'start.json')), 'completion without start'); + } + const cases = [...entry.cases].sort((a, b) => compare(a.id, b.id)).map(item => { + const history = attempts.filter(attempt => attempt.caseId === item.id).sort((a, b) => a.ordinal - b.ordinal); + assert(new Set(history.map(attempt => attempt.ordinal)).size === history.length, 'duplicate attempt ID'); + assert(history.every((attempt, index) => attempt.ordinal === index + 1), 'missing retry'); + assert(history.length <= item.maxAttempts, 'retry policy exceeded'); + assert(!history.slice(0, -1).some(attempt => attempt.outcome === 'pass'), 'retry after success'); + let outcome = history.at(-1)?.outcome; + let reason = history.at(-1)?.reason || ''; + if (!outcome) { + if (item.classification !== 'runnable') { outcome = 'skip'; reason = item.skipReason; } + else if (prerequisites.some(item => item.outcome === 'fail')) { + outcome = 'blocked'; reason = prerequisites.filter(item => item.outcome === 'fail').map(item => `${item.phase}: ${item.reason}`).join('; '); + } + else { outcome = 'not-run'; reason = 'expected case has no invocation'; } + } + const flaky = outcome === 'pass' && history.some(attempt => attempt.outcome !== 'pass'); + if (history.length) assert(component || outcome === 'blocked' || outcome === 'not-run', 'guest attempt without component identity'); + const coverage = entry.behaviorCases.includes(item.id) ? 'behavior' : item.coverage; + return { ...item, coverage, key: [artifact, entry.consumer, entry.profile, item.id], outcome, reason, flaky, + qualified: outcome === 'pass' && !flaky && entry.behaviorCases.includes(item.id) && sealed && !!runFinish, attempts: history }; + }); + const raw = files(dir).filter(file => path.dirname(file) === dir && /^(ctrf.*\.json|(?:harness|discovery)-(?:stdout|stderr)\.txt)$/.test(path.basename(file))) + .map(file => ({ path: relative(bundle, file), sha256: hash(fs.readFileSync(file)) })); + const reported = new Set(); + for (const evidence of raw.filter(file => path.basename(file.path).startsWith('ctrf'))) { + const file = within(bundle, evidence.path); + if (!text(file).trim()) continue; // A prerequisite failure can leave an empty runner report. + const ctrf = read(file); + assert(Array.isArray(ctrf.results?.tests), 'invalid raw CTRF'); + for (const result of ctrf.results.tests) { + const item = cases.find(item => item.runnerName === result?.name); + assert(item, 'unknown CTRF case'); assert(!reported.has(item.id), 'duplicate CTRF result'); reported.add(item.id); + assert(['passed', 'failed', 'skipped', 'pending', 'other'].includes(result.status), 'invalid CTRF status'); + if (item.attempts.length && item.outcome !== 'not-run') { + const expected = item.outcome === 'pass' ? ['passed'] : item.outcome === 'skip' ? ['passed', 'skipped'] : ['failed']; + assert(expected.includes(result.status), 'CTRF contradicts captured result'); + } + } + } + if (entry.profile !== 'bundled') for (const item of cases) item.qualified &&= reported.has(item.id); + const complete = sealed && !!runFinish && prerequisites.every(item => item.outcome !== 'not-run') && cases.every(item => item.outcome !== 'not-run' && + item.attempts.every(attempt => attempt.outcome !== 'not-run') && + (entry.profile === 'bundled' || item.outcome === 'blocked' || reported.has(item.id))); + return { ...entry, identity, selected, component, prerequisites, complete, raw, cases, totals: totals(cases) }; + }); + const selected = executions.filter(entry => entry.selected); + const selectedKeys = new Set(); + for (const item of selected.flatMap(entry => entry.cases)) { + const key = json(item.key); + assert(!selectedKeys.has(key), 'overlapping selected case key'); + selectedKeys.add(key); + } + return { schemaVersion: 1, claim: 'Selected local assertions only; not full API support, host durability or shipped qualification.', + complete: selected.length > 0 && selected.every(entry => entry.complete), executions, + totals: totals(selected.flatMap(entry => entry.cases)) }; +} +function render(report) { + assert.equal(report.schemaVersion, 1); assert(Array.isArray(report.executions)); + assert.deepEqual(report.totals, totals(report.executions.filter(entry => entry.selected).flatMap(entry => entry.cases)), 'invalid report totals'); + const escape = value => String(value).replace(/[|\r\n]/g, ' '); + const rows = ['# Measured execution report', '', report.claim, + '', `Complete selected evidence: **${report.complete}**`, '', + '| Execution | Profile | Selected | Cases | Non-flaky pass | Flaky pass | Properly implemented* | Attempts |', + '| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |']; + for (const entry of report.executions) { + assert.deepEqual(entry.totals, totals(entry.cases)); + const t = entry.totals; + rows.push(`| ${escape(entry.id)} | ${entry.profile} | ${entry.selected} | ${t.selected} | ${t.nonFlakyPasses} | ${t.flakyPasses} | ${t.properlyImplemented}/${t.selected} (${t.properlyImplementedPercent}%) | ${t.attempts} |`); + } + const t = report.totals; + rows.push('', `Selected total: ${t.selected}; non-flaky passes: ${t.nonFlakyPasses}; flaky passes: ${t.flakyPasses}; attempts: ${t.attempts}.`, + `Outcomes: ${OUTCOMES.map(outcome => `${outcome}: ${t[outcome]}`).join('; ')}.`, + `Properly implemented*: ${t.properlyImplemented}/${t.selected} (${t.properlyImplementedPercent}%).`, '', + '*Only explicitly declared (reviewer-audited), non-flaky behavior cases with sealed evidence qualify in this selected local inventory. Unclassified checks and flaky passes never qualify. Reviewers must exclude import-only checks from behavior declarations; discovery does not detect their assertion quality. All selected cases remain in the denominator. This is not shipped qualification.', ''); + for (const entry of report.executions) { + rows.push(`## ${escape(entry.id)}`, '', `Source: ${entry.source.revision}; component: ${entry.component?.digest || 'not built'}; lane: ${escape(entry.lane)}; workflow: ${escape(entry.workflowRun)}/${entry.workflowAttempt}.`, '', + '| Case | Coverage | Qualified | Outcome | Flaky | Attempts | Reason |', '| --- | --- | --- | --- | --- | ---: | --- |'); + for (const item of entry.cases) rows.push(`| ${escape(item.id)} | ${item.coverage} | ${item.qualified} | ${item.outcome} | ${item.flaky} | ${item.attempts.length} | ${escape(item.reason)} |`); + rows.push(''); + } + return rows.join('\n'); +} +function assemble(bundle) { + const report = normalize(bundle); + save(path.join(bundle, 'report.json'), report, 'w'); + fs.writeFileSync(path.join(bundle, 'report.md'), render(report)); + save(path.join(bundle, 'checksums.json'), checksums(bundle, ['checksums.json']), 'w'); + return report; +} +function verify(bundle) { + checkDigests(bundle, read(path.join(bundle, 'checksums.json')), true, ['checksums.json']); + assert.equal(text(path.join(bundle, 'report.json')), json(normalize(bundle)), 'normalized JSON drift'); + assert.equal(text(path.join(bundle, 'report.md')), render(read(path.join(bundle, 'report.json'))), 'Markdown drift'); +} +function main(args) { + const [operation, location, ...rest] = args; assert(location, 'missing bundle/report path'); + const bundle = path.resolve(location); + if (operation === 'plan') { + const [executionId, profile, filter, metadataFile] = rest; + plan(bundle, executionId, profile, filter, metadataFile ? read(metadataFile) : {}); + } else if (operation === 'run') { if (run(bundle, rest[0]).outcome !== 'pass') process.exitCode = 1; } + else if (operation === 'assemble') assemble(bundle); + else if (operation === 'verify') verify(bundle); + else if (operation === 'render') process.stdout.write(render(read(bundle))); + else if (operation === 'select') { + const manifest = read(path.join(bundle, 'plan.json')); validatePlan(manifest); + assert(rest.every(value => manifest.executions.some(entry => entry.id === value))); + assert.equal(new Set(rest).size, rest.length); + save(path.join(bundle, 'selection.json'), rest, 'w'); + } else throw new Error('Usage: measured-report.cjs plan|run|select|assemble|verify|render ...'); +} +module.exports = { plan, run, assemble, verify, render }; +if (require.main === module) { try { main(process.argv.slice(2)); } catch (error) { console.error(error.message); process.exitCode = 1; } } diff --git a/tools/test_measured_report.cjs b/tools/test_measured_report.cjs new file mode 100644 index 000000000..0d0966b62 --- /dev/null +++ b/tools/test_measured_report.cjs @@ -0,0 +1,398 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const crypto = require('node:crypto'); +const { spawnSync } = require('node:child_process'); +const { assemble, verify, render } = require('./measured-report.cjs'); + +const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' + ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value; +const bytes = value => JSON.stringify(canonical(value), null, 2) + '\n'; +const digest = value => crypto.createHash('sha256').update(value).digest('hex'); +const put = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, bytes(value)); }; +const read = file => JSON.parse(fs.readFileSync(file, 'utf8')); +const startTime = '2026-11-27T00:00:00Z'; +const endTime = '2026-11-27T00:00:01Z'; +function root(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'measured-test-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + return dir; +} +function sums(dir) { + const result = {}; + function walk(current) { + for (const item of fs.readdirSync(current, { withFileTypes: true })) { + const file = path.join(current, item.name); + if (item.isDirectory()) walk(file); + else result[path.relative(dir, file)] = digest(fs.readFileSync(file)); + } + } + walk(dir); return result; +} +function entry(executionId, profile, names) { + return { id: executionId, profile, filter: 'selected', consumer: 'local-wasmtime', artifactRole: 'candidate', + lane: profile, workflowRun: 'fixture', workflowAttempt: 1, source: { revision: 'a'.repeat(40) }, + runner: { component: 'full-no-logging' }, inputs: {}, toolchain: { producerNode: 'fixture' }, + behaviorCases: names.filter(name => name !== 'import'), + cases: names.map(name => ({ id: name, runnerName: `runner::${name}`, fixture: 'offline/test.js', + classification: name === 'skip' ? 'known gap' : 'runnable', skipReason: name === 'skip' ? 'not implemented' : null, + coverage: name === 'import' ? 'import' : 'unclassified', timeoutSeconds: 10, maxAttempts: 2 })) }; +} +function setup(bundle, entries, selection = entries.map(item => item.id)) { + put(path.join(bundle, 'plan.json'), { schemaVersion: 1, executions: entries }); + put(path.join(bundle, 'selection.json'), selection); + for (const item of entries) { + const dir = path.join(bundle, 'executions', item.id); fs.mkdirSync(dir, { recursive: true }); + if (item.profile !== 'bundled') for (let i = 0; i < item.cases.length; i++) put(path.join(dir, 'inventory', `${i}.json`), item.cases[i]); + } +} +function capture(bundle, item, histories, componentBytes = item.id) { + const dir = path.join(bundle, 'executions', item.id); + const identity = digest(bytes(item)); + put(path.join(dir, 'run-start.json'), { identity, toolchain: item.toolchain, startedAt: startTime }); + fs.writeFileSync(path.join(dir, 'component.wasm'), componentBytes); + put(path.join(dir, 'component.json'), { identity, algorithm: 'sha256', digest: digest(componentBytes), features: item.runner.component }); + for (const [caseId, history] of Object.entries(histories)) for (let index = 0; index < history.length; index++) { + const outcome = history[index]; const binding = { identity, caseId, ordinal: index + 1 }; + const attempt = path.join(dir, 'attempts', caseId, String(index + 1)); + const phase = outcome === 'blocked' ? 'host-control' : 'guest'; + put(path.join(attempt, 'start.json'), { ...binding, startedAt: startTime }); + put(path.join(attempt, 'phase-0001-start.json'), { ...binding, phase, startedAt: startTime }); + if (outcome === 'not-run') continue; + const reason = outcome === 'pass' ? '' : `${outcome} fixture`; + put(path.join(attempt, 'phase-0001-finish.json'), { ...binding, phase, outcome: outcome === 'blocked' ? 'fail' : outcome, reason, finishedAt: endTime }); + fs.writeFileSync(path.join(attempt, 'phase-0001-stdout.txt'), `raw ${caseId} ${index + 1}`); + fs.writeFileSync(path.join(attempt, 'phase-0001-stderr.txt'), ''); + put(path.join(attempt, 'finish.json'), { ...binding, outcome, reason, failedPhase: outcome === 'pass' ? null : phase, finishedAt: endTime }); + } + if (item.profile !== 'bundled') put(path.join(dir, 'ctrf.json'), { results: { tests: item.cases.flatMap(current => { + const outcome = histories[current.id]?.at(-1); + if (!outcome || outcome === 'not-run') return current.classification === 'runnable' ? [] : [{ name: current.runnerName, status: 'skipped' }]; + return [{ name: current.runnerName, status: outcome === 'pass' ? 'passed' : 'failed' }]; + }) } }); + put(path.join(dir, 'run-finish.json'), { identity, outcome: 'fail', finishedAt: endTime }); + put(path.join(dir, 'evidence.json'), sums(dir)); +} + +test('six outcomes, flaky denominator, import limits and profile identities survive public assembly', t => { + const bundle = root(t); + const api = entry('api-run', 'api', ['same', 'flaky', 'failure', 'skip', 'timed', 'blocked', 'interrupted', 'import']); + const installed = entry('installed-run', 'installed', ['same']); + const missing = entry('missing-lane', 'bundled', ['same']); + setup(bundle, [api, installed, missing]); + capture(bundle, api, { same: ['pass'], flaky: ['fail', 'pass'], failure: ['fail'], timed: ['timeout'], + blocked: ['blocked'], interrupted: ['not-run'], import: ['pass'] }); + capture(bundle, installed, { same: ['pass'] }); + const report = assemble(bundle); verify(bundle); + assert.equal(report.complete, false); + assert.deepEqual(report.totals, { selected: 10, pass: 4, fail: 1, skip: 1, timeout: 1, blocked: 1, 'not-run': 2, + flakyPasses: 1, nonFlakyPasses: 3, properlyImplemented: 2, properlyImplementedPercent: 20, attempts: 9 }); + const flaky = report.executions.find(item => item.id === 'api-run').cases.find(item => item.id === 'flaky'); + assert.equal(flaky.outcome, 'pass'); assert.equal(flaky.flaky, true); assert.equal(flaky.qualified, false); + assert.deepEqual(flaky.attempts.map(item => item.outcome), ['fail', 'pass']); + assert.notDeepEqual(report.executions[0].cases.find(item => item.id === 'same').key, + report.executions[1].cases.find(item => item.id === 'same').key); + const markdown = render(JSON.parse(fs.readFileSync(path.join(bundle, 'report.json')))); + assert.match(markdown, /Properly implemented\*: 2\/10 \(20%\)/); + assert.match(markdown, /\| flaky \| behavior \| false \| pass \| true \| 2 \|/); + assert.equal(fs.readFileSync(path.join(bundle, 'report.md'), 'utf8'), markdown); + const first = fs.readFileSync(path.join(bundle, 'report.json')); + const manifest = read(path.join(bundle, 'plan.json')); + manifest.executions.reverse(); + put(path.join(bundle, 'plan.json'), manifest); + const evidence = path.join(bundle, 'executions/api-run/attempts'); + for (const name of fs.readdirSync(evidence).reverse()) { + fs.renameSync(path.join(evidence, name), path.join(evidence, `${name}.move`)); + fs.renameSync(path.join(evidence, `${name}.move`), path.join(evidence, name)); + } + assemble(bundle); + assert.deepEqual(fs.readFileSync(path.join(bundle, 'report.json')), first); + assert.equal(fs.readFileSync(path.join(bundle, 'report.md'), 'utf8'), markdown); +}); + +test('selected lanes reject overlapping case keys without collapsing distinct profiles or artifacts', t => { + for (const variant of ['overlap', 'flaky-overlap', 'disjoint', 'profile', 'component']) { + const bundle = root(t); + const left = entry('left', 'bundled', ['shared', 'left-only']); + const right = entry('right', variant === 'profile' ? 'installed' : 'bundled', + variant === 'disjoint' ? ['right-only'] : ['shared']); + right.lane = 'another-lane'; + setup(bundle, [left, right]); + capture(bundle, left, { shared: ['pass'], 'left-only': ['pass'] }, 'same component'); + capture(bundle, right, { [right.cases[0].id]: variant === 'flaky-overlap' ? ['fail', 'pass'] : ['pass'] }, + variant === 'component' ? 'different component' : 'same component'); + if (variant.endsWith('overlap')) { + assert.throws(() => assemble(bundle), /overlapping selected case key/); + put(path.join(bundle, 'report.json'), {}); + fs.writeFileSync(path.join(bundle, 'report.md'), ''); + put(path.join(bundle, 'checksums.json'), sums(bundle)); + assert.throws(() => verify(bundle), /overlapping selected case key/); + put(path.join(bundle, 'selection.json'), ['right']); + const selected = assemble(bundle); verify(bundle); + assert.equal(selected.totals.selected, 1); + assert.equal(selected.totals.properlyImplemented, variant === 'flaky-overlap' ? 0 : 1); + assert.equal(selected.executions.length, 2, 'unselected evidence stays retained'); + } else { + const report = assemble(bundle); verify(bundle); + assert.equal(report.totals.selected, 3); + assert.equal(report.totals.properlyImplemented, 3); + assert.equal(report.complete, true); + } + } +}); + +test('unbuilt artifacts retain separate incomplete inventories without duplicating the same planned artifact', t => { + for (const variant of ['role', 'source', 'features', 'same']) { + const bundle = root(t); + const left = entry('left', 'installed', ['shared', 'left-only']); + const right = entry('right', 'installed', ['shared']); right.lane = 'another-lane'; + if (variant === 'role') right.artifactRole = 'baseline'; + if (variant === 'source') right.source.revision = 'b'.repeat(40); + if (variant === 'features') right.runner.component = 'full-no-logging-golem-typescript'; + setup(bundle, [left, right]); + if (variant === 'same') { + assert.throws(() => assemble(bundle), /overlapping selected case key/); + } else { + const report = assemble(bundle); verify(bundle); + assert.equal(report.complete, false); + assert.equal(report.totals.selected, 3); + assert.equal(report.totals['not-run'], 3); + assert.equal(report.totals.attempts, 0); + assert.equal(report.totals.properlyImplemented, 0); + assert.notDeepEqual(report.executions[0].cases.find(item => item.id === 'shared').key, + report.executions[1].cases.find(item => item.id === 'shared').key); + } + } +}); + +test('a selected missing workflow rerun never borrows earlier green cases', t => { + const bundle = root(t); + const old = entry('old', 'bundled', ['same']); const latest = entry('latest', 'bundled', ['same']); + latest.workflowAttempt = 2; + setup(bundle, [old, latest], ['latest']); capture(bundle, old, { same: ['pass'] }); + const report = assemble(bundle); verify(bundle); + assert.equal(report.executions.find(item => item.id === 'old').totals.pass, 1); + assert.equal(report.totals.pass, 0); assert.equal(report.totals['not-run'], 1); + assert.equal(report.totals.selected, 1); assert.equal(report.complete, false); + + const interrupted = root(t); const retry = entry('retry', 'bundled', ['same']); + setup(interrupted, [retry]); capture(interrupted, retry, { same: ['not-run', 'pass'] }); + const recovered = assemble(interrupted); verify(interrupted); + assert.equal(recovered.totals.flakyPasses, 1); assert.equal(recovered.totals.properlyImplemented, 0); + assert.equal(recovered.complete, false, 'a missing earlier completion remains incomplete'); +}); + +test('a failed shared preparation is blocked even after compilation; interruption stays not-run', t => { + const bundle = root(t); const item = entry('compile-failure', 'api', ['same']); setup(bundle, [item]); + const dir = path.join(bundle, 'executions', item.id); const identity = digest(bytes(item)); + put(path.join(dir, 'run-start.json'), { identity, toolchain: item.toolchain, startedAt: startTime }); + put(path.join(dir, 'component.json'), { identity, algorithm: 'sha256', digest: digest(item.id), features: item.runner.component }); + const phase = 'component-prepare'; + put(path.join(dir, 'prerequisites/prepare/start.json'), { identity, phase, startedAt: startTime }); + put(path.join(dir, 'prerequisites/prepare/finish.json'), { identity, phase, outcome: 'fail', reason: 'engine creation failed', finishedAt: endTime }); + put(path.join(dir, 'run-finish.json'), { identity, outcome: 'fail', exitCode: 101, finishedAt: endTime }); + fs.writeFileSync(path.join(dir, 'harness-stderr.txt'), 'Failed to compile node-compat-runner'); + put(path.join(dir, 'evidence.json'), sums(dir)); + const report = assemble(bundle); verify(bundle); + assert.equal(report.totals.blocked, 1); assert.equal(report.totals.fail, 0); + assert.equal(report.totals.pass, 0); assert.equal(report.totals.attempts, 0); + fs.rmSync(path.join(dir, 'evidence.json')); + fs.rmSync(path.join(dir, 'prerequisites/prepare/finish.json')); + const interrupted = assemble(bundle); + assert.equal(interrupted.totals['not-run'], 1); assert.equal(interrupted.totals.blocked, 0); + assert.equal(interrupted.complete, false); +}); + +test('only explicitly declared behavior assertions qualify, and declarations reject unknown/import-only cases', t => { + const bundle = root(t); const item = entry('surface', 'bundled', ['surface', 'assertions']); + item.behaviorCases = ['assertions']; + setup(bundle, [item]); capture(bundle, item, { surface: ['pass'], assertions: ['pass'] }); + const report = assemble(bundle); verify(bundle); + assert.equal(report.totals.pass, 2); assert.equal(report.totals.properlyImplemented, 1); + assert.equal(report.totals.properlyImplementedPercent, 50); + assert.equal(report.executions[0].cases.find(item => item.id === 'surface').qualified, false); + item.behaviorCases = ['unknown']; put(path.join(bundle, 'plan.json'), { schemaVersion: 1, executions: [item] }); + assert.throws(() => assemble(bundle), /behavior declaration/); + item.cases[1].coverage = 'import'; item.behaviorCases = ['assertions']; + put(path.join(bundle, 'plan.json'), { schemaVersion: 1, executions: [item] }); + assert.throws(() => assemble(bundle), /behavior declaration/); +}); + +test('corruption, duplicate attempts, contradictions and identity mixing are rejected', async t => { + const base = root(t); const item = entry('run', 'bundled', ['same']); + setup(base, [item]); capture(base, item, { same: ['pass'] }); assemble(base); verify(base); + for (const [name, change] of [ + ['checksum', dir => fs.appendFileSync(path.join(dir, 'attempts/same/1/phase-0001-stdout.txt'), 'corrupt')], + ['duplicate', dir => fs.cpSync(path.join(dir, 'attempts/same/1'), path.join(dir, 'attempts/same/copy'), { recursive: true })], + ['contradiction', dir => { const file = path.join(dir, 'attempts/same/1/phase-0001-finish.json'); put(file, { ...read(file), outcome: 'fail' }); }], + ['mixing', dir => { const file = path.join(dir, 'component.json'); put(file, { ...read(file), identity: 'different' }); }], + ['unknown', dir => { const file = path.join(dir, 'attempts/same/1/start.json'); put(file, { ...read(file), caseId: 'unknown' }); }], + ['missing-log', dir => fs.rmSync(path.join(dir, 'attempts/same/1/phase-0001-stdout.txt'))], + ['ctrf-conflict', dir => put(path.join(dir, 'ctrf.json'), { results: { tests: [{ name: 'runner::same', status: 'failed' }] } })], + ['ctrf-malformed', dir => fs.writeFileSync(path.join(dir, 'ctrf.json'), '{')], + ['toolchain-drift', dir => { const file = path.join(dir, 'run-start.json'); put(file, { ...read(file), toolchain: { producerNode: 'other' } }); }], + ['component-bytes', dir => fs.writeFileSync(path.join(dir, 'component.wasm'), 'wrong component')], + ]) await t.test(name, child => { + const copy = root(child); fs.cpSync(base, copy, { recursive: true }); + const dir = path.join(copy, 'executions/run'); + if (name !== 'checksum') fs.rmSync(path.join(dir, 'evidence.json')); + change(dir); + assert.throws(() => assemble(copy)); + assert.throws(() => verify(copy)); + }); +}); + +// Exercise the public producer in a disposable checkout. External build/runtime commands +// are controlled, but plan/run, manifests, publication, drift checks and rendering are real. +function producer(t, api = false) { + const dir = root(t); + const trackedFiles = []; + const write = (file, value) => { + const destination = path.join(dir, file); fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.writeFileSync(destination, value); + trackedFiles.push(file); + }; + for (const file of ['Cargo.toml', 'Cargo.lock', 'tools/dev-test.sh', 'tests/common/measured.rs', + 'tests/common/mod.rs', 'tests/node_compat.rs', 'tests/runtime/node_modules_apps.rs', + 'crates/wasm-rquickjs/skeleton/Cargo.toml_', 'crates/wasm-rquickjs/skeleton/Cargo.lock', + 'tests/node_modules_apps/config.jsonc', 'tests/node_modules_apps/apps/demo/test.js', + 'tests/node_modules_apps/apps/demo/results.md', + 'tests/libraries/ajv/test-01-basic.js', 'tests/libraries/ajv/package.json']) write(file, 'fixture'); + write('tools/measured-report.cjs', fs.readFileSync(path.join(__dirname, 'measured-report.cjs'))); + if (api) for (const [file, value] of Object.entries({ 'suite/NODE_VERSION': '26.13.1', + 'suite/parallel/test.js': 'assertions', 'suite/common/helper.mjs': 'original helper', + 'suite/trace_events/extra.js': 'additional setup input', + 'config.jsonc': '{}', 'vendor.sh': 'fixture' })) write(`tests/node_compat/${file}`, value); + const stub = `#!${process.execPath} +const fs = require('node:fs'), path = require('node:path'), assert = require('node:assert/strict'); +const args = process.argv.slice(2), command = path.basename(process.argv[1]); +const root = ${JSON.stringify(dir)}; +if (args.includes('--version')) { console.log(command + (process.env.STUB_VERSION || '-1')); process.exit(0); } +if (command === 'git') { + if (args[0] === 'rev-parse') console.log('a'.repeat(40)); + else if (args[0] === 'ls-files') { + const prefix = args.at(-1); + process.stdout.write(${JSON.stringify(trackedFiles)}.filter(file => file.startsWith(prefix)).join('\\0')); + } +} else if (command === 'bash' && args.includes('--list')) { + const filter = process.env.WASM_RQUICKJS_MEASURE_FILTER, api = args.includes('node_compat'); + const name = (api ? 'node_compat::gen_node_compat_tests::' : 'runtime::node_modules_apps::gen_node_modules_app_tests::') + filter; + const inventory = path.join(process.env.WASM_RQUICKJS_MEASURE_DIR,'inventory'); fs.mkdirSync(inventory,{recursive:true}); + if (api) fs.writeFileSync(path.join(process.env.WASM_RQUICKJS_MEASURE_DIR,'input-roots.json'), + JSON.stringify(['tests/node_compat/suite/common','tests/node_compat/suite/trace_events'])); + fs.writeFileSync(path.join(inventory,'case.json'),JSON.stringify({id:filter,runnerName:name, + fixture:api?'parallel/test.js':'demo/test.js',classification:'runnable',skipReason:null, + coverage:'unclassified',maxAttempts:1,timeoutSeconds:10})); + console.log(name); if (filter === 'unmeasured') console.log('node_compat::static_test'); +} else if (command === 'wasm-rquickjs') { + const output = args[args.indexOf('--output')+1]; fs.mkdirSync(output,{recursive:true}); + fs.writeFileSync(path.join(output,'Cargo.toml'),'[package]\\nname = "lib-ajv"\\n[lib]\\n'); +} else if (command === 'cargo' && args.includes('--target')) { + const manifest = fs.readFileSync('Cargo.toml','utf8'); + const name = manifest.match(/\\[lib\\]\\n(?:name = "([^"]+)"\\n)?/)[1] || 'lib_ajv'; + const output = path.join(root,'target/wasm32-wasip2/debug'); fs.mkdirSync(output,{recursive:true}); + if (!process.env.STUB_MISSING_OUTPUT) fs.writeFileSync(path.join(output,name+'.wasm'),'component:'+name); + if (process.env.STUB_FAIL_BUILD) process.exit(17); +} else if (command === 'wasmtime') { + // A subsequent fixture replaces the old shared-world output before invocation. + fs.writeFileSync(path.join(root,'target/wasm32-wasip2/debug/lib_ajv.wasm'),'another fixture'); + const component = args.at(-1); + assert(!component.includes('/target/'), 'must execute retained component'); + assert(fs.readFileSync(component,'utf8').startsWith('component:measured_'), 'must publish execution-specific output'); + console.log(JSON.stringify('PASS: isolated component')); +} +`; + for (const command of ['git', 'bash', 'cargo', 'rustc', 'node', 'npm', 'wasmtime']) { + write(`bin/${command}`, stub); fs.chmodSync(path.join(dir, 'bin', command), 0o755); + } + write('target/debug/wasm-rquickjs', stub); fs.chmodSync(path.join(dir, 'target/debug/wasm-rquickjs'), 0o755); + const call = (args, env = {}) => spawnSync(process.execPath, [path.join(dir, 'tools/measured-report.cjs'), ...args], + { cwd: dir, encoding: 'utf8', env: { ...process.env, PATH: path.join(dir, 'bin'), ...env } }); + return { dir, write, call, bundle: path.join(dir, 'bundle') }; +} + +test('public plan/run isolates bundled outputs, survives old locks, and does not require the API suite', t => { + const p = producer(t); + fs.mkdirSync(path.join(p.dir, 'tmp/measured-bundled-build.lock'), { recursive: true }); + for (const id of ['first', 'second']) { + assert.equal(p.call(['plan', p.bundle, id, 'bundled', 'ajv/test-01-basic.js']).status, 0); + // API-suite changes cannot invalidate an unrelated package plan. + p.write('tests/node_compat/suite/NODE_VERSION', id); + const result = p.call(['run', p.bundle, id]); assert.equal(result.status, 0, result.stderr); + } + const first = fs.readFileSync(path.join(p.bundle, 'executions/first/component.wasm')); + const second = fs.readFileSync(path.join(p.bundle, 'executions/second/component.wasm')); + assert.notDeepEqual(first, second); + assert.equal(p.call(['assemble', p.bundle]).status, 0); + assert.equal(p.call(['verify', p.bundle]).status, 0); + const report = read(path.join(p.bundle, 'report.json')); + assert.equal(report.executions.length, 2); assert(report.executions.every(item => item.cases[0].outcome === 'pass')); + assert.equal(report.totals.properlyImplemented, 0, 'undeclared passes never qualify'); + assert.match(fs.readFileSync(path.join(p.bundle, 'report.md'), 'utf8'), /unclassified \| false \| pass/); + assert.equal(p.call(['plan', p.bundle, 'failed', 'bundled', 'ajv/test-01-basic.js']).status, 0); + assert.equal(p.call(['run', p.bundle, 'failed'], { STUB_FAIL_BUILD: '1' }).status, 1); + assert(!fs.existsSync(path.join(p.bundle, 'executions/failed/component.wasm')), 'failed builds must not publish'); + const finish = read(path.join(p.bundle, 'executions/failed/attempts/bundled/0001/finish.json')); + assert.equal(finish.outcome, 'blocked'); assert.equal(finish.failedPhase, 'component-build'); + const failedBuild = read(path.join(p.bundle, 'executions/failed/attempts/bundled/0001/phase-0006-finish.json')); + assert.equal(failedBuild.exitCode, 17); assert.equal(failedBuild.publicationError, null); + + assert.equal(p.call(['plan', p.bundle, 'missing-output', 'bundled', 'ajv/test-01-basic.js']).status, 0); + assert.equal(p.call(['run', p.bundle, 'missing-output'], { STUB_MISSING_OUTPUT: '1' }).status, 1); + const publication = read(path.join(p.bundle, 'executions/missing-output/attempts/bundled/0001/phase-0006-finish.json')); + assert.equal(publication.exitCode, 0, 'publication errors must preserve the actual successful build exit'); + assert.equal(publication.error, null); assert.match(publication.publicationError, /ENOENT/); + assert.equal(p.call(['select', p.bundle, 'missing-output']).status, 0); + assert.equal(p.call(['assemble', p.bundle]).status, 0); + assert.equal(p.call(['verify', p.bundle]).status, 0); + const missing = read(path.join(p.bundle, 'report.json')); + assert.equal(missing.totals.blocked, 1); assert.equal(missing.totals.pass, 0); + assert.match(missing.executions.find(item => item.id === 'missing-output').cases[0].reason, /ENOENT/); +}); + +test('installed public plan/run refuses copied inputs absent from its retained inventory', t => { + const p = producer(t); + assert.equal(p.call(['plan', p.bundle, 'clean', 'installed', 'case']).status, 0); + assert.equal(fs.readFileSync(path.join(p.bundle, 'executions/clean/inputs/tests/node_modules_apps/apps/demo/results.md'), 'utf8'), 'fixture'); + assert.equal(p.call(['run', p.bundle, 'clean']).status, 0, 'tracked fixture still runs'); + assert.equal(p.call(['plan', p.bundle, 'before-extra', 'installed', 'case']).status, 0); + p.write('tests/node_modules_apps/apps/demo/helpers/extra.js', 'exports.answer = 1;'); + const plan = p.call(['plan', p.bundle, 'extra-at-plan', 'installed', 'case']); + assert.equal(plan.status, 1); assert.match(plan.stderr, /uncaptured installed fixture input/); + p.write('tests/node_modules_apps/apps/demo/helpers/extra.js', 'exports.answer = 999;'); + const run = p.call(['run', p.bundle, 'before-extra']); + assert.equal(run.status, 1); assert.match(run.stderr, /uncaptured installed fixture input/); + assert(!fs.existsSync(path.join(p.bundle, 'executions/before-extra/run-start.json'))); + assert(!read(path.join(p.bundle, 'plan.json')).executions.some(item => item.id === 'extra-at-plan')); +}); + +test('public plan/run requires only profile tools and rejects drift or unmeasured selection before invocation', t => { + const p = producer(t, true); + assert.equal(p.call(['plan', p.bundle, 'drift', 'api', 'case']).status, 0); + const drift = p.call(['run', p.bundle, 'drift'], { STUB_VERSION: '-changed' }); + assert.equal(drift.status, 1); assert.match(drift.stderr, /toolchain changed/); + assert(!fs.existsSync(path.join(p.bundle, 'executions/drift/run-start.json'))); + assert.equal(p.call(['plan', p.bundle, 'input', 'api', 'case']).status, 0); + p.write('tests/node_compat/suite/common/helper.mjs', 'changed helper'); + const changed = p.call(['run', p.bundle, 'input']); + assert.equal(changed.status, 1); assert.match(changed.stderr, /fixture input changed/); + assert(!fs.existsSync(path.join(p.bundle, 'executions/input/run-start.json'))); + assert.equal(p.call(['plan', p.bundle, 'new-root', 'api', 'case']).status, 0); + p.write('tests/node_compat/suite/trace_events/extra.js', 'changed additional setup input'); + const extra = p.call(['run', p.bundle, 'new-root']); + assert.equal(extra.status, 1); assert.match(extra.stderr, /fixture input changed/); + assert(!fs.existsSync(path.join(p.bundle, 'executions/new-root/run-start.json'))); + assert.equal(p.call(['plan', p.bundle, 'bad', 'api', 'unmeasured']).status, 1); + assert.equal(p.call(['plan', p.bundle, 'tag', 'api', ':tag:shard0']).status, 1); + fs.rmSync(path.join(p.dir, 'bin/npm')); fs.rmSync(path.join(p.dir, 'bin/wasmtime')); + assert.equal(p.call(['plan', p.bundle, 'minimal', 'api', 'case']).status, 0, 'API needs neither npm nor CLI Wasmtime'); + fs.rmSync(path.join(p.dir, 'tests/node_compat/suite'), { recursive: true }); + // Restore npm only: installed execution needs neither vendored API files nor the Wasmtime CLI. + fs.copyFileSync(path.join(p.dir, 'bin/node'), path.join(p.dir, 'bin/npm')); + fs.chmodSync(path.join(p.dir, 'bin/npm'), 0o755); + assert.equal(p.call(['plan', p.bundle, 'installed', 'installed', 'case']).status, 0); + const installed = p.call(['run', p.bundle, 'installed']); assert.equal(installed.status, 0, installed.stderr); +});