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