From b2c02ac7dd574d639dc444ee4b6d19e855e9a760 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:14:17 +0900 Subject: [PATCH 1/5] perf(native): share large comb kernels and bound compilation memory Large derived-edge process entries copied the complete combinational SIR before compilation. Retain deferred recipes, compile the large comb kernel once, and expand, compile and release one wrapper per bounded worker. Existing comb execution units compile separately with preserved cross-unit state and a thin ordered dispatcher. Other backends and tiered startup retain their existing eager path. Worker selection accounts for host, cgroup and address-space limits with bounded concurrency and deterministic result/error order. Reserve callee scratch before wrapper arenas and retain kernel offsets in native images; the container version advances to 48, so older images must be rebuilt. Validation: native library and image, completion, partition, tiered and scheduled-startup APIs; eager/deferred equivalence and merged/chunked image roundtrips with handwritten expected values. Owning-crate clippy, no-host configurations and formatting pass. Full-stack unchanged Taxi board benchmarks and common regressions are recorded in the top member. Generated callers use X86BackendOptions::with_native_callees with the emitted full child extents. This shares the ABI primitive's arena reservation contract and preserves explicitly higher arena placements. Revalidated independently after the arena review fix: 239 native library tests, 41 image/completion/partition/tiered/startup API tests and owning-crate clippy pass. Change-Id: I4dad9216b84cffc3c1a2b503adad4be8f83a366c --- crates/celox/src/backend/native/backend.rs | 391 ++++++++++++++++-- .../src/backend/native/compile_resources.rs | 194 ++++++++- crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/derived_edge.rs | 123 +++++- crates/celox/src/dpi.rs | 7 + crates/celox/src/ir.rs | 6 + crates/celox/src/settle.rs | 12 + crates/celox/src/simulator/builder.rs | 270 +++++++++++- crates/celox/src/simulator/error.rs | 4 +- 9 files changed, 937 insertions(+), 74 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index af33388459f..51e4d6b5eb8 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -232,7 +232,7 @@ impl SharedNativeCode { } // Loading DPI-C libraries runs their initializers and keeps them // loaded, so it waits until the image is known to be usable. - let extern_functions = dpi.resolve(&program_image.runtime_schema.extern_functions)?; + let mut extern_functions = dpi.resolve(&program_image.runtime_schema.extern_functions)?; let symbols = program_image .symbols .iter() @@ -249,6 +249,13 @@ impl SharedNativeCode { program_image.options.perf_map, ) .map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?; + let kernel_addresses = program_image + .runtime_schema + .native_kernel_offsets + .iter() + .map(|&offset| native_function_at(&jit_image, offset).map(|func| func as usize)) + .collect::, _>>()?; + extern_functions.append_native_kernels(kernel_addresses); let materialize = |event: NativeEventImageRef| -> Result { Ok(NativeEventRef { func: native_function_at(&jit_image, event.func_offset)?, @@ -399,6 +406,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) runtime_event_sites: Vec, /// Extern functions the code calls, resolved when the image is attached. pub(crate) extern_functions: Vec, + /// Image-local compiled callees appended to the DPI address table. + pub(crate) native_kernel_offsets: Vec, pub(crate) comb_observers: Vec>, pub(crate) testbench_read_roots: HashSet, pub(crate) rtl_writes: HashSet>, @@ -673,6 +682,11 @@ impl NativeProgramImage { if !entry_offsets.contains(&self.comb_offset) { return Err("eval_comb offset does not name an image entry".into()); } + for &offset in &self.runtime_schema.native_kernel_offsets { + if !entry_offsets.contains(&offset) { + return Err("native kernel offset does not name an image entry".into()); + } + } if self .comb_unit_offsets .iter() @@ -2163,6 +2177,16 @@ fn compile_program( options: &SimulatorOptions, capture_trace: bool, cancel: Option<&CompileCancel>, +) -> Result<(NativeProgramImage, Option), SimulatorError> { + compile_program_with_outlining_threshold(laid_out, options, capture_trace, cancel, 32_768) +} + +fn compile_program_with_outlining_threshold( + laid_out: &LaidOutProgram, + options: &SimulatorOptions, + capture_trace: bool, + cancel: Option<&CompileCancel>, + outline_threshold: usize, ) -> Result<(NativeProgramImage, Option), SimulatorError> { let sir = laid_out; let layout = laid_out.layout(); @@ -2175,42 +2199,40 @@ fn compile_program( .iter() .map(|unit| unit.blocks.len()) .sum::(); - let max_task_blocks = compile_tasks - .iter() - .map(|task| { - task.units - .iter() - .map(|unit| unit.blocks.len()) - .sum::() - }) - .max() - .unwrap_or(0); - let max_instructions = std::iter::once(sir.sir.eval_comb.iter().collect::>()) - .chain(compile_tasks.iter().map(|task| task.units.clone())) - .map(|units| { + let size = |units: &[&ExecutionUnit]| { + ( + units.iter().map(|unit| unit.blocks.len()).sum::(), units .iter() .flat_map(|unit| unit.blocks.values()) .map(|block| block.instructions.len()) - .sum::() - }) - .max() - .unwrap_or(0); + .sum::(), + ) + }; + let comb_size = size(&sir.sir.eval_comb.iter().collect::>()); + let task_sizes = compile_tasks + .iter() + .map(|task| size(&task.units)) + .collect::>(); + let max_task_blocks = task_sizes.iter().map(|size| size.0).max().unwrap_or(0); + let max_task_instructions = task_sizes.iter().map(|size| size.1).max().unwrap_or(0); + let max_instructions = comb_size.1.max(max_task_instructions); + let large = |size: (usize, usize)| size.0 >= 65_536 || size.1 >= 131_072; let release_pages = || { // Measure usable capacity after returning unused large-compiler pages. // Small single-worker builds must not trim unrelated process heaps. #[cfg(all(target_os = "linux", target_env = "gnu"))] - if comb_blocks.max(max_task_blocks) >= 65_536 { + if large(comb_size) || large((max_task_blocks, max_task_instructions)) { unsafe { libc::malloc_trim(0); } } }; release_pages(); - let workers = super::compile_resources::workers( - comb_blocks.max(max_task_blocks), - max_instructions, - compile_tasks.len() + 1, + let workers = super::compile_resources::workers_with_primary( + comb_size, + (max_task_blocks, max_task_instructions), + compile_tasks.len(), ); let serial = workers == 1; // Start expensive functions early so the final fused function does not @@ -2227,12 +2249,128 @@ fn compile_program( }); if options.x86_options.diagnostics.phase_timing { tracing::debug!( - "[native-timing] compile_program serial={serial} workers={workers} comb_blocks={comb_blocks} max_task_blocks={max_task_blocks} max_instructions={max_instructions} ff_tasks={}", - compile_tasks.len() + "[native-timing] compile_program serial={serial} workers={workers} comb_blocks={comb_blocks} max_task_blocks={max_task_blocks} max_instructions={max_instructions} ff_tasks={} settle_partitions={} settle_check={}", + compile_tasks.len(), + sir.runtime() + .runtime_schema + .settle_partitions + .as_ref() + .map_or(0, |s| s.partitions), + layout.settle_check(), ); } + // Execution units already communicate through state. Keep large units + // separate instead of rebuilding a single allocator problem, and dispatch + // them through the same bounded pool as the FF functions. + let split_comb = cfg!(any( + feature = "x86_64-codegen", + all(target_arch = "x86_64", not(feature = "arm64-codegen")) + )) && !capture_trace + && sir.sir.eval_comb.len() > 1 + && comb_size.1 >= outline_threshold; + let mut comb_chunk_jits = Vec::new(); let next_task = AtomicUsize::new(0); - let (comb_jit, compiled_ff_codes) = if serial { + let (comb_jit, compiled_ff_codes) = if split_comb { + let ff_count = compile_tasks.len(); + let sizes = task_sizes + .iter() + .copied() + .chain(sir.sir.eval_comb.iter().map(|unit| size(&[unit]))) + .collect::>(); + let mut order = (0..sizes.len()).collect::>(); + order.sort_by_key(|&index| std::cmp::Reverse(sizes[index])); + let workers = super::compile_resources::workers( + sizes.iter().map(|s| s.0).max().unwrap_or(0), + sizes.iter().map(|s| s.1).max().unwrap_or(0), + sizes.len(), + ); + if options.x86_options.diagnostics.phase_timing { + tracing::debug!( + "[native-timing] comb_chunks={} workers={workers}", + sir.sir.eval_comb.len() + ); + } + let codes = super::compile_resources::compile_tasks(&order, workers, |index| { + if cancelled(cancel) { + return Err(cancelled_error()); + } + if index < ff_count { + let task = &compile_tasks[index]; + compile_unit_refs( + &task.units, + layout, + options.four_state, + task.label, + task.merge_kind, + task.first_ff_unit, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + } else { + compile_unit_refs( + &[&sir.sir.eval_comb[index - ff_count]], + layout, + options.four_state, + "eval_comb_chunk", + NativeMergeKind::Partial, + None, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + } + }) + .map_err(|_| codegen_message("native compile worker panicked"))?; + let mut compiled = HashMap::default(); + for (index, code) in codes.into_iter().enumerate() { + let code = code?; + if index < ff_count { + compiled.insert(index, code); + } else { + comb_chunk_jits.push(code); + } + } + let first_slot = sir.runtime().runtime_schema.extern_functions.len() + 1; + let mut builder = celox_sir::SIRBuilder::new(); + for index in 0..comb_chunk_jits.len() { + let slot = u32::try_from(first_slot + index) + .ok() + .filter(|&slot| slot < 0x1000_0000) + .ok_or_else(|| codegen_message("too many native extern functions"))?; + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | slot, + args: Vec::new(), + }); + } + builder.seal_block(SIRTerminator::Return); + let caller_options = options + .x86_options + .clone() + .with_native_callees(comb_chunk_jits.iter().map(|code| code.required_state_size)); + let (blocks, register_map, _) = builder.drain(); + let comb = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + let root = compile_unit_refs( + &[&comb], + layout, + options.four_state, + "eval_comb", + NativeMergeKind::Complete, + None, + &caller_options, + false, + &options.optimize_options.diagnostics, + cancel, + )?; + (root, compiled) + } else if serial { let comb_jit = compile_units( &sir.sir.eval_comb, layout, @@ -2244,8 +2382,12 @@ fn compile_program( cancel, )?; let mut compiled = HashMap::default(); + let mut previous_large = large(comb_size); for (task_id, task) in compile_tasks.iter().enumerate() { - release_pages(); + if previous_large { + release_pages(); + } + previous_large = large(task_sizes[task_id]); let code = compile_unit_refs( &task.units, layout, @@ -2371,29 +2513,142 @@ fn compile_program( ) }) .collect::, _>>()?; - let process_jits = sir + // Return completed codegen's allocator pages before budgeting the process + // workers. Small designs leave unrelated process heaps alone. + release_pages(); + // Outlining amortizes the dominant circuit across all derived edges. + // Keep small circuits inline, where cross-boundary optimization is cheap. + let comb_instructions = sir + .sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .map(|block| block.instructions.len()) + .sum::(); + let outline_comb = cfg!(any( + feature = "x86_64-codegen", + all(target_arch = "x86_64", not(feature = "arm64-codegen")) + )) && !sir.deferred_derived_edges.is_empty() + && comb_instructions >= outline_threshold; + let outlined_comb = if outline_comb { + let slot = u32::try_from(sir.runtime().runtime_schema.extern_functions.len()) + .ok() + .filter(|&slot| slot < 0x1000_0000) + .ok_or_else(|| codegen_message("too many native extern functions"))?; + let mut builder = celox_sir::SIRBuilder::new(); + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | slot, + args: Vec::new(), + }); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + Some([ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }]) + } else { + None + }; + let mut process_options = options.x86_options.clone(); + if outline_comb { + // Nested functions must not overwrite the caller's spills, saved + // registers, scratch values, or extern call area. + process_options = process_options.with_native_callees([comb_jit.required_state_size]); + } + let derived_model = (!sir.deferred_derived_edges.is_empty()).then(|| { + celox_design::schedule::ScheduleModel::derive(&sir.design, &sir.runtime().runtime_schema) + }); + let process_sizes = sir .sir .processes .iter() .enumerate() .map(|(index, unit)| { - if cancelled(cancel) { - return Err(cancelled_error()); - } - compile_unit_refs( - &[unit], - layout, - options.four_state, - &format!("process[{index}]"), - NativeMergeKind::Complete, - None, - &options.x86_options, - false, - &options.optimize_options.diagnostics, - cancel, + sir.deferred_derived_edges.get(&index).map_or_else( + || { + ( + unit.blocks.len(), + unit.blocks + .values() + .map(|block| block.instructions.len()) + .sum(), + ) + }, + |edge| { + if outline_comb { + // The recipe estimate includes two complete comb + // copies. Both now use a single call; its fixed CFG + // allowance already covers those call instructions. + ( + edge.blocks.saturating_sub(comb_blocks.saturating_mul(2)), + edge.instructions + .saturating_sub(comb_instructions.saturating_mul(2)), + ) + } else { + (edge.blocks, edge.instructions) + } + }, ) }) - .collect::, _>>()?; + .collect::>(); + let max_process_blocks = process_sizes.iter().map(|size| size.0).max().unwrap_or(0); + let max_process_instructions = process_sizes.iter().map(|size| size.1).max().unwrap_or(0); + // The resource budget already includes overlapping SIR/MIR copies. + // Use the expanded size, rather than the tiny reserved process entry. + let process_workers = super::compile_resources::workers( + max_process_blocks, + max_process_instructions, + process_sizes.len(), + ); + let mut process_order = (0..process_sizes.len()).collect::>(); + process_order.sort_by_key(|&index| std::cmp::Reverse(process_sizes[index])); + if options.x86_options.diagnostics.phase_timing { + tracing::debug!( + "[native-timing] process_compile workers={process_workers} units={} max_blocks={max_process_blocks} max_instructions={max_process_instructions}", + process_sizes.len() + ); + } + let compile_process = |index| { + let unit = &sir.sir.processes[index]; + if cancelled(cancel) { + return Err(cancelled_error()); + } + // Expand, compile, then drop just this edge's SIR. Retaining every + // expansion makes memory scale with circuit size times edge count. + let generated = sir + .deferred_derived_edges + .get(&index) + .map(|edge| { + let model = derived_model.as_ref().expect("deferred edge model"); + if let Some(comb) = &outlined_comb { + edge.generate_with_comb(sir, model, comb) + } else { + edge.generate(sir, model) + } + .map_err(codegen_message) + }) + .transpose()?; + let unit = generated.as_ref().unwrap_or(unit); + compile_unit_refs( + &[unit], + layout, + options.four_state, + &format!("process[{index}]"), + NativeMergeKind::Complete, + None, + &process_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + }; + let process_jits = + super::compile_resources::compile_tasks(&process_order, process_workers, compile_process) + .map_err(|_| codegen_message("native process compile thread panicked"))? + .into_iter() + .collect::, _>>()?; let lane_kernels = super::lanes::compile_lane_kernels(sir, options, cancel)?; let codegen_trace = capture_trace .then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks)); @@ -2402,6 +2657,7 @@ fn compile_program( .checked_add(layout.triggered_bits_total_size) .expect("native semantic-memory size overflow"); let native_memory_size = std::iter::once(comb_jit.required_state_size) + .chain(comb_chunk_jits.iter().map(|code| code.required_state_size)) .chain( compiled_ff_codes .values() @@ -2421,6 +2677,11 @@ fn compile_program( ) .fold(semantic_memory_size, usize::max); let required_native_features = std::iter::once(comb_jit.required_native_features) + .chain( + comb_chunk_jits + .iter() + .map(|code| code.required_native_features), + ) .chain( compiled_ff_codes .values() @@ -2449,6 +2710,20 @@ fn compile_program( "eval_comb".into(), &comb_jit, )?; + let mut native_kernel_offsets = if outline_comb || split_comb { + vec![comb_offset] + } else { + Vec::new() + }; + for (index, code) in comb_chunk_jits.iter().enumerate() { + native_kernel_offsets.push(append_native_code( + &mut packed_image, + &mut code_entries, + &mut image_symbols, + format!("eval_comb_chunk[{index}]"), + code, + )?); + } let mut comb_unit_offsets = Vec::with_capacity(comb_unit_jits.len()); for (index, compiled) in comb_unit_jits.iter().enumerate() { comb_unit_offsets.push(append_native_code( @@ -2639,6 +2914,7 @@ fn compile_program( runtime_errors: sir.runtime().runtime_schema.runtime_errors.clone(), runtime_event_sites: sir.runtime().runtime_schema.runtime_event_sites.clone(), extern_functions: sir.runtime().runtime_schema.extern_functions.clone(), + native_kernel_offsets, comb_observers: sir.runtime().runtime_schema.comb_observers.clone(), testbench_read_roots: sir.runtime().runtime_schema.testbench_read_roots.clone(), rtl_writes: sir.runtime().runtime_schema.rtl_writes.clone(), @@ -2782,6 +3058,35 @@ fn write_initial_run_to_plane( } impl NativeBackend { + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + pub(crate) fn compile_outlined_image_for_test( + program: &LaidOutProgram, + options: &SimulatorOptions, + ) -> Result { + compile_program_with_outlining_threshold(program, options, false, None, 0) + .map(|(image, _)| image) + } + + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + pub(crate) fn split_comb_units_for_test(program: &mut LaidOutProgram) { + program.sir.eval_comb = program + .sir + .eval_comb + .iter() + .flat_map(split_comb_execution_unit) + .collect(); + } + pub(crate) fn eval_comb_units_with( &mut self, mut after_unit: impl FnMut(&mut Self), diff --git a/crates/celox/src/backend/native/compile_resources.rs b/crates/celox/src/backend/native/compile_resources.rs index 0144103c5a8..7d33da0e01a 100644 --- a/crates/celox/src/backend/native/compile_resources.rs +++ b/crates/celox/src/backend/native/compile_resources.rs @@ -2,6 +2,62 @@ const MAX_WORKERS: usize = 4; +/// Dispatch in priority order, but return results in stable task-index order. +/// Each worker owns at most one expanded process and its compilation state. +pub(super) fn compile_tasks( + order: &[usize], + workers: usize, + compile: impl Fn(usize) -> T + Sync, +) -> std::thread::Result> { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut results = if workers <= 1 || order.len() <= 1 { + order + .iter() + .map(|&index| (index, compile(index))) + .collect::>() + } else { + let next = AtomicUsize::new(0); + std::thread::scope(|scope| { + let handles = (0..workers.min(order.len())) + .map(|_| { + let next = &next; + let compile = &compile; + scope.spawn(move || { + let mut results = Vec::new(); + loop { + let position = next.fetch_add(1, Ordering::Relaxed); + let Some(&index) = order.get(position) else { + break; + }; + results.push((index, compile(index))); + } + results + }) + }) + .collect::>(); + let mut results = Vec::new(); + let mut panic = None; + for handle in handles { + match handle.join() { + Ok(completed) => results.extend(completed), + Err(error) => { + if panic.is_none() { + panic = Some(error); + } + } + } + } + if let Some(error) = panic { + Err(error) + } else { + Ok(results) + } + })? + }; + results.sort_unstable_by_key(|(index, _)| *index); + Ok(results.into_iter().map(|(_, result)| result).collect()) +} + pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize { choose_workers( blocks, @@ -12,6 +68,52 @@ pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize ) } +/// One primary circuit and a queue of smaller independent event functions. +/// Reserve the primary once, rather than charging its size to every worker. +pub(super) fn workers_with_primary( + primary: (usize, usize), + secondary: (usize, usize), + tasks: usize, +) -> usize { + choose_workers_with_primary( + primary, + secondary, + tasks, + std::thread::available_parallelism().map_or(1, usize::from), + available_memory(), + ) +} + +fn choose_workers_with_primary( + primary: (usize, usize), + secondary: (usize, usize), + tasks: usize, + cpus: usize, + available: Option, +) -> usize { + let maximum = MAX_WORKERS.min(cpus.max(1)).min(tasks.saturating_add(1)); + let Some(available) = available else { + return choose_workers( + primary.0.max(secondary.0), + primary.1.max(secondary.1), + tasks.saturating_add(1), + cpus, + None, + ); + }; + let budget = available - available / 5; + let remaining = budget.saturating_sub(estimated_memory(primary.0, primary.1)); + 1 + (remaining / estimated_memory(secondary.0, secondary.1)) + .min(maximum.saturating_sub(1) as u64) as usize +} + +fn estimated_memory(blocks: usize, instructions: usize) -> u64 { + (blocks as u64) + .saturating_mul(24 * 1024) + .max((instructions as u64).saturating_mul(4096)) + .max(128 * 1024 * 1024) +} + fn choose_workers( blocks: usize, instructions: usize, @@ -30,10 +132,7 @@ fn choose_workers( // eight-hart functions peaked at 6.54 GiB for the entire process tree. // Account for straight-line designs too, not only CFG size. // These are conservative estimates, not reservations or memory limits. - let per_function = (blocks as u64) - .saturating_mul(24 * 1024) - .max((instructions as u64).saturating_mul(4096)) - .max(128 * 1024 * 1024); + let per_function = estimated_memory(blocks, instructions); // Leave room for the running simulator and unrelated host activity. let budget = available - available / 5; (budget / per_function).min(maximum as u64).max(1) as usize @@ -154,6 +253,93 @@ mod tests { const GIB: u64 = 1024 * 1024 * 1024; + #[test] + fn primary_worker_budget_keeps_capacity_for_smaller_functions() { + let primary = (65_536, 1_000_000); + let small = (100, 1_000); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 16, Some(8 * GIB)), + 4 + ); + assert_eq!( + choose_workers_with_primary(primary, primary, 10, 16, Some(8 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 16, Some(4 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 0, 16, Some(8 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 2, Some(8 * GIB)), + 2 + ); + assert_eq!( + choose_workers_with_primary((120_000, 1), small, 10, 16, None), + 1 + ); + for available in [0, GIB, 4 * GIB, 5 * GIB, 8 * GIB, u64::MAX] { + for secondary in [small, primary, (usize::MAX, usize::MAX)] { + let workers = + choose_workers_with_primary(primary, secondary, 10, 16, Some(available)); + assert!((1..=MAX_WORKERS).contains(&workers)); + if workers > 1 { + let reserved = u128::from(estimated_memory(primary.0, primary.1)) + + (workers - 1) as u128 + * u128::from(estimated_memory(secondary.0, secondary.1)); + assert!(reserved <= u128::from(available - available / 5)); + } + } + } + } + + #[test] + fn indexed_tasks_keep_results_ordered_and_bound_active_work() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let order = (0..16).rev().collect::>(); + for workers in [1, 2, 4] { + let active = AtomicUsize::new(0); + let peak = AtomicUsize::new(0); + let seen = AtomicUsize::new(0); + let results = compile_tasks(&order, workers, |index| { + let count = active.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(count, Ordering::SeqCst); + seen.fetch_or(1 << index, Ordering::SeqCst); + std::thread::yield_now(); + active.fetch_sub(1, Ordering::SeqCst); + index * 3 + }) + .unwrap(); + assert_eq!(results, (0..16).map(|index| index * 3).collect::>()); + assert_eq!(seen.load(Ordering::SeqCst), (1 << 16) - 1); + assert_eq!(active.load(Ordering::SeqCst), 0); + assert!(peak.load(Ordering::SeqCst) <= workers); + } + } + + #[test] + fn indexed_tasks_preserve_errors_and_return_worker_panics() { + let results = compile_tasks(&[3, 2, 1, 0], 2, |index| { + if index == 1 || index == 3 { + Err(index) + } else { + Ok(index) + } + }) + .unwrap(); + assert_eq!(results.into_iter().collect::, _>>(), Err(1)); + assert!( + compile_tasks(&[0, 1, 2], 2, |index| { + assert_ne!(index, 1, "worker panic probe"); + index + }) + .is_err() + ); + } + #[cfg(target_os = "linux")] #[test] fn finite_process_limit_caps_the_worker_memory_budget() { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 3c1a322be44..51923540478 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Compound event probes extend the fork activation image format. -const CONTAINER_VERSION: u16 = 47; +// Native kernel offsets extend the image metadata. +const CONTAINER_VERSION: u16 = 48; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 3ebc630ef97..183cb8cae95 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -788,6 +788,49 @@ impl EdgePlan { /// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit /// reads the scheduler's dirty flag to know whether to settle first. pub(crate) fn attach(program: &mut LaidOutProgram) { + attach_with_mode(program, false); +} + +/// Reserve native entry indices without retaining a copy of the full circuit +/// for both polarities of every derived-clock event. +pub(crate) fn attach_deferred(program: &mut LaidOutProgram) { + attach_with_mode(program, true); +} + +#[derive(Clone, Debug)] +pub(crate) struct DeferredEdge { + event: AbsoluteAddr, + rising: bool, + fires: bool, + flag: AbsoluteAddr, + pub(crate) blocks: usize, + pub(crate) instructions: usize, +} + +impl DeferredEdge { + pub(crate) fn generate( + &self, + program: &LaidOutProgram, + model: &ScheduleModel, + ) -> Result { + self.generate_with_comb(program, model, &program.sir.eval_comb) + } + + pub(crate) fn generate_with_comb( + &self, + program: &LaidOutProgram, + model: &ScheduleModel, + comb: &[Unit], + ) -> Result { + let plan = EdgePlan::new(program, model, self.event)? + .ok_or("deferred derived edge no longer has a plan")?; + let mut unit = plan.unit(comb, self.rising, self.fires, Settle::Flag(self.flag)); + crate::settle::instrument_unit(program, &mut unit); + Ok(unit) + } +} + +fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) { let schema = &program.runtime.runtime_schema; let Some(flag) = schema .scheduler @@ -815,14 +858,81 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { _ => true, }; let mut indices = [0usize; 2]; - for (index, rising) in [true, false].into_iter().enumerate() { - let unit = plan.unit( - &program.sir.eval_comb, - rising, - fires(rising), - Settle::Flag(flag), + // Include both settles and every possible FF path. The control-flow + // allowance also covers gate expressions and per-unit continuations. + let (estimated_blocks, estimated_instructions) = if deferred { + let units = program + .sir + .eval_comb + .iter() + .chain(&program.sir.eval_comb) + .chain(plan.entries().flat_map(|units| { + units + .eval_apply + .iter() + .chain(units.eval_only.as_ref().unwrap_or(&units.eval_apply)) + .chain(units.apply.iter().flatten()) + })); + let gate_ops = plan.gated.iter().map(|gate| gate.gate.len()).sum::(); + units.fold( + ( + 1024usize, + 8192usize.saturating_add(gate_ops.saturating_mul(16)), + ), + |(blocks, instructions), unit| { + ( + blocks.saturating_add(unit.blocks.len()).saturating_add(2), + instructions.saturating_add( + unit.blocks + .values() + .map(|b| b.instructions.len()) + .sum::(), + ), + ) + }, + ) + } else { + (0, 0) + }; + if deferred { + tracing::debug!( + "[derived-edge-size] event={} kind={:?} blocks={} instructions={}", + program.get_path(&event), + kind, + estimated_blocks, + estimated_instructions, ); + } + for (index, rising) in [true, false].into_iter().enumerate() { indices[index] = program.sir.processes.len(); + let unit = if deferred { + program.deferred_derived_edges.insert( + indices[index], + DeferredEdge { + event, + rising, + fires: fires(rising), + flag, + blocks: estimated_blocks, + instructions: estimated_instructions, + }, + ); + let mut builder = Builder::new(); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } else { + plan.unit( + &program.sir.eval_comb, + rising, + fires(rising), + Settle::Flag(flag), + ) + }; program.sir.processes.push(unit); } edges.push(celox_design::DerivedEdgeUnits { @@ -848,6 +958,7 @@ pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { .min(); if let Some(first) = first { program.sir.processes.truncate(first); + program.deferred_derived_edges.clear(); program.runtime.runtime_schema.derived_edges.clear(); } program diff --git a/crates/celox/src/dpi.rs b/crates/celox/src/dpi.rs index 06ab57898db..164b3cf4d12 100644 --- a/crates/celox/src/dpi.rs +++ b/crates/celox/src/dpi.rs @@ -176,6 +176,13 @@ impl Default for ExternFunctionTable { } impl ExternFunctionTable { + /// Append image-local compiled callees after the DPI imports. + pub(crate) fn append_native_kernels(&mut self, addresses: impl IntoIterator) { + let mut table = self.addresses.to_vec(); + table.extend(addresses); + self.addresses = table.into(); + } + /// The user table's address, which the state header holds. The internal /// floating-point helper occupies the immediately preceding slot, and the /// heap helper the one before it. diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index f226fc20aa6..b577ebbabbd 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -563,6 +563,10 @@ pub struct LaidOutProgram { pub sir: SirProgram, pub(crate) runtime: RuntimeProgram, layout: crate::backend::MemoryLayout, + /// Native-only generated process entries. Their SIR is expanded for one + /// compilation at a time; `sir.processes` reserves their stable indices. + #[cfg(feature = "host-runtime")] + pub(crate) deferred_derived_edges: HashMap, } impl LaidOutProgram { @@ -773,6 +777,8 @@ impl OptimizedSir { sir, runtime, layout, + #[cfg(feature = "host-runtime")] + deferred_derived_edges: HashMap::default(), }; crate::settle::instrument(&mut laid_out); laid_out diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs index 4358d762110..89b3591e54c 100644 --- a/crates/celox/src/settle.rs +++ b/crates/celox/src/settle.rs @@ -150,6 +150,18 @@ pub(crate) fn instrument_processes_from(program: &mut LaidOutProgram, first: usi } } +/// Apply the same process instrumentation after a deferred native kernel is +/// expanded. Its reserved process entry contained no stores to instrument. +#[cfg(feature = "host-runtime")] +pub(crate) fn instrument_unit( + program: &LaidOutProgram, + unit: &mut ExecutionUnit, +) { + if let Some(marker) = Marker::new(program.layout(), program.runtime()) { + marker.instrument(unit); + } +} + struct Marker<'a> { settle: &'a SettleLayout, layout: &'a crate::backend::MemoryLayout, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 8060be969e9..0e0992259c5 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2837,6 +2837,7 @@ mod host { fn into_laid_out_program( self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, + defer_derived_edges: bool, ) -> Result< ( crate::ir::LaidOutProgram, @@ -2847,13 +2848,14 @@ mod host { ), SimulatorError, > { - self.into_laid_out_program_with_trace(layout_mode, None) + self.into_laid_out_program_with_trace(layout_mode, None, defer_derived_edges) } fn into_laid_out_program_with_trace( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, trace: Option<&mut crate::debug::CompilationTrace>, + defer_derived_edges: bool, ) -> Result< ( crate::ir::LaidOutProgram, @@ -3013,7 +3015,11 @@ mod host { .optimize_options .is_enabled(crate::optimizer::SirPass::DerivedEdgeUnits) { - crate::derived_edge::attach(&mut laid_out); + if defer_derived_edges { + crate::derived_edge::attach_deferred(&mut laid_out); + } else { + crate::derived_edge::attach(&mut laid_out); + } } #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] if let Some(sink) = &self.options.derived_edge_units { @@ -3069,7 +3075,10 @@ mod host { let phase_start = phase_timing.then(crate::timing::now); let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { @@ -3139,7 +3148,10 @@ mod host { let phase_start = phase_timing.then(crate::timing::now); let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { @@ -3195,9 +3207,10 @@ mod host { let (laid_out, warnings, options, vcd_path, injected_components) = { let vcd_recording = self.vcd_path.is_some(); - self.into_laid_out_program(crate::backend::tiered::tiered_layout_mode( - vcd_recording, - ))? + self.into_laid_out_program( + crate::backend::tiered::tiered_layout_mode(vcd_recording), + false, + )? }; validate_untimed_processes(laid_out.runtime())?; @@ -3266,9 +3279,10 @@ mod host { let (laid_out, warnings, options, vcd_path, injected_components) = { let vcd_recording = self.vcd_path.is_some(); - self.into_laid_out_program(crate::backend::tiered::tiered_layout_mode( - vcd_recording, - ))? + self.into_laid_out_program( + crate::backend::tiered::tiered_layout_mode(vcd_recording), + false, + )? }; validate_untimed_processes(laid_out.runtime())?; @@ -3320,6 +3334,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, )?; validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { @@ -3365,6 +3380,7 @@ mod host { .into_laid_out_program_with_trace( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, Some(&mut trace), + true, )?; validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { @@ -3493,7 +3509,10 @@ mod host { self, ) -> Result, SimulatorError> { let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; @@ -3870,6 +3889,7 @@ mod host { pub fn build_cranelift(self) -> Result, SimulatorError> { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, |program, options| { let mut trace = crate::debug::CompilationTrace::default(); let wants_trace = options.trace.pre_optimized_clif @@ -3896,6 +3916,7 @@ mod host { { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, crate::backend::native::NativeBackend::new, ) } @@ -3916,6 +3937,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, )?; let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; @@ -3970,6 +3992,7 @@ mod host { { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, crate::backend::wasm_runtime::WasmBackend::new, ) } @@ -3980,6 +4003,7 @@ mod host { ) -> Result, SimulatorError> { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, crate::backend::InterpBackend::new, ) } @@ -3990,7 +4014,7 @@ mod host { self, ) -> Result, SimulatorError> { let layout = crate::backend::tiered::tiered_layout_mode(self.vcd_path.is_some()); - self.build_with_backend(layout, |program, options| { + self.build_with_backend(layout, false, |program, options| { Ok(crate::backend::TieredBackend::new(program, options)) }) } @@ -3998,11 +4022,12 @@ mod host { fn build_with_backend( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, + defer_derived_edges: bool, compile: impl Fn(&crate::ir::LaidOutProgram, &SimulatorOptions) -> Result, ) -> Result, SimulatorError> { self.options.emit_triggers = true; let (laid_out, mut warnings, options, vcd_path, injected_components) = - self.into_laid_out_program(layout_mode)?; + self.into_laid_out_program(layout_mode, defer_derived_edges)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let shadow = Self::start_shadow( @@ -4211,6 +4236,217 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + target_arch = "x86_64", + target_arch = "aarch64", + feature = "arm64-codegen" + ) + ))] + #[test] + fn deferred_edges_preserve_expanded_ir_and_reserve_only_small_entries() { + let source = r#"module Top(input bit clk, input bit en, output bit [7:0] q); + bit [7:0] r = 0, a = 0, b = 0, c = 0; + wire gated = clk & en; + wire inverted = ~clk; + wire second = gated & r[0]; + always_ff @(posedge clk) r <= r + 1; + always_ff @(posedge gated) a <= a + r; + always_ff @(posedge inverted) b <= b + a; + always_ff @(posedge second) c <= c + b; + assign q = a + b + c; + endmodule"#; + for partitioned in [false, true] { + let builder = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("deferred_edges.sv"))], + "Top", + ) + .emit_triggers() + .opt_level(crate::OptLevel::O1) + .disable_pass(crate::SirPass::DerivedEdgeUnits); + let builder = if partitioned { + builder.settle_partition(crate::SettlePartition::Always) + } else { + builder + }; + let (base, _, options, _, _) = builder + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) + .unwrap(); + let first = base.sir.processes.len(); + let mut expanded = base.clone(); + crate::derived_edge::attach(&mut expanded); + crate::settle::instrument_processes_from(&mut expanded, first, false); + let mut deferred = base; + crate::derived_edge::attach_deferred(&mut deferred); + crate::settle::instrument_processes_from(&mut deferred, first, false); + assert!(deferred.deferred_derived_edges.len() >= 4); + assert_eq!(expanded.sir.processes.len(), deferred.sir.processes.len()); + assert_eq!( + expanded.runtime().runtime_schema.derived_edges, + deferred.runtime().runtime_schema.derived_edges, + ); + if partitioned { + assert!(deferred.layout().settle.is_some()); + } + let model = celox_design::schedule::ScheduleModel::derive( + &deferred.design, + &deferred.runtime().runtime_schema, + ); + for (&index, edge) in &deferred.deferred_derived_edges { + let reserved = &deferred.sir.processes[index]; + assert_eq!(reserved.blocks.len(), 1); + assert!(reserved.register_map.is_empty()); + assert!(reserved.blocks.values().all(|block| { + block.instructions.is_empty() + && matches!(block.terminator, crate::ir::SIRTerminator::Return) + })); + let generated = edge.generate(&deferred, &model).unwrap(); + generated.verify_result().unwrap(); + assert!(edge.blocks >= generated.blocks.len()); + assert!( + edge.instructions + >= generated + .blocks + .values() + .map(|block| block.instructions.len()) + .sum::() + ); + assert_eq!(generated.blocks, expanded.sir.processes[index].blocks); + assert_eq!( + generated.register_map, + expanded.sir.processes[index].register_map + ); + } + let expanded_image = + crate::backend::native::NativeBackend::compile_image(&expanded, &options).unwrap(); + let deferred_image = + crate::backend::native::NativeBackend::compile_image(&deferred, &options).unwrap(); + assert_eq!(expanded_image.code_image(), deferred_image.code_image()); + #[cfg(all(target_arch = "x86_64", not(feature = "arm64-codegen")))] + { + let outlined_image = + crate::backend::native::NativeBackend::compile_outlined_image_for_test( + &deferred, &options, + ) + .unwrap(); + // Exercise pointer-free serialization before relocating both + // images into independent executable mappings. + let bytes = outlined_image.to_container_bytes().unwrap(); + let outlined_image: crate::backend::native::NativeProgramImage = + crate::backend::native::NativeProgramImage::from_container_bytes(&bytes) + .unwrap(); + let mut simulations = [deferred_image, outlined_image].map(|image| { + let runtime = image.runtime_program(); + // SAFETY: these images were compiled from this fixture. + let backend = + unsafe { crate::backend::native::NativeBackend::from_image(image) } + .unwrap(); + let mut sim = crate::Simulator::with_backend_and_program_for_simulation( + backend, + runtime, + Vec::new(), + ); + sim.apply_initial_values(); + sim.modify(|_| {}).unwrap(); + sim + }); + for step in 0..80 { + for sim in &mut simulations { + let enable = sim.signal("en"); + sim.modify(|io| io.set(enable, u8::from(step % 3 != 0))) + .unwrap(); + let clk = sim.event("clk"); + if step % 5 == 0 { + sim.edge(clk, crate::Edge::Falling).unwrap(); + } else { + sim.tick(clk).unwrap(); + } + } + for name in ["q", "r", "a", "b", "c"] { + assert_eq!( + simulations[0].get(simulations[0].signal(name)), + simulations[1].get(simulations[1].signal(name)), + "partitioned={partitioned}, step={step}, signal={name}" + ); + } + } + } + let baseline = crate::derived_edge::without_units(&deferred); + assert!(baseline.deferred_derived_edges.is_empty()); + assert!(baseline.runtime().runtime_schema.derived_edges.is_empty()); + } + } + + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + #[test] + fn native_comb_chunks_preserve_cross_unit_state_through_image_roundtrip() { + let source = r#"module Top(input bit [7:0] a, + output bit [7:0] mid, out, mirror); + assign mid = a + 8'h11; + assign out = mid ^ 8'ha5; + assign mirror = out + mid; + endmodule"#; + let (mut program, _, options, _, _) = crate::Simulator::from_sv_sources( + vec![(source, std::path::Path::new("chunks.sv"))], + "Top", + ) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) + .unwrap(); + crate::backend::native::NativeBackend::split_comb_units_for_test(&mut program); + assert!(program.sir.eval_comb.len() > 1); + let merged = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let chunked = crate::backend::native::NativeBackend::compile_outlined_image_for_test( + &program, &options, + ) + .unwrap(); + assert!( + chunked + .code_entries() + .iter() + .filter(|entry| entry.name.starts_with("eval_comb_chunk[")) + .count() + > 1 + ); + for image in [merged, chunked] { + let image = crate::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + let runtime = image.runtime_program(); + // SAFETY: this image was compiled from this fixture. + let backend = unsafe { crate::NativeBackend::from_image(image) }.unwrap(); + let mut sim = crate::Simulator::with_backend_and_program_for_simulation( + backend, + runtime, + Vec::new(), + ); + sim.apply_initial_values(); + for step in 0..80u8 { + let value = step.wrapping_mul(17); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, value)).unwrap(); + let mid = value.wrapping_add(0x11); + let out = mid ^ 0xa5; + for (name, expected) in [ + ("mid", mid), + ("out", out), + ("mirror", out.wrapping_add(mid)), + ] { + let signal = sim.signal(name); + assert_eq!(sim.get(signal), num_bigint::BigUint::from(expected)); + } + } + } + } + #[cfg(all( test, feature = "systemverilog", @@ -4236,7 +4472,7 @@ endmodule"#; let (mut program, warnings, options, _, _) = crate::Simulation::from_sv_sources(sources, "Top") .emit_triggers() - .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) .unwrap(); let schema = &mut program.runtime.runtime_schema; let count = schema.processes.len(); @@ -4296,7 +4532,7 @@ endmodule"#; "Top", ) .emit_triggers() - .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); @@ -4346,7 +4582,7 @@ endmodule"#; vec![(&source, std::path::Path::new("native-vcd.sv"))], "Top", ) - .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); @@ -4408,7 +4644,7 @@ endmodule"#; "Top", ) .four_state(four_state) - .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index a633fbf92b6..11c62aaa718 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -240,7 +240,7 @@ pub enum CodegenError { source: wasmtime::Error, }, - #[cfg(feature = "host-runtime")] + #[cfg(any(feature = "host-runtime", feature = "systemverilog"))] #[error("{message}")] Message { message: String }, @@ -250,7 +250,7 @@ pub enum CodegenError { Cancelled, } -#[cfg(feature = "host-runtime")] +#[cfg(any(feature = "host-runtime", feature = "systemverilog"))] impl CodegenError { pub(crate) fn message(message: impl Into) -> Self { Self::Message { From b03076c40c73d28a32cff4b540841b9f33146f09 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:20:04 +0900 Subject: [PATCH 2/5] fix(vpi): expose interface parameters and lexical generate scopes Retain instance-local interface value parameters and localparams using declaration provenance, including indexed interface handles and authored dollar identifiers. Preserve package ownership. Build lexical generate scope prefixes for reflection separately from execution and VCD instance paths, inheriting timescales from the nearest real ancestor. The image container advances to version 49 for serialized lexical scope metadata. Validation covers specialized read-only parameters, escaped identifiers, interface arrays, generate iteration, timescales and native image roundtrips. Frontend, VPI and native library suites, owning-crate lint and formatting pass. This makes the unchanged original board tests discover all actual traffic models instead of passing with an empty MAC list. Keep the class-specialization depth guard reachable on the default stack: separate parameter binding, inherited-base resolution and body construction, with pending specialization metadata owned on the heap. Large temporary binding frames no longer accumulate across recursive inheritance. Preserve the existing depth-64 limit and diagnostics; test legitimate deep inheritance and a nonterminating specialization on an explicit 2 MiB thread stack. Validation after rebasing onto master 626dc7cb11: reproduce the CI SIGABRT with its full comparison-feature configuration, then pass the same test with the fix. All 842 analyzer unit tests (3 existing ignored), 372 class integration tests, 57 VPI tests, analyzer clippy and formatting pass. The host-runtime-disabled SystemVerilog build also passes. Change-Id: I3d0a6f889f3bc98503bbad44ab3bef8f52cab9c9 --- crates/celox-frontend-sv/src/lowering.rs | 108 ++++++++++++-- .../src/ast/classes/specializations.rs | 122 +++++++++++++++- .../celox-sv-analyzer/src/ast/interfaces.rs | 16 ++- crates/celox-vpi/tests/basic_vpi.rs | 132 ++++++++++++++++++ crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/ir.rs | 57 +++++++- crates/celox/src/parser.rs | 64 ++++++++- 7 files changed, 472 insertions(+), 31 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 77e3c065724..dc586ef7f0e 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -337,6 +337,7 @@ fn interface_signatures_collecting( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -949,6 +950,7 @@ fn lower_package_states( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -3171,24 +3173,44 @@ fn demote_level_lists( changed } -// Use elaboration provenance rather than treating every '$' as a separator: -// legal authored identifiers may themselves contain '$'. +// Candidate indices only locate a declaration; source provenance decides +// whether this is an interface path. Authored '$' names stay intact. +fn restore_interface_path( + name: &str, + paths: &HashMap, +) -> Option> { + if let Some(path) = paths.get(name) { + return path.restore(name); + } + for (separator, _) in name.match_indices('$') { + let member = &name[separator + 1..]; + let mut handle = &name[..separator]; + while let Some(indexed) = handle.strip_suffix(']') { + let Some((base, index)) = indexed.rsplit_once('[') else { + break; + }; + if index.parse::().is_err() { + break; + } + let key = format!("{base}${member}"); + if let Some(path) = paths.get(&key).filter(|path| path.arrayed) + && let Some(restored) = path.restore(name) + { + return Some(restored); + } + handle = base; + } + } + None +} + fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvModule) { for variable in module.variables.values_mut() { variable.path = variable .path .iter() .flat_map(|segment| { - source - .interface_member_paths - .get(segment) - .and_then(|path| path.restore(segment)) - .or_else(|| { - source - .interface_member_paths - .values() - .find_map(|path| path.restore(segment)) - }) + restore_interface_path(segment, &source.interface_member_paths) .unwrap_or_else(|| vec![segment.clone()]) }) .collect(); @@ -3367,6 +3389,7 @@ fn specialize_module( &local_forces, level_lists, hierarchical.foreign_writes, + &module.interface_member_paths, )?; propagate_force_signals(&mut lowered.instances, &key.force_signals); lowered.sim_module.time_precision = Some( @@ -3480,6 +3503,7 @@ fn lower_module( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { lower_module_with_overrides( module, @@ -3491,6 +3515,7 @@ fn lower_module( force_signals, level_lists, foreign_writes, + reflected_paths, ) } @@ -3573,6 +3598,7 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); @@ -3777,7 +3803,14 @@ fn lower_module_with_overrides( // Retain integral parameters for external observation, without adding them // to name_to_id: HDL expressions must still fold parameter references as // constants rather than introduce runtime loads. - for parameter in module.parameters() { + // Interface declarations are flattened into imported symbols, rather + // than authored module parameters. Retain their instance-local values as + // well; package imports remain owned by their package (IEEE 37.10). + let interface_parameters = module + .imported_parameters() + .iter() + .filter(|parameter| restore_interface_path(parameter.name(), reflected_paths).is_some()); + for parameter in module.parameters().iter().chain(interface_parameters) { let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else { continue; }; @@ -11289,3 +11322,52 @@ endmodule ); } } + +#[cfg(test)] +mod interface_reflection_tests { + use super::*; + + #[test] + fn indexed_interface_paths_require_declaration_provenance() { + let paths = [ + ( + "authored$bus$extra$width", + ["authored$bus", "extra$width"], + false, + ), + ("lanes$extra$width", ["lanes", "extra$width"], true), + ("g[3].lanes$W", ["g[3].lanes", "W"], true), + ] + .into_iter() + .map(|(key, segments, arrayed)| { + ( + key.to_string(), + sv::InterfaceMemberPath { + segments: segments.into_iter().map(str::to_string).collect(), + arrayed, + }, + ) + }) + .collect(); + for (name, expected) in [ + ("authored$bus$extra$width", ["authored$bus", "extra$width"]), + ("lanes[1][-2]$extra$width", ["lanes[1][-2]", "extra$width"]), + ("g[3].lanes[7]$W", ["g[3].lanes[7]", "W"]), + ] { + assert_eq!( + restore_interface_path(name, &paths), + Some(expected.into_iter().map(str::to_string).collect()), + "{name}" + ); + } + for name in [ + "lanes$not_declared", + "lanes[foo]$extra$width", + "authored$bus[0]$extra$width", + "normal$parameter", + "g[2].lanes[7]$W", + ] { + assert_eq!(restore_interface_path(name, &paths), None, "{name}"); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index 7fddf6b39ec..58db650b9d5 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -267,6 +267,43 @@ pub(in crate::ast) fn specialize( } depth.set(depth.get() + 1); let _nesting = Nesting(depth); + // Parameter binding and body construction have large temporary values. + // Keep those phases off the stack while resolving an inherited class. + let pending = match prepare(tree, generic, arguments, context)? { + Preparation::Existing(name) => return Ok(name), + Preparation::Pending(pending) => pending, + }; + tree.state + .class_specializations_building + .borrow_mut() + .push(pending.name.clone()); + let _building = Building(&tree.state.class_specializations_building); + let bases = bind_bases(tree, generic, &pending.env, &pending.aliases)?; + finish_specialization(tree, generic, pending, bases) +} + +struct PendingSpecialization { + name: String, + parameters: Parameters, + env: HashMap, + aliases: HashMap, +} + +enum Preparation { + Existing(String), + Pending(Box), +} + +// These boundaries keep the recursive inheritance frame small in debug and +// optimized builds alike; the specialization limit must produce a diagnostic +// before the host thread runs out of stack. +#[inline(never)] +fn prepare( + tree: &AnalysisContext<'_>, + generic: &str, + arguments: &[Argument], + context: &PackedDimensions, +) -> Converted { let native = tree.declarations(); let declaration = super::declaration(tree, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; @@ -375,7 +412,7 @@ pub(in crate::ast) fn specialize( .borrow() .contains(&name) { - return Ok(name); + return Ok(Preparation::Existing(name)); } if tree.state.class_specializations_frozen.get() { return Err(unsupported(format!( @@ -387,11 +424,24 @@ pub(in crate::ast) fn specialize( "more than {MAX_SPECIALIZATIONS} class specializations" ))); } - tree.state - .class_specializations_building - .borrow_mut() - .push(name.clone()); - let _building = Building(&tree.state.class_specializations_building); + Ok(Preparation::Pending(Box::new(PendingSpecialization { + name, + parameters, + env, + aliases, + }))) +} + +#[inline(never)] +fn bind_bases( + tree: &AnalysisContext<'_>, + generic: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The bases are named in the scope of the parameters; a class does not // inherit the declarations of the interface classes it implements. let inherited = match &declaration.base { @@ -401,12 +451,31 @@ pub(in crate::ast) fn specialize( }; let mut bases = Vec::new(); for id in inherited { - if let Some(base) = type_binding::procedural_type(id, native, tree, &env, &aliases)? + if let Some(base) = type_binding::procedural_type(id, native, tree, env, aliases)? .and_then(|ty| ty.class().map(str::to_owned)) { bases.push(base); } } + Ok(bases) +} + +#[inline(never)] +fn finish_specialization( + tree: &AnalysisContext<'_>, + generic: &str, + pending: Box, + bases: Vec, +) -> Converted { + let PendingSpecialization { + name, + mut parameters, + mut env, + mut aliases, + } = *pending; + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The body sees the parameters and types of the bases, hidden by the // class's own, and the scope of the specialization (8.25.1). for base in &bases { @@ -1088,3 +1157,42 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } } } + +#[cfg(test)] +mod tests { + use std::path::Path; + + #[test] + fn inheritance_specialization_uses_the_default_thread_stack() { + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut source = String::from("module Top;"); + for index in 0..16 { + source.push_str(&format!( + "class Layer{index} #(int N = 0) extends Layer{}#(N + 1); endclass ", + index + 1, + )); + } + source.push_str( + "class Layer16 #(int N = 0); localparam int VALUE = N; endclass + Layer0#() object; initial $display(Layer0#()::VALUE); endmodule", + ); + crate::analyze_source(&source, Path::new("deep-class-inheritance.sv")).unwrap(); + + let error = crate::analyze_source( + "module Top; + class Recursive #(int N = 0) extends Recursive#(N + 1); endclass + Recursive object; endmodule", + Path::new("unbounded-class-inheritance.sv"), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("nested more than 64 deep"), "{error}"); + assert!(error.contains("class `Recursive`"), "{error}"); + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index dfe0c33870b..4750eb0768f 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -679,6 +679,8 @@ struct InterfaceDecl { /// Whether the declaration refers to compilation-unit items of its file. uses_unit_items: bool, parameters: Vec, + /// Value parameters and localparams whose instance paths VPI can observe. + reflected_parameters: Vec, type_parameters: Vec, parameter_order: Vec, items: Vec, @@ -2423,6 +2425,7 @@ impl InterfaceDecl { uses_unit_items: false, uses_macros: has_directive(file.text(span)), parameters: Vec::new(), + reflected_parameters: Vec::new(), type_parameters: Vec::new(), parameter_order: Vec::new(), items: Vec::new(), @@ -2614,6 +2617,7 @@ impl InterfaceDecl { }); return Ok(()); }; + self.reflected_parameters.push(native_name(¶meter.name)); if local { self.declare(native_name(¶meter.name))?; self.items.push(Item::Constant { @@ -3506,11 +3510,17 @@ pub fn plan_interfaces_with_member_paths( let mut member_paths = HashMap::default(); for (handle_name, declarations) in &handles.by_name { for (_, handle) in declarations { - for member in &design.interfaces[&handle.interface].members { + let interface = &design.interfaces[&handle.interface]; + for member in interface + .members + .iter() + .map(|member| &member.name) + .chain(&interface.reflected_parameters) + { member_paths.insert( - format!("{handle_name}{SEPARATOR}{}", member.name), + format!("{handle_name}{SEPARATOR}{member}"), InterfaceMemberPath { - segments: vec![handle_name.clone(), member.name.clone()], + segments: vec![handle_name.clone(), member.clone()], arrayed: handle.arrayed, }, ); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 8f2971e3266..47c89a7fefd 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -76,6 +76,138 @@ fn systemverilog_parameters_are_typed_read_only_objects_at_o2() { clear_runtime(); } +#[cfg(feature = "systemverilog")] +#[test] +fn interface_parameters_keep_instance_paths_and_specialized_values() { + let _serial = lock_vpi(); + let source = r#" + package P; parameter PKG = 123; parameter axil_ctrl_bar$not_member = 99; endpackage + interface Bus #(parameter ADDR_W = 8, parameter extra$width = 3); + localparam HALF = ADDR_W / 2; + logic [ADDR_W-1:0] data; + endinterface + module Top #(parameter authored$width = 7)(output logic q); + import P::*; + Bus #(.ADDR_W(24)) axil_ctrl_bar(); + Bus #(.ADDR_W(12)) lanes[1:0](); + assign q = 1'b0; + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("interface_params.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + for (name, expected) in [ + (c"Top.axil_ctrl_bar.ADDR_W", 24), + (c"Top.axil_ctrl_bar.HALF", 12), + (c"Top.lanes[1].ADDR_W", 12), + (c"Top.lanes[0].HALF", 6), + (c"Top.lanes[0].extra$width", 3), + (c"Top.authored$width", 7), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TYPE, handle), VPI_PARAMETER); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?}"); + value.value.integer = 0; + vpi_put_value(handle, &value, ptr::null(), VPI_NO_DELAY); + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?} is read-only"); + vpi_free_object(handle); + } + // Imported package constants do not acquire module-instance names. + assert!(vpi_handle_by_name(c"Top.PKG".as_ptr(), ptr::null_mut()).is_null()); + assert!( + vpi_handle_by_name(c"Top.axil_ctrl_bar$not_member".as_ptr(), ptr::null_mut()).is_null() + ); + } + clear_runtime(); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn generate_scopes_with_only_child_instances_are_iterable() { + let _serial = lock_vpi(); + let source = r#" + module Leaf #(parameter P = 0)(output logic q); + timeunit 1us; timeprecision 1ns; + assign q = P; + endmodule + module Top(output logic [1:0] q); + timeunit 1ns; timeprecision 1ps; + for (genvar n = 0; n < 2; n++) begin : bank + if (1) begin : shell + Leaf #(.P(n)) u(q[n]); + end + end + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("generate_scopes.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let iterator = vpi_iterate(VPI_INTERNAL_SCOPE, top); + assert!(!iterator.is_null()); + let mut names = Vec::new(); + loop { + let bank = vpi_scan(iterator); + if bank.is_null() { + break; + } + names.push( + CStr::from_ptr(vpi_get_str(VPI_NAME, bank)) + .to_str() + .unwrap() + .to_string(), + ); + assert_eq!(vpi_get(VPI_TIME_UNIT, bank), -9); + let nested = vpi_iterate(VPI_INTERNAL_SCOPE, bank); + assert!(!nested.is_null()); + let shell = vpi_scan(nested); + assert!(!shell.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, shell)), c"shell"); + assert_eq!(vpi_get(VPI_TIME_UNIT, shell), -9); + assert!(vpi_scan(nested).is_null()); + let children = vpi_iterate(VPI_MODULE, shell); + let leaf = vpi_scan(children); + assert!(!leaf.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, leaf)), c"u"); + assert_eq!(vpi_get(VPI_TIME_UNIT, leaf), -6); + assert!(vpi_scan(children).is_null()); + vpi_free_object(leaf); + vpi_free_object(shell); + vpi_free_object(bank); + } + assert_eq!(names, ["bank[0]", "bank[1]"]); + vpi_free_object(top); + } + clear_runtime(); +} + unsafe extern "C" fn reschedule_long_callback(data: *mut VpiCbData) -> i32 { let count = LONG_CALLBACK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; let delay = LONG_CALLBACK_DELAY.load(Ordering::SeqCst); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 51923540478..f812ecbcff4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Native kernel offsets extend the image metadata. -const CONTAINER_VERSION: u16 = 48; +// Native kernel offsets and lexical reflection scopes extend the image metadata. +const CONTAINER_VERSION: u16 = 49; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index b577ebbabbd..23a062b2d34 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -93,6 +93,9 @@ pub struct RuntimeDesign { instance_ids: HashMap, variables: HashMap, package_instances: crate::HashSet, + /// Source-declared lexical scopes used only by reflection. Keep the + /// real-instance display path unchanged for lookup and VCD bookkeeping. + reflection_instance_paths: std::collections::BTreeMap>, } impl std::ops::Deref for RuntimeDesign { @@ -195,6 +198,7 @@ impl RuntimeDesign { instance_ids: frontend.instance_ids, variables, package_instances: frontend.package_instances, + reflection_instance_paths: Default::default(), }; design .validate() @@ -206,6 +210,14 @@ impl RuntimeDesign { &self.semantic } + #[cfg(feature = "systemverilog")] + pub(crate) fn set_reflection_instance_paths( + &mut self, + paths: std::collections::BTreeMap>, + ) { + self.reflection_instance_paths = paths; + } + pub fn instances(&self) -> impl Iterator { self.instances.values() } @@ -900,7 +912,11 @@ impl RuntimeProgram { .design .instances() .map(|instance| { - let segments = &instance.display_path; + let segments = self + .design + .reflection_instance_paths + .get(&instance.id) + .unwrap_or(&instance.display_path); let name = segments .last() .cloned() @@ -932,9 +948,42 @@ impl RuntimeProgram { // instances. Retain their source path segments as navigable scopes. let real_scopes = scope_sources .iter() - .map(|scope| scope.full_name.clone()) - .collect::>(); + .map(|scope| (scope.full_name.clone(), scope.instance_id)) + .collect::>(); let mut member_scopes = HashMap::default(); + let root_instance = self + .design + .root_instance() + .expect("top-level instance exists") + .id; + // A generate block can contain only child instances, without a local + // variable to create its scope. Materialize every declared prefix and + // inherit its time scale from the nearest real enclosing instance. + for segments in self.design.reflection_instance_paths.values() { + let mut owner = root_instance; + for depth in 1..segments.len() { + let full_name = format!("{root_name}.{}", segments[..depth].join(".")); + if let Some(&instance) = real_scopes.get(&full_name) { + owner = instance; + continue; + } + let parent_name = if depth == 1 { + root_name.clone() + } else { + format!("{root_name}.{}", segments[..depth - 1].join(".")) + }; + member_scopes + .entry(full_name.clone()) + .or_insert_with(|| ScopeSource { + is_instance: false, + instance_id: owner, + name: segments[depth - 1].clone(), + full_name, + parent_name: Some(parent_name), + module_name: String::new(), + }); + } + } for scope in &scope_sources { let instance = self.design.instance(scope.instance_id).unwrap(); for address in instance.state_addresses() { @@ -945,7 +994,7 @@ impl RuntimeProgram { for depth in 1..variable.path.len() { let full_name = format!("{}.{}", scope.full_name, variable.path[..depth].join(".")); - if real_scopes.contains(&full_name) { + if real_scopes.contains_key(&full_name) { continue; } let parent_name = if depth == 1 { diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index fd3e655c203..646d3e33a05 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -630,7 +630,7 @@ pub fn parse_sv( if let Some(trace) = trace.as_deref_mut() { trace.absorb_frontend(frontend_trace); } - finalize_scheduled_rtl( + let mut program = finalize_scheduled_rtl( scheduled, None, four_state, @@ -642,7 +642,43 @@ pub fn parse_sv( testbench_random_seed, component_libraries, component_file_base, - ) + )?; + let paths = program + .runtime + .design + .instances() + .filter_map(|instance| { + let scopes = sv_reflection_scope_segments(&instance.display_path); + (scopes != instance.display_path).then_some((instance.id, scopes)) + }) + .collect(); + program.runtime.design.set_reflection_instance_paths(paths); + Ok(program) +} + +/// Split only SystemVerilog hierarchy separators. Escaped identifiers retain +/// their spelling and whitespace terminator (IEEE 1800-2023 5.6.1). +#[cfg(feature = "systemverilog")] +fn sv_reflection_scope_segments(segments: &[String]) -> Vec { + let mut result = Vec::new(); + for segment in segments { + let mut start = 0; + let mut escaped = false; + for (index, character) in segment.char_indices() { + if escaped { + if character.is_ascii_whitespace() { + escaped = false; + } + } else if character == '\\' { + escaped = true; + } else if character == '.' { + result.push(segment[start..index].to_string()); + start = index + 1; + } + } + result.push(segment[start..].to_string()); + } + result } /// An analyzer error as a parser error: a construct the analyzer does not @@ -1135,3 +1171,27 @@ mod fused_hint_tests { ); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod sv_scope_tests { + use super::sv_reflection_scope_segments; + + #[test] + fn lexical_scopes_preserve_escaped_dots_and_instance_paths() { + let slash = char::from(92u8); + let generated = format!("bank[2].{slash}literal.with.dots .u"); + let leaf = format!("{slash}leaf.with.dots"); + let source = vec![generated.clone(), leaf.clone()]; + let scopes = sv_reflection_scope_segments(&source); + assert_eq!( + scopes, + vec![ + "bank[2]".to_string(), + format!("{slash}literal.with.dots "), + "u".to_string(), + leaf + ] + ); + assert_eq!(scopes.join("."), source.join(".")); + } +} From a3a7832fd79fe2580d73d98f88eb7e1eb4398dc5 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:20:55 +0900 Subject: [PATCH 3/5] perf(settle): bound estimated partitions and preserve sparse updates Keep estimated partition overhead bounded as designs grow, targeting at most 64 coarse partitions with at least 16000 expression nodes per partition. A fraction of dirty flags is not a cost estimate when clean partitions contain most of the work: use full settle only when all partitions are dirty or an untracked raw view requires it. Partitioned settle remains disabled by default for O1/O2. Validation: frontend-core and SLT unit suites, partition APIs across backends, a 3-of-9 update regression retaining the partial path, and raw-pointer full-settle preservation; clippy and formatting. Change-Id: I9e4342b5784cd4503a7987b3251cdbf654e72040 --- .../src/symbolic/assembly.rs | 32 ++++++++- crates/celox-slt/src/scheduler.rs | 19 ++---- crates/celox/tests/settle_partitions.rs | 66 +++++++++++++++++++ 3 files changed, 102 insertions(+), 15 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 88712b02971..3805e53f6a6 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2604,7 +2604,14 @@ pub fn schedule_symbolic_rtl_reporting_loops( /// [`SettlePartitionMode::Estimated`] partitions. const MIN_PARTITIONED_SETTLE_COST: usize = 20_000; /// Expression nodes per partition of an estimated partitioned settle. -const SETTLE_PARTITION_COST: usize = 2_000; +const SETTLE_PARTITION_COST: usize = 16_000; +/// Bound flag tests, publication checks, and their compiler analyses on large +/// designs instead of growing the number of partitions with every source node. +const TARGET_ESTIMATED_SETTLE_PARTITIONS: usize = 64; + +fn estimated_settle_partition_cost(cost: usize) -> usize { + SETTLE_PARTITION_COST.max(cost.div_ceil(TARGET_ESTIMATED_SETTLE_PARTITIONS)) +} /// The cost per partition of a partitioned settle of `comb_blocks`, or /// `None` to keep one pass. @@ -2634,7 +2641,7 @@ fn settle_partitioning( .iter() .map(|path| scheduler::path_cost(arena, path)) .sum(); - (cost >= MIN_PARTITIONED_SETTLE_COST).then_some(SETTLE_PARTITION_COST) + (cost >= MIN_PARTITIONED_SETTLE_COST).then(|| estimated_settle_partition_cost(cost)) } } } @@ -6305,3 +6312,24 @@ mod tests { assert!(copied > 50 * 4 + 50, "{copied} probes"); } } + +#[cfg(test)] +mod estimated_settle_budget_tests { + use super::*; + + #[test] + fn estimated_guard_count_stays_bounded_as_the_program_grows() { + for cost in [ + 20_000, + 100_000, + 1_000_000, + 3_000_000, + 100_000_000, + usize::MAX, + ] { + let target = estimated_settle_partition_cost(cost); + assert!(target >= SETTLE_PARTITION_COST); + assert!(cost.div_ceil(target) <= TARGET_ESTIMATED_SETTLE_PARTITIONS); + } + } +} diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index 12ac16440e6..410c897e497 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -3513,12 +3513,6 @@ struct PlannedPartition { pinned: bool, } -/// Run every partition of a settle that starts with at least -/// `1 / FULL_SETTLE_DIVISOR` of its flags set (or the untracked byte), and -/// skip comparing what the partitions write: running the whole settle then -/// costs about a single pass. -const FULL_SETTLE_DIVISOR: usize = 3; - /// A chunk of an object a partition writes, compared before and after the /// partition runs. struct WatchedChunk { @@ -3929,9 +3923,10 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a } } - /// Start a settle of `count` partitions: run all of them when the - /// untracked byte or at least `1 / FULL_SETTLE_DIVISOR` of their flags - /// are set, recorded in the full byte. + /// Start a settle of `count` partitions. Skip publication comparisons + /// when every partition will run anyway, or an untracked raw view requires + /// a full settle. A fraction of dirty flags is not a cost estimate: a + /// clean partition can contain most of the program's work. fn begin_settle(&mut self, flags: Addr, count: usize) { let all = self.builder.alloc_bit(count * 8, false); self.builder.emit(SIRInstruction::Load( @@ -3945,10 +3940,8 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a self.builder .emit(SIRInstruction::Unary(dirty, UnaryOp::PopCount, all)); let threshold = self.builder.alloc_bit(count_width, false); - self.builder.emit(SIRInstruction::Imm( - threshold, - SIRValue::new(count.div_ceil(FULL_SETTLE_DIVISOR) as u64), - )); + self.builder + .emit(SIRInstruction::Imm(threshold, SIRValue::new(count as u64))); let busy = self.builder.alloc_bit(1, false); self.builder.emit(SIRInstruction::Binary( busy, diff --git a/crates/celox/tests/settle_partitions.rs b/crates/celox/tests/settle_partitions.rs index 4237e5286b3..b9ff2be6e69 100644 --- a/crates/celox/tests/settle_partitions.rs +++ b/crates/celox/tests/settle_partitions.rs @@ -147,6 +147,72 @@ fn partitioned_native_matches_single_pass() { assert_eq!(trace!(partitioned().build_native().unwrap()), reference()); } +/// A count of dirty partitions says nothing about their share of the work: +/// unrelated partitions can contain much wider expressions or larger processes. +/// Updating one input must not promote its three readers to a full settle. +#[test] +fn sparse_partition_updates_do_not_promote_unrelated_work() { + const SOURCE: &str = r#" +module Top ( + a: input logic<8>, b: input logic<8>, c: input logic<8>, + a0: output logic<8>, a1: output logic<8>, a2: output logic<8>, + b0: output logic<8>, b1: output logic<8>, b2: output logic<8>, + c0: output logic<8>, c1: output logic<8>, c2: output logic<8>, +) { + assign a0 = a + 8'd1; assign a1 = a + 8'd2; assign a2 = a + 8'd3; + assign b0 = b + 8'd1; assign b1 = b + 8'd2; assign b2 = b + 8'd3; + assign c0 = c + 8'd1; assign c1 = c + 8'd2; assign c2 = c + 8'd3; +} +"#; + let mut sim = Simulator::builder(SOURCE, "Top") + .settle_partition(SettlePartition::Always) + .build_interpreter() + .unwrap(); + let settle = sim.layout().settle.as_ref().unwrap().clone(); + let flags = || { + let (memory, _) = sim.memory_as_ptr(); + // SAFETY: these offsets describe this simulator's state allocation. + unsafe { + std::slice::from_raw_parts(memory.add(settle.flags_offset), settle.partitions + 2) + .to_vec() + } + }; + // Initial evaluation still runs every partition. + let initial = flags(); + assert!(initial[..settle.partitions].iter().all(|&flag| flag == 1)); + sim.eval_comb().unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 7u8)).unwrap(); + let (memory, _) = sim.memory_as_ptr(); + let pending = + unsafe { std::slice::from_raw_parts(memory.add(settle.flags_offset), settle.partitions) }; + let dirty = pending.iter().filter(|&&flag| flag != 0).count(); + assert_eq!(dirty, 3); + assert_eq!(settle.partitions, 9); + sim.eval_comb().unwrap(); + let (memory, _) = sim.memory_as_ptr(); + assert_eq!( + unsafe { *memory.add(settle.flags_offset + settle.partitions + 1) }, + 0, + "a partial update promoted unrelated partitions to a full settle" + ); + let a2 = sim.signal("a2"); + let b2 = sim.signal("b2"); + assert_eq!(sim.get(a2), BigUint::from(10u8)); + assert_eq!(sim.get(b2), BigUint::from(3u8)); + + // A retained raw view still requires full evaluation on every settle. + let (memory, _) = sim.memory_as_mut_ptr(); + // SAFETY: a names an eight-bit input in this allocation. + unsafe { *memory.add(a.offset) = 11 }; + sim.eval_comb().unwrap(); + assert_eq!(sim.get(a2), BigUint::from(14u8)); + assert_eq!( + unsafe { *memory.add(settle.flags_offset + settle.partitions + 1) }, + 1 + ); +} + /// Loading a state file writes every object, so every partition reading one /// must run again; the settle's flags themselves are not state. #[test] From 5736f9d6bdcc27b356b4f0acb66229e2ca5a3784 Mon Sep 17 00:00:00 2001 From: mergify <37929162+mergify@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:50:13 +0000 Subject: [PATCH 4/5] chore(deps): update mbx to 1.28.0 --- flake.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flake.lock b/flake.lock index 11c01378c72..a241121c49a 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792838410, - "narHash": "sha256-PCLsTfCsvQil43pMJRF6rZIgts9ddGEGg31R+S49aV8=", + "lastModified": 1793074073, + "narHash": "sha256-PAz/rV8xAiiAlZyKGJc/UC5saAbMbNEHVtzhGPSv0ic=", "owner": "tignear", "repo": "nix-packages", - "rev": "fd5c964507d21e820c948e280a0aecda842bd5b2", + "rev": "90e555112e78f389af0cdffcea02fefb6f537128", "type": "github" }, "original": { From de343e70e113f32460ed48ebf50e914d853b3b07 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 19:54:48 +0900 Subject: [PATCH 5/5] ci: qualify release-branch candidates outside the master queue Keep affected PR checks and a bounded combined-tree integration gate in the master queue. Move heavy backend/platform/conformance validation to release candidates and the daily/manual cadence, rather than rerunning it on each speculative queue tree or every master push. Release Please updates version PRs on master but cannot create releases. After a version PR merges, a dedicated staging workflow advances release to that exact merge commit without force-pushing. Staging has no concurrency group, so other PR closures and master pushes cannot discard its pending one-shot event. Release Candidate runs full CI on that fixed SHA. Only successful qualification can create the stable tag and GitHub Release and dispatch package publication. Reject superseded candidates, unrelated commits and existing tags at a different SHA. Retry publication only for the same qualified source. Both stable publishers require a successful Release Candidate run on release at their exact build SHA, including manual retries. They wait for the parent workflow to finish instead of duplicating full validation. Recovery commits can use validation_only on release before numbered recovery-tag publication. Nightly and independent Aplite publication retain their existing policies. After this change lands, run node scripts/configure-merge-checks.mjs --apply to replace deferred platform requirements with Queue validation on master. The dry-run-by-default migration preserves other checks and enforcement and refuses to apply before the replacement workflows exist on master. The release branch has been bootstrapped from master; no release has been published. Validation: 327 Node script tests; workflow syntax with actionlint (excluding its existing ubuntu-26.04-arm/cache-mode schema gaps); pnpm lint; diff checks. The unchanged queue command previously passed 260 tests (8 existing skips), and default workspace cargo check passed. Actual multi-platform qualification and publication require GitHub Actions after deployment. Change-Id: Ic5bb694d5d17ce58a1dd1cfc97a04c8777881dcb --- .github/workflows/ci-napi.yml | 23 ++- .github/workflows/ci.yml | 177 ++++++++++++----- .github/workflows/publish-crates.yml | 20 +- .github/workflows/release-candidate.yml | 83 ++++++++ .github/workflows/release.yml | 42 +--- .github/workflows/stage-release-candidate.yml | 47 +++++ CONTRIBUTING.md | 83 ++++++-- scripts/check-release-qualification.mjs | 28 +++ scripts/check-release-qualification.test.mjs | 21 ++ scripts/ci-changes.mjs | 29 +-- scripts/ci-changes.test.mjs | 71 ++----- scripts/ci-workflow.test.mjs | 34 ++-- scripts/configure-merge-checks.mjs | 57 ++++++ scripts/configure-merge-checks.test.mjs | 32 +++ scripts/promote-release-candidate.mjs | 54 ++++++ scripts/release-pr-update.test.mjs | 4 +- scripts/release-publication.test.mjs | 183 ++++++------------ scripts/release-validation.test.mjs | 100 ++++++++++ 18 files changed, 757 insertions(+), 331 deletions(-) create mode 100644 .github/workflows/release-candidate.yml create mode 100644 .github/workflows/stage-release-candidate.yml create mode 100644 scripts/check-release-qualification.mjs create mode 100644 scripts/check-release-qualification.test.mjs create mode 100644 scripts/configure-merge-checks.mjs create mode 100644 scripts/configure-merge-checks.test.mjs create mode 100644 scripts/promote-release-candidate.mjs create mode 100644 scripts/release-validation.test.mjs diff --git a/.github/workflows/ci-napi.yml b/.github/workflows/ci-napi.yml index 76645afad97..8200ecb90d1 100644 --- a/.github/workflows/ci-napi.yml +++ b/.github/workflows/ci-napi.yml @@ -133,6 +133,25 @@ jobs: if: env.NIGHTLY != 'true' run: node scripts/check-release-version.mjs + qualify: + name: Verify release branch qualification + needs: validate-release + if: ${{ !startsWith(inputs.channel, 'nightly-') }} + runs-on: ubuntu-latest + timeout-minutes: 12 + permissions: + contents: read + actions: read + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ needs.validate-release.outputs.build_sha }} + - name: Require the successful candidate run + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_SHA: ${{ needs.validate-release.outputs.build_sha }} + run: node scripts/check-release-qualification.mjs + build: needs: validate-release cache-mode: write @@ -281,7 +300,8 @@ jobs: run: pnpm --filter="!@celox-sim/celox-napi" --filter="!@celox-sim/playground" -r test publish: - needs: [validate-release, test] + needs: [validate-release, test, qualify] + if: ${{ !cancelled() && needs.validate-release.result == 'success' && needs.test.result == 'success' && (needs.qualify.result == 'success' || (startsWith(inputs.channel, 'nightly-') && needs.qualify.result == 'skipped')) }} runs-on: ubuntu-latest name: Publish environment: npm @@ -318,6 +338,7 @@ jobs: - name: Download all artifacts uses: actions/download-artifact@v8 with: + pattern: bindings-* path: crates/celox-napi/artifacts - name: Create npm dirs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8fce6137741..5bfe3952428 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,7 @@ name: CI # Ordinary PRs run focused checks; queue draft PRs run pre-merge validation. -# Keep merge_group during migration and rollback; landed pushes need no rerun. +# Heavy validation runs on release candidates and at the scheduled cadence. on: pull_request: merge_group: @@ -9,11 +9,17 @@ on: schedule: - cron: "17 1 * * *" workflow_dispatch: + workflow_call: + inputs: + validation_ref: + description: Immutable publication source SHA + required: true + type: string concurrency: # A new push must not cancel the daily full run halfway through its corpus. - group: ${{ github.workflow }}-${{ github.ref }}-${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && 'full' || 'changes' }} - cancel-in-progress: ${{ github.event_name != 'schedule' && github.event_name != 'workflow_dispatch' }} + group: ${{ github.workflow }}-${{ inputs.validation_ref || github.ref }}-${{ (inputs.validation_ref != '' || github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && 'full' || 'changes' }} + cancel-in-progress: ${{ inputs.validation_ref == '' && github.event_name != 'push' && github.event_name != 'schedule' && github.event_name != 'workflow_dispatch' }} env: CARGO_INCREMENTAL: "0" @@ -29,8 +35,9 @@ jobs: STABLE_LANE: ${{ github.ref_name == 'master' || github.base_ref == 'master' || (github.event_name == 'merge_group' && github.event.merge_group.base_ref == 'refs/heads/master') }} outputs: queue: ${{ steps.classify.outputs.queue }} + full_validation: ${{ steps.classify.outputs.full_validation }} + fast_queue: ${{ steps.classify.outputs.fast_queue }} docs: ${{ steps.classify.outputs.docs }} - release: ${{ steps.classify.outputs.release }} javascript: ${{ steps.classify.outputs.javascript }} napi: ${{ steps.classify.outputs.napi }} napi_arm64: ${{ steps.classify.outputs.napi_arm64 }} @@ -52,8 +59,15 @@ jobs: rust_library_features: ${{ steps.classify.outputs.rust_library_features }} scripts: ${{ steps.classify.outputs.scripts }} steps: + - name: Validate qualification revision + if: inputs.validation_ref != '' + env: + VALIDATION_REF: ${{ inputs.validation_ref }} + run: '[[ "$VALIDATION_REF" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} fetch-depth: 0 - name: Classify changed files @@ -61,8 +75,7 @@ jobs: env: BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }} - FULL_VALIDATION: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} - MERGE_GROUP_BASE_REF: ${{ github.event.merge_group.base_ref || format('refs/heads/{0}', github.base_ref) }} + FULL_VALIDATION: ${{ contains(github.event.pull_request.labels.*.name, 'ci:full') || inputs.validation_ref != '' || github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} RELEASE_PLEASE_PR: ${{ github.event_name == 'pull_request' && github.head_ref == 'release-please--branches--master--components--celox' && github.event.pull_request.head.repo.full_name == github.repository }} QUEUE_VALIDATION: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'mergify/merge-queue/') || contains(github.event.pull_request.labels.*.name, 'ci:full') }} # Keep the classifier usable before the pinned toolchain is installed. @@ -80,6 +93,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + ref: ${{ inputs.validation_ref || github.sha }} - uses: pnpm/action-setup@v6 @@ -104,6 +119,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - name: Install Nix @@ -148,24 +164,24 @@ jobs: fi - name: cargo clippy - if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' + if: needs.changes.outputs.fast_queue != 'true' && ((needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false') run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim --no-deps - name: Lint the crates this pull request can affect - if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '') env: BUILDS: ${{ needs.changes.outputs.rust_lint_builds }} run: | node scripts/run-ci-rust-scope.mjs lint - name: Build Rust API documentation - if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' + if: needs.changes.outputs.fast_queue != 'true' && ((needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false') env: RUSTDOCFLAGS: -D warnings run: cargo doc --locked --workspace --exclude lydite-celox --no-deps - name: Build the API documentation this pull request can affect - if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_doc_libraries != '' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_doc_libraries != '') env: RUSTDOCFLAGS: -D warnings LIBRARIES: ${{ needs.changes.outputs.rust_doc_libraries }} @@ -206,6 +222,11 @@ jobs: if: needs.changes.result == 'success' && needs.changes.outputs.rust == 'true' && needs.changes.outputs.scripts != 'true' run: node --test scripts/ci-changes.test.mjs scripts/ci-rust-scope.test.mjs scripts/ci-lydite-changes.test.mjs + - name: Check default workspace integration + if: needs.changes.outputs.fast_queue == 'true' && needs.changes.outputs.rust == 'true' + timeout-minutes: 20 + run: cargo check --locked --workspace --exclude 'lydite*' + rust-tests: name: Rust Tests needs: changes @@ -217,6 +238,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -230,12 +252,12 @@ jobs: run: node scripts/ci-rust-reports.mjs reset - uses: actions/setup-python@v7 - if: needs.changes.outputs.rust_vpi_e2e != 'false' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_vpi_e2e != 'false') with: python-version: "3.14" - name: Install cocotb - if: needs.changes.outputs.rust_vpi_e2e != 'false' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_vpi_e2e != 'false') run: python -m pip install cocotb==2.1.0 - name: Install cargo-nextest @@ -244,7 +266,7 @@ jobs: tool: cargo-nextest@0.9.144 - name: Build the optimized vtest executor - if: needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox ') + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox ')) run: node scripts/run-vtest.mjs --prepare-ci # Enable the frontend and suite features together so common integration @@ -252,31 +274,40 @@ jobs: # nextest schedules tests from all binaries on one pool; `cargo test` # runs the binaries one after another. # A pull request builds and runs only the tests its changes can affect - # (scripts/ci-rust-scope.mjs); merge groups and the daily run keep the + # (scripts/ci-rust-scope.mjs); post-merge and release validation keep the # Celox workspace. lydite-checks.yml owns Lydite tests at its own cadence. - name: Run workspace tests with CI features id: workspace-tests - if: needs.changes.outputs.rust_full != 'false' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full != 'false') run: >- cargo nextest run --locked --workspace --exclude 'lydite*' --profile ci --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases - name: Run the tests this pull request can affect id: scoped-tests - if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '') env: BUILDS: ${{ needs.changes.outputs.rust_builds }} FILTER: ${{ needs.changes.outputs.rust_filter }} run: | node scripts/run-ci-rust-scope.mjs test + - name: Run merge queue integration tests + id: queue-tests + if: needs.changes.outputs.fast_queue == 'true' + timeout-minutes: 20 + run: >- + cargo nextest run --locked -p celox --features systemverilog --profile ci + --test counter --test hierarchy --test native_exec + --test simulation_limits --test sv_unit_scope --test sv_packages + - name: Collect Rust test reports if: success() || failure() run: node scripts/ci-rust-reports.mjs collect - name: Run cocotb VPI end-to-end test id: cocotb-tests - if: needs.changes.outputs.rust_vpi_e2e != 'false' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_vpi_e2e != 'false') env: RUST_FULL: ${{ needs.changes.outputs.rust_full }} BUILDS: ${{ needs.changes.outputs.rust_builds }} @@ -298,17 +329,17 @@ jobs: token: ${{ secrets.MERGIFY_TOKEN }} report_path: work/ci-reports/rust/*.xml job_name: rust-tests - test_step_outcome: ${{ steps.cocotb-tests.outcome == 'failure' && 'failure' || steps.workspace-tests.outcome != 'skipped' && steps.workspace-tests.outcome || steps.scoped-tests.outcome }} + test_step_outcome: ${{ steps.queue-tests.outcome != 'skipped' && steps.queue-tests.outcome || steps.cocotb-tests.outcome == 'failure' && 'failure' || steps.workspace-tests.outcome != 'skipped' && steps.workspace-tests.outcome || steps.scoped-tests.outcome }} # nextest does not run documentation tests. - name: Run workspace documentation tests with CI features - if: needs.changes.outputs.rust_full != 'false' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full != 'false') run: >- cargo test --locked --workspace --exclude 'lydite*' --doc --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases - name: Run the documentation tests of the changed libraries - if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_libraries != '' + if: needs.changes.outputs.fast_queue != 'true' && (needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_libraries != '') env: LIBRARIES: ${{ needs.changes.outputs.rust_libraries }} FEATURES: ${{ needs.changes.outputs.rust_library_features }} @@ -317,15 +348,15 @@ jobs: for package in $LIBRARIES; do args+=(-p "$package"); done if [ -n "$FEATURES" ]; then args+=(--features "$FEATURES"); fi cargo test --locked --doc "${args[@]}" - rust-default-tests: name: Rust default-feature tests needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && (needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_libraries), ' celox ')))) }} + if: ${{ !cancelled() && needs.changes.outputs.fast_queue != 'true' && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && (needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_libraries), ' celox ')))) }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust - uses: Swatinem/rust-cache@v2 @@ -339,9 +370,8 @@ jobs: external-suites: name: External suite (${{ matrix.suite }}, ${{ matrix.tool }}) needs: changes - # Scheduled and manual runs compare even when change detection fails. A - # merge group that cuts a release also compares before it can merge. - if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || needs.changes.outputs.release == 'true') }} + # External comparisons belong to full validation, never the merge queue. + if: ${{ !cancelled() && needs.changes.outputs.full_validation == 'true' }} runs-on: ubuntu-latest timeout-minutes: 90 strategy: @@ -359,6 +389,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive # Use the same locked tool versions as the retained exclusion evidence. @@ -438,11 +469,14 @@ jobs: common-cells: name: Upstream SystemVerilog testbench - if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }} + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.full_validation == 'true' }} runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@v7 + with: + ref: ${{ inputs.validation_ref || github.sha }} - uses: ./.github/actions/setup-rust @@ -482,11 +516,13 @@ jobs: sv-tests: name: sv-tests conformance needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && needs.changes.outputs.rust_sv_tests != 'false')) }} + if: ${{ !cancelled() && needs.changes.outputs.fast_queue != 'true' && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && needs.changes.outputs.rust_sv_tests != 'false')) }} runs-on: ubuntu-latest timeout-minutes: 60 steps: - uses: actions/checkout@v7 + with: + ref: ${{ inputs.validation_ref || github.sha }} - uses: ./.github/actions/setup-rust @@ -569,6 +605,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -607,11 +644,12 @@ jobs: napi-wasm: name: NAPI WASM Build & Test needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.napi == 'true') }} + if: ${{ !cancelled() && needs.changes.outputs.fast_queue != 'true' && (needs.changes.result != 'success' || needs.changes.outputs.napi == 'true') }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -670,19 +708,19 @@ jobs: CHANGES_RESULT: ${{ needs.changes.result }} RUST_REQUIRED: ${{ needs.changes.outputs.rust }} RUST_RESULT: ${{ needs.rust-tests.result }} - DEFAULT_REQUIRED: ${{ needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && (needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_libraries), ' celox '))) }} + DEFAULT_REQUIRED: ${{ needs.changes.outputs.fast_queue != 'true' && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && (needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_libraries), ' celox ')))) }} DEFAULT_RESULT: ${{ needs.rust-default-tests.result }} - SV_TESTS_REQUIRED: ${{ needs.changes.outputs.rust != 'false' && needs.changes.outputs.rust_sv_tests != 'false' }} + SV_TESTS_REQUIRED: ${{ needs.changes.outputs.fast_queue != 'true' && needs.changes.outputs.rust != 'false' && needs.changes.outputs.rust_sv_tests != 'false' }} SV_TESTS_RESULT: ${{ needs.sv-tests.result }} - # Platform coverage is mandatory in queue and full validation runs. - ARM64_REQUIRED: ${{ needs.changes.outputs.queue != 'false' && needs.changes.outputs.rust != 'false' }} + # Platform coverage is mandatory in full validation, outside the queue. + ARM64_REQUIRED: ${{ needs.changes.outputs.full_validation != 'false' && needs.changes.outputs.rust != 'false' }} ARM64_RESULT: ${{ needs.arm64-backend.result }} NAPI_REQUIRED: ${{ needs.changes.outputs.napi }} NATIVE_RESULT: ${{ needs.napi-linux.result }} + WASM_REQUIRED: ${{ needs.changes.outputs.fast_queue != 'true' && needs.changes.outputs.napi != 'false' }} WASM_RESULT: ${{ needs.napi-wasm.result }} - # Only a release merge group gates on the comparisons. Full runs report - # them through report-full-validation instead. - RELEASE_REQUIRED: ${{ needs.changes.outputs.release }} + # Every full run requires external comparisons as well as Celox tests. + RELEASE_REQUIRED: ${{ needs.changes.outputs.full_validation }} EXTERNAL_RESULT: ${{ needs.external-suites.result }} steps: - name: Check tests and builds @@ -703,7 +741,7 @@ jobs: if [ "$NAPI_REQUIRED" != false ] || [ "$NATIVE_RESULT" != skipped ]; then test "$NATIVE_RESULT" = success fi - if [ "$NAPI_REQUIRED" != false ] || [ "$WASM_RESULT" != skipped ]; then + if [ "$WASM_REQUIRED" != false ] || [ "$WASM_RESULT" != skipped ]; then test "$WASM_RESULT" = success fi if [ "$RELEASE_REQUIRED" != false ]; then @@ -713,12 +751,13 @@ jobs: arm64-backend: name: ARM64 Backend Test needs: changes - # Full platform checks run once in the queue, not on every PR push. - if: ${{ !cancelled() && needs.changes.outputs.queue != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') }} + # Full platform checks run after landing and before publication. + if: ${{ !cancelled() && needs.changes.outputs.full_validation != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') }} runs-on: ubuntu-26.04-arm steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -758,11 +797,12 @@ jobs: napi-windows: name: NAPI Build (Windows) needs: changes - if: ${{ !cancelled() && needs.changes.outputs.queue != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.napi == 'true') }} + if: ${{ !cancelled() && needs.changes.outputs.full_validation != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.napi == 'true') }} runs-on: windows-latest steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -796,11 +836,12 @@ jobs: napi-linux-arm64: name: NAPI Build (Linux ARM64 GNU) needs: changes - if: ${{ !cancelled() && needs.changes.outputs.queue != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.napi_arm64 == 'true') }} + if: ${{ !cancelled() && needs.changes.outputs.full_validation != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.napi_arm64 == 'true') }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: ./.github/actions/setup-rust @@ -844,6 +885,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: pnpm/action-setup@v6 @@ -885,11 +927,12 @@ jobs: js-windows: name: JS Test (Windows) needs: [changes, napi-windows] - if: ${{ !cancelled() && needs.changes.outputs.queue != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true') }} + if: ${{ !cancelled() && needs.changes.outputs.full_validation != 'false' && (needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true') }} runs-on: windows-latest steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: pnpm/action-setup@v6 @@ -917,12 +960,13 @@ jobs: playground-browser: name: Playground Browser Test needs: [changes, napi-wasm] - if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' || needs.changes.outputs.napi == 'true') }} + if: ${{ !cancelled() && needs.changes.outputs.fast_queue != 'true' && (needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' || needs.changes.outputs.napi == 'true') }} runs-on: ubuntu-latest timeout-minutes: 15 steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} submodules: recursive - uses: pnpm/action-setup@v6 @@ -974,11 +1018,11 @@ jobs: docs: changed.docs === "true", lint: [changed.rust, changed.javascript, changed.scripts].includes("true"), rust: [changed.rust, changed.napi].includes("true"), - "napi-windows": changed.napi === "true", - "napi-linux-arm64": changed.napi_arm64 === "true", + "napi-windows": changed.full_validation === "true" && changed.napi === "true", + "napi-linux-arm64": changed.full_validation === "true" && changed.napi_arm64 === "true", "js-ubuntu": changed.javascript === "true", - "js-windows": changed.javascript === "true", - "playground-browser": [changed.napi, changed.javascript].includes("true"), + "js-windows": changed.full_validation === "true" && changed.javascript === "true", + "playground-browser": changed.fast_queue !== "true" && [changed.napi, changed.javascript].includes("true"), }; if (Object.entries(required).some(([name, required]) => required && jobs[name].result !== "success") || jobs.changes.result !== "success" || jobs.changes.outputs.queue !== "true" || @@ -987,12 +1031,48 @@ jobs: } ' - # Report daily/manual runs independently of merge queue validation. + # Fail closed: skipped full coverage cannot qualify a release. + full-validation: + name: Release qualification + needs: + [ + changes, + queue-validation, + docs, + lint, + rust-tests, + rust-default-tests, + sv-tests, + external-suites, + common-cells, + napi-linux, + napi-wasm, + rust, + arm64-backend, + napi-windows, + napi-linux-arm64, + js-ubuntu, + js-windows, + playground-browser, + ] + if: ${{ always() && needs.changes.outputs.full_validation == 'true' }} + runs-on: ubuntu-latest + env: + NEEDS: ${{ toJSON(needs) }} + steps: + - name: Require every full-validation job + run: | + node --input-type=module -e ' + const jobs = JSON.parse(process.env.NEEDS); + if (Object.values(jobs).some(job => job.result !== "success")) process.exit(1); + ' + report-full-validation: name: Report full validation needs: [ changes, + full-validation, queue-validation, docs, lint, @@ -1011,7 +1091,7 @@ jobs: js-windows, playground-browser, ] - if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && (github.ref_name == 'master' || github.ref_name == 'develop') }} + if: ${{ !cancelled() && inputs.validation_ref == '' && (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && (github.ref_name == 'master' || github.ref_name == 'develop') }} runs-on: ubuntu-latest permissions: contents: read @@ -1019,6 +1099,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + ref: ${{ inputs.validation_ref || github.sha }} sparse-checkout: scripts - name: Open, update, or close the full CI issue diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index 1854ecf87d2..54b0e53e36d 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -76,6 +76,24 @@ jobs: - name: Check synchronized release versions run: node scripts/check-release-version.mjs + qualify: + name: Verify release branch qualification + needs: validate + runs-on: ubuntu-latest + timeout-minutes: 12 + permissions: + contents: read + actions: read + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + - name: Require the successful candidate run + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_SHA: ${{ github.sha }} + run: node scripts/check-release-qualification.mjs + package: name: Package and test needs: validate @@ -111,7 +129,7 @@ jobs: publish: name: Publish to crates.io - needs: [validate, package] + needs: [validate, package, qualify] runs-on: ubuntu-latest environment: crates-io permissions: diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml new file mode 100644 index 00000000000..fe577c580a0 --- /dev/null +++ b/.github/workflows/release-candidate.yml @@ -0,0 +1,83 @@ +name: Release Candidate + +on: + push: + branches: [release] + workflow_dispatch: + inputs: + validation_only: + description: Qualify a recovery SHA without creating a stable release + type: boolean + default: false + +# A newer RC must not cancel qualification of a running candidate. +concurrency: + group: release-candidate + cancel-in-progress: false + +permissions: + contents: read + +jobs: + candidate: + name: Resolve release candidate + if: github.ref == 'refs/heads/release' + runs-on: ubuntu-latest + outputs: + sha: ${{ steps.candidate.outputs.sha }} + tag: ${{ steps.candidate.outputs.tag }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + - name: Validate candidate identity + id: candidate + run: | + git merge-base --is-ancestor HEAD origin/master + node scripts/check-release-version.mjs + tag="v$(tr -d '\r\n' < VERSION)" + [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + + qualify: + name: Qualify release candidate + needs: candidate + uses: ./.github/workflows/ci.yml + permissions: + contents: read + issues: write + with: + validation_ref: ${{ needs.candidate.outputs.sha }} + secrets: inherit + + publish: + name: Promote qualified candidate + if: inputs.validation_only != true + needs: [candidate, qualify] + runs-on: ubuntu-latest + steps: + - name: Create release app token + id: release-token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-pull-requests: write + permission-issues: write + permission-actions: write + permission-contents: write + permission-workflows: write + + - uses: actions/checkout@v7 + with: + ref: ${{ needs.candidate.outputs.sha }} + fetch-depth: 0 + + - name: Publish the qualified candidate + env: + GH_TOKEN: ${{ steps.release-token.outputs.token }} + CANDIDATE_SHA: ${{ needs.candidate.outputs.sha }} + RELEASE_TAG: ${{ needs.candidate.outputs.tag }} + run: node scripts/promote-release-candidate.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eb1f128ed34..5452365a188 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -59,48 +59,10 @@ jobs: token: ${{ steps.release-token.outputs.token }} config-file: release-please-config.json manifest-file: .release-please-manifest.json - # Keep tag/Release creation active when a frozen PR has merged. + # Version PRs land on master; only the release branch publishes. + skip-github-release: true skip-github-pull-request: ${{ steps.release-pr.outputs.frozen == 'true' }} - # A merge queue can push several merged PRs together. The release tag - # then points at an earlier commit than github.sha. Publish the tag that - # release-please actually created, including on scheduled/manual runs. - - name: Queue package publication for this release - if: steps.release.outputs.release_created == 'true' - env: - GH_TOKEN: ${{ steps.release-token.outputs.token }} - RELEASE_TAG: ${{ steps.release.outputs.tag_name }} - shell: bash - run: | - release_tag="$RELEASE_TAG" - if [[ ! "$release_tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "Expected a v-prefixed stable release tag, got $release_tag." >&2 - exit 1 - fi - - published_tag="$( - gh release view "$release_tag" \ - --repo "$GITHUB_REPOSITORY" \ - --json tagName,isDraft,isPrerelease \ - --jq 'select(.isDraft == false and .isPrerelease == false) | .tagName' - )" - if [ "$published_tag" != "$release_tag" ]; then - echo "Published GitHub Release $release_tag was not found." >&2 - exit 1 - fi - - jq -n \ - --arg tag "$release_tag" \ - '{event_type: "napi-release", client_payload: {tag: $tag}}' \ - | gh api \ - --method POST \ - "repos/$GITHUB_REPOSITORY/dispatches" \ - --input - - - gh workflow run publish-crates.yml \ - --repo "$GITHUB_REPOSITORY" \ - --ref "$release_tag" - queue-release: name: Queue weekly release needs: release-please diff --git a/.github/workflows/stage-release-candidate.yml b/.github/workflows/stage-release-candidate.yml new file mode 100644 index 00000000000..f54b65074a2 --- /dev/null +++ b/.github/workflows/stage-release-candidate.yml @@ -0,0 +1,47 @@ +name: Stage Release Candidate + +on: + pull_request: + types: [closed] + branches: [master] + +# Each merged release PR must reach staging. Do not put these one-shot events +# in a concurrency group: even cancel-in-progress: false replaces pending runs. +# The non-force push below prevents an older event from rewinding release. +permissions: {} + +jobs: + stage-candidate: + name: Stage release candidate + if: >- + github.event_name == 'pull_request' && github.event.pull_request.merged == true && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.head.ref == 'release-please--branches--master--components--celox' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Create release app token + id: release-token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + permission-workflows: write + + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.merge_commit_sha }} + fetch-depth: 0 + token: ${{ steps.release-token.outputs.token }} + + - name: Advance release to the merged candidate + env: + CANDIDATE_SHA: ${{ github.event.pull_request.merge_commit_sha }} + run: | + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + node scripts/check-release-version.mjs + # No force push: release contains only successive master candidates. + git push origin "$CANDIDATE_SHA:refs/heads/release" + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index def9181d534..999956839cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -89,7 +89,8 @@ CI keeps the normal test profile and existing dependency cache: sharing a Cargo profile alone does not share artifacts when the executor and workspace resolve different dependency features. Ordinary Cargo test commands retain the embedded, in-process path. CI's Rust Tests job prepares the executor once and uses it for -full workspace runs and scoped runs that include Celox. Scopes without Celox +full workspace runs and scoped PR runs that include Celox. The merge queue +runs a small integration set directly, without building the all-backend executor. Scopes without Celox skip that build. The default-branch cache warmer builds both executor and test dependencies under the same cache key; preparation failures fail the test job. Cocotb runs through nextest with the exact packages, features and targets of its @@ -140,7 +141,7 @@ Daily CI uses `--fresh` and runs the complete corpus afresh. ## Compilation scaling in CodSpeed -Normal PR and merge-queue CI retains small nested-write semantic regressions on +Affected PR and full CI retain small nested-write semantic regressions on interpreter, native and Cranelift backends in both two-state and four-state modes, wide-value latch checks, and a small sorter compilation smoke test. The 257/512-bit per-bit graph cases and sorter sizes 4/8/16/32 are measured by @@ -223,9 +224,8 @@ mixed Rust changes and unknown paths retain their existing coverage. Pull requests use `scripts/ci-changes.mjs` to select jobs and scope Rust tests -by affected crates. Windows and ARM64 checks run in Mergify queue draft PRs, -legacy merge groups, and daily/manual full runs. Queue drafts run the full Celox Rust -workspace when Rust is affected. Mergify checks up to five batches concurrently +by affected crates. Windows and ARM64 checks run during release/daily/manual full validation. Queue drafts and legacy merge groups +use the bounded integration checks described below. Mergify checks up to five batches concurrently across three queue rules. Parallel mode separates independent file scopes while retaining combined-tree validation for overlapping scopes: @@ -273,13 +273,17 @@ marker chain, so a stack branch without it is still refused. Lydite tests use the independent change-selected and daily cadence described below, including on Mergify queue draft PRs. The `Queue validation` merge condition requires the selected checks in `ci.yml` to pass; -ordinary PR checks cannot satisfy it. The `ci:full` label opts a PR into the -same coverage on its next push. Unrelated paths may still skip jobs. +ordinary PR checks cannot satisfy it. The queue checks the combined tree with +format/script checks, default workspace compilation, a bounded native/SV test +set, and affected Linux NAPI/JS integration. It does not rerun the complete +backend matrix, sv-tests, default-feature/doctests, WASI/browser, Windows, +ARM64 or external simulator comparisons. The `ci:full` label opts a PR into +full coverage on its next push. Unrelated paths may still skip queue jobs. - Enable both Merge Queue and Workflow Automation in Mergify; the latter runs the label-based queue rule. -- Version-only Release Please PRs defer product tests to the queue, where the - release manifest change requires full validation including external suites. +- Version-only Release Please PRs use the same lightweight queue. Their merged SHA advances `release`; full product + qualification there gates all release publication instead. - Add `merge-ready` to request automatic queueing, or comment `@mergifyio queue` for an ordinary PR. A failed queue entry receives `dequeued`; investigate it, remove that label, and request queueing again. There is no automatic retry loop. @@ -299,8 +303,9 @@ same coverage on its next push. Unrelated paths may still skip jobs. validates the combined tree instead of updating every original PR. Required status checks remain enabled. Keep the `Queue validation` merge condition. - `merge_group` remains supported for rollback to GitHub's native queue. -- The queue validates the tree before it lands, so pushes to `master` and - `develop` do not run CI again. Daily full runs keep those branches' caches warm. +- Ordinary master pushes do not launch another full matrix. Heavy validation + runs on `release` candidates and at the daily/manual cadence, so ordinary + development does not continuously compete with the queue for those runners. - `sync-develop.yml` opens or updates the master-to-develop synchronization pull request once a day (22:07 UTC) rather than on every master push. Dispatch it to sync sooner. @@ -387,25 +392,26 @@ Ordinary PRs also scope Rust compilation and execution: and downstream consumers do not select this separate release-mode build. - Python/cocotb setup runs only when VPI tests are selected. -Queue drafts, merge groups, releases, `ci:full`, and daily/manual full runs -retain the existing workspace tests, lint, documentation, sv-tests and platform -coverage. Cargo manifest, lockfile, toolchain, unknown-path and failed scope -analysis changes fall back to broad validation. Required checks permit skips +Release qualification, `ci:full` and daily/manual full runs +retain workspace tests, lint, documentation, sv-tests and platform coverage. +On ordinary PRs, Cargo manifest, lockfile, toolchain, unknown-path and failed +scope analysis changes fall back to broad validation. Queue drafts keep their +bounded integration set even for these changes. Required checks permit skips only when explicitly unneeded and still reject failures and cancellations. Local validation uses the behavior-based matrix above. | Cadence | Coverage | | --- | --- | +| On a candidate push to `release` | Full CI on the fixed candidate SHA, followed by stable tag/GitHub Release creation and package dispatch only after success. Stable publishers verify this successful branch run, including manual retries and recovery tags. | | Daily at 01:17 UTC (10:17 JST) | Full `ci.yml` on the default branch, with every change-classifier output enabled. Includes native/WASI NAPI, JS/browser tests, ARM64, script tests, and all ordinary Celox workspace tests. | | Daily from `nightly.yml` at 02:43 UTC (11:43 JST) | Dispatch the same full CI on `develop`, with detection of its Veryl dependency lane. Queue nightly packages and the small pinned/HEAD Heliodor Linux boot compatibility checks. | | Daily at 01:47 UTC (10:47 JST) | `bench.yml` measures Rust, Verilator, and TypeScript on one host and publishes master history. Manual dispatch supports branch measurements. | | Daily at 02:17 UTC (11:17 JST) | `codspeed.yml` measures compile time on the default branch using CPU simulation. Execution failures and CodSpeed performance-check failures open or update a branch issue; the next healthy run closes it. Manual dispatch supports branch measurements. PRs, merge groups, and pushes do not run CodSpeed. | | Daily at 02:37 UTC (11:37 JST) | `heliodor-bench.yml` runs the complete master Linux suite on x86-64 and AArch64. Explicit manual selections retain focused suite runs and ARM64 profiling. PRs do not run this workflow; its tooling tests run in `Lint & Format` with the other script tests. | -| Every daily/manual full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | +| Every full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | | Every full CI run | Run every shared Veryl and SystemVerilog case against both Verilator and Icarus, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | | Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs. Bridge gates are disabled; daily and manual runs enable only core lanes and report failures in an issue. | | On demand | Dispatch `ci.yml` on the desired branch to run full CI and external comparisons, regardless of its diff. | -| Pull requests that cut a release | A `master` pull request or legacy merge group whose diff changes `.release-please-manifest.json` (only the release pull request does there; syncing it into `develop` is not a release) runs full CI and the external comparisons. `Rust Test & NAPI Build` then requires the comparisons to pass, so a release cannot merge after only change-based checks. Daily and manual full runs do not gate on the comparisons; their failures reach the full CI issue below. A `master` pull request or legacy merge group whose diff cannot be determined is treated the same way. | Full runs have a separate concurrency group so ordinary pushes cannot cancel them. Scheduled and dispatched full runs on `master` and `develop` end with @@ -422,6 +428,49 @@ endings, including checkout-dependent Verilator padding; wording and source locations must match. Improvements may pass without updating the baseline. Baseline changes require review rather than automatic acceptance of a new run. +Release Please on `master` only updates the version PR; it cannot create tags +or GitHub releases. A dedicated `stage-release-candidate.yml` handles each +merged version PR without a concurrency group, so master pushes and other PR +closures cannot replace a pending staging event. The release App advances the `release` +branch to its exact merge commit without force-pushing. The App-authenticated +push starts `release-candidate.yml` on that branch, independently of the master +queue. The branch is a sequence of master release candidates, not a development +branch. A normal master merge never advances it. + +The candidate workflow passes its fixed SHA to full CI. All checkouts use that +SHA, and all required jobs must succeed. Only then may the promotion job create +the stable tag and GitHub Release, followed by package publication dispatches. +Promotion rejects superseded candidates, candidates that are not merged release +PRs, and tags pointing at a different SHA. Retrying an existing release is +allowed only for the same qualified SHA. Release notes come from GitHub's +release-note generator; the version PR still updates the checked-in changelog. + +Both stable publishers verify that `release-candidate.yml` succeeded on the +`release` branch at their exact build SHA. They wait briefly for the dispatching +candidate workflow to finish, rather than rerunning the full suite. A failed, +cancelled, skipped, unrelated-branch or different-SHA run cannot authorize +publication. npm downloads only `bindings-*` release artifacts. Nightly and +independent Aplite publication retain their existing policies. + +For a numbered crate recovery tag, advance `release` to the recovery commit +(which must be on master), then dispatch Release Candidate on `release` with +`validation_only=true`. This runs full qualification without creating or moving +a stable tag. Publish the numbered recovery tag only after that run succeeds. + +After this workflow change lands on `master`, migrate its GitHub ruleset: + +```sh +node scripts/configure-merge-checks.mjs # inspect the proposed ruleset +node scripts/configure-merge-checks.mjs --apply # requires repository administration access +``` + +The migration removes the Windows NAPI, Windows JS and ARM64 NAPI required +checks and adds `Queue validation`. It preserves the other checks, enforcement, +branch conditions and bypass policy. It refuses to apply before the queue and +publisher changes exist on `master`. Mergify still requires a genuinely +successful `Queue validation`; it does not receive a bypass. Before this +migration, the old platform requirements can still impede queue admission. + Scheduled workflows begin using this configuration after it reaches the default branch; the develop dispatch also requires the updated `ci.yml` on `develop`. diff --git a/scripts/check-release-qualification.mjs b/scripts/check-release-qualification.mjs new file mode 100644 index 00000000000..603b750597c --- /dev/null +++ b/scripts/check-release-qualification.mjs @@ -0,0 +1,28 @@ +import { execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export function qualificationState(runs, sha) { + const candidates = runs.filter(run => run.head_sha === sha && run.head_branch === "release" && ["push", "workflow_dispatch"].includes(run.event)); + if (candidates.some(run => run.status === "completed" && run.conclusion === "success")) return "success"; + if (candidates.some(run => ["queued", "in_progress", "waiting", "pending", "requested"].includes(run.status))) return "pending"; + return "missing"; +} + +export async function requireQualification({ sha, runs, now = Date.now, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), timeout = 600_000 }) { + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error("Expected an immutable release SHA"); + const deadline = now() + timeout; + for (;;) { + const state = qualificationState(await runs(), sha); + if (state === "success") return; + if (state !== "pending") throw new Error("No successful Release Candidate run for this release SHA"); + if (now() >= deadline) throw new Error("Release Candidate workflow did not finish successfully before the deadline"); + await sleep(10_000); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const repository = process.env.GITHUB_REPOSITORY; + const sha = process.env.CANDIDATE_SHA; + if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) throw new Error("Invalid repository"); + await requireQualification({ sha, runs: () => JSON.parse(execFileSync("gh", ["api", `repos/${repository}/actions/workflows/release-candidate.yml/runs?head_sha=${sha}&branch=release&per_page=100`], { encoding: "utf8" })).workflow_runs }); +} diff --git a/scripts/check-release-qualification.test.mjs b/scripts/check-release-qualification.test.mjs new file mode 100644 index 00000000000..ff2a1f6e4f6 --- /dev/null +++ b/scripts/check-release-qualification.test.mjs @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { qualificationState, requireQualification } from "./check-release-qualification.mjs"; +const sha = "a".repeat(40); +const good = { head_sha: sha, head_branch: "release", event: "push", status: "completed", conclusion: "success" }; +test("only a successful release-branch run at the exact SHA authorizes publication", () => { + assert.equal(qualificationState([good], sha), "success"); + for (const changes of [{ head_sha: "b".repeat(40) }, { head_branch: "master" }, { event: "pull_request" }, { conclusion: "failure" }, { conclusion: "cancelled" }, { conclusion: "skipped" }]) { + assert.equal(qualificationState([{ ...good, ...changes }], sha), "missing"); + } +}); +test("publication waits for its dispatching candidate workflow to finish", async () => { + let calls = 0; + await requireQualification({ sha, runs: () => [++calls === 1 ? { ...good, status: "in_progress", conclusion: null } : good], sleep: async () => {} }); + assert.equal(calls, 2); +}); +test("missing, failed and timed-out qualification cannot publish", async () => { + await assert.rejects(requireQualification({ sha, runs: () => [] }), /No successful/); + let time = 0; + await assert.rejects(requireQualification({ sha, runs: () => [{ ...good, status: "in_progress" }], now: () => time++, timeout: 1, sleep: async () => {} }), /deadline/); +}); diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 1af4a631c18..85277ce00bf 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -112,18 +112,6 @@ export function isVersionOnlyRelease(files) { ); } -// On master, only the release pull request changes the release manifest, so a -// PR or legacy merge group carrying it gets full validation before merging -// instead of the change-based subset. Syncing master into develop carries the -// same change without releasing anything. An undeterminable diff fails open. -export function isReleaseMergeGroup({ event, baseRef, files }) { - return ( - ["merge_group", "pull_request"].includes(event) && - baseRef === "refs/heads/master" && - (files === null || cutsRelease(files)) - ); -} - export function classifyFiles(files, { releasePlease = false } = {}) { const affected = { docs: false, @@ -286,13 +274,8 @@ if ( : changedFiles(process.argv[2] ?? "", process.argv[3] ?? ""); const queue = process.env.QUEUE_VALIDATION === "true" || (process.env.QUEUE_VALIDATION !== "false" && process.env.GITHUB_EVENT_NAME !== "pull_request"); - const release = queue && isReleaseMergeGroup({ - event: process.env.GITHUB_EVENT_NAME, - baseRef: process.env.MERGE_GROUP_BASE_REF, - files, - }); const affected = - files === null || release + files === null ? { ...ALL_AFFECTED, heliodor_arm64: true } : { ...classifyFiles(files, { releasePlease: !queue && process.env.RELEASE_PLEASE_PR === "true" }), @@ -300,12 +283,12 @@ if ( }; writeOutputs({ queue, + full_validation: scheduledFull, + fast_queue: queue && !scheduledFull, ...affected, - release, ...rustScopeOutputs( process.env.GITHUB_EVENT_NAME === "pull_request" && - !queue && - !release && + !scheduledFull && affected.rust ? files : null, @@ -321,8 +304,8 @@ export function celoxRustTestScope(files, packages) { ); } -// Queue drafts, merge groups, releases and daily runs keep the Celox -// workspace. Lydite tests run independently in lydite-checks.yml. +// Full validation keeps the Celox workspace; PR and queue lint use change scopes. +// Lydite tests run independently in lydite-checks.yml. export function rustScopeOutputs(files) { let scope = { full: true }; let checks; diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 16f53c40c24..ccff9ec85d4 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -11,7 +11,6 @@ import { affectsHeliodorArm64, classifyFiles, cutsRelease, - isReleaseMergeGroup, rustScopeOutputs, } from "./ci-changes.mjs"; @@ -159,8 +158,9 @@ test("full validation overrides even an empty valid diff", () => { { ...all, queue: true, + full_validation: true, + fast_queue: false, heliodor_arm64: true, - release: false, // The whole Rust workspace, with no package scope or filter. rust_full: true, rust_packages: false, @@ -216,7 +216,7 @@ function runClassifier( const [name, value] = line.split("="); return [name, value === "true"]; }) - .filter(([name]) => !name.startsWith("rust_") && name !== "queue"), + .filter(([name]) => !name.startsWith("rust_") && !["queue", "full_validation", "fast_queue"].includes(name)), ); } @@ -233,50 +233,20 @@ test("only the release manifest marks a release", () => { ); }); -test("only master merge groups that change the release manifest are releases", () => { - const manifest = [".release-please-manifest.json"]; - const master = { event: "merge_group", baseRef: "refs/heads/master" }; - assert.equal(isReleaseMergeGroup({ ...master, files: manifest }), true); - assert.equal(isReleaseMergeGroup({ ...master, files: null }), true); - assert.equal(isReleaseMergeGroup({ ...master, files: ["README.md"] }), false); - // Syncing a release into develop carries the manifest but tags nothing. - for (const files of [manifest, null]) { - assert.equal( - isReleaseMergeGroup({ - event: "merge_group", - baseRef: "refs/heads/develop", - files, - }), - false, - ); - } - for (const event of ["push", "schedule"]) { - assert.equal( - isReleaseMergeGroup({ - event, - baseRef: "refs/heads/master", - files: manifest, - }), - false, - ); - } -}); - -test("merge groups with an unknown diff are treated as releases", () => { +test("unknown queue diffs select all paths without running release qualification", () => { assert.deepEqual(runClassifier("", "", MASTER_GROUP), { ...all, heliodor_arm64: true, - release: true, }); // Other events still run every path, but without the release gate. assert.deepEqual( runClassifier("", "", { GITHUB_EVENT_NAME: "pull_request" }), - { ...all, heliodor_arm64: true, release: false }, + { ...all, heliodor_arm64: true }, ); }); // CI checks out a single commit, so build the history this test needs. -test("a merge group that changes the release manifest is a release", (t) => { +test("release manifest changes no longer trigger full queue validation", (t) => { const repository = mkdtempSync(join(tmpdir(), "celox-ci-changes-")); t.after(() => rmSync(repository, { recursive: true, force: true })); const git = (...args) => @@ -297,9 +267,9 @@ test("a merge group that changes the release manifest is a release", (t) => { const base = commitManifest("0.1.0"); const release = commitManifest("0.2.0"); const classify = (env) => - runClassifier(base, release, env, repository).release; + runClassifier(base, release, env, repository).rust; - assert.equal(classify(MASTER_GROUP), true); + assert.equal(classify(MASTER_GROUP), false); assert.equal(classify({ GITHUB_EVENT_NAME: "pull_request" }), false); assert.equal( classify({ @@ -319,7 +289,6 @@ test("other merge groups are not releases", () => { assert.deepEqual(runClassifier(head, head, MASTER_GROUP), { ...none, heliodor_arm64: false, - release: false, }); }); @@ -494,32 +463,14 @@ test("generic Rust changes do not schedule ARM64 Heliodor on pull requests", () ); }); -test("queue drafts on master run release gates even with an unknown diff", () => { - for (const files of [[".release-please-manifest.json"], null]) { - assert.equal( - isReleaseMergeGroup({ - event: "pull_request", - baseRef: "refs/heads/master", - files, - }), - true, - ); - assert.equal( - isReleaseMergeGroup({ - event: "pull_request", - baseRef: "refs/heads/develop", - files, - }), - false, - ); - } +test("queue drafts do not run release gates even with an unknown diff", () => { assert.deepEqual( runClassifier("", "", { GITHUB_EVENT_NAME: "pull_request", MERGE_GROUP_BASE_REF: "refs/heads/master", QUEUE_VALIDATION: "true", }), - { ...all, heliodor_arm64: true, release: true }, + { ...all, heliodor_arm64: true }, ); }); @@ -565,7 +516,7 @@ test("PR branches behind their base ignore unmerged base changes", (t) => { assert.deepEqual(changedFilesBetween(base, head, repository), ["CONTRIBUTING.md"]); assert.deepEqual( runClassifier(base, head, { GITHUB_EVENT_NAME: "pull_request" }, repository), - { ...none, docs: true, heliodor_arm64: false, release: false }, + { ...none, docs: true, heliodor_arm64: false }, ); }); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index ce4381e8131..13c03a9e382 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -31,7 +31,7 @@ test("the required gate rejects failures and only accepts explicitly optional sk ); assert.match( gate, - /ARM64_REQUIRED: \$\{\{ needs\.changes\.outputs\.queue != 'false' && needs\.changes\.outputs\.rust != 'false' \}\}/, + /ARM64_REQUIRED: \$\{\{ needs\.changes\.outputs\.full_validation != 'false' && needs\.changes\.outputs\.rust != 'false' \}\}/, ); assert.match(gate, /ARM64_RESULT: \$\{\{ needs\.arm64-backend\.result \}\}/); const script = gate.match(/ run: \|\n([\s\S]*)/)[1]; @@ -47,6 +47,7 @@ test("the required gate rejects failures and only accepts explicitly optional sk ARM64_RESULT: "success", NAPI_REQUIRED: "true", NATIVE_RESULT: "success", + WASM_REQUIRED: "true", WASM_RESULT: "success", RELEASE_REQUIRED: "false", EXTERNAL_RESULT: "skipped", @@ -123,6 +124,7 @@ test("the required gate rejects failures and only accepts explicitly optional sk const rustOnly = { ...success, NAPI_REQUIRED: "false", + WASM_REQUIRED: "false", NATIVE_RESULT: "skipped", WASM_RESULT: "skipped", }; @@ -184,15 +186,7 @@ test("scheduled and manual validation run all paths and external suites", () => assert.match(external, /needs: changes\n/); assert.match( external, - /if: \$\{\{ !cancelled\(\) && \(github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch' \|\| needs\.changes\.outputs\.release == 'true'\)/, - ); - assert.match( - job("changes"), - /release: \$\{\{ steps\.classify\.outputs\.release \}\}/, - ); - assert.match( - job("changes"), - /MERGE_GROUP_BASE_REF: .*github\.event\.merge_group\.base_ref.*github\.base_ref/, + /if: \$\{\{ !cancelled\(\) && needs\.changes\.outputs\.full_validation == 'true'/, ); assert.match(job("changes"), /RELEASE_PLEASE_PR: .*github\.event\.pull_request\.head\.repo\.full_name == github\.repository/); assert.match(job("changes"), /QUEUE_VALIDATION: .*startsWith\(github\.head_ref, 'mergify\/merge-queue\/'\)/); @@ -254,17 +248,17 @@ test("Rust changes validate dependency exclusions even when script jobs are omit ); }); -test("queue CI retains the whole workspace and ordinary PRs use scoped tests", () => { +test("full validation retains the whole workspace; the queue uses bounded integration tests", () => { const rust = job("rust-tests"); assert.match(job("changes"), /QUEUE_VALIDATION: .*startsWith\(github\.head_ref, 'mergify\/merge-queue\/'\)/); // Anything but an explicit scope, including a failed detection, runs all. assert.match( rust, - /name: Run workspace tests with CI features\n id: workspace-tests\n if: needs\.changes\.outputs\.rust_full != 'false'\n/, + /name: Run workspace tests with CI features\n id: workspace-tests\n if: needs\.changes\.outputs\.fast_queue != 'true' && \(needs\.changes\.outputs\.rust_full != 'false'\)\n/, ); assert.match( rust, - /name: Run the tests this pull request can affect\n id: scoped-tests\n if: needs\.changes\.outputs\.rust_full == 'false' && /, + /name: Run the tests this pull request can affect\n id: scoped-tests\n if: needs\.changes\.outputs\.fast_queue != 'true' && \(needs\.changes\.outputs\.rust_full == 'false' && /, ); assert.match( job("changes"), @@ -287,14 +281,14 @@ test("artifact consumers wait for their producer rather than the Rust test gate" assert.match(browser, /name: napi-wasm32-wasi/); }); -test("landed commits are not re-validated by a push run", () => { +test("master pushes do not compete with the queue for full-matrix runners", () => { const triggers = workflow.match(/^on:\n([\s\S]*?)\n\S/m)[1]; assert.doesNotMatch(triggers, /^\s+push:/m); assert.match(triggers, /^\s+merge_group:/m); assert.match(triggers, /^\s+schedule:/m); }); -test("platform jobs are deferred to queue validation", () => { +test("platform jobs are deferred to full validation", () => { const platform = [ "arm64-backend", "napi-windows", @@ -302,7 +296,7 @@ test("platform jobs are deferred to queue validation", () => { "js-windows", ]; for (const name of platform) { - assert.match(job(name), /\n if: \$\{\{ !cancelled\(\) && needs\.changes\.outputs\.queue != 'false' && \(/, name); + assert.match(job(name), /\n if: \$\{\{ !cancelled\(\) && needs\.changes\.outputs\.full_validation != 'false' && \(/, name); } // Linux jobs still give pull requests their feedback. for (const name of [ @@ -333,7 +327,7 @@ test("full runs on long-lived branches report every job's result", () => { assert.deepEqual([...needs].sort(), [...jobs].sort()); assert.match( report, - /if: \$\{\{ !cancelled\(\) && \(github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch'\) && \(github\.ref_name == 'master' \|\| github\.ref_name == 'develop'\)/, + /if: \$\{\{ !cancelled\(\) && inputs\.validation_ref == '' && \(github\.event_name == 'push' \|\| github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch'\) && \(github\.ref_name == 'master' \|\| github\.ref_name == 'develop'\)/, ); assert.match(report, /issues: write/); assert.match(report, /NEEDS: \$\{\{ toJSON\(needs\) \}\}/); @@ -345,7 +339,7 @@ test("queue validation rejects missing coverage, producer failures and detection assert.match(gate, /if: \$\{\{ !cancelled\(\) && needs\.changes\.outputs\.queue != 'false'/); const script = gate.match(/ run: \|\n([\s\S]*)/)[1]; const needs = Object.fromEntries(["lint", "rust", "napi-windows", "napi-linux-arm64", "js-ubuntu", "js-windows", "playground-browser", "docs"].map(name => [name, { result: "success" }])); - needs.changes = { result: "success", outputs: { queue: "true", rust: "true", napi: "true", napi_arm64: "true", javascript: "true", scripts: "true", docs: "true" } }; + needs.changes = { result: "success", outputs: { queue: "true", full_validation: "true", fast_queue: "false", rust: "true", napi: "true", napi_arm64: "true", javascript: "true", scripts: "true", docs: "true" } }; const passes = (value) => spawnSync("bash", ["-e", "-c", script], { env: { ...process.env, NEEDS: JSON.stringify(value) } }).status === 0; assert.equal(passes(needs), true); for (const name of Object.keys(needs)) { @@ -462,7 +456,7 @@ test("CI prepares one executor for full runs and scopes containing Celox", () => const rust = job("rust-tests"); const step = rust.split(" - name: Build the optimized vtest executor\n")[1] .split("\n #")[0]; - assert.match(step, /if: needs.changes.outputs.rust_full != 'false' \|\| contains\(format\(' \{0\} ', needs.changes.outputs.rust_packages\), ' celox '\)/); + assert.match(step, /if: needs.changes.outputs.fast_queue != 'true' && \(needs.changes.outputs.rust_full != 'false' \|\| contains\(format\(' \{0\} ', needs.changes.outputs.rust_packages\), ' celox '\)/); assert.match(step, /run: node scripts\/run-vtest.mjs --prepare-ci/); assert.ok(rust.indexOf("Build the optimized vtest executor") < rust.indexOf("Run workspace tests")); assert.match(rust, /cargo nextest run[^\n]*\n[^\n]*celox-test-suite\/runtime-cases/); @@ -561,7 +555,7 @@ test("full Clippy validation excludes the disabled bridge", () => { test("upstream SV TB runs on full CI and feeds failure reporting", () => { const upstream = job("common-cells"); - assert.match(upstream, /github.event_name == 'schedule' \|\| github.event_name == 'workflow_dispatch'/); + assert.match(upstream, /needs.changes.outputs.full_validation == 'true'/); assert.doesNotMatch(upstream, /continue-on-error/); assert.match(upstream, /conformance\/common-cells\/revision/); assert.match(upstream, /cargo build --locked -p celox-vpi --features systemverilog --bin celox/); diff --git a/scripts/configure-merge-checks.mjs b/scripts/configure-merge-checks.mjs new file mode 100644 index 00000000000..58ba2649106 --- /dev/null +++ b/scripts/configure-merge-checks.mjs @@ -0,0 +1,57 @@ +import { execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +const DEFERRED_CHECKS = new Set([ + "NAPI Build (Linux ARM64 GNU)", + "NAPI Build (Windows)", + "JS Test (Windows)", +]); + +// Preserve the ruleset's enforcement, bypass actors, branch selectors and all +// unrelated checks. Queue validation still rejects failures in its producers. +export function lightweightRuleset(ruleset) { + const result = structuredClone(ruleset); + const checks = result.rules.find(rule => rule.type === "required_status_checks"); + if (!checks) throw new Error("Missing required status checks rule"); + const previous = checks.parameters.required_status_checks; + const integration = previous.find(check => check.context === "Lint & Format"); + if (!integration) throw new Error("Missing GitHub Actions lint check"); + checks.parameters.required_status_checks = previous.filter(check => !DEFERRED_CHECKS.has(check.context)); + if (!previous.some(check => check.context === "Queue validation")) { + checks.parameters.required_status_checks.push({ + context: "Queue validation", + integration_id: integration.integration_id, + }); + } + return Object.fromEntries(["name", "target", "enforcement", "bypass_actors", "conditions", "rules"] + .filter(key => key in result).map(key => [key, result[key]])); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const args = process.argv.slice(2); + if (args.some(arg => arg !== "--apply")) throw new Error("Usage: node scripts/configure-merge-checks.mjs [--apply]"); + const repository = process.env.GITHUB_REPOSITORY || "celox-sim/celox"; + const api = (path, options = []) => JSON.parse(execFileSync("gh", ["api", `repos/${repository}/${path}`, ...options], { encoding: "utf8" })); + const rulesets = api("rulesets"); + const master = rulesets.find(rule => rule.name === "master"); + if (!master) throw new Error("master ruleset not found"); + const current = api(`rulesets/${master.id}`); + const desired = lightweightRuleset(current); + console.log(JSON.stringify(desired, null, 2)); + if (args.includes("--apply")) { + // Do not remove existing required checks before the replacement is deployed. + const source = path => Buffer.from(api(`contents/${path}?ref=master`).content, "base64").toString(); + const ci = source(".github/workflows/ci.yml"); + if (!ci.includes("name: Run merge queue integration tests") || !ci.includes("name: Release qualification")) { + throw new Error("Merge the release-validation workflow change before applying the ruleset migration"); + } + for (const path of [".github/workflows/ci-napi.yml", ".github/workflows/publish-crates.yml"]) { + if (!source(path).includes("name: Verify release branch qualification")) { + throw new Error(`${path} does not yet require release qualification`); + } + } + execFileSync("gh", ["api", "--method", "PUT", `repos/${repository}/rulesets/${master.id}`, "--input", "-"], { + input: JSON.stringify(desired), stdio: ["pipe", "inherit", "inherit"], + }); + } +} diff --git a/scripts/configure-merge-checks.test.mjs b/scripts/configure-merge-checks.test.mjs new file mode 100644 index 00000000000..ddff2c873d0 --- /dev/null +++ b/scripts/configure-merge-checks.test.mjs @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { lightweightRuleset } from "./configure-merge-checks.mjs"; + +test("migration removes only deferred platforms, preserves enforcement and adds the queue gate", () => { + const input = { + id: 123, name: "master", target: "branch", enforcement: "active", + bypass_actors: [{ actor_id: 42, actor_type: "Integration", bypass_mode: "always" }], + conditions: { ref_name: { include: ["refs/heads/master"], exclude: [] } }, + rules: [{ type: "non_fast_forward" }, { type: "required_status_checks", parameters: { + strict_required_status_checks_policy: false, + required_status_checks: ["Lint & Format", "Rust Test & NAPI Build", "Conventional Commit title", "NAPI Build (Windows)", "JS Test (Windows)", "NAPI Build (Linux ARM64 GNU)", "Custom audit"] + .map(context => ({ context, integration_id: 15368 })), + } }], + }; + const before = structuredClone(input); + const actual = lightweightRuleset(input); + assert.deepEqual(input, before); + assert.equal(actual.enforcement, "active"); + assert.deepEqual(actual.bypass_actors, input.bypass_actors); + assert.deepEqual(actual.conditions, input.conditions); + assert.deepEqual(actual.rules[0], input.rules[0]); + assert.deepEqual(actual.rules[1].parameters.required_status_checks.map(check => check.context), + ["Lint & Format", "Rust Test & NAPI Build", "Conventional Commit title", "Custom audit", "Queue validation"]); + assert.deepEqual(lightweightRuleset(actual), actual); + assert.equal(actual.id, undefined); +}); + +test("unexpected rulesets are rejected instead of guessing required checks", () => { + assert.throws(() => lightweightRuleset({ rules: [] }), /Missing required/); + assert.throws(() => lightweightRuleset({ rules: [{ type: "required_status_checks", parameters: { required_status_checks: [] } }] }), /Missing GitHub Actions/); +}); diff --git a/scripts/promote-release-candidate.mjs b/scripts/promote-release-candidate.mjs new file mode 100644 index 00000000000..7d661203cd4 --- /dev/null +++ b/scripts/promote-release-candidate.mjs @@ -0,0 +1,54 @@ +import { execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export async function promoteCandidate({ github, sha, tag }) { + if (!/^[0-9a-f]{40}$/.test(sha) || !/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(tag)) throw new Error("Invalid candidate identity"); + if (await github.branchSha() !== sha) throw new Error("Candidate was superseded on release; do not publish it"); + const pull = await github.releasePull(sha); + if (!pull) throw new Error("Candidate is not a merged master release pull request"); + const tagged = await github.tagSha(tag); + if (tagged && tagged !== sha) throw new Error("Release tag points at a different candidate"); + const release = await github.release(tag); + if (release) { + if (release.draft || release.prerelease || tagged !== sha) throw new Error("Existing release is not the qualified stable candidate"); + } else { + await github.createRelease(tag, sha); + } + // Retry publication only for this immutable, qualified tag. + await github.dispatchPackages(tag); + await github.markTagged(pull.number); +} + +function cli(args, input) { + return execFileSync("gh", args, { encoding: "utf8", input, stdio: ["pipe", "pipe", "pipe"] }).trim(); +} +export function githubClient(repository) { + if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) throw new Error("Invalid repository"); + const api = (path, optional = false) => { + try { return JSON.parse(cli(["api", `repos/${repository}/${path}`])); } + catch (error) { + if (optional && /\(HTTP 404\)/.test(String(error.stderr))) return null; + throw error; + } + }; + return { + branchSha: () => api("git/ref/heads/release").object.sha, + releasePull: sha => api(`commits/${sha}/pulls`).find(pr => pr.merged_at && pr.merge_commit_sha === sha && pr.base.ref === "master" && pr.head.ref === "release-please--branches--master--components--celox" && pr.head.repo?.full_name === repository), + tagSha: tag => { + let object = api(`git/ref/tags/${tag}`, true)?.object; + for (let depth = 0; object?.type === "tag" && depth < 10; depth++) object = api(`git/tags/${object.sha}`).object; + if (object && object.type !== "commit") throw new Error("Invalid release tag object"); + return object?.sha ?? null; + }, + release: tag => api(`releases/tags/${tag}`, true), + createRelease: (tag, sha) => cli(["release", "create", tag, "--repo", repository, "--target", sha, "--title", tag, "--generate-notes"]), + dispatchPackages: tag => { + cli(["api", "--method", "POST", `repos/${repository}/dispatches`, "--input", "-"], JSON.stringify({ event_type: "napi-release", client_payload: { tag } })); + cli(["workflow", "run", "publish-crates.yml", "--repo", repository, "--ref", tag]); + }, + markTagged: number => cli(["pr", "edit", String(number), "--repo", repository, "--remove-label", "autorelease: pending", "--add-label", "autorelease: tagged"]), + }; +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await promoteCandidate({ github: githubClient(process.env.GITHUB_REPOSITORY), sha: process.env.CANDIDATE_SHA, tag: process.env.RELEASE_TAG }); +} diff --git a/scripts/release-pr-update.test.mjs b/scripts/release-pr-update.test.mjs index e55150bd494..6e6a7fc517c 100644 --- a/scripts/release-pr-update.test.mjs +++ b/scripts/release-pr-update.test.mjs @@ -95,7 +95,7 @@ test("a failed lookup stops the workflow instead of permitting a rewrite", () => assert.equal(result.output, ""); }); -test("freeze suppresses only PR writes, preserving release creation on every event", () => { +test("master updates release PRs but never creates tags or GitHub releases", () => { const action = workflow .split(" - name: Create release or update release pull request\n")[1] .split(" - name: Queue package publication for this release\n")[0]; @@ -105,6 +105,6 @@ test("freeze suppresses only PR writes, preserving release creation on every eve action, /skip-github-pull-request: \$\{\{ steps\.release-pr\.outputs\.frozen == 'true' \}\}/, ); - assert.doesNotMatch(action, /skip-github-release:|\n if:/); + assert.match(action, /skip-github-release: true/); assert.doesNotMatch(guard, /github\.event_name|\n if:/); }); diff --git a/scripts/release-publication.test.mjs b/scripts/release-publication.test.mjs index 104bce766f7..a0dbf363e5d 100644 --- a/scripts/release-publication.test.mjs +++ b/scripts/release-publication.test.mjs @@ -1,127 +1,72 @@ import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import { - existsSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { readFileSync } from "node:fs"; import test from "node:test"; - -const workflow = readFileSync( - new URL("../.github/workflows/release.yml", import.meta.url), - "utf8", -); -const publication = workflow - .split(" - name: Queue package publication for this release\n")[1] - .split("\n queue-release:")[0]; -const script = publication - .split(" run: |\n")[1] - .split("\n") - .map((line) => line.replace(/^ /, "")) - .join("\n"); - -function dispatch({ tag = "v0.8.2", publishedTag = tag } = {}) { - const directory = mkdtempSync(join(tmpdir(), "celox-release-publication-")); - const callsPath = join(directory, "calls.jsonl"); - writeFileSync( - join(directory, "gh"), - `#!/usr/bin/env node -const fs = require("node:fs"); -const args = process.argv.slice(2); -const input = args[0] === "api" ? fs.readFileSync(0, "utf8") : ""; -fs.appendFileSync(process.env.CALLS_PATH, JSON.stringify({ args, input }) + "\\n"); -if (args[0] === "release") console.log(process.env.PUBLISHED_TAG); -`, - { mode: 0o755 }, - ); - try { - const result = spawnSync("bash", ["-e", "-o", "pipefail", "-c", script], { - cwd: directory, - env: { - ...process.env, - PATH: `${directory}:${process.env.PATH}`, - RELEASE_TAG: tag, - PUBLISHED_TAG: publishedTag, - CALLS_PATH: callsPath, - GITHUB_REPOSITORY: "celox-sim/celox", - // A batched merge push ends at a commit after the release tag. - GITHUB_SHA: "259c946c7465644bb856f286295170453958ce78", - }, - encoding: "utf8", - }); - const calls = existsSync(callsPath) - ? readFileSync(callsPath, "utf8").trim().split("\n").map(JSON.parse) - : []; - return { ...result, calls }; - } finally { - rmSync(directory, { recursive: true, force: true }); - } +import { promoteCandidate } from "./promote-release-candidate.mjs"; +const sha = "a".repeat(40), tag = "v0.11.0"; +function fixture(overrides = {}) { + const calls = []; + return { calls, github: { + branchSha: async () => sha, + releasePull: async () => ({ number: 7 }), + tagSha: async () => null, + release: async () => null, + createRelease: async (...args) => calls.push(["create", ...args]), + dispatchPackages: async (...args) => calls.push(["dispatch", ...args]), + markTagged: async (...args) => calls.push(["tagged", ...args]), + ...overrides, + } }; } - -test("publication runs only for a newly created root release on any event", () => { - assert.match( - workflow, - /id: release\n\s+uses: googleapis\/release-please-action@v5/, - ); - assert.match( - publication, - /if: steps\.release\.outputs\.release_created == 'true'/, - ); - assert.match( - publication, - /RELEASE_TAG: \$\{\{ steps\.release\.outputs\.tag_name \}\}/, - ); - assert.doesNotMatch(publication, /github\.event_name/); +test("promotion creates the tag/release at the qualified SHA before dispatch", async () => { + const f = fixture(); await promoteCandidate({ ...f, sha, tag }); + assert.deepEqual(f.calls, [["create", tag, sha], ["dispatch", tag], ["tagged", 7]]); }); - -test("dispatches both publishers for the created tag after a batched merge", () => { - const result = dispatch(); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.calls.length, 3); - assert.deepEqual(result.calls[0].args.slice(0, 3), [ - "release", - "view", - "v0.8.2", - ]); - assert.deepEqual(result.calls[1].args, [ - "api", - "--method", - "POST", - "repos/celox-sim/celox/dispatches", - "--input", - "-", - ]); - assert.deepEqual(JSON.parse(result.calls[1].input), { - event_type: "napi-release", - client_payload: { tag: "v0.8.2" }, - }); - assert.deepEqual(result.calls[2].args, [ - "workflow", - "run", - "publish-crates.yml", - "--repo", - "celox-sim/celox", - "--ref", - "v0.8.2", - ]); +test("superseded, unrelated and conflicting candidates cannot publish", async () => { + for (const overrides of [ + { branchSha: () => "b".repeat(40) }, { releasePull: () => null }, + { tagSha: () => "b".repeat(40) }, + { tagSha: () => sha, release: () => ({ draft: true }) }, + { tagSha: () => sha, release: () => ({ prerelease: true }) }, + { branchSha: () => { throw new Error("API failure"); } }, + ]) { + const f = fixture(overrides); + await assert.rejects(promoteCandidate({ ...f, sha, tag })); assert.deepEqual(f.calls, []); + } }); - -test("does not dispatch publishers when the stable GitHub release is missing", () => { - const result = dispatch({ publishedTag: "" }); - assert.notEqual(result.status, 0); - assert.equal(result.calls.length, 1); - assert.match(result.stderr, /Published GitHub Release v0.8.2 was not found/); +test("an exact existing release can resume package dispatch", async () => { + const f = fixture({ tagSha: () => sha, release: () => ({ draft: false, prerelease: false }) }); + await promoteCandidate({ ...f, sha, tag }); + assert.deepEqual(f.calls, [["dispatch", tag], ["tagged", 7]]); +}); +test("release creation failure cannot dispatch packages", async () => { + const f = fixture({ createRelease: () => { throw new Error("creation failed"); } }); + await assert.rejects(promoteCandidate({ ...f, sha, tag })); assert.deepEqual(f.calls, []); +}); +test("only release branch qualification can create the public release", () => { + const master = readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8"); + const stage = readFileSync(new URL("../.github/workflows/stage-release-candidate.yml", import.meta.url), "utf8"); + const rc = readFileSync(new URL("../.github/workflows/release-candidate.yml", import.meta.url), "utf8"); + assert.match(master, /skip-github-release: true/); + assert.doesNotMatch(master, /release_created|release create|napi-release/); + assert.match(stage, /git push origin "\$CANDIDATE_SHA:refs\/heads\/release"/); + assert.match(stage, /ref: \$\{\{ github.event.pull_request.merge_commit_sha \}\}/); + assert.match(rc, /branches: \[release\]/); + assert.match(rc, /if: github.ref == 'refs\/heads\/release'/); + assert.match(rc, /validation_ref: \$\{\{ needs.candidate.outputs.sha \}\}/); + assert.match(rc, /needs: \[candidate, qualify\]/); + assert.doesNotMatch(rc, /continue-on-error/); }); -test("rejects missing and non-stable release tags", () => { - for (const tag of ["", "v0.8.2-rc.1", "master"]) { - const result = dispatch({ tag }); - assert.notEqual(result.status, 0); - assert.deepEqual(result.calls, []); - assert.match(result.stderr, /Expected a v-prefixed stable release tag/); - } + +test("one-shot candidate staging cannot be coalesced with release management or other closures", () => { + const management = readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8"); + const stage = readFileSync(new URL("../.github/workflows/stage-release-candidate.yml", import.meta.url), "utf8"); + assert.doesNotMatch(management, /^ pull_request:|^ stage-candidate:/m); + assert.match(management, /group: release-management/); + assert.match(stage, /pull_request:\n types: \[closed\]\n branches: \[master\]/); + // Neither workflow-level nor job-level concurrency may discard a pending RC. + assert.doesNotMatch(stage, /^\s*concurrency:/m); + assert.match(stage, /github.event.pull_request.merged == true/); + assert.match(stage, /github.event.pull_request.head.repo.full_name == github.repository/); + assert.match(stage, /github.event.pull_request.head.ref == 'release-please--branches--master--components--celox'/); + assert.doesNotMatch(stage, /git push[^\n]*(?:--force|\+)/); }); diff --git a/scripts/release-validation.test.mjs b/scripts/release-validation.test.mjs new file mode 100644 index 00000000000..724a04064e0 --- /dev/null +++ b/scripts/release-validation.test.mjs @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; + +const workflow = readFileSync(new URL("../.github/workflows/ci.yml", import.meta.url), "utf8"); +function job(text, name) { + const parts = text.split(/^ ([\w-]+):\n/m); + const index = parts.indexOf(name); + assert.ok(index >= 0, name); + return parts[index + 1]; +} +function runGate(name, needs) { + const script = job(workflow, name).split(" run: |\n")[1]; + return spawnSync("bash", ["-e", "-c", script], { env: { ...process.env, NEEDS: JSON.stringify(needs) } }).status; +} + +test("qualification fails on every missing, skipped, failed or cancelled required job", () => { + const names = job(workflow, "full-validation").match(/needs:\s*\[([^\]]+)\]/)[1] + .split(",").map(name => name.trim()).filter(Boolean); + for (const required of ["rust-tests", "rust-default-tests", "sv-tests", "external-suites", "common-cells", "arm64-backend", "js-windows", "napi-wasm", "playground-browser"]) { + assert.ok(names.includes(required), required); + } + const needs = Object.fromEntries(names.map(name => [name, { result: "success" }])); + assert.equal(runGate("full-validation", needs), 0); + for (const name of names) { + for (const result of ["skipped", "failure", "cancelled", ""]) { + assert.notEqual(runGate("full-validation", { ...needs, [name]: { result } }), 0, `${name}: ${result}`); + } + } +}); + +test("queue accepts deferred coverage but rejects any failed queue producer", () => { + const needs = Object.fromEntries(["lint", "rust", "js-ubuntu", "docs"].map(name => [name, { result: "success" }])); + for (const name of ["napi-windows", "napi-linux-arm64", "js-windows", "playground-browser"]) needs[name] = { result: "skipped" }; + needs.changes = { result: "success", outputs: { queue: "true", fast_queue: "true", full_validation: "false", rust: "true", napi: "true", napi_arm64: "true", javascript: "true", docs: "true" } }; + assert.equal(runGate("queue-validation", needs), 0); + for (const name of ["lint", "rust", "js-ubuntu", "docs", "changes"]) { + for (const result of ["failure", "cancelled", "skipped"]) { + assert.notEqual(runGate("queue-validation", { ...needs, [name]: { ...needs[name], result } }), 0); + } + } +}); + +test("every full-validation checkout uses the requested immutable source", () => { + const checkouts = [...workflow.matchAll(/uses: actions\/checkout@v7\n([\s\S]*?)(?=\n -|\n [\w-]+:)/g)]; + assert.ok(checkouts.length > 10); + for (const [, checkout] of checkouts) assert.match(checkout, /ref: \$\{\{ inputs.validation_ref \|\| github.sha \}\}/); + assert.match(workflow, /FULL_VALIDATION: .*inputs.validation_ref != ''/); +}); + +test("both stable publishers verify release-branch qualification of their actual build SHA", () => { + for (const [file, source] of [["publish-crates.yml", "github.sha"], ["ci-napi.yml", "needs.validate-release.outputs.build_sha"]]) { + const text = readFileSync(new URL(`../.github/workflows/${file}`, import.meta.url), "utf8"); + const qualification = job(text, "qualify"); + assert.match(qualification, /run: node scripts\/check-release-qualification.mjs/); + assert.ok(qualification.includes(`CANDIDATE_SHA: \${{ ${source} }}`)); + assert.match(job(text, "publish"), /needs: \[[^\]]*qualify\]/); + if (file === "ci-napi.yml") { + assert.match(job(text, "publish"), /needs.qualify.result == 'success'/); + assert.match(job(text, "publish"), /startsWith\(inputs.channel, 'nightly-'\) && needs.qualify.result == 'skipped'/); + // Debug artifacts from qualification must never enter npm packages. + assert.match(job(text, "publish"), /pattern: bindings-\*/); + } + } +}); + +test("queue integration tests run before reports are collected and keep normal failure handling", () => { + const rust = job(workflow, "rust-tests"); + const smoke = rust.split(" - name: Run merge queue integration tests")[1].split(" - name:")[0]; + assert.match(smoke, /if: needs.changes.outputs.fast_queue == 'true'/); + assert.match(smoke, /cargo nextest run --locked -p celox --features systemverilog --profile ci/); + assert.doesNotMatch(smoke, /no-tests=pass|continue-on-error/); + assert.ok(rust.indexOf("Run merge queue integration tests") < rust.indexOf("Collect Rust test reports")); + assert.match(rust, /test_step_outcome: .*steps.queue-tests.outcome/); +}); + +test("classification keeps PRs, fast queue and full qualification distinct", () => { + const classifier = new URL("./ci-changes.mjs", import.meta.url); + for (const [queue, full, expectedFast] of [["false", "false", "false"], ["true", "false", "true"], ["true", "true", "false"]]) { + const result = spawnSync(process.execPath, [classifier.pathname, "", ""], { + env: { ...process.env, GITHUB_EVENT_NAME: "pull_request", QUEUE_VALIDATION: queue, FULL_VALIDATION: full, GITHUB_OUTPUT: "" }, encoding: "utf8", + }); + assert.equal(result.status, 0, result.stderr); + const outputs = Object.fromEntries(result.stdout.trim().split("\n").map(line => line.split("="))); + assert.equal(outputs.full_validation, full); + assert.equal(outputs.fast_queue, expectedFast); + // Unknown diffs still request all product paths; queue mode only narrows execution. + assert.equal(outputs.rust, "true"); + assert.equal(outputs.napi, "true"); + } +}); + +test("qualification names every CI producer, including future additions", () => { + const producers = [...workflow.split(/^jobs:\n/m)[1].matchAll(/^ ([\w-]+):\n/gm)] + .map(match => match[1]).filter(name => !["report-full-validation", "full-validation"].includes(name)); + const required = job(workflow, "full-validation").match(/needs:\s*\[([^\]]+)\]/)[1] + .split(",").map(name => name.trim()).filter(Boolean); + assert.deepEqual(required.sort(), producers.sort()); +});