From 571727cc54630089868d90ba1731450db769a8fc Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:22:47 +0900 Subject: [PATCH 1/7] fix(sv): allow bare zero-argument container methods Calls such as q.size, q.pop_front and map.delete now bind through the same argument and void-result checks as their parenthesized forms. Handle void-cast statements that discard pop results, including string and class handles. Preserve the declared element type when querying an integral pop result, including packed rank and authored bounds. Type queries validate without executing the pop. Reject unsupported queries on nonintegral pop results instead of treating string/class handles as packed integer values. The upstream queue and associative examples are narrow: all 28 initially selected official case/mode checks passed while a packed-result query still failed on every Celox backend. Add that counterexample alongside ordinary, four-state/default, side-effect, discarded-return and required-argument checks. The fixed packed-result case also passes Verilator. The official runner checked 36 pinned upstream cases containing bare method names in both state modes (72 verdicts). Sixteen simulation cases improve from fail to pass in both modes, including associative allocation and nonexistent reads beyond the initial selection. Update exactly those 32 expectations; preserve the other 3,268 rows. No previously passing candidate regresses. This was a focused run, not a full-corpus conformance measurement. Validation: - Common SV suite: 5,679 passed, 20 existing ignored. Latest container suite: 108 passed, including four new shared cases across five configurations. - Analyzer/frontend units: 833 and 7 passed, with 3 existing analyzer ignores. - Debug NAPI build and JS integration: 435 passed across 16 files. - Affected-crate all-targets Clippy with -D warnings, formatting, diff checks and the five sv-tests aggregate tests passed. Independent checks retain their original assertions and exclusions: - Verilator 5.052: 3 passes, 1 four-state adapter unsupported. - Icarus 13.0: 1 pass, 2 compile errors for unsupported associative arrays and 1 mismatch in the packed-result dimension/bound queries. - xezim 0.11.3: all four compile but mismatch. Standalone probes reproduce queue mutation inside $bits/$size, zero instead of X from an empty logic queue pop, and receiver capture before a nested pop argument. Queue slicing, queue concatenation operands, element-reference persistence, warning diagnostics and nonintegral pop result queries remain outside this change's support contract. Change-Id: Ie020842652d298a923ebb251ce8d4775b3249082 --- conformance/sv-tests/README.md | 20 ++++ conformance/sv-tests/expected.tsv | 64 ++++++------- .../celox-sv-analyzer/src/ast/containers.rs | 60 +++++++++++- .../src/ast/dimensions/query_binding.rs | 23 +++++ .../celox-sv-analyzer/src/ast/procedural.rs | 7 ++ .../src/sv/cases/containers.vtest | 95 +++++++++++++++++++ .../frontends/systemverilog/containers.rs | 4 + docs/guide/systemverilog-reference.md | 10 +- 8 files changed, 245 insertions(+), 38 deletions(-) diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index aeb7df2da7b..fec41b659ee 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -145,6 +145,26 @@ contains 3,300 case/mode verdicts at the pinned revision. These are its only changed rows, with no passing case regressing: 1,201 cases pass in 2state and 1,212 in 4state. Only these reviewed expectations are updated. +Zero-argument dynamic-container methods accept omitted parentheses, including +`size`, associative `num`, `delete`, and queue `pop_front` / `pop_back` +(7.5.2–7.5.3, 7.9, 7.10.2). Sixteen unmodified upstream simulation cases pass +the official runner in both state modes at the pinned revision: dynamic +`op-delete` / `op-size`, associative `alloc`, `nonexistent`, `delete`, `num`, +and `size`, and queue +`bounded`, `delete`, `insert`, `max-size`, `pop_back`, `pop_front`, `push_back`, +`push_front` and `size`. Only these 32 expectations change from `fail` to `pass`. +The focused runner checked 36 pinned case files containing these bare +method names (72 case/mode verdicts), with no passing candidate regressing. +This does not establish full dynamic-container conformance. +Shared regressions additionally cover discarded pop results, string/class +handles, four-state values and empty-pop defaults, and unevaluated type queries +that preserve packed result dimensions and authored bounds. The packed-result +query regression failed on all five Celox backend configurations even after +the initial 28 upstream checks passed. Arity and void-result rejection remain checked. +Queue slices, queue operands in concatenations, element-reference persistence, +warning diagnostics, and queries on nonintegral pop results remain outside +this change's support contract. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b9bae1143b3..547a5dcf84c 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1255,8 +1255,8 @@ chapter-6/6.9.2--vector_vectored.sv 2state fail chapter-6/6.9.2--vector_vectored.sv 4state fail chapter-6/6.9.2--vector_vectored_inv.sv 2state pass chapter-6/6.9.2--vector_vectored_inv.sv 4state pass -chapter-7/arrays/associative/alloc.sv 2state fail -chapter-7/arrays/associative/alloc.sv 4state fail +chapter-7/arrays/associative/alloc.sv 2state pass +chapter-7/arrays/associative/alloc.sv 4state pass chapter-7/arrays/associative/arguments.sv 2state fail chapter-7/arrays/associative/arguments.sv 4state fail chapter-7/arrays/associative/assignment.sv 2state pass @@ -1287,8 +1287,8 @@ chapter-7/arrays/associative/locator-methods/unique-index.sv 2state fail chapter-7/arrays/associative/locator-methods/unique-index.sv 4state fail chapter-7/arrays/associative/locator-methods/unique.sv 2state fail chapter-7/arrays/associative/locator-methods/unique.sv 4state fail -chapter-7/arrays/associative/methods/delete.sv 2state fail -chapter-7/arrays/associative/methods/delete.sv 4state fail +chapter-7/arrays/associative/methods/delete.sv 2state pass +chapter-7/arrays/associative/methods/delete.sv 4state pass chapter-7/arrays/associative/methods/exists.sv 2state pass chapter-7/arrays/associative/methods/exists.sv 4state pass chapter-7/arrays/associative/methods/first.sv 2state pass @@ -1297,16 +1297,16 @@ chapter-7/arrays/associative/methods/last.sv 2state pass chapter-7/arrays/associative/methods/last.sv 4state pass chapter-7/arrays/associative/methods/next.sv 2state pass chapter-7/arrays/associative/methods/next.sv 4state pass -chapter-7/arrays/associative/methods/num.sv 2state fail -chapter-7/arrays/associative/methods/num.sv 4state fail +chapter-7/arrays/associative/methods/num.sv 2state pass +chapter-7/arrays/associative/methods/num.sv 4state pass chapter-7/arrays/associative/methods/prev.sv 2state pass chapter-7/arrays/associative/methods/prev.sv 4state pass -chapter-7/arrays/associative/methods/size.sv 2state fail -chapter-7/arrays/associative/methods/size.sv 4state fail +chapter-7/arrays/associative/methods/size.sv 2state pass +chapter-7/arrays/associative/methods/size.sv 4state pass chapter-7/arrays/associative/methods/traversal.sv 2state pass chapter-7/arrays/associative/methods/traversal.sv 4state pass -chapter-7/arrays/associative/nonexistent.sv 2state fail -chapter-7/arrays/associative/nonexistent.sv 4state fail +chapter-7/arrays/associative/nonexistent.sv 2state pass +chapter-7/arrays/associative/nonexistent.sv 4state pass chapter-7/arrays/associative/other.sv 2state fail chapter-7/arrays/associative/other.sv 4state fail chapter-7/arrays/associative/string.sv 2state pass @@ -1315,12 +1315,12 @@ chapter-7/arrays/associative/wildcard.sv 2state fail chapter-7/arrays/associative/wildcard.sv 4state fail chapter-7/arrays/dynamic/basic.sv 2state pass chapter-7/arrays/dynamic/basic.sv 4state pass -chapter-7/arrays/dynamic/op-delete.sv 2state fail -chapter-7/arrays/dynamic/op-delete.sv 4state fail +chapter-7/arrays/dynamic/op-delete.sv 2state pass +chapter-7/arrays/dynamic/op-delete.sv 4state pass chapter-7/arrays/dynamic/op-new.sv 2state pass chapter-7/arrays/dynamic/op-new.sv 4state pass -chapter-7/arrays/dynamic/op-size.sv 2state fail -chapter-7/arrays/dynamic/op-size.sv 4state fail +chapter-7/arrays/dynamic/op-size.sv 2state pass +chapter-7/arrays/dynamic/op-size.sv 4state pass chapter-7/arrays/multidimensional/basic.sv 2state pass chapter-7/arrays/multidimensional/basic.sv 4state pass chapter-7/arrays/multidimensional/copy.sv 2state pass @@ -1409,38 +1409,38 @@ chapter-7/memories/read-write.sv 2state pass chapter-7/memories/read-write.sv 4state pass chapter-7/queues/basic.sv 2state pass chapter-7/queues/basic.sv 4state pass -chapter-7/queues/bounded.sv 2state fail -chapter-7/queues/bounded.sv 4state fail -chapter-7/queues/delete.sv 2state fail -chapter-7/queues/delete.sv 4state fail +chapter-7/queues/bounded.sv 2state pass +chapter-7/queues/bounded.sv 4state pass +chapter-7/queues/delete.sv 2state pass +chapter-7/queues/delete.sv 4state pass chapter-7/queues/delete_assign.sv 2state fail chapter-7/queues/delete_assign.sv 4state fail -chapter-7/queues/insert.sv 2state fail -chapter-7/queues/insert.sv 4state fail +chapter-7/queues/insert.sv 2state pass +chapter-7/queues/insert.sv 4state pass chapter-7/queues/insert_assign.sv 2state fail chapter-7/queues/insert_assign.sv 4state fail -chapter-7/queues/max-size.sv 2state fail -chapter-7/queues/max-size.sv 4state fail +chapter-7/queues/max-size.sv 2state pass +chapter-7/queues/max-size.sv 4state pass chapter-7/queues/persistence.sv 2state fail chapter-7/queues/persistence.sv 4state fail -chapter-7/queues/pop_back.sv 2state fail -chapter-7/queues/pop_back.sv 4state fail +chapter-7/queues/pop_back.sv 2state pass +chapter-7/queues/pop_back.sv 4state pass chapter-7/queues/pop_back_assing.sv 2state fail chapter-7/queues/pop_back_assing.sv 4state fail -chapter-7/queues/pop_front.sv 2state fail -chapter-7/queues/pop_front.sv 4state fail +chapter-7/queues/pop_front.sv 2state pass +chapter-7/queues/pop_front.sv 4state pass chapter-7/queues/pop_front_assign.sv 2state fail chapter-7/queues/pop_front_assign.sv 4state fail -chapter-7/queues/push_back.sv 2state fail -chapter-7/queues/push_back.sv 4state fail +chapter-7/queues/push_back.sv 2state pass +chapter-7/queues/push_back.sv 4state pass chapter-7/queues/push_back_assign.sv 2state fail chapter-7/queues/push_back_assign.sv 4state fail -chapter-7/queues/push_front.sv 2state fail -chapter-7/queues/push_front.sv 4state fail +chapter-7/queues/push_front.sv 2state pass +chapter-7/queues/push_front.sv 4state pass chapter-7/queues/push_front_assign.sv 2state fail chapter-7/queues/push_front_assign.sv 4state fail -chapter-7/queues/size.sv 2state fail -chapter-7/queues/size.sv 4state fail +chapter-7/queues/size.sv 2state pass +chapter-7/queues/size.sv 4state pass chapter-7/queues/slice.sv 2state fail chapter-7/queues/slice.sv 4state fail chapter-7/structures/packed/basic.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index f30930ee12f..e8acce08883 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -399,15 +399,21 @@ pub(super) fn value( ], ))) } - ExprKind::Call { - expression, - arguments, - } => { + ExprKind::Call { .. } | ExprKind::Member { .. } => { + // No-argument built-in methods also permit the bare member form, + // e.g. q.size, q.pop_front and map.delete (clauses 7.9 and 7.10). + let (expression, arguments) = match &native.expression(id).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (id, &[][..]), + }; let ExprKind::Member { expression: base, separator, name, - } = &native.expression(*expression).kind + } = &native.expression(expression).kind else { return Ok(None); }; @@ -476,6 +482,12 @@ pub(super) fn value( name.spelling ))); } + if dims.type_query + && matches!(op, ContainerOp::PopFront | ContainerOp::PopBack) + && target.layout.handle.is_some() + { + return Err(unsupported("type queries on nonintegral queue pop results")); + } let mut args = vec![expression_binding::value(*base, native, tree, dims)?]; for (index, arg) in arguments.iter().enumerate() { let id = arg.value.unwrap(); @@ -727,3 +739,41 @@ mod tests { Source::from_syntax(&tree).unwrap(); } } + +#[cfg(test)] +mod method_call_tests { + use super::*; + + #[test] + fn bare_methods_keep_argument_and_void_result_checks() { + for statement in [ + "q.push_back;", + "q.push_front;", + "q.insert;", + "map.exists;", + "map.first;", + "map.last;", + "map.next;", + "map.prev;", + "value = q.delete;", + "value = a.delete;", + "value = map.delete;", + "value = q.num;", + "value = $bits(strings.pop_front);", + "value = $dimensions(strings.pop_back());", + "value = $bits(objects.pop_front());", + "value = $dimensions(objects.pop_back);", + ] { + let source = format!( + "module Top; int q[$], a[], map[int], value; string strings[$]; + class Cell; int n; endclass Cell objects[$]; + initial begin {statement} end endmodule" + ); + let result = crate::analyze_source(&source, Path::new("bare-container-method.sv")); + assert!( + matches!(result, Err(AnalyzerError::Unsupported(_))), + "{statement}: {result:?}" + ); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 353055ff483..8a314d56c71 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -690,6 +690,29 @@ pub(in crate::ast) fn shape( while let Some(job) = jobs.pop() { match job { Job::Enter(id) => { + let callee = match native.expression(id).kind { + ExprKind::Call { expression, .. } => expression, + _ => id, + }; + if let ExprKind::Member { + expression, name, .. + } = &native.expression(callee).kind + && let Some(container) = containers::native_type(*expression, native, context) + { + // Validate the call without executing it. Pop returns the + // declared element type, including packed dimensions and + // authored bounds, rather than a flattened bit vector. + let value = expression_binding::bind(id, tree, context)?; + let shape = if matches!(name.spelling.as_str(), "pop_front" | "pop_back") { + procedural::dimensions_from_type(&container.element) + } else { + let ty = bound_bits_type(&tree.state, &value, context) + .ok_or_else(|| unsupported("container method result type"))?; + scalar(ty.width, ty.signed, ty.width > 1) + }; + values.push(shape); + continue; + } if let Some((name, dimensions)) = type_binding::argument_alias(id, native) && dimensions.is_empty() { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 594ed4bed04..ebd7f92adcb 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1236,6 +1236,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if discarded + && let Some(mut value) = + containers::value(query_root, native, self.tree, &self.dims, true)? + { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if let Some(call) = self.method_call_statement(query_root)? { return Ok(vec![call]); } diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest index ef81766ee8d..5a1010c002f 100644 --- a/crates/celox-test-suite/src/sv/cases/containers.vtest +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -386,3 +386,98 @@ module Top(output bit [2:0] flags); endmodule "#) (top Top) (run_until 0) (assert_eq flags 7)) + +(case optional_parentheses + (source "optional_parentheses.sv" #" +module Top(output bit [14:0] flags); + int a[], q[$], numbers[int], words[string], value; + string strings[$], text; + class Cell; int n; endclass + Cell objects[$], original, popped; + initial begin + flags[0] = a.size == 0 && q.size == 0 && numbers.num == 0 && words.size == 0; + a = new[3]; + flags[1] = a.size == 3 && a.size() == a.size; + a.delete; + flags[2] = a.size == 0; + q = {2, 3, 4}; value = q.pop_front; + flags[3] = value == 2 && q.size == 2 && q[0] == 3; + value = q.pop_back; + flags[4] = value == 4 && q.size == 1; + q.pop_front; + flags[5] = q.size == 0; + q = {5, 6}; void'(q.pop_front); void'(q.pop_back()); + flags[6] = q.size == 0; + q = {1, 2}; q.push_back(q.pop_front); + flags[7] = q.size == 2 && q[0] == 2 && q[1] == 1; + q.delete; + flags[8] = q.size == 0; + numbers[-1] = 10; numbers[5] = 20; + flags[9] = numbers.size == 2 && numbers.num == 2; + words["first"] = 10; words["second"] = 20; words.delete("first"); + flags[10] = words.size == 1 && words.num == 1 && words["second"] == 20; + numbers.delete; words.delete; q.size; + flags[11] = numbers.num == 0 && words.size == 0; + strings = {"first", "last"}; text = strings.pop_front; + flags[12] = text == "first" && strings.size == 1; + text = strings.pop_back; + flags[13] = text == "last" && strings.size == 0; + original = new; original.n = 9; objects.push_back(original); popped = objects.pop_front; + flags[14] = popped == original && popped.n == 9 && objects.size == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 32767)) + +(case optional_parentheses_queries + (source "optional_parentheses.sv" #" +module Top(output bit [3:0] flags); + logic [3:0] q[$]; + int a[], map[int]; + initial begin + q = {4'h5, 4'h6}; + flags[0] = $bits(q.pop_front) == 4 && $size(q.pop_back) == 4 && q.size == 2; + flags[1] = $bits(a.size) == 32 && $bits(map.num) == 32; + flags[2] = $dimensions(q.pop_front) == 1 && $unpacked_dimensions(q.pop_back) == 0 && q.size == 2; + flags[3] = q.pop_back == 6 && q.pop_front == 5 && q.size == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case optional_parentheses_four_state + (source "optional_parentheses.sv" #" +module Top(output bit [3:0] flags); + logic [3:0] q[$], value; + initial begin + q = {4'b1xz0, 4'bz01x}; + value = q.pop_front; + flags[0] = value === 4'b1xz0 && q.size == 1; + value = q.pop_back; + flags[1] = value === 4'bz01x && q.size == 0; + value = q.pop_front; + flags[2] = value === 4'bxxxx && q.size == 0; + q = {4'bxzxz}; void'(q.pop_back); + flags[3] = q.size == 0; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case optional_parentheses_packed_result + (source "optional_parentheses.sv" #" +module Top(output bit [4:0] flags); + logic [2:1][7:4] q[$]; + initial begin + q = {8'h12, 8'h34}; + flags[0] = $bits(q.pop_front) == 8 && $bits(q.pop_back()) == 8; + flags[1] = $dimensions(q.pop_front) == 2 && $dimensions(q.pop_back()) == 2; + flags[2] = $size(q.pop_front, 1) == 2 && $size(q.pop_back(), 2) == 4; + flags[3] = $left(q.pop_front, 1) == 2 && $right(q.pop_back(), 1) == 1 + && $left(q.pop_front(), 2) == 7 && $right(q.pop_back, 2) == 4; + flags[4] = q.size == 2 && q.pop_back == 8'h34 && q.pop_front == 8'h12 && q.size == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 31)) diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index 693181a3894..b00caad9ff0 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -1,6 +1,10 @@ use super::*; sv_backends! { + fn optional_parentheses_packed_result(sim) { @case "containers::optional_parentheses_packed_result"; } + fn optional_parentheses(sim) { @case "containers::optional_parentheses"; } + fn optional_parentheses_queries(sim) { @case "containers::optional_parentheses_queries"; } + fn optional_parentheses_four_state(sim) { @case "containers::optional_parentheses_four_state"; } fn queue_argument_side_effects(sim) { @case "containers::queue_argument_side_effects"; } fn queue_argument_four_state(sim) { @case "containers::queue_argument_four_state"; } fn string_associative_foreach(sim) { @case "containers::string_associative_foreach"; } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ea7c9387bfb..7eefdc84c57 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -356,11 +356,19 @@ VCD output and the TypeScript API. Dynamic arrays (`T a[]`) support `new[n]`, `new[n](a)`, `size()` and `delete()` (IEEE 1800-2023 7.5). Queues (`T q[$]`, `T q[$:N]`) support `size`, `insert`, `delete`, `push_front`, `push_back`, `pop_front` and -`pop_back`, with parentheses. Queue indices may use `$` and `$+1`. +`pop_back`. Queue indices may use `$` and `$+1`. Associative arrays support integral keys up to 64 bits or `string` keys, `num` / `size`, `exists`, `delete`, and `first` / `last` / `next` / `prev` (7.8–7.10). Traversal leaves its index unchanged when no key is found. +The empty parentheses on zero-argument container methods are optional: +`a.size`, `q.pop_front`, `map.num` and `map.delete` have the same behavior as +their parenthesized forms. A bare `delete` clears the container. Queue pop +results may be discarded with `void'(...)`; type queries such as +`$bits(q.pop_front)` inspect the result without removing an element. +Integral pop result queries preserve the element's packed dimensions and +declared bounds. Queries on string- or class-valued pop results remain unsupported. + Elements may be packed integral values up to 64 bits, strings or class handles. Positional assignment patterns and element concatenations construct sequences; assignments between dynamic arrays and queues copy values and From c918c9e7184ec3b9b18c774d1f5e65d1ecf43134 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:50:58 +0900 Subject: [PATCH 2/7] fix(sv): preserve disjoint single-bit array driver windows Independent always_comb processes writing different unpacked elements were rejected as multiple drivers when each packed element held one bit. Recover the checked singleton element window and preserve it through driver analysis and packed lowering, including the symbolic scheduler. Ordinary dynamic outer array accesses retain conservative driver ranges. Cover [0:0], [7:7] and [-2:-2] packed ranges, invalid inner indices, and actual overlapping writers. IEEE 1800-2023 9.2.2.2 and 11.5.3 permit the disjoint static prefixes. Keep out-of-range behavior in an owning-crate regression because Verilator 5.052 truncates the bit index of a one-bit element; valid-index cases remain shared with both external adapters. Validation: 5,679 SystemVerilog tests passed (20 existing skips), 7 frontend unit tests passed, affected frontend/Celox clippy with warnings denied, formatting and diff checks. All three shared cases passed Icarus and Verilator. No retained verification baseline or external simulator exclusion was changed. Change-Id: I616b5657904654df72a57e191f04f6d9c47744b5 --- crates/celox-frontend-sv/src/lowering.rs | 110 +++++++++++++++++- .../src/sv/cases/indexed_select.vtest | 72 ++++++++++++ .../frontends/systemverilog/indexed_select.rs | 41 +++++++ .../systemverilog/review_regressions.rs | 15 +++ 4 files changed, 235 insertions(+), 3 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index a5a2a7f987d..44a6c3b9b11 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -7463,6 +7463,90 @@ struct DynamicPackedWrite { window: Option, } +/// Recover a constant outer element for a checked dynamic bit select of a +/// one-bit packed element. Its only valid inner index is its declared bound. +/// An arbitrary dynamic unpacked element permits more than one index and must +/// retain its dynamic element addressing. +fn single_bit_select_window( + lsb: &sv::ir::ConstExpr, + width: usize, + constants: &HashMap, + types: &HashMap, +) -> Option { + use sv::ir::{BinaryOp, ConstExpr}; + fn selected<'a>( + mut expr: &'a ConstExpr, + constants: &HashMap, + types: &HashMap, + ) -> &'a ConstExpr { + while let ConstExpr::Mux { + condition, + then_expr, + else_expr, + } = expr + { + match sv::typecheck::eval_const_expr_with_types(condition, constants, types) { + Some(0) => expr = else_expr, + Some(_) => expr = then_expr, + None => break, + } + } + expr + } + let (base, offset) = split_dynamic_array_offset(lsb, constants, types)?; + let ConstExpr::Mux { + condition, + then_expr, + else_expr, + } = selected(base, constants, types) + else { + return None; + }; + let ConstExpr::Binary { + left, + op: BinaryOp::LogicAnd, + right, + } = selected(condition, constants, types) + else { + return None; + }; + let bound = |expr, expected| { + let ConstExpr::Binary { left, op, right } = selected(expr, constants, types) else { + return None; + }; + let ConstExpr::Ident(name) = left.as_ref() else { + return None; + }; + if *op != expected { + return None; + } + Some(( + name, + sv::typecheck::eval_const_expr_with_types(right, constants, types)?, + )) + }; + let lower = bound(left, BinaryOp::Ge)?; + let upper = bound(right, BinaryOp::Le)?; + if lower != upper { + return None; + } + let invalid = sv::typecheck::eval_const_expr_with_types(else_expr, constants, types)? + .checked_add(offset)?; + let width = i128::try_from(width).ok()?; + if (0..width).contains(&invalid) { + return None; + } + let mut checked_index = constants.clone(); + checked_index.insert(lower.0.clone(), lower.1); + let position = sv::typecheck::eval_const_expr_with_types(then_expr, &checked_index, types)? + .checked_add(offset)?; + if !(0..width).contains(&position) { + return None; + } + let position = usize::try_from(position).ok()?; + Some(BitAccess::new(position, position)) +} + /// For a run-time select inside one element of an unpacked array, such as /// `mem[1][i]`, the bits of that element: the constant part of the flattened /// position names the element, and the run-time part moves within it. @@ -7473,9 +7557,13 @@ fn runtime_select_window( constants: &HashMap, parameter_types: &HashMap, ) -> Option { - // One-bit elements have no bits within an element, and their run-time - // index has no stride to recognize. - if element_width <= 1 || element_width == width { + // A checked bit select inside a one-bit element can only write its zero + // bit. Preserve the constant outer element in both driver analysis and + // lowering; an arbitrary run-time array index remains unconstrained. + if element_width == 1 { + return single_bit_select_window(lsb, width, constants, parameter_types); + } + if element_width == 0 || element_width == width { return None; } let (base, offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; @@ -9232,6 +9320,14 @@ fn dynamic_array_element_subselection( if !is_dynamic { return None; } + // This is a dynamic bit inside one constant one-bit element, rather + // than a dynamic element of the whole array. Let the packed lowering + // retain the checked element window. + if packed_element_width == 1 + && single_bit_select_window(lsb, variable.width, constants, parameter_types).is_some() + { + return None; + } let (msb_base, msb_offset) = split_dynamic_array_offset(msb, constants, parameter_types)?; let (lsb_base, lsb_offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; if msb_base != lsb_base { @@ -9366,6 +9462,14 @@ fn dynamic_array_element_lvalue( if !is_dynamic { return None; } + // This is a dynamic bit inside one constant one-bit element, rather + // than a dynamic element of the whole array. Let the packed lowering + // retain the checked element window. + if packed_element_width == 1 + && single_bit_select_window(lsb, variable.width, constants, parameter_types).is_some() + { + return None; + } let (msb_base, msb_offset) = split_dynamic_array_offset(msb, constants, parameter_types)?; let (lsb_base, lsb_offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; if msb_base != lsb_base { diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 65c69699a08..0af60134328 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -2185,3 +2185,75 @@ (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case disjoint_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=0)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index 0) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) + +(case disjoint_shifted_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=7)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index 7) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) + +(case disjoint_negative_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=-2)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index (trunc 32 -2)) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 6350b87d6f7..80f2ce3f756 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -403,3 +403,44 @@ sv_backends! { @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; } } + +sv_backends! { + fn disjoint_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_single_bit_array_drivers"; + } +} + +// Verilator 5.052 truncates the bit index of a one-bit packed element and +// writes its zero bit for index 2. Keep the out-of-range check local; the +// disjoint-driver behavior at valid indices is shared with both adapters. +sv_backends! { + fn single_bit_array_drivers_ignore_invalid_inner_indices(sim) { + @setup { + let source = "module Top(input logic [1:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [0:0] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin ready[n]='0; ready[n][index]=value[n]; end + assign q[n]=ready[n][0]; + end + endmodule"; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("single_bit_bounds.sv"))], "Top"); + let index=sim.signal("index"); + let value=sim.signal("value"); + let q=sim.signal("q"); + for (position, bits, expected) in [(0u8,5u8,5u8),(1,5,0),(2,5,0),(0,2,2)] { + sim.modify(|io| {io.set(index,position);io.set(value,bits);}).unwrap(); + assert_eq!(sim.get(q),BigUint::from(expected)); + } + } +} + +sv_backends! { + fn disjoint_shifted_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_shifted_single_bit_array_drivers"; + } + fn disjoint_negative_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_negative_single_bit_array_drivers"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 9d03cf15da5..e5985594160 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8974,3 +8974,18 @@ fn net_alias_coalescing_retains_distinct_and_variable_drivers() { assert!(error.contains(diagnostic), "{error}"); } } + +#[test] +fn single_bit_array_driver_windows_still_reject_overlaps() { + for source in [ + "module Top(input logic index, input logic a, b, output logic [0:0] q[2]); + always_comb begin q[0]='0; q[0][index]=a; end + always_comb begin q[0]='0; q[0][index]=b; end endmodule", + "module Top(input logic index, input logic a, b, output logic [0:0] q[2]); + always_comb q[index]=a; + always_comb q[0]=b; endmodule", + ] { + let error = cranelift_build_error(source); + assert!(error.contains("multiple variable drivers"), "{error}"); + } +} From c2a33b9581709847768eb5ad13811d2959fe7e5b Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:13:23 +0900 Subject: [PATCH 3/7] feat(aplite): query bounded projected XOR cells Add PreparedQuery::enumerate_cell to enumerate at most a caller-bounded projected cell under temporary predicates. Use one scoped CDCL database, retaining local learning while blocking already-seen projected assignments. Hidden witness multiplicity does not duplicate a projected model. Blocking clauses and their learned consequences never escape into the prepared query or a later cell. Return Complete, TooLarge, or Unknown distinctly. One extra search distinguishes an exact-size cell from overflow; only Complete exposes models. Work and time budgets cover the entire cell operation, including model replay. Replay source formulas, contexts and predicate assumptions before accepting models or declaring overflow. Add HashCells to prepare seed-selected affine XOR rows once and query different prefixes/targets without recompilation. Preserve constant and dependent rows, validate projection variables, and bound construction as well as search. These are partitioning/counting primitives, not a uniform sampler: adaptive sizing and a justified cell-acceptance/model-selection policy remain follow-up work. The exhaustive reservoir sampler remains test-only; an empty predicate prefix can still inspect a small whole domain within the explicit cell bound. Validation: 98 Aplite unit tests and four README doctests. Checked every three-Boolean truth table across XOR cells; verified disjoint/complete partitions across seeds, projected multiplicity, alias/constant bits, exact thresholds, overflow, invalid inputs, budget recovery and no state leakage. A 32-bit domain narrowed by XOR predicates completes a 16-model cell; the unpartitioned query stops at overflow. Lydite IR/solver/kernel tests (38/29/5), affected all-target clippy, formatting, package/version checks and standalone package verification passed. No full RV32I campaign, release build, or production uniformity guarantee is claimed. Change-Id: I562d30b5a8a1d9c75859358602aa1b3cc9c76455 --- crates/aplite/README.md | 31 ++ crates/aplite/src/finite.rs | 2 +- crates/aplite/src/finite/prepared.rs | 5 + crates/aplite/src/finite/prepared/cell.rs | 442 +++++++++++++++++++ crates/aplite/src/finite/prepared/hashing.rs | 303 +++++++++++++ crates/aplite/src/lib.rs | 4 +- 6 files changed, 784 insertions(+), 3 deletions(-) create mode 100644 crates/aplite/src/finite/prepared/cell.rs create mode 100644 crates/aplite/src/finite/prepared/hashing.rs diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 0a9b136e90e..077f0fec470 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -86,3 +86,34 @@ the query history because learning and search activity are retained. Unknown includes invalid predicate indexes and exhausted budgets, and is not Unsat. This API supplies reusable solving for future distribution policies; it does not implement uniform sampling, variable ordering, or SystemVerilog `randomize()`. + +## Bounded hash cells + +`HashCells` prepares seed-selected affine XOR predicates over chosen scalar +variables. A query chooses a prefix of those predicates and their target bits; +shorter prefixes leave larger cells. The original formula and all predicates are +compiled once. The cell query uses one temporary SAT database and retains local +learning while it blocks already-seen projected assignments. It does not recompile +the formula for each model or retain blockers between cells. + +```rust +use aplite::{CellStatus, Env, HashCells, Limits, Sort, boolv, var}; +let projection = Env::from([("value".into(), var("x".into(), Sort::Bv(3)))]); +let cells = HashCells::new(&boolv(true), &projection, 2, 42, Limits::default()).unwrap(); +let cell = cells.cell(&[true, false], 8, Limits::default()); +assert_eq!(cell.status, CellStatus::Complete); +assert!(cell.models.iter().all(|model| model.contains_key("x"))); +``` + +`Complete` certifies all models in that cell, including an empty cell. `TooLarge` +means the cell has more models than the caller's bound, and `Unknown` covers +invalid input or exhausted budgets. Neither exposes a truncated model list. +All searches and replay in one cell share one work/time budget. Hidden variables +are existential: multiple witnesses cannot duplicate a projected assignment. +Call `PreparedQuery::enumerate_cell` directly for custom partition predicates. + +These operations are building blocks, **not a uniform sampler**. Uniformly picking +a cell and then uniformly picking one of its models generally biases results +when cells have different sizes. A sampling policy must control cell sizing and +acceptance separately. The exhaustive reservoir sampler remains a test-only reference. +Rows may be dependent or constant; hash construction preserves those cases. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index a3136f146ee..62443ec8663 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -16,7 +16,7 @@ mod control; mod lookup; mod prepared; mod readonly; -pub use prepared::{Assumption, PreparedQuery}; +pub use prepared::{Assumption, Cell, CellStatus, HashCells, PreparedQuery}; pub use readonly::ArrayModel; type Lit = i32; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs index 3016ce5691c..36f5d3916b9 100644 --- a/crates/aplite/src/finite/prepared.rs +++ b/crates/aplite/src/finite/prepared.rs @@ -1,6 +1,11 @@ //! Reusable scalar encoding with temporary Boolean assumptions. use super::*; +mod cell; +mod hashing; +pub use cell::{Cell, CellStatus}; +pub use hashing::HashCells; + /// Select the polarity of a predicate supplied when preparing the query. #[derive(Clone, Copy, Debug)] pub struct Assumption { diff --git a/crates/aplite/src/finite/prepared/cell.rs b/crates/aplite/src/finite/prepared/cell.rs new file mode 100644 index 00000000000..47da225784e --- /dev/null +++ b/crates/aplite/src/finite/prepared/cell.rs @@ -0,0 +1,442 @@ +//! Bounded projected model enumeration in a temporary SAT database. +use super::*; +use std::collections::BTreeSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CellStatus { + /// The entire selected cell was enumerated. It may be empty. + Complete, + /// At least max_models + 1 distinct projected models exist in the cell. + TooLarge, + /// Invalid input, unsupported query, or an exhausted resource budget. + Unknown, +} + +#[derive(Debug)] +pub struct Cell { + pub status: CellStatus, + /// Exposed only for Complete cells; never a biased truncated prefix. + /// Keys are original variable names, not context labels. + pub models: Vec>, + pub work: u64, + pub reason: Option, +} + +impl PreparedQuery { + /// Enumerate a bounded cell selected by temporary predicate assumptions. + /// + /// `projection` names distinct original scalar variables known at preparation. + /// Hidden witnesses do not multiply a projected assignment. One extra SAT + /// query distinguishes an exact-size cell from an oversized cell. The work + /// and time budgets cover all searches, blocking and replay in this call. + /// + /// This is a building block for hash-based sampling, not a sampling policy. + /// It never enumerates more than max_models + 1 witnesses. Blocking clauses + /// and learned clauses derived from them live only inside this call, so they + /// cannot change later cells or ordinary solves on the prepared query. + pub fn enumerate_cell( + &self, + assumptions: &[Assumption], + projection: &[String], + max_models: usize, + limits: Limits, + ) -> Cell { + let mut cell = Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: None, + }; + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + let run = (|| -> Res { + budget.tick(1)?; + if self.blast.vars > budget.limits.max_variables + || self.blast.memo.len() > budget.limits.max_terms + || self.blast.clauses.len() > budget.limits.max_clauses + { + return Err("prepared cell exceeds solve size limits".into()); + } + let mut seen = BTreeSet::new(); + let mut bits = Vec::new(); + for name in projection { + budget.tick(1)?; + if !seen.insert(name) { + return Err("duplicate cell projection variable".into()); + } + let input = self + .blast + .inputs + .get(name) + .ok_or("unknown cell projection variable")?; + budget.tick(input.bits.len() as u64)?; + bits.extend_from_slice(&input.bits); + } + let mut literals = Vec::new(); + for assumption in assumptions { + budget.tick(1)?; + let lit = *self + .literals + .get(assumption.predicate) + .ok_or("invalid prepared predicate index")?; + literals.push(if assumption.value { lit } else { -lit }); + } + let mut clauses = Vec::new(); + for clause in &self.blast.clauses { + budget.tick(1 + clause.len() as u64)?; + clauses.push(clause.clone()); + } + // One scoped CDCL instance for the whole cell. Reuse encoding, + // propagation and local learning between models, without copying + // or recompiling the base formula on each enumeration step. + let mut solver = Sat::new(self.blast.vars, clauses); + loop { + match solver.run_slice_assuming(&mut budget, u64::MAX, &literals)? { + Search::Complete(Verdict::Unsat) => { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + Search::Complete(Verdict::Sat) => {} + _ => return Err("cell search did not complete".into()), + } + let (assignments, _) = replay_model( + &self.formula, + &self.context, + &self.blast, + &solver, + &mut budget, + )?; + let mut memo = HashMap::new(); + for assumption in assumptions { + if evaluate( + &self.predicates[assumption.predicate], + &assignments, + &mut memo, + &mut budget, + 0, + )? != Scalar::Bool(assumption.value) + { + return Err("cell model failed assumption replay".into()); + } + } + if cell.models.len() == max_models { + budget.check_time()?; + return Ok(CellStatus::TooLarge); + } + let mut model = BTreeMap::new(); + for name in projection { + budget.tick(1)?; + model.insert(name.clone(), assignments[name].clone()); + } + let mut blocking = Vec::new(); + for &bit in &bits { + budget.tick(1)?; + blocking.push(if truth(&solver.values, bit) > 0 { + -bit + } else { + bit + }); + } + cell.models.push(model); + solver.backtrack(0, &mut budget)?; + if !add_blocking_clause(&mut solver, blocking, &mut budget)? { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + } + })(); + cell.work = budget.work; + match run { + Ok(status) => cell.status = status, + Err(reason) => cell.reason = Some(reason), + } + if cell.status != CellStatus::Complete { + cell.models.clear(); + } + cell + } +} + +/// Insert a model blocker after backtracking to root. Root assignments are +/// permanent within this scoped database. Simplify by them before watching the +/// clause, so a newly inserted unit is propagated and an empty clause closes +/// the cell immediately. Assumption decisions have already been removed. +fn add_blocking_clause(solver: &mut Sat, clause: Vec, budget: &mut Budget) -> Res { + debug_assert!(solver.starts.is_empty()); + let mut remaining = BTreeSet::new(); + for lit in clause { + budget.tick(1)?; + match truth(&solver.values, lit) { + 1 => return Ok(true), + -1 => {} + _ => { + remaining.insert(lit); + } + } + } + if remaining.is_empty() { + return Ok(false); + } + if solver.clauses.len() >= budget.limits.max_clauses { + return Err("cell blocking-clause budget exhausted".into()); + } + let clause: Vec<_> = remaining.into_iter().collect(); + let unit = (clause.len() == 1).then_some(clause[0]); + let id = solver.clauses.len(); + solver.clauses.push(clause); + solver.attach(id); + if let Some(unit) = unit { + return Ok(solver.enqueue(unit, Some(id))); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{and, boolv, bv, eq, node, not, var}; + + fn selected(predicate: usize, value: bool) -> Assumption { + Assumption { predicate, value } + } + + #[test] + fn projected_enumeration_ignores_hidden_witnesses_and_is_scoped() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = node(Sort::Bool, "or", vec![not(x.clone()), y.clone()]); + let mut query = + PreparedQuery::new(&formula, &Env::new(), &[x, y], Limits::default()).unwrap(); + for _ in 0..3 { + let cell = query.enumerate_cell(&[], &["x".into()], 2, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 2); + assert_ne!(cell.models[0], cell.models[1]); + let both = query.enumerate_cell(&[], &["x".into(), "y".into()], 3, Limits::default()); + assert_eq!(both.status, CellStatus::Complete); + assert_eq!(both.models.len(), 3); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + assert_eq!( + query + .solve(&[selected(0, false)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + } + } + + #[test] + fn exact_limit_overflow_empty_and_unsat_are_distinct() { + let x = var("x".into(), Sort::Bv(2)); + let query = PreparedQuery::new( + &boolv(true), + &Env::new(), + &[eq(x.clone(), bv(2, 0))], + Limits::default(), + ) + .unwrap(); + for bound in 0..=4 { + let cell = query.enumerate_cell(&[], &["x".into()], bound, Limits::default()); + assert_eq!( + cell.status, + if bound == 4 { + CellStatus::Complete + } else { + CellStatus::TooLarge + } + ); + assert_eq!(cell.models.len(), if bound == 4 { 4 } else { 0 }); + } + let empty = query.enumerate_cell( + &[selected(0, true), selected(0, false)], + &["x".into()], + 0, + Limits::default(), + ); + assert_eq!(empty.status, CellStatus::Complete); + assert!(empty.models.is_empty()); + let unit = query.enumerate_cell(&[], &[], 1, Limits::default()); + assert_eq!(unit.status, CellStatus::Complete); + assert_eq!(unit.models, vec![BTreeMap::new()]); + } + + #[test] + fn alias_and_constant_bits_do_not_duplicate_models() { + let x = var("x".into(), Sort::Bv(3)); + let y = var("y".into(), Sort::Bv(3)); + let z = var("z".into(), Sort::Bv(3)); + let formula = and(eq(x, y), eq(z, bv(3, 5))); + let query = PreparedQuery::new(&formula, &Env::new(), &[], Limits::default()).unwrap(); + let cell = query.enumerate_cell( + &[], + &["x".into(), "y".into(), "z".into()], + 8, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 8); + for model in cell.models { + assert_eq!(model["x"], model["y"]); + assert_eq!(model["z"], Scalar::Bv { width: 3, value: 5 }); + } + } + + #[test] + fn xor_cells_cover_small_truth_tables_without_overlap() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let z = var("z".into(), Sort::Bool); + let predicates = [ + node(Sort::Bool, "xor", vec![x.clone(), y.clone()]), + node(Sort::Bool, "xor", vec![y.clone(), z.clone()]), + ]; + for mask in 0..256u16 { + let mut formula = boolv(false); + for row in 0..8 { + if mask & (1 << row) != 0 { + let cube = and( + and( + eq(x.clone(), boolv(row & 1 != 0)), + eq(y.clone(), boolv(row & 2 != 0)), + ), + eq(z.clone(), boolv(row & 4 != 0)), + ); + formula = node(Sort::Bool, "or", vec![formula, cube]); + } + } + let query = + PreparedQuery::new(&formula, &Env::new(), &predicates, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + for target in 0..4 { + let cell = query.enumerate_cell( + &[selected(0, target & 1 != 0), selected(1, target & 2 != 0)], + &["x".into(), "y".into(), "z".into()], + 2, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + for model in cell.models { + let row = usize::from(model["x"] == Scalar::Bool(true)) + | (usize::from(model["y"] == Scalar::Bool(true)) << 1) + | (usize::from(model["z"] == Scalar::Bool(true)) << 2); + assert_ne!(mask & (1 << row), 0); + assert!(found.insert(row)); + } + } + assert_eq!(found.len(), mask.count_ones() as usize); + } + } + + #[test] + fn wide_space_is_bounded_by_xor_cell_not_total_cardinality() { + let x = var("x".into(), Sort::Bv(32)); + let bit = |i| { + eq( + node(Sort::Bv(1), format!("(_ extract {i} {i})"), vec![x.clone()]), + bv(1, 1), + ) + }; + let predicates: Vec<_> = (4..32) + .map(|i| node(Sort::Bool, "xor", vec![bit(i), bit(i - 1)])) + .collect(); + let query = + PreparedQuery::new(&boolv(true), &Env::new(), &predicates, Limits::default()).unwrap(); + let assumptions: Vec<_> = (0..28).map(|i| selected(i, i % 3 == 0)).collect(); + let cell = query.enumerate_cell(&assumptions, &["x".into()], 16, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete, "{:?}", cell.reason); + assert_eq!(cell.models.len(), 16); + let mut lows = BTreeSet::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + lows.insert(value & 15); + for i in 4..32 { + assert_eq!( + ((value >> i) ^ (value >> (i - 1))) & 1 != 0, + (i - 4) % 3 == 0 + ); + } + } + assert_eq!(lows.len(), 16); + assert_eq!( + query + .enumerate_cell(&[], &["x".into()], 16, Limits::default()) + .status, + CellStatus::TooLarge + ); + } + + #[test] + fn failures_clear_partial_results_and_leave_prepared_state_untouched() { + let x = var("x".into(), Sort::Bv(3)); + let mut query = PreparedQuery::new( + &boolv(true), + &Env::from([("label".into(), x.clone())]), + &[eq(x, bv(3, 3))], + Limits::default(), + ) + .unwrap(); + query.solve(&[], Limits::default(), 0); + let original_clauses = query.sat.as_ref().unwrap().clauses.len(); + let full = query.enumerate_cell(&[], &["x".into()], 8, Limits::default()); + assert_eq!(full.status, CellStatus::Complete); + for work in [0, full.work / 2, full.work - 1] { + let cell = query.enumerate_cell( + &[], + &["x".into()], + 8, + Limits { + max_work: work, + ..Limits::default() + }, + ); + assert_eq!(cell.status, CellStatus::Unknown); + assert!(cell.models.is_empty()); + assert_eq!(query.sat.as_ref().unwrap().clauses.len(), original_clauses); + } + for projection in [vec!["label".into()], vec!["x".into(), "x".into()]] { + assert_eq!( + query + .enumerate_cell(&[], &projection, 8, Limits::default()) + .status, + CellStatus::Unknown + ); + } + assert_eq!( + query + .enumerate_cell(&[selected(1, true)], &[], 1, Limits::default()) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .enumerate_cell( + &[], + &[], + 1, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 0) + .verdict, + Verdict::Sat + ); + } +} diff --git a/crates/aplite/src/finite/prepared/hashing.rs b/crates/aplite/src/finite/prepared/hashing.rs new file mode 100644 index 00000000000..264f1ce3338 --- /dev/null +++ b/crates/aplite/src/finite/prepared/hashing.rs @@ -0,0 +1,303 @@ +//! Seeded affine XOR partitions, with bounded projected cell queries. +use super::*; +use crate::{boolv, bv, eq, node}; +use std::collections::BTreeSet; + +/// A prepared family of affine XOR rows over projected scalar bits. +/// +/// Each row includes each bit and a constant with seed-selected coefficients. +/// With ideal independent random coefficients this is the standard affine XOR +/// hash family. The implementation uses a deterministic SplitMix64 PRNG, not a +/// source of cryptographic entropy. Rows may be zero or dependent: preserving +/// those cases is essential to the family; we do not silently repair them. +/// +/// `cell` selects a prefix of the rows and a target value for each selected row. +/// A caller can measure differently sized cells without recompiling the formula. +/// This is NOT a uniform sampler: choosing a cell and then a model arbitrarily +/// can bias results. A sampling policy must separately control cell acceptance, +/// target selection, and the distribution of models within accepted cells. +pub struct HashCells { + query: PreparedQuery, + projection: Vec, + rows: usize, + preparation_work: u64, +} + +impl HashCells { + /// Build at most `rows` XOR constraints. Projection values must be distinct + /// Bool or 1..=64-bit variable terms. Context labels do not affect model keys. + /// The single budget covers hash construction and query preparation. + pub fn new( + formula: &Term, + projection: &Env, + rows: usize, + seed: u64, + limits: Limits, + ) -> Res { + let mut budget = Budget { + limits: limits.clone(), + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + budget.tick(1)?; + let mut created = 0usize; + let mut names = BTreeSet::new(); + let mut bits = Vec::new(); + for variable in projection.values() { + budget.tick(1)?; + let name = variable + .0 + .op + .strip_prefix('@') + .ok_or("hash projection requires variables")?; + if !variable.0.args.is_empty() + || !valid_sort(&variable.0.sort) + || !names.insert(name.to_owned()) + { + return Err("hash projection requires distinct supported scalar variables".into()); + } + let width = match variable.0.sort { + Sort::Bool => 1, + Sort::Bv(width) => width, + _ => unreachable!(), + }; + if bits.len().saturating_add(width as usize) > limits.max_variables { + return Err("hash projection bit budget exhausted".into()); + } + for bit in 0..width { + budget.tick(1)?; + let term = if variable.0.sort == Sort::Bool { + variable.clone() + } else { + reserve_terms(&mut created, 3, &budget)?; + eq( + node( + Sort::Bv(1), + format!("(_ extract {bit} {bit})"), + vec![variable.clone()], + ), + bv(1, 1), + ) + }; + bits.push(term); + } + } + if rows > bits.len() || rows > limits.max_terms { + return Err("hash row limit exceeds projected width or term budget".into()); + } + let mut rng = seed; + let mut predicates = Vec::new(); + for _ in 0..rows { + budget.tick(1)?; + reserve_terms(&mut created, 1, &budget)?; + let mut terms = vec![boolv(next(&mut rng) & 1 != 0)]; + for bit in &bits { + budget.tick(1)?; + if next(&mut rng) & 1 != 0 { + terms.push(bit.clone()); + } + } + predicates.push(parity(&terms, &mut budget, &mut created)?); + } + budget.check_time()?; + let mut remaining = limits; + remaining.max_work -= budget.work; + remaining.timeout_ms = remaining + .timeout_ms + .checked_sub(u64::try_from(budget.start.elapsed().as_millis()).unwrap_or(u64::MAX)) + .filter(|&ms| ms > 0) + .ok_or("hash preparation time budget exhausted")?; + let query = PreparedQuery::new(formula, projection, &predicates, remaining)?; + budget.tick(query.preparation_work())?; + budget.check_time()?; + Ok(Self { + query, + projection: names.into_iter().collect(), + rows, + preparation_work: budget.work, + }) + } + + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + /// Targets select a prefix of the prepared XOR rows. Empty targets query + /// the unpartitioned space with the same bounded model limit. + pub fn cell(&self, targets: &[bool], max_models: usize, mut limits: Limits) -> Cell { + let start = Instant::now(); + if targets.len() > self.rows + || targets.len() as u64 >= limits.max_work + || limits.timeout_ms == 0 + { + return Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: Some("hash targets exceed prepared rows or query budget".into()), + }; + } + let assumptions: Vec<_> = targets + .iter() + .enumerate() + .map(|(predicate, &value)| Assumption { predicate, value }) + .collect(); + let overhead = targets.len() as u64; + limits.max_work -= overhead; + let timeout = limits.timeout_ms; + let mut cell = + self.query + .enumerate_cell(&assumptions, &self.projection, max_models, limits); + cell.work = cell.work.saturating_add(overhead); + if start.elapsed().as_millis() >= u128::from(timeout) { + cell.status = CellStatus::Unknown; + cell.models.clear(); + cell.reason = Some("hash cell time budget exhausted".into()); + } + cell + } +} + +fn next(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut value = *state; + value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); + value ^ (value >> 31) +} + +fn reserve_terms(created: &mut usize, amount: usize, budget: &Budget) -> Res<()> { + *created = created + .checked_add(amount) + .ok_or("hash construction term overflow")?; + if *created > budget.limits.max_terms { + return Err("hash construction term budget exhausted".into()); + } + Ok(()) +} + +fn parity(terms: &[Term], budget: &mut Budget, created: &mut usize) -> Res { + budget.tick(1)?; + if terms.len() == 1 { + return Ok(terms[0].clone()); + } + reserve_terms(created, 1, budget)?; + let mid = terms.len() / 2; + Ok(node( + Sort::Bool, + "xor", + vec![ + parity(&terms[..mid], budget, created)?, + parity(&terms[mid..], budget, created)?, + ], + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::var; + + #[test] + fn random_affine_cells_partition_and_reproduce_the_projected_domain() { + let x = var("x".into(), Sort::Bv(3)); + let context = Env::from([("label".into(), x)]); + let mut signatures = BTreeSet::new(); + for seed in 0..16 { + let cells = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let same = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + let mut signature = Vec::new(); + for target in 0..4 { + let bits = [target & 1 != 0, target & 2 != 0]; + let cell = cells.cell(&bits, 8, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models, same.cell(&bits, 8, Limits::default()).models); + let mut values = Vec::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + assert!(found.insert(value)); + values.push(value); + } + values.sort(); + signature.push(values); + } + assert_eq!(found.len(), 8); + signatures.insert(signature); + assert_eq!( + cells.cell(&[], 4, Limits::default()).status, + CellStatus::TooLarge + ); + assert_eq!( + cells.cell(&[false; 3], 8, Limits::default()).status, + CellStatus::Unknown + ); + } + assert!(signatures.len() > 1); + } + + #[test] + fn construction_and_cell_budgets_fail_closed() { + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); + assert!(HashCells::new(&boolv(true), &context, 9, 0, Limits::default()).is_err()); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_work: 1, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_terms: 2, + ..Limits::default() + } + ) + .is_err() + ); + let hash = HashCells::new(&boolv(true), &context, 3, 0, Limits::default()).unwrap(); + assert!(hash.preparation_work() > 0); + let failed = hash.cell( + &[true], + 8, + Limits { + max_work: 2, + ..Limits::default() + }, + ); + assert_eq!(failed.status, CellStatus::Unknown); + assert!(failed.models.is_empty()); + let duplicates = Env::from([ + ("x".into(), var("x".into(), Sort::Bool)), + ("alias".into(), var("x".into(), Sort::Bool)), + ]); + assert!(HashCells::new(&boolv(true), &duplicates, 1, 0, Limits::default()).is_err()); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 7a721daf55f..c9cad434b1a 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -10,8 +10,8 @@ pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Assumption, Limits, Outcome, PreparedQuery, Scalar, SearchHint, Verdict, solve, solve_seeded, - solve_with_hint, + Assumption, Cell, CellStatus, HashCells, Limits, Outcome, PreparedQuery, Scalar, SearchHint, + Verdict, solve, solve_seeded, solve_with_hint, }; #[cfg(test)] From 52daeacbb6a769b368415f114f7b16857ddc6efd Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:35:10 +0900 Subject: [PATCH 4/7] perf(aplite): reduce affine XOR rows before bit blasting Dense affine XOR queries exhausted the work budget even for an unconstrained 32-bit projection. Reduce each row against earlier rows before encoding, and transform cell targets by the same operations. Every original prefix and cell remains unchanged, including zero and dependent rows. Validation: exhaustive original-versus-reduced cell comparison across 32 seeds, all three-bit prefixes and targets; prepared-query tests; Aplite tests and doctests; Aplite and Lydite consumer clippy and tests. The downstream 32-bit sampling regression now completes within the default budget. Change-Id: I9afa00067cbc3831d331ed9a987982c4f23fb1f1 --- crates/aplite/src/finite/prepared/hashing.rs | 127 +++++++++++++++++-- 1 file changed, 117 insertions(+), 10 deletions(-) diff --git a/crates/aplite/src/finite/prepared/hashing.rs b/crates/aplite/src/finite/prepared/hashing.rs index 264f1ce3338..02646a8c882 100644 --- a/crates/aplite/src/finite/prepared/hashing.rs +++ b/crates/aplite/src/finite/prepared/hashing.rs @@ -10,6 +10,8 @@ use std::collections::BTreeSet; /// hash family. The implementation uses a deterministic SplitMix64 PRNG, not a /// source of cryptographic entropy. Rows may be zero or dependent: preserving /// those cases is essential to the family; we do not silently repair them. +/// Prefix-preserving Gaussian elimination simplifies rows and transforms target +/// bits together, preserving exactly the original random cells. /// /// `cell` selects a prefix of the rows and a target value for each selected row. /// A caller can measure differently sized cells without recompiling the formula. @@ -20,6 +22,7 @@ pub struct HashCells { query: PreparedQuery, projection: Vec, rows: usize, + transforms: Vec>, preparation_work: u64, } @@ -88,17 +91,55 @@ impl HashCells { } let mut rng = seed; let mut predicates = Vec::new(); - for _ in 0..rows { + let mut echelon: Vec<(Vec, bool, Vec, Option)> = Vec::new(); + let mut transforms = Vec::new(); + for index in 0..rows { budget.tick(1)?; + let mut constant = next(&mut rng) & 1 != 0; + let mut coefficients = Vec::new(); + for _ in &bits { + budget.tick(1)?; + coefficients.push(next(&mut rng) & 1 != 0); + } + budget.tick(rows as u64)?; + let mut transform = vec![false; rows]; + transform[index] = true; + // Only earlier rows participate: every prefix remains equivalent + // to the same prefix of the original random affine hash family. + for (previous, offset, mapping, pivot) in &echelon { + budget.tick(1)?; + if pivot.is_some_and(|pivot| coefficients[pivot]) { + for (bit, other) in coefficients.iter_mut().zip(previous) { + budget.tick(1)?; + *bit ^= other; + } + constant ^= offset; + for (bit, other) in transform.iter_mut().zip(mapping) { + budget.tick(1)?; + *bit ^= other; + } + } + } + let mut pivot = None; + let mut terms = Vec::new(); reserve_terms(&mut created, 1, &budget)?; - let mut terms = vec![boolv(next(&mut rng) & 1 != 0)]; - for bit in &bits { + terms.push(boolv(constant)); + for (position, (&include, bit)) in coefficients.iter().zip(&bits).enumerate() { budget.tick(1)?; - if next(&mut rng) & 1 != 0 { + if include { + pivot.get_or_insert(position); terms.push(bit.clone()); } } predicates.push(parity(&terms, &mut budget, &mut created)?); + transforms.push( + transform + .iter() + .enumerate() + .filter_map(|(i, &bit)| bit.then_some(i)) + .collect(), + ); + echelon.push((coefficients, constant, transform, pivot)); } budget.check_time()?; let mut remaining = limits; @@ -115,6 +156,7 @@ impl HashCells { query, projection: names.into_iter().collect(), rows, + transforms, preparation_work: budget.work, }) } @@ -138,12 +180,25 @@ impl HashCells { reason: Some("hash targets exceed prepared rows or query budget".into()), }; } - let assumptions: Vec<_> = targets - .iter() - .enumerate() - .map(|(predicate, &value)| Assumption { predicate, value }) - .collect(); - let overhead = targets.len() as u64; + let mut overhead = targets.len() as u64; + let mut assumptions = Vec::new(); + for (predicate, mapping) in self.transforms.iter().take(targets.len()).enumerate() { + overhead = overhead.saturating_add(mapping.len() as u64); + if overhead >= limits.max_work + || start.elapsed().as_millis() >= u128::from(limits.timeout_ms) + { + return Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: overhead, + reason: Some("hash target transformation budget exhausted".into()), + }; + } + let value = mapping + .iter() + .fold(false, |value, &index| value ^ targets[index]); + assumptions.push(Assumption { predicate, value }); + } limits.max_work -= overhead; let timeout = limits.timeout_ms; let mut cell = @@ -239,6 +294,58 @@ mod tests { assert!(signatures.len() > 1); } + #[test] + fn elimination_preserves_every_original_affine_prefix_and_target() { + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(3)))]); + for seed in 0..32 { + let cells = HashCells::new(&boolv(true), &context, 3, seed, Limits::default()).unwrap(); + let mut rng = seed; + let original: Vec<_> = (0..3) + .map(|_| { + let constant = next(&mut rng) & 1 != 0; + let mask: Vec<_> = (0..3).map(|_| next(&mut rng) & 1 != 0).collect(); + (constant, mask) + }) + .collect(); + for prefix in 0..=3 { + for target in 0..(1 << prefix) { + let targets: Vec<_> = (0..prefix).map(|i| target & (1 << i) != 0).collect(); + let cell = cells.cell(&targets, 8, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + let actual: BTreeSet<_> = cell + .models + .iter() + .map(|model| { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + value + }) + .collect(); + let expected: BTreeSet<_> = (0..8u64) + .filter(|value| { + original + .iter() + .zip(&targets) + .all(|((constant, mask), target)| { + mask.iter().enumerate().fold( + *constant, + |parity, (i, &include)| { + parity ^ (include && value & (1 << i) != 0) + }, + ) == *target + }) + }) + .collect(); + assert_eq!( + actual, expected, + "seed={seed}, prefix={prefix}, target={target}" + ); + } + } + } + } + #[test] fn construction_and_cell_budgets_fail_closed() { let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); From 7c9ef1c2556121c02ed2431b0849d4f71cb9fc86 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:35:28 +0900 Subject: [PATCH 5/7] feat(aplite): generate approximate projected sample batches Add a seeded Sampler with UniGen2-style parameter estimation and fresh affine XOR cells. Enumerate only bounded cells: spaces with at most 64 projected assignments use an exact small-domain path; larger spaces accept complete cells containing 11 through 63 models and return 11 distinct randomly selected assignments. Preparation caches the immutable formula, projection and estimated parameters. Each fresh hash family currently builds its own encoding. Preparation and each batch have aggregate work/time budgets; failed estimation, incomplete solving and cell rejection remain errors or Unknown with no partial models or heuristic fallback. Only a proved empty space yields Unsat. This is approximate sampling, not an exact-uniformity certificate. Document the fixed kappa and broad epsilon, seeded reproducibility conditions, and remaining SV integration, dist, solve-before and randc work. Validation: 105 Aplite unit tests and 5 doctests, followed by the additional passing permutation regression (106 unit tests total); Lydite IR and solver tests with Z3; clippy for all three crates; formatting; package verification and release/package guards. Regressions cover projected distribution, hidden witnesses, replay, constrained support, 32-bit spaces, permutations and aggregate budget exhaustion. Development-build smoke probes only; no local release build or full RV32I proof run. Change-Id: I6b228ea76629b92831384582faf9308f39b4bf52 --- crates/aplite/README.md | 43 ++ crates/aplite/src/finite.rs | 2 +- crates/aplite/src/finite/prepared.rs | 2 + crates/aplite/src/finite/prepared/sampler.rs | 464 +++++++++++++++++++ crates/aplite/src/lib.rs | 6 +- 5 files changed, 513 insertions(+), 4 deletions(-) create mode 100644 crates/aplite/src/finite/prepared/sampler.rs diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 077f0fec470..f8367b90a8c 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -117,3 +117,46 @@ a cell and then uniformly picking one of its models generally biases results when cells have different sizes. A sampling policy must control cell sizing and acceptance separately. The exhaustive reservoir sampler remains a test-only reference. Rows may be dependent or constant; hash construction preserves those cases. + +## Approximate sample batches + +`Sampler` connects count estimation, cell acceptance and model selection using +the two-stage policy of [UniGen2, algorithms 1 and 2](https://people.eecs.berkeley.edu/~sseshia/pubdir/tacas15.pdf). +It uses fixed kappa=0.638 (pivot 27, accepted cell sizes 11..63), estimates the +number of XOR rows, then tries that count and its two predecessors with fresh +hash families. An accepted cell yields 11 distinct randomly selected models. +A bounded initial probe handles at most 64 total models directly, returning one +random model per call; a larger space is never fully enumerated. + +```rust +use aplite::{Env, Limits, Sampler, Sort, Verdict, boolv, var}; +let projection = Env::from([("data".into(), var("data".into(), Sort::Bv(8)))]); +let mut sampler = Sampler::new(&boolv(true), &projection, 7, Limits::default()).unwrap(); +let batch = sampler.sample_batch(Limits::default()); +match batch.verdict { + Verdict::Sat => assert!(!batch.models.is_empty()), + Verdict::Unsat => panic!("this unconstrained query is satisfiable"), + Verdict::Unknown => assert!(batch.models.is_empty()), +} +``` + +Preparation caches the formula/projection snapshot and estimated count parameters. +Each fresh hash family currently builds its own encoding; searches within its cell +reuse that encoding and local learned clauses. Gaussian elimination simplifies +XOR rows and transforms target bits together, preserving every original cell and +prefix. This avoids sending a dense redundant linear system directly to CDCL. + +This is **approximate sampling**, not a claim of exact uniformity or independent +samples. The paper's ideal-randomness guarantees are not a certification of this +seeded, resource-bounded implementation. Its fixed tolerance is broad (epsilon +approximately 16.09); empirical frequency tests do not establish a tighter bound. +A failed estimate or an unsuccessful three-cell attempt is reported as an error +or `Unknown`, never a heuristic sample or an UNSAT verdict. A complete empty +initial probe is the only source of UNSAT. There is no automatic fallback. + +One budget covers preparation and a separate budget covers each complete batch +request. Unknown returns no partial batch. Work after an unreported preparation +failure is conservatively charged to the remaining work limit. Changing state +variables or constraints requires a new sampler. Weighted distributions, +`solve before`, `randc`, and SystemVerilog frontend/runtime integration are not +implemented by this API. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index 62443ec8663..a95699b98ba 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -16,7 +16,7 @@ mod control; mod lookup; mod prepared; mod readonly; -pub use prepared::{Assumption, Cell, CellStatus, HashCells, PreparedQuery}; +pub use prepared::{Assumption, Cell, CellStatus, HashCells, PreparedQuery, SampleBatch, Sampler}; pub use readonly::ArrayModel; type Lit = i32; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs index 36f5d3916b9..ac4b83caa07 100644 --- a/crates/aplite/src/finite/prepared.rs +++ b/crates/aplite/src/finite/prepared.rs @@ -3,8 +3,10 @@ use super::*; mod cell; mod hashing; +mod sampler; pub use cell::{Cell, CellStatus}; pub use hashing::HashCells; +pub use sampler::{SampleBatch, Sampler}; /// Select the polarity of a predicate supplied when preparing the query. #[derive(Clone, Copy, Debug)] diff --git a/crates/aplite/src/finite/prepared/sampler.rs b/crates/aplite/src/finite/prepared/sampler.rs new file mode 100644 index 00000000000..0bfb75ee2c8 --- /dev/null +++ b/crates/aplite/src/finite/prepared/sampler.rs @@ -0,0 +1,464 @@ +//! UniGen2-style projected batch sampling. See algorithms 1 and 2 in +//! +use super::*; + +// kappa=0.638: pivot=ceil(4.03*(1+1/kappa)^2)=27, +// lo=floor(pivot/(sqrt(2)*(1+kappa)))=11, +// hi=ceil(1+sqrt(2)*(1+kappa)*pivot)=64. +const PIVOT: f64 = 27.; +const LOW: usize = 11; +const HIGH: usize = 64; +const ESTIMATE_BOUND: usize = 60; + +type Model = BTreeMap; + +enum Mode { + Small(Vec), + Hashed { bits: isize }, +} + +/// Outcome of one bounded batch request. SAT batches contain only validated +/// projected assignments. Unknown never exposes an incomplete batch. +#[derive(Debug)] +pub struct SampleBatch { + pub verdict: Verdict, + pub models: Vec, + pub work: u64, + pub cells: usize, + pub reason: Option, +} + +/// Seeded approximate projected sampler following the UniGen2 two-stage policy. +/// +/// A bounded probe handles at most 64 total models exactly. Larger spaces use +/// randomized XOR count estimation, then fresh hash families at the +/// estimated row count and its two predecessors. Only complete cells with +/// 11..=63 models are accepted; each returns 11 distinct randomly chosen models. +/// Small spaces return one uniformly selected model per call. +/// +/// The large-space policy is approximate, not exact uniform or independent +/// sampling. The paper's ideal-randomness theorems are not a certification of this +/// seeded, resource-bounded implementation. There is no heuristic fallback on +/// failure. Unknown includes failed parameter estimation or cell acceptance, +/// and must not be translated into SystemVerilog randomize()==0. +/// +/// Formula and projection are immutable snapshots. Preparation and each batch +/// have separate aggregate budgets. Seed replay requires identical call history, +/// solver version and budgets sufficient to finish. No global RNG is used. +pub struct Sampler { + formula: Term, + projection: Env, + width: usize, + rng: u64, + mode: Mode, + preparation_work: u64, +} + +impl Sampler { + pub fn new(formula: &Term, projection: &Env, seed: u64, limits: Limits) -> Res { + let mut budget = new_budget(limits); + budget.tick(1)?; + let mut sampler = Self { + formula: formula.clone(), + projection: projection.clone(), + width: 0, + rng: seed, + mode: Mode::Small(Vec::new()), + preparation_work: 0, + }; + // HashCells validates variable identity, widths and all source terms. + let tiny = sampler.query_cell(0, HIGH, &mut budget)?; + if tiny.status == CellStatus::Complete { + sampler.mode = Mode::Small(tiny.models); + } else { + for term in projection.values() { + budget.tick(1)?; + sampler.width += match term.0.sort { + Sort::Bool => 1, + Sort::Bv(w) => w as usize, + _ => unreachable!(), + }; + } + let mut estimate = None; + // Every attempt uses a fresh hash, as required by Algorithm 1. + for rows in 1..=sampler.width { + let cell = sampler.query_cell(rows, ESTIMATE_BOUND, &mut budget)?; + if cell.status == CellStatus::Complete && !cell.models.is_empty() { + let bits = ((cell.models.len() as f64).log2() + rows as f64 + 1.8f64.log2() + - PIVOT.log2()) + .round() as isize; + estimate = Some(bits); + break; + } + } + sampler.mode = Mode::Hashed { + bits: estimate.ok_or("sampling parameter estimation failed")?, + }; + } + budget.check_time()?; + sampler.preparation_work = budget.work; + Ok(sampler) + } + + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + pub fn sample_batch(&mut self, limits: Limits) -> SampleBatch { + let mut budget = new_budget(limits); + let mut result = SampleBatch { + verdict: Verdict::Unknown, + models: Vec::new(), + work: 0, + cells: 0, + reason: None, + }; + let run = (|| -> Res { + budget.tick(1)?; + match &self.mode { + Mode::Small(models) => { + if models.is_empty() { + return Ok(Verdict::Unsat); + } + let index = draw(&mut self.rng, models.len(), &mut budget)?; + budget.tick(1 + models[index].len() as u64)?; + result.models.push(models[index].clone()); + } + Mode::Hashed { bits } => { + let bits = *bits; + for rows in [bits - 2, bits - 1, bits] { + // Do not clamp an invalid estimate into a different hash + // policy. Skip undefined row counts and fail if none work. + if rows < 0 || rows as usize > self.width { + continue; + } + result.cells += 1; + let mut cell = self.query_cell(rows as usize, HIGH - 1, &mut budget)?; + if cell.status != CellStatus::Complete || cell.models.len() < LOW { + continue; + } + // Partial Fisher-Yates: unbiased bounded draws and no + // replacement, including order within the returned batch. + for index in 0..LOW { + let chosen = index + + draw(&mut self.rng, cell.models.len() - index, &mut budget)?; + cell.models.swap(index, chosen); + } + cell.models.truncate(LOW); + result.models = cell.models; + return Ok(Verdict::Sat); + } + return Err("sampling found no cell in the accepted size interval".into()); + } + } + Ok(Verdict::Sat) + })(); + match run.and_then(|verdict| { + budget.check_time()?; + Ok(verdict) + }) { + Ok(verdict) => result.verdict = verdict, + Err(reason) => { + result.models.clear(); + result.reason = Some(reason); + } + } + result.work = budget.work; + result + } + + fn query_cell(&mut self, rows: usize, bound: usize, budget: &mut Budget) -> Res { + budget.tick(1)?; + let seed = next(&mut self.rng); + let prepare_limits = remaining(budget)?; + let cells = + match HashCells::new(&self.formula, &self.projection, rows, seed, prepare_limits) { + Ok(cells) => cells, + Err(reason) => { + // Preparation's error API has no partial work count. Reserve + // the remaining work budget conservatively and abort, never retry. + budget.work = budget.limits.max_work; + return Err(reason); + } + }; + budget.tick(cells.preparation_work())?; + let mut targets = Vec::new(); + for _ in 0..rows { + budget.tick(1)?; + targets.push(next(&mut self.rng) & 1 != 0); + } + let cell = cells.cell(&targets, bound, remaining(budget)?); + budget.tick(cell.work)?; + budget.check_time()?; + if cell.status == CellStatus::Unknown { + return Err(cell + .reason + .unwrap_or_else(|| "sampling cell query was incomplete".into())); + } + Ok(cell) + } +} + +fn new_budget(limits: Limits) -> Budget { + Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + } +} +fn remaining(budget: &Budget) -> Res { + budget.check_time()?; + let mut limits = budget.limits.clone(); + limits.max_work = limits + .max_work + .checked_sub(budget.work) + .ok_or("sampling work budget exhausted")?; + limits.timeout_ms = limits + .timeout_ms + .checked_sub(u64::try_from(budget.start.elapsed().as_millis()).unwrap_or(u64::MAX)) + .filter(|&ms| ms > 0) + .ok_or("sampling time budget exhausted")?; + Ok(limits) +} +fn next(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut value = *state; + value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); + value ^ (value >> 31) +} +fn draw(state: &mut u64, count: usize, budget: &mut Budget) -> Res { + let count = count as u64; + let threshold = count.wrapping_neg() % count; + loop { + budget.tick(1)?; + let value = next(state); + if value >= threshold { + return Ok((value % count) as usize); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{boolv, bv, eq, node, var}; + use std::collections::BTreeSet; + + #[test] + fn small_domain_distribution_replay_and_hidden_projection() { + let x = var("x".into(), Sort::Bv(2)); + let hidden = var("hidden".into(), Sort::Bool); + let formula = node(Sort::Bool, "or", vec![eq(x.clone(), bv(2, 0)), hidden]); + let projection = Env::from([("label".into(), x)]); + let mut a = Sampler::new(&formula, &projection, 42, Limits::default()).unwrap(); + let mut b = Sampler::new(&formula, &projection, 42, Limits::default()).unwrap(); + let mut counts = [0; 4]; + for _ in 0..2048 { + let batch = a.sample_batch(Limits::default()); + assert_eq!(batch.verdict, Verdict::Sat); + assert_eq!(batch.models, b.sample_batch(Limits::default()).models); + let Scalar::Bv { value, .. } = batch.models[0]["x"] else { + panic!() + }; + counts[value as usize] += 1; + } + assert!( + counts.iter().all(|&count| (400..625).contains(&count)), + "{counts:?}" + ); + } + + #[test] + fn hashed_batches_are_complete_valid_unique_and_reproducible() { + let projection = Env::from([("x".into(), var("x".into(), Sort::Bv(7)))]); + let mut a = Sampler::new(&boolv(true), &projection, 7, Limits::default()).unwrap(); + let mut b = Sampler::new(&boolv(true), &projection, 7, Limits::default()).unwrap(); + assert!(matches!(a.mode, Mode::Hashed { .. })); + let mut counts = [0; 128]; + let mut successes = 0; + for _ in 0..64 { + let batch = a.sample_batch(Limits::default()); + let replay = b.sample_batch(Limits::default()); + assert_eq!(batch.verdict, replay.verdict); + assert_eq!(batch.models, replay.models); + if batch.verdict == Verdict::Unknown { + assert!(batch.models.is_empty()); + continue; + } + assert_eq!(batch.verdict, Verdict::Sat); + assert_eq!(batch.models.len(), LOW); + let mut distinct = BTreeSet::new(); + for model in batch.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + assert!(value < 128); + assert!(distinct.insert(value)); + counts[value as usize] += 1; + } + successes += 1; + } + assert!(successes > 32); + assert!(counts.iter().filter(|&&n| n > 0).count() > 110); + } + + #[test] + fn unsat_unknown_and_empty_projection_are_distinct() { + let mut empty = Sampler::new(&boolv(false), &Env::new(), 0, Limits::default()).unwrap(); + assert_eq!( + empty.sample_batch(Limits::default()).verdict, + Verdict::Unsat + ); + let mut unit = Sampler::new(&boolv(true), &Env::new(), 0, Limits::default()).unwrap(); + assert_eq!( + unit.sample_batch(Limits::default()).models, + vec![BTreeMap::new()] + ); + let failed = unit.sample_batch(Limits { + max_work: 0, + ..Limits::default() + }); + assert_eq!(failed.verdict, Verdict::Unknown); + assert!(failed.models.is_empty()); + assert_eq!(unit.sample_batch(Limits::default()).verdict, Verdict::Sat); + assert!( + Sampler::new( + &boolv(true), + &Env::new(), + 0, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .is_err() + ); + } + + #[test] + fn batch_budget_is_global_and_failure_does_not_return_partial_models() { + let projection = Env::from([("x".into(), var("x".into(), Sort::Bv(7)))]); + let mut complete = Sampler::new(&boolv(true), &projection, 7, Limits::default()).unwrap(); + let batch = complete.sample_batch(Limits::default()); + assert_eq!(batch.verdict, Verdict::Sat); + for work in [0, 5, batch.work - 1] { + let mut limited = + Sampler::new(&boolv(true), &projection, 7, Limits::default()).unwrap(); + let result = limited.sample_batch(Limits { + max_work: work, + ..Limits::default() + }); + assert_eq!(result.verdict, Verdict::Unknown); + assert!(result.models.is_empty()); + } + let timed = complete.sample_batch(Limits { + timeout_ms: 0, + ..Limits::default() + }); + assert_eq!(timed.verdict, Verdict::Unknown); + assert!(timed.models.is_empty()); + assert!( + Sampler::new( + &boolv(true), + &projection, + 7, + Limits { + max_work: 100, + ..Limits::default() + } + ) + .is_err() + ); + } + + #[test] + fn constrained_large_branch_never_returns_outside_projected_support() { + let x = var("x".into(), Sort::Bv(8)); + let formula = node(Sort::Bool, "bvult", vec![x.clone(), bv(8, 100)]); + let projection = Env::from([("x".into(), x)]); + let mut sampler = Sampler::new(&formula, &projection, 13, Limits::default()).unwrap(); + assert!(matches!(sampler.mode, Mode::Hashed { .. })); + let mut seen = BTreeSet::new(); + let mut batches = 0; + for _ in 0..64 { + let batch = sampler.sample_batch(Limits::default()); + if batch.verdict == Verdict::Unknown { + assert!(batch.models.is_empty()); + continue; + } + assert_eq!(batch.verdict, Verdict::Sat); + batches += 1; + for model in batch.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + assert!(value < 100); + seen.insert(value); + } + } + assert!(batches > 32); + assert!(seen.len() > 90); + } + + #[test] + fn permutation_batch_contains_valid_distinct_projected_assignments() { + let variables: Vec<_> = (0..8).map(|i| var(format!("x{i}"), Sort::Bv(3))).collect(); + let mut formula = boolv(true); + for i in 0..8 { + for j in i + 1..8 { + formula = crate::and( + formula, + crate::not(eq(variables[i].clone(), variables[j].clone())), + ); + } + } + let context: Env = variables + .into_iter() + .enumerate() + .map(|(i, term)| (format!("x{i}"), term)) + .collect(); + let limits = Limits { + timeout_ms: 30_000, + ..Limits::default() + }; + let mut sampler = Sampler::new(&formula, &context, 42, limits.clone()).unwrap(); + let batch = sampler.sample_batch(limits); + assert_eq!(batch.verdict, Verdict::Sat, "{:?}", batch.reason); + assert_eq!(batch.models.len(), LOW); + let mut assignments = BTreeSet::new(); + for model in batch.models { + let values: Vec<_> = model + .values() + .map(|value| { + let Scalar::Bv { value, .. } = value else { + panic!() + }; + *value + }) + .collect(); + assert_eq!( + values.iter().copied().collect::>(), + (0..8).collect() + ); + assert!(assignments.insert(values)); + } + } + + #[test] + fn wide_domain_is_sampled_without_full_enumeration() { + let projection = Env::from([("x".into(), var("x".into(), Sort::Bv(32)))]); + let mut sampler = Sampler::new(&boolv(true), &projection, 42, Limits::default()).unwrap(); + assert!(matches!(sampler.mode, Mode::Hashed { .. })); + for _ in 0..4 { + let batch = sampler.sample_batch(Limits::default()); + if batch.verdict == Verdict::Sat { + assert_eq!(batch.models.len(), LOW); + return; + } + assert!(batch.models.is_empty()); + } + panic!("no complete batch for wide-domain smoke test"); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index c9cad434b1a..f120eae399b 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -4,14 +4,14 @@ //! The solver runs in process, without an external SMT executable. Unsupported //! expressions and exhausted resource budgets return [`Verdict::Unknown`]. //! SAT models are replayed against the original formula; UNSAT trusts the solver. -//! This crate does not provide uniform sampling of satisfying assignments. +//! Hash-based batch sampling is approximate, not a uniformity certificate. pub mod term; pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Assumption, Cell, CellStatus, HashCells, Limits, Outcome, PreparedQuery, Scalar, SearchHint, - Verdict, solve, solve_seeded, solve_with_hint, + Assumption, Cell, CellStatus, HashCells, Limits, Outcome, PreparedQuery, SampleBatch, Sampler, + Scalar, SearchHint, Verdict, solve, solve_seeded, solve_with_hint, }; #[cfg(test)] From a24ad1138e71b67dfe78aba93b8a36a71ddc4027 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 03:07:40 +0900 Subject: [PATCH 6/7] feat(sv-syntax)!: retain named constraint expressions Retain names and expression nodes for simple class constraint blocks so the analyzer can bind them for randomize. Mark prototypes and unsupported control, soft, distribution and ordering forms explicitly, preventing partial enforcement. Reject duplicate declarations in a class while leaving inheritance override handling to the analyzer. Validation: 132 syntax tests and doctests; analyzer regression suite; focused retained-expression test; clippy. BREAKING CHANGE: ClassDeclaration has a new constraints field. Change-Id: Ic0c2bccf33129288214910a3fbf1ff120734ff4b --- crates/celox-sv-syntax/src/nodes.rs | 9 ++++ crates/celox-sv-syntax/src/parser/classes.rs | 1 + .../celox-sv-syntax/src/parser/constraints.rs | 48 ++++++++++++++++--- crates/celox-sv-syntax/src/parser/tests.rs | 11 +++++ 4 files changed, 62 insertions(+), 7 deletions(-) diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index 7d4a6be5969..219e8a8fea3 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -960,6 +960,14 @@ pub struct VariableDeclaration { pub tokens: TokenRange, } +/// A named constraint block. Unsupported constraint forms retain their name +/// but no executable expressions, so randomization cannot silently ignore them. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassConstraint { + pub name: Name, + pub expressions: Option>, +} + /// A class declaration (IEEE 1800-2023 8.3). Its body also remains an /// unconverted body item covering the same tokens. #[derive(Clone, Debug, Eq, PartialEq)] @@ -976,6 +984,7 @@ pub struct ClassDeclaration { pub interfaces: Vec, /// Whether the class declares constraints, including prototypes. pub has_constraints: bool, + pub constraints: Vec, /// The parameter port list `#(...)`, after which the parameters the /// body declares are local (8.25). pub parameter_ports: Option, diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index bed49079811..637f457812e 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -223,6 +223,7 @@ impl Parser<'_> { base, interfaces, has_constraints: false, + constraints: Vec::new(), parameter_ports, parameters: Vec::new(), type_aliases: Vec::new(), diff --git a/crates/celox-sv-syntax/src/parser/constraints.rs b/crates/celox-sv-syntax/src/parser/constraints.rs index 3dcdfc0bbc4..2469d9465da 100644 --- a/crates/celox-sv-syntax/src/parser/constraints.rs +++ b/crates/celox-sv-syntax/src/parser/constraints.rs @@ -1,5 +1,5 @@ //! Class constraint syntax validation. Constraints retain their opaque class -//! owner; no randomization or solver semantics are introduced here. +//! owner. Simple expression blocks also retain their expression nodes. use super::*; enum Job { @@ -32,10 +32,26 @@ impl Parser<'_> { class.has_constraints = true; } let prototype = self.eat("extern") || self.eat("pure"); - self.eat("static"); + let is_static = self.eat("static"); self.expect("constraint")?; - self.name()?; + let name = self.name()?; + if self.class_stack.last().is_some_and(|class| { + class + .constraints + .iter() + .any(|block| block.name.spelling == name.spelling) + }) { + return Err(self.error("duplicate constraint block")); + } + let mut expressions = Vec::new(); + let mut supported = !is_static; if self.eat(";") { + if let Some(class) = self.class_stack.last_mut() { + class.constraints.push(ClassConstraint { + name, + expressions: None, + }); + } return Ok(()); } if prototype { @@ -52,6 +68,7 @@ impl Parser<'_> { } jobs.push(Job::Block(solve)); if solve && self.eat("solve") { + supported = false; self.constraint_primary_list()?; self.expect("before")?; self.constraint_primary_list()?; @@ -74,32 +91,41 @@ impl Parser<'_> { } Job::Expression => { if self.eat("if") { + supported = false; self.expect("(")?; self.expression(0)?; self.expect(")")?; jobs.push(Job::Else); jobs.push(Job::Set); } else if self.eat("foreach") { + supported = false; self.foreach_header()?; jobs.push(Job::Set); } else if self.eat("disable") { + supported = false; self.expect("soft")?; self.constraint_primary()?; self.expect(";")?; } else if self.eat("unique") { + supported = false; self.constraint_ranges(false)?; self.expect(";")?; } else { let soft = self.eat("soft"); if soft { + supported = false; self.expression(0)?; } else { - self.constraint_condition()?; + let (expression, simple) = self.constraint_condition()?; + expressions.push(expression); + supported &= simple; } if !soft && self.eat("->") { + supported = false; jobs.push(Job::Set); } else { if self.eat("dist") { + supported = false; self.constraint_ranges(true)?; } self.expect(";")?; @@ -108,17 +134,25 @@ impl Parser<'_> { } } } + if let Some(class) = self.class_stack.last_mut() { + class.constraints.push(ClassConstraint { + name, + expressions: supported.then_some(expressions), + }); + } Ok(()) } - fn constraint_condition(&mut self) -> Result<()> { + fn constraint_condition(&mut self) -> Result<(ExprId, bool)> { // Keep the constraint-set arrow for the outer continuation. Equivalence // shares its expression precedence, so consume it explicitly here. - self.expression(2)?; + let expression = self.expression(2)?; + let mut simple = true; while self.eat("<->") { + simple = false; self.expression(2)?; } - Ok(()) + Ok((expression, simple)) } fn constraint_ranges(&mut self, distribution: bool) -> Result<()> { diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index c6b29330e73..53d0d1c822a 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -3043,3 +3043,14 @@ fn malformed_array_method_with_is_rejected() { ); } } + +#[test] +fn constraints_retain_simple_expressions_and_mark_other_forms() { + let tree = parse( + "class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } endclass", + ); + let blocks = &tree.classes[0].constraints; + assert_eq!(blocks[0].name.spelling, "a"); + assert_eq!(blocks[0].expressions.as_ref().unwrap().len(), 2); + assert!(blocks[1].expressions.is_none()); +} From 668ab648668175e60ed91a88dfb79946eba0ba58 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 03:29:16 +0900 Subject: [PATCH 7/7] test(sv-tests): classify failures and summarize diagnostics Official sv-tests failures currently share one verdict even when they indicate unsupported constructs, compilation diagnostics, output assertion failures, unexpected negative-test success, timeout, crashes or input/environment problems. Annotate observed evidence without changing the official verdict, dashboard denominator or expected.tsv. Unknown, absent and inconsistent evidence remains unclassified. Add per-state/group category and frequent-diagnostic summaries, a failing-case JSON index and a readable CI job summary. Surface negative-test passes with suspicious unsupported/crash/timeout diagnostics separately. Retain completed rows and structured collection errors after infrastructure failures, mark reports incomplete and continue to prohibit expectation updates. Cancel queued work on collection errors and interruptions. Provide reporting.py to reclassify saved TSV/log artifacts with relocated log roots and optional pinned meta-tags. Preserve incomplete provenance and mark old reports with unknown completeness instead of claiming a full run. Validation: all 27 Python contract tests pass against the actual pinned upstream tools/runner, including timeout, negative tests, parallel infrastructure failure, baseline protection and stale-report replacement. Focused classifier tests also pass after diagnostic excerpt changes. Reclassified 3,300 historical rows with every verdict and every original summary field unchanged. CI YAML parses and git diff --check passes. No Rust/compiler or corpus changes; no fresh full simulator run or release build. This PR is based directly on master and does not depend on the Aplite/randomize stack. Change-Id: Ic9bf68f5d4ba127e3e62cd9993a4b8cd1aee80d1 --- .github/workflows/ci.yml | 11 ++ conformance/sv-tests/README.md | 67 +++++++- conformance/sv-tests/reporting.py | 211 +++++++++++++++++++++++++ conformance/sv-tests/run.py | 73 ++++++--- conformance/sv-tests/test_reporting.py | 131 +++++++++++++++ conformance/sv-tests/test_runner.py | 28 +++- 6 files changed, 495 insertions(+), 26 deletions(-) create mode 100644 conformance/sv-tests/reporting.py create mode 100644 conformance/sv-tests/test_reporting.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d403ce24246..8fce6137741 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -538,6 +538,15 @@ jobs: --expected conformance/sv-tests/expected.tsv --report "$RUNNER_TEMP/sv-tests-report.tsv" + - name: Summarize sv-tests failures + if: always() + shell: bash + run: | + report="$RUNNER_TEMP/sv-tests-report.summary.md" + if [ -f "$report" ]; then + cat "$report" >> "$GITHUB_STEP_SUMMARY" + fi + - name: Retain the report and official per-case logs if: always() uses: actions/upload-artifact@v7 @@ -546,6 +555,8 @@ jobs: path: | ${{ runner.temp }}/sv-tests-report.tsv ${{ runner.temp }}/sv-tests-report.summary.json + ${{ runner.temp }}/sv-tests-report.summary.md + ${{ runner.temp }}/sv-tests-report.failures.json ${{ runner.temp }}/sv-tests-results if-no-files-found: ignore retention-days: 14 diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index aeb7df2da7b..03aae132116 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -45,7 +45,7 @@ modes, sources without a module still undergo preprocessing and parsing; root detection then reports the actual no-root diagnostic. The current compiler and simulator require a module root, so the driver reports a failure for rootless unit, package and interface inputs. The official runner still decides -the case verdict, including expected failures. There is no `no_top` classification +the case verdict, including expected failures. There is no `no_top` verdict or preemptive skip. Without an explicit top, the driver infers a single root from parsed declarations and instantiations; multiple roots receive a diagnostic because Celox’s simulator requires one root. Each input file is a separate @@ -341,3 +341,68 @@ These fixtures exercise the actual upstream runner with a controlled driver, including mode priority, skips, negative tests, assertions, timeouts, library injection and missing-environment failures. The Rust example is a single-case compiler/simulator driver; it does not parse sv-tests metadata or judge verdicts. + +## Failure triage + +`run.py` now writes four companion artifacts: + +- `report.tsv`: official verdicts plus `failure_category`, `diagnostic`, a bounded + diagnostic excerpt (`evidence`), and `negative_test` (`1`, `0`, or empty when unknown). +- `report.summary.json`: schema version 2, collection completeness, requested and + collected row counts, per-group/per-state totals, failure counts and frequent + diagnostics. `classification_version` identifies the diagnostic rules. +- `report.summary.md`: a readable overview, also attached to the CI job summary. +- `report.failures.json`: every failing case with its classification and log path, + plus collection errors. No case is removed from the TSV or denominator. + +Categories describe **observed diagnostics**, not proven compiler root causes: + +| Category | Evidence | +| --- | --- | +| `unsupported` | explicit unsupported-construct or single-module-root diagnostic | +| `compile_error` | parse-error or illegal-context diagnostic, even if the selected mode was simulation | +| `runtime_error` | `$fatal` or lost-runtime-event diagnostic | +| `assertion_failure` | official simulation output validation failed after a successful positive invocation | +| `unexpected_success` | a negative test's driver succeeded | +| `timeout` | upstream timeout return code **and** timeout diagnostic | +| `crash` | Rust panic diagnostic or abnormal/signal return code | +| `input_issue` | the reviewed upstream input defect described above | +| `environment` | missing include directory without the reviewed input exception | +| `unclassified` | unknown diagnostic, missing log, or TSV/log metadata disagreement | + +For example, a parser error on a valid but unimplemented grammar construct is +still `compile_error`; the classifier does not guess whether the source or the +parser is wrong. A nonzero return code in simulation mode alone does not establish +a runtime bug because compilation may have failed first. Frequent diagnostic +counts normalize source paths and line numbers; `.failures.json` retains the +individual evidence and log locations. Tag counts still overlap as described above. + +Negative-test passes accompanied by unsupported, root-requirement, timeout or +crash diagnostics appear in `negative_pass_diagnostics` for review. They remain +**official passes**, not new failures. No assertion expression is evaluated by +this classification code. + +Missing drivers, missing libraries, runner exceptions and other collection +errors still return exit code 2 and prohibit `--update`. A failed collection now +retains already completed rows and separate `collection_errors`, with +`complete: false`; cancelled/unrun cases do not become invented failure rows. +An incomplete report must not be used as a full conformance score. Successful +collection has `complete: true` even when comparison with expectations returns 1. + +Reclassify a downloaded or older **run report**, without rerunning simulations or +changing `expected.tsv`: + +```bash +python conformance/sv-tests/reporting.py work/sv-tests-report.tsv \ + --log-root work/sv-tests-results \ + --meta-tags ../sv-tests/conf/meta-tags.conf \ + --output work/triage/report.tsv +``` + +`--log-root` relocates logs using `STATE/TEST/official.log`. Otherwise the paths +in the TSV are used (relative paths resolve against the TSV directory). +`--meta-tags` should reference the matching pinned checkout; omit it to count +only literal tags, reported as `meta_tags_expanded: false`. The existing summary +supplies the corpus revision and incomplete-collection provenance. Without a +completeness marker in that summary, offline reports use `complete: null` +(unknown), not a claim that every case ran. Missing logs stay unclassified. diff --git a/conformance/sv-tests/reporting.py b/conformance/sv-tests/reporting.py new file mode 100644 index 00000000000..21d3c427679 --- /dev/null +++ b/conformance/sv-tests/reporting.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Classify sv-tests diagnostics without changing the official runner verdicts.""" + +import argparse +from collections import Counter +import csv +import json +from pathlib import Path +import re +import sys + +CLASSIFICATION_VERSION = 1 +FIELDS = ("failure_category", "diagnostic", "evidence", "negative_test") +BASE_FIELDS = ("test", "state_mode", "result", "mode", "tags", "group", + "input_issue", "rc", "tool_success", "log") + + +def classify(row, log): + """Evidence labels, not a second verdict evaluator or a proof of root cause.""" + meta, separator, body = log.partition("\n\n") + metadata = dict(line.split(": ", 1) for line in meta.splitlines() if ": " in line) if separator else {} + # BaseRunner puts the invocation on the first line, except on timeout. + lines = body.splitlines() if separator else [] + if lines and not lines[0].startswith("Timeout: > "): + lines = lines[1:] + text = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(lines)) + rc = metadata.get("rc", row.get("rc", "")) + success = metadata.get("tool_success", row.get("tool_success", "")) + negative = metadata.get("should_fail", "") == "1" + category, diagnostic = "unclassified", "unrecognized_diagnostic" + evidence = next((line.strip() for line in text.splitlines() if line.strip()), "no driver diagnostic") + if not log: + diagnostic, evidence = "missing_log", "official log is unavailable" + elif row.get("input_issue"): + category, diagnostic, evidence = "input_issue", "reviewed_upstream_input", row["input_issue"] + elif rc == "71" and re.search(r"^Timeout: > \d+s$", text, re.MULTILINE): + category, diagnostic = "timeout", "runner_timeout" + elif re.search(r"^thread .* panicked at", text, re.MULTILINE): + category, diagnostic = "crash", "rust_panic" + evidence = re.search(r"^thread .* panicked at.*$", text, re.MULTILINE)[0] + elif re.fullmatch(r"-?\d+", rc) and (int(rc) < 0 or int(rc) >= 126): + category, diagnostic, evidence = "crash", "abnormal_exit", f"driver return code {rc}" + elif row["result"] == "fail" and success == "1" and negative: + category, diagnostic, evidence = "unexpected_success", "negative_test_succeeded", "negative test: driver succeeded" + elif row["result"] == "fail" and success == "1" and metadata.get("should_fail") == "0" and row.get("mode") == "simulation": + category, diagnostic, evidence = "assertion_failure", "official_output_validation", "official simulation output validation failed" + elif re.search(r"^unsupported_simulator_parser$|^Unsupported SystemVerilog construct:", text, re.MULTILINE): + category, diagnostic = "unsupported", "unsupported_construct" + # Join miette's wrapped diagnostic, keeping the specific missing feature. + clean = " ".join(line.strip(" │×╰─") for line in text.splitlines() if line.strip()) + match = re.search(r"Unsupported SystemVerilog construct: (.*)", clean) + evidence = match[1].rstrip(") ") if match else evidence + elif text.startswith("elaboration requires a module root;") or text.startswith("multiple module roots ("): + category, diagnostic = "unsupported", "module_root_requirement" + elif text.startswith("SystemVerilog parse error:"): + category, diagnostic = "compile_error", "parse_error" + elif re.search(r"^illegal_context$", text, re.MULTILINE): + category, diagnostic = "compile_error", "illegal_context" + elif re.search(r"^.*include directory is unavailable:", text, re.MULTILINE): + category, diagnostic = "environment", "missing_include_directory" + elif re.search(r"^\$fatal: |^\d+ runtime events were lost$", text, re.MULTILINE): + category, diagnostic = "runtime_error", "runtime_diagnostic" + evidence = re.search(r"^\$fatal: .*|^\d+ runtime events were lost$", text, re.MULTILINE)[0] + if row["result"] == "pass" and success == "1": + diagnostic, evidence = "", "" + if log and any(row.get(key) and metadata.get(key) != row[key] for key in ("rc", "mode", "tool_success")): + category, diagnostic, evidence = "unclassified", "metadata_mismatch", "TSV and official log metadata disagree" + # Driver failure in simulation mode can still be a compiler failure. Leave + # unknown diagnostics unclassified instead of labelling them runtime bugs. + return { + "failure_category": category if row["result"] == "fail" else "", + "diagnostic": diagnostic if row["result"] != "skip" else "", + "evidence": evidence[:1000] if row["result"] != "skip" else "", + "negative_test": "1" if negative else "0" if metadata.get("should_fail") == "0" else "", + } + + +def annotate(row, log): + return {**row, **classify(row, log)} + + +def breakdown(rows): + failures = [row for row in rows if row["result"] == "fail"] + counts = Counter(row.get("failure_category") or "unclassified" for row in failures) + diagnostics = Counter((row.get("failure_category") or "unclassified", row.get("diagnostic") or "unknown") + for row in failures) + reasons = Counter() + examples = {} + for row in failures: + evidence = re.sub(r"\S+\.svh?:\d+(?::\d+)?:?", "", row.get("evidence", "")) + key = (row.get("failure_category") or "unclassified", row.get("diagnostic") or "unknown", evidence) + reasons[key] += 1 + examples.setdefault(key, {"test": row.get("test", ""), "log": row.get("log", "")}) + return { + "by_failure_reason": [{"category": key[0], "diagnostic": key[1], "evidence": key[2], + "count": count, "example": examples[key]} + for key, count in sorted(reasons.items(), key=lambda item: (-item[1], item[0]))], + "by_failure_category": dict(sorted(counts.items())), + "by_failure_diagnostic": [{"category": category, "diagnostic": diagnostic, "count": count} + for (category, diagnostic), count in sorted(diagnostics.items())], + "negative_pass_diagnostics": dict(sorted(Counter( + row["diagnostic"] for row in rows + if row["result"] == "pass" and row.get("negative_test") == "1" + and row.get("diagnostic") in {"unsupported_construct", "module_root_requirement", "runner_timeout", "rust_panic", "abnormal_exit"} + ).items())), + } + + +def markdown(summary): + def cell(value): + return str(value).replace("|", "\\|").replace("\n", " ") + lines = ["# sv-tests results", "", f"Corpus revision: `{summary.get('revision') or 'unknown'}`", ""] + if summary["complete"] is None: + lines += ["**Collection completeness is unknown: the source report has no completeness marker.**", ""] + elif not summary["complete"]: + lines += ["**INCOMPLETE: collection failed. These totals are not a full conformance result.**", ""] + lines += ["| Group | State | Pass / executed | Pass % | Skipped |", "| --- | --- | ---: | ---: | ---: |"] + for group, states in summary["groups"].items(): + for state, counts in states.items(): + lines.append(f"| {cell(group)} | {state} | {counts['passed']} / {counts['executed']} | {counts['pass_percent']} | {counts['skipped']} |") + lines += ["", "## Failure categories", "", "| Group | State | Category | Count |", "| --- | --- | --- | ---: |"] + for group, states in summary["groups"].items(): + for state, counts in states.items(): + for category, count in counts["by_failure_category"].items(): + lines.append(f"| {cell(group)} | {state} | {category} | {count} |") + for group, states in summary["groups"].items(): + for state, counts in states.items(): + if counts["by_failure_reason"]: + lines += ["", f"### Frequent diagnostics: {cell(group)} / {state}", "", + "| Count | Category | Diagnostic | Evidence |", "| ---: | --- | --- | --- |"] + for reason in counts["by_failure_reason"][:10]: + lines.append(f"| {reason['count']} | {reason['category']} | {reason['diagnostic']} | {cell(reason['evidence'][:200])} |") + if counts["negative_pass_diagnostics"]: + lines += ["", f"Negative-test passes requiring diagnostic review ({cell(group)}, {state}): " + + cell(counts["negative_pass_diagnostics"]), ""] + if summary["collection_errors"]: + lines += ["", "## Collection errors", ""] + lines += [f"- {cell(error.get('test', error['stage']))} {cell(error.get('state_mode', ''))}: {cell(error['message'])}" + for error in summary["collection_errors"]] + lines += ["", "Official verdicts and denominators are unchanged. Categories describe observed evidence, not proven root causes.", + "Unrecognized diagnostics remain unclassified. Case names, diagnostics and log paths are in the companion .failures.json.", ""] + return "\n".join(lines) + + +def write_reports(path, rows, groups, revision, errors=(), requested=None, complete=True, meta_tags_expanded=True): + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(BASE_FIELDS) + list(FIELDS) + with path.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=fieldnames, delimiter="\t", lineterminator="\n", extrasaction="ignore") + writer.writeheader() + writer.writerows(rows) + summary = {"schema_version": 2, "classification_version": CLASSIFICATION_VERSION, + "revision": revision, "complete": False if errors else complete, "collected": len(rows), + "meta_tags_expanded": meta_tags_expanded, + "requested": requested, "collection_errors": list(errors), "groups": groups} + path.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2) + "\n") + path.with_suffix(".summary.md").write_text(markdown(summary)) + failures = [{key: row.get(key, "") for key in (*BASE_FIELDS, *FIELDS)} + for row in rows if row["result"] == "fail"] + path.with_suffix(".failures.json").write_text(json.dumps({ + "classification_version": CLASSIFICATION_VERSION, "complete": summary["complete"], + "failures": failures, "collection_errors": list(errors), + }, indent=2) + "\n") + return summary + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path, help="existing run.py TSV (never expected.tsv)") + parser.add_argument("--output", type=Path, required=True, help="new annotated TSV and companion reports") + parser.add_argument("--log-root", type=Path, help="relocated logs: ROOT/STATE/TEST/official.log") + parser.add_argument("--meta-tags", type=Path, help="pinned upstream conf/meta-tags.conf") + args = parser.parse_args(argv) + try: + # Import here to keep the classifier reusable by run.py. + from run import read_meta_tags, summarize + if args.output.resolve() == args.report.resolve(): + raise ValueError("output must differ from the source report") + with args.report.open(newline="") as stream: + reader = csv.DictReader(stream, delimiter="\t") + if not set(BASE_FIELDS).issubset(reader.fieldnames or []): + raise ValueError("expected a run.py report with case metadata and log paths") + rows, seen = [], set() + for row in reader: + key = (row["test"], row["state_mode"]) + test = Path(row["test"]) + if (None in row or any(value is None for value in row.values()) or key in seen + or not row["test"] or test.is_absolute() or ".." in test.parts + or row["state_mode"] not in ("2state", "4state") or row["result"] not in ("pass", "fail", "skip")): + raise ValueError(f"invalid or duplicate report row: {key}") + seen.add(key) + log = args.log_root / row["state_mode"] / test / "official.log" if args.log_root else Path(row["log"]) + if not args.log_root and not log.is_absolute(): + log = args.report.parent / log + row["log"] = str(log) + rows.append(annotate(row, log.read_text() if log.is_file() else "")) + companion = args.report.with_suffix(".summary.json") + source = json.loads(companion.read_text()) if companion.is_file() else {} + rows.sort(key=lambda row: (row["test"], row["state_mode"])) + groups = summarize(rows, read_meta_tags(args.meta_tags) if args.meta_tags else {}) + write_reports(args.output, rows, groups, source.get("revision"), + source.get("collection_errors", []), source.get("requested"), + complete=source.get("complete"), meta_tags_expanded=args.meta_tags is not None) + return 0 + except (OSError, ValueError) as error: + print(f"sv-tests reporting: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/conformance/sv-tests/run.py b/conformance/sv-tests/run.py index 7c977a6db6b..304da24d526 100644 --- a/conformance/sv-tests/run.py +++ b/conformance/sv-tests/run.py @@ -3,7 +3,7 @@ import argparse from collections import Counter -from concurrent.futures import ThreadPoolExecutor, as_completed +from concurrent.futures import CancelledError, ThreadPoolExecutor, as_completed import csv import importlib.util import json @@ -13,6 +13,8 @@ import subprocess import sys +import reporting + MODES = ("2state", "4state") HEADER = ("test", "state_mode", "result") REPO = Path(__file__).resolve().parents[2] @@ -116,7 +118,7 @@ def run_case(root, driver, out_dir, test, state_mode): verdict = official_verdict(result.stderr, log, test) meta = log_metadata(log) if log else {} input_issues = json.loads((REPO / "conformance/sv-tests/input-issues.json").read_text())["cases"] - return { + return reporting.annotate({ "test": test, "state_mode": state_mode, "result": verdict, "mode": meta.get("mode", ""), "tags": meta.get("tags", ""), "group": (meta.get("results_group") or "main") if meta else "unclassified", @@ -124,7 +126,7 @@ def run_case(root, driver, out_dir, test, state_mode): if meta.get("rc") == "1" and "include directory is unavailable:" in log else ""), "rc": meta.get("rc", ""), "tool_success": meta.get("tool_success", ""), "log": str(log_path), - } + }, log) def read_meta_tags(path): @@ -171,6 +173,7 @@ def summarize(rows, meta_tags=None): "by_tag": {tag: {"passed": count["pass"], "executed": sum(count.values())} for tag, count in sorted(tags.items())}, "by_execution_mode": {mode: dict(count) for mode, count in sorted(modes.items())}, + **reporting.breakdown(selected), } return groups @@ -182,23 +185,38 @@ def positive_int(value): return number +class CollectionError(ValueError): + def __init__(self, rows, errors): + super().__init__("official runner infrastructure failure; collection is incomplete") + self.rows = sorted(rows, key=lambda row: (row["test"], row["state_mode"])) + self.errors = sorted(errors, key=lambda error: (error["test"], error["state_mode"])) + + def collect_cases(root, driver, out_dir, tests, modes, jobs): - # Each official runner owns a unique case/state directory. BaseRunner also - # uses mkdtemp for its work directory below OUT_DIR/tmp. + # Preserve completed evidence, but never update a baseline after an error. + rows, errors = [], [] executor = ThreadPoolExecutor(max_workers=jobs) - futures = [] - rows = [] try: - futures = [executor.submit(run_case, root, driver, out_dir, test, mode) - for test in tests for mode in modes] + futures = {executor.submit(run_case, root, driver, out_dir, test, mode): (test, mode) + for test in tests for mode in modes} for future in as_completed(futures): - rows.append(future.result()) - if len(rows) % (100 * len(modes)) == 0: + test, mode = futures[future] + try: + rows.append(future.result()) + except CancelledError: + continue + except (OSError, ValueError) as error: + errors.append({"category": "infrastructure", "stage": "collection", "test": test, + "state_mode": mode, "message": str(error), + "log": str(out_dir / mode / test / "runner.log")}) + for pending in futures: + pending.cancel() + if len(rows) and len(rows) % (100 * len(modes)) == 0: print(f"sv-tests: {len(rows)}/{len(tests) * len(modes)} mode runs", file=sys.stderr) finally: - # A preparation/infrastructure error cannot accept a partial baseline. - # Cancel queued work and let already running official processes clean up. executor.shutdown(wait=True, cancel_futures=True) + if errors: + raise CollectionError(rows, errors) return sorted(rows, key=lambda row: (row["test"], row["state_mode"])) @@ -216,31 +234,31 @@ def main(argv=None): if options.update and not options.expected: parser.error("--update requires --expected") root, driver, out_dir = options.sv_tests.resolve(), options.driver.resolve(), options.out_dir.resolve() + report = options.report or out_dir / "report.tsv" + rows, meta_tags, requested = [], {}, None + stage = "preflight" + revision = None try: + result = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True) + revision = result.stdout.strip() if result.returncode == 0 else None preflight(root, driver) meta_tags = read_meta_tags(root / "conf/meta-tags.conf") modes = MODES if options.state_mode == "both" else (options.state_mode,) expected = read_expected(options.expected) if options.expected and options.expected.exists() else {} if options.expected and not options.expected.exists() and not options.update: raise ValueError(f"expectations do not exist: {options.expected}") + stage = "corpus" tests = sorted(p.relative_to(root / "tests").as_posix() for p in (root / "tests").rglob("*") if p.is_file() and p.suffix.lower() == ".sv") if not tests: raise ValueError("sv-tests checkout contains no .sv tests") + requested = len(tests) * len(modes) + stage = "collection" rows = collect_cases(root, driver, out_dir, tests, modes, options.jobs) results = {(row["test"], row["state_mode"]): row["result"] for row in rows} - report = options.report or out_dir / "report.tsv" - report.parent.mkdir(parents=True, exist_ok=True) - with report.open("w", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=list(rows[0]), delimiter="\t", lineterminator="\n") - writer.writeheader() - writer.writerows(rows) + stage = "report" groups = summarize(rows, meta_tags) - revision = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], - capture_output=True, text=True) - summary = {"revision": revision.stdout.strip() if revision.returncode == 0 else None, - "groups": groups} - report.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2) + "\n") + reporting.write_reports(report, rows, groups, revision, requested=requested) for group, states in groups.items(): for mode, counts in states.items(): print(f"{group} [{mode}]: {counts['passed']}/{counts['executed']} passed " @@ -263,6 +281,13 @@ def main(argv=None): return 0 except (OSError, ValueError) as error: print(f"sv-tests: {error}", file=sys.stderr) + errors = [{"category": "infrastructure", "stage": stage, "message": str(error)}] + if isinstance(error, CollectionError): + rows, errors = error.rows, error.errors + try: + reporting.write_reports(report, rows, summarize(rows, meta_tags), revision, errors, requested) + except OSError as report_error: + print(f"sv-tests: cannot write incomplete report: {report_error}", file=sys.stderr) return 2 diff --git a/conformance/sv-tests/test_reporting.py b/conformance/sv-tests/test_reporting.py new file mode 100644 index 00000000000..91ea351f2ea --- /dev/null +++ b/conformance/sv-tests/test_reporting.py @@ -0,0 +1,131 @@ +"""Diagnostic classification and offline report contracts (no verdict recomputation).""" + +import csv +import json +from pathlib import Path +import tempfile +import unittest + +import reporting +import run as runner + + +def fixture(body, result="fail", rc="1", mode="elaboration", negative="0"): + row = {"test": "chapter-18/test.sv", "state_mode": "2state", "group": "main", "tags": "18 a", + "result": result, "rc": rc, "mode": mode, "tool_success": "1" if rc == "0" else "0", + "log": "official.log", "input_issue": ""} + log = f"mode: {mode}\nrc: {rc}\ntool_success: {row['tool_success']}\nshould_fail: {negative}\n\n/driver -- source.sv\n{body}\n" + return row, log + + +class ClassificationTests(unittest.TestCase): + def test_observed_failures_are_distinct(self): + examples = [ + ("unsupported_simulator_parser\n\n × Unsupported SystemVerilog\n │ construct: constrained randomize)", "1", "elaboration", "0", "unsupported"), + ("SystemVerilog parse error: /root/a.sv:2:3: expected `;`", "1", "simulation", "0", "compile_error"), + ("illegal_context\n × invalid argument", "1", "elaboration", "0", "compile_error"), + ("elaboration requires a module root; none found", "1", "elaboration", "0", "unsupported"), + ("$fatal: bad data", "1", "simulation", "0", "runtime_error"), + ("Timeout: > 30s", "71", "simulation", "0", "timeout"), + ("thread 'main' panicked at x.rs:1", "101", "elaboration", "0", "crash"), + ("", "-11", "simulation", "1", "crash"), + ("", "139", "simulation", "0", "crash"), + (":assert: (1 == 2)", "0", "simulation", "0", "assertion_failure"), + ("", "0", "elaboration", "1", "unexpected_success"), + ("include directory is unavailable: /missing", "1", "elaboration", "0", "environment"), + ("some new diagnostic", "1", "simulation", "0", "unclassified"), + ("unsupported file name only", "1", "simulation", "0", "unclassified"), + ] + for body, rc, mode, negative, category in examples: + with self.subTest(body=body, rc=rc): + row, log = fixture(body, rc=rc, mode=mode, negative=negative) + actual = reporting.annotate(row, log) + self.assertEqual(actual["failure_category"], category) + self.assertEqual(actual["result"], "fail") + row, log = fixture(examples[0][0]) + self.assertEqual(reporting.annotate(row, log)["evidence"], "constrained randomize") + + def test_passes_and_negative_diagnostic_warnings_do_not_become_failures(self): + row, log = fixture("unsupported_simulator_parser", result="pass", negative="1") + annotated = reporting.annotate(row, log) + self.assertEqual(annotated["failure_category"], "") + summary = runner.summarize([annotated])["main"]["2state"] + self.assertEqual((summary["passed"], summary["failed"], summary["executed"]), (1, 0, 1)) + self.assertEqual(summary["negative_pass_diagnostics"], {"unsupported_construct": 1}) + row, log = fixture(":assert: (1 == 1)", result="pass", rc="0", mode="simulation") + self.assertEqual(reporting.annotate(row, log)["diagnostic"], "") + row["result"] = "skip" + self.assertEqual(reporting.annotate(row, "")["failure_category"], "") + + def test_missing_stale_and_ambiguous_evidence_is_not_guessed(self): + row, log = fixture("unsupported_simulator_parser") + self.assertEqual(reporting.annotate(row, "")["diagnostic"], "missing_log") + self.assertEqual(reporting.annotate(row, log.replace("rc: 1", "rc: 0"))["diagnostic"], "metadata_mismatch") + row, log = fixture("driver returned an ordinary error", rc="71") + self.assertEqual(reporting.annotate(row, log)["failure_category"], "unclassified") + row["input_issue"] = "reviewed bad include" + self.assertEqual(reporting.annotate(row, log)["failure_category"], "input_issue") + + def test_summaries_partition_failures_without_changing_dashboard_totals(self): + rows = [] + for state in ("2state", "4state"): + for source in ("/checkout/a.sv:2:3:", "/other/b.sv:90:12:"): + row, log = fixture(f"SystemVerilog parse error: {source} expected `;`") + row["state_mode"] = state + rows.append(reporting.annotate(row, log)) + row, log = fixture("", result="pass", rc="0") + rows.append(reporting.annotate(row, log)) + groups = runner.summarize(rows) + for counts in groups["main"].values(): + self.assertEqual(sum(counts["by_failure_category"].values()), counts["failed"]) + self.assertEqual(len(counts["by_failure_reason"]), 1) + self.assertEqual(counts["by_failure_reason"][0]["count"], 2) + self.assertEqual(groups["main"]["2state"]["pass_percent"], 33.33) + self.assertEqual(groups["main"]["4state"]["pass_percent"], 0) + + def test_offline_report_relocates_logs_and_preserves_incomplete_provenance(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + row, log = fixture("unsupported_simulator_parser") + source = root / "old.tsv" + with source.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=list(row), delimiter="\t") + writer.writeheader() + writer.writerow(row) + source.with_suffix(".summary.json").write_text(json.dumps({ + "revision": "pinned", "complete": False, "requested": 2, + "collection_errors": [{"stage": "collection", "message": "broken runner"}], + })) + logs = root / "logs" + path = logs / row["state_mode"] / row["test"] / "official.log" + path.parent.mkdir(parents=True) + path.write_text(log) + output = root / "classified.tsv" + before = source.read_bytes() + self.assertEqual(reporting.main([str(source), "--output", str(output), "--log-root", str(logs)]), 0) + summary = json.loads(output.with_suffix(".summary.json").read_text()) + failures = json.loads(output.with_suffix(".failures.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertFalse(failures["complete"]) + self.assertEqual(summary["revision"], "pinned") + self.assertEqual(failures["failures"][0]["failure_category"], "unsupported") + self.assertIn("INCOMPLETE", output.with_suffix(".summary.md").read_text()) + self.assertEqual(source.read_bytes(), before) + self.assertEqual(reporting.main([str(source), "--output", str(source)]), 2) + source.with_suffix(".summary.json").unlink() + self.assertEqual(reporting.main([str(source), "--output", str(output), "--log-root", str(logs)]), 0) + self.assertIsNone(json.loads(output.with_suffix(".summary.json").read_text())["complete"]) + self.assertIsNone(json.loads(output.with_suffix(".failures.json").read_text())["complete"]) + + def test_offline_rejects_baselines_and_duplicate_rows(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source, output = root / "input.tsv", root / "output.tsv" + source.write_text("test\tstate_mode\tresult\na.sv\t2state\tfail\n") + self.assertEqual(reporting.main([str(source), "--output", str(output)]), 2) + row, _ = fixture("") + with source.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=list(row), delimiter="\t") + writer.writeheader() + writer.writerows([row, row]) + self.assertEqual(reporting.main([str(source), "--output", str(output)]), 2) diff --git a/conformance/sv-tests/test_runner.py b/conformance/sv-tests/test_runner.py index 024343e13ce..c9592135f0a 100644 --- a/conformance/sv-tests/test_runner.py +++ b/conformance/sv-tests/test_runner.py @@ -112,7 +112,12 @@ def test_official_metadata_defaults_priority_negative_and_assertions(self): self.assertEqual(self.case()["mode"], "elaboration") self.assertEqual(self.case(":type: parsing elaboration\n")["mode"], "elaboration") self.assertEqual(self.case(":type: elaboration simulation\n", "// OUTPUT: :assert: 1 == 1")["result"], "pass") - self.assertEqual(self.case(":type: simulation\n", "// OUTPUT: :assert: 1 == 2")["result"], "fail") + row = self.case(":type: simulation\n", "// OUTPUT: :assert: 1 == 2") + self.assertEqual((row["result"], row["failure_category"]), ("fail", "assertion_failure")) + row = self.case(":should_fail_because: invalid\n") + self.assertEqual((row["result"], row["failure_category"]), ("fail", "unexpected_success")) + row = self.case(":should_fail_because: invalid\n", "// OUTPUT: unsupported_simulator_parser\n// EXIT: 1") + self.assertEqual((row["result"], row["diagnostic"]), ("pass", "unsupported_construct")) row = self.case(":type: simulation\n:should_fail_because: invalid\n", "// EXIT: 1") self.assertEqual((row["result"], row["rc"]), ("pass", "1")) self.assertEqual(self.case(":type: simulation\n:should_fail_because: invalid\n", "// EXIT: 1\n// OUTPUT: :assert: False")["result"], "fail") @@ -172,6 +177,7 @@ def test_variants_are_forwarded_separately_only_for_simulation(self): def test_official_timeout(self): row = self.case(":type: simulation\n:timeout: 1\n", "// SLEEP") self.assertEqual((row["result"], row["rc"]), ("fail", "71")) + self.assertEqual(row["failure_category"], "timeout") def test_partial_update_and_comparison(self): self.case() @@ -230,3 +236,23 @@ def test_parallel_infrastructure_error_preserves_expectations(self): "--jobs", "4", "--expected", str(expected), "--update"]) self.assertEqual(code, 2) self.assertEqual(expected.read_bytes(), original) + summary = json.loads((self.out / "report.summary.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertEqual(summary["requested"], 4) + self.assertTrue(summary["collection_errors"]) + self.assertTrue(all(error["test"] == "broken.sv" for error in summary["collection_errors"])) + with (self.out / "report.tsv").open() as stream: + rows = list(csv.DictReader(stream, delimiter="\t")) + self.assertTrue(all(row["result"] == "pass" for row in rows)) + self.assertIn("INCOMPLETE", (self.out / "report.summary.md").read_text()) + + def test_preflight_failure_replaces_stale_reports(self): + self.case() + args = [str(self.root), "--driver", str(self.driver), "--out-dir", str(self.out)] + self.assertEqual(runner.main(args), 0) + self.driver.unlink() + self.assertEqual(runner.main(args), 2) + summary = json.loads((self.out / "report.summary.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertEqual(summary["collected"], 0) + self.assertEqual(summary["collection_errors"][0]["stage"], "preflight")