Skip to main content

sqry_core/graph/unified/rebuild/
rebuild_graph.rs

1//! [A2 §H] `RebuildGraph` + `clone_for_rebuild` + `finalize()` — Gate 0c.
2//!
3//! **This module is feature-gated.** Every item lives behind
4//! `#[cfg(feature = "rebuild-internals")]`; only `sqry-daemon` is
5//! whitelisted to enable the feature (see
6//! `sqry-core/tests/rebuild_internals_whitelist.rs` and the plan at
7//! `docs/superpowers/plans/2026-03-19-sqryd-daemon.md` §H "Placement
8//! and feature gate").
9//!
10//! # What this module delivers
11//!
12//! Per the plan's A2 §H (pre-implementation Gate 0c, required before
13//! any `clone_for_rebuild` caller in Task 4 Step 4 can exist):
14//!
15//! 1. [`sqry_graph_fields!`] — a **single source of truth** macro that
16//!    enumerates every field on [`super::super::concurrent::CodeGraph`].
17//!    It is invoked in three places by the rest of this module:
18//!      - `sqry_graph_fields!(@decl_rebuild)` declares the
19//!        [`RebuildGraph`] struct.
20//!      - `sqry_graph_fields!(@clone_inner from self)` is expanded
21//!        inside [`CodeGraph::clone_for_rebuild`]; the destructure
22//!        `let CodeGraph { .. } = self;` is exhaustive, so adding a
23//!        field to [`CodeGraph`] without adding it to the macro's
24//!        field list is a hard `E0027` compile error.
25//!      - `sqry_graph_fields!(@field_names)` emits a `&[&str]` of
26//!        every field name, used by the Gate 0d bijection check
27//!        (future) and by diagnostics.
28//! 2. [`CodeGraph::clone_for_rebuild`] — deep-copies every Arc-wrapped
29//!    field into an owned, rebuild-local [`RebuildGraph`]. The rebuild
30//!    dispatcher (Task 4 Step 4) is the only caller.
31//! 3. [`RebuildGraph::finalize`] — the canonical 14-step sequence
32//!    spelled out in §H lines 658–707. Every step is either an API
33//!    call on an owned component (freeze interner, compact arena,
34//!    compact edges, compact indices, compact metadata, compact file
35//!    buckets, compact K-list extras), a drain/move of scratch state
36//!    (drain tombstones), a derived-state reset (rebuild CSR), a
37//!    per-language metadata update (confidence), a scalar bump (epoch),
38//!    a struct assembly (`Arc::new` wrapping), or a debug invariant
39//!    (bucket bijection + tombstone residue).
40//!
41//! # Why the macro is kind-tagged, not a single callback
42//!
43//! The plan's literal example invokes `sqry_graph_fields!(CodeGraph,
44//! RebuildGraph)` to generate both structs from one sibling macro
45//! call. That shape would require `CodeGraph` to be declared by the
46//! macro — but `CodeGraph` has dozens of `impl` blocks, Clone
47//! semantics, and accessor methods that already destructure the fields
48//! by name on stable Rust. Moving the declaration into a macro
49//! expansion would obscure every one of those sites.
50//!
51//! A callback-based idiom (`sqry_graph_fields!(my_cb!)`) was also
52//! considered; it worked for the struct declaration but collapsed
53//! under `macro_rules!` hygiene constraints for the destructure-and-
54//! construct clone path (the `self` keyword cannot be synthesised by
55//! a macro; passing identifiers across a callback boundary requires
56//! forwarding them through an `:expr` metavar, which loses the
57//! token-level decomposition needed for Arc-vs-scalar dispatch).
58//!
59//! The **kind-tagged single macro** settled on here expands inline at
60//! the call site — `sqry_graph_fields!(@clone_inner from self)` —
61//! so the destructure runs in the caller's hygiene context, the
62//! `self` keyword is the caller's `self`, and the per-field Arc /
63//! scalar / owned dispatch is baked into the macro body without a
64//! secondary callback hop.
65//!
66//! The single-source-of-truth guarantee is the same: adding a field
67//! requires touching (a) the `CodeGraph` struct in
68//! `concurrent/graph.rs`, (b) the field list inside this macro, and
69//! (c) the step in `finalize()` that compacts it. Missing any of
70//! (a) or (b) makes `clone_for_rebuild_inner` fail to compile.
71//!
72//! # Release-build posture
73//!
74//! The debug bucket-bijection and tombstone-residue checks at steps 13
75//! and 14 are gated on `cfg(any(debug_assertions, test))`. Release
76//! builds pay zero overhead. The §E equivalence harness in CI is the
77//! release-time drift backstop (plan §F "Release build semantics").
78
79// Module-level `#[cfg(feature = "rebuild-internals")]` lives on the
80// `pub mod rebuild_graph;` declaration in the parent `mod.rs`; duplicating
81// it here trips the `duplicated_attributes` clippy lint.
82#![allow(clippy::too_many_lines)]
83
84use std::collections::{HashMap, HashSet};
85
86use crate::confidence::ConfidenceMetadata;
87use crate::graph::error::GraphResult;
88use crate::graph::unified::bind::alias::AliasTable;
89use crate::graph::unified::bind::scope::ScopeArena;
90use crate::graph::unified::bind::scope::provenance::ScopeProvenanceStore;
91use crate::graph::unified::bind::shadow::ShadowTable;
92use crate::graph::unified::concurrent::CodeGraph;
93use crate::graph::unified::edge::bidirectional::BidirectionalEdgeStore;
94use crate::graph::unified::node::NodeId;
95use crate::graph::unified::storage::arena::NodeArena;
96use crate::graph::unified::storage::c_indirect::CIndirectSideTables;
97use crate::graph::unified::storage::edge_provenance::EdgeProvenanceStore;
98use crate::graph::unified::storage::indices::AuxiliaryIndices;
99use crate::graph::unified::storage::interner::StringInterner;
100use crate::graph::unified::storage::metadata::NodeMetadataStore;
101use crate::graph::unified::storage::node_provenance::NodeProvenanceStore;
102use crate::graph::unified::storage::registry::FileRegistry;
103use crate::graph::unified::storage::segment::FileSegmentTable;
104
105use super::coverage::NodeIdBearing;
106
107// =====================================================================
108// Single source of truth: field list
109// =====================================================================
110
111/// Single source of truth for the [`CodeGraph`] field list.
112///
113/// This macro takes a **kind-tag** selector (`@decl_rebuild`,
114/// `@clone_inner from ...`, `@field_names`) and emits a tailored
115/// expansion for each consumer. The field-list rows live exactly once,
116/// inside this macro body, so any new field is added in one place:
117/// here.
118///
119/// # Adding / renaming / removing a field on [`CodeGraph`]
120///
121/// 1. Edit the `CodeGraph` struct in
122///    `sqry-core/src/graph/unified/concurrent/graph.rs` (declaration
123///    order matters — match the order here).
124/// 2. Edit the field list below. The `@decl_rebuild` arm auto-mirrors
125///    into `RebuildGraph`; the `@clone_inner` arm auto-mirrors into
126///    `clone_for_rebuild_inner`.
127/// 3. Extend `RebuildGraph::finalize()` with the step that compacts
128///    the new field (and, if it carries `NodeId`s, add a K.A/K.B row
129///    + `NodeIdBearing` impl in `super::coverage`).
130///
131/// Missing step (1) or (2) is a hard `E0027` compile error in the
132/// `let CodeGraph { .. } = ...` destructure inside the `@clone_inner`
133/// arm. Step (3) is enforced by the §F tombstone-residue check
134/// (Gate 0d) and by the §E incremental-vs-full equivalence harness.
135#[macro_export]
136macro_rules! sqry_graph_fields {
137    // -------------------------------------------------------------
138    // Arm @decl_rebuild: emit the `RebuildGraph` struct declaration.
139    // -------------------------------------------------------------
140    (@decl_rebuild) => {
141        /// Owned, rebuild-local mirror of [`CodeGraph`].
142        ///
143        /// Each field stores a value type rather than an [`Arc`], so
144        /// the rebuild task can mutate freely without touching the
145        /// live published graph. The only path to produce a
146        /// publishable [`CodeGraph`] from a [`RebuildGraph`] is
147        /// [`RebuildGraph::finalize`]; the trybuild fixture at
148        /// `sqry-core/tests/rebuild_internals_compile_fail/rebuild_graph_no_public_assembly.rs`
149        /// locks that invariant in.
150        pub struct RebuildGraph {
151            pub(crate) nodes: NodeArena,
152            pub(crate) edges: BidirectionalEdgeStore,
153            pub(crate) strings: StringInterner,
154            pub(crate) files: FileRegistry,
155            pub(crate) indices: AuxiliaryIndices,
156            pub(crate) macro_metadata: NodeMetadataStore,
157            pub(crate) node_provenance: NodeProvenanceStore,
158            pub(crate) edge_provenance: EdgeProvenanceStore,
159            pub(crate) fact_epoch: u64,
160            pub(crate) epoch: u64,
161            pub(crate) confidence: HashMap<String, ConfidenceMetadata>,
162            pub(crate) scope_arena: ScopeArena,
163            pub(crate) alias_table: AliasTable,
164            pub(crate) shadow_table: ShadowTable,
165            pub(crate) scope_provenance_store: ScopeProvenanceStore,
166            pub(crate) file_segments: FileSegmentTable,
167            /// Phase A (U09): C indirect-call resolver side tables.
168            /// `None` outside C workspaces; cloned through the rebuild
169            /// pipeline so an in-flight rebuild preserves the side
170            /// tables already committed on the source graph.
171            pub(crate) c_indirect_tables: Option<CIndirectSideTables>,
172            /// Build-time scratch side-channel for the Go plugin's
173            /// post-Phase-4e `pass_go_method_set_satisfaction` (Cluster
174            /// A of the Go T1 implements-and-promotion design). Mirror
175            /// of `CodeGraph::go_hints`; held by value (no Arc) for
176            /// the same rationale as on `CodeGraph`.
177            pub(crate) go_hints: $crate::graph::unified::build::staging::GoHints,
178            /// Active tombstone set during finalize steps 2–7.
179            /// Populated by `RebuildGraph::remove_file` /
180            /// `RebuildGraph::tombstone` (added by Task 4 Step 4) and
181            /// drained into [`drained_tombstones`] at step 8.
182            pub(crate) tombstones: HashSet<NodeId>,
183            /// Snapshot of [`tombstones`] taken at finalize step 8,
184            /// kept for the debug residue check in step 14.
185            pub(crate) drained_tombstones: HashSet<NodeId>,
186        }
187    };
188
189    // -------------------------------------------------------------
190    // Arm @clone_inner: emit the body of `clone_for_rebuild_inner`.
191    //
192    // The caller passes their `self` binding as `$this:expr` so
193    // macro hygiene preserves the method-local reference. The
194    // destructure is exhaustive — adding a `CodeGraph` field without
195    // also adding it here is a hard `E0027` compile error. Removing
196    // a row here without removing the `CodeGraph` field is an unused-
197    // pattern warning that our `-D warnings` CI setting escalates.
198    // -------------------------------------------------------------
199    (@clone_inner from $this:expr) => {{
200        let CodeGraph {
201            nodes,
202            edges,
203            strings,
204            files,
205            indices,
206            macro_metadata,
207            node_provenance,
208            edge_provenance,
209            fact_epoch,
210            epoch,
211            confidence,
212            scope_arena,
213            alias_table,
214            shadow_table,
215            scope_provenance_store,
216            file_segments,
217            c_indirect_tables,
218            go_hints,
219            // Not mirrored into RebuildGraph: a rebuild reparses source files and
220            // regenerates is_definition fresh, so `finalize` stamps the marker
221            // `true` unconditionally. Destructured to `_` to keep the match
222            // exhaustive (the E0027 guard still fires for any other new field).
223            definition_signal_present: _,
224        } = $this;
225        RebuildGraph {
226            nodes: (**nodes).clone(),
227            edges: (**edges).clone(),
228            strings: (**strings).clone(),
229            files: (**files).clone(),
230            indices: (**indices).clone(),
231            macro_metadata: (**macro_metadata).clone(),
232            node_provenance: (**node_provenance).clone(),
233            edge_provenance: (**edge_provenance).clone(),
234            fact_epoch: *fact_epoch,
235            epoch: *epoch,
236            confidence: confidence.clone(),
237            scope_arena: (**scope_arena).clone(),
238            alias_table: (**alias_table).clone(),
239            shadow_table: (**shadow_table).clone(),
240            scope_provenance_store: (**scope_provenance_store).clone(),
241            file_segments: (**file_segments).clone(),
242            c_indirect_tables: c_indirect_tables.clone(),
243            go_hints: go_hints.clone(),
244            tombstones: ::std::collections::HashSet::new(),
245            drained_tombstones: ::std::collections::HashSet::new(),
246        }
247    }};
248
249    // -------------------------------------------------------------
250    // Arm @field_names: emit a comma-separated list of every field
251    // name. Used by tests that want to assert coverage of field names
252    // against a declared list without re-parsing Rust source.
253    // -------------------------------------------------------------
254    (@field_names) => {
255        &[
256            "nodes",
257            "edges",
258            "strings",
259            "files",
260            "indices",
261            "macro_metadata",
262            "node_provenance",
263            "edge_provenance",
264            "fact_epoch",
265            "epoch",
266            "confidence",
267            "scope_arena",
268            "alias_table",
269            "shadow_table",
270            "scope_provenance_store",
271            "file_segments",
272            "c_indirect_tables",
273            "go_hints",
274        ]
275    };
276}
277
278// =====================================================================
279// RebuildGraph struct declaration (macro-driven)
280// =====================================================================
281
282sqry_graph_fields!(@decl_rebuild);
283
284// =====================================================================
285// clone_for_rebuild: CodeGraph -> RebuildGraph
286// =====================================================================
287
288impl CodeGraph {
289    /// Produce a fresh [`RebuildGraph`] from this graph's current
290    /// committed state, deep-cloning every Arc-wrapped component so the
291    /// returned value is decoupled from future mutations to `self`.
292    ///
293    /// The exhaustive destructure inside the `@clone_inner` arm of
294    /// [`sqry_graph_fields!`] guarantees that every field on
295    /// [`CodeGraph`] is mirrored into the returned [`RebuildGraph`].
296    /// Adding a field to [`CodeGraph`] without also adding it to the
297    /// field list inside `sqry_graph_fields!` is a hard `E0027`
298    /// compile error on the `let CodeGraph { .. } = self;` destructure.
299    ///
300    /// # When to call this
301    ///
302    /// Only the incremental-rebuild dispatcher (Task 4 Step 4) calls
303    /// `clone_for_rebuild`, on the rebuild task's background tokio
304    /// context, against an `Arc<CodeGraph>` freshly obtained via
305    /// `ArcSwap::load_full()`. The Arc's refcount is 1 in the common
306    /// case, so the underlying deep clones amount to `Arc::get_mut`-
307    /// equivalent cost on each component.
308    ///
309    /// # Performance budget (A2 §H, line 734)
310    ///
311    /// On a 384k-node / 1.3M-edge reference graph, this call must
312    /// complete in < 50 ms. The daemon's rebuild-latency benchmark
313    /// tracks the budget; warning threshold 50 ms, hard record
314    /// threshold 200 ms. Exceeding the warning logs but does not fail
315    /// the rebuild.
316    #[must_use]
317    pub fn clone_for_rebuild(&self) -> RebuildGraph {
318        Self::clone_for_rebuild_inner(self)
319    }
320
321    /// Inner implementation, kept separate so the public entrypoint is
322    /// a single-line shim that also makes the exhaustive destructure
323    /// visible at the top of the rebuild surface.
324    ///
325    /// The `@clone_inner from self` macro arm emits the destructure +
326    /// struct-construction inline; passing `self` as an `:expr`
327    /// metavar preserves call-site hygiene so the macro-introduced
328    /// field bindings (`nodes`, `edges`, ...) are resolvable against
329    /// the `self` binding in this method.
330    fn clone_for_rebuild_inner(&self) -> RebuildGraph {
331        sqry_graph_fields!(@clone_inner from self)
332    }
333}
334
335// =====================================================================
336// finalize(): RebuildGraph -> CodeGraph — the 14-step contract
337// =====================================================================
338
339impl RebuildGraph {
340    /// Consume this [`RebuildGraph`] and assemble a publishable
341    /// [`CodeGraph`].
342    ///
343    /// This is the **only** safe path from [`RebuildGraph`] back to
344    /// [`CodeGraph`]. No public API converts a [`RebuildGraph`] into
345    /// an [`Arc<CodeGraph>`] any other way, and no
346    /// `From<RebuildGraph> for CodeGraph` impl exists — the trybuild
347    /// fixture at
348    /// `sqry-core/tests/rebuild_internals_compile_fail/rebuild_graph_no_public_assembly.rs`
349    /// locks that property in.
350    ///
351    /// # The 14 ordered steps (plan §H lines 658–707)
352    ///
353    /// Each numbered comment below traces the matching plan step. In
354    /// debug / test builds, steps 13 and 14 also execute the §F
355    /// bijection and tombstone-residue checks; release builds compile
356    /// them out.
357    ///
358    /// Steps 2–7 uniformly invoke
359    /// [`super::coverage::NodeIdBearing::retain_nodes`] with the
360    /// closure `|nid| !self.tombstones.contains(&nid)`, so adding a new
361    /// K.A or K.B row for a future `NodeId`-bearing container
362    /// automatically extends compaction coverage once the new row's
363    /// `retain_nodes` call is appended to step 7.
364    ///
365    /// # Errors
366    ///
367    /// Returns `Err(GraphBuilderError::Internal{..})` only if a
368    /// compaction primitive fails; all current primitives are
369    /// infallible, so `finalize()` is currently infallible. The `Result`
370    /// return is preserved for future fallible compaction steps without
371    /// a signature change.
372    pub fn finalize(mut self) -> GraphResult<CodeGraph> {
373        // ----------------------------------------------------------------
374        // Step 1 — Freeze the rebuild's interner.
375        //
376        // The plan §H describes step 1 as `new_strings =
377        // self.string_builder.freeze()`. In this codebase the
378        // rebuild-local interner is a [`StringInterner`] (no separate
379        // "builder" type), so the concrete freeze operation is:
380        //
381        //   (a) canonicalise the interner by running
382        //       [`StringInterner::build_dedup_table`]. This guarantees:
383        //         * `lookup_stale == false` (required for all read-path
384        //           accessors); any in-flight bulk-alloc residue from a
385        //           prior failed rebuild is healed.
386        //         * Every string value is backed by exactly one
387        //           canonical slot — no duplicate arcs remain. The
388        //           `ref_counts` of duplicate slots are folded into
389        //           their canonical slot. `StringId` values held by
390        //           live `NodeEntry`s remain valid because this pass
391        //           only collapses slots that are *not* referenced from
392        //           live nodes (nothing in this pass renames already
393        //           live slots).
394        //   (b) rewrite every live `NodeEntry` through the remap table
395        //       produced by (a) so any node whose fields happen to
396        //       point at a now-collapsed duplicate slot is rewired to
397        //       the canonical slot. This preserves the post-freeze
398        //       invariant "every live `NodeEntry` references only
399        //       canonical `StringId`s" even if earlier rebuild steps
400        //       produced duplicate slots.
401        //   (c) prune unreferenced slots with
402        //       [`StringInterner::recycle_unreferenced`] so the frozen
403        //       interner carries only strings the final graph actually
404        //       needs. This is the step that drives
405        //       `interner_live_ratio < interner_compaction_threshold`
406        //       down over time (plan §H line 713) so the next
407        //       housekeeping rebuild observes an accurate live ratio.
408        //
409        // After this block runs, `self.strings` is in a fully
410        // canonical, shared-immutable-ready state. Step 12's
411        // `Arc::new(new_strings)` is then purely the ownership-to-
412        // shared transition; the semantic freeze itself has already
413        // happened here.
414        // ----------------------------------------------------------------
415        let string_remap = self.strings.build_dedup_table();
416        if !string_remap.is_empty() {
417            // Rewrite every live node's interned-string fields through
418            // the remap so freshly-collapsed duplicate slots are not
419            // reachable from any live `NodeEntry`. This is required
420            // for (c) below to be safe to call: `recycle_unreferenced`
421            // only frees slots with `ref_count == 0`, so the refcount
422            // bookkeeping that `build_dedup_table` consolidated into
423            // the canonical slot must be honoured by node-level fields
424            // as well.
425            rewrite_node_entries_through_remap(&mut self.nodes, &string_remap);
426            // Iter-2 B1 (verbatim): `AuxiliaryIndices::name_index` /
427            // `qualified_name_index` are keyed by `StringId`. If
428            // `build_dedup_table()` collapses a key's slot and
429            // `recycle_unreferenced` subsequently frees it, the bucket
430            // keys would dangle. Remap every `StringId`-backed holder
431            // on the rebuild through the same dedup table before the
432            // recycle pass runs, merging any buckets that collapse onto
433            // the same canonical key.
434            //
435            // All remap-capable stores are listed here exhaustively.
436            // Extending this block when a new `CodeGraph` field gains a
437            // `StringId` payload is a code-owner obligation tied to the
438            // `sqry_graph_fields!` macro (plan §H "Placement and feature
439            // gate"). Today, the StringId-bearing surfaces on the
440            // publish-visible graph are:
441            //
442            //   * `AuxiliaryIndices.name_index` / `qualified_name_index`
443            //     (BTreeMap keys — collapse on canonicalisation)
444            //   * `FileRegistry` — `FileEntry.source_uri: Option<StringId>`
445            //     per slot
446            //   * `AliasTable` — `AliasEntry.from_symbol` /
447            //     `to_symbol` per entry; the `(scope, from_symbol)`
448            //     sort key is re-established after rewrite
449            //   * `ShadowTable` — `ShadowEntry.symbol` per entry; the
450            //     `(scope, symbol, byte_offset)` sort key and the
451            //     `chains` range index are rebuilt after rewrite
452            //
453            // `NodeArena` (above) is the fifth surface; it is handled
454            // inline because it is the single largest consumer and
455            // already has a purpose-built helper.
456            //
457            // Iter-3 B1 (verbatim): `BidirectionalEdgeStore` holds
458            // `EdgeKind` instances whose variants — `Imports{alias}`,
459            // `Exports{alias}`, `TypeOf{name}`, `TraitMethodBinding
460            // {trait_name, impl_type}`, `HttpRequest{url}`,
461            // `GrpcCall{service, method}`, `DbQuery{table}`,
462            // `TableRead{table_name, schema}`, `TableWrite{table_name,
463            // schema}`, `TriggeredBy{trigger_name, schema}`,
464            // `MessageQueue{protocol::Other(_), topic}`,
465            // `WebSocket{event}`, `GraphQLOperation{operation}`,
466            // `ProcessExec{command}`, `FileIpc{path_pattern}`,
467            // `ProtocolCall{protocol, metadata}` — carry
468            // `StringId` payloads inside both the steady-state CSR
469            // (`CsrGraph::edge_kind`) and the mutable delta
470            // (`DeltaBuffer` `DeltaEdge::kind`), in **both** the
471            // forward and reverse stores. Before this iter-4 fix,
472            // step 1 left those payloads un-remapped — so after
473            // `recycle_unreferenced` below, those edges would have
474            // dangled onto freed interner slots. The full-build
475            // pipeline recognises this surface explicitly at
476            // `build/entrypoint.rs` (Phase 4b) +
477            // `build/parallel_commit.rs::phase4_apply_global_remap`;
478            // the rebuild pipeline must do the same against
479            // committed storage because, unlike Phase 4b, the edges
480            // are no longer a `Vec<Vec<PendingEdge>>`.
481            //
482            // `BidirectionalEdgeStore::rewrite_edge_kind_string_ids_through_remap`
483            // is the sixth surface on this list. The exhaustive match
484            // on `EdgeKind` lives in
485            // `parallel_commit::remap_edge_kind_string_ids` so adding a
486            // new `StringId`-bearing variant becomes a single source of
487            // truth: a compile error there forces both pipelines to
488            // rewrite it.
489            //
490            // Stores whose data is keyed by `NodeId`/`FileId`/`EdgeId`
491            // only (metadata keyed on NodeId, node / edge provenance,
492            // scope arena indexed by ScopeId, scope provenance,
493            // file-segments keyed on FileId/EdgeId) do not hold
494            // `StringId` payloads and are out of scope for this
495            // rewrite. Any future field that lifts a `StringId` onto
496            // `CodeGraph` must extend this list in the same commit
497            // that declares it, matching the A2 §K discipline.
498            self.indices.rewrite_string_ids_through_remap(&string_remap);
499            self.files.rewrite_string_ids_through_remap(&string_remap);
500            self.alias_table
501                .rewrite_string_ids_through_remap(&string_remap);
502            self.shadow_table
503                .rewrite_string_ids_through_remap(&string_remap);
504            // Iter-4 K.B1 fix: rewrite `StringId` payloads carried by
505            // committed `EdgeKind`s in both forward and reverse stores,
506            // across both CSR and delta tiers. Must run before
507            // `recycle_unreferenced` below so freed slots stay unreferenced.
508            self.edges
509                .rewrite_edge_kind_string_ids_through_remap(&string_remap);
510        }
511        self.strings.recycle_unreferenced();
512
513        // ----------------------------------------------------------------
514        // Step 2 — Compact NodeArena.
515        //
516        // K.A1 row: `NodeArena::retain_nodes` drops every occupied slot
517        // whose NodeId fails the predicate, advancing the slot's
518        // generation so lingering NodeId handles become stale.
519        // ----------------------------------------------------------------
520        {
521            let tombstones = &self.tombstones;
522            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
523                Box::new(move |nid| !tombstones.contains(&nid));
524            self.nodes.retain_nodes(&*predicate);
525        }
526
527        // ----------------------------------------------------------------
528        // Step 3 — Compact BidirectionalEdgeStore (forward + reverse).
529        //
530        // K.A2 + K.A3 rows: `retain_nodes` drops every delta edge with
531        // a tombstoned endpoint in either direction. CSR compaction is
532        // deferred to step 9 (CSR is derived state, rebuilt not mutated).
533        // ----------------------------------------------------------------
534        {
535            let tombstones = &self.tombstones;
536            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
537                Box::new(move |nid| !tombstones.contains(&nid));
538            self.edges.retain_nodes(&*predicate);
539        }
540
541        // ----------------------------------------------------------------
542        // Step 4 — Compact AuxiliaryIndices.
543        //
544        // K.A4–K.A7 rows (kind / name / qualified-name / file indices):
545        // a single `AuxiliaryIndices::retain_nodes` call visits every
546        // inner bucket.
547        // ----------------------------------------------------------------
548        {
549            let tombstones = &self.tombstones;
550            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
551                Box::new(move |nid| !tombstones.contains(&nid));
552            self.indices.retain_nodes(&*predicate);
553        }
554
555        // ----------------------------------------------------------------
556        // Step 5 — Compact NodeMetadataStore.
557        //
558        // K.A8 row: macro / classpath per-node metadata keyed by the
559        // full `(index, generation)` pair.
560        // ----------------------------------------------------------------
561        {
562            let tombstones = &self.tombstones;
563            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
564                Box::new(move |nid| !tombstones.contains(&nid));
565            self.macro_metadata.retain_nodes(&*predicate);
566        }
567
568        // ----------------------------------------------------------------
569        // Step 6 — Compact FileRegistry per-file buckets.
570        //
571        // K.B1 row. Iter-2 B2 (verbatim): this step used to be a
572        // no-op scheduled against a future base-plan Step 1. Pulling
573        // `per_file_nodes: HashMap<FileId, Vec<NodeId>>` forward into
574        // Gate 0c retires the no-op — every `NodeId` the rebuild's
575        // parallel-parse pass committed is already bucketed via
576        // `FileRegistry::record_node`, so this step now does real work:
577        //
578        //   * drop every `NodeId` whose arena slot was tombstoned in
579        //     step 2 (or earlier) via the shared predicate
580        //   * dedup each surviving bucket
581        //   * drop buckets that collapse to empty
582        //
583        // The §F.1 bucket-bijection check at step 13 consumes the
584        // result of this compaction, so a mis-applied predicate here
585        // surfaces as a panic at the publish boundary in debug builds.
586        // ----------------------------------------------------------------
587        {
588            let tombstones = &self.tombstones;
589            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
590                Box::new(move |nid| !tombstones.contains(&nid));
591            self.files.retain_nodes(&*predicate);
592        }
593
594        // ----------------------------------------------------------------
595        // Step 7 — Compact K-list extras.
596        //
597        // Rows K.A10 (node_provenance), K.A11 (scope_arena),
598        // K.A12 (alias_table), K.A13 (shadow_table). Each is a direct
599        // NodeIdBearing::retain_nodes call.
600        //
601        // When a future task lifts a new NodeId-bearing structure onto
602        // `CodeGraph`, extend this step with one additional
603        // `retain_nodes` call and add a K.A/K.B row to
604        // `super::coverage` per the plan §K contract.
605        // ----------------------------------------------------------------
606        {
607            let tombstones = &self.tombstones;
608            let predicate: Box<dyn Fn(NodeId) -> bool + '_> =
609                Box::new(move |nid| !tombstones.contains(&nid));
610            self.node_provenance.retain_nodes(&*predicate);
611            self.scope_arena.retain_nodes(&*predicate);
612            self.alias_table.retain_nodes(&*predicate);
613            self.shadow_table.retain_nodes(&*predicate);
614        }
615
616        // ----------------------------------------------------------------
617        // Step 8 — Drain tombstones into `drained_tombstones`.
618        //
619        // The residue check at step 14 asserts that the finalized
620        // `CodeGraph` does not contain any of these NodeIds in any
621        // NodeId-bearing structure. Keep the drained set until the
622        // check completes; then it is dropped with `self`.
623        // ----------------------------------------------------------------
624        self.drained_tombstones = std::mem::take(&mut self.tombstones);
625
626        // ----------------------------------------------------------------
627        // Step 9 — Rebuild CSR adjacency (both directions).
628        //
629        // CSR is derived state (K.A9 — "CSR adjacency is derived state;
630        // rebuilt from compacted edges — never mutated in place"). After
631        // step 3 filtered the delta tier to live-only endpoints, the
632        // correct operation is to *construct* a fresh CSR from the
633        // compacted delta snapshot and *install* it — not merely drop
634        // the stale cache. This matches plan §H lines 684–691 (the
635        // committed-then-queried graph has a CSR from the first read).
636        //
637        // Build path: `compaction::snapshot_edges` → compaction merges
638        // in-memory delta (no tombstones left after step 3) →
639        // `build_compacted_csr` constructs an immutable `CsrGraph` →
640        // `swap_csrs_and_clear_deltas` installs both directions and
641        // clears the now-absorbed delta buffers. The node_count is the
642        // post-compaction slot count of the arena (not the live count —
643        // CSR uses dense slot indexing; vacant slots appear as nodes
644        // with zero out-edges).
645        //
646        // The plan's example spells this `self.edges.rebuild_csr()` as
647        // shorthand for this sequence; we expand it to concrete calls
648        // so reviewers can audit each primitive. The post-condition is
649        // identical to the plan's: after step 9 the `CodeGraph` about
650        // to be assembled has no CSR referencing a tombstoned NodeId,
651        // because the CSR was built from the already-filtered delta.
652        // ----------------------------------------------------------------
653        {
654            use crate::graph::unified::compaction::{
655                Direction, build_compacted_csr, snapshot_edges,
656            };
657            let node_count = self.nodes.slot_count();
658            // Snapshot the forward/reverse deltas (CSR is still stale
659            // at this point — `build_compacted_csr` uses the delta's
660            // live-only contents). Because step 3 tombstoned endpoints
661            // out of the delta already, the merged build sees only
662            // live edges.
663            let forward_snapshot = {
664                let forward = self.edges.forward();
665                snapshot_edges(&forward, node_count)
666            };
667            let reverse_snapshot = {
668                let reverse = self.edges.reverse();
669                snapshot_edges(&reverse, node_count)
670            };
671            // Build both directions in parallel (matches the pattern
672            // used by `build/entrypoint.rs`).
673            let (forward_csr, reverse_csr) = rayon::join(
674                || build_compacted_csr(&forward_snapshot, Direction::Forward),
675                || build_compacted_csr(&reverse_snapshot, Direction::Reverse),
676            );
677            let (forward_csr, _) =
678                forward_csr.map_err(|e| crate::graph::error::GraphBuilderError::Internal {
679                    reason: format!("rebuild finalize step 9 (forward CSR build): {e}"),
680                })?;
681            let (reverse_csr, _) =
682                reverse_csr.map_err(|e| crate::graph::error::GraphBuilderError::Internal {
683                    reason: format!("rebuild finalize step 9 (reverse CSR build): {e}"),
684                })?;
685            // Install both CSRs and clear the absorbed deltas.
686            self.edges
687                .swap_csrs_and_clear_deltas(forward_csr, reverse_csr);
688        }
689
690        // ----------------------------------------------------------------
691        // Step 10 — Per-language confidence update.
692        //
693        // Incremental rebuild must ensure the published confidence map
694        // matches the set of languages that actually have live nodes in
695        // the rebuild's graph. Languages whose only source files were
696        // all removed during this rebuild must not linger in the
697        // confidence surface — they would mislead MCP clients into
698        // believing analysis for that language is still available.
699        //
700        // The rebuild-local `FileRegistry` carries per-file `Language`
701        // tags; we enumerate them, collect the set of languages with at
702        // least one live file, and drop confidence entries for any
703        // language that no longer appears. Entries for still-present
704        // languages are preserved as-is (their `ConfidenceMetadata` is
705        // updated by the plugin-level confidence-ingestion path in
706        // `CodeGraph::merge_confidence`; this step only filters, it
707        // does not fabricate new samples).
708        //
709        // A language entry is preserved when (a) at least one live file
710        // is tagged with that language in the rebuild-local registry,
711        // OR (b) the confidence entry carries a non-default set of
712        // limitations / unavailable-features — that is analysis
713        // metadata the plugin layer deliberately recorded, and dropping
714        // it on a zero-file rebuild would be lossy. Both conditions are
715        // evaluated against the rebuild-local state that will be
716        // published by step 12.
717        // ----------------------------------------------------------------
718        {
719            use std::collections::BTreeSet;
720            let mut active_languages: BTreeSet<String> = BTreeSet::new();
721            for (_file_id, _path, maybe_language) in self.files.iter_with_language() {
722                if let Some(language) = maybe_language {
723                    active_languages.insert(language.to_string());
724                }
725            }
726            self.confidence.retain(|language_key, meta| {
727                if active_languages.contains(language_key) {
728                    true
729                } else {
730                    // Preserve entries that encode deliberate
731                    // plugin-recorded limitations even when no live
732                    // files remain — those are analysis-state facts
733                    // the daemon must not silently drop.
734                    !meta.limitations.is_empty() || !meta.unavailable_features.is_empty()
735                }
736            });
737        }
738
739        // ----------------------------------------------------------------
740        // Step 11 — Epoch bump.
741        //
742        // `prior_epoch` captured at `clone_for_rebuild` time; +1 marks
743        // the publication boundary. Wrapping add matches the existing
744        // `CodeGraph::bump_epoch` behavior at
745        // `sqry-core/src/graph/unified/concurrent/graph.rs`.
746        // ----------------------------------------------------------------
747        let new_epoch = self.epoch.wrapping_add(1);
748
749        // ----------------------------------------------------------------
750        // Step 12 — Assemble the immutable `CodeGraph`.
751        //
752        // Every Arc-wrapped field is freshly wrapped from the
753        // rebuild-local owned value, so the new `CodeGraph` has no
754        // Arc-sharing relationship with the pre-rebuild snapshot. This
755        // is the point at which the rebuild-local interner becomes
756        // immutable (step 1's freeze).
757        // ----------------------------------------------------------------
758        let mut graph = CodeGraph::__assemble_from_rebuild_parts_internal(
759            self.nodes,
760            self.edges,
761            self.strings,
762            self.files,
763            self.indices,
764            self.macro_metadata,
765            self.node_provenance,
766            self.edge_provenance,
767            self.fact_epoch,
768            new_epoch,
769            self.confidence,
770            self.scope_arena,
771            self.alias_table,
772            self.shadow_table,
773            self.scope_provenance_store,
774            self.file_segments,
775            self.go_hints,
776        );
777        // Phase A (U09): the assembled `CodeGraph` resets
778        // `c_indirect_tables` to `None`. Re-install the rebuild's owned
779        // value so an in-flight rebuild preserves side tables already
780        // committed on the source graph.
781        graph.set_c_indirect_tables(self.c_indirect_tables);
782
783        // ----------------------------------------------------------------
784        // Steps 13 + 14 — (debug) Publish-boundary invariants.
785        //
786        // Per plan §F.3 "single source of truth", both the §F.1 bucket
787        // bijection and the §F.2 tombstone-residue checks fire through
788        // the canonical `publish::assert_publish_invariants` helper.
789        // That helper is also called at the full-rebuild end
790        // (`build_unified_graph_inner`), by Task 6's
791        // `WorkspaceManager::publish_graph`, and by every §E harness
792        // iteration — so any invariant drift surfaces in all four
793        // places simultaneously, not in a subset.
794        //
795        // The §F.2 assertion is the **single site** against
796        // `self.drained_tombstones` (populated at step 8); we do not
797        // run the residue check anywhere else.
798        // ----------------------------------------------------------------
799        #[cfg(any(debug_assertions, test))]
800        crate::graph::unified::publish::assert_publish_invariants(&graph, &self.drained_tombstones);
801
802        Ok(graph)
803    }
804
805    /// Returns the number of `NodeIds` currently staged for tombstoning
806    /// via [`RebuildGraph::tombstone`] (to be added by Task 4 Step 4).
807    /// Useful for Gate 0c tests that exercise finalize with an empty
808    /// or non-empty tombstone set.
809    #[must_use]
810    pub fn pending_tombstone_count(&self) -> usize {
811        self.tombstones.len()
812    }
813
814    /// Shared-reference accessor for the rebuild-local
815    /// [`NodeArena`]. Read-only; the writer is the rebuild dispatcher
816    /// which holds `&mut self`.
817    ///
818    /// Used by sqry-daemon's `WorkspaceManager` (Task 6) and by the
819    /// Task 4 Step 4 scale test to inspect arena state between
820    /// [`remove_file`](Self::remove_file) calls without going through
821    /// the pub(crate) field directly.
822    #[must_use]
823    pub fn nodes(&self) -> &NodeArena {
824        &self.nodes
825    }
826
827    /// Shared-reference accessor for the rebuild-local
828    /// [`FileRegistry`]. Read-only. The rebuild dispatcher writes via
829    /// `&mut self` on [`remove_file`](Self::remove_file) and
830    /// finalization.
831    #[must_use]
832    pub fn files(&self) -> &FileRegistry {
833        &self.files
834    }
835
836    /// Shared-reference accessor for the rebuild-local
837    /// [`FileSegmentTable`]. Read-only.
838    ///
839    /// `FileSegmentTable` is a plain `Vec<Option<FileSegment>>` with no
840    /// interior mutability (see
841    /// `sqry-core/src/graph/unified/storage/segment.rs`), so this
842    /// accessor is genuinely read-only. Writers ride through the
843    /// `&mut self` mutation path inside
844    /// [`remove_file`](Self::remove_file) and
845    /// [`finalize`](Self::finalize).
846    ///
847    /// Added as part of the iter-1 Codex review fix for Task 4
848    /// Steps 2-3: the `remove_file` integration tests need to assert
849    /// that a file's segment entry is cleared after removal, closing
850    /// the FileId-recycle stale-range bug documented at
851    /// `sqry-core/tests/incremental_remove_file_scale.rs`.
852    #[must_use]
853    pub fn file_segments(&self) -> &FileSegmentTable {
854        &self.file_segments
855    }
856
857    // Note (iter-1 review fix): a `pub fn edges(&self) -> &BidirectionalEdgeStore`
858    // accessor was removed. `BidirectionalEdgeStore` exposes
859    // `forward_mut(&self)` and `reverse_mut(&self)` (interior mutability),
860    // so returning `&BidirectionalEdgeStore` from `&self` would let
861    // external callers escalate a "read-only" handle into a writer. The
862    // rebuild contract requires that edge mutation only happens inside
863    // `RebuildGraph::remove_file` / `finalize` on `&mut self`. If a
864    // read-only edge-view accessor is ever needed by a legitimate
865    // consumer, add a wrapper struct (e.g., `BidirectionalEdgeStoreView`)
866    // that exposes only `forward()` / `reverse()` / `edges_from` /
867    // `edges_to` / `stats` on `&self` — never the `*_mut` methods.
868
869    /// Stage a `NodeId` for tombstoning during the next `finalize` pass.
870    ///
871    /// Gate 0c ships this helper so finalize tests can drive the
872    /// 14-step contract with a realistic tombstone set without waiting
873    /// for Task 4 Step 4's `remove_file` plumbing. Production callers
874    /// will route through `RebuildGraph::remove_file` (Task 4 Step 4),
875    /// which internally populates the same set via
876    /// `FileRegistry::take_nodes`.
877    pub fn tombstone(&mut self, id: NodeId) {
878        self.tombstones.insert(id);
879    }
880
881    /// Stage every `NodeId` in `ids` for tombstoning during the next
882    /// `finalize` pass. Equivalent to calling [`tombstone`](Self::tombstone)
883    /// for each id, but expresses the bulk intent at the call site.
884    ///
885    /// Used by [`remove_file`](Self::remove_file) to fold every
886    /// file-local `NodeId` into the staged set in a single pass.
887    pub(crate) fn tombstone_many<I: IntoIterator<Item = NodeId>>(&mut self, ids: I) {
888        self.tombstones.extend(ids);
889    }
890
891    /// Drain every `NodeId` belonging to `file_id`, invalidate every
892    /// rebuild-local edge whose source or target is one of those nodes
893    /// (across both forward and reverse CSR + delta tiers of the
894    /// rebuild-local edge store), drop the file's entry from the
895    /// rebuild-local [`FileRegistry`], and return the list of
896    /// tombstoned [`NodeId`]s.
897    ///
898    /// This is the rebuild-side mirror of
899    /// [`super::super::concurrent::CodeGraph::remove_file`]. Whereas
900    /// the `CodeGraph` variant mutates a live publishable graph in
901    /// place (O(1) publish once the caller wraps it in an `Arc`), this
902    /// variant operates on the owned, pre-finalize
903    /// [`RebuildGraph`] state — so the edge-store tombstones land in
904    /// the CSR's tombstone bitmap and the delta buffer, and are later
905    /// physically purged by [`finalize`](Self::finalize) step 9 when
906    /// the CSR is rebuilt from the compacted delta (§H lines 684–691).
907    ///
908    /// The method does **not** rewrite `NodeIdBearing` surfaces on the
909    /// rebuild (`NodeArena`, `AuxiliaryIndices`, `NodeMetadataStore`,
910    /// `NodeProvenanceStore`, `ScopeArena`, `AliasTable`, `ShadowTable`) —
911    /// those surfaces are compacted once, uniformly, by `finalize()`
912    /// steps 2–7 against the accumulated `tombstones` set. Running a
913    /// partial compaction here would duplicate work and violate the
914    /// plan's "compact once at step N" contract.
915    ///
916    /// Instead, the tombstoned `NodeId`s are accumulated in
917    /// `self.tombstones` via [`tombstone_many`](Self::tombstone_many).
918    /// Successive `remove_file` calls against different files
919    /// accumulate into the same set; `finalize()` then sweeps every
920    /// K.A/K.B surface once with the union predicate.
921    ///
922    /// # What is tombstoned immediately
923    ///
924    /// Only two surfaces are mutated before `finalize()` runs:
925    ///
926    /// * **`NodeArena`**: each file-local `NodeId` is `remove`d so the
927    ///   slot's generation advances and stale handles cannot alias a
928    ///   re-allocation. Downstream compaction at step 2 is then a
929    ///   no-op for these slots (idempotent; the arena skips stale
930    ///   generations).
931    /// * **Edge store** (both forward + reverse, both CSR + delta):
932    ///   [`BidirectionalEdgeStore::tombstone_edges_for_nodes`] kills
933    ///   every edge whose source or target is one of the drained
934    ///   `NodeIds`. CSR tombstones land in `csr_tombstones`; delta
935    ///   edges are dropped outright. Step 9 of `finalize` then
936    ///   rebuilds a fresh CSR from the tombstone-free delta, so the
937    ///   CSR tombstones become physically invisible by publish time.
938    /// * **`FileRegistry`**: the bucket is drained via
939    ///   [`FileRegistry::take_nodes`] and the file entry is
940    ///   deregistered via [`FileRegistry::unregister`]. Both are
941    ///   idempotent on an already-removed file.
942    ///
943    /// # Returned value
944    ///
945    /// The list of `NodeIds` that were staged for tombstoning. Empty on
946    /// an unknown or already-removed file. Useful for Gate 0c finalize
947    /// tests that need to assert on bucket-drain correctness or on the
948    /// union of staged tombstones across several `remove_file` calls.
949    ///
950    /// # Idempotency
951    ///
952    /// Calling twice with the same `file_id` is a no-op on the second
953    /// call. The bucket is already drained, `take_nodes` returns an
954    /// empty `Vec`, the rest of the method short-circuits, and the
955    /// `tombstones` set is unchanged.
956    #[allow(dead_code)] // Intra-crate consumer is Task 4 Step 4
957    // (`incremental_rebuild`); external consumer is sqry-daemon's
958    // Task 6 `WorkspaceManager` via the feature-gated `pub use` of
959    // `RebuildGraph`. The visibility is `pub` (not `pub(crate)`) so
960    // the daemon can drive file removals through the rebuild plane,
961    // which is the canonical path for file-deletion events per §F.2.
962    pub fn remove_file(&mut self, file_id: super::super::file::FileId) -> Vec<NodeId> {
963        // Drain the rebuild-local FileRegistry bucket.
964        let tombstoned: Vec<NodeId> = self.files.take_nodes(file_id);
965        // Deregister the file entry unconditionally (idempotent).
966        self.files.unregister(file_id);
967        // Clear the rebuild-local `FileSegmentTable` entry for this
968        // file (idempotent — `remove` no-ops on unknown ids). This
969        // matches `CodeGraph::remove_file`'s behaviour: finalize()
970        // publishes `self.file_segments` verbatim at step 12, so any
971        // stale entry leaked here would survive into the assembled
972        // `CodeGraph`. Because `FileRegistry::unregister` recycles
973        // `FileId` slots, a leaked segment would later alias a
974        // different file's node range after the slot is reissued —
975        // which would cause `reindex_files` to tombstone the wrong
976        // range. Clearing the segment at remove time is the only
977        // defence that closes both the "finalize publishes stale
978        // segment" path AND the "FileId recycle attaches stale
979        // range" path.
980        self.file_segments.remove(file_id);
981
982        if tombstoned.is_empty() {
983            return tombstoned;
984        }
985
986        let dead: std::collections::HashSet<NodeId> = tombstoned.iter().copied().collect();
987
988        // 1. Tombstone each arena slot. `NodeArena::remove` is
989        //    idempotent against stale generations, so retriggering a
990        //    file removal after finalize is safe.
991        for &nid in &tombstoned {
992            let _ = self.nodes.remove(nid);
993        }
994
995        // 2. Invalidate edges across both CSR + delta in both
996        //    directions on the rebuild-local edge store.
997        self.edges.tombstone_edges_for_nodes(&dead);
998
999        // 3. Stage the drained NodeIds for the finalize-time K.A/K.B
1000        //    compaction sweep. finalize() will consume these at steps
1001        //    2–7 through the NodeIdBearing::retain_nodes predicate.
1002        self.tombstone_many(tombstoned.iter().copied());
1003
1004        tombstoned
1005    }
1006
1007    /// Returns the rebuild-local epoch captured at `clone_for_rebuild`.
1008    #[must_use]
1009    pub fn prior_epoch(&self) -> u64 {
1010        self.epoch
1011    }
1012
1013    /// Pre-finalize tombstone-residue check on the rebuild-state
1014    /// structures themselves (plan §F.2 literal named API).
1015    ///
1016    /// Iterates every `NodeIdBearing` field on this `RebuildGraph` and
1017    /// panics if any contains a `NodeId` present in `self.tombstones`.
1018    /// This is a diagnostic helper for mid-rebuild consistency checks:
1019    /// e.g., Task 4 Step 4's `RebuildGraph::remove_file` can call this
1020    /// after tombstoning a file but before more closure files land, to
1021    /// prove the just-tombstoned `NodeIds` really left every index before
1022    /// the next pass commits. The `RebuildGraph::finalize` flow then
1023    /// re-asserts against the drained set on the *assembled* `CodeGraph`
1024    /// at step 14 — those are two different snapshots of the same
1025    /// invariant; both must hold.
1026    ///
1027    /// No-op when `self.tombstones` is empty or in release builds.
1028    ///
1029    /// Does **not** replace the step-14 call site; the single source of
1030    /// truth for the publish-boundary residue check remains
1031    /// `crate::graph::unified::publish::assert_publish_invariants`. This
1032    /// helper exists so pre-finalize call sites (Task 4 Step 4's
1033    /// post-remove sanity check, incremental-engine debug probes, Gate
1034    /// 0d negative tests) can name the assertion without rolling their
1035    /// own iteration.
1036    ///
1037    /// # Panics
1038    ///
1039    /// Panics in debug/test builds when any node-bearing rebuild surface
1040    /// still references a node recorded in `self.tombstones`. That indicates
1041    /// the rebuild plane removed a file without fully compacting every
1042    /// dependent arena, edge, and auxiliary index before the next pass.
1043    #[cfg(any(debug_assertions, test))]
1044    pub fn assert_no_tombstone_residue(&self) {
1045        use super::coverage::NodeIdBearing;
1046        let dead = &self.tombstones;
1047        if dead.is_empty() {
1048            return;
1049        }
1050        for nid in self.nodes.all_node_ids() {
1051            assert!(
1052                !dead.contains(&nid),
1053                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in NodeArena"
1054            );
1055        }
1056        for nid in self.edges.all_node_ids() {
1057            assert!(
1058                !dead.contains(&nid),
1059                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in edge store"
1060            );
1061        }
1062        for nid in self.indices.all_node_ids() {
1063            assert!(
1064                !dead.contains(&nid),
1065                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in auxiliary indices"
1066            );
1067        }
1068        for nid in self.macro_metadata.all_node_ids() {
1069            assert!(
1070                !dead.contains(&nid),
1071                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in macro metadata"
1072            );
1073        }
1074        for nid in self.node_provenance.all_node_ids() {
1075            assert!(
1076                !dead.contains(&nid),
1077                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in node provenance"
1078            );
1079        }
1080        for nid in self.scope_arena.all_node_ids() {
1081            assert!(
1082                !dead.contains(&nid),
1083                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in scope arena"
1084            );
1085        }
1086        for nid in self.alias_table.all_node_ids() {
1087            assert!(
1088                !dead.contains(&nid),
1089                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in alias table"
1090            );
1091        }
1092        for nid in self.shadow_table.all_node_ids() {
1093            assert!(
1094                !dead.contains(&nid),
1095                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in shadow table"
1096            );
1097        }
1098        for nid in self.files.all_node_ids() {
1099            assert!(
1100                !dead.contains(&nid),
1101                "RebuildGraph::assert_no_tombstone_residue: tombstone {nid:?} still in per-file bucket"
1102            );
1103        }
1104    }
1105}
1106
1107// =====================================================================
1108// Step 1 helper: rewrite every live `NodeEntry`'s interned-string
1109// fields through the dedup-remap table produced by
1110// `StringInterner::build_dedup_table()`.
1111// =====================================================================
1112
1113/// Rewrite every `NodeEntry` field that holds a [`crate::graph::unified::string::id::StringId`]
1114/// through `remap` so no live node points at a collapsed-duplicate
1115/// slot. Called from finalize step 1 after the interner has been
1116/// canonicalised; a no-op when `remap` is empty (the common case of a
1117/// no-op rebuild).
1118///
1119/// Fields rewritten: `name`, `signature`, `doc`, `qualified_name`,
1120/// `visibility`. These are every `StringId` / `Option<StringId>` field
1121/// that `NodeEntry` currently declares. Adding a new `StringId`-valued
1122/// field to `NodeEntry` requires extending this helper — the closest
1123/// enforcement is the compile-fail coverage in the `sqry_graph_fields!`
1124/// macro which forces a new `RebuildGraph` field and a matching
1125/// finalize step for any new `CodeGraph` field; individual arena
1126/// fields are caught at review time against this helper.
1127fn rewrite_node_entries_through_remap(
1128    nodes: &mut NodeArena,
1129    remap: &HashMap<
1130        crate::graph::unified::string::id::StringId,
1131        crate::graph::unified::string::id::StringId,
1132    >,
1133) {
1134    if remap.is_empty() {
1135        return;
1136    }
1137    for (_id, entry) in nodes.iter_mut() {
1138        if let Some(&canon) = remap.get(&entry.name) {
1139            entry.name = canon;
1140        }
1141        if let Some(sid) = entry.signature
1142            && let Some(&canon) = remap.get(&sid)
1143        {
1144            entry.signature = Some(canon);
1145        }
1146        if let Some(sid) = entry.doc
1147            && let Some(&canon) = remap.get(&sid)
1148        {
1149            entry.doc = Some(canon);
1150        }
1151        if let Some(sid) = entry.qualified_name
1152            && let Some(&canon) = remap.get(&sid)
1153        {
1154            entry.qualified_name = Some(canon);
1155        }
1156        if let Some(sid) = entry.visibility
1157            && let Some(&canon) = remap.get(&sid)
1158        {
1159            entry.visibility = Some(canon);
1160        }
1161    }
1162}
1163
1164// =====================================================================
1165// Assembly path notes (A2 §H "Type-enforced publish path")
1166// =====================================================================
1167//
1168// The only route from `RebuildGraph` to `Arc<CodeGraph>` is:
1169//
1170//     let code_graph = rebuild.finalize()?;            // Step 12 assembles CodeGraph
1171//     let arc = Arc::new(code_graph);                  // caller wraps (publish site)
1172//
1173// The assembly inside `finalize` uses
1174// `CodeGraph::__assemble_from_rebuild_parts_internal`, which is
1175// `pub(crate)` on `CodeGraph`. That means downstream crates — even
1176// `sqry-daemon` with `rebuild-internals` enabled — cannot call the
1177// assembler directly; they must route through `finalize()`, which
1178// guarantees the 14-step compaction sequence runs first.
1179//
1180// The trybuild fixture
1181// `sqry-core/tests/rebuild_internals_compile_fail/rebuild_graph_no_public_assembly.rs`
1182// exercises this: a downstream crate attempting to call
1183// `__assemble_from_rebuild_parts_internal` fails with E0603 ("function
1184// is private"), and attempting to `impl From<RebuildGraph> for CodeGraph`
1185// from outside this module fails with E0117 (orphan-rule violation).
1186
1187// =====================================================================
1188// Tests
1189// =====================================================================
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194    use crate::graph::unified::file::FileId;
1195    use crate::graph::unified::node::NodeKind;
1196    use crate::graph::unified::storage::arena::NodeEntry;
1197    use crate::graph::unified::storage::metadata::MacroNodeMetadata;
1198
1199    /// Seed a `CodeGraph` with a handful of live nodes distributed over
1200    /// two files so the per-field compaction steps have something
1201    /// non-trivial to operate on.
1202    fn seeded_graph() -> (CodeGraph, NodeId, NodeId, NodeId) {
1203        let mut graph = CodeGraph::new();
1204        let file_a = FileId::new(1);
1205        let file_b = FileId::new(2);
1206        let sym = graph.strings_mut().intern("symbol_a").expect("intern a");
1207        let node_a;
1208        let node_b;
1209        let node_c;
1210        {
1211            let arena = graph.nodes_mut();
1212            node_a = arena
1213                .alloc(NodeEntry::new(NodeKind::Function, sym, file_a))
1214                .expect("alloc a");
1215            node_b = arena
1216                .alloc(NodeEntry::new(NodeKind::Method, sym, file_a))
1217                .expect("alloc b");
1218            node_c = arena
1219                .alloc(NodeEntry::new(NodeKind::Struct, sym, file_b))
1220                .expect("alloc c");
1221        }
1222        graph
1223            .indices_mut()
1224            .add(node_a, NodeKind::Function, sym, Some(sym), file_a);
1225        graph
1226            .indices_mut()
1227            .add(node_b, NodeKind::Method, sym, Some(sym), file_a);
1228        graph
1229            .indices_mut()
1230            .add(node_c, NodeKind::Struct, sym, Some(sym), file_b);
1231        graph
1232            .macro_metadata_mut()
1233            .insert(node_a, MacroNodeMetadata::default());
1234        (graph, node_a, node_b, node_c)
1235    }
1236
1237    #[test]
1238    fn clone_for_rebuild_copies_every_field_without_arc_sharing() {
1239        let (graph, _a, _b, _c) = seeded_graph();
1240        let rebuild = graph.clone_for_rebuild();
1241
1242        // Field-level counts match the source graph.
1243        assert_eq!(rebuild.nodes.len(), graph.nodes().len());
1244        assert_eq!(rebuild.macro_metadata.len(), graph.macro_metadata().len());
1245        // The rebuild owns its own arena (not an Arc share), so
1246        // mutating it in place would not affect the source graph. We
1247        // verify this by tombstoning a node in the rebuild and
1248        // confirming the source is unchanged.
1249        let mut rebuild = rebuild;
1250        let ids: Vec<NodeId> = rebuild.nodes.all_node_ids().collect();
1251        let victim = *ids.first().expect("at least one node");
1252        rebuild.tombstone(victim);
1253        assert_eq!(rebuild.pending_tombstone_count(), 1);
1254        // Source graph unaffected.
1255        assert_eq!(graph.nodes().len(), ids.len());
1256    }
1257
1258    #[test]
1259    fn clone_for_rebuild_preserves_epoch_and_fact_epoch() {
1260        let (mut graph, _, _, _) = seeded_graph();
1261        graph.set_epoch(7);
1262        let rebuild = graph.clone_for_rebuild();
1263        assert_eq!(rebuild.prior_epoch(), 7);
1264        assert_eq!(rebuild.fact_epoch, graph.fact_epoch());
1265    }
1266
1267    // ---- Step-level finalize tests ---------------------------------
1268
1269    #[test]
1270    fn finalize_step11_bumps_epoch_by_one() {
1271        let (mut graph, _, _, _) = seeded_graph();
1272        graph.set_epoch(41);
1273        let rebuild = graph.clone_for_rebuild();
1274        let finalized = rebuild.finalize().expect("finalize ok");
1275        assert_eq!(finalized.epoch(), 42);
1276    }
1277
1278    #[test]
1279    fn finalize_step8_drains_tombstones_into_drained_set() {
1280        // We use a reach-into-guts test: finalize consumes self, so we
1281        // verify the drain via a direct RebuildGraph constructed inside
1282        // this module (which has crate visibility into the field).
1283        let (graph, a, _b, _c) = seeded_graph();
1284        let mut rebuild = graph.clone_for_rebuild();
1285        rebuild.tombstone(a);
1286        assert_eq!(rebuild.pending_tombstone_count(), 1);
1287        // After finalize, the graph must not contain `a`.
1288        let finalized = rebuild.finalize().expect("finalize ok");
1289        assert!(
1290            finalized.nodes().get(a).is_none(),
1291            "tombstoned node must be gone from arena"
1292        );
1293    }
1294
1295    #[test]
1296    fn finalize_steps_2_and_4_compact_arena_and_indices_consistently() {
1297        let (graph, a, _b, c) = seeded_graph();
1298        let mut rebuild = graph.clone_for_rebuild();
1299        rebuild.tombstone(a);
1300        rebuild.tombstone(c);
1301        let finalized = rebuild.finalize().expect("finalize ok");
1302
1303        // Arena compaction (step 2): dropped nodes are gone.
1304        assert!(finalized.nodes().get(a).is_none());
1305        assert!(finalized.nodes().get(c).is_none());
1306        // Step 4 must compact the auxiliary indices in lockstep, so
1307        // the tombstoned ids do not linger in any index.
1308        use crate::graph::unified::storage::metadata::TypedMetadata;
1309        let _ = TypedMetadata::Macro(MacroNodeMetadata::default()); // silence unused import warning on some cfgs
1310        assert!(!finalized.indices().by_kind(NodeKind::Function).contains(&a));
1311        assert!(!finalized.indices().by_kind(NodeKind::Struct).contains(&c));
1312    }
1313
1314    #[test]
1315    fn finalize_step5_compacts_macro_metadata() {
1316        let (graph, a, _b, _c) = seeded_graph();
1317        let mut rebuild = graph.clone_for_rebuild();
1318        rebuild.tombstone(a);
1319        let finalized = rebuild.finalize().expect("finalize ok");
1320        // `a` had macro metadata seeded; after finalize it must be gone.
1321        assert!(finalized.macro_metadata().get_macro(a).is_none());
1322    }
1323
1324    #[test]
1325    fn finalize_step9_installs_rebuilt_csr() {
1326        // Step 9 (plan §H lines 684–691) must install a freshly built
1327        // CSR — not merely drop the stale cache. The assembled graph's
1328        // forward and reverse edge stores must both expose a `csr()`
1329        // after finalize, and the deltas must be empty (absorbed by
1330        // the swap).
1331        let (graph, _, _, _) = seeded_graph();
1332        let rebuild = graph.clone_for_rebuild();
1333        let finalized = rebuild.finalize().expect("finalize ok");
1334        assert!(
1335            finalized.edges().forward().csr().is_some(),
1336            "step 9 must install forward CSR"
1337        );
1338        assert!(
1339            finalized.edges().reverse().csr().is_some(),
1340            "step 9 must install reverse CSR"
1341        );
1342        // Deltas were absorbed by the swap.
1343        assert_eq!(finalized.edges().forward().delta_count(), 0);
1344        assert_eq!(finalized.edges().reverse().delta_count(), 0);
1345    }
1346
1347    #[test]
1348    fn finalize_step10_drops_confidence_for_removed_languages() {
1349        // Seed a graph with Rust + Python confidence; the rebuild-local
1350        // FileRegistry has zero files tagged (seeded_graph does not
1351        // register paths), so step 10 must drop both.
1352        let (mut graph, _, _, _) = seeded_graph();
1353        graph.merge_confidence(
1354            "rust",
1355            crate::confidence::ConfidenceMetadata {
1356                level: crate::confidence::ConfidenceLevel::Verified,
1357                ..Default::default()
1358            },
1359        );
1360        graph.merge_confidence(
1361            "python",
1362            crate::confidence::ConfidenceMetadata {
1363                level: crate::confidence::ConfidenceLevel::Partial,
1364                ..Default::default()
1365            },
1366        );
1367        assert_eq!(graph.confidence().len(), 2);
1368
1369        let rebuild = graph.clone_for_rebuild();
1370        let finalized = rebuild.finalize().expect("finalize ok");
1371        assert!(
1372            finalized.confidence().is_empty(),
1373            "step 10 must drop confidence entries for languages that \
1374             have no live files and no recorded limitations"
1375        );
1376    }
1377
1378    #[test]
1379    fn finalize_step10_preserves_confidence_with_limitations() {
1380        // A confidence entry that encodes deliberate limitations must
1381        // survive a zero-file rebuild: dropping it would silently lose
1382        // plugin-recorded analysis state.
1383        let (mut graph, _, _, _) = seeded_graph();
1384        graph.merge_confidence(
1385            "rust",
1386            crate::confidence::ConfidenceMetadata {
1387                level: crate::confidence::ConfidenceLevel::AstOnly,
1388                limitations: vec!["no rust-analyzer".to_string()],
1389                unavailable_features: vec!["type inference".to_string()],
1390            },
1391        );
1392        let rebuild = graph.clone_for_rebuild();
1393        let finalized = rebuild.finalize().expect("finalize ok");
1394        assert_eq!(finalized.confidence().len(), 1);
1395        assert!(finalized.confidence().contains_key("rust"));
1396    }
1397
1398    #[test]
1399    fn finalize_step1_canonicalises_interner_via_dedup() {
1400        // Freeze step must leave the interner's lookup consistent
1401        // (non-stale) and zero duplicate slots after finalize.
1402        let (graph, _, _, _) = seeded_graph();
1403        let rebuild = graph.clone_for_rebuild();
1404        let finalized = rebuild.finalize().expect("finalize ok");
1405        assert!(
1406            !finalized.strings().is_lookup_stale(),
1407            "step 1 freeze must leave lookup_stale == false"
1408        );
1409    }
1410
1411    #[test]
1412    fn finalize_is_infallible_on_empty_tombstone_set() {
1413        let (graph, _, _, _) = seeded_graph();
1414        let rebuild = graph.clone_for_rebuild();
1415        let result = rebuild.finalize();
1416        assert!(result.is_ok(), "empty-tombstone finalize must succeed");
1417        let finalized = result.unwrap();
1418        // Every node survives.
1419        assert_eq!(finalized.nodes().len(), 3);
1420    }
1421
1422    #[test]
1423    fn finalize_survives_interner_snapshot_unchanged_when_no_edits() {
1424        let (graph, _, _, _) = seeded_graph();
1425        let prior_string_count = graph.strings().len();
1426        let rebuild = graph.clone_for_rebuild();
1427        let finalized = rebuild.finalize().expect("finalize ok");
1428        assert_eq!(
1429            finalized.strings().len(),
1430            prior_string_count,
1431            "freeze step must preserve string count across a no-op rebuild"
1432        );
1433    }
1434
1435    #[test]
1436    fn rebuild_graph_pending_tombstone_count_is_accurate() {
1437        let (graph, a, b, c) = seeded_graph();
1438        let mut rebuild = graph.clone_for_rebuild();
1439        assert_eq!(rebuild.pending_tombstone_count(), 0);
1440        rebuild.tombstone(a);
1441        rebuild.tombstone(b);
1442        rebuild.tombstone(c);
1443        // Inserting the same id again is idempotent.
1444        rebuild.tombstone(a);
1445        assert_eq!(rebuild.pending_tombstone_count(), 3);
1446    }
1447
1448    // ----------------------------------------------------------------
1449    // Iter-2 B1: StringId remap across every StringId-backed holder.
1450    // ----------------------------------------------------------------
1451
1452    /// Construct a RebuildGraph whose interner has intentional duplicate
1453    /// `StringId` slots (two slots containing the same canonical
1454    /// "symbol_dup" bytes), with the **live** state referencing both
1455    /// slots. `build_dedup_table()` must collapse them, step 1 must
1456    /// rewrite every StringId-backed surface through the remap, and
1457    /// step 4 must leave no bucket pointing at a recycled StringId.
1458    #[test]
1459    fn step1_remaps_auxiliary_indices_keys_through_dedup_table() {
1460        use crate::graph::unified::storage::interner::StringInterner;
1461
1462        let mut graph = CodeGraph::new();
1463        // Intern "alpha" twice via the bulk path so the two slots are
1464        // NOT coalesced at intern time. We emulate that by manually
1465        // using `alloc_range` + direct bulk_slices_mut assignment on
1466        // the interner.
1467        let interner: &mut StringInterner = graph.strings_mut();
1468        let start = interner.alloc_range(2).expect("alloc range");
1469        {
1470            let (s_slots, rc_slots) = interner.bulk_slices_mut(start, 2);
1471            s_slots[0] = Some(std::sync::Arc::from("alpha"));
1472            s_slots[1] = Some(std::sync::Arc::from("alpha"));
1473            rc_slots[0] = 1;
1474            rc_slots[1] = 1;
1475        }
1476        let id_dup = crate::graph::unified::string::id::StringId::new(start + 1);
1477        let id_canon = crate::graph::unified::string::id::StringId::new(start);
1478        let file = FileId::new(1);
1479
1480        // Allocate one node that references the duplicate StringId so
1481        // after dedup the arena still points at a canonical id.
1482        let mut entry = NodeEntry::new(NodeKind::Function, id_dup, file);
1483        entry.qualified_name = Some(id_dup);
1484        let node = graph.nodes_mut().alloc(entry).expect("alloc");
1485        graph
1486            .indices_mut()
1487            .add(node, NodeKind::Function, id_dup, Some(id_dup), file);
1488
1489        let rebuild = graph.clone_for_rebuild();
1490        let finalized = rebuild.finalize().expect("finalize ok");
1491
1492        // After step 1 the duplicate slot must be recycled and every
1493        // live surface must reference the canonical slot.
1494        // (a) Arena field references canonical
1495        let entry = finalized.nodes().get(node).expect("node survives");
1496        assert_eq!(entry.name, id_canon, "NodeEntry.name must be canonicalised");
1497        assert_eq!(
1498            entry.qualified_name,
1499            Some(id_canon),
1500            "NodeEntry.qualified_name must be canonicalised"
1501        );
1502        // (b) AuxiliaryIndices: by_name must find the node under canonical id.
1503        assert!(
1504            finalized.indices().by_name(id_canon).contains(&node),
1505            "indices.by_name under canonical StringId must contain the node"
1506        );
1507        // (c) And must NOT have any bucket under the duplicate StringId.
1508        assert!(
1509            finalized.indices().by_name(id_dup).is_empty(),
1510            "duplicate StringId bucket must be empty after remap"
1511        );
1512        assert!(
1513            finalized.indices().by_qualified_name(id_dup).is_empty(),
1514            "duplicate StringId qname bucket must be empty after remap"
1515        );
1516        // (d) Interner has no stale lookup.
1517        assert!(!finalized.strings().is_lookup_stale());
1518    }
1519
1520    #[test]
1521    fn step1_merges_aux_indices_buckets_when_keys_collapse() {
1522        use crate::graph::unified::storage::interner::StringInterner;
1523
1524        let mut graph = CodeGraph::new();
1525        let interner: &mut StringInterner = graph.strings_mut();
1526        let start = interner.alloc_range(2).expect("alloc range");
1527        {
1528            let (s_slots, rc_slots) = interner.bulk_slices_mut(start, 2);
1529            s_slots[0] = Some(std::sync::Arc::from("beta"));
1530            s_slots[1] = Some(std::sync::Arc::from("beta"));
1531            rc_slots[0] = 1;
1532            rc_slots[1] = 1;
1533        }
1534        let id_canon = crate::graph::unified::string::id::StringId::new(start);
1535        let id_dup = crate::graph::unified::string::id::StringId::new(start + 1);
1536        let file = FileId::new(1);
1537
1538        // Two nodes: one references canonical, one references duplicate.
1539        // After remap, both must land in the canonical bucket of
1540        // `name_index` (merged, deduplicated by NodeId).
1541        let node_canon = graph
1542            .nodes_mut()
1543            .alloc(NodeEntry::new(NodeKind::Function, id_canon, file))
1544            .expect("alloc canon");
1545        let node_dup = graph
1546            .nodes_mut()
1547            .alloc(NodeEntry::new(NodeKind::Function, id_dup, file))
1548            .expect("alloc dup");
1549        graph
1550            .indices_mut()
1551            .add(node_canon, NodeKind::Function, id_canon, None, file);
1552        graph
1553            .indices_mut()
1554            .add(node_dup, NodeKind::Function, id_dup, None, file);
1555
1556        let rebuild = graph.clone_for_rebuild();
1557        let finalized = rebuild.finalize().expect("finalize ok");
1558
1559        let canonical_bucket = finalized.indices().by_name(id_canon);
1560        assert!(canonical_bucket.contains(&node_canon));
1561        assert!(canonical_bucket.contains(&node_dup));
1562        // No duplicates within the merged bucket.
1563        let mut seen = std::collections::HashSet::new();
1564        for id in canonical_bucket {
1565            assert!(seen.insert(*id), "bucket must be dedup'd by NodeId");
1566        }
1567        assert!(
1568            finalized.indices().by_name(id_dup).is_empty(),
1569            "collapsed duplicate key bucket must be removed"
1570        );
1571    }
1572
1573    #[test]
1574    fn step1_remaps_file_registry_source_uri() {
1575        use crate::graph::unified::storage::interner::StringInterner;
1576
1577        let mut graph = CodeGraph::new();
1578        // Force two identical "file:///foo" StringId slots.
1579        let interner: &mut StringInterner = graph.strings_mut();
1580        let start = interner.alloc_range(2).expect("alloc range");
1581        {
1582            let (s, rc) = interner.bulk_slices_mut(start, 2);
1583            s[0] = Some(std::sync::Arc::from("file:///foo"));
1584            s[1] = Some(std::sync::Arc::from("file:///foo"));
1585            rc[0] = 1;
1586            rc[1] = 1;
1587        }
1588        let id_canon = crate::graph::unified::string::id::StringId::new(start);
1589        let id_dup = crate::graph::unified::string::id::StringId::new(start + 1);
1590
1591        let fid = graph
1592            .files_mut()
1593            .register_external_with_uri(
1594                "/virtual/Foo.class",
1595                Some(crate::graph::node::Language::Java),
1596                Some(id_dup),
1597            )
1598            .expect("register external");
1599
1600        let rebuild = graph.clone_for_rebuild();
1601        let finalized = rebuild.finalize().expect("finalize ok");
1602
1603        let view = finalized
1604            .files()
1605            .file_provenance(fid)
1606            .expect("provenance present");
1607        assert_eq!(
1608            view.source_uri,
1609            Some(id_canon),
1610            "FileRegistry source_uri must be rewritten to canonical StringId"
1611        );
1612    }
1613
1614    // ----------------------------------------------------------------
1615    // Iter-4 B1: edge-store StringId remap across delta + CSR tiers.
1616    // ----------------------------------------------------------------
1617
1618    /// Construct a `RebuildGraph` whose interner has three slots
1619    /// containing the same canonical bytes ("symbol_edge_dup"), with
1620    /// two distinct `EdgeKind::Imports { alias }` edges pointing at
1621    /// different duplicate slots. Step 1 must rewrite both aliases
1622    /// through the dedup table so the post-step-9 CSR references only
1623    /// the canonical slot; the duplicate slots must be recycled by
1624    /// `recycle_unreferenced` (ref_count == 0) and the canonical slot
1625    /// must retain references.
1626    ///
1627    /// This test intentionally exercises both the delta-tier write path
1628    /// (`DeltaBuffer::iter_mut`) *during* step 1 (where the edges still
1629    /// live in the delta buffer because no compaction has been run)
1630    /// and the CSR-tier read path (where the edges land after step 9's
1631    /// `swap_csrs_and_clear_deltas`). The companion test
1632    /// `step1_remaps_edge_kind_string_ids_in_csr_tier` covers the
1633    /// symmetric case where edges start in the CSR tier at the time
1634    /// step 1 runs.
1635    #[test]
1636    fn step1_remaps_edge_kind_string_ids_through_dedup_table() {
1637        use crate::graph::unified::edge::EdgeKind;
1638        use crate::graph::unified::storage::interner::StringInterner;
1639
1640        let mut graph = CodeGraph::new();
1641        let file_a = FileId::new(1);
1642        // Force three slots carrying the same canonical bytes so
1643        // `build_dedup_table()` collapses slot[start+1] and slot[start+2]
1644        // onto slot[start].
1645        let interner: &mut StringInterner = graph.strings_mut();
1646        let start = interner.alloc_range(3).expect("alloc range");
1647        {
1648            let (s, rc) = interner.bulk_slices_mut(start, 3);
1649            s[0] = Some(std::sync::Arc::from("symbol_edge_dup"));
1650            s[1] = Some(std::sync::Arc::from("symbol_edge_dup"));
1651            s[2] = Some(std::sync::Arc::from("symbol_edge_dup"));
1652            rc[0] = 1;
1653            rc[1] = 1;
1654            rc[2] = 1;
1655        }
1656        let id_canon = crate::graph::unified::string::id::StringId::new(start);
1657        let id_dup_1 = crate::graph::unified::string::id::StringId::new(start + 1);
1658        let id_dup_2 = crate::graph::unified::string::id::StringId::new(start + 2);
1659
1660        // Allocate two nodes so we can hang two edges off distinct
1661        // (src, tgt) pairs and verify both are remapped.
1662        let src;
1663        let tgt;
1664        {
1665            let arena = graph.nodes_mut();
1666            src = arena
1667                .alloc(NodeEntry::new(NodeKind::Function, id_canon, file_a))
1668                .expect("alloc src");
1669            tgt = arena
1670                .alloc(NodeEntry::new(NodeKind::Function, id_canon, file_a))
1671                .expect("alloc tgt");
1672        }
1673        graph
1674            .indices_mut()
1675            .add(src, NodeKind::Function, id_canon, None, file_a);
1676        graph
1677            .indices_mut()
1678            .add(tgt, NodeKind::Function, id_canon, None, file_a);
1679
1680        // Edge 1: Imports { alias = id_dup_1 } — forward src→tgt.
1681        graph.edges_mut().add_edge(
1682            src,
1683            tgt,
1684            EdgeKind::Imports {
1685                alias: Some(id_dup_1),
1686                is_wildcard: false,
1687            },
1688            file_a,
1689        );
1690        // Edge 2: Imports { alias = id_dup_2 } — forward tgt→src (so the
1691        // two edges are distinct keys in the store).
1692        graph.edges_mut().add_edge(
1693            tgt,
1694            src,
1695            EdgeKind::Imports {
1696                alias: Some(id_dup_2),
1697                is_wildcard: true,
1698            },
1699            file_a,
1700        );
1701
1702        // Pre-finalize sanity: the edges live in the delta tier.
1703        assert!(
1704            graph.edges().forward().delta_count() >= 2,
1705            "pre-finalize: forward delta must hold both Imports edges"
1706        );
1707        assert!(
1708            graph.edges().reverse().delta_count() >= 2,
1709            "pre-finalize: reverse delta must hold the mirror of both Imports edges"
1710        );
1711
1712        let rebuild = graph.clone_for_rebuild();
1713        let finalized = rebuild.finalize().expect("finalize ok");
1714
1715        // After finalize step 9, edges have been absorbed into the CSR
1716        // tier by `swap_csrs_and_clear_deltas`. Step 1's `EdgeKind`
1717        // rewrite ran on the delta *before* step 9 snapshotted it, so
1718        // the CSR we assert on is built from the already-remapped delta.
1719        //
1720        // Forward CSR: every `Imports` alias must be canonical.
1721        let forward = finalized.edges().forward();
1722        let fwd_csr = forward
1723            .csr()
1724            .expect("forward CSR must be populated after step 9");
1725        let mut fwd_imports_seen = 0usize;
1726        for kind in fwd_csr.edge_kind() {
1727            if let EdgeKind::Imports { alias, .. } = kind {
1728                fwd_imports_seen += 1;
1729                assert_ne!(
1730                    *alias,
1731                    Some(id_dup_1),
1732                    "forward CSR Imports alias must not reference pre-dedup slot id_dup_1"
1733                );
1734                assert_ne!(
1735                    *alias,
1736                    Some(id_dup_2),
1737                    "forward CSR Imports alias must not reference pre-dedup slot id_dup_2"
1738                );
1739                assert_eq!(
1740                    *alias,
1741                    Some(id_canon),
1742                    "forward CSR Imports alias must be canonicalised"
1743                );
1744            }
1745        }
1746        drop(forward);
1747        assert!(
1748            fwd_imports_seen >= 2,
1749            "forward CSR must hold both Imports edges after finalize (saw {fwd_imports_seen})"
1750        );
1751
1752        // Reverse CSR: mirror edges must be canonicalised identically.
1753        let reverse = finalized.edges().reverse();
1754        let rev_csr = reverse
1755            .csr()
1756            .expect("reverse CSR must be populated after step 9");
1757        let mut rev_imports_seen = 0usize;
1758        for kind in rev_csr.edge_kind() {
1759            if let EdgeKind::Imports { alias, .. } = kind {
1760                rev_imports_seen += 1;
1761                assert_ne!(*alias, Some(id_dup_1));
1762                assert_ne!(*alias, Some(id_dup_2));
1763                assert_eq!(*alias, Some(id_canon));
1764            }
1765        }
1766        drop(reverse);
1767        assert!(
1768            rev_imports_seen >= 2,
1769            "reverse CSR must mirror the forward Imports edges (saw {rev_imports_seen})"
1770        );
1771
1772        // Step-1 (c) invariant: after `recycle_unreferenced`, the
1773        // duplicate slots must report `ref_count == 0`. If step 1's
1774        // edge-store remap had skipped `EdgeKind` payloads, the
1775        // duplicates' refcounts would stay positive (held by the edge
1776        // store) and recycle would not reclaim them.
1777        assert_eq!(
1778            finalized.strings().ref_count(id_dup_1),
1779            0,
1780            "duplicate slot id_dup_1 must be recycled (ref_count == 0) by step 1"
1781        );
1782        assert_eq!(
1783            finalized.strings().ref_count(id_dup_2),
1784            0,
1785            "duplicate slot id_dup_2 must be recycled (ref_count == 0) by step 1"
1786        );
1787        assert!(
1788            finalized.strings().ref_count(id_canon) > 0,
1789            "canonical slot must retain references from the two Imports edges (got {})",
1790            finalized.strings().ref_count(id_canon)
1791        );
1792    }
1793
1794    /// Same construction as above, but compact the edges into a CSR tier
1795    /// before calling finalize so the rewrite covers the steady-state
1796    /// `CsrGraph::edge_kind` path. This exercises the branch of
1797    /// `BidirectionalEdgeStore::rewrite_edge_kind_string_ids_through_remap`
1798    /// that is otherwise dead in the tests above.
1799    #[test]
1800    fn step1_remaps_edge_kind_string_ids_in_csr_tier() {
1801        use crate::graph::unified::compaction::{Direction, build_compacted_csr, snapshot_edges};
1802        use crate::graph::unified::edge::EdgeKind;
1803        use crate::graph::unified::storage::interner::StringInterner;
1804
1805        let mut graph = CodeGraph::new();
1806        let file_a = FileId::new(1);
1807        let interner: &mut StringInterner = graph.strings_mut();
1808        let start = interner.alloc_range(2).expect("alloc range");
1809        {
1810            let (s, rc) = interner.bulk_slices_mut(start, 2);
1811            s[0] = Some(std::sync::Arc::from("csr_alias_dup"));
1812            s[1] = Some(std::sync::Arc::from("csr_alias_dup"));
1813            rc[0] = 1;
1814            rc[1] = 1;
1815        }
1816        let id_canon = crate::graph::unified::string::id::StringId::new(start);
1817        let id_dup = crate::graph::unified::string::id::StringId::new(start + 1);
1818
1819        let src;
1820        let tgt;
1821        {
1822            let arena = graph.nodes_mut();
1823            src = arena
1824                .alloc(NodeEntry::new(NodeKind::Function, id_canon, file_a))
1825                .expect("alloc src");
1826            tgt = arena
1827                .alloc(NodeEntry::new(NodeKind::Function, id_canon, file_a))
1828                .expect("alloc tgt");
1829        }
1830        graph
1831            .indices_mut()
1832            .add(src, NodeKind::Function, id_canon, None, file_a);
1833        graph
1834            .indices_mut()
1835            .add(tgt, NodeKind::Function, id_canon, None, file_a);
1836
1837        // Push the Imports edge into delta with alias pointing at the
1838        // duplicate StringId slot.
1839        graph.edges_mut().add_edge(
1840            src,
1841            tgt,
1842            EdgeKind::Imports {
1843                alias: Some(id_dup),
1844                is_wildcard: false,
1845            },
1846            file_a,
1847        );
1848
1849        // Compact delta → CSR on both directions. This mirrors what the
1850        // full-build pipeline does after Phase 4d plus an explicit
1851        // compaction step.
1852        let node_count = 2;
1853        let edges = graph.edges_mut();
1854        let fwd_snap = snapshot_edges(&edges.forward(), node_count);
1855        let (forward_csr, _) =
1856            build_compacted_csr(&fwd_snap, Direction::Forward).expect("forward csr");
1857        let rev_snap = snapshot_edges(&edges.reverse(), node_count);
1858        let (reverse_csr, _) =
1859            build_compacted_csr(&rev_snap, Direction::Reverse).expect("reverse csr");
1860        edges.swap_csrs_and_clear_deltas(forward_csr, reverse_csr);
1861        assert!(
1862            edges.forward().csr().is_some(),
1863            "forward CSR must be present"
1864        );
1865        assert!(
1866            edges.reverse().csr().is_some(),
1867            "reverse CSR must be present"
1868        );
1869        assert_eq!(edges.forward().delta_count(), 0, "delta must be empty");
1870        assert_eq!(edges.reverse().delta_count(), 0, "delta must be empty");
1871
1872        let rebuild = graph.clone_for_rebuild();
1873        let finalized = rebuild.finalize().expect("finalize ok");
1874
1875        // CSR tier: every `edge_kind` entry must reference the canonical
1876        // StringId, never the duplicate.
1877        let forward = finalized.edges().forward();
1878        let csr = forward
1879            .csr()
1880            .expect("forward CSR must survive finalize step 1");
1881        let mut imports_seen = 0usize;
1882        for kind in csr.edge_kind() {
1883            if let EdgeKind::Imports { alias, .. } = kind {
1884                imports_seen += 1;
1885                assert_ne!(
1886                    *alias,
1887                    Some(id_dup),
1888                    "CSR Imports alias must not reference pre-dedup duplicate"
1889                );
1890                assert_eq!(
1891                    *alias,
1892                    Some(id_canon),
1893                    "CSR Imports alias must be canonicalised"
1894                );
1895            }
1896        }
1897        assert!(
1898            imports_seen > 0,
1899            "forward CSR must hold at least one Imports edge"
1900        );
1901        drop(forward);
1902
1903        // Reverse CSR — same guarantee.
1904        let reverse = finalized.edges().reverse();
1905        let rev_csr = reverse
1906            .csr()
1907            .expect("reverse CSR must survive finalize step 1");
1908        let mut rev_imports_seen = 0usize;
1909        for kind in rev_csr.edge_kind() {
1910            if let EdgeKind::Imports { alias, .. } = kind {
1911                rev_imports_seen += 1;
1912                assert_ne!(*alias, Some(id_dup));
1913                assert_eq!(*alias, Some(id_canon));
1914            }
1915        }
1916        assert!(rev_imports_seen > 0, "reverse CSR must hold Imports edges");
1917        drop(reverse);
1918
1919        assert_eq!(
1920            finalized.strings().ref_count(id_dup),
1921            0,
1922            "duplicate slot must be recycled (ref_count == 0) by step 1"
1923        );
1924    }
1925
1926    /// Exhaustive coverage: every `StringId`-holding surface *reachable
1927    /// through `CodeGraph`'s public mutation API* must be rewritten by
1928    /// finalize step 1. This test drives each surface with a distinct
1929    /// duplicate `StringId` slot and verifies after finalize that (i)
1930    /// every surface references the canonical slot, never the duplicate;
1931    /// (ii) every duplicate slot is recycled (`ref_count == 0`); (iii)
1932    /// the canonical slot retains a positive ref count.
1933    ///
1934    /// Surfaces exercised:
1935    /// * **Arena** (`NodeEntry.name`, `NodeEntry.qualified_name`)
1936    /// * **AuxiliaryIndices** (`name_index` / `qualified_name_index` keys)
1937    /// * **FileRegistry** (`FileEntry.source_uri`)
1938    /// * **BidirectionalEdgeStore** (`EdgeKind::Imports.alias` — delta tier)
1939    ///
1940    /// `AliasTable` and `ShadowTable` StringId fields live under private
1941    /// API (`pub(crate) fn set_alias_table`, no public entry mutators)
1942    /// and are already covered by the iter-2 `step1_remaps_*` tests above
1943    /// that exercise their `rewrite_string_ids_through_remap` helpers
1944    /// end-to-end through the binding-plane derivation path. Covering
1945    /// them here would require either exposing additional test-only APIs
1946    /// or duplicating the iter-2 coverage; neither adds assurance beyond
1947    /// what the dedicated iter-2 tests already provide.
1948    #[test]
1949    fn step1_remaps_all_stringid_holders_exhaustively() {
1950        use crate::graph::unified::edge::EdgeKind;
1951        use crate::graph::unified::storage::interner::StringInterner;
1952
1953        let mut graph = CodeGraph::new();
1954        let file_a = FileId::new(1);
1955        let interner: &mut StringInterner = graph.strings_mut();
1956        // 10 slots = 5 surfaces × 2 (canon + dup) interleaved.
1957        let start = interner.alloc_range(10).expect("alloc range");
1958        {
1959            let (s, rc) = interner.bulk_slices_mut(start, 10);
1960            for (i, label) in [
1961                "arena_name",
1962                "arena_name",
1963                "arena_qname",
1964                "arena_qname",
1965                "idx_key",
1966                "idx_key",
1967                "edge_alias",
1968                "edge_alias",
1969                "file_uri",
1970                "file_uri",
1971            ]
1972            .iter()
1973            .enumerate()
1974            {
1975                s[i] = Some(std::sync::Arc::from(*label));
1976                rc[i] = 1;
1977            }
1978        }
1979        let sid = |off: u32| crate::graph::unified::string::id::StringId::new(start + off);
1980        let arena_name_canon = sid(0);
1981        let arena_name_dup = sid(1);
1982        let arena_qname_canon = sid(2);
1983        let arena_qname_dup = sid(3);
1984        let idx_key_canon = sid(4);
1985        let idx_key_dup = sid(5);
1986        let edge_alias_canon = sid(6);
1987        let edge_alias_dup = sid(7);
1988        let file_uri_canon = sid(8);
1989        let file_uri_dup = sid(9);
1990
1991        // (a) Arena — name + qualified_name reference duplicate slots.
1992        let node;
1993        let node2;
1994        {
1995            let arena = graph.nodes_mut();
1996            let mut entry = NodeEntry::new(NodeKind::Function, arena_name_dup, file_a);
1997            entry.qualified_name = Some(arena_qname_dup);
1998            node = arena.alloc(entry).expect("alloc arena node");
1999            node2 = arena
2000                .alloc(NodeEntry::new(NodeKind::Function, arena_name_dup, file_a))
2001                .expect("alloc arena node2");
2002        }
2003        // (b) Indices — key under the duplicate StringId.
2004        graph
2005            .indices_mut()
2006            .add(node, NodeKind::Function, idx_key_dup, None, file_a);
2007        graph
2008            .indices_mut()
2009            .add(node2, NodeKind::Function, idx_key_dup, None, file_a);
2010        // (c) File registry — register a file with source_uri = dup.
2011        let fid = graph
2012            .files_mut()
2013            .register_external_with_uri(
2014                "/virtual/Exhaustive.class",
2015                Some(crate::graph::node::Language::Java),
2016                Some(file_uri_dup),
2017            )
2018            .expect("register external");
2019        // (d) Edge store — Imports edge with alias = dup.
2020        graph.edges_mut().add_edge(
2021            node,
2022            node2,
2023            EdgeKind::Imports {
2024                alias: Some(edge_alias_dup),
2025                is_wildcard: false,
2026            },
2027            file_a,
2028        );
2029
2030        let rebuild = graph.clone_for_rebuild();
2031        let finalized = rebuild.finalize().expect("finalize ok");
2032
2033        // (a) Arena: name + qualified_name on every live node.
2034        for nid in [node, node2] {
2035            let entry = finalized.nodes().get(nid).expect("node survives");
2036            assert_eq!(entry.name, arena_name_canon, "arena name canonicalised");
2037            if let Some(q) = entry.qualified_name {
2038                assert_eq!(q, arena_qname_canon, "arena qname canonicalised");
2039            }
2040        }
2041        // (b) Indices: canonical bucket populated, duplicate bucket empty.
2042        assert!(finalized.indices().by_name(idx_key_dup).is_empty());
2043        assert!(!finalized.indices().by_name(idx_key_canon).is_empty());
2044        // (c) File registry.
2045        let view = finalized
2046            .files()
2047            .file_provenance(fid)
2048            .expect("provenance present");
2049        assert_eq!(view.source_uri, Some(file_uri_canon));
2050        // (d) Edge store: every Imports alias canonical on both
2051        // directions. Post-finalize, edges live in CSR (step 9 drained
2052        // the delta into the CSR on both directions). Step 1's remap
2053        // ran on the delta *before* step 9, so the CSR is built from
2054        // the already-remapped delta.
2055        let fwd = finalized.edges().forward();
2056        let fwd_csr = fwd
2057            .csr()
2058            .expect("forward CSR must be populated after step 9");
2059        let mut fwd_imports = 0usize;
2060        for kind in fwd_csr.edge_kind() {
2061            if let EdgeKind::Imports { alias, .. } = kind {
2062                fwd_imports += 1;
2063                assert_ne!(*alias, Some(edge_alias_dup));
2064                assert_eq!(*alias, Some(edge_alias_canon));
2065            }
2066        }
2067        drop(fwd);
2068        assert!(fwd_imports > 0, "forward Imports must be present in CSR");
2069        let rev = finalized.edges().reverse();
2070        let rev_csr = rev
2071            .csr()
2072            .expect("reverse CSR must be populated after step 9");
2073        let mut rev_imports = 0usize;
2074        for kind in rev_csr.edge_kind() {
2075            if let EdgeKind::Imports { alias, .. } = kind {
2076                rev_imports += 1;
2077                assert_ne!(*alias, Some(edge_alias_dup));
2078                assert_eq!(*alias, Some(edge_alias_canon));
2079            }
2080        }
2081        drop(rev);
2082        assert!(rev_imports > 0, "reverse Imports must be present in CSR");
2083
2084        // All duplicate slots recycled; canonical slots retained.
2085        for (dup, canon, label) in [
2086            (arena_name_dup, arena_name_canon, "arena_name"),
2087            (arena_qname_dup, arena_qname_canon, "arena_qname"),
2088            (idx_key_dup, idx_key_canon, "idx_key"),
2089            (edge_alias_dup, edge_alias_canon, "edge_alias"),
2090            (file_uri_dup, file_uri_canon, "file_uri"),
2091        ] {
2092            assert_eq!(
2093                finalized.strings().ref_count(dup),
2094                0,
2095                "{label}: duplicate slot must be recycled (ref_count == 0)"
2096            );
2097            assert!(
2098                finalized.strings().ref_count(canon) > 0,
2099                "{label}: canonical slot must retain references (got {})",
2100                finalized.strings().ref_count(canon)
2101            );
2102        }
2103    }
2104
2105    // ----------------------------------------------------------------
2106    // Iter-2 B2: step 6 + step 13 per_file_nodes / bucket bijection.
2107    // ----------------------------------------------------------------
2108
2109    #[test]
2110    fn finalize_step6_drops_tombstoned_nodes_from_buckets() {
2111        let (graph, a, b, c) = seeded_graph();
2112        // Seed the registry buckets so finalize step 6 has real work.
2113        let file_a = FileId::new(1);
2114        let file_b = FileId::new(2);
2115        {
2116            // Direct access via clone-for-rebuild — we need to populate
2117            // the REBUILD-local registry because `seeded_graph` doesn't.
2118        }
2119        // Populate buckets on the graph first so clone captures them.
2120        {
2121            let files = graph.files();
2122            let _ = files; // ensure immut ref scope
2123        }
2124        let mut graph = graph;
2125        graph.files_mut().record_node(file_a, a);
2126        graph.files_mut().record_node(file_a, b);
2127        graph.files_mut().record_node(file_b, c);
2128
2129        let mut rebuild = graph.clone_for_rebuild();
2130        rebuild.tombstone(a);
2131        rebuild.tombstone(c);
2132        let finalized = rebuild.finalize().expect("finalize ok");
2133
2134        // a and c were tombstoned — must be absent from any bucket.
2135        // b survives under file_a; file_b's bucket collapsed to empty
2136        // and must be dropped.
2137        let buckets: std::collections::BTreeMap<FileId, Vec<crate::graph::unified::node::NodeId>> =
2138            finalized.files().per_file_nodes_for_gate0d().collect();
2139        assert_eq!(buckets.len(), 1, "empty bucket must be dropped");
2140        assert_eq!(buckets.get(&file_a).cloned().unwrap_or_default(), vec![b]);
2141        assert!(!buckets.contains_key(&file_b));
2142    }
2143
2144    #[test]
2145    fn finalize_step6_dedups_within_bucket() {
2146        let (mut graph, a, b, c) = seeded_graph();
2147        let file_a = FileId::new(1);
2148        let file_b = FileId::new(2);
2149        // Bucket every live node consistently with seeded_graph's own
2150        // FileId assignment (so the non-vacuous bijection check passes),
2151        // but duplicate `a` once to exercise step 6's dedup path.
2152        graph.files_mut().record_node(file_a, a);
2153        graph.files_mut().record_node(file_a, a); // intentional duplicate
2154        graph.files_mut().record_node(file_a, b);
2155        graph.files_mut().record_node(file_b, c);
2156        let rebuild = graph.clone_for_rebuild();
2157        let finalized = rebuild.finalize().expect("finalize ok");
2158        let buckets: std::collections::BTreeMap<FileId, Vec<crate::graph::unified::node::NodeId>> =
2159            finalized.files().per_file_nodes_for_gate0d().collect();
2160        let bucket_a = buckets.get(&file_a).expect("bucket for file_a");
2161        // Two live nodes (a, b) in file_a, duplicate `a` collapsed.
2162        assert_eq!(
2163            bucket_a.len(),
2164            2,
2165            "duplicates within bucket must be dedup'd"
2166        );
2167        assert!(bucket_a.contains(&a));
2168        assert!(bucket_a.contains(&b));
2169    }
2170
2171    #[test]
2172    fn finalize_step6_drops_empty_buckets() {
2173        let (mut graph, a, _b, _c) = seeded_graph();
2174        let file = FileId::new(1);
2175        graph.files_mut().record_node(file, a);
2176        let mut rebuild = graph.clone_for_rebuild();
2177        rebuild.tombstone(a); // drops the only bucket member
2178        let finalized = rebuild.finalize().expect("finalize ok");
2179        assert_eq!(
2180            finalized.files().per_file_bucket_count(),
2181            0,
2182            "empty bucket must be dropped by step 6"
2183        );
2184    }
2185
2186    #[test]
2187    fn bucket_bijection_passes_when_every_live_node_is_bucketed() {
2188        let (mut graph, a, b, c) = seeded_graph();
2189        // Bucket every live node consistently with each node's FileId.
2190        // seeded_graph uses file_a=1 for a, b and file_b=2 for c.
2191        let file_a = FileId::new(1);
2192        let file_b = FileId::new(2);
2193        graph.files_mut().record_node(file_a, a);
2194        graph.files_mut().record_node(file_a, b);
2195        graph.files_mut().record_node(file_b, c);
2196
2197        // Round-trip through finalize so the bijection check runs.
2198        let rebuild = graph.clone_for_rebuild();
2199        let finalized = rebuild.finalize().expect("finalize ok");
2200        // Explicit assert_bucket_bijection call also passes.
2201        finalized.assert_bucket_bijection();
2202    }
2203
2204    #[test]
2205    #[should_panic(expected = "duplicate node")]
2206    fn bucket_bijection_detects_duplicate_within_bucket() {
2207        let (mut graph, a, _b, _c) = seeded_graph();
2208        let file_a = FileId::new(1);
2209        // Manually force a duplicate inside a bucket by bypassing
2210        // `retain_nodes_in_buckets`. We achieve this by calling
2211        // `record_node` twice on the live graph and then invoking the
2212        // bijection check directly *without* routing through finalize
2213        // (which would dedup in step 6).
2214        graph.files_mut().record_node(file_a, a);
2215        graph.files_mut().record_node(file_a, a);
2216        graph.assert_bucket_bijection();
2217    }
2218
2219    #[test]
2220    #[should_panic(expected = "misfiled")]
2221    fn bucket_bijection_detects_misfiled_node() {
2222        let (mut graph, a, _b, _c) = seeded_graph();
2223        // Node `a` was allocated against FileId(1); put it in a bucket
2224        // keyed by FileId(99) — the bijection must reject with the
2225        // precise "misfiled" panic message emitted by
2226        // `CodeGraph::assert_bucket_bijection` (concurrent/graph.rs
2227        // around line 865). A broader `expected = "node"` would also
2228        // match the duplicate-node / dead-node / multi-bucket arms, so
2229        // it would not discriminate the specific failure mode under test.
2230        graph.files_mut().record_node(FileId::new(99), a);
2231        graph.assert_bucket_bijection();
2232    }
2233
2234    #[test]
2235    #[should_panic(expected = "absent from all buckets")]
2236    fn bucket_bijection_detects_missing_live_node() {
2237        let (mut graph, a, _b, c) = seeded_graph();
2238        // Bucket one node but not the other; with at least one populated
2239        // bucket, condition (d) becomes strict and the missing live node
2240        // must trigger a panic.
2241        let file_a = FileId::new(1);
2242        let _ = c;
2243        graph.files_mut().record_node(file_a, a);
2244        graph.assert_bucket_bijection();
2245    }
2246
2247    #[test]
2248    #[should_panic(expected = "dead node")]
2249    fn bucket_bijection_detects_dead_node_in_bucket() {
2250        let (mut graph, a, _b, _c) = seeded_graph();
2251        // Tombstone a, then leave it in a bucket — bijection must reject.
2252        let file_a = FileId::new(1);
2253        graph.files_mut().record_node(file_a, a);
2254        graph.nodes_mut().remove(a);
2255        graph.assert_bucket_bijection();
2256    }
2257
2258    // -----------------------------------------------------------------
2259    // Gate 0d — Tombstone-residue negative tests.
2260    //
2261    // Covers both the `RebuildGraph::assert_no_tombstone_residue`
2262    // diagnostic helper and the finalize step-14 publish-boundary
2263    // check. The bijection counterparts live in the block immediately
2264    // above.
2265    // -----------------------------------------------------------------
2266
2267    #[test]
2268    #[should_panic(expected = "still in edge store")]
2269    fn rebuild_graph_residue_detects_tombstone_still_in_edge_store() {
2270        // Gate 0d iter-1 Minor — dedicated negative test for the
2271        // edge-store residue arm.
2272        //
2273        // The residue check iterates K-rows in order (see
2274        // `assert_no_tombstone_residue` above): NodeArena → edges →
2275        // AuxiliaryIndices → macro_metadata → ... — so to exercise the
2276        // `edges` arm specifically we must remove `a` from the
2277        // NodeArena first (so the NodeArena arm does not fire), leave
2278        // the edge that references `a` intact, and tombstone it.
2279        use crate::graph::unified::edge::kind::EdgeKind;
2280        #[cfg(test)]
2281        use crate::graph::unified::edge::kind::ResolvedVia;
2282        let (graph, a, b, _c) = seeded_graph();
2283        let mut rebuild = graph.clone_for_rebuild();
2284        // Seed the edge store with an edge that references `a`. This
2285        // becomes the "dangling reference" the residue check must
2286        // detect: `a` will be removed from the arena but the edge
2287        // keeps pointing at it.
2288        rebuild.edges.add_edge(
2289            a,
2290            b,
2291            EdgeKind::Calls {
2292                argument_count: 0,
2293                is_async: false,
2294                resolved_via: ResolvedVia::Direct,
2295            },
2296            FileId::new(1),
2297        );
2298        // Remove `a` from the arena so the K.A1 arm passes.
2299        rebuild.nodes.remove(a);
2300        rebuild.tombstone(a);
2301        rebuild.assert_no_tombstone_residue();
2302    }
2303
2304    #[test]
2305    #[should_panic(expected = "still in auxiliary indices")]
2306    fn rebuild_graph_residue_detects_tombstone_still_in_auxiliary_indices() {
2307        // The residue check iterates K-rows starting at `NodeArena`, so
2308        // to exercise the `AuxiliaryIndices` arm specifically we must
2309        // first remove `a` from the arena (simulating step 2 of
2310        // finalize), leaving the `AuxiliaryIndices` stale reference
2311        // as the first arm that can trip. This reproduces the exact
2312        // failure mode the pre-finalize helper exists to catch: a bug
2313        // where finalize compacts the arena but forgets one index.
2314        let (graph, a, _b, _c) = seeded_graph();
2315        let mut rebuild = graph.clone_for_rebuild();
2316        rebuild.nodes.remove(a);
2317        rebuild.tombstone(a);
2318        rebuild.assert_no_tombstone_residue();
2319    }
2320
2321    #[test]
2322    #[should_panic(expected = "still in NodeArena")]
2323    fn rebuild_graph_residue_detects_tombstone_still_in_node_arena() {
2324        // NodeArena is the first `NodeIdBearing` in the residue check's
2325        // iteration order, so we can trip it with a raw `tombstone(a)`
2326        // call before we touch any auxiliary index. The live arena
2327        // entry for `a` remains — that is the bug we want to surface.
2328        let (graph, a, _b, _c) = seeded_graph();
2329        let mut rebuild = graph.clone_for_rebuild();
2330        // Prove the arena still contains `a` before the assertion so
2331        // the panic expectation maps to a real condition, not a vacuous
2332        // empty-tombstone skip.
2333        assert!(
2334            rebuild.nodes.get(a).is_some(),
2335            "pre-condition: arena must still contain the staged tombstone"
2336        );
2337        rebuild.tombstone(a);
2338        rebuild.assert_no_tombstone_residue();
2339    }
2340
2341    #[test]
2342    fn rebuild_graph_residue_is_noop_on_empty_tombstone_set() {
2343        // Positive: with no tombstones staged, the assertion must be a
2344        // no-op — otherwise every fresh `clone_for_rebuild` would panic.
2345        let (graph, _a, _b, _c) = seeded_graph();
2346        let rebuild = graph.clone_for_rebuild();
2347        assert_eq!(rebuild.pending_tombstone_count(), 0);
2348        rebuild.assert_no_tombstone_residue();
2349    }
2350
2351    #[test]
2352    #[should_panic(expected = "still in NodeArena")]
2353    fn finalize_step14_residue_detects_live_reference_to_drained_node() {
2354        // Drive the `finalize` step-14 residue assertion through the
2355        // publish-boundary helper. `seeded_graph()` returns a graph in
2356        // which `a` is a live NodeArena entry; passing `a` in the
2357        // `drained` set without actually removing the arena slot
2358        // simulates the bug step 14 exists to catch — step 8 drained
2359        // `a` into `drained_tombstones`, but something failed to
2360        // compact the arena. The residue check's K-row iteration
2361        // starts at `NodeArena`, so that is the arm that fires.
2362        //
2363        // The test routes through the canonical
2364        // `publish::assert_publish_invariants` helper so the test
2365        // exercises the exact code path `finalize` step 14 executes,
2366        // not just the underlying `assert_no_tombstone_residue_for`
2367        // entry point.
2368        let (graph, a, _b, _c) = seeded_graph();
2369        let mut drained: ::std::collections::HashSet<NodeId> = ::std::collections::HashSet::new();
2370        drained.insert(a);
2371        crate::graph::unified::publish::assert_publish_invariants(&graph, &drained);
2372    }
2373
2374    #[test]
2375    fn finalize_with_empty_drained_set_passes_publish_invariants() {
2376        // Positive smoke test: the happy path through finalize (no
2377        // tombstones staged) must pass `assert_publish_invariants`
2378        // unconditionally on every build profile. This is the case the
2379        // full-rebuild `build_unified_graph_inner` end-of-function call
2380        // exercises on every CI run.
2381        let (graph, _a, _b, _c) = seeded_graph();
2382        let file_a = FileId::new(1);
2383        let file_b = FileId::new(2);
2384        let mut graph = graph;
2385        graph.files_mut().record_node(file_a, _a);
2386        graph.files_mut().record_node(file_a, _b);
2387        graph.files_mut().record_node(file_b, _c);
2388
2389        let rebuild = graph.clone_for_rebuild();
2390        let finalized = rebuild.finalize().expect("finalize ok");
2391        crate::graph::unified::publish::assert_publish_invariants(
2392            &finalized,
2393            &::std::collections::HashSet::new(),
2394        );
2395    }
2396
2397    // ---- Task 4 Step 3 — RebuildGraph::remove_file ------------------
2398
2399    /// Seed a graph + rebuild with 2 files × `per_file` nodes and a
2400    /// mix of intra- and cross-file `Calls` edges, then clone for
2401    /// rebuild. Returns `(rebuild, file_a, file_b, file_a_nodes,
2402    /// file_b_nodes)` — mirrors `seed_two_file_graph` in the
2403    /// `concurrent::graph::tests` module but yields the rebuild value
2404    /// so tests here can drive `RebuildGraph::remove_file` directly.
2405    fn seed_two_file_rebuild(
2406        per_file: usize,
2407    ) -> (
2408        RebuildGraph,
2409        crate::graph::unified::file::FileId,
2410        crate::graph::unified::file::FileId,
2411        Vec<NodeId>,
2412        Vec<NodeId>,
2413    ) {
2414        use crate::graph::unified::edge::{EdgeKind, ResolvedVia};
2415        use crate::graph::unified::node::NodeKind;
2416        use crate::graph::unified::storage::arena::NodeEntry;
2417        use std::path::Path;
2418
2419        let mut graph = CodeGraph::new();
2420        let sym = graph.strings_mut().intern("sym").expect("intern");
2421        let file_a = graph
2422            .files_mut()
2423            .register(Path::new("/tmp/rebuild_remove_file_test/a.rs"))
2424            .expect("register a");
2425        let file_b = graph
2426            .files_mut()
2427            .register(Path::new("/tmp/rebuild_remove_file_test/b.rs"))
2428            .expect("register b");
2429
2430        let mut file_a_nodes = Vec::with_capacity(per_file);
2431        let mut file_b_nodes = Vec::with_capacity(per_file);
2432        for _ in 0..per_file {
2433            let n = graph
2434                .nodes_mut()
2435                .alloc(NodeEntry::new(NodeKind::Function, sym, file_a))
2436                .expect("alloc a");
2437            file_a_nodes.push(n);
2438            graph.files_mut().record_node(file_a, n);
2439            graph
2440                .indices_mut()
2441                .add(n, NodeKind::Function, sym, None, file_a);
2442        }
2443        for _ in 0..per_file {
2444            let n = graph
2445                .nodes_mut()
2446                .alloc(NodeEntry::new(NodeKind::Function, sym, file_b))
2447                .expect("alloc b");
2448            file_b_nodes.push(n);
2449            graph.files_mut().record_node(file_b, n);
2450            graph
2451                .indices_mut()
2452                .add(n, NodeKind::Function, sym, None, file_b);
2453        }
2454        for i in 0..per_file.saturating_sub(1) {
2455            graph.edges_mut().add_edge(
2456                file_a_nodes[i],
2457                file_a_nodes[i + 1],
2458                EdgeKind::Calls {
2459                    argument_count: 0,
2460                    is_async: false,
2461                    resolved_via: ResolvedVia::Direct,
2462                },
2463                file_a,
2464            );
2465            graph.edges_mut().add_edge(
2466                file_b_nodes[i],
2467                file_b_nodes[i + 1],
2468                EdgeKind::Calls {
2469                    argument_count: 0,
2470                    is_async: false,
2471                    resolved_via: ResolvedVia::Direct,
2472                },
2473                file_b,
2474            );
2475        }
2476        graph.edges_mut().add_edge(
2477            file_a_nodes[0],
2478            file_b_nodes[0],
2479            EdgeKind::Calls {
2480                argument_count: 0,
2481                is_async: false,
2482                resolved_via: ResolvedVia::Direct,
2483            },
2484            file_a,
2485        );
2486        graph.edges_mut().add_edge(
2487            file_b_nodes[0],
2488            file_a_nodes[0],
2489            EdgeKind::Calls {
2490                argument_count: 0,
2491                is_async: false,
2492                resolved_via: ResolvedVia::Direct,
2493            },
2494            file_b,
2495        );
2496
2497        let rebuild = graph.clone_for_rebuild();
2498        (rebuild, file_a, file_b, file_a_nodes, file_b_nodes)
2499    }
2500
2501    #[test]
2502    fn rebuild_remove_file_tombstones_all_per_file_nodes() {
2503        let (mut rebuild, file_a, _file_b, file_a_nodes, _) = seed_two_file_rebuild(3);
2504
2505        let returned = rebuild.remove_file(file_a);
2506
2507        let returned_set: std::collections::HashSet<NodeId> = returned.iter().copied().collect();
2508        let expected_set: std::collections::HashSet<NodeId> =
2509            file_a_nodes.iter().copied().collect();
2510        assert_eq!(
2511            returned_set, expected_set,
2512            "remove_file must return exactly the file_a nodes drained from the bucket"
2513        );
2514        // Each returned NodeId is arena-gone on the rebuild.
2515        for nid in &file_a_nodes {
2516            assert!(
2517                rebuild.nodes.get(*nid).is_none(),
2518                "node {nid:?} from removed file must be tombstoned on rebuild arena"
2519            );
2520        }
2521        // And staged for the finalize-time NodeIdBearing sweep.
2522        assert_eq!(rebuild.pending_tombstone_count(), file_a_nodes.len());
2523    }
2524
2525    #[test]
2526    fn rebuild_remove_file_invalidates_all_edges_sourced_or_targeted_at_removed_nodes() {
2527        let (mut rebuild, file_a, _file_b, file_a_nodes, file_b_nodes) = seed_two_file_rebuild(3);
2528
2529        // Seed produces 6 forward delta edges (2 intra-A + 2 intra-B
2530        // + 2 cross). The rebuild's own forward/reverse edge stores
2531        // mirror this.
2532        assert_eq!(rebuild.edges.forward().delta().len(), 6);
2533
2534        let _ = rebuild.remove_file(file_a);
2535
2536        // After removal: only 2 intra-B edges remain in each direction.
2537        assert_eq!(rebuild.edges.forward().delta().len(), 2);
2538        assert_eq!(rebuild.edges.reverse().delta().len(), 2);
2539
2540        // Cross-file edge b[0] -> a[0] must be gone from any direction.
2541        let b0 = file_b_nodes[0];
2542        let a0 = file_a_nodes[0];
2543        let from_b0: Vec<_> = rebuild
2544            .edges
2545            .edges_from(b0)
2546            .into_iter()
2547            .filter(|e| e.target == a0)
2548            .collect();
2549        assert!(
2550            from_b0.is_empty(),
2551            "edge b0 -> a0 must be gone after rebuild.remove_file(file_a)"
2552        );
2553    }
2554
2555    #[test]
2556    fn rebuild_remove_file_drops_file_registry_entry() {
2557        let (mut rebuild, file_a, _file_b, _, _) = seed_two_file_rebuild(2);
2558
2559        assert!(rebuild.files.resolve(file_a).is_some());
2560        assert!(!rebuild.files.nodes_for_file(file_a).is_empty());
2561
2562        let _ = rebuild.remove_file(file_a);
2563
2564        assert!(
2565            rebuild.files.resolve(file_a).is_none(),
2566            "rebuild FileRegistry entry must be gone"
2567        );
2568        assert!(
2569            rebuild.files.nodes_for_file(file_a).is_empty(),
2570            "rebuild per-file bucket for file_a must be drained"
2571        );
2572    }
2573
2574    #[test]
2575    fn rebuild_remove_file_is_idempotent_on_unknown_file() {
2576        use crate::graph::unified::file::FileId;
2577        let (mut rebuild, _file_a, _file_b, _, _) = seed_two_file_rebuild(2);
2578
2579        let nodes_before = rebuild.nodes.len();
2580        let delta_fwd_before = rebuild.edges.forward().delta().len();
2581        let delta_rev_before = rebuild.edges.reverse().delta().len();
2582        let tombstones_before = rebuild.pending_tombstone_count();
2583
2584        let bogus = FileId::new(9999);
2585        let returned = rebuild.remove_file(bogus);
2586        assert!(returned.is_empty());
2587
2588        assert_eq!(rebuild.nodes.len(), nodes_before);
2589        assert_eq!(rebuild.edges.forward().delta().len(), delta_fwd_before);
2590        assert_eq!(rebuild.edges.reverse().delta().len(), delta_rev_before);
2591        assert_eq!(rebuild.pending_tombstone_count(), tombstones_before);
2592    }
2593
2594    #[test]
2595    fn rebuild_remove_file_stages_tombstones_for_finalize_sweep() {
2596        // The whole point of RebuildGraph::remove_file deferring the
2597        // K.A/K.B sweep to finalize() is that the sweep happens exactly
2598        // once against the union of every file's tombstones. Drive this
2599        // end-to-end: remove both files, finalize, and assert the
2600        // publish-boundary invariants hold.
2601        let (mut rebuild, file_a, file_b, file_a_nodes, file_b_nodes) = seed_two_file_rebuild(2);
2602
2603        let _ = rebuild.remove_file(file_a);
2604        let _ = rebuild.remove_file(file_b);
2605
2606        // Pending tombstones: union of both files' nodes.
2607        assert_eq!(
2608            rebuild.pending_tombstone_count(),
2609            file_a_nodes.len() + file_b_nodes.len()
2610        );
2611
2612        // Pre-finalize residue check against the rebuild-local state
2613        // is expected to pass: every NodeIdBearing surface on the
2614        // rebuild must already be clean of the tombstoned IDs (via the
2615        // immediate arena + edge tombstoning in step 1–2 of
2616        // remove_file) — NO, the NodeIdBearing K.A/K.B surfaces beyond
2617        // NodeArena/edges are NOT touched before finalize. The
2618        // assert_no_tombstone_residue helper on RebuildGraph walks
2619        // every surface, so it will legitimately find tombstones in
2620        // the auxiliary indices + metadata stores until finalize runs.
2621        //
2622        // So: do NOT run the pre-finalize residue check here. Instead,
2623        // confirm finalize runs successfully and the assembled
2624        // CodeGraph passes the publish-boundary invariants against
2625        // the drained set — that is the real post-condition.
2626        let finalized = rebuild.finalize().expect("finalize must succeed");
2627
2628        // Every surface on the finalized CodeGraph must be clean of the
2629        // tombstoned ids. Use the publish-boundary residue helper
2630        // against an empty dead set (finalize's own step-14 call already
2631        // covered the drained set; we re-verify the bijection for
2632        // paranoia).
2633        crate::graph::unified::publish::assert_publish_bijection(&finalized);
2634        // Arena is empty (every seeded node was tombstoned).
2635        assert_eq!(finalized.nodes().len(), 0);
2636        // No file registration survives.
2637        assert!(finalized.files().resolve(file_a).is_none());
2638        assert!(finalized.files().resolve(file_b).is_none());
2639    }
2640
2641    #[test]
2642    fn rebuild_remove_file_repeated_calls_are_idempotent() {
2643        let (mut rebuild, file_a, _file_b, file_a_nodes, _) = seed_two_file_rebuild(3);
2644
2645        let first = rebuild.remove_file(file_a);
2646        assert_eq!(first.len(), file_a_nodes.len());
2647        let staged = rebuild.pending_tombstone_count();
2648
2649        // Second call: bucket is already drained, NodeArena::remove
2650        // ignores stale generations, and the tombstones set should not
2651        // grow. The immediate tombstone side effects are idempotent.
2652        let second = rebuild.remove_file(file_a);
2653        assert!(second.is_empty());
2654        assert_eq!(rebuild.pending_tombstone_count(), staged);
2655    }
2656
2657    #[test]
2658    fn rebuild_remove_file_clears_file_segments_entry() {
2659        // Iter-1 Codex review fix mirror of the CodeGraph-side test
2660        // in `concurrent/graph.rs`. Seed a segment for file A, invoke
2661        // `RebuildGraph::remove_file`, and assert both the
2662        // rebuild-local `file_segments` and the finalized `CodeGraph`'s
2663        // `file_segments` table carry no entry for file A. The second
2664        // half of the check is critical: `finalize()` step 12 publishes
2665        // `self.file_segments` verbatim, so a missing clear here would
2666        // leak the stale range into the publishable graph.
2667        use std::path::Path;
2668
2669        let (mut rebuild, file_a, _file_b, file_a_nodes, _) = seed_two_file_rebuild(3);
2670
2671        // Seed a segment for file A. Fish out the span from the
2672        // allocated NodeIds to mirror the shape `phase3_parallel_commit`
2673        // produces.
2674        let first_index = file_a_nodes
2675            .iter()
2676            .map(|n| n.index())
2677            .min()
2678            .expect("per_file = 3");
2679        let last_index = file_a_nodes
2680            .iter()
2681            .map(|n| n.index())
2682            .max()
2683            .expect("per_file = 3");
2684        let slot_count = last_index - first_index + 1;
2685        rebuild
2686            .file_segments
2687            .record_range(file_a, first_index, slot_count);
2688        assert!(
2689            rebuild.file_segments().get(file_a).is_some(),
2690            "seeded segment for file_a must be present before remove_file"
2691        );
2692
2693        // Act.
2694        let _ = rebuild.remove_file(file_a);
2695
2696        // Rebuild-local post-condition.
2697        assert!(
2698            rebuild.file_segments().get(file_a).is_none(),
2699            "RebuildGraph::remove_file must clear the file_segments entry"
2700        );
2701
2702        // Finalize post-condition: the published CodeGraph must also
2703        // carry no entry for file_a.
2704        let finalized = rebuild.finalize().expect("finalize must succeed");
2705        assert!(
2706            finalized.file_segments().get(file_a).is_none(),
2707            "finalize must publish a CodeGraph with no stale file_segments for file_a"
2708        );
2709
2710        // Defensive suppression: the Path import is used only by the
2711        // adjacent `seed_two_file_rebuild` helper when the signature
2712        // is exercised — the let-binding below keeps this test
2713        // self-contained even if the helper's surface changes later.
2714        let _ = Path::new("");
2715    }
2716}