diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75963609aff..373a96c002f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -210,26 +210,22 @@ jobs: fi scripts/check-test-timeout.sh /tmp/v3-test-timings.log - # PB-1-e — DB-8 fresh-compile gate at regen time. Replaces the in-tree - # `compile_full_bootstrap_dag()` vs committed-snapshot drift tests with a - # CI-side check: regen the bootstrap snapshot from authority, then assert - # the committed `bootstrap_*_generated.rs` files are byte-identical to a - # fresh compile. Any drift (hand-edit, stale regen, substrate change) fails - # CI here. See `docs/briefs/pb-1-e-residual-scaffold-retirement-worker.md`. - - name: v3 bootstrap snapshot fresh-compile gate - run: | - cargo run -p v3-compiler --bin regen_bootstrap - if ! git diff --exit-code -- \ - src/v3/compiler/src/bootstrap_std_generated.rs \ - src/v3/compiler/src/bootstrap_generated.rs \ - src/v3/compiler/src/bootstrap_generated_without_parse_surface.rs; then - echo "::error::Committed bootstrap snapshot drifted from a fresh compile. Run \`cargo run -p v3-compiler --bin regen_bootstrap\` and commit the result." - exit 1 - fi - - - name: v3 Compiler Clippy + # Default graph (no regen feature): locks in `cfg_attr(dead_code)` hygiene and + # ensures production targets stay clean without relying on the feature build alone. + - name: v3 Compiler Clippy (default features) run: cargo clippy -p v3-compiler --all-targets -- -D warnings + - name: v3 Compiler Clippy (bootstrap-regen-fresh) + run: cargo clippy -p v3-compiler --all-targets --features bootstrap-regen-fresh -- -D warnings + + # Type-check lib + default integration harness with the regen feature on + # (clippy already checks targets; this ensures `cargo test` linkage too). + - name: v3 test targets compile with bootstrap-regen-fresh + run: cargo test -p v3-compiler --no-run --features bootstrap-regen-fresh + + - name: v3 regen_bootstrap snapshot gate (--verify) + run: cargo run -p v3-compiler --features bootstrap-regen-fresh --bin regen_bootstrap -- --verify + - name: L-7 Substrate accessor reconstruction gate run: | # L-7 (INVARIANTS.md): lenses consume substrate query diff --git a/scripts/check-test-timeout.sh b/scripts/check-test-timeout.sh index 4d1f73d3c6c..104e81c0319 100755 --- a/scripts/check-test-timeout.sh +++ b/scripts/check-test-timeout.sh @@ -46,7 +46,7 @@ # (default scripts/slow-test-exemptions.txt). # TEST_TIMEOUT_MAX_EXEMPTIONS # Ratchet floor for active exemption entries -# (default 42, captured 2026-04-24). Lower this +# (default 39, captured 2026-04-25). Lower this # value in the same PR that removes exemptions. set -euo pipefail @@ -55,7 +55,7 @@ log_file_arg=${1:-} budget_ms=${2:-${TEST_TIMEOUT_MS:-2000}} pkg=${TEST_TIMEOUT_PACKAGE:-v3-compiler} exempt_file=${TEST_TIMEOUT_EXEMPT:-scripts/slow-test-exemptions.txt} -max_exemptions=${TEST_TIMEOUT_MAX_EXEMPTIONS:-42} +max_exemptions=${TEST_TIMEOUT_MAX_EXEMPTIONS:-39} script_dir=$(cd "$(dirname "$0")" && pwd) repo_root=$(cd "$script_dir/.." && pwd) diff --git a/scripts/slow-test-exemptions.txt b/scripts/slow-test-exemptions.txt index cac5592b8c3..796cfec1beb 100644 --- a/scripts/slow-test-exemptions.txt +++ b/scripts/slow-test-exemptions.txt @@ -64,9 +64,6 @@ m2_lens_idempotency_migration_test::idempotency_emitted_analyze_matches_oracle m2_lens_provenance_migration_test::lens_provenance_dag_runs_end_to_end_via_rustc_harness # Lane 2 migration harness roundtrip; compile-heavy oracle test remains explicit until lens migration paydown. m2_lens_unused_parameters_migration_test::unused_parameters_dag_runs_end_to_end_via_rustc_harness # Lane 2 migration harness roundtrip; compile-heavy oracle test remains explicit until lens migration paydown. m2_lens_unused_parameters_migration_test::unused_parameters_dag_self_analysis_reports_zero_findings # Lane 2 migration harness roundtrip; compile-heavy self-analysis remains explicit until lens migration paydown. -pb1_bootstrap_full_snapshot_test::generated_full_bootstrap_snapshot_matches_runtime_full_bootstrap # PB-1 bootstrap closure parity test: full legacy-runtime bootstrap builder vs committed generated snapshot; cold CI wall-clock exceeds 2s while the drift check remains explicit. Paydown trigger: shared compile-once warming for PB-1 snapshot gates (TESTING.md shared-setup / `cached_compile` class); re-measure and remove when landed. -pb1_bootstrap_full_snapshot_test::generated_full_bootstrap_without_parse_surface_matches_runtime_variant # PB-1 bootstrap closure parity test for the no-parse-surface snapshot used by regen/tests; cold CI wall-clock exceeds 2s while the first-of-name guard stays explicit. Paydown trigger: same as `generated_full_bootstrap_snapshot_matches_runtime_full_bootstrap` (shared PB-1 compile warming). -pb1_bootstrap_std_snapshot_test::generated_std_bootstrap_snapshot_matches_runtime_std_bootstrap # PB-1 std-only snapshot parity (`bootstrap_std_generated.rs`); same compile + `first_difference` class as full PB-1 gates — can exceed 2s wall on cold ubuntu-latest under default libtest parallelism; drift check stays explicit. Paydown trigger: same shared PB-1 compile warming as sibling PB-1 exemptions above. pb1_bootstrap_full_snapshot_test::full_bootstrap_extends_std_snapshot # PB-1 shape guard: compares two large generated bootstrap snapshots in-process; cold CI + libtest parallelism can exceed 2s wall while the structural inequality check stays explicit. Paydown trigger: same shared PB-1 compile warming; optional extra win if snapshot compare moves to mmap/streaming (PB-1 lane only). bootstrap::tests::kernel_bool_path_a_attaches_diagnostic_when_boolean_algebra_unresolvable # Lane 1e-2b Path A regression: two `Dag::new()` paths + mutation; can exceed 2s wall on cold ubuntu-latest when compiled alongside heavy integration neighbors — keep explicit bootstrap diagnostic coverage. Paydown trigger: when the Bool/`BooleanAlgebra` kernel bootstrap bridge dissolves into `dsl/std/types.dag` (see `bootstrap.rs` + `dsl/std/types.dag` dissolution notes), collapse fixtures and/or adopt shared `Dag::new` warming; re-measure and remove if under 2s. diff --git a/src/v3/compiler/Cargo.toml b/src/v3/compiler/Cargo.toml index e50dda1292a..c9c85a12886 100644 --- a/src/v3/compiler/Cargo.toml +++ b/src/v3/compiler/Cargo.toml @@ -3,6 +3,15 @@ name = "v3-compiler" version.workspace = true edition.workspace = true license.workspace = true +# PB-1-e / Zero-Floor: `regen_bootstrap` is the only bin that enables +# `bootstrap-regen-fresh`; listing bins explicitly keeps that boundary +# without Cargo silently promoting a new `src/bin/*.rs` driver. +autobins = false + +[features] +# Fresh tokenize/parse/lower bootstrap for `regen_bootstrap` only — not part of +# the default `v3-compiler` library build graph (production uses snapshots). +bootstrap-regen-fresh = [] # M0: the smallest v3 pipeline that exercises the full substrate. # parse -> lower to L1 behaviors -> infer types through Ports -> @@ -20,3 +29,32 @@ license.workspace = true # Interpreter-backed receipts for substrate behavior (repeat_string, etc.). v2-compiler = { path = "../../v2/stage0" } v2-compiler-tests = { path = "../../v2/tests" } + +[[bin]] +name = "regen_bootstrap" +path = "src/bin/regen_bootstrap.rs" +required-features = ["bootstrap-regen-fresh"] + +[[bin]] +name = "regen_lens" +path = "src/bin/regen_lens.rs" + +[[bin]] +name = "regen_parse" +path = "src/bin/regen_parse.rs" + +[[bin]] +name = "regen_parse_tables" +path = "src/bin/regen_parse_tables.rs" + +[[bin]] +name = "regen_tokenize" +path = "src/bin/regen_tokenize.rs" + +[[bin]] +name = "regen_v3" +path = "src/bin/regen_v3.rs" + +[[bin]] +name = "self_host_fixed_point" +path = "src/bin/self_host_fixed_point.rs" diff --git a/src/v3/compiler/src/bin/regen_bootstrap.rs b/src/v3/compiler/src/bin/regen_bootstrap.rs index 0f030be4902..da9682eb2f6 100644 --- a/src/v3/compiler/src/bin/regen_bootstrap.rs +++ b/src/v3/compiler/src/bin/regen_bootstrap.rs @@ -1,3 +1,21 @@ +//! Regenerate `bootstrap_*_generated.rs` snapshots from on-disk `.dag` sources. +//! +//! This binary is the sole `v3-compiler` target with `required-features = +//! ["bootstrap-regen-fresh"]`, so the fresh-parse bootstrap subgraph is not part +//! of the default library build graph. +//! +//! PB-1-e mechanism (ii): the **fresh-compile vs committed snapshot** gate lives +//! here, not in `cargo test`. Use `--verify` in CI (or before push) to assert the +//! checked-in `bootstrap_*.rs` files match a from-scratch compile; omit `--verify` +//! to write updated snapshots after intentional `.dag` changes. +//! +//! Local invocation (feature is required): +//! `cargo run -p v3-compiler --features bootstrap-regen-fresh --bin regen_bootstrap` +//! (append `-- --verify` to check without writing). + +use std::env; +use std::fs; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; use v3_compiler::{ @@ -13,6 +31,21 @@ const GENERATED_NO_PARSE_SURFACE_FILE: &str = "src/v3/compiler/src/bootstrap_generated_without_parse_surface.rs"; fn main() { + let args: Vec = env::args().skip(1).collect(); + let verify_only = match args.as_slice() { + [] => false, + [flag] if flag == "--verify" => true, + unexpected => { + let _ = writeln!( + io::stderr(), + "regen_bootstrap: unexpected arguments: {unexpected:?}\n\ + Usage: regen_bootstrap [--verify]\n\ + Omit flags to write snapshots; pass exactly `--verify` to check without writing." + ); + std::process::exit(2); + } + }; + for generated_file in [ GENERATED_STD_FILE, GENERATED_FULL_FILE, @@ -30,7 +63,6 @@ fn main() { let std_dag = compile_std_bootstrap_dag(); let std_formatted = render_bootstrap_std_generated_rs(&std_dag) .unwrap_or_else(|e| panic!("regen_bootstrap std: {e}")); - write_generated(&manifest_dir, "bootstrap_std_generated.rs", &std_formatted); let full_dag = compile_full_bootstrap_dag_from_std_seed(std_dag.clone()); let full_formatted = render_bootstrap_generated_rs( @@ -39,7 +71,6 @@ fn main() { "bootstrapped_fixture_dag", ) .unwrap_or_else(|e| panic!("regen_bootstrap full: {e}")); - write_generated(&manifest_dir, "bootstrap_generated.rs", &full_formatted); let full_no_parse_surface_dag = compile_full_bootstrap_without_parse_surface_dag_from_std_seed(std_dag); @@ -49,6 +80,21 @@ fn main() { "bootstrapped_fixture_without_parse_surface_dag", ) .unwrap_or_else(|e| panic!("regen_bootstrap no-parse-surface: {e}")); + + if verify_only { + assert_disk_matches(&manifest_dir, "bootstrap_std_generated.rs", &std_formatted); + assert_disk_matches(&manifest_dir, "bootstrap_generated.rs", &full_formatted); + assert_disk_matches( + &manifest_dir, + "bootstrap_generated_without_parse_surface.rs", + &full_no_parse_surface_formatted, + ); + println!("regen_bootstrap --verify: committed snapshots match fresh compile."); + return; + } + + write_generated(&manifest_dir, "bootstrap_std_generated.rs", &std_formatted); + write_generated(&manifest_dir, "bootstrap_generated.rs", &full_formatted); write_generated( &manifest_dir, "bootstrap_generated_without_parse_surface.rs", @@ -56,6 +102,59 @@ fn main() { ); } +fn assert_disk_matches(manifest_dir: &Path, file_name: &str, expected: &str) { + let path = manifest_dir.join("src").join(file_name); + let on_disk = + fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + if on_disk != expected { + let hint = first_text_mismatch_hint(&on_disk, expected); + panic!( + "{file_name}: committed snapshot does not match fresh compile from .dag sources. \ + Run `cargo run -p v3-compiler --features bootstrap-regen-fresh --bin regen_bootstrap` \ + (without `--verify`) to \ + regenerate after intentional authority edits, or fix unintended drift. \ + {hint}", + ); + } +} + +/// Byte offset of first differing UTF-8 byte, lengths, and a small lossy window +/// around the mismatch (UTF-8 boundaries not guaranteed inside the window). +fn first_text_mismatch_hint(on_disk: &str, expected: &str) -> String { + const RADIUS: usize = 40; + let a = on_disk.as_bytes(); + let b = expected.as_bytes(); + let prefix_len = a.len().min(b.len()); + let mut first_diff = None; + for i in 0..prefix_len { + if a[i] != b[i] { + first_diff = Some(i); + break; + } + } + // If one string is a strict prefix of the other, all shared bytes match. + let offset = first_diff.unwrap_or(prefix_len); + let window_disk = lossy_byte_window(a, offset, RADIUS); + let window_exp = lossy_byte_window(b, offset, RADIUS); + format!( + "(first differing byte index: {offset}, on_disk_len={}, expected_len={}, \ + on_disk[…]≈{:?}, expected[…]≈{:?})", + on_disk.len(), + expected.len(), + window_disk, + window_exp, + ) +} + +fn lossy_byte_window(bytes: &[u8], center: usize, radius: usize) -> String { + if bytes.is_empty() { + return String::new(); + } + let start = center.saturating_sub(radius).min(bytes.len()); + let end = (center + radius).min(bytes.len()); + String::from_utf8_lossy(&bytes[start..end]).into_owned() +} + fn write_generated(manifest_dir: &Path, file_name: &str, contents: &str) { let out_path = manifest_dir.join("src").join(file_name); std::fs::write(&out_path, contents).unwrap_or_else(|e| panic!("write {file_name}: {e}")); diff --git a/src/v3/compiler/src/bootstrap.rs b/src/v3/compiler/src/bootstrap.rs index 5c09de1c03e..641cb8c30e4 100644 --- a/src/v3/compiler/src/bootstrap.rs +++ b/src/v3/compiler/src/bootstrap.rs @@ -5,10 +5,15 @@ // are loaded from committed generated snapshots: // // - `std_fixtures` (`dsl/std/*.dag`) -// - `STAGED_FILES` (`src/v3/std/*.dag`) -// - `V3_SPECS` (`src/v3/spec/*.dag`) -// - `COMPILER_FILES` (`src/v3/compiler/*.dag`, minus `tokenize.dag`) -// - `EXTDEPS_BOOTSTRAP_FIXTURES` (scoped subset of `dsl/extdeps/languages/*/*.dag`) +// - `STAGED_FILES` / `V3_SPECS` / `COMPILER_FILES` / extdeps primitives — fresh +// tokenize/parse/lower lives in `bootstrap_regen_fresh.rs` behind feature +// `bootstrap-regen-fresh` (`regen_bootstrap` only). `Dag::new()` does not load +// them from disk at runtime. +// +// **Single authority at runtime:** `Dag::new()` (and `std_fixture_bootstrap_snapshot`) +// materialize **only** from the committed `bootstrap_*_generated.rs` snapshots +// (`include!` / generated Rust). They never re-tokenize or re-parse the `OUT_DIR` +// fixture string tables — those arrays exist solely for the feature-gated regen host. // // `compile_parse_surface_std_authority_dag` uses the companion snapshot // that omits `src/v3/std/parse_surface.dag`, so a fresh parse+lower of @@ -59,188 +64,23 @@ // on every subsequent call — the same structural channel user errors // go through. A failed bootstrap is visible to callers without a // side channel. - -use crate::dag::{ArrowBody, Dag, Declaration, DeclarationId, TemplateArgument, TypeConnective}; +// +// **PB-1-e split — what stays here:** `patch_kernel_bool_boolean_algebra_inhabits`, +// `materialize_pipeline_realizations`, and `report_pipeline_authority_error` remain +// in this file because the `#[cfg(test)]` module below exercises them on +// `Dag::new()` snapshots. The regen-only fresh tokenize/parse/lower loop lives in +// `bootstrap_regen_fresh.rs` (feature `bootstrap-regen-fresh`); do not duplicate +// pipeline materialization there without relocating or rewriting these unit tests. + +use crate::dag::{ArrowBody, Dag, Declaration, TemplateArgument, TypeConnective}; use crate::diagnostics::{Diagnostic, SourceSpan}; -use crate::lower::{collect_symbols_phase, lower_bodies_phase, resolve_pending_identifiers}; -use crate::parse::{parse, SurfaceModule}; use crate::pipeline_authority::{ordered_pipeline_stages, PIPELINE_AUTHORITY_FILE}; -use crate::tokenize::tokenize; -use std::collections::HashMap; - -const LOGIC_DAG: &str = include_str!("../../../../dsl/std/logic.dag"); -const BIT_DAG: &str = include_str!("../../../../dsl/std/bit.dag"); -const ALGEBRA_DAG: &str = include_str!("../../../../dsl/std/algebra.dag"); -const INTEGER_DAG: &str = include_str!("../../../../dsl/std/integer.dag"); -const FLOAT_DAG: &str = include_str!("../../../../dsl/std/float.dag"); -const STRING_TYPE_DAG: &str = include_str!("../../../../dsl/std/string_type.dag"); -const TYPES_DAG: &str = include_str!("../../../../dsl/std/types.dag"); - -// Scoped extdeps bootstrap authorities. See the `EXTDEPS_BOOTSTRAP_FIXTURES` -// commentary in the file header: only pure structural-data extdeps authorities -// are in scope, and expansion is a file-system edit to this array. -const EXTDEPS_RUST_PRIMITIVES_DAG: &str = - include_str!("../../../../dsl/extdeps/languages/rust/primitives.dag"); - -const EXTDEPS_BOOTSTRAP_FIXTURES: &[(&str, &str)] = &[( - "dsl/extdeps/languages/rust/primitives.dag", - EXTDEPS_RUST_PRIMITIVES_DAG, -)]; - -// M1(3) PR-B-unwind R1 — the v3-only staged files are enumerated -// by `build.rs` at compile time and exposed via generated statics: -// -// - `STAGED_FILES` for `src/v3/std/*.dag` -// - `V3_SPECS` for `src/v3/spec/*.dag` -// - `COMPILER_FILES` for `src/v3/compiler/*.dag` -// -// Adding a new staged std/spec/compiler file is a pure file-system change: -// drop the `.dag` file in the staged directory, the build script -// picks it up at the next compile, and the bootstrap loop loads it -// without any `bootstrap.rs` edit. -// -// The pre-unwind shape had `const RUST_DAG: &str = include_str!(...)` -// constants here and a hardcoded fixture array, which PR #445 -// review flagged as a duplicate-authority bug: the on-disk spec -// files and the Rust constants were two parallel representations -// of the same set. The build-script-generated staged arrays are the -// single authority. -// -// **Why these live in `src/v3/std/` and `src/v3/spec/` instead of -// `dsl/std/`.** v2's CI pipeline scans `dsl/` recursively and tries -// to resolve every identifier in every record-literal field value. -// v2 doesn't know about v3-only surface/substrate features, so -// keeping staged files outside the v2-scanned tree is the cleanest -// separation. v3 reads them via the build-script-generated arrays — -// no source-root scanning involved. -include!(concat!(env!("OUT_DIR"), "/v3_staged_files.rs")); -include!(concat!(env!("OUT_DIR"), "/v3_specs.rs")); -include!(concat!(env!("OUT_DIR"), "/v3_compiler_files.rs")); +// Used by `materialize_pipeline_realizations` (regen + unit tests below). When +// `bootstrap-regen-fresh` is off, that path is cfg-dead in non-test lib builds. +#[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] const PIPELINE_REALIZATION_META: &str = "CompilerHostRealization"; -fn declaration_name_preference_rank(file: &str) -> usize { - if file.starts_with("src/v3/") { - 2 - } else if file.starts_with("dsl/") { - 0 - } else { - 1 - } -} - -// PB-1-e scaffold boundary: the runtime-parse helpers below exist solely so -// `regen_bootstrap` can produce the committed snapshot files -// (`bootstrap_*_generated.rs`) from the canonical `.dag` authorities. -// Production bootstrap MUST seed from `Dag::std_fixture_bootstrap_snapshot()` -// or `Dag::new()` directly; neither calls these helpers. -// -// In-tree DB-8 cross-check is "the committed snapshot is internally -// consistent" (see `tests/integration/pb1_bootstrap_full_snapshot_test.rs`). -// The fresh-parse-vs-snapshot acid test runs at regen time: CI invokes -// `cargo run --bin regen_bootstrap` and asserts `git diff --exit-code` on -// `src/v3/compiler/src/bootstrap_*_generated.rs` — drift between the -// committed bytes and a fresh compile fails CI. -// -// Named dissolution trigger: delete these helpers once `regen_bootstrap` -// itself is generated from a `.dag` regen-authority spec (so the fresh-parse -// step is no longer hand-Rust). At that point the std snapshot can be -// derived from the same authority that drives the rest of the regen registry. -pub(crate) fn bootstrap_std_fixtures_only(dag: &mut Dag) { - *dag = Dag::empty(); - load_fixtures(dag, std_fixtures()); - dag.populate_primitive_cache(); -} - -pub(crate) fn bootstrap_runtime_authorities_on( - dag: &mut Dag, - excluded_staged_paths: &[&str], - excluded_compiler_paths: &[&str], -) { - load_runtime_bootstrap_authorities(dag, excluded_staged_paths, excluded_compiler_paths); -} - -fn load_runtime_bootstrap_authorities( - dag: &mut Dag, - excluded_staged_paths: &[&str], - excluded_compiler_paths: &[&str], -) { - let staged_iter = STAGED_FILES - .iter() - .copied() - .filter(|(path, _)| !excluded_staged_paths.contains(path)); - let compiler_iter = COMPILER_FILES - .iter() - .copied() - .filter(|(path, _)| !excluded_compiler_paths.contains(path)); - let fixtures: Vec<(&str, &str)> = staged_iter - .chain(V3_SPECS.iter().copied()) - .chain(compiler_iter) - .chain(EXTDEPS_BOOTSTRAP_FIXTURES.iter().copied()) - .collect(); - load_fixtures(dag, &fixtures); - materialize_pipeline_realizations(dag); - dag.populate_primitive_cache(); -} - -fn std_fixtures() -> &'static [(&'static str, &'static str)] { - &[ - ("dsl/std/logic.dag", LOGIC_DAG), - ("dsl/std/bit.dag", BIT_DAG), - ("dsl/std/algebra.dag", ALGEBRA_DAG), - ("dsl/std/integer.dag", INTEGER_DAG), - ("dsl/std/float.dag", FLOAT_DAG), - ("dsl/std/types.dag", TYPES_DAG), - ("dsl/std/string_type.dag", STRING_TYPE_DAG), - ] -} - -fn load_fixtures(dag: &mut Dag, fixtures: &[(&str, &str)]) { - let mut parsed: Vec<(SurfaceModule, Vec)> = Vec::with_capacity(fixtures.len()); - for (file, source) in fixtures.iter() { - let Some(module) = parse_fixture(dag, source, file) else { - continue; - }; - let (_stale_symbols, is_first) = collect_symbols_phase(dag, &module.items); - parsed.push((module, is_first)); - } - - // Rebuild the symbols map from the shared declaration table. By - // now every top-level declaration across all fixtures is present - // with its type_params slot populated, so Phase 2 can resolve - // every cross-file template reference at construction time. - // Use the same staged-v3-over-dsl preference policy as - // `collect_symbols`, otherwise Phase 1 can register the staged - // shadowing declaration but Phase 2 will still lower bodies - // against the legacy `dsl/` declaration. - let mut shared_symbols: HashMap = HashMap::new(); - for d in dag.declarations() { - if let Some(name) = &d.name { - match shared_symbols.get(name).copied() { - None => { - shared_symbols.insert(name.clone(), d.id); - } - Some(existing_id) => { - let existing = dag.declaration(existing_id); - let new_rank = declaration_name_preference_rank(&d.span.file); - let existing_rank = declaration_name_preference_rank(&existing.span.file); - if new_rank > existing_rank { - shared_symbols.insert(name.clone(), d.id); - } - } - } - } - } - - // Phase 2: lower bodies using the shared symbols map. - for (module, is_first) in parsed.iter() { - lower_bodies_phase(dag, module, &shared_symbols, is_first); - } - - resolve_pending_identifiers(dag); - patch_kernel_bool_boolean_algebra_inhabits(dag); -} - /// v3-only inhabitance for kernel `Bool` (Class 5 / Lane 1e-2b Path A). /// /// `dsl/std/types.dag` must stay free of `inhabits` so v2 can parse every @@ -257,7 +97,8 @@ fn load_fixtures(dag: &mut Dag, fixtures: &[(&str, &str)]) { /// `type … inhabits … =` in `dsl/` (then express /// `type Bool inhabits BooleanAlgebra = True | False` in /// `dsl/std/types.dag` and delete `patch_kernel_bool_boolean_algebra_inhabits`). -fn patch_kernel_bool_boolean_algebra_inhabits(dag: &mut Dag) { +#[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] +pub(crate) fn patch_kernel_bool_boolean_algebra_inhabits(dag: &mut Dag) { const BOOL_TYPES_FILE: &str = "dsl/std/types.dag"; let Some(bool_decl) = dag .declarations() @@ -339,7 +180,8 @@ fn patch_kernel_bool_boolean_algebra_inhabits(dag: &mut Dag) { // (same runtime for every target), so "one realization per stage" is // the correct authority there. -fn materialize_pipeline_realizations(dag: &mut Dag) { +#[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] +pub(crate) fn materialize_pipeline_realizations(dag: &mut Dag) { let stages = match ordered_pipeline_stages(dag) { Ok(stages) => stages, Err(error) => { @@ -402,6 +244,7 @@ fn materialize_pipeline_realizations(dag: &mut Dag) { } } +#[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] fn report_pipeline_authority_error(dag: &mut Dag, name: String) { dag.attach_diagnostic(Diagnostic::ResolveError { name, @@ -410,23 +253,6 @@ fn report_pipeline_authority_error(dag: &mut Dag, name: String) { }); } -fn parse_fixture(dag: &mut Dag, source: &str, file: &str) -> Option { - let tokens = match tokenize(source, file) { - Ok(t) => t, - Err(diag) => { - dag.attach_diagnostic(diag); - return None; - } - }; - match parse(&tokens, file) { - Ok(m) => Some(m), - Err(diag) => { - dag.attach_diagnostic(diag); - None - } - } -} - #[cfg(test)] mod tests { //! §6.5 realization smoke test. The stub chain (Realization meta- diff --git a/src/v3/compiler/src/bootstrap_regen_fresh.rs b/src/v3/compiler/src/bootstrap_regen_fresh.rs new file mode 100644 index 00000000000..acc63539413 --- /dev/null +++ b/src/v3/compiler/src/bootstrap_regen_fresh.rs @@ -0,0 +1,166 @@ +//! Fresh tokenize/parse/lower bootstrap from on-disk `.dag` authorities. +//! +//! This module is compiled **only** with Cargo feature `bootstrap-regen-fresh` +//! (the `regen_bootstrap` binary enables it via `required-features`). It is not +//! a second production bootstrap authority: `Dag::new()` loads the committed +//! `bootstrap_generated.rs` snapshot. Per PB-1-e mechanism (ii), the +//! fresh-compile-vs-snapshot acid test runs at `regen_bootstrap` time +//! (`--verify`), not in the default integration test suite. +//! +//! **Classification:** permanent PB-1-e **regen verification** substrate (not +//! the old “delete once the drift harness stops needing runtime std” scaffold). +//! **Dissolution:** when PB-Bootstrap-Process replaces this hand-Rust regen +//! host with a declared `bootstrap.dag` / generated producer path, delete this +//! module in favor of that single authority — same cost-of-change rule as the +//! retired `bootstrap_std_fixtures_only` dissolution trigger, reframed for +//! “regen host goes data-native” rather than “in-tree tests stop diffing.” + +use crate::dag::{Dag, DeclarationId}; +use crate::lower::{collect_symbols_phase, lower_bodies_phase, resolve_pending_identifiers}; +use crate::parse::{parse, SurfaceModule}; +use crate::tokenize::tokenize; +use std::collections::HashMap; + +const LOGIC_DAG: &str = include_str!("../../../../dsl/std/logic.dag"); +const BIT_DAG: &str = include_str!("../../../../dsl/std/bit.dag"); +const ALGEBRA_DAG: &str = include_str!("../../../../dsl/std/algebra.dag"); +const INTEGER_DAG: &str = include_str!("../../../../dsl/std/integer.dag"); +const FLOAT_DAG: &str = include_str!("../../../../dsl/std/float.dag"); +const STRING_TYPE_DAG: &str = include_str!("../../../../dsl/std/string_type.dag"); +const TYPES_DAG: &str = include_str!("../../../../dsl/std/types.dag"); + +const EXTDEPS_RUST_PRIMITIVES_DAG: &str = + include_str!("../../../../dsl/extdeps/languages/rust/primitives.dag"); + +const EXTDEPS_BOOTSTRAP_FIXTURES: &[(&str, &str)] = &[( + "dsl/extdeps/languages/rust/primitives.dag", + EXTDEPS_RUST_PRIMITIVES_DAG, +)]; + +// Same `OUT_DIR` fixture arrays `build.rs` emits for staged/spec/compiler sources; +// this module is their only remaining fresh-parse consumer. +include!(concat!(env!("OUT_DIR"), "/v3_staged_files.rs")); +include!(concat!(env!("OUT_DIR"), "/v3_specs.rs")); +include!(concat!(env!("OUT_DIR"), "/v3_compiler_files.rs")); + +// Single authority for staged-vs-`dsl/` name collision resolution during regen. +// The committed `bootstrap_generated.rs` snapshot was baked with this policy; any +// future runtime path that re-parses the same fixture set must keep this logic +// in lockstep (cost of change: one module — extend here only). +fn declaration_name_preference_rank(file: &str) -> usize { + if file.starts_with("src/v3/") { + 2 + } else if file.starts_with("dsl/") { + 0 + } else { + 1 + } +} + +pub fn compile_std_bootstrap_dag() -> Dag { + let mut dag = Dag::empty(); + load_fixtures(&mut dag, std_fixtures()); + dag.populate_primitive_cache(); + dag +} + +pub fn compile_full_bootstrap_dag_from_std_seed(std_seed: Dag) -> Dag { + let mut dag = std_seed; + load_runtime_bootstrap_authorities(&mut dag, &[], &[]); + dag +} + +pub fn compile_full_bootstrap_without_parse_surface_dag_from_std_seed(std_seed: Dag) -> Dag { + let mut dag = std_seed; + load_runtime_bootstrap_authorities(&mut dag, &["src/v3/std/parse_surface.dag"], &[]); + dag +} + +fn load_runtime_bootstrap_authorities( + dag: &mut Dag, + excluded_staged_paths: &[&str], + excluded_compiler_paths: &[&str], +) { + let staged_iter = STAGED_FILES + .iter() + .copied() + .filter(|(path, _)| !excluded_staged_paths.contains(path)); + let compiler_iter = COMPILER_FILES + .iter() + .copied() + .filter(|(path, _)| !excluded_compiler_paths.contains(path)); + let fixtures: Vec<(&str, &str)> = staged_iter + .chain(V3_SPECS.iter().copied()) + .chain(compiler_iter) + .chain(EXTDEPS_BOOTSTRAP_FIXTURES.iter().copied()) + .collect(); + load_fixtures(dag, &fixtures); + crate::bootstrap::materialize_pipeline_realizations(dag); + dag.populate_primitive_cache(); +} + +fn std_fixtures() -> &'static [(&'static str, &'static str)] { + &[ + ("dsl/std/logic.dag", LOGIC_DAG), + ("dsl/std/bit.dag", BIT_DAG), + ("dsl/std/algebra.dag", ALGEBRA_DAG), + ("dsl/std/integer.dag", INTEGER_DAG), + ("dsl/std/float.dag", FLOAT_DAG), + ("dsl/std/types.dag", TYPES_DAG), + ("dsl/std/string_type.dag", STRING_TYPE_DAG), + ] +} + +fn load_fixtures(dag: &mut Dag, fixtures: &[(&str, &str)]) { + let mut parsed: Vec<(SurfaceModule, Vec)> = Vec::with_capacity(fixtures.len()); + for (file, source) in fixtures.iter() { + let Some(module) = parse_fixture(dag, source, file) else { + continue; + }; + let (_stale_symbols, is_first) = collect_symbols_phase(dag, &module.items); + parsed.push((module, is_first)); + } + + let mut shared_symbols: HashMap = HashMap::new(); + for d in dag.declarations() { + if let Some(name) = &d.name { + match shared_symbols.get(name).copied() { + None => { + shared_symbols.insert(name.clone(), d.id); + } + Some(existing_id) => { + let existing = dag.declaration(existing_id); + let new_rank = declaration_name_preference_rank(&d.span.file); + let existing_rank = declaration_name_preference_rank(&existing.span.file); + if new_rank > existing_rank { + shared_symbols.insert(name.clone(), d.id); + } + } + } + } + } + + for (module, is_first) in parsed.iter() { + lower_bodies_phase(dag, module, &shared_symbols, is_first); + } + + resolve_pending_identifiers(dag); + crate::bootstrap::patch_kernel_bool_boolean_algebra_inhabits(dag); +} + +fn parse_fixture(dag: &mut Dag, source: &str, file: &str) -> Option { + let tokens = match tokenize(source, file) { + Ok(t) => t, + Err(diag) => { + dag.attach_diagnostic(diag); + return None; + } + }; + match parse(&tokens, file) { + Ok(m) => Some(m), + Err(diag) => { + dag.attach_diagnostic(diag); + None + } + } +} diff --git a/src/v3/compiler/src/dag.rs b/src/v3/compiler/src/dag.rs index 89b3e707136..2933207617d 100644 --- a/src/v3/compiler/src/dag.rs +++ b/src/v3/compiler/src/dag.rs @@ -2163,6 +2163,11 @@ static BOOTSTRAPPED_DAG_WITHOUT_PARSE_SURFACE_FIXTURE: LazyLock = LazyLock: }); impl Dag { + // Only `bootstrap_regen_fresh` constructs an empty Dag for regen; omitting + // that module without `bootstrap-regen-fresh` would otherwise trip `dead_code`. + // If a **default-feature** caller needs `empty()`, do not grow `allow(dead_code)` — + // revisit the PB-1-e regen-vs-runtime authority split instead. + #[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] pub(crate) fn empty() -> Self { Self { nodes: Vec::new(), diff --git a/src/v3/compiler/src/lib.rs b/src/v3/compiler/src/lib.rs index b88909df137..57ab0814aa7 100644 --- a/src/v3/compiler/src/lib.rs +++ b/src/v3/compiler/src/lib.rs @@ -715,6 +715,19 @@ pub mod lens_structural_resolution { } mod bootstrap; + +#[cfg(feature = "bootstrap-regen-fresh")] +mod bootstrap_regen_fresh; + +/// Fresh tokenize/parse/lower bootstrap used **only** by `regen_bootstrap` +/// (`--features bootstrap-regen-fresh`). Default `v3-compiler` builds omit this +/// module; production callers load snapshots via `Dag::new()`. +#[cfg(feature = "bootstrap-regen-fresh")] +pub use bootstrap_regen_fresh::{ + compile_full_bootstrap_dag_from_std_seed, + compile_full_bootstrap_without_parse_surface_dag_from_std_seed, compile_std_bootstrap_dag, +}; + mod dimension; mod infer; @@ -1162,42 +1175,12 @@ pub fn patch_lower_helpers_generated_type_alias_refinement(src: &str) -> String out } -/// PB-1-e scaffold helper: fresh-parse the std fixtures so `regen_bootstrap` -/// can produce `bootstrap_std_generated.rs` from authority. Not a production -/// bootstrap path — `Dag::new()` seeds from the committed snapshot. Sole -/// in-tree consumer is `regen_bootstrap`; CI's `regen_bootstrap` + `git diff` -/// step is the cross-check that the snapshot matches a fresh compile. -pub fn compile_std_bootstrap_dag() -> Dag { - let mut dag = Dag::empty(); - bootstrap::bootstrap_std_fixtures_only(&mut dag); - dag -} - /// PB-1-a generated snapshot helper: load the committed std-fixture /// bootstrap snapshot without re-running tokenize/parse/lower. pub fn generated_std_bootstrap_dag() -> Dag { Dag::std_fixture_bootstrap_snapshot() } -/// PB-1-e regen-only scaffold helper: layer the staged/spec/compiler bootstrap -/// authorities onto an explicitly supplied std seed so all generated outputs in -/// one regen pass derive from the same `dsl/std/*.dag` authority. Sole consumer -/// is `regen_bootstrap`; not a production bootstrap entry point. -pub fn compile_full_bootstrap_dag_from_std_seed(std_seed: Dag) -> Dag { - let mut dag = std_seed; - bootstrap::bootstrap_runtime_authorities_on(&mut dag, &[], &[]); - dag -} - -/// PB-1 closure scaffold helper for `regen_bootstrap`: same as -/// `compile_full_bootstrap_dag_from_std_seed`, but excludes -/// `src/v3/std/parse_surface.dag` so regen/tests can keep that authority first-of-name. -pub fn compile_full_bootstrap_without_parse_surface_dag_from_std_seed(std_seed: Dag) -> Dag { - let mut dag = std_seed; - bootstrap::bootstrap_runtime_authorities_on(&mut dag, &["src/v3/std/parse_surface.dag"], &[]); - dag -} - pub fn generated_full_bootstrap_dag() -> Dag { Dag::new() } diff --git a/src/v3/compiler/src/lower.rs b/src/v3/compiler/src/lower.rs index bb3df0a9c3e..4baf6353f08 100644 --- a/src/v3/compiler/src/lower.rs +++ b/src/v3/compiler/src/lower.rs @@ -2186,6 +2186,7 @@ fn report_declaration_error(dag: &mut Dag, diag: Diagnostic) { /// `algebra.dag` with no defining `.dag` file among the seven loaded), /// and those are not bootstrap errors. User-facing code uses the /// strict variant below. +#[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] pub(crate) fn resolve_pending_identifiers(dag: &mut Dag) { run_identifier_sweep(dag, /*strict_from=*/ usize::MAX); } diff --git a/src/v3/compiler/src/pipeline_authority.rs b/src/v3/compiler/src/pipeline_authority.rs index 01526939c1f..6c55aab78bd 100644 --- a/src/v3/compiler/src/pipeline_authority.rs +++ b/src/v3/compiler/src/pipeline_authority.rs @@ -16,9 +16,14 @@ pub(crate) enum PipelineSnapshotKind { #[derive(Debug, Clone)] pub(crate) struct PipelineStageAuthority { + // Read by `bootstrap::materialize_pipeline_realizations` when feature + // `bootstrap-regen-fresh` is enabled. + #[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] pub(crate) stage: DeclarationId, pub(crate) stage_name: String, + #[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] pub(crate) realization: DeclarationId, + #[cfg_attr(not(feature = "bootstrap-regen-fresh"), allow(dead_code))] pub(crate) realization_name: String, pub(crate) snapshot_kind: PipelineSnapshotKind, } diff --git a/src/v3/compiler/tests/integration/pb1_bootstrap_full_snapshot_test.rs b/src/v3/compiler/tests/integration/pb1_bootstrap_full_snapshot_test.rs index e96eab4bb31..424c294fd08 100644 --- a/src/v3/compiler/tests/integration/pb1_bootstrap_full_snapshot_test.rs +++ b/src/v3/compiler/tests/integration/pb1_bootstrap_full_snapshot_test.rs @@ -1,14 +1,15 @@ //! **Layer:** integration //! -//! PB-1-e — in-tree DB-8 cross-check is now "the committed bootstrap snapshot is -//! internally consistent": `Dag::new()` is diagnostic-clean and byte-stable across -//! clones, and the std-only snapshot is a strict prefix-shape of the full snapshot. -//! The fresh-parse-vs-snapshot acid test runs at regen time (`regen_bootstrap` + -//! CI's `git diff --exit-code` on the committed `bootstrap_*_generated.rs`), -//! not on every `cargo test`. See `docs/briefs/pb-1-e-residual-scaffold-retirement-worker.md`. +//! PB-1-e: in-tree DB-8 cross-check is structural — committed snapshots are +//! internally consistent; `Dag::new()` is diagnostic-clean and byte-stable across +//! clones; the std-only snapshot is a strict prefix-shape of the full snapshot. +//! The fresh-compile vs committed snapshot contract is enforced by CI +//! `regen_bootstrap --verify` (`--features bootstrap-regen-fresh`), not on every +//! `cargo test`. See `docs/briefs/pb-1-e-residual-scaffold-retirement-worker.md`. use v3_compiler::{ - generated_full_bootstrap_dag, generated_std_bootstrap_dag, + generated_full_bootstrap_dag, generated_full_bootstrap_without_parse_surface_dag, + generated_std_bootstrap_dag, serialize::{first_difference, serialize_dag}, Dag, }; @@ -23,6 +24,58 @@ fn full_bootstrap_extends_std_snapshot() { ); } +#[test] +fn generated_std_bootstrap_snapshot_has_no_diagnostics() { + let dag = generated_std_bootstrap_dag(); + assert!( + dag.diagnostics().is_empty(), + "expected clean std snapshot bootstrap, got {:?}", + dag.diagnostics() + ); +} + +#[test] +fn generated_std_bootstrap_snapshot_includes_bool() { + let dag = generated_std_bootstrap_dag(); + assert!( + dag.declaration_by_name("Bool").is_some(), + "std snapshot should include kernel Bool" + ); +} + +#[test] +fn generated_full_bootstrap_snapshots_have_no_diagnostics() { + for (label, dag) in [ + ("full", generated_full_bootstrap_dag()), + ( + "without_parse_surface", + generated_full_bootstrap_without_parse_surface_dag(), + ), + ] { + assert!( + dag.diagnostics().is_empty(), + "{label}: expected clean generated bootstrap, got {:?}", + dag.diagnostics() + ); + } +} + +#[test] +fn generated_full_bootstrap_snapshots_include_parse_stage() { + for (label, dag) in [ + ("full", generated_full_bootstrap_dag()), + ( + "without_parse_surface", + generated_full_bootstrap_without_parse_surface_dag(), + ), + ] { + assert!( + dag.declaration_by_name("parse").is_some(), + "{label}: expected pipeline `parse` stage in bootstrap Dag" + ); + } +} + #[test] fn dag_new_bootstrap_is_clean_and_byte_stable() { let first = Dag::new(); diff --git a/src/v3/compiler/tests/integration/sg0_census_test.rs b/src/v3/compiler/tests/integration/sg0_census_test.rs index 89a68110ba2..51180ccba2f 100644 --- a/src/v3/compiler/tests/integration/sg0_census_test.rs +++ b/src/v3/compiler/tests/integration/sg0_census_test.rs @@ -159,6 +159,7 @@ const EXPECTED_HAND_AUTHORED_NON_TEST: &[&str] = &[ "src/v3/compiler/src/bin/regen_v3.rs", "src/v3/compiler/src/bin/self_host_fixed_point.rs", "src/v3/compiler/src/bootstrap.rs", + "src/v3/compiler/src/bootstrap_regen_fresh.rs", "src/v3/compiler/src/dag.rs", "src/v3/compiler/src/dag/builder.rs", "src/v3/compiler/src/dag/effects.rs",