From 7acd965896fca9ffe62fe95206309f53b6737090 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:53:34 +0900 Subject: [PATCH 1/7] fix(sv): bound recursive specialization along instance paths The global limit of 64 specializations per module rejected finite designs with many independently parameterized siblings, including the HTG9200 statistics collectors. Track the instantiation parent of newly discovered specializations and apply the existing budget to repeated module names along that chain instead. Allow 65 independent sibling specializations in pure SystemVerilog and mixed Veryl/SystemVerilog hierarchies. Parameter-changing recursion remains bounded and identical-specialization cycles retain the existing hierarchy checks. This does not resolve the remaining full-board compilation performance problem. Validation: 5,685 SystemVerilog tests passed (20 existing skips), 7 frontend unit tests passed, affected frontend/Celox clippy with warnings denied, formatting and diff checks. The new shared sibling case passed Icarus and Verilator; the existing recursive elaboration regression also passed. Change-Id: I3c2330c0973e79f5ff44f5f5e646147a65d14cc6 --- crates/celox-frontend-sv/src/lowering.rs | 48 +++++++++++-------- .../src/sv/cases/hierarchy.vtest | 22 +++++++++ .../frontends/systemverilog/hierarchy.rs | 6 +++ .../systemverilog/review_regressions.rs | 24 ++++++++++ 4 files changed, 80 insertions(+), 20 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 44a6c3b9b11..39a4d605af5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -46,7 +46,7 @@ mod procedural; type RegionedVarAddr = RegionedVarAddrBase; type GlueBlock = GlueBlockBase; -const MAX_SV_SPECIALIZATIONS_PER_MODULE: usize = 64; +const MAX_SV_RECURSIVE_SPECIALIZATIONS: usize = 64; /// The name of a module's [`SimModule::time_slot`]. const TIME_SLOT: &str = "$time"; @@ -2268,7 +2268,7 @@ fn prepare_external_hierarchy_collecting( names.sort(); let mut module_ids = HashMap::default(); - let mut module_specialization_counts = HashMap::default(); + let mut specialization_parents = HashMap::default(); let mut queue = Vec::new(); let mut requested_roots = HashMap::default(); for name in names { @@ -2309,7 +2309,6 @@ fn prepare_external_hierarchy_collecting( } let module_id = ModuleId(module_ids.len()); module_ids.insert(key.clone(), module_id); - module_specialization_counts.insert(name.clone(), 1usize); queue.push(key); } @@ -2374,7 +2373,6 @@ fn prepare_external_hierarchy_collecting( if !module_ids.contains_key(&dependency) { let id = ModuleId(module_ids.len()); module_ids.insert(dependency.clone(), id); - module_specialization_counts.insert(name.clone(), 1); queue.push(dependency); } } @@ -2400,13 +2398,7 @@ fn prepare_external_hierarchy_collecting( continue; } if !module_ids.contains_key(&child_key) { - let specialization_count = module_specialization_counts - .entry(child_key.name.clone()) - .or_insert(0); - if *specialization_count >= MAX_SV_SPECIALIZATIONS_PER_MODULE { - return Err(sv_specialization_limit_error(child_key.name.clone()).into()); - } - *specialization_count += 1; + register_specialization_parent(&child_key, &key, &mut specialization_parents)?; let child_id = ModuleId(module_ids.len()); module_ids.insert(child_key.clone(), child_id); queue.push(child_key); @@ -2885,8 +2877,7 @@ fn schedule_sources_collecting( let root_id = ModuleId(0); let mut module_ids = HashMap::default(); module_ids.insert(root_key.clone(), root_id); - let mut module_specialization_counts = HashMap::default(); - module_specialization_counts.insert(root_key.name.clone(), 1usize); + let mut specialization_parents = HashMap::default(); let mut queue = vec![root_key.clone()]; let mut index = 0; let mut elaborated = HashMap::default(); @@ -2923,13 +2914,7 @@ fn schedule_sources_collecting( return Err(unsupported_sv_instance(child_key.name.clone()).into()); } if !module_ids.contains_key(&child_key) { - let specialization_count = module_specialization_counts - .entry(child_key.name.clone()) - .or_insert(0); - if *specialization_count >= MAX_SV_SPECIALIZATIONS_PER_MODULE { - return Err(sv_specialization_limit_error(child_key.name.clone()).into()); - } - *specialization_count += 1; + register_specialization_parent(&child_key, &key, &mut specialization_parents)?; let child_id = ModuleId(module_ids.len()); module_ids.insert(child_key.clone(), child_id); queue.push(child_key); @@ -3210,6 +3195,29 @@ fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvMod } } +/// Bound parameter-changing recursion along one instantiation path. Independent +/// siblings may have any number of distinct parameter specializations. Repeated +/// identical keys are handled by the hierarchy cycle checks. +fn register_specialization_parent( + child: &LoweredSvModuleKey, + parent: &LoweredSvModuleKey, + parents: &mut HashMap, +) -> Result<(), ParserError> { + let mut ancestor = Some(parent); + let mut occurrences = 1usize; + while let Some(key) = ancestor { + if key.name == child.name { + occurrences += 1; + if occurrences > MAX_SV_RECURSIVE_SPECIALIZATIONS { + return Err(sv_specialization_limit_error(child.name.clone())); + } + } + ancestor = parents.get(key); + } + parents.insert(child.clone(), parent.clone()); + Ok(()) +} + fn sv_specialization_limit_error(name: String) -> ParserError { ParserError::unsupported( sv::SV_FRONTEND_TRACKING_ISSUE, diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index d9a8121de40..891856da116 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1738,3 +1738,25 @@ (assert_eq y (fourstate 0x55 0xa0)) (modify (set d 0x96)) (assert_eq y 0x96)) + +(case many_sibling_parameter_specializations + (source "sibling_specializations.sv" #" + module Leaf #(parameter ID=0)(input wire [7:0] x, output wire [7:0] q); + assign q=x ^ 8'(ID); + endmodule + module Top(input wire [7:0] x, output wire [7:0] first, last); + wire [7:0] lanes[65]; + for (genvar n=0; n<65; n=n+1) begin : siblings + Leaf #(.ID(n)) u(.x(x), .q(lanes[n])); + end + assign first=lanes[0]; + assign last=lanes[64]; + endmodule + "#) + (top Top) + (modify (set x 60)) + (assert_eq first 60) + (assert_eq last 124) + (modify (set x 255)) + (assert_eq first 255) + (assert_eq last 191)) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 1e0a3cd893c..8c893ac3d94 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -776,3 +776,9 @@ fn rejects_malformed_non_ansi_port_declarations() { assert!(error.contains(message), "{source}: {error}"); } } + +sv_backends! { + fn many_sibling_parameter_specializations(sim) { + @case "hierarchy::many_sibling_parameter_specializations"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index e5985594160..5c9d4afab27 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8989,3 +8989,27 @@ fn single_bit_array_driver_windows_still_reject_overlaps() { assert!(error.contains("multiple variable drivers"), "{error}"); } } + +#[test] +fn mixed_hierarchies_accept_many_sibling_specializations() { + let veryl = "module Top(x: input logic<8>, y: output logic<8>) { inst tree: $sv::Root(x, y); }"; + let sv = "module Leaf #(parameter ID=0)(input wire [7:0] x, output wire [7:0] y); + assign y=x ^ 8'(ID); endmodule + module Root(input wire [7:0] x, output wire [7:0] y); + wire [7:0] lanes[65]; + for(genvar n=0;n<65;n=n+1) begin: g + Leaf #(.ID(n)) u(.x(x),.y(lanes[n])); + end + assign y=lanes[64]; endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("siblings.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let x = sim.signal("x"); + let y = sim.signal("y"); + sim.modify(|io| io.set(x, 60u8)).unwrap(); + assert_eq!(sim.get(y), BigUint::from(124u8)); +} From eecd74700ff7b4aa66aa3cdb08deff4f35292454 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:56:44 +0900 Subject: [PATCH 2/7] perf(vpi): compile process-capable images without retrying VPI builds first compiled an untimed Simulator image and, after detecting a process, repeated frontend analysis and SIR optimization with Simulation. Compile the process-capable Simulation native image directly for both process-free and process-containing SystemVerilog DUTs. Keep the configured optimization level, diagnostics, parameter overrides and signal access settings. This removes the complete Simulator-to-Simulation retry without disabling optimization. Large VCU108 and HTG9200 native compilations remain a performance issue; this change does not claim that all Taxi configurations or runtime tests pass. Validation: 166 normal celox-vpi tests passed, all eight explicitly selected cocotb tests passed, affected VPI clippy with warnings denied, formatting and diff checks. Cocotb coverage includes a process-free flip-flop, DUT processes, edge/NBA ordering, force/release, unpacked arrays, finish and femtosecond clocks. Change-Id: I6439f16cd7cc0f3b26019b6c8bccb526b7fb1302 --- crates/celox-vpi/src/bin/celox.rs | 37 +++++++++---------------------- 1 file changed, 10 insertions(+), 27 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 225e09851ca..e5829c56bd8 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -839,35 +839,18 @@ fn compile_native_design(design: &Design) -> Result .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let untimed = configure_sv( + // VPI advances time and dispatches callbacks even for a process-free + // DUT. Compile its process-capable image directly, rather than first + // compiling an untimed image and repeating analysis and optimization + // when that builder discovers a process. + let simulation = configure_sv( design, - celox::Simulator::from_sv_sources(refs.clone(), &design.top), + celox::Simulation::from_sv_sources(refs, &design.top), ) - .compile_native(); - let image = match untimed { - Ok(simulator) => { - report_warnings(simulator.warnings())?; - simulator.into_program_image() - } - // A design with processes runs as a timed simulation, in step - // with the VPI time callbacks. - Err(error) - if matches!( - error.kind(), - celox::SimulatorErrorKind::ProcessRequiresSimulation(_) - ) => - { - let simulation = configure_sv( - design, - celox::Simulation::from_sv_sources(refs, &design.top), - ) - .compile_native() - .map_err(|error| format!("compilation failed:\n{error}"))?; - report_warnings(simulation.warnings())?; - simulation.into_program_image() - } - Err(error) => return Err(format!("compilation failed:\n{error}")), - }; + .compile_native() + .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; + let image = simulation.into_program_image(); return Ok(image); } #[cfg(not(feature = "systemverilog"))] From b79fb2822bf4780ca67776148560b5672e6449cf Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 03:53:28 +0900 Subject: [PATCH 3/7] chore(deps): update zstd-sys to fix the wasm allocator advisory Update only zstd-sys from 2.0.16+zstd.1.5.7 to 2.1.2+zstd.1.5.7. This removes RUSTSEC-2026-0410 from the workspace dependency audit, covering the upstream wasm allocator fix without adding vendor patches or advisory exclusions. This is a partial remediation: cargo-deny still reports RUSTSEC-2026-0391, RUSTSEC-2026-0398, and RUSTSEC-2026-0403 for zstd 0.13.3 and zstd-safe 7.2.4. The latest include-flate-compress 0.3.4 and wasmtime-internal-cache 50.0.0 still require zstd ^0.13, preventing resolution to fixed zstd 0.14.3 / zstd-safe 8.2.0. Keep this PR in draft while those upstream constraints remain; the advisory gate is unchanged. No downstream minimum version is imposed by a workspace lockfile update. Security-only Cargo update automation is handled independently in #2199 so it can land without this remaining advisory failure. Validation: celox-backend-wasm library tests (7 passed); include-flate-compress compiled against the updated chain; workspace/all-target cargo check with the CI feature configuration, including native/Cranelift/Wasmtime and external-suite adapters (excluding the disabled lydite-celox bridge); cargo-deny bans/licenses/sources passed; advisories reduced from 4 to the 3 documented above. Advisory/version verification was used instead of an allocator-exhaustion exploit reproduction. Change-Id: I510c5d926178a7c3441caaf5f40740cab1c584da --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a33a7e74520..2ff45141965 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5664,9 +5664,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", From 40976fd6ea7e0c73db67cd1f8b982cf2e54ce4f6 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 03:09:35 +0900 Subject: [PATCH 4/7] feat(sv)!: solve scalar class constraints during randomize Connect named scalar class constraints to Aplite through a serializable heap program. Support 1-64 bit two-state integer comparisons, Boolean and bitwise operators, and addition/subtraction/multiplication with SV context sizing. Inherit constraints and replace same-name blocks in derived classes, including calls through base handles. Read state and random modes after pre_randomize. Apply a complete satisfying assignment atomically; proved UNSAT returns 0 without changing random fields or calling post_randomize. Restore temporary member selections on failure. Check-only calls consume no object random draws. Resource exhaustion raises a heap fault instead of masquerading as UNSAT. Use seeded SAT search for the initial integration. This avoids hash-cell acceptance failures and makes no uniformity claim; distribution work is tracked in #2187. Constrained enums/randc, inside, dist, solve-before, inline with, conditional/soft/foreach constraints and external/static blocks remain diagnosed as unsupported. The publishing consumer requires the independent aplite 0.1.0 release before publishing celox-heap. Validation: 129 randomization regressions across native, Cranelift, Wasm and parallel backends; 25 heap, 832 analyzer and 132 syntax tests plus doctests; focused failure/replay and unsupported-form tests; affected-crate clippy and rustdoc with warnings denied; NAPI cargo check; formatting and package/release guards. Verilator passes scalar mode/selection and width/inheritance cases. Retained evidence records its post_randomize-on-UNSAT disagreement and Icarus unsupported constraint declarations, with narrow tool-specific exclusions and unchanged Celox assertions. No local release build. BREAKING CHANGE: ObjectOp and heap Fault gain constraint randomization variants. Change-Id: I0bbc4db8256385015e506817f5ea46fd3fcdd006 --- .github/RELEASING.md | 9 +- Cargo.lock | 4 + Cargo.toml | 4 +- crates/celox-frontend-sv/Cargo.toml | 2 + .../src/lowering/ff/objects.rs | 19 +- crates/celox-heap/Cargo.toml | 3 + crates/celox-heap/src/lib.rs | 1 + crates/celox-heap/src/objects.rs | 4 + crates/celox-heap/src/ops.rs | 16 + crates/celox-heap/src/randomization.rs | 356 ++++++++++++++++++ crates/celox-sv-analyzer/Cargo.toml | 2 + crates/celox-sv-analyzer/src/ast/classes.rs | 25 +- .../src/ast/classes/constraints.rs | 214 +++++++++++ .../src/ast/procedural/randomization.rs | 82 ++-- .../celox-sv-analyzer/src/system_functions.rs | 5 +- crates/celox-sv-analyzer/src/tests.rs | 32 +- crates/celox-test-suite/LIMITATIONS.md | 10 + .../celox-test-suite/src/sv/cases/class.vtest | 91 +++++ .../repros/sv_scalar_constraints.json | 33 ++ .../verification/sv/icarus/class.json | 69 ++++ .../verification/sv/limitations.json | 36 ++ .../verification/sv/verilator/class.json | 23 ++ crates/celox-testbench/src/format.rs | 2 +- .../tests/frontends/systemverilog/class.rs | 13 +- docs/guide/systemverilog-reference.md | 22 +- docs/ja/guide/systemverilog-reference.md | 17 +- scripts/ci-changes.mjs | 5 +- scripts/ci-changes.test.mjs | 9 +- scripts/ci-lydite-changes.test.mjs | 7 +- scripts/publish-crates.sh | 2 +- scripts/publish-crates.test.mjs | 6 + 31 files changed, 1073 insertions(+), 50 deletions(-) create mode 100644 crates/celox-heap/src/randomization.rs create mode 100644 crates/celox-sv-analyzer/src/ast/classes/constraints.rs create mode 100644 crates/celox-test-suite/verification/repros/sv_scalar_constraints.json diff --git a/.github/RELEASING.md b/.github/RELEASING.md index 8ebf82c9402..6d455b10f3a 100644 --- a/.github/RELEASING.md +++ b/.github/RELEASING.md @@ -1,12 +1,19 @@ # Release policy Celox is released as one lockstep distribution. `VERSION`, -`.release-please-manifest.json`, the npm packages, and all Rust workspace crates +`.release-please-manifest.json`, the npm packages, and all Celox Rust workspace crates must always carry the same version. The public Rust entry points are `celox`, `celox-frontend-sdk`, `celox-test-suite`, and the Rust adapter API in `celox-napi`; the remaining published `celox-*` crates satisfy their Cargo dependency graph and remain implementation details. +Aplite has its own version and release train (`release-aplite.yml` and +`publish-aplite.yml`). Publish the Aplite version required by the workspace +before releasing Celox: `celox-heap` depends on it, and Cargo resolves the +published Aplite crate when packaging Celox crates. A bootstrap `0.0.0` release +does not satisfy this dependency. Aplite is deliberately absent from Celox's +lockstep publication list. + ## Versioning before 1.0 Pull request titles are the input to release automation after GitHub copies the diff --git a/Cargo.lock b/Cargo.lock index a33a7e74520..42717f4af44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "miette", "num-bigint", "num-traits", + "serde_json", "thiserror 2.0.21", ] @@ -663,8 +664,10 @@ dependencies = [ name = "celox-heap" version = "0.11.0" dependencies = [ + "aplite", "fxhash", "serde", + "serde_json", ] [[package]] @@ -784,6 +787,7 @@ name = "celox-sv-analyzer" version = "0.11.0" dependencies = [ "celox-design", + "celox-heap", "celox-sv-syntax", "fxhash", "miette", diff --git a/Cargo.toml b/Cargo.toml index 90e67df41c8..49e7d97722b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,8 +57,8 @@ description = "Celox HDL Simulator" rust-version = "1.99.1" [workspace.dependencies] -# Aplite has its own release version; these consumers are unpublished. -aplite = { path = "crates/aplite" } +# Aplite has an independent release version. +aplite = { version = "0.1.0", path = "crates/aplite" } celox = { version = "=0.11.0", path = "crates/celox", default-features = false } # x-release-please-version celox-analysis = { version = "=0.11.0", path = "crates/celox-analysis" } # x-release-please-version celox-backend-arm64 = { version = "=0.11.0", path = "crates/celox-backend-arm64" } # x-release-please-version diff --git a/crates/celox-frontend-sv/Cargo.toml b/crates/celox-frontend-sv/Cargo.toml index a51b484247d..e40e95db058 100644 --- a/crates/celox-frontend-sv/Cargo.toml +++ b/crates/celox-frontend-sv/Cargo.toml @@ -10,6 +10,8 @@ edition.workspace = true rust-version.workspace = true [dependencies] +serde_json = { workspace = true } + celox-design = { workspace = true } celox-frontend-core = { workspace = true } celox-heap = { workspace = true } diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index b0f44024a44..e2d499dae70 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -24,6 +24,22 @@ impl Ff<'_, '_> { }) .collect::, _>>()?; let result = match op { + ObjectOp::Randomize(program) => { + let object = self.handle(&args[0])?; + let check = self.integer_of_width(&args[1], 1, false)?; + let bytes = serde_json::to_vec(program).expect("constraint program serialization"); + let mut buffer = self.heap_call(ops::NEW, &[]); + for chunk in bytes.chunks(8) { + let value = chunk + .iter() + .fold(0u64, |value, byte| (value << 8) | u64::from(*byte)); + let value = self.constant64(value); + let count = self.constant64(chunk.len() as u64); + buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, value, count]); + } + let program = self.heap_call(ops::FREEZE, &[buffer]); + self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check]) + } ObjectOp::Container { .. } => unreachable!("handled by container_call"), ObjectOp::New { class, @@ -132,7 +148,8 @@ impl Ff<'_, '_> { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, }), - ObjectOp::Store(_) + ObjectOp::Randomize(_) + | ObjectOp::Store(_) | ObjectOp::ClassOf | ObjectOp::Random | ObjectOp::RandomCyclic { .. } diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml index 0ab148bba27..e8223578ef6 100644 --- a/crates/celox-heap/Cargo.toml +++ b/crates/celox-heap/Cargo.toml @@ -10,6 +10,9 @@ edition.workspace = true rust-version.workspace = true [dependencies] +aplite = { workspace = true } +serde_json = { workspace = true } + serde = { workspace = true, features = ["rc"] } fxhash = { workspace = true } diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index ad28602712c..0e0c65aa918 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -19,6 +19,7 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; pub mod containers; mod objects; pub mod ops; +pub mod randomization; pub use objects::{Fault, NULL}; diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 19644b31990..4a55a8f4f2f 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -49,6 +49,7 @@ impl Object { /// reports once control returns to it. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Fault { + ConstraintRandomization(String), NegativeArraySize, ContainerAllocationLimit, /// A property access or method call through `null` or a handle of no @@ -61,6 +62,9 @@ pub enum Fault { impl std::fmt::Display for Fault { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Self::ConstraintRandomization(reason) => { + write!(f, "constraint randomization failed: {reason}") + } Self::NegativeArraySize => f.write_str("negative dynamic array size"), Self::ContainerAllocationLimit => { f.write_str("dynamic container allocation limit exceeded") diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index c1720c54a97..8df747bd277 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -83,6 +83,8 @@ pub const OBJECT_MODE_SELECTED: u64 = 61; pub const OBJECT_RANDOM_CYCLIC: u64 = 62; /// `copy(object)`: a new object with a copy of the properties of `object`. pub const OBJECT_COPY: u64 = 63; +/// Solve the scalar constraint program in string b for object a; c selects check-only. +pub const OBJECT_RANDOMIZE: u64 = 64; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -193,6 +195,20 @@ impl Heap { 0 } OBJECT_CLASS => self.class_of(a as Handle).into(), + OBJECT_RANDOMIZE => { + match serde_json::from_slice::( + self.string(b as Handle), + ) { + Ok(program) => u64::from(self.randomize_object(a as Handle, &program, c != 0)), + Err(error) => { + self.fault + .get_or_insert(crate::Fault::ConstraintRandomization( + error.to_string(), + )); + 0 + } + } + } OBJECT_RANDOM => self.random_object(a as Handle), OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b), OBJECT_SEED => { diff --git a/crates/celox-heap/src/randomization.rs b/crates/celox-heap/src/randomization.rs new file mode 100644 index 00000000000..18980c30405 --- /dev/null +++ b/crates/celox-heap/src/randomization.rs @@ -0,0 +1,356 @@ +//! Serializable scalar constraint programs shared by the SV compiler and heap. +//! The program carries no pointers or persistent solver state. +use crate::{Fault, Handle, Heap}; +use aplite::{ + Env, Limits, Scalar, Sort, Term, Verdict, and, boolv, bv, eq, ite, node, not, solve_seeded, var, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Field { + pub offset: u32, + pub width: u32, + pub random: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum Expr { + Literal(u32, u64), + Field(usize), + Resize { + value: Box, + width: u32, + signed: bool, + }, + Unary { + op: String, + value: Box, + }, + Binary { + op: String, + left: Box, + right: Box, + signed: bool, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Program { + pub fields: Vec, + pub constraints: Vec, +} + +fn truth(value: Term) -> Term { + let Sort::Bv(width) = value.0.sort else { + unreachable!() + }; + not(eq(value, bv(width, 0))) +} +fn boolean(value: Term) -> Term { + ite(value, bv(1, 1), bv(1, 0)) +} + +impl Expr { + fn term(&self, fields: &[Term]) -> Result { + Ok(match self { + Self::Literal(width, value) => bv(*width, *value), + Self::Field(index) => fields + .get(*index) + .ok_or("invalid constraint field")? + .clone(), + Self::Resize { + value, + width, + signed, + } => { + let value = value.term(fields)?; + let Sort::Bv(old) = value.0.sort else { + unreachable!() + }; + if old == *width { + value + } else { + let op = if old > *width { + format!("(_ extract {} 0)", width - 1) + } else { + format!( + "(_ {}_extend {})", + if *signed { "sign" } else { "zero" }, + width - old + ) + }; + node(Sort::Bv(*width), op, vec![value]) + } + } + Self::Unary { op, value } => { + let value = value.term(fields)?; + match op.as_str() { + "!" => boolean(not(truth(value))), + "~" => node(value.0.sort.clone(), "bvnot", vec![value]), + "-" => { + let Sort::Bv(width) = value.0.sort else { + unreachable!() + }; + node(Sort::Bv(width), "bvsub", vec![bv(width, 0), value]) + } + _ => return Err("invalid constraint unary operation".into()), + } + } + Self::Binary { + op, + left, + right, + signed, + } => { + let a = left.term(fields)?; + let b = right.term(fields)?; + let relation = match op.as_str() { + "==" => Some(eq(a.clone(), b.clone())), + "!=" => Some(not(eq(a.clone(), b.clone()))), + "&&" => Some(and(truth(a.clone()), truth(b.clone()))), + "||" => Some(node( + Sort::Bool, + "or", + vec![truth(a.clone()), truth(b.clone())], + )), + "<" | "<=" | ">" | ">=" => { + let suffix = if op.ends_with('=') { "le" } else { "lt" }; + let operands = if op.starts_with('>') { + vec![b.clone(), a.clone()] + } else { + vec![a.clone(), b.clone()] + }; + Some(node( + Sort::Bool, + format!("bv{}{suffix}", if *signed { "s" } else { "u" }), + operands, + )) + } + _ => None, + }; + if let Some(relation) = relation { + boolean(relation) + } else { + let op = match op.as_str() { + "+" => "bvadd", + "-" => "bvsub", + "*" => "bvmul", + "&" => "bvand", + "|" => "bvor", + "^" => "bvxor", + _ => return Err("invalid constraint binary operation".into()), + }; + node(a.0.sort.clone(), op, vec![a, b]) + } + } + }) + } +} + +impl Heap { + /// Evaluate against the state after pre_randomize; commit only a complete + /// assignment. A solver failure is a runtime fault, never an UNSAT result. + pub fn randomize_object( + &mut self, + handle: Handle, + program: &Program, + check_only: bool, + ) -> bool { + self.randomize_object_with_limits(handle, program, check_only, Limits::default()) + } + + fn randomize_object_with_limits( + &mut self, + handle: Handle, + program: &Program, + check_only: bool, + limits: Limits, + ) -> bool { + if !self.check_object(handle, 0) { + return false; + } + let result = (|| -> Result { + let mut projection = Env::new(); + let mut terms = Vec::new(); + let mut active = Vec::new(); + let mut formula = boolv(true); + for (index, field) in program.fields.iter().enumerate() { + if !(1..=64).contains(&field.width) { + return Err("invalid constraint field width".into()); + } + let name = index.to_string(); + let term = var(name.clone(), Sort::Bv(field.width)); + let enabled = !check_only && self.random_mode(handle, field.offset, field.random); + if enabled { + projection.insert(name, term.clone()); + active.push((index, field)); + } else { + let value = self.load( + handle, + field.offset as usize, + field.width.div_ceil(8) as usize, + ); + formula = and(formula, eq(term.clone(), bv(field.width, value))); + } + terms.push(term); + } + for constraint in &program.constraints { + formula = and(formula, truth(constraint.term(&terms)?)); + } + let seed = if projection.is_empty() { + 0 + } else { + self.random_object(handle) + }; + // Initial integration uses seeded SAT search, not hash-cell acceptance. + // It finds a valid model without claiming uniform sampling (#2187). + let outcome = solve_seeded(&formula, &projection, limits, seed); + match outcome.verdict { + Verdict::Unsat => Ok(false), + Verdict::Unknown => Err(outcome + .reason + .unwrap_or_else(|| "constraint solving incomplete".into())), + Verdict::Sat => { + let model = &outcome.context_values; + let updates = active + .into_iter() + .map(|(index, field)| match model.get(&index.to_string()) { + Some(Scalar::Bv { value, .. }) => Ok((field, *value)), + _ => Err("missing constraint field value".to_owned()), + }) + .collect::, _>>()?; + for (field, value) in updates { + self.store( + handle, + field.offset as usize, + field.width.div_ceil(8) as usize, + value, + ); + } + Ok(true) + } + } + })(); + match result { + Ok(success) => success, + Err(reason) => { + self.fault + .get_or_insert(Fault::ConstraintRandomization(reason)); + false + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program() -> Program { + Program { + fields: vec![Field { + offset: 0, + width: 4, + random: true, + }], + constraints: vec![Expr::Binary { + op: "<".into(), + left: Box::new(Expr::Field(0)), + right: Box::new(Expr::Literal(4, 3)), + signed: false, + }], + } + } + + #[test] + fn modes_unsat_faults_and_snapshot_replay() { + let mut heap = Heap::new(); + let object = heap.new_object(1, 1); + heap.store(object, 0, 1, 9); + let program = program(); + let mut before_check = heap.clone(); + assert!(!heap.randomize_object(object, &program, true)); + assert_eq!( + heap.random_object(object), + before_check.random_object(object) + ); + assert_eq!(heap.load(object, 0, 1), 9); + assert_eq!(heap.take_fault(), None); + let limits = Limits { + max_work: 0, + ..Limits::default() + }; + assert!(!heap.randomize_object_with_limits(object, &program, false, limits)); + assert_eq!(heap.load(object, 0, 1), 9); + assert!(matches!( + heap.take_fault(), + Some(Fault::ConstraintRandomization(_)) + )); + heap.seed_object(object, 42); + let mut restored = heap.clone(); + for _ in 0..16 { + assert!(heap.randomize_object(object, &program, false)); + assert!(restored.randomize_object(object, &program, false)); + let value = heap.load(object, 0, 1); + assert!(value < 3); + assert_eq!(value, restored.load(object, 0, 1)); + } + heap.set_random_mode(object, 0, false); + heap.store(object, 0, 1, 7); + assert!(!heap.randomize_object(object, &program, false)); + assert_eq!(heap.load(object, 0, 1), 7); + assert_eq!(heap.take_fault(), None); + } + + #[test] + fn signed_inputs_in_unsigned_arithmetic_context() { + let field = |i, signed| Expr::Resize { + value: Box::new(Expr::Field(i)), + width: 32, + signed, + }; + let binary = |op: &str, left, right| Expr::Binary { + op: op.into(), + left: Box::new(left), + right: Box::new(right), + signed: false, + }; + let program = Program { + fields: [8, 16, 32] + .into_iter() + .enumerate() + .map(|(i, width)| Field { + offset: i as u32 * 8, + width, + random: true, + }) + .collect(), + constraints: vec![ + binary( + "==", + field(0, true), + Expr::Unary { + op: "-".into(), + value: Box::new(Expr::Literal(32, 1)), + }, + ), + binary("==", field(1, true), Expr::Literal(32, 1)), + binary("==", Expr::Field(2), Expr::Literal(32, 256)), + binary( + "==", + binary("+", field(0, false), field(1, false)), + Expr::Field(2), + ), + ], + }; + let mut heap = Heap::new(); + let object = heap.new_object(1, 24); + assert!( + heap.randomize_object(object, &program, false), + "{:?}", + heap.take_fault() + ); + assert_eq!(heap.load(object, 0, 1), 255); + assert_eq!(heap.load(object, 8, 2), 1); + assert_eq!(heap.load(object, 16, 4), 256); + } +} diff --git a/crates/celox-sv-analyzer/Cargo.toml b/crates/celox-sv-analyzer/Cargo.toml index dbcb248dc87..16fa5ab642c 100644 --- a/crates/celox-sv-analyzer/Cargo.toml +++ b/crates/celox-sv-analyzer/Cargo.toml @@ -10,6 +10,8 @@ edition.workspace = true rust-version.workspace = true [dependencies] +celox-heap = { workspace = true } + celox-design = { workspace = true } celox-sv-syntax = { workspace = true } fxhash = { workspace = true } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 471476bbbe7..a3924547f9b 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -12,6 +12,7 @@ use std::rc::Rc; use super::*; use crate::system_functions::{HandleProperty, ObjectField, ObjectOp}; +mod constraints; pub(super) mod specializations; /// Bit width of a handle, see `celox_design::HANDLE_WIDTH`. @@ -131,6 +132,7 @@ pub(super) struct Class { /// Bytes of an object. pub size: u32, pub has_constraints: bool, + pub constraints: Vec<(String, Result, String>)>, } /// An internal unsigned packed argument of a generated method. @@ -152,7 +154,7 @@ impl Class { /// Validate the supported unconstrained subset before binding a call. pub fn check_randomize(&self) -> Converted<()> { if self.has_constraints { - return Err(unsupported("class randomize with constraints")); + self.constraint_program()?; } for property in &self.properties { if property.randc && property.cyclic_domain_size().is_none() { @@ -860,9 +862,29 @@ pub(super) fn class( method.name ))); } + let mut constraints = base + .as_ref() + .map(|base| base.constraints.clone()) + .unwrap_or_default(); + for block in &declaration.constraints { + let block_name = block.name.spelling.clone(); + constraints.retain(|(name, _)| *name != block_name); + let expressions = block + .expressions + .as_ref() + .ok_or_else(|| "unsupported constraint block form".to_owned()) + .and_then(|expressions| { + expressions + .iter() + .map(|&id| constraints::bind(id, tree, &properties, env)) + .collect() + }); + constraints.push((block_name, expressions)); + } let class = Rc::new(Class { name: name.to_owned(), id: class_id(tree, name), + constraints, has_constraints: declaration.has_constraints || base.as_ref().is_some_and(|base| base.has_constraints), base: base.map(|base| base.name.clone()), @@ -988,6 +1010,7 @@ fn interface_class( is_abstract: true, is_interface: true, has_constraints: false, + constraints: Vec::new(), properties: Vec::new(), base_properties: 0, statics: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs new file mode 100644 index 00000000000..3cb2e87ef24 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -0,0 +1,214 @@ +//! Scalar constraint binding. Unsupported forms fail before any RNG draws. +use super::*; +use celox_heap::randomization::{Expr as ConstraintExpr, Field, Program}; +use celox_sv_syntax::{ExprId, ExprKind}; + +struct Typed { + kind: Kind, + width: u32, + signed: bool, +} +enum Kind { + Leaf(ConstraintExpr), + Unary(String, Box), + Binary(String, Box, Box), +} +fn comparison(op: &str) -> bool { + matches!(op, "==" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||") +} + +// Apply context sizing before arithmetic evaluation (IEEE 1800-2023 11.8.2). +// Keep operand types until this pass: eagerly extending signed children would +// incorrectly sign-extend them before a wider unsigned parent is encountered. +fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr { + let (width, signed) = context.unwrap_or((value.width, value.signed)); + let (expr, result_width) = match value.kind { + Kind::Leaf(expr) => (expr, value.width), + Kind::Unary(op, child) => { + let logical = op == "!"; + ( + ConstraintExpr::Unary { + op, + value: Box::new(emit(*child, (!logical).then_some((width, signed)))), + }, + if logical { 1 } else { width }, + ) + } + Kind::Binary(op, a, b) => { + let is_comparison = comparison(&op); + let logical = matches!(op.as_str(), "&&" | "||"); + let operands = if is_comparison { + (a.width.max(b.width), a.signed && b.signed) + } else { + (width, signed) + }; + let a = emit(*a, (!logical).then_some(operands)); + let b = emit(*b, (!logical).then_some(operands)); + ( + ConstraintExpr::Binary { + op, + left: Box::new(a), + right: Box::new(b), + signed: operands.1, + }, + if is_comparison { 1 } else { width }, + ) + } + }; + if result_width == width { + expr + } else { + ConstraintExpr::Resize { + value: Box::new(expr), + width, + signed, + } + } +} + +pub(super) fn bind( + id: ExprId, + tree: &AnalysisContext<'_>, + properties: &[Property], + env: &HashMap, +) -> Result { + fn expression( + id: ExprId, + tree: &AnalysisContext<'_>, + properties: &[Property], + env: &HashMap, + depth: usize, + ) -> Result { + if depth > 64 { + return Err("constraint expression nesting limit".into()); + } + let recurse = |id| expression(id, tree, properties, env, depth + 1); + let native = tree.declarations(); + Ok(match &native.expression(id).kind { + ExprKind::Group(id) => return recurse(*id), + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + if let Some((index, property)) = properties + .iter() + .enumerate() + .rev() + .find(|(_, p)| p.name == name) + { + Typed { + kind: Kind::Leaf(ConstraintExpr::Field(index)), + width: property.field.width, + signed: property.field.signed, + } + } else if env.contains_key(&name) { + // Parameter type reconstruction belongs to the general expression binder. + // Do not guess its width/sign here. + return Err("typed parameters in constraints".into()); + } else { + return Err(format!("constraint variable `{name}`")); + } + } + ExprKind::Literal(text) => { + if text.starts_with("'0") || text.starts_with("'1") { + return Err("unbased unsized constraint literal".into()); + } + let literal = + typecheck::parse_integral_literal(text).ok_or("integral constraint literal")?; + if literal.width > 64 || literal.mask != num_bigint::BigUint::default() { + return Err("constraint literal wider than 64 bits or containing X/Z".into()); + } + let value = literal.value.to_u64_digits().first().copied().unwrap_or(0); + Typed { + kind: Kind::Leaf(ConstraintExpr::Literal(literal.width as u32, value)), + width: literal.width as u32, + signed: literal.signed, + } + } + ExprKind::Unary { + operator, + expression, + postfix: false, + } if matches!(operator.as_str(), "+" | "-" | "~" | "!") => { + let value = recurse(*expression)?; + if operator == "+" { + return Ok(value); + } + Typed { + width: if operator == "!" { 1 } else { value.width }, + signed: operator != "!" && value.signed, + kind: Kind::Unary(operator.clone(), Box::new(value)), + } + } + ExprKind::Binary { + left, + operator, + right, + } if matches!( + operator.as_str(), + "+" | "-" + | "*" + | "&" + | "|" + | "^" + | "==" + | "!=" + | "<" + | "<=" + | ">" + | ">=" + | "&&" + | "||" + ) => + { + let a = recurse(*left)?; + let b = recurse(*right)?; + let width = a.width.max(b.width); + let signed = a.signed && b.signed; + let logical = matches!(operator.as_str(), "&&" | "||"); + let comparison = + logical || matches!(operator.as_str(), "==" | "!=" | "<" | "<=" | ">" | ">="); + Typed { + width: if comparison { 1 } else { width }, + signed: !comparison && signed, + kind: Kind::Binary(operator.clone(), Box::new(a), Box::new(b)), + } + } + _ => return Err("unsupported scalar constraint expression".into()), + }) + } + expression(id, tree, properties, env, 0).map(|value| emit(value, None)) +} + +impl Class { + pub fn constraint_program(&self) -> Converted { + let mut fields = Vec::new(); + for property in &self.properties { + if property.randc + || property.field.handle.is_some() + || property.field.width > 64 + || property.r#type.is_enum + { + return Err(unsupported( + "constraints currently require scalar non-enum properties without randc", + )); + } + fields.push(Field { + offset: property.field.offset, + width: property.field.width, + random: property.rand, + }); + } + let mut constraints = Vec::new(); + for (_, block) in &self.constraints { + constraints.extend( + block + .as_ref() + .map_err(|reason| unsupported(format!("constraints: {reason}")))? + .clone(), + ); + } + Ok(Program { + fields, + constraints, + }) + } +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 5e446a9caa9..06b9c0a3c8d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -133,32 +133,66 @@ pub(super) fn lower( else_body: Vec::new(), }); body.extend(hook("pre_randomize")); - for property in &class.properties { - if property.constant - || property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none()) - { - continue; - } + if class.has_constraints { + let success = builder.declare("$constraint_success", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(success.clone()), + rhs: classes::object_call( + ObjectOp::Randomize(class.constraint_program()?), + vec![ + Expr::Ident(this.clone()), + Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal("1".into())), + }, + ], + ), + nonblocking: false, + }); body.push(Stmt::If { - condition: Expr::Binary { - left: Box::new(Expr::Binary { - left: Box::new(Expr::Ident(argument.clone())), - op: BinaryOp::Ne, - right: Box::new(Expr::Literal("1".into())), - }), - op: BinaryOp::LogicAnd, - right: Box::new(classes::object_call( - ObjectOp::ModeGet( - property.field.offset, - property.rand || property.randc, - ), - vec![Expr::Ident(this.clone())], - )), - }, - then_body: random_property(&mut builder, property, &this), - else_body: Vec::new(), + condition: Expr::Ident(success), + then_body: Vec::new(), + else_body: vec![ + Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePop, + vec![Expr::Ident(this.clone())], + ))], + else_body: Vec::new(), + }, + Stmt::Return(Some(Expr::Literal("32'sd0".into()))), + ], }); + } else { + for property in &class.properties { + if property.constant + || property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + { + continue; + } + body.push(Stmt::If { + condition: Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1".into())), + }), + op: BinaryOp::LogicAnd, + right: Box::new(classes::object_call( + ObjectOp::ModeGet( + property.field.offset, + property.rand || property.randc, + ), + vec![Expr::Ident(this.clone())], + )), + }, + then_body: random_property(&mut builder, property, &this), + else_body: Vec::new(), + }); + } } body.extend(hook("post_randomize")); body.push(Stmt::If { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 0ee78a1655e..d580fad8947 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -896,6 +896,7 @@ impl ContainerOp { /// frontend needs no class table. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ObjectOp { + Randomize(celox_heap::randomization::Program), Container { op: ContainerOp, layout: ContainerLayout, @@ -955,7 +956,8 @@ impl ObjectOp { match self { Self::Container { op, layout } => op.result_type(*layout), Self::Random | Self::RandomCyclic { .. } => (64, false), - Self::Seed + Self::Randomize(_) + | Self::Seed | Self::Check(_) | Self::ModeSet(_) | Self::ModePush @@ -978,6 +980,7 @@ impl fmt::Display for ObjectOp { Self::Store(_) => "property write", Self::ClassOf => "class query", Self::Random => "object random bits", + Self::Randomize(_) => "constrained object randomization", Self::RandomCyclic { .. } => "object random cyclic index", Self::Seed => "object random seed", Self::Check(_) => "object receiver check", diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index dca17b7b5b6..9d1c6193ed2 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6588,7 +6588,37 @@ fn explicit_output_data_types_default_to_variables() { fn class_randomize_rejects_unsupported_semantics() { for (members, call, expected) in [ ( - "rand int x; constraint c { x == 1; }", + "rand int x; constraint c { if (x) x == 1; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { soft x == 1; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x, y; constraint c { solve x before y; x == y; }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { x inside {[1:3]}; }", + "c.randomize()", + "constraint", + ), + ( + "rand int x; constraint c { (x == 1) -> (x < 3); }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { (x == 1) <-> (x < 3); }", + "c.randomize()", + "constraints", + ), + ( + "rand int x; constraint c { x dist {1 := 2}; }", "c.randomize()", "constraints", ), diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index c6304b223f4..fa2a2e8ecfa 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -345,6 +345,16 @@ records the native-runner result; the case stays enabled on all Celox backends. ## SystemVerilog suite +The scalar class-constraint cases are rejected by Icarus 13.0 because constraint +blocks are unsupported. Verilator 5.052 passes the scalar modes and mixed-width +inheritance cases, but calls `post_randomize` even when ordinary `randomize` +returns failure. IEEE 1800-2023 18.6.3 requires skipping that hook. The focused +`class::constrained_randomize_hooks` assertion stays enabled in Celox and is +excluded only for Verilator. [Recorded diagnostics](verification/repros/sv_scalar_constraints.json) +retain both tool limitations; reproduce with `--include-ignored --filter +class::constrained_randomize`. + + Verilator 5.052 rejects a string variable or string method expression as the `$sscanf` format, requiring a literal instead. IEEE 1800-2023 21.3.4.3 permits string expressions here. Only `scan::sscanf_string_format_expression` is diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 87511f25c91..cd39b6a0903 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1911,3 +1911,94 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "5\n")) + +(case constrained_randomize_scalar + (source "constraints.sv" #" +module Top(output bit done); + class Packet; + rand bit [3:0] x, y; + int limit = 4; + constraint bounds { x < limit; y < 4; x + y == 5; x >= 0; y > 0; x <= 3; } + endclass + Packet p; + int old_x, old_y; + initial begin + p = new; + p.srandom(17); + repeat (8) begin + if (!p.randomize()) $fatal(1, "sat failed"); + if (!(p.x < 4 && p.y < 4 && p.x + p.y == 5)) $fatal(1, "invalid model"); + end + old_x = p.x; old_y = p.y; + p.limit = 1; + if (p.randomize()) $fatal(1, "unsat succeeded"); + if (p.x != old_x || p.y != old_y) $fatal(1, "unsat changed fields"); + p.limit = 4; + p.x = 2; p.y = 3; + if (!p.randomize(null)) $fatal(1, "check-only failed"); + p.y = 0; + if (p.randomize(null)) $fatal(1, "check-only ignored constraints"); + p.x.rand_mode(0); + if (!p.randomize() || p.x != 2 || p.y != 3) $fatal(1, "disabled rand is not state"); + p.y = 1; + if (p.randomize(x)) $fatal(1, "selection should be unsat"); + if (p.x.rand_mode() != 0 || p.y.rand_mode() != 1) $fatal(1, "failed selection leaked modes"); + p.y = 3; + if (!p.randomize() || p.x != 2) $fatal(1, "modes not restored"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_width_and_inheritance + (source "constraint_widths.sv" #" +module Top(output bit done); + class Base; + rand bit signed [7:0] a; + rand bit signed [15:0] b; + rand bit [31:0] c; + constraint values { a == -1; b == 1; c == 256; } + constraint sum { (a + b) == c; } + endclass + class Derived extends Base; + constraint values { a == -2; b == 2; c == 256; } + endclass + Base p; + Derived q; + initial begin + p = new; + if (!p.randomize()) $fatal(1, "unsigned context was lost"); + if (p.a != -1 || p.b != 1 || p.c != 256) $fatal(1, "base values"); + q = new; + p = q; + if (!p.randomize()) $fatal(1, "derived constraints were not dispatched"); + if (q.a != -2 || q.b != 2 || q.c != 256) $fatal(1, "override values"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_hooks + (source "constraint_hooks.sv" #" +module Top(output bit done); + class Packet; + rand int x; + int limit, before_count, after_count; + constraint bounds { x == limit; x < 3; } + function void pre_randomize(); before_count++; limit = before_count; endfunction + function void post_randomize(); after_count++; endfunction + endclass + Packet p; + initial begin + p = new; + if (!p.randomize() || p.x != 1) $fatal(1, "first pre state"); + if (!p.randomize() || p.x != 2) $fatal(1, "second pre state"); + if (p.randomize() || p.x != 2) $fatal(1, "unsat changed fields"); + if (p.before_count != 3 || p.after_count != 2) $fatal(1, "post called on failure"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json b/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json new file mode 100644 index 00000000000..fdbb8d899b8 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scalar_constraints.json @@ -0,0 +1,33 @@ +{ + "specification": "IEEE 1800-2023 18.5, 18.6.3", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "case": "class::constrained_randomize_hooks", + "status": "runtime_error", + "log": "%Warning-UNSATCONSTR: /source_0.sv:6: Unsatisfied constraint: 'constraint bounds { x == limit; x < 3; }'\n%Warning-UNSATCONSTR: /source_0.sv:6: Unsatisfied constraint: 'constraint bounds { x == limit; x < 3; }'\n[0] %Fatal: source_0.sv:16: Assertion failed in TOP.celox_suite_tb.dut: post called on failure\n%Error: /source_0.sv:16: Verilog $stop\nAborting...\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_hooks", + "status": "compile_error", + "log": "/source_0.sv:6: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_scalar", + "status": "compile_error", + "log": "/source_0.sv:6: sorry: Constraint declarations not supported.\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "case": "class::constrained_randomize_width_and_inheritance", + "status": "compile_error", + "log": "/source_0.sv:7: sorry: Constraint declarations not supported.\n/source_0.sv:8: sorry: Constraint declarations not supported.\n/source_0.sv:11: sorry: Constraint declarations not supported.\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 693a8141fb0..6aee7194ef9 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -184,6 +184,75 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_hooks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_scalar", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [] + }, + "name": "class::constrained_randomize_width_and_inheritance", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 6c53e1025bc..0ddd3479670 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2578,5 +2578,41 @@ "scan::sscanf_string_format_expression" ] } + }, + { + "id": "sv_icarus_scalar_constraints", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::constrained_randomize_scalar", + "class::constrained_randomize_width_and_inheritance", + "class::constrained_randomize_hooks" + ] + } + }, + { + "id": "sv_verilator_post_randomize_unsat", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::constrained_randomize_hooks" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index ceb08b51dc7..d576761f5c8 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -101,6 +101,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_post_randomize_unsat", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "upstream": [] + }, + "name": "class::constrained_randomize_hooks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-testbench/src/format.rs b/crates/celox-testbench/src/format.rs index 5aa0e3b0c7b..cff68d2b959 100644 --- a/crates/celox-testbench/src/format.rs +++ b/crates/celox-testbench/src/format.rs @@ -720,7 +720,7 @@ mod tests { is_string: false, float_precision: None, }; - assert_eq!(format_sized_display_arg(&arg, 's', Some(0)), []); + assert!(format_sized_display_arg(&arg, 's', Some(0)).is_empty()); } fn sized(value: u32, width: usize, signed: bool, spec: char, field: Option) -> String { diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index b3243686b6b..22d5d034586 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -381,7 +381,7 @@ sv_backends! { } sv_backends! { - fn class_randomize_rejects_dynamic_base_handle(sim) { + fn class_randomize_rejects_unsupported_dynamic_constraints(sim) { @setup { let source = r#"module Top(output int value, hooks, result); class Base; @@ -391,7 +391,7 @@ sv_backends! { function void post_randomize(); calls++; endfunction endclass class Derived extends Base; - constraint c { x == 1; } + constraint c { x dist {1 := 2}; } endclass Base b; Derived d; @@ -923,3 +923,12 @@ sv_backends! { assert_eq!(sim.get_four_state(value), expected); } } + +sv_backends! { + fn constrained_randomize_scalar(sim) { @case "class::constrained_randomize_scalar"; } + fn constrained_randomize_width_and_inheritance(sim) { @case "class::constrained_randomize_width_and_inheritance"; } +} + +sv_backends! { + fn constrained_randomize_hooks(sim) { @case "class::constrained_randomize_hooks"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ea7c9387bfb..4cf3e16b95a 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -200,8 +200,8 @@ including supported properties not declared `rand`. Names are resolved in the receiver's class, not the caller's scope; expressions and inaccessible members are rejected. The temporary modes are installed before the pre-hook and restored after the post-hook; hooks can inspect and change them. `randomize(null)` runs -the hooks without drawing or assigning random values (18.11). Constraints are -not supported even for this checker form. +the pre-hook and checks constraints without drawing or assigning random values; +the post-hook runs only on success (18.11). Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both @@ -212,9 +212,21 @@ members. Each property visits every value once before starting another cycle Disabled properties retain their cycle; checkpoints restore it. `srandom` reseeds the RNG without making already consumed values eligible again. -Constraints, `with`, larger `randc` domains, static random properties, and random -array/object/string properties remain unsupported. A constrained dynamic -subclass is rejected rather than silently randomizing only its base properties. +Named constraint blocks support 1–64-bit two-state scalar integer properties, +comparisons, logical and bitwise operations, addition, subtraction and multiplication. +Inherited blocks apply, and a derived block with the same name replaces its base +block. Disabled and unselected properties are state inputs read after the pre-hook. +Aplite searches for a satisfying assignment using the object's seed, then updates +all selected properties together. Proved infeasibility returns `0`, preserves the +properties and skips the post-hook (18.6.3). Resource exhaustion is a runtime error. +This initial seeded-search policy does not guarantee a uniform distribution; +distribution improvements are tracked in [#2187](https://github.com/celox-sim/celox/issues/2187). + +Constrained enums and `randc`, `inside`, conditional/foreach/soft constraints, +`dist`, `solve before`, constraint modes, external/static blocks, typed parameters +in constraints, and inline `with` remain unsupported. Larger unconstrained `randc` +domains, static random properties and random array/object/string properties also +remain unsupported. Unsupported dynamic subclasses are rejected before draws. A call through `null` is a runtime error. ### Time literal delays {#time-literal-delays} diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 439ea865291..6c0507119d2 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -125,8 +125,8 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や `object.randomize(x, y)` はその呼び出しに限り対象を指定します。対応型なら `rand` でない プロパティも指定できます。名前は呼び出し元ではなくreceiverのクラスで解決し、式やアクセス権のない メンバーは拒否します。一時モードはpreフックの前に設定し、postフックの後に復元します。 -フックから一時モードを参照・変更できます。`randomize(null)` は乱数生成や代入を行わずフックを -呼びます(18.11)。この形式でも制約付きクラスは未対応です。 +フックから一時モードを参照・変更できます。`randomize(null)` はpreフックの後、乱数生成や +代入を行わず制約を検査し、成功時だけpostフックを呼びます(18.11)。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します @@ -136,8 +136,17 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や `rand_mode`、引数による対象選択とチェックポイント復元にも対応します。無効化中は 循環を進めず、`srandom` は消費済みの値を保持したまま乱数生成器を再シードします。 -制約、`with`、上記の上限を超える `randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の -乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 +名前付き制約ブロックは、1〜64ビットの2値整数プロパティに対する比較、論理・ビット演算、 +加減乗算に対応します。親の制約を継承し、子クラスの同名ブロックで置き換えられます。 +無効化・選択対象外のプロパティはpreフック後の状態値として扱います。Apliteがオブジェクトの +seedを使って解を探索し、成功時だけ対象プロパティをまとめて更新します。解なしが確定した場合は +値を保持して`0`を返し、postフックを呼びません(18.6.3)。探索予算切れは実行時エラーです。 +この初期実装は一様分布を保証しません。分布の改善は[#2187](https://github.com/celox-sim/celox/issues/2187)で追跡します。 + +制約付きenum・`randc`、`inside`、条件付き・foreach・soft制約、`dist`、`solve before`、 +制約モード、外部・static制約ブロック、制約中の型付きパラメーター、inline `with` は未対応です。 +上記の上限を超える制約なし`randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の +乱数化も未対応です。未対応の子クラスは乱数生成前に拒否します。 `null` を通した呼び出しは実行時エラーです。 ### 時間リテラルによる遅延 {#time-literal-delays} diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 3e343ee2a67..a97b9d17302 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -42,7 +42,6 @@ const RELEASE_PLEASE_FILES = new Set([ // dependencies of celox-napi. ci-changes.test.mjs checks the workspace graph // so adding a dependency cannot silently make this exclusion unsafe. const RUST_ONLY_CRATES = new Set([ - "aplite", "celox-test-suite", "celox-bench", "celox-bench-sv", @@ -309,8 +308,8 @@ if ( // Lydite core tests run independently; bridge CI is disabled. export function celoxRustTestScope(files, packages) { return rustTestScope( - files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/(?:lydite(?:-|\/)|aplite\/))/.test(path)), - packages.filter((pkg) => !/^(?:lydite(?:-|$)|aplite$)/.test(pkg.name)), + files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/lydite(?:-|\/))/.test(path)), + packages.filter((pkg) => !/^lydite(?:-|$)/.test(pkg.name)), ); } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 42b42f7e884..0c856295b91 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -56,7 +56,6 @@ test("Rust test infrastructure skips bindings while retaining Rust checks", () = "crates/celox-bench-sv/src/main.rs", "crates/celox-vpi/src/lib.rs", "crates/celox-wasm/src/lib.rs", - "crates/aplite/src/lib.rs", "crates/lydite/src/lib.rs", "crates/lydite-ir/src/lib.rs", "crates/lydite-solver/src/lib.rs", @@ -355,6 +354,14 @@ test("Rust changes exercise native builds and JavaScript bindings", () => { }); }); +test("Aplite runtime changes exercise native builds and JavaScript bindings", () => { + assert.deepEqual(classifyFiles(["crates/aplite/src/finite.rs"]), { + ...all, + docs: false, + scripts: false, + }); +}); + test("test runner configuration changes exercise Rust", () => { assert.deepEqual(classifyFiles([".config/nextest.toml"]), { ...all, diff --git a/scripts/ci-lydite-changes.test.mjs b/scripts/ci-lydite-changes.test.mjs index 2a31c7d37f1..6a153af2a8e 100644 --- a/scripts/ci-lydite-changes.test.mjs +++ b/scripts/ci-lydite-changes.test.mjs @@ -313,8 +313,11 @@ test("normal CI and standalone core conformance never build the bridge", () => { }); // The extracted solver is tested directly as well as through its proof consumers. -test("Aplite runs its own tests in the Lydite lane", () => { +test("Aplite changes test both proof and simulation consumers", () => { const workflow = readFileSync(new URL("../.github/workflows/lydite-checks.yml", import.meta.url), "utf8"); assert.match(workflow, /cargo test --locked .* -p aplite/); - assert.deepEqual(celoxRustTestScope(["crates/aplite/src/finite.rs"], packages).packages ?? [], []); + const selected = celoxRustTestScope(["crates/aplite/src/finite.rs"], packages).packages; + for (const name of ["aplite", "celox-heap", "celox", "celox-napi"]) + assert.ok(selected.includes(name), name); + assert.ok(selected.every(name => !isLydite(name))); }); diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 890afaef325..d57887307df 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -18,6 +18,7 @@ fi crates=( celox-sv-syntax celox-design + celox-heap celox-sv-analyzer celox-test-suite celox-analysis @@ -25,7 +26,6 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen - celox-heap celox-testbench celox-sir celox-state-layout diff --git a/scripts/publish-crates.test.mjs b/scripts/publish-crates.test.mjs index 9e8025385eb..7fadfe12418 100644 --- a/scripts/publish-crates.test.mjs +++ b/scripts/publish-crates.test.mjs @@ -120,6 +120,12 @@ test("publication order includes every public crate after its workspace dependen for (const [index, name] of order.entries()) { for (const dependency of packages.get(name).dependencies) { if (!dependency.path) continue; + // Aplite has an independent release train and must already be available + // on crates.io before publishing a Celox version that depends on it. + if (dependency.name === "aplite") { + assert.equal(dependency.req, `^${packages.get("aplite").version}`); + continue; + } const dependencyIndex = order.indexOf(dependency.name); assert.ok( dependencyIndex >= 0 && dependencyIndex < index, From 3d9c4a3825ec21f379081802dad512b275a771a0 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 04:09:24 +0900 Subject: [PATCH 5/7] feat(sv)!: support unindexed interface array value parameters Taxi uses references such as m_axi_rd.ID_W and m_axis.DATA_W without selecting an interface-array element. Add interface_array_parameter=warn|allow compatibility handling that reads the value parameter from the first element in declaration order, including nonzero bounds. The default remains error under IEEE 1800-2023 23.6. Keep signal and type-parameter references indexed. Preserve the selected parameter's value, width and signedness, lexical shadowing, indexed generate prefixes, and a located diagnostic. The existing CLI diagnostic override and celox.toml diagnostics table both select this behavior. No whole-array uniformity requirement is added. Validation covers 5,700 SystemVerilog/diagnostic tests (20 existing skips), 838 analyzer and 8 frontend unit tests (3 existing ignored), and 2 doctests, affected clippy with warnings denied, formatting and diff checks. Three original unmodified Taxi representative configurations passed their complete cocotb modules in the combined implementation snapshot: 33 tests passed and one upstream test skipped. This is not a full Taxi parameter-matrix result. A Verilator 5.052 execution probe confirmed the unindexed reference reads the actual parameter override. BREAKING CHANGE: public AnalyzerWarning and FrontendWarningKind gain InterfaceArrayParameter variants; downstream exhaustive Rust matches must handle the new diagnostic. Change-Id: Idf34f3eba2c1cecce3e66d17da569518cb05cb3b --- crates/celox-frontend-sv/src/warning.rs | 19 ++++++ .../src/ast/expression_binding/direct.rs | 14 ++++ .../src/ast/interface_binding.rs | 37 ++++++++++ crates/celox-sv-analyzer/src/ast/warnings.rs | 6 ++ crates/celox/src/diagnostic_policy.rs | 1 + crates/celox/tests/diagnostic_policy.rs | 68 +++++++++++++++++++ .../frontends/systemverilog/interfaces.rs | 38 +++++++++++ docs/guide/celox-toml.md | 8 +++ 8 files changed, 191 insertions(+) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 4d5752d35ce..9bdc2f46418 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -42,6 +42,10 @@ pub enum FrontendWarningKind { MixedTimescale, #[error("`$size` on an interface array is a language extension")] InterfaceArrayQuery, + #[error( + "unindexed interface array parameter `{path}` uses the first declared element `{element}`" + )] + InterfaceArrayParameter { path: String, element: String }, /// IEEE 1800-2023 9.2.2.4 restricts writes by other processes. #[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")] MultipleAlwaysFfDrivers { module: String, signal: String }, @@ -101,6 +105,17 @@ pub(crate) fn analyzer_warnings( celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayQuery { site } => { (FrontendWarningKind::InterfaceArrayQuery, site.clone()) } + celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayParameter { + path, + element, + site, + } => ( + FrontendWarningKind::InterfaceArrayParameter { + path: path.clone(), + element: element.clone(), + }, + site.clone(), + ), celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => { (FrontendWarningKind::MixedTimescale, None) } @@ -155,6 +170,7 @@ impl miette::Diagnostic for FrontendWarning { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", FrontendWarningKind::InterfaceArrayQuery => "interface_array_query", + FrontendWarningKind::InterfaceArrayParameter { .. } => "interface_array_parameter", FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers", FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::InferredLatch => "inferred_latch", @@ -175,6 +191,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::InterfaceArrayQuery => { "interface arrays are not data arrays in IEEE 1800-2023 20.7; set interface_array_query=warn or allow for compatibility" } + FrontendWarningKind::InterfaceArrayParameter { .. } => { + "IEEE 1800-2023 23.6 requires an instance select before a member; set interface_array_parameter=warn or allow to use the first declared element" + } FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index c7416bb7102..0b759a45053 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1389,6 +1389,7 @@ fn path( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted<(Vec, Option)> { + let authored = root; // A static class property is a variable of the module. if let Some(variable) = objects::static_property(tree, root, native, dimensions)? { return Ok((vec![variable], None)); @@ -1426,12 +1427,25 @@ fn path( let last = prefix.last_mut().ok_or_else(disagreement)?; last.push_str(&format!("[{value}]")); prefix.extend(parts.into_iter().rev()); + if base.is_none() + && let Some(name) = + interface_binding::unindexed_parameter(&prefix, tree, dimensions, authored) + { + return Ok((vec![name], None)); + } return Ok((prefix, base)); } _ => return Err(unsupported("member receiver")), } } parts.reverse(); + if qualified.is_none() + && let Some(name) = + interface_binding::unindexed_parameter(&parts, tree, dimensions, authored) + { + return Ok((vec![name], None)); + } + if let Some(length) = qualified { if parts.len() == length + 1 { let base = parts[..2].join("::"); diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 5b2ec074539..da526c4c675 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -33,6 +33,43 @@ pub(super) struct ArrayBinding { pub ranges: Vec<(i128, i128)>, } +/// Compatibility shorthand for an unindexed interface-array value parameter. +/// Follow the first element in declaration order, including nonzero bounds. +/// Runtime members and type parameters retain their ordinary indexed lookup. +pub(super) fn unindexed_parameter( + path: &[String], + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + root: celox_sv_syntax::ExprId, +) -> Option { + let (member, handle) = path.split_last()?; + let root_name = handle.first()?; + if dimensions.get(root_name).is_some() + || dimensions.const_env.contains_key(root_name) + || dimensions.parameter_values.contains_key(root_name) + { + return None; + } + let imported = scope::imported(&tree.state); + let array = imported.interface_arrays.get(&handle.join("."))?; + let element = array.elements.first()?; + let bound = imported + .interface_members + .get(&format!("{element}.{member}"))?; + if !imported.parameter_values.contains_key(bound) { + return None; + } + warnings::append( + &mut tree.state.diagnostics.borrow_mut(), + [warnings::AnalyzerWarning::InterfaceArrayParameter { + path: path.join("."), + element: element.clone(), + site: procedural::source_span(tree.declarations().expression(root).tokens, tree), + }], + ); + Some(bound.clone()) +} + pub(super) fn analyze_module( tree: &AnalysisContext<'_>, path: &Path, diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index c4924e34220..9d5372e82b8 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -10,6 +10,12 @@ pub enum AnalyzerWarning { MixedTimescale, /// `$size` on an interface array is a compatibility extension to 20.7. InterfaceArrayQuery { site: Option }, + /// Omitted interface array selections are an extension to 23.6. + InterfaceArrayParameter { + path: String, + element: String, + site: Option, + }, /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). ExitOutsideProgram { site: Option }, } diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index dc58a639307..d00d5e69359 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -86,6 +86,7 @@ impl DiagnosticPolicy { code, "mixed_timescale" | "interface_array_query" + | "interface_array_parameter" | "unpacked_port_default" | "multiple_always_ff_drivers" | "inferred_latch" diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index ffbc6bc5658..8896d12923a 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -734,3 +734,71 @@ fn invalid_interface_array_query_dimensions_return_integer_unknowns() { ); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_array_parameters_have_a_located_recoverable_diagnostic() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=8); logic [WIDTH-1:0] v; endinterface + module Top(output wire [31:0] q); Bus #(13) bus[5:4](); assign q=bus.WIDTH; endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, Path::new("array_parameter.sv"))], "Top"); + let error = build().build_cranelift().err().unwrap(); + assert!( + matches!(error.kind(), SimulatorErrorKind::DiagnosticPolicy(_)), + "{error}" + ); + assert!( + error.to_string().contains("interface_array_parameter"), + "{error}" + ); + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let mut sim = build() + .diagnostic_policy(policy("interface_array_parameter", level)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 13u8.into()); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + if let Some(warning) = sim.warnings().first() { + let rendered = celox::render_diagnostic(warning); + assert!(rendered.contains("array_parameter.sv"), "{rendered}"); + assert!(rendered.contains("bus[5]"), "{rendered}"); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_parameter_lookup_respects_lexical_shadowing() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=13); endinterface + module Top(output wire [31:0] q); + Bus bus[2](); + typedef struct packed {logic [7:0] WIDTH;} Word; + function automatic int f(input Word bus); return bus.WIDTH; endfunction + localparam VALUE=f(8'd42); assign q=VALUE; endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("shadowed_bus.sv"))], "Top") + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 42u8.into()); + assert!(sim.warnings().is_empty()); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn unindexed_interface_parameters_resolve_inside_indexed_generate_paths() { + use std::path::Path; + let source = "interface Bus #(parameter WIDTH=8); endinterface + module Top(output wire [31:0] q); + for(genvar i=0;i<2;i=i+1) begin:g Bus #(10+i) bus[5:4](); end + assign q=g[1].bus.WIDTH; endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("generated_bus.sv"))], "Top") + .diagnostic_policy(policy("interface_array_parameter", DiagnosticLevel::Warn)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("q")), 11u8.into()); + assert_eq!(sim.warnings().len(), 1); +} diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index bd1bc1737c5..984d742005a 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -280,3 +280,41 @@ fn rejects_interface_array_slices_in_multiple_dimensions() { "{error}" ); } + +// The unindexed value-parameter shorthand is an explicit compatibility mode. +sv_backends! { + fn unindexed_interface_array_parameters_preserve_bound_values_and_types(sim) { + @setup { + let source = "interface Bus #(parameter int WIDTH=8, parameter logic signed [7:0] NEG=-3); + logic [WIDTH-1:0] data; modport sink(input data); endinterface + module Child(Bus.sink bus[5:4], output wire [31:0] q, n); + function automatic int width_value(); return bus.WIDTH; endfunction + localparam W=width_value(); + assign q=W; + assign n=bus.NEG; + endmodule + module Top(output wire [31:0] q,n); + Bus #(13,-5) buses[5:4](); Child dut(buses,q,n); + endmodule"; + let mut policy=celox::DiagnosticPolicy::default(); + policy.set("interface_array_parameter",celox::DiagnosticLevel::Allow); + } + @build Simulator::from_sv_sources(vec![(source,Path::new("array_parameter_types.sv"))],"Top").diagnostic_policy(policy); + assert_eq!(sim.get(sim.signal("q")),BigUint::from(13u8)); + assert_eq!(sim.get(sim.signal("n")),BigUint::from(0xfffffffbu32)); + } +} + +#[test] +fn interface_array_parameter_shorthand_does_not_bind_runtime_members() { + let source = "interface Bus #(parameter WIDTH=8); logic [WIDTH-1:0] data; endinterface + module Top(output wire [7:0] q); Bus bus[2](); assign q=bus.data; endmodule"; + let mut policy = celox::DiagnosticPolicy::default(); + policy.set("interface_array_parameter", celox::DiagnosticLevel::Allow); + let error = Simulator::from_sv_sources(vec![(source, Path::new("array_signal.sv"))], "Top") + .diagnostic_policy(policy) + .build_cranelift() + .err() + .unwrap(); + assert!(error.to_string().contains("bus.data"), "{error}"); +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 3b54313138e..5a8c51d7b07 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -183,6 +183,14 @@ interface_array_query = "warn" The CLI uses the same policy: `celox run top.sv --top Top --diagnostic interface_array_query=warn`. +`interface_array_parameter` also defaults to `error`. Set it to `warn` or `allow` +for the compatibility shorthand `bus.WIDTH` when `bus` is an interface array. +It reads the value parameter from the first element in declaration order, +including arrays with nonzero bounds. Signals and type parameters still require +an explicit element selection. The same setting works in `[diagnostics]` and +with `--diagnostic interface_array_parameter=warn`. + + `multiple_always_ff_drivers` defaults to `error` for shared memories written by an `always_ff` and another edge process (IEEE 1800-2023 §9.2.2.4). With `warn` or `allow`, Celox stages their nonblocking writes in sparse next-state storage From 2042895ab873f89be4d7059232f791c3d76e7300 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 04:11:46 +0900 Subject: [PATCH 6/7] perf(x86): validate wide values at mutation boundaries Debug ISel scanned the entire growing wide-value map after every instruction. Large process functions consequently repeated the same invariant checks quadratically. Validate the changed entry in set_wide_chunks, the only insertion path, and scan the complete map once before extracting it for phi construction. Retain all width and chunk-count invariants. Release behavior, HDL optimization levels and generated instruction selection are unchanged. Add a debug-only 128-value regression that counts invariant checks rather than asserting wall-clock time. Validation covers 620 x86 crate tests and 5,700 SystemVerilog/diagnostic tests (20 existing skips), affected clippy with warnings denied, formatting and diff checks. Full VCU108 and HTG9200 compiles still exceeded 300 seconds in the implementation snapshot: this removes a quadratic debug check but does not claim to resolve the board-level timeout or demonstrate an end-to-end speedup. Change-Id: Ief6ae9750c629821b5b52b0e8e7a30ae89b7e545 --- .../src/backend/native/isel.rs | 64 ++++++++++++------- .../src/backend/native/isel/tests/wide.rs | 41 ++++++++++++ 2 files changed, 81 insertions(+), 24 deletions(-) diff --git a/crates/celox-backend-x86/src/backend/native/isel.rs b/crates/celox-backend-x86/src/backend/native/isel.rs index e4da6840d2a..798f1615f56 100644 --- a/crates/celox-backend-x86/src/backend/native/isel.rs +++ b/crates/celox-backend-x86/src/backend/native/isel.rs @@ -1480,10 +1480,6 @@ pub fn lower_execution_unit_with_diagnostics( sparse_write_states.metadata_action(sir_block_id, inst_idx), ); } - if cfg!(debug_assertions) { - ctx.verify_wide_values(); - } - // Track known bit width for redundant mask elimination. let dst_reg = inst.defined_register(); if let Some(dr) = dst_reg { @@ -1563,6 +1559,12 @@ pub fn lower_execution_unit_with_diagnostics( // Extract mask_map for phi node construction (ctx borrows func fields) let saved_mask_map = std::mem::replace(&mut ctx.mask_map, RegMap::new(0)); + // Each mutation validates its own entry. Scan the whole map once at + // the boundary rather than once per instruction, which is quadratic in + // large functions with many wide values. + if cfg!(debug_assertions) { + ctx.verify_wide_values(); + } let saved_wide_regs = std::mem::take(&mut ctx.wide_regs); let saved_wide_masks = std::mem::take(&mut ctx.wide_masks); drop(ctx); // Release borrows on func @@ -1758,6 +1760,11 @@ type WideMaskMap = crate::HashMap>; /// Tracks known constant values for SIR registers (for constant folding in ISel). type ConstMap = crate::HashMap; +#[cfg(test)] +thread_local! { + static WIDE_VALUE_VERIFICATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + struct ISelContext<'a> { vregs: &'a mut VRegAllocator, spill_descs: &'a mut Vec, @@ -2193,6 +2200,9 @@ impl<'a> ISelContext<'a> { if width <= 64 { self.wide_regs.remove(®); } else { + if cfg!(debug_assertions) { + self.verify_wide_value(®, &chunks); + } self.wide_regs.replace(reg, chunks); } } @@ -2244,28 +2254,34 @@ impl<'a> ISelContext<'a> { /// this map through a direct insertion. fn verify_wide_values(&self) { for (reg, chunks) in self.wide_regs.iter() { - let width = self.sir_width(reg); - assert!( - width > 64, - "narrow SIR register r{} has a wide native representation (width={width})", - reg.0 - ); - let expected_chunks = Self::num_chunks(width); + self.verify_wide_value(reg, chunks); + } + } + + fn verify_wide_value(&self, reg: &RegisterId, chunks: &[(VReg, usize)]) { + #[cfg(test)] + WIDE_VALUE_VERIFICATIONS.with(|count| count.set(count.get() + 1)); + let width = self.sir_width(reg); + assert!( + width > 64, + "narrow SIR register r{} has a wide native representation (width={width})", + reg.0 + ); + let expected_chunks = Self::num_chunks(width); + assert_eq!( + chunks.len(), + expected_chunks, + "wide SIR register r{} has {} chunks, expected {expected_chunks}", + reg.0, + chunks.len() + ); + for (index, (_, chunk_width)) in chunks.iter().enumerate() { + let expected_width = width.saturating_sub(index * 64).min(64); assert_eq!( - chunks.len(), - expected_chunks, - "wide SIR register r{} has {} chunks, expected {expected_chunks}", - reg.0, - chunks.len() + *chunk_width, expected_width, + "wide SIR register r{} chunk {index} has width {chunk_width}, expected {expected_width}", + reg.0 ); - for (index, (_, chunk_width)) in chunks.iter().enumerate() { - let expected_width = width.saturating_sub(index * 64).min(64); - assert_eq!( - *chunk_width, expected_width, - "wide SIR register r{} chunk {index} has width {chunk_width}, expected {expected_width}", - reg.0 - ); - } } } diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 3f94d1bda99..e1b98ebefce 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -1463,3 +1463,44 @@ fn widened_zero_compares_equal_to_a_zero_wide_load() { assert_eq!(state[output_offset] & 1, 1, "four_state={four_state}"); } } + +#[cfg(debug_assertions)] +#[test] +fn wide_value_invariant_validation_scales_with_values() { + const COUNT: usize = 128; + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: (0..COUNT) + .map(|i| { + SIRInstruction::Imm( + RegisterId(i), + SIRValue::new_four_state(BigUint::from(i), BigUint::default()), + ) + }) + .collect(), + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: (0..COUNT) + .map(|i| (RegisterId(i), RegisterType::Logic { width: 65 })) + .collect(), + }; + WIDE_VALUE_VERIFICATIONS.with(|count| count.set(0)); + let _ = lower_execution_unit(&unit, &empty_layout(), false); + let checks = WIDE_VALUE_VERIFICATIONS.with(|count| count.get()); + assert!( + checks >= COUNT, + "the invariant must still be checked: {checks}" + ); + assert!( + checks <= 2 * COUNT, + "repeated whole-map validation: {checks}" + ); +} From acfcf7594b184a3f88ed5b5f53a8a10f17311ac2 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 05:18:48 +0900 Subject: [PATCH 7/7] ci(mergify): add queue priority without interrupting checks Add merge-priority for requests that should pass waiting ordinary PRs while allowing running checks to finish. Assign priority 9000 with interruption disabled, below merge-urgent's 10000 and above lightweight changes. The first matching rule makes merge-urgent win when both labels are present. Both labels use the same guarded merge-ready authorization, preserving required checks, holds, conflicts, drafts, and the dequeue latch. Document their distinct behavior and withdrawal procedure. The merge-priority repository label has been created; its queue behavior activates after this configuration is merged. Validation: mergify config validate; 38 Mergify and CI-classifier tests passed; git diff --check. No PR was queued or merged for validation. Change-Id: Ib8ed2198d9309dc9f530a37264d5418a8092c40d --- .mergify.yml | 12 ++++++++++-- CONTRIBUTING.md | 27 ++++++++++++++++----------- scripts/mergify.test.mjs | 18 ++++++++++++++++-- 3 files changed, 42 insertions(+), 15 deletions(-) diff --git a/.mergify.yml b/.mergify.yml index 17116d77903..10d2798f7ee 100644 --- a/.mergify.yml +++ b/.mergify.yml @@ -55,6 +55,12 @@ priority_rules: priority: 10000 allow_checks_interruption: true + - name: Priority merges without interruption + conditions: + - label = merge-priority + priority: 9000 + allow_checks_interruption: false + - name: Lightweight validated changes first conditions: - check-success = Lint & Format @@ -160,7 +166,7 @@ queue_rules: # rulesets. Keep those rules enforced by GitHub; Mergify gets no bypass. pull_request_rules: - - name: Authorize emergency merge requests + - name: Authorize prioritized merge requests conditions: - or: - base ~= ^(master|develop)$ @@ -169,7 +175,9 @@ pull_request_rules: - and: - base ~= ^stack/ - 'body ~= (?m)^Depends-On: ' - - label = merge-urgent + - or: + - label = merge-urgent + - label = merge-priority - -label = release:hold - -label = dequeued - -draft diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f2133eecae7..def9181d534 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -435,20 +435,25 @@ regressions and manual scaling measurements are not made passing by blindly running every `#[ignore]` test. New exclusions need a concrete reason and evidence; an unexpected failure must not become a skip. -## Emergency merge priority +## Merge priority labels -Apply `merge-urgent` to request an emergency merge. Mergify adds `merge-ready` -and gives the PR priority 10000, ahead of the normal and lightweight priorities. -It may interrupt lower-priority queue checks to test the urgent PR first; use -this only when the urgency justifies restarting that work. Existing queue -categories and batching still apply, as do stack dependency ordering and all -required checks. This is priority, not permission to merge failing CI. +Both labels add `merge-ready` and request normal queue admission: + +| Label | Priority | Running lower-priority checks | +| --- | --- | --- | +| `merge-priority` | 9000 | Finish first; this PR goes ahead of waiting ordinary PRs | +| `merge-urgent` | 10000 | May be interrupted to test this PR first | + +Both outrank normal and lightweight priorities. If both labels are present, +`merge-urgent` wins. Reserve it for emergencies that justify restarting checks. +Existing queue categories, batching, stack dependency ordering, and all required +checks still apply. These labels do not permit merging failing CI. Drafts, conflicts, `release:hold`, and `dequeued` still block automatic admission. -After addressing a dequeue's cause, remove `dequeued` to retry. Removing -`merge-urgent` restores normal priority; remove `merge-ready` and explicitly +After addressing a dequeue's cause, remove `dequeued` to retry. Remove both +priority labels to restore normal priority; remove `merge-ready` and explicitly dequeue as usual to withdraw the merge request entirely. The generated `merge-ready` label also activates the existing release-PR freeze mechanism. -The label works after this configuration reaches the PR's base branch. Creating -or applying the label alone does not install the queue policy. +Each label's behavior works after its configuration reaches the PR's base +branch. Creating or applying a label alone does not install the queue policy. diff --git a/scripts/mergify.test.mjs b/scripts/mergify.test.mjs index a00fad46d1e..1c23ef340e9 100644 --- a/scripts/mergify.test.mjs +++ b/scripts/mergify.test.mjs @@ -198,14 +198,14 @@ test("lightweight queue priority requires actual skipped product checks and succ test("emergency labels authorize normal admission and outrank lightweight checks", () => { const priorities = queueConfig.split("priority_rules:\n")[1].split("queue_rules:\n")[0]; - const emergency = priorities.split(" - name: Lightweight validated changes first")[0]; + const emergency = priorities.split(" - name: Priority merges without interruption")[0]; assert.match(emergency, /name: Emergency merges first/); assert.match(emergency, /conditions:\n - label = merge-urgent/); assert.match(emergency, /priority: 10000/); assert.match(emergency, /allow_checks_interruption: true/); const admission = queueConfig.split("pull_request_rules:\n")[1]; const authorize = admission.split(" - name: Queue explicitly requested merges")[0]; - assert.match(authorize, /label = merge-urgent/); + assert.match(authorize, /- or:\n - label = merge-urgent\n - label = merge-priority/); assert.match(authorize, /actions:\n label:\n add:\n - merge-ready/); for (const guard of ["-label = release:hold", "-label = dequeued", "-draft", "-conflict"]) assert.ok(authorize.includes(` - ${guard}`), guard); @@ -214,3 +214,17 @@ test("emergency labels authorize normal admission and outrank lightweight checks assert.match(authorize, /Depends-On:/); assert.doesNotMatch(authorize, /queue:|merge:|remove:/); }); + + +test("priority requests pass waiting work without interrupting running checks", () => { + const rules = queueConfig.split("priority_rules:\n")[1].split("queue_rules:\n")[0] + .split(/^ - name: /m).slice(1); + assert.equal(rules.length, 3); + assert.match(rules[0], /^Emergency merges first/); + assert.match(rules[1], /^Priority merges without interruption/); + assert.match(rules[1], /conditions:\n - label = merge-priority/); + assert.match(rules[1], /priority: 9000/); + assert.match(rules[1], /allow_checks_interruption: false/); + assert.doesNotMatch(rules[1], /check-success|check-skipped/); + assert.match(rules[2], /^Lightweight validated changes first/); +});