sqry_core/graph/unified/concurrent/graph.rs
1//! `CodeGraph` and `ConcurrentCodeGraph` implementations.
2//!
3//! This module provides the core graph types with thread-safe access:
4//!
5//! - [`CodeGraph`]: Arc-wrapped internals for O(1) `CoW` snapshots
6//! - [`ConcurrentCodeGraph`]: `RwLock` wrapper with epoch versioning
7//! - [`GraphSnapshot`]: Immutable snapshot for long-running queries
8
9use std::collections::{HashMap, HashSet};
10use std::fmt;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicU64, Ordering};
13
14use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
15
16use crate::confidence::ConfidenceMetadata;
17use crate::graph::unified::bind::alias::AliasTable;
18use crate::graph::unified::bind::scope::provenance::{
19 ScopeProvenance, ScopeProvenanceStore, ScopeStableId,
20};
21use crate::graph::unified::bind::scope::{ScopeArena, ScopeId};
22use crate::graph::unified::bind::shadow::ShadowTable;
23use crate::graph::unified::edge::EdgeKind;
24#[cfg(test)]
25use crate::graph::unified::edge::ResolvedVia;
26use crate::graph::unified::edge::bidirectional::BidirectionalEdgeStore;
27use crate::graph::unified::file::FileId;
28use crate::graph::unified::memory::{GraphMemorySize, HASHMAP_ENTRY_OVERHEAD};
29use crate::graph::unified::resolution::display_graph_qualified_name;
30use crate::graph::unified::storage::arena::NodeArena;
31use crate::graph::unified::storage::c_indirect::CIndirectSideTables;
32use crate::graph::unified::storage::edge_provenance::{EdgeProvenance, EdgeProvenanceStore};
33use crate::graph::unified::storage::indices::AuxiliaryIndices;
34use crate::graph::unified::storage::interner::StringInterner;
35use crate::graph::unified::storage::metadata::NodeMetadataStore;
36use crate::graph::unified::storage::node_provenance::{NodeProvenance, NodeProvenanceStore};
37use crate::graph::unified::storage::registry::{FileProvenanceView, FileRegistry};
38use crate::graph::unified::storage::segment::FileSegmentTable;
39use crate::graph::unified::string::id::StringId;
40
41/// Core graph with Arc-wrapped internals for O(1) `CoW` snapshots.
42///
43/// `CodeGraph` uses `Arc` for all internal components, enabling:
44/// - O(1) snapshot creation via Arc cloning
45/// - Copy-on-write semantics via `Arc::make_mut`
46/// - Memory-efficient sharing between snapshots
47///
48/// # Design
49///
50/// The Arc wrapping enables the MVCC pattern:
51/// - Readers see a consistent snapshot at the time they acquired access
52/// - Writers use `Arc::make_mut` to get exclusive copies only when mutating
53/// - Multiple snapshots can coexist without copying data
54///
55/// # Performance
56///
57/// - Snapshot creation: O(5) Arc clones ≈ <1μs
58/// - Read access: Direct Arc dereference, no locking
59/// - Write access: `Arc::make_mut` clones only if refcount > 1
60///
61/// # Phase 2 binding-plane access
62///
63/// Use the two-line snapshot pattern to access `BindingPlane`:
64///
65/// ```rust,ignore
66/// let snapshot = graph.snapshot();
67/// let plane = snapshot.binding_plane();
68/// let resolution = plane.resolve(&query);
69/// ```
70///
71/// The two-line form is intentional: `BindingPlane<'g>` borrows from
72/// `GraphSnapshot` and the explicit snapshot handle makes the MVCC lifetime
73/// visible at the call site. The full Phase 2 scope/alias/shadow and
74/// witness-bearing resolution API is exposed through `BindingPlane`.
75// Field visibility is `pub(crate)` so the Gate 0c `rebuild_graph` module
76// (A2 §H) can destructure `CodeGraph` exhaustively in `clone_for_rebuild`.
77// External crates still go through the public accessor methods below.
78#[derive(Clone)]
79pub struct CodeGraph {
80 /// Node storage with generational indices.
81 pub(crate) nodes: Arc<NodeArena>,
82 /// Bidirectional edge storage (forward + reverse).
83 pub(crate) edges: Arc<BidirectionalEdgeStore>,
84 /// String interner for symbol names.
85 pub(crate) strings: Arc<StringInterner>,
86 /// File registry for path deduplication.
87 pub(crate) files: Arc<FileRegistry>,
88 /// Auxiliary indices for fast lookup.
89 pub(crate) indices: Arc<AuxiliaryIndices>,
90 /// Sparse macro boundary metadata (keyed by full `NodeId`).
91 pub(crate) macro_metadata: Arc<NodeMetadataStore>,
92 /// Dense node provenance (Phase 1 fact layer).
93 pub(crate) node_provenance: Arc<NodeProvenanceStore>,
94 /// Dense edge provenance (Phase 1 fact layer).
95 pub(crate) edge_provenance: Arc<EdgeProvenanceStore>,
96 /// Monotonic fact-layer epoch (0 until set by the V8 persistence path).
97 pub(crate) fact_epoch: u64,
98 /// Epoch for version tracking.
99 pub(crate) epoch: u64,
100 /// Per-language confidence metadata collected during build.
101 /// Maps language name (e.g., "rust") to aggregated confidence.
102 pub(crate) confidence: HashMap<String, ConfidenceMetadata>,
103 /// Phase 2 binding-plane scope arena (populated by Phase 4e).
104 pub(crate) scope_arena: Arc<ScopeArena>,
105 /// Phase 2 binding-plane alias table (populated by Phase 4e / P2U04).
106 pub(crate) alias_table: Arc<AliasTable>,
107 /// Phase 2 binding-plane shadow table (populated by Phase 4e / P2U05).
108 pub(crate) shadow_table: Arc<ShadowTable>,
109 /// Phase 2 binding-plane scope provenance store (populated by Phase 4e / P2U11).
110 pub(crate) scope_provenance_store: Arc<ScopeProvenanceStore>,
111 /// Phase 3 file segment table mapping `FileId` to contiguous node ranges.
112 /// Populated during build Phase 3 parallel commit, persisted in V10+ snapshots.
113 pub(crate) file_segments: Arc<FileSegmentTable>,
114 /// Phase A (U09): C-only indirect-call resolver side tables.
115 ///
116 /// `None` on non-C workspaces — the parent slot stays unallocated so
117 /// non-C builds incur zero side-table overhead. Populated by Phase 3
118 /// commit (U11) and consumed by `pass5b_c_indirect_resolve` (U12).
119 /// Persisted as the V11 `Option<CIndirectSideTables>` envelope slot
120 /// (DESIGN §10.2); V10 → V11 upconvert sets this to `None`.
121 pub(crate) c_indirect_tables: Option<CIndirectSideTables>,
122 /// Build-time scratch side-channel from the Go plugin (Cluster A
123 /// of the Go T1 implements-and-promotion design).
124 ///
125 /// Populated during Phase 1 plugin parse, merged into the live
126 /// target by Phase 3 commit after NodeId / StringId remap, drained
127 /// by `pass_go_method_set_satisfaction` between Phase 4e and Pass
128 /// 5. Not part of `GraphSnapshot`, not persisted in V10 — see
129 /// 02_DESIGN §6. Held by-value (not `Arc<…>`) because no
130 /// copy-on-write or shared-reader access is required: only the
131 /// rebuild owner mutates, only the pass consumes, then the field
132 /// is reset.
133 pub(crate) go_hints: crate::graph::unified::build::staging::GoHints,
134}
135
136impl CodeGraph {
137 /// Creates a new empty `CodeGraph`.
138 ///
139 /// # Example
140 ///
141 /// ```rust
142 /// use sqry_core::graph::unified::concurrent::CodeGraph;
143 ///
144 /// let graph = CodeGraph::new();
145 /// assert_eq!(graph.epoch(), 0);
146 /// ```
147 #[must_use]
148 pub fn new() -> Self {
149 Self {
150 nodes: Arc::new(NodeArena::new()),
151 edges: Arc::new(BidirectionalEdgeStore::new()),
152 strings: Arc::new(StringInterner::new()),
153 files: Arc::new(FileRegistry::new()),
154 indices: Arc::new(AuxiliaryIndices::new()),
155 macro_metadata: Arc::new(NodeMetadataStore::new()),
156 node_provenance: Arc::new(NodeProvenanceStore::new()),
157 edge_provenance: Arc::new(EdgeProvenanceStore::new()),
158 fact_epoch: 0,
159 epoch: 0,
160 confidence: HashMap::new(),
161 scope_arena: Arc::new(ScopeArena::new()),
162 alias_table: Arc::new(AliasTable::new()),
163 shadow_table: Arc::new(ShadowTable::new()),
164 scope_provenance_store: Arc::new(ScopeProvenanceStore::new()),
165 file_segments: Arc::new(FileSegmentTable::new()),
166 c_indirect_tables: None,
167 go_hints: crate::graph::unified::build::staging::GoHints::default(),
168 }
169 }
170
171 /// Creates a `CodeGraph` from existing components.
172 ///
173 /// This is useful when building a graph from external data or
174 /// reconstructing from serialized state.
175 #[must_use]
176 pub fn from_components(
177 nodes: NodeArena,
178 edges: BidirectionalEdgeStore,
179 strings: StringInterner,
180 files: FileRegistry,
181 indices: AuxiliaryIndices,
182 macro_metadata: NodeMetadataStore,
183 ) -> Self {
184 Self {
185 nodes: Arc::new(nodes),
186 edges: Arc::new(edges),
187 strings: Arc::new(strings),
188 files: Arc::new(files),
189 indices: Arc::new(indices),
190 macro_metadata: Arc::new(macro_metadata),
191 node_provenance: Arc::new(NodeProvenanceStore::new()),
192 edge_provenance: Arc::new(EdgeProvenanceStore::new()),
193 fact_epoch: 0,
194 epoch: 0,
195 confidence: HashMap::new(),
196 scope_arena: Arc::new(ScopeArena::new()),
197 alias_table: Arc::new(AliasTable::new()),
198 shadow_table: Arc::new(ShadowTable::new()),
199 scope_provenance_store: Arc::new(ScopeProvenanceStore::new()),
200 file_segments: Arc::new(FileSegmentTable::new()),
201 c_indirect_tables: None,
202 go_hints: crate::graph::unified::build::staging::GoHints::default(),
203 }
204 }
205
206 /// Creates a cheap snapshot of the graph.
207 ///
208 /// This operation is O(5) Arc clones, which completes in <1μs.
209 /// The snapshot is isolated from future mutations to the original graph.
210 ///
211 /// # Example
212 ///
213 /// ```rust
214 /// use sqry_core::graph::unified::concurrent::CodeGraph;
215 ///
216 /// let graph = CodeGraph::new();
217 /// let snapshot = graph.snapshot();
218 /// // snapshot is independent of future mutations to graph
219 /// ```
220 #[must_use]
221 pub fn snapshot(&self) -> GraphSnapshot {
222 GraphSnapshot {
223 nodes: Arc::clone(&self.nodes),
224 edges: Arc::clone(&self.edges),
225 strings: Arc::clone(&self.strings),
226 files: Arc::clone(&self.files),
227 indices: Arc::clone(&self.indices),
228 macro_metadata: Arc::clone(&self.macro_metadata),
229 node_provenance: Arc::clone(&self.node_provenance),
230 edge_provenance: Arc::clone(&self.edge_provenance),
231 fact_epoch: self.fact_epoch,
232 epoch: self.epoch,
233 scope_arena: Arc::clone(&self.scope_arena),
234 alias_table: Arc::clone(&self.alias_table),
235 shadow_table: Arc::clone(&self.shadow_table),
236 scope_provenance_store: Arc::clone(&self.scope_provenance_store),
237 file_segments: Arc::clone(&self.file_segments),
238 c_indirect_tables: self.c_indirect_tables.clone(),
239 }
240 }
241
242 /// Returns a reference to the node arena.
243 #[inline]
244 #[must_use]
245 pub fn nodes(&self) -> &NodeArena {
246 &self.nodes
247 }
248
249 /// Returns a reference to the bidirectional edge store.
250 #[inline]
251 #[must_use]
252 pub fn edges(&self) -> &BidirectionalEdgeStore {
253 &self.edges
254 }
255
256 /// Returns a reference to the string interner.
257 #[inline]
258 #[must_use]
259 pub fn strings(&self) -> &StringInterner {
260 &self.strings
261 }
262
263 /// Returns a reference to the file registry.
264 #[inline]
265 #[must_use]
266 pub fn files(&self) -> &FileRegistry {
267 &self.files
268 }
269
270 /// Returns a reference to the auxiliary indices.
271 #[inline]
272 #[must_use]
273 pub fn indices(&self) -> &AuxiliaryIndices {
274 &self.indices
275 }
276
277 /// Returns a reference to the macro boundary metadata store.
278 #[inline]
279 #[must_use]
280 pub fn macro_metadata(&self) -> &NodeMetadataStore {
281 &self.macro_metadata
282 }
283
284 /// Returns a reference to the C indirect-call side tables, if any.
285 ///
286 /// `None` on non-C workspaces — the slot is allocated lazily and only
287 /// when the C plugin's Phase 1 instrumentation observes content worth
288 /// recording. On loaded snapshots, the V11 envelope's
289 /// `Option<CIndirectSideTables>` field round-trips into this slot
290 /// (DESIGN §10.2); V10 → V11 upconvert always sets the slot to `None`.
291 ///
292 /// `pass5b_c_indirect_resolve` (U12) consumes these tables to rewrite
293 /// synthetic indirect-call `Calls` edges into precise binding-plane /
294 /// type-match candidates.
295 #[inline]
296 #[must_use]
297 pub fn c_indirect_tables(&self) -> Option<&CIndirectSideTables> {
298 self.c_indirect_tables.as_ref()
299 }
300
301 /// Returns a mutable reference to the `Option<CIndirectSideTables>`
302 /// slot, allowing callers to install / replace / clear the side
303 /// tables.
304 ///
305 /// Mirrors the accessor pattern used for [`Self::macro_metadata_mut`]
306 /// but exposes the `Option` directly — the side tables are owned in
307 /// place, not behind an `Arc`. Callers that need to merge incremental
308 /// state into the existing tables typically do:
309 ///
310 /// ```rust,ignore
311 /// let slot = graph.c_indirect_tables_mut();
312 /// let tables = slot.get_or_insert_with(CIndirectSideTables::new);
313 /// tables.bindings_by_field.entry(key).or_default().push(entry);
314 /// ```
315 ///
316 /// Populated by the build pipeline (U11). Read-only consumers should
317 /// use [`Self::c_indirect_tables`] instead.
318 #[inline]
319 pub fn c_indirect_tables_mut(&mut self) -> &mut Option<CIndirectSideTables> {
320 &mut self.c_indirect_tables
321 }
322
323 /// Test-only: strip every Phase-A-introduced piece of state from this
324 /// graph, leaving a graph that is byte-identical (modulo persistence
325 /// header timestamps) to what a pre-Phase-A build would have produced
326 /// on the same fixture.
327 ///
328 /// Specifically:
329 ///
330 /// * Clears the [`CIndirectSideTables`] slot (sets it to `None`).
331 /// * Removes [`NodeFlags::ADDRESS_TAKEN`] and
332 /// [`NodeFlags::CALLSITE_PROMISCUOUS`] marker bits from every
333 /// [`StoredEntry`] in the macro-metadata store.
334 /// * Rewrites the `resolved_via` field of every [`EdgeKind::Calls`]
335 /// edge (across CSR and delta tiers, forward and reverse stores)
336 /// to [`ResolvedVia::Direct`].
337 ///
338 /// Used exclusively by `sqry-core/tests/snapshot_size_phase_a.rs`
339 /// (U19) to materialize a "Phase-A-free" baseline snapshot for the
340 /// +10% snapshot-size gate. Gated behind `cfg(any(test, feature =
341 /// "test-support"))` so the helper is invisible to production
342 /// builds.
343 ///
344 /// [`NodeFlags::ADDRESS_TAKEN`]: crate::graph::unified::storage::metadata::NodeFlags::ADDRESS_TAKEN
345 /// [`NodeFlags::CALLSITE_PROMISCUOUS`]: crate::graph::unified::storage::metadata::NodeFlags::CALLSITE_PROMISCUOUS
346 /// [`StoredEntry`]: crate::graph::unified::storage::metadata::StoredEntry
347 /// [`EdgeKind::Calls`]: crate::graph::unified::edge::EdgeKind::Calls
348 /// [`ResolvedVia::Direct`]: crate::graph::unified::edge::ResolvedVia::Direct
349 #[cfg(any(test, feature = "test-support"))]
350 pub fn clear_phase_a_state_for_test(&mut self) {
351 *self.c_indirect_tables_mut() = None;
352 self.macro_metadata_mut().clear_phase_a_flags_for_test();
353 self.edges_mut().normalize_calls_resolved_via_for_test();
354 }
355
356 // ------------------------------------------------------------------
357 // Phase 1 fact-layer provenance accessors (P1U09).
358 // ------------------------------------------------------------------
359
360 /// Returns the monotonic fact-layer epoch stamped on the most recently
361 /// saved or loaded snapshot. Returns `0` for graphs that have not been
362 /// persisted yet or were loaded from V7 snapshots.
363 #[inline]
364 #[must_use]
365 pub fn fact_epoch(&self) -> u64 {
366 self.fact_epoch
367 }
368
369 /// Looks up node provenance by `NodeId`.
370 ///
371 /// Returns `None` if the `NodeId` is out of range, the slot is vacant,
372 /// or the stored generation does not match (stale handle).
373 #[inline]
374 #[must_use]
375 pub fn node_provenance(
376 &self,
377 id: crate::graph::unified::node::id::NodeId,
378 ) -> Option<&NodeProvenance> {
379 self.node_provenance.lookup(id)
380 }
381
382 /// Looks up edge provenance by `EdgeId`.
383 ///
384 /// Returns `None` if the `EdgeId` is out of range, the slot is vacant,
385 /// or the edge is the invalid sentinel.
386 #[inline]
387 #[must_use]
388 pub fn edge_provenance(
389 &self,
390 id: crate::graph::unified::edge::id::EdgeId,
391 ) -> Option<&EdgeProvenance> {
392 self.edge_provenance.lookup(id)
393 }
394
395 /// Returns a borrowed provenance view for a file.
396 ///
397 /// Returns `None` for invalid/unregistered `FileId`s.
398 #[inline]
399 #[must_use]
400 pub fn file_provenance(
401 &self,
402 id: crate::graph::unified::file::id::FileId,
403 ) -> Option<FileProvenanceView<'_>> {
404 self.files.file_provenance(id)
405 }
406
407 // ------------------------------------------------------------------
408 // Phase 2 binding-plane accessors (P2U03).
409 // ------------------------------------------------------------------
410
411 /// Returns a reference to the scope arena derived during Phase 4e.
412 ///
413 /// The arena is empty on freshly-constructed `CodeGraph` instances and is
414 /// populated by calling `phase4e_binding::derive_binding_plane`.
415 #[inline]
416 #[must_use]
417 pub fn scope_arena(&self) -> &ScopeArena {
418 &self.scope_arena
419 }
420
421 /// Installs a freshly-derived scope arena.
422 ///
423 /// Called from `phase4e_binding::derive_binding_plane` during the build
424 /// pipeline. External callers that run Phase 4e manually (e.g., test
425 /// fixture builders) use this to store the result.
426 pub(crate) fn set_scope_arena(&mut self, arena: ScopeArena) {
427 self.scope_arena = Arc::new(arena);
428 }
429
430 /// Returns a reference to the alias table derived during Phase 4e.
431 ///
432 /// The table is empty on freshly-constructed `CodeGraph` instances and is
433 /// populated by calling `phase4e_binding::derive_binding_plane`.
434 #[inline]
435 #[must_use]
436 pub fn alias_table(&self) -> &AliasTable {
437 &self.alias_table
438 }
439
440 /// Installs a freshly-derived alias table.
441 ///
442 /// Called from `phase4e_binding::derive_binding_plane` during the build
443 /// pipeline. External callers that run Phase 4e manually (e.g., test
444 /// fixture builders) use this to store the result.
445 pub(crate) fn set_alias_table(&mut self, table: AliasTable) {
446 self.alias_table = Arc::new(table);
447 }
448
449 /// Returns a reference to the shadow table derived during Phase 4e.
450 ///
451 /// The table is empty on freshly-constructed `CodeGraph` instances and is
452 /// populated by calling `phase4e_binding::derive_binding_plane`.
453 #[inline]
454 #[must_use]
455 pub fn shadow_table(&self) -> &ShadowTable {
456 &self.shadow_table
457 }
458
459 /// Installs a freshly-derived shadow table.
460 ///
461 /// Called from `phase4e_binding::derive_binding_plane` during the build
462 /// pipeline. External callers that run Phase 4e manually (e.g., test
463 /// fixture builders) use this to store the result.
464 pub(crate) fn set_shadow_table(&mut self, table: ShadowTable) {
465 self.shadow_table = Arc::new(table);
466 }
467
468 /// Returns a reference to the scope provenance store derived during Phase 4e.
469 ///
470 /// The store is empty on freshly-constructed `CodeGraph` instances and is
471 /// populated by calling `phase4e_binding::derive_binding_plane`.
472 #[inline]
473 #[must_use]
474 pub fn scope_provenance_store(&self) -> &ScopeProvenanceStore {
475 &self.scope_provenance_store
476 }
477
478 /// Looks up scope provenance by `ScopeId`.
479 ///
480 /// Returns `None` if the slot is out of range, vacant, or the stored
481 /// generation does not match (stale handle).
482 #[inline]
483 #[must_use]
484 pub fn scope_provenance(&self, id: ScopeId) -> Option<&ScopeProvenance> {
485 self.scope_provenance_store.lookup(id)
486 }
487
488 /// Looks up the live `ScopeId` for a stable scope identity.
489 ///
490 /// Returns `None` if no provenance record is registered for that stable id.
491 /// The reverse index is populated by `insert` during Phase 4e and must be
492 /// rebuilt after V9 deserialization.
493 #[inline]
494 #[must_use]
495 pub fn scope_by_stable_id(&self, stable: ScopeStableId) -> Option<ScopeId> {
496 self.scope_provenance_store.scope_by_stable_id(stable)
497 }
498
499 /// Installs a freshly-derived scope provenance store.
500 ///
501 /// Called from `phase4e_binding::derive_binding_plane` during the build
502 /// pipeline. External callers that run Phase 4e manually (e.g., test
503 /// fixture builders) use this to store the result.
504 pub(crate) fn set_scope_provenance_store(&mut self, store: ScopeProvenanceStore) {
505 self.scope_provenance_store = Arc::new(store);
506 }
507
508 /// Returns a reference to the file segment table.
509 #[inline]
510 #[must_use]
511 pub fn file_segments(&self) -> &FileSegmentTable {
512 &self.file_segments
513 }
514
515 /// Replaces the file segment table.
516 pub(crate) fn set_file_segments(&mut self, table: FileSegmentTable) {
517 self.file_segments = Arc::new(table);
518 }
519
520 /// Installs the C indirect-call side tables loaded from a V11
521 /// snapshot.
522 ///
523 /// `None` clears the slot (used on V10 → V11 upconvert and on non-C
524 /// workspaces). `Some(...)` carries the live tables onto the freshly
525 /// reconstructed `CodeGraph`. Build-pipeline callers that incrementally
526 /// populate the tables should prefer [`Self::c_indirect_tables_mut`].
527 pub(crate) fn set_c_indirect_tables(&mut self, tables: Option<CIndirectSideTables>) {
528 self.c_indirect_tables = tables;
529 }
530
531 /// Returns a mutable reference to the file segment table (via `Arc::make_mut`).
532 pub(crate) fn file_segments_mut(&mut self) -> &mut FileSegmentTable {
533 Arc::make_mut(&mut self.file_segments)
534 }
535
536 /// Test-only helper that records a file segment directly on the
537 /// graph, bypassing the full Phase 3 commit pipeline. Only
538 /// available under `#[cfg(feature = "rebuild-internals")]` so the
539 /// surface is opt-in for rebuild-plane consumers (the feature is
540 /// whitelisted to sqry-daemon + sqry-core integration tests; see
541 /// `sqry-core/tests/rebuild_internals_whitelist.rs`).
542 ///
543 /// Integration tests (notably
544 /// `sqry-core/tests/incremental_remove_file_scale.rs`) call this
545 /// to seed the synthetic workspaces they build before exercising
546 /// `RebuildGraph::remove_file` / `CodeGraph::remove_file`. Production
547 /// code paths never touch this method — Phase 3 parallel commit
548 /// is the sole production writer, via the crate-internal
549 /// `file_segments_mut` accessor above.
550 ///
551 /// Renamed with `test_only_` prefix so the purpose is unambiguous
552 /// at every call site; `#[doc(hidden)]` hides it from rendered
553 /// rustdoc so downstream daemon integrations don't discover it by
554 /// accident.
555 #[cfg(feature = "rebuild-internals")]
556 #[doc(hidden)]
557 pub fn test_only_record_file_segment(
558 &mut self,
559 file_id: FileId,
560 start_slot: u32,
561 slot_count: u32,
562 ) {
563 Arc::make_mut(&mut self.file_segments).record_range(file_id, start_slot, slot_count);
564 }
565
566 /// Sets the provenance stores and fact epoch, typically called by the
567 /// persistence loader after deserializing a V8 snapshot.
568 pub(crate) fn set_provenance(
569 &mut self,
570 node_provenance: NodeProvenanceStore,
571 edge_provenance: EdgeProvenanceStore,
572 fact_epoch: u64,
573 ) {
574 self.node_provenance = Arc::new(node_provenance);
575 self.edge_provenance = Arc::new(edge_provenance);
576 self.fact_epoch = fact_epoch;
577 }
578
579 /// Returns the current epoch.
580 #[inline]
581 #[must_use]
582 pub fn epoch(&self) -> u64 {
583 self.epoch
584 }
585
586 /// Returns a mutable reference to the node arena.
587 ///
588 /// Uses `Arc::make_mut` for copy-on-write semantics: if other
589 /// references exist (e.g., snapshots), the data is cloned.
590 #[inline]
591 pub fn nodes_mut(&mut self) -> &mut NodeArena {
592 Arc::make_mut(&mut self.nodes)
593 }
594
595 /// Returns a mutable reference to the bidirectional edge store.
596 ///
597 /// Uses `Arc::make_mut` for copy-on-write semantics.
598 #[inline]
599 pub fn edges_mut(&mut self) -> &mut BidirectionalEdgeStore {
600 Arc::make_mut(&mut self.edges)
601 }
602
603 /// Returns a mutable reference to the string interner.
604 ///
605 /// Uses `Arc::make_mut` for copy-on-write semantics.
606 #[inline]
607 pub fn strings_mut(&mut self) -> &mut StringInterner {
608 Arc::make_mut(&mut self.strings)
609 }
610
611 /// Returns a mutable reference to the file registry.
612 ///
613 /// Uses `Arc::make_mut` for copy-on-write semantics.
614 #[inline]
615 pub fn files_mut(&mut self) -> &mut FileRegistry {
616 Arc::make_mut(&mut self.files)
617 }
618
619 /// Returns a mutable reference to the auxiliary indices.
620 ///
621 /// Uses `Arc::make_mut` for copy-on-write semantics.
622 #[inline]
623 pub fn indices_mut(&mut self) -> &mut AuxiliaryIndices {
624 Arc::make_mut(&mut self.indices)
625 }
626
627 /// Returns a mutable reference to the macro boundary metadata store.
628 ///
629 /// Uses `Arc::make_mut` for copy-on-write semantics.
630 #[inline]
631 pub fn macro_metadata_mut(&mut self) -> &mut NodeMetadataStore {
632 Arc::make_mut(&mut self.macro_metadata)
633 }
634
635 /// Returns mutable references to both the node arena and the string interner.
636 ///
637 /// This avoids the borrow-conflict that arises when calling `nodes_mut()` and
638 /// `strings_mut()` separately on `&mut self`.
639 #[inline]
640 pub fn nodes_and_strings_mut(&mut self) -> (&mut NodeArena, &mut StringInterner) {
641 (
642 Arc::make_mut(&mut self.nodes),
643 Arc::make_mut(&mut self.strings),
644 )
645 }
646
647 /// Rebuilds auxiliary indices from the current node arena.
648 ///
649 /// This avoids the borrow conflict that arises when calling `nodes()` and
650 /// `indices_mut()` separately on `&mut self`. Uses disjoint field borrowing
651 /// to access `nodes` (shared) and `indices` (mutable) simultaneously.
652 /// Internally calls `AuxiliaryIndices::build_from_arena` which clears
653 /// existing indices and rebuilds in a single pass without per-element
654 /// duplicate checking.
655 ///
656 /// As of Task 4 Step 4 Phase 2 this inherent method delegates to the
657 /// generic
658 /// [`crate::graph::unified::build::parallel_commit::rebuild_indices`]
659 /// free function so the same implementation serves both the
660 /// full-build (`CodeGraph`) and incremental-rebuild (`RebuildGraph`)
661 /// pipelines. Call sites that hold a concrete `CodeGraph` can keep
662 /// using `graph.rebuild_indices()`; incremental rebuild call sites
663 /// should use the free function directly.
664 pub fn rebuild_indices(&mut self) {
665 crate::graph::unified::build::parallel_commit::rebuild_indices(self);
666 }
667
668 /// Increments the epoch counter and returns the new value.
669 ///
670 /// Called automatically by `ConcurrentCodeGraph::write()`.
671 #[inline]
672 pub fn bump_epoch(&mut self) -> u64 {
673 self.epoch = self.epoch.wrapping_add(1);
674 self.epoch
675 }
676
677 /// Sets the epoch to a specific value.
678 ///
679 /// This is primarily for testing or reconstruction from serialized state.
680 #[inline]
681 pub fn set_epoch(&mut self, epoch: u64) {
682 self.epoch = epoch;
683 }
684
685 /// Returns the number of nodes in the graph.
686 ///
687 /// This is a convenience method that delegates to `nodes().len()`.
688 ///
689 /// # Example
690 ///
691 /// ```rust
692 /// use sqry_core::graph::unified::concurrent::CodeGraph;
693 ///
694 /// let graph = CodeGraph::new();
695 /// assert_eq!(graph.node_count(), 0);
696 /// ```
697 #[inline]
698 #[must_use]
699 pub fn node_count(&self) -> usize {
700 self.nodes.len()
701 }
702
703 /// Returns the number of edges in the graph (forward direction).
704 ///
705 /// This counts edges in the forward store, including both CSR and delta edges.
706 ///
707 /// # Example
708 ///
709 /// ```rust
710 /// use sqry_core::graph::unified::concurrent::CodeGraph;
711 ///
712 /// let graph = CodeGraph::new();
713 /// assert_eq!(graph.edge_count(), 0);
714 /// ```
715 #[inline]
716 #[must_use]
717 pub fn edge_count(&self) -> usize {
718 let stats = self.edges.stats();
719 stats.forward.csr_edge_count + stats.forward.delta_edge_count
720 }
721
722 /// Returns true if the graph contains no nodes.
723 ///
724 /// This is a convenience method that delegates to `nodes().is_empty()`.
725 ///
726 /// # Example
727 ///
728 /// ```rust
729 /// use sqry_core::graph::unified::concurrent::CodeGraph;
730 ///
731 /// let graph = CodeGraph::new();
732 /// assert!(graph.is_empty());
733 /// ```
734 #[inline]
735 #[must_use]
736 pub fn is_empty(&self) -> bool {
737 self.nodes.is_empty()
738 }
739
740 /// Returns an iterator over all indexed file paths.
741 ///
742 /// This is useful for enumerating all files that have been processed
743 /// and added to the graph.
744 ///
745 /// # Example
746 ///
747 /// ```rust
748 /// use sqry_core::graph::unified::concurrent::CodeGraph;
749 ///
750 /// let graph = CodeGraph::new();
751 /// for (file_id, path) in graph.indexed_files() {
752 /// println!("File {}: {}", file_id.index(), path.display());
753 /// }
754 /// ```
755 #[inline]
756 pub fn indexed_files(
757 &self,
758 ) -> impl Iterator<Item = (crate::graph::unified::file::FileId, &std::path::Path)> {
759 self.files
760 .iter()
761 .map(|(id, arc_path)| (id, arc_path.as_ref()))
762 }
763
764 /// Returns the set of files that import one or more symbols exported by
765 /// `file_id`, deduplicated and sorted ascending.
766 ///
767 /// For every [`EdgeKind::Imports`] edge whose target node lives in
768 /// `file_id`, the source node's [`FileId`] is added to the result. Files
769 /// are returned sorted by raw index so the result is deterministic across
770 /// runs. The caller's own file is never included — an `Imports` edge
771 /// whose source and target both live in `file_id` is treated as a
772 /// self-import and elided. Edges whose source node is no longer resolvable
773 /// in the arena (tombstoned) are silently skipped.
774 ///
775 /// This is the file-level view of Pass 4 cross-file `Imports` edges, used
776 /// by the incremental rebuild engine to compute reverse-dependency
777 /// closures: "if file X changes its exports, which files need to be
778 /// re-linked?"
779 ///
780 /// # Complexity
781 ///
782 /// `O(|nodes_in_file_id| × avg_incoming_edges_per_node)` amortized. Uses
783 /// [`AuxiliaryIndices::by_file`] for O(1)-amortized per-file node lookup
784 /// (HashMap-backed) and the bidirectional edge store's reverse adjacency;
785 /// no full-graph scan. A final `O(R log R)` sort over the deduplicated
786 /// importer set (where `R` is the importer count) is negligible in
787 /// practice since `R ≤ file_count`.
788 ///
789 /// [`AuxiliaryIndices::by_file`]: crate::graph::unified::storage::indices::AuxiliaryIndices::by_file
790 #[must_use]
791 pub fn reverse_import_index(&self, file_id: FileId) -> Vec<FileId> {
792 let mut importers: HashSet<FileId> = HashSet::new();
793 for &target_node in self.indices.by_file(file_id) {
794 for edge_ref in self.edges.edges_to(target_node) {
795 if !matches!(edge_ref.kind, EdgeKind::Imports { .. }) {
796 continue;
797 }
798 let Some(source_entry) = self.nodes.get(edge_ref.source) else {
799 continue;
800 };
801 let source_file = source_entry.file;
802 if source_file != file_id {
803 importers.insert(source_file);
804 }
805 }
806 }
807 let mut result: Vec<FileId> = importers.into_iter().collect();
808 result.sort();
809 result
810 }
811
812 /// Returns the set of files that hold at least one live inter-file edge
813 /// targeting a node in `file_id`, deduplicated and sorted ascending.
814 ///
815 /// Unlike [`reverse_import_index`](Self::reverse_import_index) — which
816 /// filters to [`EdgeKind::Imports`] only — this helper treats **every**
817 /// cross-file edge as a dependency signal: `Calls`, `References`,
818 /// `TypeOf`, `Inherits`, `Implements`, `FfiCall`, `HttpRequest`,
819 /// `GrpcCall`, `WebAssemblyCall`, `DbQuery`, `TableRead`, `TableWrite`,
820 /// `TriggeredBy`, `MessageQueue`, `WebSocket`, `GraphQLOperation`,
821 /// `ProcessExec`, `FileIpc`, `ProtocolCall`, and any future
822 /// cross-file-capable variant. This is the reverse-dependency surface the
823 /// incremental rebuild engine (Task 4 Step 4 Phase 3e) needs: when
824 /// `file_id` changes, every file whose committed edges point into
825 /// `file_id`'s nodes must re-enter the rebuild closure so its cross-file
826 /// references survive the target-side tombstone-and-reparse cycle.
827 ///
828 /// The caller's own file is never included — an edge whose source and
829 /// target both live in `file_id` is a self-reference and is elided.
830 /// Edges whose source node is no longer resolvable in the arena
831 /// (tombstoned) are silently skipped.
832 ///
833 /// # When to use this vs [`reverse_import_index`](Self::reverse_import_index)
834 ///
835 /// * [`reverse_import_index`](Self::reverse_import_index) remains the
836 /// right surface for consumers that specifically need *import*
837 /// relationships (export surface analysis, module-dependency graphs,
838 /// etc.).
839 /// * `reverse_dependency_index` is the right surface for incremental
840 /// rebuild closure computation. Widening past imports is necessary
841 /// because call sites, type references, trait implementations, FFI
842 /// declarations, HTTP clients, and every other cross-file edge kind
843 /// hold a committed edge into the target file that becomes stale the
844 /// moment `remove_file(target)` tombstones its arena nodes. Leaving
845 /// those files out of the closure leaves the committed edges pointing
846 /// at the stale (pre-tombstone) node IDs — Phase 4c-prime only
847 /// rewrites edges on **re-parsed** files' `PendingEdge` sets, never
848 /// committed edges owned by files outside the reparse scope.
849 ///
850 /// # Complexity
851 ///
852 /// `O(|nodes_in_file_id| × avg_incoming_edges_per_node)` amortized —
853 /// same bound as [`reverse_import_index`](Self::reverse_import_index).
854 /// Uses [`AuxiliaryIndices::by_file`] for O(1)-amortized per-file node
855 /// lookup and the bidirectional edge store's reverse adjacency; no
856 /// full-graph scan. Final `O(R log R)` sort over the deduplicated
857 /// dependent set is negligible since `R ≤ file_count`.
858 ///
859 /// # Over-widening is expected and acceptable
860 ///
861 /// The closure will include every file that references anything in
862 /// `file_id`, not just files whose exports change. In common codebases
863 /// this widens the reparse set modestly (a 10-file change may expand
864 /// to 20–30 dependent files in a medium crate). Correctness requires
865 /// the widening; minimality is a follow-up optimisation if profiling
866 /// demands it.
867 ///
868 /// [`AuxiliaryIndices::by_file`]: crate::graph::unified::storage::indices::AuxiliaryIndices::by_file
869 #[must_use]
870 pub fn reverse_dependency_index(&self, file_id: FileId) -> Vec<FileId> {
871 let mut dependents: HashSet<FileId> = HashSet::new();
872 for &target_node in self.indices.by_file(file_id) {
873 for edge_ref in self.edges.edges_to(target_node) {
874 let Some(source_entry) = self.nodes.get(edge_ref.source) else {
875 continue;
876 };
877 let source_file = source_entry.file;
878 if source_file != file_id {
879 dependents.insert(source_file);
880 }
881 }
882 }
883 let mut result: Vec<FileId> = dependents.into_iter().collect();
884 result.sort();
885 result
886 }
887
888 /// Returns the per-language confidence metadata.
889 ///
890 /// This contains analysis confidence information collected during graph build,
891 /// primarily used by language plugins (e.g., Rust) to track analysis quality.
892 #[inline]
893 #[must_use]
894 pub fn confidence(&self) -> &HashMap<String, ConfidenceMetadata> {
895 &self.confidence
896 }
897
898 /// Merges confidence metadata for a language.
899 ///
900 /// If confidence already exists for the language, this merges the new
901 /// metadata (taking the lower confidence level and combining limitations).
902 /// Otherwise, it inserts the new confidence.
903 pub fn merge_confidence(&mut self, language: &str, metadata: ConfidenceMetadata) {
904 use crate::confidence::ConfidenceLevel;
905
906 self.confidence
907 .entry(language.to_string())
908 .and_modify(|existing| {
909 // Take the lower confidence level (more conservative)
910 let new_level = match (&existing.level, &metadata.level) {
911 (ConfidenceLevel::Verified, other) | (other, ConfidenceLevel::Verified) => {
912 *other
913 }
914 (ConfidenceLevel::Partial, ConfidenceLevel::AstOnly)
915 | (ConfidenceLevel::AstOnly, ConfidenceLevel::Partial) => {
916 ConfidenceLevel::AstOnly
917 }
918 (level, _) => *level,
919 };
920 existing.level = new_level;
921
922 // Merge limitations (deduplicated)
923 for limitation in &metadata.limitations {
924 if !existing.limitations.contains(limitation) {
925 existing.limitations.push(limitation.clone());
926 }
927 }
928
929 // Merge unavailable features (deduplicated)
930 for feature in &metadata.unavailable_features {
931 if !existing.unavailable_features.contains(feature) {
932 existing.unavailable_features.push(feature.clone());
933 }
934 }
935 })
936 .or_insert(metadata);
937 }
938
939 /// Sets the confidence metadata map directly.
940 ///
941 /// This is primarily used when loading a graph from serialized state.
942 pub fn set_confidence(&mut self, confidence: HashMap<String, ConfidenceMetadata>) {
943 self.confidence = confidence;
944 }
945
946 // ------------------------------------------------------------------
947 // Task 4 Step 2 (A2 §F.2) — File-level tombstoning on a CodeGraph.
948 //
949 // Unlike the rebuild pipeline's `RebuildGraph::remove_file`, this
950 // path mutates a live `CodeGraph` in place and is the mechanism
951 // used by the full-rebuild flow when it needs to evict a file's
952 // nodes+edges between compactions. The daemon's incremental
953 // `WorkspaceManager` (Task 6) goes through the rebuild path, which
954 // is why this entry point is `pub(crate)`.
955 // ------------------------------------------------------------------
956
957 /// Tombstone every node that belongs to `file_id`, invalidate every
958 /// edge whose source or target is one of those nodes (across both
959 /// forward and reverse CSR + delta tiers), drop the file's entry
960 /// from the [`FileRegistry`], and return the set of [`NodeId`]s
961 /// that were tombstoned.
962 ///
963 /// This is the §F.2-aware file-removal primitive. Semantically, the
964 /// post-condition matches what a full rebuild of the workspace
965 /// without `file_id` would produce:
966 ///
967 /// * Every [`NodeEntry`] whose [`NodeEntry.file`] was `file_id` has
968 /// been `NodeArena::remove`d, advancing its slot generation so
969 /// stale [`NodeId`] handles do not alias a later re-allocation.
970 /// * Every CSR edge whose source or target slot matches one of the
971 /// tombstoned slot indices has its `csr_tombstones` bit set; the
972 /// read path's merge step already filters tombstoned CSR edges
973 /// out of every query result.
974 /// * Every delta-buffer edge (Add or Remove, any file) whose source
975 /// or target matches a tombstoned slot has been dropped from the
976 /// delta in both directions.
977 /// * The [`AuxiliaryIndices`] (kind / name / qualified-name / file)
978 /// no longer reference any of the tombstoned `NodeId`s.
979 /// * [`NodeMetadataStore`], [`NodeProvenanceStore`], [`ScopeArena`],
980 /// [`AliasTable`], and [`ShadowTable`] have been compacted through
981 /// the [`NodeIdBearing::retain_nodes`] predicate so no
982 /// tombstoned `NodeId` survives in any publish-visible store.
983 /// * [`FileRegistry::per_file_nodes`] no longer holds a bucket for
984 /// `file_id`, the lookup slot is recycled, and
985 /// [`FileRegistry::resolve(file_id)`] returns `None`.
986 ///
987 /// Returns the `Vec<NodeId>` of tombstoned nodes. The returned list
988 /// is useful for downstream housekeeping (e.g., resetting per-file
989 /// caches keyed by `NodeId`) and for tests that need to assert on the
990 /// exact membership of the tombstone set.
991 ///
992 /// # Idempotency
993 ///
994 /// Calling `remove_file` twice with the same `file_id` — or calling
995 /// it for a `file_id` that was never registered — is a safe no-op.
996 /// The returned `Vec<NodeId>` is empty on the second call; no
997 /// arena / edge / index state is mutated (the predicate-based
998 /// compaction of `NodeIdBearing` surfaces short-circuits when the
999 /// dead set is empty).
1000 ///
1001 /// # Visibility
1002 ///
1003 /// `pub(crate)` because external callers (Task 6's
1004 /// `WorkspaceManager` on the sqry-daemon side) route through
1005 /// [`super::super::rebuild::rebuild_graph::RebuildGraph::remove_file`]
1006 /// instead. This `CodeGraph`-level variant is used by full-rebuild
1007 /// housekeeping paths inside sqry-core and by the Task 4 Step 4
1008 /// incremental fallback for cases where the caller already has a
1009 /// `&mut CodeGraph` and does not need the clone-and-publish
1010 /// round-trip of [`clone_for_rebuild`](Self::clone_for_rebuild) →
1011 /// [`finalize`](super::super::rebuild::rebuild_graph::RebuildGraph::finalize).
1012 ///
1013 /// # Performance
1014 ///
1015 /// * `O(|tombstoned| + |csr_edges| + |delta_edges|)` amortised.
1016 /// The CSR walk is linear in total edge count (not per-file),
1017 /// which is the dominant cost; each row check is O(1) via the
1018 /// precomputed dead-slot-index `HashSet` in
1019 /// [`BidirectionalEdgeStore::tombstone_edges_for_nodes`].
1020 /// * Delta filtering is `O(|delta|)` per direction.
1021 /// * Auxiliary-index compaction is `O(|tombstoned|)` amortised
1022 /// because each of the four indices keys its entries by the
1023 /// tombstoned `NodeIds` directly.
1024 ///
1025 /// [`NodeEntry`]: crate::graph::unified::storage::arena::NodeEntry
1026 /// [`NodeEntry.file`]: crate::graph::unified::storage::arena::NodeEntry::file
1027 /// [`NodeIdBearing::retain_nodes`]: crate::graph::unified::rebuild::coverage::NodeIdBearing::retain_nodes
1028 #[allow(dead_code)] // Consumer is Task 4 Step 4 (`incremental_rebuild`)
1029 // and the unit tests below; published in this commit so the §F.2
1030 // invariant surface can be reviewed in isolation per the Gate 0c
1031 // split contract.
1032 pub(crate) fn remove_file(
1033 &mut self,
1034 file_id: FileId,
1035 ) -> Vec<crate::graph::unified::node::NodeId> {
1036 use crate::graph::unified::node::NodeId;
1037 use crate::graph::unified::rebuild::coverage::NodeIdBearing;
1038
1039 // Drain the per-file bucket. For a file that was never
1040 // registered, this returns an empty Vec — the rest of the
1041 // method short-circuits on the `if tombstoned.is_empty()` test
1042 // below so we still deregister the file on the off chance the
1043 // bucket was empty but the file was registered (defensive; the
1044 // common case is the bucket existed iff the file was
1045 // registered).
1046 let tombstoned: Vec<NodeId> = self.files_mut().take_nodes(file_id);
1047 // Always drop the file's path entry + recycle its slot, even
1048 // when the bucket was empty, so repeated registrations of the
1049 // same path don't resurrect a zombie FileId. `unregister` is
1050 // idempotent (returns None for unknown IDs) so the cost is a
1051 // single HashMap probe when file_id is already gone.
1052 self.files_mut().unregister(file_id);
1053 // Clear the file's segment entry unconditionally (idempotent
1054 // — `FileSegmentTable::remove` no-ops on unknown ids). This
1055 // MUST run before `FileRegistry::unregister` recycles the
1056 // FileId slot for reuse, otherwise a later registration of a
1057 // different path under the reused FileId would inherit the
1058 // previous file's stale node range (see
1059 // `sqry-core/src/graph/unified/build/reindex.rs` — which
1060 // trusts `file_segments().get(file_id)` to decide which slots
1061 // to tombstone). Note: `unregister` above was called first
1062 // only to keep the existing bucket-drain ordering; the
1063 // segment-clear is order-independent with respect to
1064 // `unregister` because neither touches the other's backing
1065 // store, and the FileId slot cannot be recycled-and-reissued
1066 // across a single `remove_file` call (the registry's slot
1067 // recycler is driven by a later `register`, not by
1068 // `unregister`).
1069 self.file_segments_mut().remove(file_id);
1070
1071 if tombstoned.is_empty() {
1072 return tombstoned;
1073 }
1074
1075 // Dead set keyed on NodeId for NodeIdBearing predicates.
1076 // `retain_nodes` uses `HashSet::contains` so membership is O(1).
1077 let dead: HashSet<NodeId> = tombstoned.iter().copied().collect();
1078
1079 // 1. Tombstone the arena slots. `NodeArena::remove` is
1080 // idempotent — stale NodeIds that don't match a slot's
1081 // current generation are no-ops, which lets this method be
1082 // safely re-run on the same file.
1083 {
1084 let arena = self.nodes_mut();
1085 for &nid in &tombstoned {
1086 let _ = arena.remove(nid);
1087 }
1088 }
1089
1090 // 2. Invalidate edges across both CSR + delta in both
1091 // directions. This is the expensive step; the helper uses a
1092 // precomputed dead-slot-index set so the CSR walk is linear
1093 // in total edge count, not quadratic.
1094 self.edges_mut().tombstone_edges_for_nodes(&dead);
1095
1096 // 3. Compact the auxiliary indices so name/kind/qname/file
1097 // lookups do not return tombstoned NodeIds. Using the
1098 // NodeIdBearing surface keeps this step in lockstep with the
1099 // rebuild pipeline's step 4 — any future publish-visible
1100 // NodeId-bearing container added to the K.A/K.B matrix is
1101 // automatically swept here too.
1102 {
1103 let predicate: Box<dyn Fn(NodeId) -> bool + '_> = Box::new(|nid| !dead.contains(&nid));
1104 self.indices_mut().retain_nodes(&*predicate);
1105 self.macro_metadata_mut().retain_nodes(&*predicate);
1106 // The remaining K.A rows (node_provenance, scope_arena,
1107 // alias_table, shadow_table) need Arc::make_mut accessors —
1108 // they are wrapped in Arc at rest so this is where the
1109 // CoW clone happens on demand. Inline the Arc::make_mut
1110 // calls here (no public mut accessor exists today because
1111 // the sole writer has been the rebuild path; extend the
1112 // set by adding a similar inline call plus a K.A/K.B row
1113 // in `super::super::rebuild::coverage`).
1114 Arc::make_mut(&mut self.node_provenance).retain_nodes(&*predicate);
1115 Arc::make_mut(&mut self.scope_arena).retain_nodes(&*predicate);
1116 Arc::make_mut(&mut self.alias_table).retain_nodes(&*predicate);
1117 Arc::make_mut(&mut self.shadow_table).retain_nodes(&*predicate);
1118 }
1119
1120 tombstoned
1121 }
1122
1123 // ------------------------------------------------------------------
1124 // Gate 0c (A2 §H, Task 4) — RebuildGraph assembly path.
1125 // ------------------------------------------------------------------
1126
1127 /// Assemble a [`CodeGraph`] from owned rebuild-local parts produced
1128 /// by `RebuildGraph::finalize()` (defined in
1129 /// `super::super::rebuild::rebuild_graph`).
1130 ///
1131 /// This constructor is deliberately `pub(crate)` and named with a
1132 /// leading `__` so it is inaccessible from downstream crates even
1133 /// when the `rebuild-internals` feature is enabled: only code in
1134 /// `sqry-core` itself (specifically `RebuildGraph::finalize`) is
1135 /// permitted to call it. The trybuild fixture
1136 /// `sqry-core/tests/rebuild_internals_compile_fail/rebuild_graph_no_public_assembly.rs`
1137 /// proves there is no other path from `RebuildGraph` to
1138 /// `Arc<CodeGraph>`.
1139 ///
1140 /// The argument order mirrors the `CodeGraph` struct declaration
1141 /// order exactly; the public `clone_for_rebuild` → `finalize`
1142 /// round-trip uses the same macro-driven field enumeration so any
1143 /// new `CodeGraph` field automatically threads through this
1144 /// constructor as well.
1145 #[doc(hidden)]
1146 #[allow(clippy::too_many_arguments)]
1147 #[must_use]
1148 pub(crate) fn __assemble_from_rebuild_parts_internal(
1149 nodes: NodeArena,
1150 edges: BidirectionalEdgeStore,
1151 strings: StringInterner,
1152 files: FileRegistry,
1153 indices: AuxiliaryIndices,
1154 macro_metadata: NodeMetadataStore,
1155 node_provenance: NodeProvenanceStore,
1156 edge_provenance: EdgeProvenanceStore,
1157 fact_epoch: u64,
1158 epoch: u64,
1159 confidence: HashMap<String, ConfidenceMetadata>,
1160 scope_arena: ScopeArena,
1161 alias_table: AliasTable,
1162 shadow_table: ShadowTable,
1163 scope_provenance_store: ScopeProvenanceStore,
1164 file_segments: FileSegmentTable,
1165 go_hints: crate::graph::unified::build::staging::GoHints,
1166 ) -> Self {
1167 Self {
1168 nodes: Arc::new(nodes),
1169 edges: Arc::new(edges),
1170 strings: Arc::new(strings),
1171 files: Arc::new(files),
1172 indices: Arc::new(indices),
1173 macro_metadata: Arc::new(macro_metadata),
1174 node_provenance: Arc::new(node_provenance),
1175 edge_provenance: Arc::new(edge_provenance),
1176 fact_epoch,
1177 epoch,
1178 confidence,
1179 scope_arena: Arc::new(scope_arena),
1180 alias_table: Arc::new(alias_table),
1181 shadow_table: Arc::new(shadow_table),
1182 scope_provenance_store: Arc::new(scope_provenance_store),
1183 file_segments: Arc::new(file_segments),
1184 c_indirect_tables: None,
1185 go_hints,
1186 }
1187 }
1188
1189 // ------------------------------------------------------------------
1190 // Gate 0c (A2 §F) — publish-boundary debug invariants.
1191 //
1192 // These checks fire only in debug / test builds; release builds
1193 // compile them out. They are called from
1194 // `RebuildGraph::finalize()` steps 13 and 14 (the single source of
1195 // truth for the residue check, per §F and §H agreement). Gate 0d
1196 // will additionally wire the bijection check into
1197 // `build_and_persist_graph`, `WorkspaceManager::publish_graph`, and
1198 // every §E equivalence-harness run.
1199 // ------------------------------------------------------------------
1200
1201 /// Assert the bijective bucket-membership invariant (A2 §F.1).
1202 ///
1203 /// Four conditions must hold simultaneously:
1204 /// (a) every `NodeId` inside any `per_file_nodes` bucket maps to a
1205 /// live arena slot;
1206 /// (b) every `NodeId` appears in exactly one bucket (no duplicates
1207 /// across buckets, no duplicates within a bucket);
1208 /// (c) the bucket's `FileId` matches the node's own `file` field on
1209 /// `NodeEntry`;
1210 /// (d) when at least one bucket is populated, every live node in
1211 /// the arena is accounted for by some bucket.
1212 ///
1213 /// Condition (d) is guarded on `!seen.is_empty()` so an empty-graph
1214 /// (no recorded buckets) publish boundary is vacuously consistent:
1215 /// legacy V7 snapshots, fresh `CodeGraph::new()` instances, and
1216 /// rebuilds on graphs that predate Gate 0c's parallel-commit
1217 /// bucketing must not panic. Once any bucket is populated, every
1218 /// live arena slot must appear in a bucket.
1219 ///
1220 /// Iter-2 B2 (verbatim): this check used to be documented as
1221 /// "vacuous until future `per_file_nodes` work lands". Pulling
1222 /// base-plan Step 1 into Gate 0c retires that phrasing — the check
1223 /// is non-vacuous the moment parallel-parse commits nodes, which
1224 /// happens on every real build. The `!seen.is_empty()` guard now
1225 /// exists solely for the empty-graph corner case, not as a phased-
1226 /// delivery deferral.
1227 ///
1228 /// The check is a no-op in release builds. Panics with a
1229 /// descriptive message on violation. This is intentional: publish-
1230 /// boundary violations are programmer errors that must surface
1231 /// loudly during CI / test runs.
1232 #[cfg(any(debug_assertions, test))]
1233 pub fn assert_bucket_bijection(&self) {
1234 use std::collections::HashMap as StdHashMap;
1235 // (a) + (b) + (c): every bucketed node is live, unique across
1236 // buckets, and the bucket's FileId matches the node's own file.
1237 let mut seen: StdHashMap<
1238 crate::graph::unified::node::NodeId,
1239 crate::graph::unified::file::FileId,
1240 > = StdHashMap::new();
1241 let mut any_bucket_populated = false;
1242 for (file_id, bucket) in self.files.per_file_nodes_for_gate0d() {
1243 if !bucket.is_empty() {
1244 any_bucket_populated = true;
1245 }
1246 // Local dedup guard within the bucket itself. `retain_nodes_in_buckets`
1247 // dedups during finalize step 6, but we re-check here so the
1248 // invariant covers non-finalize publish paths too (e.g. if a
1249 // future pipeline builds a graph without routing through
1250 // `RebuildGraph::finalize`).
1251 let mut within_bucket: std::collections::HashSet<crate::graph::unified::node::NodeId> =
1252 std::collections::HashSet::new();
1253 for node_id in bucket {
1254 assert!(
1255 within_bucket.insert(node_id),
1256 "assert_bucket_bijection: duplicate node {node_id:?} inside bucket {file_id:?}"
1257 );
1258 assert!(
1259 self.nodes.get(node_id).is_some(),
1260 "assert_bucket_bijection: dead node {node_id:?} in bucket {file_id:?}"
1261 );
1262 let prior = seen.insert(node_id, file_id);
1263 assert!(
1264 prior.is_none(),
1265 "assert_bucket_bijection: node {node_id:?} in multiple buckets: \
1266 prior={prior:?}, current={file_id:?}"
1267 );
1268 if let Some(entry) = self.nodes.get(node_id) {
1269 assert_eq!(
1270 entry.file, file_id,
1271 "assert_bucket_bijection: node {node_id:?} misfiled: in bucket \
1272 {file_id:?}, actual {:?}",
1273 entry.file
1274 );
1275 }
1276 }
1277 }
1278 // (d): every live node is accounted for by `seen` once buckets
1279 // are populated. The guard keeps legacy-empty-graph boundaries
1280 // vacuously consistent (see docs above).
1281 if any_bucket_populated {
1282 for (node_id, _entry) in self.nodes.iter() {
1283 assert!(
1284 seen.contains_key(&node_id),
1285 "assert_bucket_bijection: live node {node_id:?} absent from all buckets"
1286 );
1287 }
1288 }
1289 }
1290
1291 /// Assert the pre-reuse tombstone-residue invariant (A2 §F.2).
1292 ///
1293 /// Iterates every publish-visible NodeId-bearing structure on
1294 /// `self` and panics if any contains a node in `dead`. Called from
1295 /// `RebuildGraph::finalize()` step 14 against the set drained at
1296 /// step 8 — exactly one site per the plan's §F / §H agreement.
1297 ///
1298 /// No-op when `dead` is empty or in release builds.
1299 #[cfg(any(debug_assertions, test))]
1300 pub fn assert_no_tombstone_residue_for(
1301 &self,
1302 dead: &std::collections::HashSet<crate::graph::unified::node::NodeId>,
1303 ) {
1304 use super::super::rebuild::coverage::NodeIdBearing;
1305 if dead.is_empty() {
1306 return;
1307 }
1308 // Every K.A/K.B row must be inspected per §F.2.
1309 for nid in self.nodes.all_node_ids() {
1310 assert!(
1311 !dead.contains(&nid),
1312 "assert_no_tombstone_residue: tombstone {nid:?} still in NodeArena"
1313 );
1314 }
1315 for nid in self.indices.all_node_ids() {
1316 assert!(
1317 !dead.contains(&nid),
1318 "assert_no_tombstone_residue: tombstone {nid:?} still in auxiliary indices"
1319 );
1320 }
1321 for nid in self.edges.all_node_ids() {
1322 assert!(
1323 !dead.contains(&nid),
1324 "assert_no_tombstone_residue: tombstone {nid:?} still in edge store"
1325 );
1326 }
1327 for nid in self.macro_metadata.all_node_ids() {
1328 assert!(
1329 !dead.contains(&nid),
1330 "assert_no_tombstone_residue: tombstone {nid:?} still in macro metadata"
1331 );
1332 }
1333 for nid in self.node_provenance.all_node_ids() {
1334 assert!(
1335 !dead.contains(&nid),
1336 "assert_no_tombstone_residue: tombstone {nid:?} still in node provenance"
1337 );
1338 }
1339 for nid in self.scope_arena.all_node_ids() {
1340 assert!(
1341 !dead.contains(&nid),
1342 "assert_no_tombstone_residue: tombstone {nid:?} still in scope arena"
1343 );
1344 }
1345 for nid in self.alias_table.all_node_ids() {
1346 assert!(
1347 !dead.contains(&nid),
1348 "assert_no_tombstone_residue: tombstone {nid:?} still in alias table"
1349 );
1350 }
1351 for nid in self.shadow_table.all_node_ids() {
1352 assert!(
1353 !dead.contains(&nid),
1354 "assert_no_tombstone_residue: tombstone {nid:?} still in shadow table"
1355 );
1356 }
1357 for nid in self.files.all_node_ids() {
1358 assert!(
1359 !dead.contains(&nid),
1360 "assert_no_tombstone_residue: tombstone {nid:?} still in per-file bucket"
1361 );
1362 }
1363 }
1364}
1365
1366impl Default for CodeGraph {
1367 fn default() -> Self {
1368 Self::new()
1369 }
1370}
1371
1372impl fmt::Debug for CodeGraph {
1373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1374 f.debug_struct("CodeGraph")
1375 .field("nodes", &self.nodes.len())
1376 .field("epoch", &self.epoch)
1377 .finish_non_exhaustive()
1378 }
1379}
1380
1381impl GraphMemorySize for CodeGraph {
1382 /// Estimates the total heap bytes owned by this `CodeGraph`.
1383 ///
1384 /// Sums heap usage across every component the graph owns: node arena,
1385 /// bidirectional edge store (forward + reverse CSR + tombstones + delta
1386 /// buffer), string interner, file registry, auxiliary indices, sparse
1387 /// macro/classpath metadata, provenance stores, and the per-language
1388 /// confidence map. Used by the `sqryd` daemon's admission controller
1389 /// and workspace retention reaper to enforce memory budgets.
1390 fn heap_bytes(&self) -> usize {
1391 let mut confidence_bytes = self.confidence.capacity()
1392 * (std::mem::size_of::<String>()
1393 + std::mem::size_of::<ConfidenceMetadata>()
1394 + HASHMAP_ENTRY_OVERHEAD);
1395 for (key, meta) in &self.confidence {
1396 confidence_bytes += key.capacity();
1397 // `ConfidenceMetadata.limitations` / `unavailable_features` are
1398 // `Vec<String>`; charge their spill and inner String payloads.
1399 confidence_bytes += meta.limitations.capacity() * std::mem::size_of::<String>();
1400 for s in &meta.limitations {
1401 confidence_bytes += s.capacity();
1402 }
1403 confidence_bytes +=
1404 meta.unavailable_features.capacity() * std::mem::size_of::<String>();
1405 for s in &meta.unavailable_features {
1406 confidence_bytes += s.capacity();
1407 }
1408 }
1409
1410 self.nodes.heap_bytes()
1411 + self.edges.heap_bytes()
1412 + self.strings.heap_bytes()
1413 + self.files.heap_bytes()
1414 + self.indices.heap_bytes()
1415 + self.macro_metadata.heap_bytes()
1416 + self.node_provenance.heap_bytes()
1417 + self.edge_provenance.heap_bytes()
1418 + confidence_bytes
1419 + self.file_segments.capacity()
1420 * std::mem::size_of::<Option<crate::graph::unified::storage::segment::FileSegment>>(
1421 )
1422 }
1423}
1424
1425/// Thread-safe wrapper for `CodeGraph` with epoch versioning.
1426///
1427/// `ConcurrentCodeGraph` provides MVCC-style concurrency:
1428/// - Multiple readers can access the graph simultaneously
1429/// - Only one writer can hold the lock at a time
1430/// - Each write operation increments the epoch for cursor invalidation
1431///
1432/// # Design
1433///
1434/// The wrapper uses `parking_lot::RwLock` for efficient locking:
1435/// - Fair scheduling prevents writer starvation
1436/// - No poisoning (unlike `std::sync::RwLock`)
1437/// - Faster lock/unlock operations
1438///
1439/// # Phase 2 binding-plane access
1440///
1441/// Use the three-line snapshot pattern to access `BindingPlane`:
1442///
1443/// ```rust,ignore
1444/// let read_guard = concurrent.read();
1445/// let snapshot = read_guard.snapshot();
1446/// let plane = snapshot.binding_plane();
1447/// let resolution = plane.resolve(&query);
1448/// ```
1449///
1450/// The explicit snapshot handle makes the MVCC lifetime visible at the call
1451/// site. The full Phase 2 scope/alias/shadow and witness-bearing resolution
1452/// API is exposed through `BindingPlane`.
1453///
1454/// # Usage
1455///
1456/// ```rust
1457/// use sqry_core::graph::unified::concurrent::ConcurrentCodeGraph;
1458///
1459/// let graph = ConcurrentCodeGraph::new();
1460///
1461/// // Read access (multiple readers allowed)
1462/// {
1463/// let guard = graph.read();
1464/// let _nodes = guard.nodes();
1465/// }
1466///
1467/// // Write access (exclusive)
1468/// {
1469/// let mut guard = graph.write();
1470/// let _nodes = guard.nodes_mut();
1471/// }
1472///
1473/// // Snapshot for long queries
1474/// let snapshot = graph.snapshot();
1475/// ```
1476pub struct ConcurrentCodeGraph {
1477 /// The underlying code graph protected by a read-write lock.
1478 inner: RwLock<CodeGraph>,
1479 /// Global epoch counter for cursor validation.
1480 epoch: AtomicU64,
1481}
1482
1483impl ConcurrentCodeGraph {
1484 /// Creates a new empty `ConcurrentCodeGraph`.
1485 #[must_use]
1486 pub fn new() -> Self {
1487 Self {
1488 inner: RwLock::new(CodeGraph::new()),
1489 epoch: AtomicU64::new(0),
1490 }
1491 }
1492
1493 /// Creates a `ConcurrentCodeGraph` from an existing `CodeGraph`.
1494 #[must_use]
1495 pub fn from_graph(graph: CodeGraph) -> Self {
1496 let epoch = graph.epoch();
1497 Self {
1498 inner: RwLock::new(graph),
1499 epoch: AtomicU64::new(epoch),
1500 }
1501 }
1502
1503 /// Acquires a read lock on the graph.
1504 ///
1505 /// Multiple readers can hold the lock simultaneously.
1506 /// This does not increment the epoch.
1507 #[inline]
1508 pub fn read(&self) -> RwLockReadGuard<'_, CodeGraph> {
1509 self.inner.read()
1510 }
1511
1512 /// Acquires a write lock on the graph.
1513 ///
1514 /// Only one writer can hold the lock at a time.
1515 /// This increments the global epoch counter.
1516 #[inline]
1517 pub fn write(&self) -> RwLockWriteGuard<'_, CodeGraph> {
1518 // Increment the global epoch
1519 self.epoch.fetch_add(1, Ordering::SeqCst);
1520 let mut guard = self.inner.write();
1521 // Sync the inner graph's epoch with the global epoch
1522 guard.set_epoch(self.epoch.load(Ordering::SeqCst));
1523 guard
1524 }
1525
1526 /// Returns the current global epoch.
1527 ///
1528 /// This can be used to detect if the graph has been modified
1529 /// since a previous operation (cursor invalidation).
1530 #[inline]
1531 #[must_use]
1532 pub fn epoch(&self) -> u64 {
1533 self.epoch.load(Ordering::SeqCst)
1534 }
1535
1536 /// Creates a cheap snapshot of the graph.
1537 ///
1538 /// This acquires a brief read lock to clone the Arc references.
1539 /// The snapshot is isolated from future mutations.
1540 #[must_use]
1541 pub fn snapshot(&self) -> GraphSnapshot {
1542 self.inner.read().snapshot()
1543 }
1544
1545 // ------------------------------------------------------------------
1546 // Phase 1 fact-layer provenance convenience accessors.
1547 // These acquire a brief read lock, matching the snapshot() pattern.
1548 // ------------------------------------------------------------------
1549
1550 /// Returns the monotonic fact-layer epoch from the underlying graph.
1551 #[must_use]
1552 pub fn fact_epoch(&self) -> u64 {
1553 self.inner.read().fact_epoch()
1554 }
1555
1556 /// Looks up node provenance by `NodeId` (acquires a brief read lock).
1557 #[must_use]
1558 pub fn node_provenance(
1559 &self,
1560 id: crate::graph::unified::node::id::NodeId,
1561 ) -> Option<NodeProvenance> {
1562 self.inner.read().node_provenance(id).copied()
1563 }
1564
1565 /// Looks up edge provenance by `EdgeId` (acquires a brief read lock).
1566 #[must_use]
1567 pub fn edge_provenance(
1568 &self,
1569 id: crate::graph::unified::edge::id::EdgeId,
1570 ) -> Option<EdgeProvenance> {
1571 self.inner.read().edge_provenance(id).copied()
1572 }
1573
1574 /// Returns a file provenance view (acquires a brief read lock).
1575 ///
1576 /// Returns an owned copy since the borrow cannot outlive the lock guard.
1577 #[must_use]
1578 pub fn file_provenance(
1579 &self,
1580 id: crate::graph::unified::file::id::FileId,
1581 ) -> Option<OwnedFileProvenanceView> {
1582 let guard = self.inner.read();
1583 guard.file_provenance(id).map(|v| OwnedFileProvenanceView {
1584 content_hash: *v.content_hash,
1585 indexed_at: v.indexed_at,
1586 source_uri: v.source_uri,
1587 is_external: v.is_external,
1588 })
1589 }
1590
1591 // ------------------------------------------------------------------
1592 // Phase 2 binding-plane accessors (P2U03).
1593 // ------------------------------------------------------------------
1594
1595 /// Returns the scope arena from the underlying graph (acquires a brief
1596 /// read lock).
1597 ///
1598 /// Returns an `Arc` clone so the caller does not hold the lock beyond
1599 /// this call site.
1600 #[must_use]
1601 pub fn scope_arena(&self) -> Arc<ScopeArena> {
1602 Arc::clone(&self.inner.read().scope_arena)
1603 }
1604
1605 /// Returns the alias table from the underlying graph (acquires a brief
1606 /// read lock).
1607 ///
1608 /// Returns an `Arc` clone so the caller does not hold the lock beyond
1609 /// this call site.
1610 #[must_use]
1611 pub fn alias_table(&self) -> Arc<AliasTable> {
1612 Arc::clone(&self.inner.read().alias_table)
1613 }
1614
1615 /// Returns the shadow table from the underlying graph (acquires a brief
1616 /// read lock).
1617 ///
1618 /// Returns an `Arc` clone so the caller does not hold the lock beyond
1619 /// this call site.
1620 #[must_use]
1621 pub fn shadow_table(&self) -> Arc<ShadowTable> {
1622 Arc::clone(&self.inner.read().shadow_table)
1623 }
1624
1625 /// Returns the scope provenance store from the underlying graph (acquires
1626 /// a brief read lock).
1627 ///
1628 /// Returns an `Arc` clone so the caller does not hold the lock beyond
1629 /// this call site.
1630 #[must_use]
1631 pub fn scope_provenance_store(&self) -> Arc<ScopeProvenanceStore> {
1632 Arc::clone(&self.inner.read().scope_provenance_store)
1633 }
1634
1635 /// Looks up scope provenance by `ScopeId` (acquires a brief read lock).
1636 ///
1637 /// Returns an owned copy since the borrow cannot outlive the lock guard.
1638 #[must_use]
1639 pub fn scope_provenance(&self, id: ScopeId) -> Option<ScopeProvenance> {
1640 self.inner.read().scope_provenance(id).cloned()
1641 }
1642
1643 /// Looks up the live `ScopeId` for a stable scope identity (acquires a
1644 /// brief read lock).
1645 ///
1646 /// Returns `None` if no provenance record is registered for that stable id.
1647 #[must_use]
1648 pub fn scope_by_stable_id(&self, stable: ScopeStableId) -> Option<ScopeId> {
1649 self.inner.read().scope_by_stable_id(stable)
1650 }
1651
1652 /// Returns the file segment table from the underlying graph (acquires a
1653 /// brief read lock).
1654 #[must_use]
1655 pub fn file_segments(&self) -> Arc<FileSegmentTable> {
1656 Arc::clone(&self.inner.read().file_segments)
1657 }
1658
1659 /// Attempts to acquire a read lock without blocking.
1660 ///
1661 /// Returns `None` if the lock is currently held exclusively.
1662 #[inline]
1663 #[must_use]
1664 pub fn try_read(&self) -> Option<RwLockReadGuard<'_, CodeGraph>> {
1665 self.inner.try_read()
1666 }
1667
1668 /// Attempts to acquire a write lock without blocking.
1669 ///
1670 /// Returns `None` if the lock is currently held by another thread.
1671 /// If successful, increments the epoch.
1672 #[inline]
1673 pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, CodeGraph>> {
1674 self.inner.try_write().map(|mut guard| {
1675 self.epoch.fetch_add(1, Ordering::SeqCst);
1676 guard.set_epoch(self.epoch.load(Ordering::SeqCst));
1677 guard
1678 })
1679 }
1680}
1681
1682impl Default for ConcurrentCodeGraph {
1683 fn default() -> Self {
1684 Self::new()
1685 }
1686}
1687
1688impl fmt::Debug for ConcurrentCodeGraph {
1689 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1690 f.debug_struct("ConcurrentCodeGraph")
1691 .field("epoch", &self.epoch.load(Ordering::SeqCst))
1692 .finish_non_exhaustive()
1693 }
1694}
1695
1696/// Owned copy of file provenance, returned by [`ConcurrentCodeGraph::file_provenance`]
1697/// because the borrowed [`FileProvenanceView`] cannot outlive the read-lock guard.
1698#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1699pub struct OwnedFileProvenanceView {
1700 /// SHA-256 of the on-disk file bytes (owned copy).
1701 pub content_hash: [u8; 32],
1702 /// Unix-epoch seconds at which this file was registered.
1703 pub indexed_at: u64,
1704 /// Optional interned physical origin URI.
1705 pub source_uri: Option<StringId>,
1706 /// Whether this file originates from an external source.
1707 pub is_external: bool,
1708}
1709
1710/// Immutable snapshot of a `CodeGraph` for long-running queries.
1711///
1712/// `GraphSnapshot` holds Arc references to the graph components,
1713/// providing a consistent view that is isolated from concurrent mutations.
1714///
1715/// # Design
1716///
1717/// Snapshots are created via `CodeGraph::snapshot()` or
1718/// `ConcurrentCodeGraph::snapshot()`. They are:
1719///
1720/// - **Immutable**: No mutation methods available
1721/// - **Isolated**: Independent of future graph mutations
1722/// - **Cheap**: Only Arc clones, no data copying
1723/// - **Self-contained**: Can outlive the original graph/lock
1724///
1725/// # Usage
1726///
1727/// ```rust
1728/// use sqry_core::graph::unified::concurrent::{ConcurrentCodeGraph, GraphSnapshot};
1729///
1730/// let graph = ConcurrentCodeGraph::new();
1731///
1732/// // Create snapshot for a long query
1733/// let snapshot: GraphSnapshot = graph.snapshot();
1734///
1735/// // Snapshot can be used independently
1736/// let _epoch = snapshot.epoch();
1737/// ```
1738#[derive(Clone)]
1739pub struct GraphSnapshot {
1740 /// Node storage snapshot.
1741 nodes: Arc<NodeArena>,
1742 /// Edge storage snapshot.
1743 edges: Arc<BidirectionalEdgeStore>,
1744 /// String interner snapshot.
1745 strings: Arc<StringInterner>,
1746 /// File registry snapshot.
1747 files: Arc<FileRegistry>,
1748 /// Auxiliary indices snapshot.
1749 indices: Arc<AuxiliaryIndices>,
1750 /// Sparse macro boundary metadata snapshot.
1751 macro_metadata: Arc<NodeMetadataStore>,
1752 /// Dense node provenance snapshot (Phase 1).
1753 node_provenance: Arc<NodeProvenanceStore>,
1754 /// Dense edge provenance snapshot (Phase 1).
1755 edge_provenance: Arc<EdgeProvenanceStore>,
1756 /// Monotonic fact-layer epoch at snapshot time.
1757 fact_epoch: u64,
1758 /// Epoch at snapshot time (for cursor validation).
1759 epoch: u64,
1760 /// Phase 2 binding-plane scope arena snapshot (populated by Phase 4e).
1761 scope_arena: Arc<ScopeArena>,
1762 /// Phase 2 binding-plane alias table snapshot (populated by Phase 4e / P2U04).
1763 alias_table: Arc<AliasTable>,
1764 /// Phase 2 binding-plane shadow table snapshot (populated by Phase 4e / P2U05).
1765 shadow_table: Arc<ShadowTable>,
1766 /// Phase 2 binding-plane scope provenance store snapshot (populated by Phase 4e / P2U11).
1767 scope_provenance_store: Arc<ScopeProvenanceStore>,
1768 /// Phase 3 file segment table snapshot mapping `FileId` to node ranges.
1769 file_segments: Arc<FileSegmentTable>,
1770 /// Phase A (U09): C indirect-call resolver side tables snapshot.
1771 ///
1772 /// `None` on non-C workspaces. The snapshot owns its own clone of the
1773 /// `Option<CIndirectSideTables>` so concurrent readers see a stable
1774 /// view independent of subsequent mutations to the source `CodeGraph`.
1775 c_indirect_tables: Option<CIndirectSideTables>,
1776}
1777
1778impl GraphSnapshot {
1779 /// Returns a reference to the node arena.
1780 #[inline]
1781 #[must_use]
1782 pub fn nodes(&self) -> &NodeArena {
1783 &self.nodes
1784 }
1785
1786 /// Returns a reference to the bidirectional edge store.
1787 #[inline]
1788 #[must_use]
1789 pub fn edges(&self) -> &BidirectionalEdgeStore {
1790 &self.edges
1791 }
1792
1793 /// Returns a reference to the string interner.
1794 #[inline]
1795 #[must_use]
1796 pub fn strings(&self) -> &StringInterner {
1797 &self.strings
1798 }
1799
1800 /// Returns a reference to the file registry.
1801 #[inline]
1802 #[must_use]
1803 pub fn files(&self) -> &FileRegistry {
1804 &self.files
1805 }
1806
1807 /// Returns a reference to the auxiliary indices.
1808 #[inline]
1809 #[must_use]
1810 pub fn indices(&self) -> &AuxiliaryIndices {
1811 &self.indices
1812 }
1813
1814 /// Returns a reference to the macro boundary metadata store.
1815 #[inline]
1816 #[must_use]
1817 pub fn macro_metadata(&self) -> &NodeMetadataStore {
1818 &self.macro_metadata
1819 }
1820
1821 /// Returns a reference to the C indirect-call side tables, if any.
1822 ///
1823 /// Mirrors [`CodeGraph::c_indirect_tables`]; see that method for
1824 /// the contract. Snapshot-level access is read-only.
1825 #[inline]
1826 #[must_use]
1827 pub fn c_indirect_tables(&self) -> Option<&CIndirectSideTables> {
1828 self.c_indirect_tables.as_ref()
1829 }
1830
1831 // ------------------------------------------------------------------
1832 // Phase 1 fact-layer provenance accessors (P1U09).
1833 // ------------------------------------------------------------------
1834
1835 /// Returns the monotonic fact-layer epoch.
1836 #[inline]
1837 #[must_use]
1838 pub fn fact_epoch(&self) -> u64 {
1839 self.fact_epoch
1840 }
1841
1842 /// Looks up node provenance by `NodeId`.
1843 #[inline]
1844 #[must_use]
1845 pub fn node_provenance(
1846 &self,
1847 id: crate::graph::unified::node::id::NodeId,
1848 ) -> Option<&NodeProvenance> {
1849 self.node_provenance.lookup(id)
1850 }
1851
1852 /// Looks up edge provenance by `EdgeId`.
1853 #[inline]
1854 #[must_use]
1855 pub fn edge_provenance(
1856 &self,
1857 id: crate::graph::unified::edge::id::EdgeId,
1858 ) -> Option<&EdgeProvenance> {
1859 self.edge_provenance.lookup(id)
1860 }
1861
1862 /// Returns a borrowed provenance view for a file.
1863 #[inline]
1864 #[must_use]
1865 pub fn file_provenance(
1866 &self,
1867 id: crate::graph::unified::file::id::FileId,
1868 ) -> Option<FileProvenanceView<'_>> {
1869 self.files.file_provenance(id)
1870 }
1871
1872 // ------------------------------------------------------------------
1873 // Phase 2 binding-plane accessors (P2U03).
1874 // ------------------------------------------------------------------
1875
1876 /// Returns a reference to the scope arena at snapshot time.
1877 ///
1878 /// Participates in MVCC: the snapshot holds an `Arc` clone of the arena
1879 /// as it existed when `snapshot()` was called. Subsequent calls to
1880 /// `set_scope_arena` on the source `CodeGraph` do not affect this view.
1881 #[inline]
1882 #[must_use]
1883 pub fn scope_arena(&self) -> &ScopeArena {
1884 &self.scope_arena
1885 }
1886
1887 /// Returns a reference to the alias table at snapshot time.
1888 ///
1889 /// Participates in MVCC: the snapshot holds an `Arc` clone of the table
1890 /// as it existed when `snapshot()` was called. Subsequent calls to
1891 /// `set_alias_table` on the source `CodeGraph` do not affect this view.
1892 #[inline]
1893 #[must_use]
1894 pub fn alias_table(&self) -> &AliasTable {
1895 &self.alias_table
1896 }
1897
1898 /// Returns a reference to the shadow table at snapshot time.
1899 ///
1900 /// Participates in MVCC: the snapshot holds an `Arc` clone of the table
1901 /// as it existed when `snapshot()` was called. Subsequent calls to
1902 /// `set_shadow_table` on the source `CodeGraph` do not affect this view.
1903 #[inline]
1904 #[must_use]
1905 pub fn shadow_table(&self) -> &ShadowTable {
1906 &self.shadow_table
1907 }
1908
1909 /// Returns a reference to the scope provenance store at snapshot time.
1910 ///
1911 /// Participates in MVCC: the snapshot holds an `Arc` clone of the store
1912 /// as it existed when `snapshot()` was called. Subsequent calls to
1913 /// `set_scope_provenance_store` on the source `CodeGraph` do not affect
1914 /// this view.
1915 #[inline]
1916 #[must_use]
1917 pub fn scope_provenance_store(&self) -> &ScopeProvenanceStore {
1918 &self.scope_provenance_store
1919 }
1920
1921 /// Looks up scope provenance by `ScopeId` at snapshot time.
1922 ///
1923 /// Returns `None` if the slot is out of range, vacant, or the stored
1924 /// generation does not match (stale handle).
1925 #[inline]
1926 #[must_use]
1927 pub fn scope_provenance(&self, id: ScopeId) -> Option<&ScopeProvenance> {
1928 self.scope_provenance_store.lookup(id)
1929 }
1930
1931 /// Looks up the live `ScopeId` for a stable scope identity at snapshot time.
1932 ///
1933 /// Returns `None` if no provenance record is registered for that stable id.
1934 #[inline]
1935 #[must_use]
1936 pub fn scope_by_stable_id(&self, stable: ScopeStableId) -> Option<ScopeId> {
1937 self.scope_provenance_store.scope_by_stable_id(stable)
1938 }
1939
1940 /// Returns a reference to the file segment table at snapshot time.
1941 #[inline]
1942 #[must_use]
1943 pub fn file_segments(&self) -> &FileSegmentTable {
1944 &self.file_segments
1945 }
1946
1947 /// Returns the epoch at which this snapshot was taken.
1948 ///
1949 /// This can be compared against the current graph epoch to
1950 /// detect if the graph has changed since the snapshot.
1951 #[inline]
1952 #[must_use]
1953 pub fn epoch(&self) -> u64 {
1954 self.epoch
1955 }
1956
1957 /// Returns `true` if this snapshot's epoch matches the given epoch.
1958 ///
1959 /// Use this to validate cursors before continuing pagination.
1960 #[inline]
1961 #[must_use]
1962 pub fn epoch_matches(&self, other_epoch: u64) -> bool {
1963 self.epoch == other_epoch
1964 }
1965
1966 // ------------------------------------------------------------------
1967 // Phase 2 binding-plane facade accessor (P2U07).
1968 // ------------------------------------------------------------------
1969
1970 /// Returns a [`BindingPlane`] facade borrowing this snapshot's lifetime.
1971 ///
1972 /// The facade is the stable Phase 2 public API for scope/alias/shadow
1973 /// queries and witness-bearing resolution. It provides a single entry
1974 /// point (`resolve`) that returns both a `BindingResult` and an ordered
1975 /// step trace in a `BindingResolution`.
1976 ///
1977 /// # MVCC note
1978 ///
1979 /// `BindingPlane<'_>` borrows from this snapshot, which is already an
1980 /// MVCC-consistent view of the graph at snapshot time. Callers from
1981 /// `CodeGraph` or `ConcurrentCodeGraph` should follow the two-line
1982 /// pattern so the snapshot lifetime is explicit:
1983 ///
1984 /// ```rust,ignore
1985 /// // CodeGraph caller:
1986 /// let snapshot = graph.snapshot();
1987 /// let plane = snapshot.binding_plane();
1988 ///
1989 /// // ConcurrentCodeGraph caller:
1990 /// let read_guard = concurrent.read();
1991 /// let snapshot = read_guard.snapshot();
1992 /// let plane = snapshot.binding_plane();
1993 /// ```
1994 #[inline]
1995 #[must_use]
1996 pub fn binding_plane(&self) -> crate::graph::unified::bind::plane::BindingPlane<'_> {
1997 crate::graph::unified::bind::plane::BindingPlane::new(self)
1998 }
1999
2000 // ============================================================================
2001 // Query Methods
2002 // ============================================================================
2003
2004 /// Finds nodes matching a pattern.
2005 ///
2006 /// Performs a simple substring match on node names and qualified names.
2007 /// Returns all matching node IDs.
2008 ///
2009 /// **Synthetic suppression (`C_SUPPRESS`):** synthetic placeholder
2010 /// nodes — internal scaffolding the language plugins emit for
2011 /// binding-plane and scope analysis (e.g. the Go plugin's
2012 /// `<field:operand.field>` field-access shadows and the
2013 /// `<ident>@<offset>` per-binding-site Variable nodes from the
2014 /// local-scope resolver) — are filtered out by default. Internal
2015 /// callers that need to reach these nodes (binding plane, scope /
2016 /// alias / shadow analysis) use
2017 /// [`Self::find_by_pattern_with_options`] with
2018 /// `include_synthetic = true`.
2019 ///
2020 /// # Performance
2021 ///
2022 /// Optimized to iterate over unique strings in the interner (smaller set)
2023 /// rather than all nodes in the arena.
2024 ///
2025 /// # Arguments
2026 ///
2027 /// * `pattern` - The pattern to match (substring search)
2028 ///
2029 /// # Returns
2030 ///
2031 /// A vector of `NodeIds` for all matching nodes (synthetic
2032 /// placeholders excluded).
2033 #[must_use]
2034 pub fn find_by_pattern(&self, pattern: &str) -> Vec<crate::graph::unified::node::NodeId> {
2035 self.find_by_pattern_with_options(pattern, false)
2036 }
2037
2038 /// Finds nodes matching a pattern with explicit control over synthetic
2039 /// placeholder visibility.
2040 ///
2041 /// `include_synthetic = false` is the default surface used by every
2042 /// user-facing caller (CLI `search`, MCP `semantic_search` /
2043 /// `pattern_search` / `relation_query`, etc.). Synthetic
2044 /// placeholders are suppressed via two parallel checks that must
2045 /// agree:
2046 ///
2047 /// 1. The authoritative `NodeFlags::SYNTHETIC` bit on the
2048 /// metadata store
2049 /// ([`crate::graph::unified::storage::metadata::NodeMetadataStore::is_synthetic`]).
2050 /// 2. The structural name-shape fallback
2051 /// ([`crate::graph::unified::storage::arena::NodeEntry::is_synthetic_placeholder_name`])
2052 /// for V10 snapshots written before the synthetic bit existed
2053 /// and for cross-file unification losers that retained their
2054 /// name but lost their metadata entry.
2055 ///
2056 /// Either check matching is sufficient to suppress the node. The
2057 /// design lives in `docs/development/public-issue-triage/`
2058 /// under the `C_SUPPRESS` unit; see also the rationale in
2059 /// [`crate::graph::unified::storage::metadata::NodeFlags::SYNTHETIC`].
2060 ///
2061 /// `include_synthetic = true` is **internal-only**. The binding
2062 /// plane, scope resolver, and rebuild's coverage gate use this
2063 /// path to reach synthetic nodes for their structural integrity
2064 /// checks. **No CLI / MCP surface should ever pass `true`.**
2065 #[must_use]
2066 pub fn find_by_pattern_with_options(
2067 &self,
2068 pattern: &str,
2069 include_synthetic: bool,
2070 ) -> Vec<crate::graph::unified::node::NodeId> {
2071 let mut matches = Vec::new();
2072
2073 // 1. Scan unique strings in interner for matches
2074 for (str_id, s) in self.strings.iter() {
2075 if s.contains(pattern) {
2076 // 2. If string matches, look up all nodes with this name
2077 // Check qualified name index
2078 matches.extend_from_slice(self.indices.by_qualified_name(str_id));
2079 // Check simple name index
2080 matches.extend_from_slice(self.indices.by_name(str_id));
2081 }
2082 }
2083
2084 // Deduplicate matches (a node might match both qualified and simple name)
2085 matches.sort_unstable();
2086 matches.dedup();
2087
2088 if !include_synthetic {
2089 matches.retain(|&node_id| !self.is_node_synthetic(node_id));
2090 }
2091
2092 matches
2093 }
2094
2095 /// Finds nodes whose interned simple **or** qualified name equals `name`,
2096 /// accepting dot- and Ruby-`#` qualified display form as a fallback for
2097 /// graph-canonical `::` qualified names.
2098 ///
2099 /// This is the canonical surface for **exact-name** lookups —
2100 /// shared by the CLI `--exact <pattern>` shorthand
2101 /// (`sqry-cli/src/commands/search.rs::run_regular_search`) and the
2102 /// structural query planner's `name:` predicate
2103 /// (`sqry-db/src/planner/parse.rs`,
2104 /// `sqry-db/src/planner/execute.rs`). Both surfaces are
2105 /// contract-bound (DAG `B1_ALIGN`) to return the same set against
2106 /// any fixture: the CLI calls this method directly, while the
2107 /// planner uses the same interner + by-name index pair internally
2108 /// when scanning, then applies the same synthetic filter.
2109 ///
2110 /// **Synthetic suppression.** Synthetic placeholder nodes
2111 /// (Go-plugin `<field:operand.field>` shadows and
2112 /// `<ident>@<offset>` per-binding-site Variables; see
2113 /// [`Self::find_by_pattern_with_options`] for the full taxonomy)
2114 /// are excluded via [`Self::is_node_synthetic`]. There is **no**
2115 /// `include_synthetic = true` variant for the exact-match surface
2116 /// because the synthetic name shapes the structural fallback
2117 /// recognises (`<…>`, `…@<offset>`) cannot equal a user-typed
2118 /// name byte-for-byte; the metadata-bit channel is the only
2119 /// realistic leak vector and it is suppressed unconditionally.
2120 ///
2121 /// **Display fallback.** Exact lookup checks the literal input. When the
2122 /// input is qualified, language-aware display candidates win over raw
2123 /// canonical matches. This keeps native Rust `identity::T` from also
2124 /// returning a TypeScript type parameter whose internal canonical form is
2125 /// `identity::T` but whose display form is `identity.T`. If neither
2126 /// display nor literal lookup finds candidates, dot- and Ruby-`#`
2127 /// qualified inputs also check the graph-canonical `::` rewrite.
2128 ///
2129 /// # Performance
2130 ///
2131 /// `O(1)` interner lookup + `O(matches)` filter. If `name` is not
2132 /// interned the resolver still tries a native-display to graph-canonical
2133 /// `::` fallback for user-facing qualified names before returning empty.
2134 ///
2135 /// # Arguments
2136 ///
2137 /// * `name` - The exact name to look up (no glob, no regex).
2138 ///
2139 /// # Returns
2140 ///
2141 /// Sorted, deduplicated `NodeId`s for every non-synthetic node
2142 /// whose `entry.name`, `entry.qualified_name`, or language-aware display
2143 /// name equals `name`, or matches for the graph-canonical `::` rewrite
2144 /// when the user supplied a dot- or Ruby-`#` qualified name that had no
2145 /// literal or display candidates.
2146 #[must_use]
2147 pub fn find_by_exact_name(&self, name: &str) -> Vec<crate::graph::unified::node::NodeId> {
2148 let is_qualified = name.contains('.') || name.contains('#') || name.contains("::");
2149 if !is_qualified {
2150 // Bare name lookup: the interned `by_name` index covers
2151 // every language and is O(1); no display scan is needed.
2152 return self.find_by_exact_interned_name(name);
2153 }
2154 // Qualified name: each plugin stores its native form
2155 // (PHP `Ledger.promotedField`, Rust `Ledger::promotedField`,
2156 // Ruby `Ledger#promotedField`). Scan computed display names so
2157 // a single dotted user query resolves to all language matches,
2158 // then fall back to the interned form (and the graph-canonical
2159 // `::` rewrite) when display yields nothing.
2160 let mut exact_matches = self.find_by_exact_display_name(name);
2161 if exact_matches.is_empty() {
2162 exact_matches = self.find_by_exact_interned_name(name);
2163 if exact_matches.is_empty() && !name.contains("::") {
2164 let canonical = name.replace(['.', '#'], "::");
2165 exact_matches.extend(self.find_by_exact_interned_name(&canonical));
2166 exact_matches.sort_unstable();
2167 exact_matches.dedup();
2168 }
2169 }
2170 exact_matches
2171 }
2172
2173 fn find_by_exact_display_name(&self, name: &str) -> Vec<crate::graph::unified::node::NodeId> {
2174 let mut matches = self
2175 .iter_nodes()
2176 .filter(|(node_id, _)| !self.is_node_synthetic(*node_id))
2177 .filter_map(|(node_id, entry)| {
2178 let qualified = entry
2179 .qualified_name
2180 .and_then(|sid| self.strings.resolve(sid))?;
2181 let display = self.files.language_for_file(entry.file).map_or_else(
2182 || qualified.to_string(),
2183 |language| {
2184 display_graph_qualified_name(
2185 language,
2186 qualified.as_ref(),
2187 entry.kind,
2188 entry.is_static,
2189 )
2190 },
2191 );
2192 (display == name).then_some(node_id)
2193 })
2194 .collect::<Vec<_>>();
2195 matches.sort_unstable();
2196 matches.dedup();
2197 matches
2198 }
2199
2200 fn find_by_exact_interned_name(&self, name: &str) -> Vec<crate::graph::unified::node::NodeId> {
2201 let Some(str_id) = self.strings.get(name) else {
2202 return Vec::new();
2203 };
2204
2205 let mut matches: Vec<crate::graph::unified::node::NodeId> = Vec::new();
2206 matches.extend_from_slice(self.indices.by_name(str_id));
2207 matches.extend_from_slice(self.indices.by_qualified_name(str_id));
2208 matches.sort_unstable();
2209 matches.dedup();
2210 matches.retain(|&node_id| !self.is_node_synthetic(node_id));
2211 matches
2212 }
2213
2214 /// Returns `true` if the node should be treated as a synthetic
2215 /// placeholder for user-facing surfaces.
2216 ///
2217 /// Combines the metadata-store flag and the structural name-shape
2218 /// fallback (see [`Self::find_by_pattern_with_options`] for the
2219 /// full rationale). Returns `false` for missing nodes (an unknown
2220 /// `NodeId` is not "synthetic" — it is "not present").
2221 #[must_use]
2222 pub fn is_node_synthetic(&self, node_id: crate::graph::unified::node::NodeId) -> bool {
2223 // Authoritative check: metadata-store bit (NodeFlags::SYNTHETIC).
2224 if self.macro_metadata.is_synthetic(node_id) {
2225 return true;
2226 }
2227 // Structural fallback: name shape recognised as synthetic.
2228 // Required for V10 snapshots written before the bit existed,
2229 // for unification losers that lost their metadata entry, and
2230 // as defence-in-depth against future plugins forgetting to
2231 // flip the bit.
2232 let Some(entry) = self.nodes.get(node_id) else {
2233 return false;
2234 };
2235 if entry.is_unified_loser() {
2236 // Already invisible for other reasons; do not also flag as synthetic.
2237 return false;
2238 }
2239 let Some(name) = self.strings.resolve(entry.name) else {
2240 return false;
2241 };
2242 crate::graph::unified::storage::arena::NodeEntry::is_synthetic_placeholder_name(
2243 name.as_ref(),
2244 )
2245 }
2246
2247 /// Gets all callees of a node (functions called by this node).
2248 ///
2249 /// Queries the forward edge store for all Calls edges from this node.
2250 ///
2251 /// # Arguments
2252 ///
2253 /// * `node` - The node ID to query
2254 ///
2255 /// # Returns
2256 ///
2257 /// A vector of `NodeIds` representing functions called by this node.
2258 #[must_use]
2259 pub fn get_callees(
2260 &self,
2261 node: crate::graph::unified::node::NodeId,
2262 ) -> Vec<crate::graph::unified::node::NodeId> {
2263 use crate::graph::unified::edge::EdgeKind;
2264
2265 self.edges
2266 .edges_from(node)
2267 .into_iter()
2268 .filter(|edge| matches!(edge.kind, EdgeKind::Calls { .. }))
2269 .map(|edge| edge.target)
2270 .collect()
2271 }
2272
2273 /// Gets all callers of a node (functions that call this node).
2274 ///
2275 /// Queries the reverse edge store for all Calls edges to this node.
2276 ///
2277 /// # Arguments
2278 ///
2279 /// * `node` - The node ID to query
2280 ///
2281 /// # Returns
2282 ///
2283 /// A vector of `NodeIds` representing functions that call this node.
2284 #[must_use]
2285 pub fn get_callers(
2286 &self,
2287 node: crate::graph::unified::node::NodeId,
2288 ) -> Vec<crate::graph::unified::node::NodeId> {
2289 use crate::graph::unified::edge::EdgeKind;
2290
2291 self.edges
2292 .edges_to(node)
2293 .into_iter()
2294 .filter(|edge| matches!(edge.kind, EdgeKind::Calls { .. }))
2295 .map(|edge| edge.source)
2296 .collect()
2297 }
2298
2299 /// Iterates over all nodes in the graph.
2300 ///
2301 /// Returns an iterator yielding (`NodeId`, &`NodeEntry`) pairs for all
2302 /// occupied slots in the arena.
2303 ///
2304 /// # Returns
2305 ///
2306 /// An iterator over (`NodeId`, &`NodeEntry`) pairs.
2307 pub fn iter_nodes(
2308 &self,
2309 ) -> impl Iterator<
2310 Item = (
2311 crate::graph::unified::node::NodeId,
2312 &crate::graph::unified::storage::arena::NodeEntry,
2313 ),
2314 > {
2315 self.nodes.iter()
2316 }
2317
2318 /// Iterates over all edges in the graph.
2319 ///
2320 /// Returns an iterator yielding (source, target, `EdgeKind`) tuples for
2321 /// all edges in the forward edge store.
2322 ///
2323 /// # Returns
2324 ///
2325 /// An iterator over edge tuples.
2326 pub fn iter_edges(
2327 &self,
2328 ) -> impl Iterator<
2329 Item = (
2330 crate::graph::unified::node::NodeId,
2331 crate::graph::unified::node::NodeId,
2332 crate::graph::unified::edge::EdgeKind,
2333 ),
2334 > + '_ {
2335 // Iterate over all nodes in the arena and get their outgoing edges
2336 self.nodes.iter().flat_map(move |(node_id, _entry)| {
2337 // Get all edges from this node
2338 self.edges
2339 .edges_from(node_id)
2340 .into_iter()
2341 .map(move |edge| (node_id, edge.target, edge.kind))
2342 })
2343 }
2344
2345 /// Gets a node entry by ID.
2346 ///
2347 /// Returns a reference to the `NodeEntry` if the ID is valid, or None
2348 /// if the ID is invalid or stale.
2349 ///
2350 /// # Arguments
2351 ///
2352 /// * `id` - The node ID to look up
2353 ///
2354 /// # Returns
2355 ///
2356 /// A reference to the `NodeEntry`, or None if not found.
2357 #[must_use]
2358 pub fn get_node(
2359 &self,
2360 id: crate::graph::unified::node::NodeId,
2361 ) -> Option<&crate::graph::unified::storage::arena::NodeEntry> {
2362 self.nodes.get(id)
2363 }
2364}
2365
2366impl fmt::Debug for GraphSnapshot {
2367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2368 f.debug_struct("GraphSnapshot")
2369 .field("nodes", &self.nodes.len())
2370 .field("epoch", &self.epoch)
2371 .finish_non_exhaustive()
2372 }
2373}
2374
2375/// Read-only accessor trait shared by [`CodeGraph`] and [`GraphSnapshot`].
2376///
2377/// This lets helpers that only *read* graph state (name-matching, relation
2378/// traversal, reference lookups) be written once and called from both the
2379/// live `CodeGraph` path in `sqry-core::query::executor::graph_eval` and
2380/// the snapshot-based path in `sqry-db::queries::*`. No mutation is exposed.
2381pub trait GraphAccess {
2382 /// Returns the node arena (read-only).
2383 fn nodes(&self) -> &NodeArena;
2384 /// Returns the bidirectional edge store (read-only).
2385 fn edges(&self) -> &BidirectionalEdgeStore;
2386 /// Returns the string interner (read-only).
2387 fn strings(&self) -> &StringInterner;
2388 /// Returns the file registry (read-only).
2389 fn files(&self) -> &FileRegistry;
2390 /// Returns the auxiliary indices (read-only).
2391 fn indices(&self) -> &AuxiliaryIndices;
2392}
2393
2394impl GraphAccess for CodeGraph {
2395 #[inline]
2396 fn nodes(&self) -> &NodeArena {
2397 CodeGraph::nodes(self)
2398 }
2399 #[inline]
2400 fn edges(&self) -> &BidirectionalEdgeStore {
2401 CodeGraph::edges(self)
2402 }
2403 #[inline]
2404 fn strings(&self) -> &StringInterner {
2405 CodeGraph::strings(self)
2406 }
2407 #[inline]
2408 fn files(&self) -> &FileRegistry {
2409 CodeGraph::files(self)
2410 }
2411 #[inline]
2412 fn indices(&self) -> &AuxiliaryIndices {
2413 CodeGraph::indices(self)
2414 }
2415}
2416
2417impl GraphAccess for GraphSnapshot {
2418 #[inline]
2419 fn nodes(&self) -> &NodeArena {
2420 GraphSnapshot::nodes(self)
2421 }
2422 #[inline]
2423 fn edges(&self) -> &BidirectionalEdgeStore {
2424 GraphSnapshot::edges(self)
2425 }
2426 #[inline]
2427 fn strings(&self) -> &StringInterner {
2428 GraphSnapshot::strings(self)
2429 }
2430 #[inline]
2431 fn files(&self) -> &FileRegistry {
2432 GraphSnapshot::files(self)
2433 }
2434 #[inline]
2435 fn indices(&self) -> &AuxiliaryIndices {
2436 GraphSnapshot::indices(self)
2437 }
2438}
2439
2440#[cfg(test)]
2441mod tests {
2442 use super::*;
2443 use crate::graph::unified::{
2444 FileScope, NodeId, ResolutionMode, SymbolCandidateOutcome, SymbolQuery,
2445 SymbolResolutionOutcome,
2446 };
2447
2448 fn resolve_symbol_strict(snapshot: &GraphSnapshot, symbol: &str) -> Option<NodeId> {
2449 match snapshot.resolve_symbol(&SymbolQuery {
2450 symbol,
2451 file_scope: FileScope::Any,
2452 mode: ResolutionMode::Strict,
2453 }) {
2454 SymbolResolutionOutcome::Resolved(node_id) => Some(node_id),
2455 SymbolResolutionOutcome::NotFound
2456 | SymbolResolutionOutcome::FileNotIndexed
2457 | SymbolResolutionOutcome::Ambiguous(_) => None,
2458 }
2459 }
2460
2461 fn candidate_nodes(snapshot: &GraphSnapshot, symbol: &str) -> Vec<NodeId> {
2462 match snapshot.find_symbol_candidates(&SymbolQuery {
2463 symbol,
2464 file_scope: FileScope::Any,
2465 mode: ResolutionMode::AllowSuffixCandidates,
2466 }) {
2467 SymbolCandidateOutcome::Candidates(candidates) => candidates,
2468 SymbolCandidateOutcome::NotFound | SymbolCandidateOutcome::FileNotIndexed => Vec::new(),
2469 }
2470 }
2471
2472 #[test]
2473 fn test_code_graph_new() {
2474 let graph = CodeGraph::new();
2475 assert_eq!(graph.epoch(), 0);
2476 assert_eq!(graph.nodes().len(), 0);
2477 }
2478
2479 #[test]
2480 fn test_code_graph_default() {
2481 let graph = CodeGraph::default();
2482 assert_eq!(graph.epoch(), 0);
2483 }
2484
2485 #[test]
2486 fn test_code_graph_snapshot() {
2487 let graph = CodeGraph::new();
2488 let snapshot = graph.snapshot();
2489 assert_eq!(snapshot.epoch(), 0);
2490 assert_eq!(snapshot.nodes().len(), 0);
2491 }
2492
2493 #[test]
2494 fn test_code_graph_bump_epoch() {
2495 let mut graph = CodeGraph::new();
2496 assert_eq!(graph.epoch(), 0);
2497 assert_eq!(graph.bump_epoch(), 1);
2498 assert_eq!(graph.epoch(), 1);
2499 assert_eq!(graph.bump_epoch(), 2);
2500 assert_eq!(graph.epoch(), 2);
2501 }
2502
2503 #[test]
2504 fn test_code_graph_set_epoch() {
2505 let mut graph = CodeGraph::new();
2506 graph.set_epoch(42);
2507 assert_eq!(graph.epoch(), 42);
2508 }
2509
2510 #[test]
2511 fn test_code_graph_from_components() {
2512 let nodes = NodeArena::new();
2513 let edges = BidirectionalEdgeStore::new();
2514 let strings = StringInterner::new();
2515 let files = FileRegistry::new();
2516 let indices = AuxiliaryIndices::new();
2517 let macro_metadata = NodeMetadataStore::new();
2518
2519 let graph =
2520 CodeGraph::from_components(nodes, edges, strings, files, indices, macro_metadata);
2521 assert_eq!(graph.epoch(), 0);
2522 }
2523
2524 #[test]
2525 fn test_code_graph_mut_accessors() {
2526 let mut graph = CodeGraph::new();
2527
2528 // Access mutable references - should not panic
2529 let _nodes = graph.nodes_mut();
2530 let _edges = graph.edges_mut();
2531 let _strings = graph.strings_mut();
2532 let _files = graph.files_mut();
2533 let _indices = graph.indices_mut();
2534 }
2535
2536 #[test]
2537 fn test_code_graph_snapshot_isolation() {
2538 let mut graph = CodeGraph::new();
2539 let snapshot1 = graph.snapshot();
2540
2541 // Mutate the graph
2542 graph.bump_epoch();
2543
2544 let snapshot2 = graph.snapshot();
2545
2546 // Snapshots should have different epochs
2547 assert_eq!(snapshot1.epoch(), 0);
2548 assert_eq!(snapshot2.epoch(), 1);
2549 }
2550
2551 #[test]
2552 fn test_code_graph_debug() {
2553 let graph = CodeGraph::new();
2554 let debug_str = format!("{graph:?}");
2555 assert!(debug_str.contains("CodeGraph"));
2556 assert!(debug_str.contains("epoch"));
2557 }
2558
2559 /// Exact-byte regression for the iter2 fix of CodeGraph.confidence
2560 /// accounting: adding a `ConfidenceMetadata` entry with known inner
2561 /// Vec<String> capacities must increase `heap_bytes()` by exactly the sum
2562 /// of those capacities plus Vec<String> slot overhead.
2563 #[test]
2564 fn test_codegraph_heap_bytes_counts_confidence_inner_strings() {
2565 let mut graph = CodeGraph::new();
2566 // Seed one confidence entry so the HashMap has non-zero capacity;
2567 // reserve slack so the next insert cannot rehash.
2568 graph.set_confidence({
2569 let mut m = HashMap::with_capacity(8);
2570 m.insert("seed".to_string(), ConfidenceMetadata::default());
2571 m
2572 });
2573 let before = graph.heap_bytes();
2574 let before_cap = graph.confidence.capacity();
2575
2576 let lim1 = String::from("no type inference");
2577 let lim2 = String::from("no generic specialization");
2578 let feat1 = String::from("rust-analyzer");
2579 let l1 = lim1.capacity();
2580 let l2 = lim2.capacity();
2581 let f1 = feat1.capacity();
2582
2583 let limitations = vec![lim1, lim2];
2584 let lim_vec_cap = limitations.capacity();
2585
2586 let unavailable_features = vec![feat1];
2587 let feat_vec_cap = unavailable_features.capacity();
2588
2589 let key = String::from("rust");
2590 let key_cap = key.capacity();
2591 graph.confidence.insert(
2592 key,
2593 ConfidenceMetadata {
2594 limitations,
2595 unavailable_features,
2596 ..Default::default()
2597 },
2598 );
2599 assert_eq!(
2600 graph.confidence.capacity(),
2601 before_cap,
2602 "prerequisite: confidence HashMap must not rehash during the test insert",
2603 );
2604
2605 let after = graph.heap_bytes();
2606 let expected_inner = key_cap
2607 + lim_vec_cap * std::mem::size_of::<String>()
2608 + l1
2609 + l2
2610 + feat_vec_cap * std::mem::size_of::<String>()
2611 + f1;
2612 assert_eq!(
2613 after - before,
2614 expected_inner,
2615 "CodeGraph::heap_bytes must count ConfidenceMetadata inner Vec<String> capacity exactly",
2616 );
2617 }
2618
2619 #[test]
2620 fn test_codegraph_heap_bytes_grows_with_content() {
2621 use crate::graph::unified::node::NodeKind;
2622 use crate::graph::unified::storage::arena::NodeEntry;
2623 use std::path::Path;
2624
2625 // An empty graph reports some heap bytes (FileRegistry seeds index 0
2626 // with `vec![None]`, HashMaps have non-zero base capacity once touched,
2627 // etc.) but the value must be finite and well under the 100 MB cap.
2628 let empty = CodeGraph::new();
2629 let empty_bytes = empty.heap_bytes();
2630 assert!(
2631 empty_bytes < 100 * 1024 * 1024,
2632 "empty graph heap_bytes should be <100 MiB, got {empty_bytes}"
2633 );
2634
2635 let mut graph = CodeGraph::new();
2636 for i in 0..32u32 {
2637 let name = format!("sym_{i}");
2638 let qual = format!("module::sym_{i}");
2639 let file = format!("file_{i}.rs");
2640
2641 let name_id = graph.strings_mut().intern(&name).unwrap();
2642 let qual_id = graph.strings_mut().intern(&qual).unwrap();
2643 let file_id = graph.files_mut().register(Path::new(&file)).unwrap();
2644
2645 let entry =
2646 NodeEntry::new(NodeKind::Function, name_id, file_id).with_qualified_name(qual_id);
2647 let node_id = graph.nodes_mut().alloc(entry).unwrap();
2648 graph
2649 .indices_mut()
2650 .add(node_id, NodeKind::Function, name_id, Some(qual_id), file_id);
2651 }
2652
2653 let populated_bytes = graph.heap_bytes();
2654 assert!(
2655 populated_bytes > 0,
2656 "populated graph should report nonzero heap bytes"
2657 );
2658 assert!(
2659 populated_bytes > empty_bytes,
2660 "populated graph ({populated_bytes}) should exceed empty graph ({empty_bytes})"
2661 );
2662 assert!(
2663 populated_bytes < 100 * 1024 * 1024,
2664 "test graph heap_bytes should be <100 MiB, got {populated_bytes}"
2665 );
2666 }
2667
2668 #[test]
2669 fn test_concurrent_code_graph_new() {
2670 let graph = ConcurrentCodeGraph::new();
2671 assert_eq!(graph.epoch(), 0);
2672 }
2673
2674 #[test]
2675 fn test_concurrent_code_graph_default() {
2676 let graph = ConcurrentCodeGraph::default();
2677 assert_eq!(graph.epoch(), 0);
2678 }
2679
2680 #[test]
2681 fn test_concurrent_code_graph_from_graph() {
2682 let mut inner = CodeGraph::new();
2683 inner.set_epoch(10);
2684 let graph = ConcurrentCodeGraph::from_graph(inner);
2685 assert_eq!(graph.epoch(), 10);
2686 }
2687
2688 #[test]
2689 fn test_concurrent_code_graph_read() {
2690 let graph = ConcurrentCodeGraph::new();
2691 let guard = graph.read();
2692 assert_eq!(guard.epoch(), 0);
2693 assert_eq!(guard.nodes().len(), 0);
2694 }
2695
2696 #[test]
2697 fn test_concurrent_code_graph_write_increments_epoch() {
2698 let graph = ConcurrentCodeGraph::new();
2699 assert_eq!(graph.epoch(), 0);
2700
2701 {
2702 let guard = graph.write();
2703 assert_eq!(guard.epoch(), 1);
2704 }
2705
2706 assert_eq!(graph.epoch(), 1);
2707
2708 {
2709 let _guard = graph.write();
2710 }
2711
2712 assert_eq!(graph.epoch(), 2);
2713 }
2714
2715 #[test]
2716 fn test_concurrent_code_graph_snapshot() {
2717 let graph = ConcurrentCodeGraph::new();
2718
2719 {
2720 let _guard = graph.write();
2721 }
2722
2723 let snapshot = graph.snapshot();
2724 assert_eq!(snapshot.epoch(), 1);
2725 }
2726
2727 #[test]
2728 fn test_concurrent_code_graph_try_read() {
2729 let graph = ConcurrentCodeGraph::new();
2730 let guard = graph.try_read();
2731 assert!(guard.is_some());
2732 }
2733
2734 #[test]
2735 fn test_concurrent_code_graph_try_write() {
2736 let graph = ConcurrentCodeGraph::new();
2737 let guard = graph.try_write();
2738 assert!(guard.is_some());
2739 assert_eq!(graph.epoch(), 1);
2740 }
2741
2742 #[test]
2743 fn test_concurrent_code_graph_debug() {
2744 let graph = ConcurrentCodeGraph::new();
2745 let debug_str = format!("{graph:?}");
2746 assert!(debug_str.contains("ConcurrentCodeGraph"));
2747 assert!(debug_str.contains("epoch"));
2748 }
2749
2750 #[test]
2751 fn test_graph_snapshot_accessors() {
2752 let graph = CodeGraph::new();
2753 let snapshot = graph.snapshot();
2754
2755 // All accessors should work
2756 let _nodes = snapshot.nodes();
2757 let _edges = snapshot.edges();
2758 let _strings = snapshot.strings();
2759 let _files = snapshot.files();
2760 let _indices = snapshot.indices();
2761 let _epoch = snapshot.epoch();
2762 }
2763
2764 #[test]
2765 fn test_graph_snapshot_epoch_matches() {
2766 let graph = CodeGraph::new();
2767 let snapshot = graph.snapshot();
2768
2769 assert!(snapshot.epoch_matches(0));
2770 assert!(!snapshot.epoch_matches(1));
2771 }
2772
2773 #[test]
2774 fn test_graph_snapshot_clone() {
2775 let graph = CodeGraph::new();
2776 let snapshot1 = graph.snapshot();
2777 let snapshot2 = snapshot1.clone();
2778
2779 assert_eq!(snapshot1.epoch(), snapshot2.epoch());
2780 }
2781
2782 #[test]
2783 fn test_graph_snapshot_debug() {
2784 let graph = CodeGraph::new();
2785 let snapshot = graph.snapshot();
2786 let debug_str = format!("{snapshot:?}");
2787 assert!(debug_str.contains("GraphSnapshot"));
2788 assert!(debug_str.contains("epoch"));
2789 }
2790
2791 #[test]
2792 fn test_multiple_readers() {
2793 let graph = ConcurrentCodeGraph::new();
2794
2795 // Multiple readers should be able to acquire locks simultaneously
2796 let guard1 = graph.read();
2797 let guard2 = graph.read();
2798 let guard3 = graph.read();
2799
2800 assert_eq!(guard1.epoch(), 0);
2801 assert_eq!(guard2.epoch(), 0);
2802 assert_eq!(guard3.epoch(), 0);
2803 }
2804
2805 #[test]
2806 fn test_code_graph_clone() {
2807 let mut graph = CodeGraph::new();
2808 graph.bump_epoch();
2809
2810 let cloned = graph.clone();
2811 assert_eq!(cloned.epoch(), 1);
2812 }
2813
2814 #[test]
2815 fn test_epoch_wrapping() {
2816 let mut graph = CodeGraph::new();
2817 graph.set_epoch(u64::MAX);
2818 let new_epoch = graph.bump_epoch();
2819 assert_eq!(new_epoch, 0); // Should wrap around
2820 }
2821
2822 // ============================================================================
2823 // Query method tests
2824 // ============================================================================
2825
2826 #[test]
2827 fn test_snapshot_resolve_symbol() {
2828 use crate::graph::unified::node::NodeKind;
2829 use crate::graph::unified::storage::arena::NodeEntry;
2830 use std::path::Path;
2831
2832 let mut graph = CodeGraph::new();
2833
2834 // Add some nodes with qualified names
2835 let name_id = graph.strings_mut().intern("test_func").unwrap();
2836 let qual_name_id = graph.strings_mut().intern("module::test_func").unwrap();
2837 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
2838
2839 let entry =
2840 NodeEntry::new(NodeKind::Function, name_id, file_id).with_qualified_name(qual_name_id);
2841
2842 let node_id = graph.nodes_mut().alloc(entry).unwrap();
2843 graph.indices_mut().add(
2844 node_id,
2845 NodeKind::Function,
2846 name_id,
2847 Some(qual_name_id),
2848 file_id,
2849 );
2850
2851 let snapshot = graph.snapshot();
2852
2853 // Find by qualified name
2854 let found = resolve_symbol_strict(&snapshot, "module::test_func");
2855 assert_eq!(found, Some(node_id));
2856
2857 // Find by exact simple name
2858 let found2 = resolve_symbol_strict(&snapshot, "test_func");
2859 assert_eq!(found2, Some(node_id));
2860
2861 // Not found
2862 assert!(resolve_symbol_strict(&snapshot, "nonexistent").is_none());
2863 }
2864
2865 #[test]
2866 fn test_snapshot_find_by_pattern() {
2867 use crate::graph::unified::node::NodeKind;
2868 use crate::graph::unified::storage::arena::NodeEntry;
2869 use std::path::Path;
2870
2871 let mut graph = CodeGraph::new();
2872
2873 // Add nodes with different names
2874 let name1 = graph.strings_mut().intern("foo_bar").unwrap();
2875 let name2 = graph.strings_mut().intern("baz_bar").unwrap();
2876 let name3 = graph.strings_mut().intern("qux_test").unwrap();
2877 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
2878
2879 let node1 = graph
2880 .nodes_mut()
2881 .alloc(NodeEntry::new(NodeKind::Function, name1, file_id))
2882 .unwrap();
2883 let node2 = graph
2884 .nodes_mut()
2885 .alloc(NodeEntry::new(NodeKind::Function, name2, file_id))
2886 .unwrap();
2887 let node3 = graph
2888 .nodes_mut()
2889 .alloc(NodeEntry::new(NodeKind::Function, name3, file_id))
2890 .unwrap();
2891
2892 graph
2893 .indices_mut()
2894 .add(node1, NodeKind::Function, name1, None, file_id);
2895 graph
2896 .indices_mut()
2897 .add(node2, NodeKind::Function, name2, None, file_id);
2898 graph
2899 .indices_mut()
2900 .add(node3, NodeKind::Function, name3, None, file_id);
2901
2902 let snapshot = graph.snapshot();
2903
2904 // Find by pattern
2905 let matches = snapshot.find_by_pattern("bar");
2906 assert_eq!(matches.len(), 2);
2907 assert!(matches.contains(&node1));
2908 assert!(matches.contains(&node2));
2909
2910 // Find single match
2911 let matches = snapshot.find_by_pattern("qux");
2912 assert_eq!(matches.len(), 1);
2913 assert_eq!(matches[0], node3);
2914
2915 // No matches
2916 let matches = snapshot.find_by_pattern("nonexistent");
2917 assert!(matches.is_empty());
2918 }
2919
2920 #[test]
2921 fn synthetic_nodes_are_filtered_from_find_by_pattern_default() {
2922 // C_SUPPRESS: synthetic placeholder nodes (Go plugin
2923 // `<field:operand.field>` shadows + `<ident>@<offset>`
2924 // per-binding-site Variables) must NOT surface from
2925 // find_by_pattern, but must still be reachable via
2926 // find_by_pattern_with_options(_, true).
2927 use crate::graph::unified::node::NodeKind;
2928 use crate::graph::unified::storage::arena::NodeEntry;
2929 use std::path::Path;
2930
2931 let mut graph = CodeGraph::new();
2932 let real_property = graph
2933 .strings_mut()
2934 .intern("main.SelectorSource.NeedTags")
2935 .unwrap();
2936 let real_local_var = graph.strings_mut().intern("NeedTags").unwrap();
2937 let synthetic_field = graph
2938 .strings_mut()
2939 .intern("<field:selector.NeedTags>")
2940 .unwrap();
2941 let synthetic_offset_a = graph.strings_mut().intern("NeedTags@469").unwrap();
2942 let synthetic_offset_b = graph.strings_mut().intern("NeedTags@508").unwrap();
2943 let file_id = graph.files_mut().register(Path::new("main.go")).unwrap();
2944
2945 let prop_id = graph
2946 .nodes_mut()
2947 .alloc(NodeEntry::new(NodeKind::Property, real_property, file_id))
2948 .unwrap();
2949 let local_var_id = graph
2950 .nodes_mut()
2951 .alloc(NodeEntry::new(NodeKind::Variable, real_local_var, file_id))
2952 .unwrap();
2953 let syn_field_id = graph
2954 .nodes_mut()
2955 .alloc(NodeEntry::new(NodeKind::Variable, synthetic_field, file_id))
2956 .unwrap();
2957 let syn_a_id = graph
2958 .nodes_mut()
2959 .alloc(NodeEntry::new(
2960 NodeKind::Variable,
2961 synthetic_offset_a,
2962 file_id,
2963 ))
2964 .unwrap();
2965 let syn_b_id = graph
2966 .nodes_mut()
2967 .alloc(NodeEntry::new(
2968 NodeKind::Variable,
2969 synthetic_offset_b,
2970 file_id,
2971 ))
2972 .unwrap();
2973
2974 graph
2975 .indices_mut()
2976 .add(prop_id, NodeKind::Property, real_property, None, file_id);
2977 graph.indices_mut().add(
2978 local_var_id,
2979 NodeKind::Variable,
2980 real_local_var,
2981 None,
2982 file_id,
2983 );
2984 graph.indices_mut().add(
2985 syn_field_id,
2986 NodeKind::Variable,
2987 synthetic_field,
2988 None,
2989 file_id,
2990 );
2991 graph.indices_mut().add(
2992 syn_a_id,
2993 NodeKind::Variable,
2994 synthetic_offset_a,
2995 None,
2996 file_id,
2997 );
2998 graph.indices_mut().add(
2999 syn_b_id,
3000 NodeKind::Variable,
3001 synthetic_offset_b,
3002 None,
3003 file_id,
3004 );
3005
3006 // Flag two of them via the metadata-store bit (the canonical
3007 // Go-plugin emission path) and leave one (`<field:...>`) only
3008 // covered by the structural name-shape fallback to verify both
3009 // recognition channels suppress the leak.
3010 graph.macro_metadata_mut().mark_synthetic(syn_a_id);
3011 graph.macro_metadata_mut().mark_synthetic(syn_b_id);
3012
3013 let snapshot = graph.snapshot();
3014
3015 // Default surface (CLI `search --exact`, MCP, LSP): no synthetics.
3016 let matches = snapshot.find_by_pattern("NeedTags");
3017 assert!(matches.contains(&prop_id), "Property must be surfaced");
3018 assert!(
3019 matches.contains(&local_var_id),
3020 "real local var must be surfaced"
3021 );
3022 assert!(
3023 !matches.contains(&syn_field_id),
3024 "<field:...> synthetic must be suppressed (name-shape fallback)"
3025 );
3026 assert!(
3027 !matches.contains(&syn_a_id),
3028 "NeedTags@469 must be suppressed (metadata bit)"
3029 );
3030 assert!(
3031 !matches.contains(&syn_b_id),
3032 "NeedTags@508 must be suppressed (metadata bit)"
3033 );
3034 assert_eq!(matches.len(), 2, "exactly Property + local var, no leakage");
3035
3036 // Internal include-synthetic surface (binding plane, scope analysis):
3037 // every node remains reachable.
3038 let all_matches = snapshot.find_by_pattern_with_options("NeedTags", true);
3039 assert_eq!(
3040 all_matches.len(),
3041 5,
3042 "include_synthetic surfaces everything"
3043 );
3044 assert!(all_matches.contains(&prop_id));
3045 assert!(all_matches.contains(&local_var_id));
3046 assert!(all_matches.contains(&syn_field_id));
3047 assert!(all_matches.contains(&syn_a_id));
3048 assert!(all_matches.contains(&syn_b_id));
3049
3050 // is_node_synthetic exposed for surface-level filters
3051 // (e.g., MCP semantic_search/relation_query post-filters).
3052 assert!(snapshot.is_node_synthetic(syn_field_id));
3053 assert!(snapshot.is_node_synthetic(syn_a_id));
3054 assert!(snapshot.is_node_synthetic(syn_b_id));
3055 assert!(!snapshot.is_node_synthetic(prop_id));
3056 assert!(!snapshot.is_node_synthetic(local_var_id));
3057 }
3058
3059 #[test]
3060 #[allow(clippy::too_many_lines)]
3061 fn find_by_exact_name_aligns_with_planner_name_predicate() {
3062 // B1_ALIGN: `find_by_exact_name("NeedTags")` is the canonical
3063 // surface for the CLI `--exact NeedTags` shorthand and the
3064 // planner's `name:NeedTags` predicate. Both paths must return
3065 // the same set against this fixture.
3066 use crate::graph::unified::node::NodeKind;
3067 use crate::graph::unified::storage::arena::NodeEntry;
3068 use std::path::Path;
3069
3070 let mut graph = CodeGraph::new();
3071 // Property nodes carry the package-qualified name as
3072 // `entry.name` (Go plugin convention; see `helper.rs`'s
3073 // `semantic_name_for_node_input`).
3074 let property_qname = graph
3075 .strings_mut()
3076 .intern("main.SelectorSource.NeedTags")
3077 .unwrap();
3078 let local_var_name = graph.strings_mut().intern("NeedTags").unwrap();
3079 let synthetic_field_name = graph
3080 .strings_mut()
3081 .intern("<field:selector.NeedTags>")
3082 .unwrap();
3083 let synthetic_offset_name = graph.strings_mut().intern("NeedTags@469").unwrap();
3084 let unrelated_name = graph.strings_mut().intern("NeedTagsHelper").unwrap();
3085 let display_fallback_name = graph.strings_mut().intern("Other").unwrap();
3086 let display_fallback_qname = graph
3087 .strings_mut()
3088 .intern("main::SelectorSource::Other")
3089 .unwrap();
3090 let file_id = graph.files_mut().register(Path::new("main.go")).unwrap();
3091
3092 let prop_id = graph
3093 .nodes_mut()
3094 .alloc(NodeEntry::new(NodeKind::Property, property_qname, file_id))
3095 .unwrap();
3096 let local_var_id = graph
3097 .nodes_mut()
3098 .alloc(NodeEntry::new(NodeKind::Variable, local_var_name, file_id))
3099 .unwrap();
3100 let syn_field_id = graph
3101 .nodes_mut()
3102 .alloc(NodeEntry::new(
3103 NodeKind::Variable,
3104 synthetic_field_name,
3105 file_id,
3106 ))
3107 .unwrap();
3108 let syn_offset_id = graph
3109 .nodes_mut()
3110 .alloc(NodeEntry::new(
3111 NodeKind::Variable,
3112 synthetic_offset_name,
3113 file_id,
3114 ))
3115 .unwrap();
3116 let unrelated_id = graph
3117 .nodes_mut()
3118 .alloc(NodeEntry::new(NodeKind::Function, unrelated_name, file_id))
3119 .unwrap();
3120 let display_fallback_id = graph
3121 .nodes_mut()
3122 .alloc(
3123 NodeEntry::new(NodeKind::Property, display_fallback_name, file_id)
3124 .with_qualified_name(display_fallback_qname),
3125 )
3126 .unwrap();
3127
3128 graph
3129 .indices_mut()
3130 .add(prop_id, NodeKind::Property, property_qname, None, file_id);
3131 graph.indices_mut().add(
3132 local_var_id,
3133 NodeKind::Variable,
3134 local_var_name,
3135 None,
3136 file_id,
3137 );
3138 graph.indices_mut().add(
3139 syn_field_id,
3140 NodeKind::Variable,
3141 synthetic_field_name,
3142 None,
3143 file_id,
3144 );
3145 graph.indices_mut().add(
3146 syn_offset_id,
3147 NodeKind::Variable,
3148 synthetic_offset_name,
3149 None,
3150 file_id,
3151 );
3152 graph.indices_mut().add(
3153 unrelated_id,
3154 NodeKind::Function,
3155 unrelated_name,
3156 None,
3157 file_id,
3158 );
3159 graph.indices_mut().add(
3160 display_fallback_id,
3161 NodeKind::Property,
3162 display_fallback_name,
3163 Some(display_fallback_qname),
3164 file_id,
3165 );
3166
3167 // Mark the offset-suffixed synthetic via the metadata bit so we
3168 // exercise both recognition channels in this fixture.
3169 graph.macro_metadata_mut().mark_synthetic(syn_offset_id);
3170
3171 let snapshot = graph.snapshot();
3172
3173 // Exact-name lookup on "NeedTags" — should pick up only the
3174 // local variable (its `entry.name` is exactly "NeedTags"); it
3175 // must NOT pick up the Property (qualified name contains but
3176 // does not equal "NeedTags") and must NOT pick up either
3177 // synthetic placeholder.
3178 let exact = snapshot.find_by_exact_name("NeedTags");
3179 assert_eq!(
3180 exact,
3181 vec![local_var_id],
3182 "exact match must be byte-for-byte against entry.name / qualified_name and exclude synthetics"
3183 );
3184
3185 // The Property's full qualified name is exact-addressable.
3186 let qualified = snapshot.find_by_exact_name("main.SelectorSource.NeedTags");
3187 assert_eq!(qualified, vec![prop_id]);
3188
3189 // Dot-qualified display form falls back to graph-canonical `::` only
3190 // when the exact dot string was absent.
3191 let display_fallback = snapshot.find_by_exact_name("main.SelectorSource.Other");
3192 assert_eq!(display_fallback, vec![display_fallback_id]);
3193
3194 // Substring-only matches must not surface from exact lookup.
3195 assert!(
3196 snapshot
3197 .find_by_exact_name("NeedTagsHelper")
3198 .contains(&unrelated_id)
3199 );
3200 assert!(
3201 !snapshot
3202 .find_by_exact_name("NeedTags")
3203 .contains(&unrelated_id),
3204 "exact 'NeedTags' must not match 'NeedTagsHelper'"
3205 );
3206
3207 // Unknown name short-circuits to an empty vec without
3208 // scanning any nodes.
3209 assert!(
3210 snapshot
3211 .find_by_exact_name("ThisStringIsNotInterned")
3212 .is_empty()
3213 );
3214 }
3215
3216 #[test]
3217 fn test_snapshot_get_callees() {
3218 use crate::graph::unified::edge::EdgeKind;
3219 use crate::graph::unified::node::NodeKind;
3220 use crate::graph::unified::storage::arena::NodeEntry;
3221 use std::path::Path;
3222
3223 let mut graph = CodeGraph::new();
3224
3225 // Create caller and callee nodes
3226 let caller_name = graph.strings_mut().intern("caller").unwrap();
3227 let callee1_name = graph.strings_mut().intern("callee1").unwrap();
3228 let callee2_name = graph.strings_mut().intern("callee2").unwrap();
3229 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3230
3231 let caller_id = graph
3232 .nodes_mut()
3233 .alloc(NodeEntry::new(NodeKind::Function, caller_name, file_id))
3234 .unwrap();
3235 let callee1_id = graph
3236 .nodes_mut()
3237 .alloc(NodeEntry::new(NodeKind::Function, callee1_name, file_id))
3238 .unwrap();
3239 let callee2_id = graph
3240 .nodes_mut()
3241 .alloc(NodeEntry::new(NodeKind::Function, callee2_name, file_id))
3242 .unwrap();
3243
3244 // Add call edges
3245 graph.edges_mut().add_edge(
3246 caller_id,
3247 callee1_id,
3248 EdgeKind::Calls {
3249 argument_count: 0,
3250 is_async: false,
3251 resolved_via: ResolvedVia::Direct,
3252 },
3253 file_id,
3254 );
3255 graph.edges_mut().add_edge(
3256 caller_id,
3257 callee2_id,
3258 EdgeKind::Calls {
3259 argument_count: 0,
3260 is_async: false,
3261 resolved_via: ResolvedVia::Direct,
3262 },
3263 file_id,
3264 );
3265
3266 let snapshot = graph.snapshot();
3267
3268 // Query callees
3269 let callees = snapshot.get_callees(caller_id);
3270 assert_eq!(callees.len(), 2);
3271 assert!(callees.contains(&callee1_id));
3272 assert!(callees.contains(&callee2_id));
3273
3274 // Node with no callees
3275 let callees = snapshot.get_callees(callee1_id);
3276 assert!(callees.is_empty());
3277 }
3278
3279 #[test]
3280 fn test_snapshot_get_callers() {
3281 use crate::graph::unified::edge::EdgeKind;
3282 use crate::graph::unified::node::NodeKind;
3283 use crate::graph::unified::storage::arena::NodeEntry;
3284 use std::path::Path;
3285
3286 let mut graph = CodeGraph::new();
3287
3288 // Create caller and callee nodes
3289 let caller1_name = graph.strings_mut().intern("caller1").unwrap();
3290 let caller2_name = graph.strings_mut().intern("caller2").unwrap();
3291 let callee_name = graph.strings_mut().intern("callee").unwrap();
3292 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3293
3294 let caller1_id = graph
3295 .nodes_mut()
3296 .alloc(NodeEntry::new(NodeKind::Function, caller1_name, file_id))
3297 .unwrap();
3298 let caller2_id = graph
3299 .nodes_mut()
3300 .alloc(NodeEntry::new(NodeKind::Function, caller2_name, file_id))
3301 .unwrap();
3302 let callee_id = graph
3303 .nodes_mut()
3304 .alloc(NodeEntry::new(NodeKind::Function, callee_name, file_id))
3305 .unwrap();
3306
3307 // Add call edges
3308 graph.edges_mut().add_edge(
3309 caller1_id,
3310 callee_id,
3311 EdgeKind::Calls {
3312 argument_count: 0,
3313 is_async: false,
3314 resolved_via: ResolvedVia::Direct,
3315 },
3316 file_id,
3317 );
3318 graph.edges_mut().add_edge(
3319 caller2_id,
3320 callee_id,
3321 EdgeKind::Calls {
3322 argument_count: 0,
3323 is_async: false,
3324 resolved_via: ResolvedVia::Direct,
3325 },
3326 file_id,
3327 );
3328
3329 let snapshot = graph.snapshot();
3330
3331 // Query callers
3332 let callers = snapshot.get_callers(callee_id);
3333 assert_eq!(callers.len(), 2);
3334 assert!(callers.contains(&caller1_id));
3335 assert!(callers.contains(&caller2_id));
3336
3337 // Node with no callers
3338 let callers = snapshot.get_callers(caller1_id);
3339 assert!(callers.is_empty());
3340 }
3341
3342 #[test]
3343 fn test_snapshot_find_symbol_candidates() {
3344 use crate::graph::unified::node::NodeKind;
3345 use crate::graph::unified::storage::arena::NodeEntry;
3346 use std::path::Path;
3347
3348 let mut graph = CodeGraph::new();
3349
3350 // Add nodes with same symbol name but different qualified names
3351 let symbol_name = graph.strings_mut().intern("test").unwrap();
3352 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3353
3354 let node1 = graph
3355 .nodes_mut()
3356 .alloc(NodeEntry::new(NodeKind::Function, symbol_name, file_id))
3357 .unwrap();
3358 let node2 = graph
3359 .nodes_mut()
3360 .alloc(NodeEntry::new(NodeKind::Method, symbol_name, file_id))
3361 .unwrap();
3362
3363 // Add a different symbol
3364 let other_name = graph.strings_mut().intern("other").unwrap();
3365 let node3 = graph
3366 .nodes_mut()
3367 .alloc(NodeEntry::new(NodeKind::Function, other_name, file_id))
3368 .unwrap();
3369
3370 graph
3371 .indices_mut()
3372 .add(node1, NodeKind::Function, symbol_name, None, file_id);
3373 graph
3374 .indices_mut()
3375 .add(node2, NodeKind::Method, symbol_name, None, file_id);
3376 graph
3377 .indices_mut()
3378 .add(node3, NodeKind::Function, other_name, None, file_id);
3379
3380 let snapshot = graph.snapshot();
3381
3382 // Find by symbol
3383 let matches = candidate_nodes(&snapshot, "test");
3384 assert_eq!(matches.len(), 2);
3385 assert!(matches.contains(&node1));
3386 assert!(matches.contains(&node2));
3387
3388 // Find other symbol
3389 let matches = candidate_nodes(&snapshot, "other");
3390 assert_eq!(matches.len(), 1);
3391 assert_eq!(matches[0], node3);
3392
3393 // No matches
3394 let matches = candidate_nodes(&snapshot, "nonexistent");
3395 assert!(matches.is_empty());
3396 }
3397
3398 #[test]
3399 fn test_snapshot_iter_nodes() {
3400 use crate::graph::unified::node::NodeKind;
3401 use crate::graph::unified::storage::arena::NodeEntry;
3402 use std::path::Path;
3403
3404 let mut graph = CodeGraph::new();
3405
3406 // Add some nodes
3407 let name1 = graph.strings_mut().intern("func1").unwrap();
3408 let name2 = graph.strings_mut().intern("func2").unwrap();
3409 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3410
3411 let node1 = graph
3412 .nodes_mut()
3413 .alloc(NodeEntry::new(NodeKind::Function, name1, file_id))
3414 .unwrap();
3415 let node2 = graph
3416 .nodes_mut()
3417 .alloc(NodeEntry::new(NodeKind::Function, name2, file_id))
3418 .unwrap();
3419
3420 let snapshot = graph.snapshot();
3421
3422 // Iterate nodes
3423 let snapshot_nodes: Vec<_> = snapshot.iter_nodes().collect();
3424 assert_eq!(snapshot_nodes.len(), 2);
3425
3426 let node_ids: Vec<_> = snapshot_nodes.iter().map(|(id, _)| *id).collect();
3427 assert!(node_ids.contains(&node1));
3428 assert!(node_ids.contains(&node2));
3429 }
3430
3431 #[test]
3432 fn test_snapshot_iter_edges() {
3433 use crate::graph::unified::edge::EdgeKind;
3434 use crate::graph::unified::node::NodeKind;
3435 use crate::graph::unified::storage::arena::NodeEntry;
3436 use std::path::Path;
3437
3438 let mut graph = CodeGraph::new();
3439
3440 // Create nodes
3441 let name1 = graph.strings_mut().intern("func1").unwrap();
3442 let name2 = graph.strings_mut().intern("func2").unwrap();
3443 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3444
3445 let node1 = graph
3446 .nodes_mut()
3447 .alloc(NodeEntry::new(NodeKind::Function, name1, file_id))
3448 .unwrap();
3449 let node2 = graph
3450 .nodes_mut()
3451 .alloc(NodeEntry::new(NodeKind::Function, name2, file_id))
3452 .unwrap();
3453
3454 // Add edges
3455 graph.edges_mut().add_edge(
3456 node1,
3457 node2,
3458 EdgeKind::Calls {
3459 argument_count: 0,
3460 is_async: false,
3461 resolved_via: ResolvedVia::Direct,
3462 },
3463 file_id,
3464 );
3465
3466 let snapshot = graph.snapshot();
3467
3468 // Iterate edges
3469 let edges: Vec<_> = snapshot.iter_edges().collect();
3470 assert_eq!(edges.len(), 1);
3471
3472 let (src, tgt, kind) = &edges[0];
3473 assert_eq!(*src, node1);
3474 assert_eq!(*tgt, node2);
3475 assert!(matches!(
3476 kind,
3477 EdgeKind::Calls {
3478 argument_count: 0,
3479 is_async: false,
3480 resolved_via: ResolvedVia::Direct,
3481 }
3482 ));
3483 }
3484
3485 #[test]
3486 fn test_snapshot_get_node() {
3487 use crate::graph::unified::node::NodeId;
3488 use crate::graph::unified::node::NodeKind;
3489 use crate::graph::unified::storage::arena::NodeEntry;
3490 use std::path::Path;
3491
3492 let mut graph = CodeGraph::new();
3493
3494 // Add a node
3495 let name = graph.strings_mut().intern("test_func").unwrap();
3496 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3497
3498 let node_id = graph
3499 .nodes_mut()
3500 .alloc(NodeEntry::new(NodeKind::Function, name, file_id))
3501 .unwrap();
3502
3503 let snapshot = graph.snapshot();
3504
3505 // Get node
3506 let entry = snapshot.get_node(node_id);
3507 assert!(entry.is_some());
3508 assert_eq!(entry.unwrap().kind, NodeKind::Function);
3509
3510 // Invalid node
3511 let invalid_id = NodeId::INVALID;
3512 assert!(snapshot.get_node(invalid_id).is_none());
3513 }
3514
3515 #[test]
3516 fn test_snapshot_query_empty_graph() {
3517 use crate::graph::unified::node::NodeId;
3518
3519 let graph = CodeGraph::new();
3520 let snapshot = graph.snapshot();
3521
3522 // All queries should return empty on empty graph
3523 assert!(resolve_symbol_strict(&snapshot, "test").is_none());
3524 assert!(snapshot.find_by_pattern("test").is_empty());
3525 assert!(candidate_nodes(&snapshot, "test").is_empty());
3526
3527 let dummy_id = NodeId::new(0, 1);
3528 assert!(snapshot.get_callees(dummy_id).is_empty());
3529 assert!(snapshot.get_callers(dummy_id).is_empty());
3530
3531 assert_eq!(snapshot.iter_nodes().count(), 0);
3532 assert_eq!(snapshot.iter_edges().count(), 0);
3533 }
3534
3535 #[test]
3536 fn test_snapshot_edge_filtering_by_kind() {
3537 use crate::graph::unified::edge::EdgeKind;
3538 use crate::graph::unified::node::NodeKind;
3539 use crate::graph::unified::storage::arena::NodeEntry;
3540 use std::path::Path;
3541
3542 let mut graph = CodeGraph::new();
3543
3544 // Create nodes
3545 let name1 = graph.strings_mut().intern("func1").unwrap();
3546 let name2 = graph.strings_mut().intern("func2").unwrap();
3547 let file_id = graph.files_mut().register(Path::new("test.rs")).unwrap();
3548
3549 let node1 = graph
3550 .nodes_mut()
3551 .alloc(NodeEntry::new(NodeKind::Function, name1, file_id))
3552 .unwrap();
3553 let node2 = graph
3554 .nodes_mut()
3555 .alloc(NodeEntry::new(NodeKind::Function, name2, file_id))
3556 .unwrap();
3557
3558 // Add different kinds of edges
3559 graph.edges_mut().add_edge(
3560 node1,
3561 node2,
3562 EdgeKind::Calls {
3563 argument_count: 0,
3564 is_async: false,
3565 resolved_via: ResolvedVia::Direct,
3566 },
3567 file_id,
3568 );
3569 graph
3570 .edges_mut()
3571 .add_edge(node1, node2, EdgeKind::References, file_id);
3572
3573 let snapshot = graph.snapshot();
3574
3575 // get_callees should only return Calls edges
3576 let callees = snapshot.get_callees(node1);
3577 assert_eq!(callees.len(), 1);
3578 assert_eq!(callees[0], node2);
3579
3580 // iter_edges returns all edges regardless of kind
3581 let edges: Vec<_> = snapshot.iter_edges().collect();
3582 assert_eq!(edges.len(), 2);
3583 }
3584
3585 // -------- reverse_import_index tests --------
3586
3587 /// Helper: build an empty graph with the given file paths registered, a
3588 /// single placeholder node allocated per file, and indices rebuilt so
3589 /// `by_file` returns the per-file node sets. Returns the file IDs in
3590 /// the order passed in and the per-file node ID.
3591 #[cfg(test)]
3592 fn build_import_test_graph(files: &[&str]) -> (CodeGraph, Vec<FileId>, Vec<NodeId>) {
3593 use crate::graph::unified::node::NodeKind;
3594 use crate::graph::unified::storage::arena::NodeEntry;
3595 use std::path::Path;
3596
3597 let mut graph = CodeGraph::new();
3598 let placeholder_name = graph.strings_mut().intern("sym").unwrap();
3599 let mut file_ids = Vec::with_capacity(files.len());
3600 let mut node_ids = Vec::with_capacity(files.len());
3601 for path in files {
3602 let file_id = graph.files_mut().register(Path::new(path)).unwrap();
3603 let node_id = graph
3604 .nodes_mut()
3605 .alloc(NodeEntry::new(
3606 NodeKind::Function,
3607 placeholder_name,
3608 file_id,
3609 ))
3610 .unwrap();
3611 file_ids.push(file_id);
3612 node_ids.push(node_id);
3613 }
3614 graph.rebuild_indices();
3615 (graph, file_ids, node_ids)
3616 }
3617
3618 /// Helper: add an `Imports` edge from `source_node` (in importer file) to
3619 /// `target_node` (in exporter file). The edge is recorded against the
3620 /// importer file so `clear_file` cleanup would behave identically to
3621 /// production Pass 4 writes.
3622 #[cfg(test)]
3623 fn add_import_edge(
3624 graph: &mut CodeGraph,
3625 source_node: NodeId,
3626 target_node: NodeId,
3627 importer_file: FileId,
3628 ) {
3629 graph.edges_mut().add_edge(
3630 source_node,
3631 target_node,
3632 EdgeKind::Imports {
3633 alias: None,
3634 is_wildcard: false,
3635 },
3636 importer_file,
3637 );
3638 }
3639
3640 #[test]
3641 fn reverse_import_index_empty_graph_returns_empty() {
3642 let (graph, files, _) = build_import_test_graph(&["only.rs"]);
3643 assert!(graph.reverse_import_index(files[0]).is_empty());
3644 }
3645
3646 #[test]
3647 fn reverse_import_index_single_importer() {
3648 // File A imports a symbol exported by file B. Reverse index of B
3649 // should return exactly [A]; reverse index of A should be empty.
3650 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs", "b.rs"]);
3651 let (a, b) = (files[0], files[1]);
3652 add_import_edge(&mut graph, nodes[0], nodes[1], a);
3653
3654 let importers_of_b = graph.reverse_import_index(b);
3655 assert_eq!(importers_of_b, vec![a]);
3656
3657 let importers_of_a = graph.reverse_import_index(a);
3658 assert!(
3659 importers_of_a.is_empty(),
3660 "A has no inbound Imports edges; reverse index must be empty"
3661 );
3662 }
3663
3664 #[test]
3665 fn reverse_import_index_multiple_importers_deduped_and_sorted() {
3666 // A, B, C all import from D. Reverse index of D must contain each
3667 // importer exactly once, sorted ascending by FileId.
3668 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs", "b.rs", "c.rs", "d.rs"]);
3669 let (a, b, c, d) = (files[0], files[1], files[2], files[3]);
3670 add_import_edge(&mut graph, nodes[0], nodes[3], a);
3671 add_import_edge(&mut graph, nodes[1], nodes[3], b);
3672 add_import_edge(&mut graph, nodes[2], nodes[3], c);
3673 // Add a duplicate edge from A to D to confirm dedup behavior.
3674 add_import_edge(&mut graph, nodes[0], nodes[3], a);
3675
3676 let importers_of_d = graph.reverse_import_index(d);
3677 assert_eq!(importers_of_d, vec![a, b, c]);
3678 // Sort invariant: Vec is ascending by raw index.
3679 let mut sorted = importers_of_d.clone();
3680 sorted.sort();
3681 assert_eq!(importers_of_d, sorted);
3682 }
3683
3684 #[test]
3685 fn reverse_import_index_filters_non_import_edges() {
3686 // A `Calls` edge from A into B must not contribute to B's reverse
3687 // import index. Only `EdgeKind::Imports` edges count.
3688 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs", "b.rs"]);
3689 let (a, b) = (files[0], files[1]);
3690 graph.edges_mut().add_edge(
3691 nodes[0],
3692 nodes[1],
3693 EdgeKind::Calls {
3694 argument_count: 0,
3695 is_async: false,
3696 resolved_via: ResolvedVia::Direct,
3697 },
3698 a,
3699 );
3700 graph
3701 .edges_mut()
3702 .add_edge(nodes[0], nodes[1], EdgeKind::References, a);
3703
3704 assert!(
3705 graph.reverse_import_index(b).is_empty(),
3706 "non-Imports edges must not register as importers"
3707 );
3708 }
3709
3710 #[test]
3711 fn reverse_import_index_elides_self_imports() {
3712 // An Imports edge whose source and target are both in the same file
3713 // is a self-import; the caller's own file must not appear in its own
3714 // reverse index.
3715 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs"]);
3716 let a = files[0];
3717 // Add a second node in the same file so we have a distinct source.
3718 let name2 = graph.strings_mut().intern("sym2").unwrap();
3719 let second_in_a = graph
3720 .nodes_mut()
3721 .alloc(crate::graph::unified::storage::arena::NodeEntry::new(
3722 crate::graph::unified::node::NodeKind::Function,
3723 name2,
3724 a,
3725 ))
3726 .unwrap();
3727 graph.rebuild_indices();
3728 add_import_edge(&mut graph, second_in_a, nodes[0], a);
3729
3730 assert!(
3731 graph.reverse_import_index(a).is_empty(),
3732 "self-imports must be elided from reverse index"
3733 );
3734 }
3735
3736 #[test]
3737 fn reverse_import_index_mixed_edge_kinds_counts_only_imports() {
3738 // Two files: A has both Calls and Imports edges into B. Reverse
3739 // index must return exactly [A] — the Calls edge contributes
3740 // nothing.
3741 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs", "b.rs"]);
3742 let (a, b) = (files[0], files[1]);
3743 add_import_edge(&mut graph, nodes[0], nodes[1], a);
3744 graph.edges_mut().add_edge(
3745 nodes[0],
3746 nodes[1],
3747 EdgeKind::Calls {
3748 argument_count: 0,
3749 is_async: false,
3750 resolved_via: ResolvedVia::Direct,
3751 },
3752 a,
3753 );
3754
3755 assert_eq!(graph.reverse_import_index(b), vec![a]);
3756 }
3757
3758 #[test]
3759 fn reverse_import_index_uninitialized_file_returns_empty() {
3760 // Querying a FileId that is not registered in the graph must return
3761 // an empty Vec, not panic.
3762 let (graph, _, _) = build_import_test_graph(&["a.rs"]);
3763 let bogus = FileId::new(9999);
3764 assert!(
3765 graph.reverse_import_index(bogus).is_empty(),
3766 "unknown FileId must return empty Vec without panicking"
3767 );
3768 }
3769
3770 #[test]
3771 fn reverse_import_index_skips_tombstoned_source_nodes() {
3772 // In the incremental rebuild path the prior graph retains tombstoned
3773 // arena slots for nodes belonging to closure files that have been
3774 // removed but not yet fully compacted. reverse_import_index is
3775 // called on that prior graph to widen the closure, so its
3776 // tombstone guard (`let Some(source_entry) = self.nodes.get(...)`)
3777 // is a semantically important branch, not a theoretical one.
3778 // This test exercises it directly by tombstoning the source node of
3779 // an Imports edge and asserting the edge silently disappears from
3780 // the reverse index.
3781 let (mut graph, files, nodes) = build_import_test_graph(&["a.rs", "b.rs"]);
3782 let (a, b) = (files[0], files[1]);
3783 add_import_edge(&mut graph, nodes[0], nodes[1], a);
3784 // Sanity: before tombstoning, A shows up as the importer of B.
3785 assert_eq!(graph.reverse_import_index(b), vec![a]);
3786 // Tombstone the source node via the arena (generation bump). The
3787 // Imports edge still exists in the edge store but its source NodeId
3788 // is now stale; `nodes.get(edge_ref.source)` returns None and the
3789 // guard skips the edge.
3790 let removed = graph.nodes_mut().remove(nodes[0]);
3791 assert!(
3792 removed.is_some(),
3793 "arena.remove must succeed for a live node"
3794 );
3795 assert!(
3796 graph.nodes().get(nodes[0]).is_none(),
3797 "tombstoned lookup must return None"
3798 );
3799 assert!(
3800 graph.reverse_import_index(b).is_empty(),
3801 "Imports edges whose source is tombstoned must be silently skipped"
3802 );
3803 }
3804
3805 // ------------------------------------------------------------------
3806 // Task 4 Step 2 — CodeGraph::remove_file
3807 // ------------------------------------------------------------------
3808
3809 /// Seed a graph with 2 files × `per_file` nodes per file, plus a set
3810 /// of intra- and inter-file edges. Each call site produces a
3811 /// canonical topology so tests below can assert bit-level on edge
3812 /// survival. Returns `(graph, file_a, file_b, file_a_nodes,
3813 /// file_b_nodes)`.
3814 fn seed_two_file_graph(
3815 per_file: usize,
3816 ) -> (
3817 CodeGraph,
3818 crate::graph::unified::file::FileId,
3819 crate::graph::unified::file::FileId,
3820 Vec<NodeId>,
3821 Vec<NodeId>,
3822 ) {
3823 use crate::graph::unified::edge::EdgeKind;
3824 use crate::graph::unified::node::NodeKind;
3825 use crate::graph::unified::storage::arena::NodeEntry;
3826 use std::path::Path;
3827
3828 let mut graph = CodeGraph::new();
3829 let sym = graph.strings_mut().intern("sym").expect("intern");
3830 let file_a = graph
3831 .files_mut()
3832 .register(Path::new("/tmp/remove_file_test/a.rs"))
3833 .expect("register a");
3834 let file_b = graph
3835 .files_mut()
3836 .register(Path::new("/tmp/remove_file_test/b.rs"))
3837 .expect("register b");
3838
3839 let mut file_a_nodes = Vec::with_capacity(per_file);
3840 let mut file_b_nodes = Vec::with_capacity(per_file);
3841
3842 for _ in 0..per_file {
3843 let n = graph
3844 .nodes_mut()
3845 .alloc(NodeEntry::new(NodeKind::Function, sym, file_a))
3846 .expect("alloc a-node");
3847 file_a_nodes.push(n);
3848 graph.files_mut().record_node(file_a, n);
3849 graph
3850 .indices_mut()
3851 .add(n, NodeKind::Function, sym, None, file_a);
3852 }
3853 for _ in 0..per_file {
3854 let n = graph
3855 .nodes_mut()
3856 .alloc(NodeEntry::new(NodeKind::Function, sym, file_b))
3857 .expect("alloc b-node");
3858 file_b_nodes.push(n);
3859 graph.files_mut().record_node(file_b, n);
3860 graph
3861 .indices_mut()
3862 .add(n, NodeKind::Function, sym, None, file_b);
3863 }
3864
3865 // Intra-file edges inside each file: pairwise a[i] -> a[i+1],
3866 // b[i] -> b[i+1]. These are the ones that must die when the
3867 // corresponding file is removed.
3868 for i in 0..per_file.saturating_sub(1) {
3869 graph.edges_mut().add_edge(
3870 file_a_nodes[i],
3871 file_a_nodes[i + 1],
3872 EdgeKind::Calls {
3873 argument_count: 0,
3874 is_async: false,
3875 resolved_via: ResolvedVia::Direct,
3876 },
3877 file_a,
3878 );
3879 graph.edges_mut().add_edge(
3880 file_b_nodes[i],
3881 file_b_nodes[i + 1],
3882 EdgeKind::Calls {
3883 argument_count: 0,
3884 is_async: false,
3885 resolved_via: ResolvedVia::Direct,
3886 },
3887 file_b,
3888 );
3889 }
3890 // Cross-file edges: a[0] -> b[0], b[0] -> a[0]. Both must die
3891 // when *either* endpoint's file is removed (plan §F.2).
3892 graph.edges_mut().add_edge(
3893 file_a_nodes[0],
3894 file_b_nodes[0],
3895 EdgeKind::Calls {
3896 argument_count: 0,
3897 is_async: false,
3898 resolved_via: ResolvedVia::Direct,
3899 },
3900 file_a,
3901 );
3902 graph.edges_mut().add_edge(
3903 file_b_nodes[0],
3904 file_a_nodes[0],
3905 EdgeKind::Calls {
3906 argument_count: 0,
3907 is_async: false,
3908 resolved_via: ResolvedVia::Direct,
3909 },
3910 file_b,
3911 );
3912
3913 (graph, file_a, file_b, file_a_nodes, file_b_nodes)
3914 }
3915
3916 #[test]
3917 fn code_graph_remove_file_tombstones_all_per_file_nodes() {
3918 let (mut graph, file_a, _file_b, file_a_nodes, _file_b_nodes) = seed_two_file_graph(3);
3919
3920 let returned = graph.remove_file(file_a);
3921
3922 // Returned list must equal the original per-file bucket
3923 // membership, deterministically.
3924 let returned_set: std::collections::HashSet<NodeId> = returned.iter().copied().collect();
3925 let expected_set: std::collections::HashSet<NodeId> =
3926 file_a_nodes.iter().copied().collect();
3927 assert_eq!(
3928 returned_set, expected_set,
3929 "remove_file must return exactly the file_a nodes drained from the bucket"
3930 );
3931
3932 // Every returned NodeId is gone from the arena.
3933 for nid in &file_a_nodes {
3934 assert!(
3935 graph.nodes().get(*nid).is_none(),
3936 "node {nid:?} from removed file must be tombstoned in arena"
3937 );
3938 }
3939 }
3940
3941 #[test]
3942 fn code_graph_remove_file_invalidates_all_edges_sourced_or_targeted_at_removed_nodes() {
3943 use crate::graph::unified::edge::EdgeKind;
3944
3945 let (mut graph, file_a, _file_b, file_a_nodes, file_b_nodes) = seed_two_file_graph(3);
3946
3947 // Sanity: the seed has 2 intra-A edges, 2 intra-B edges, plus
3948 // 2 cross-file edges (a0↔b0).
3949 let before_delta = graph.edges().stats().forward.delta_edge_count;
3950 assert_eq!(
3951 before_delta, 6,
3952 "seed must produce 2 intra-A + 2 intra-B + 2 cross edges"
3953 );
3954
3955 let _ = graph.remove_file(file_a);
3956
3957 // Forward delta after removal: all 2 intra-A edges are gone,
3958 // both cross edges are gone, only the 2 intra-B edges remain.
3959 let after_delta_forward = graph.edges().stats().forward.delta_edge_count;
3960 assert_eq!(
3961 after_delta_forward, 2,
3962 "only intra-B forward edges must remain after removing file_a"
3963 );
3964 let after_delta_reverse = graph.edges().stats().reverse.delta_edge_count;
3965 assert_eq!(
3966 after_delta_reverse, 2,
3967 "only intra-B reverse edges must remain after removing file_a"
3968 );
3969
3970 // Cross-file edge from b[0] -> a[0] must no longer be visible
3971 // from either direction, because a[0] is tombstoned.
3972 let b0 = file_b_nodes[0];
3973 let a0 = file_a_nodes[0];
3974 let remaining_from_b0: Vec<_> = graph
3975 .edges()
3976 .edges_from(b0)
3977 .into_iter()
3978 .filter(|e| {
3979 matches!(
3980 e.kind,
3981 EdgeKind::Calls {
3982 argument_count: 0,
3983 is_async: false,
3984 resolved_via: ResolvedVia::Direct,
3985 }
3986 )
3987 })
3988 .collect();
3989 assert!(
3990 !remaining_from_b0.iter().any(|e| e.target == a0),
3991 "edge b0 -> a0 must be gone after remove_file(file_a)"
3992 );
3993 let remaining_to_a0: Vec<_> = graph.edges().edges_to(a0).into_iter().collect();
3994 assert!(
3995 remaining_to_a0.is_empty(),
3996 "every edge targeting the tombstoned a0 must be gone"
3997 );
3998 }
3999
4000 #[test]
4001 fn code_graph_remove_file_drops_file_registry_entry() {
4002 let (mut graph, file_a, _file_b, _, _) = seed_two_file_graph(2);
4003
4004 assert!(
4005 graph.files().resolve(file_a).is_some(),
4006 "seed registered file_a"
4007 );
4008 assert!(
4009 !graph.files().nodes_for_file(file_a).is_empty(),
4010 "seed populated the file_a bucket"
4011 );
4012
4013 let _ = graph.remove_file(file_a);
4014
4015 assert!(
4016 graph.files().resolve(file_a).is_none(),
4017 "FileRegistry::resolve must return None after remove_file"
4018 );
4019 assert!(
4020 graph.files().nodes_for_file(file_a).is_empty(),
4021 "per-file bucket for file_a must be drained"
4022 );
4023 }
4024
4025 #[test]
4026 fn code_graph_remove_file_is_idempotent_on_unknown_file() {
4027 use crate::graph::unified::file::FileId;
4028 let (mut graph, _file_a, _file_b, _, _) = seed_two_file_graph(2);
4029
4030 // Snapshot state before idempotent no-op.
4031 let nodes_before = graph.nodes().len();
4032 let delta_fwd_before = graph.edges().stats().forward.delta_edge_count;
4033 let delta_rev_before = graph.edges().stats().reverse.delta_edge_count;
4034 let files_before = graph.files().len();
4035
4036 // A FileId that was never registered: the caller may legitimately
4037 // receive a bogus id from stale indexing state. `remove_file`
4038 // must be a silent no-op.
4039 let bogus = FileId::new(9999);
4040 let returned = graph.remove_file(bogus);
4041 assert!(
4042 returned.is_empty(),
4043 "remove_file on unknown FileId must return an empty Vec"
4044 );
4045
4046 assert_eq!(graph.nodes().len(), nodes_before, "arena count unchanged");
4047 assert_eq!(
4048 graph.edges().stats().forward.delta_edge_count,
4049 delta_fwd_before,
4050 "forward delta unchanged"
4051 );
4052 assert_eq!(
4053 graph.edges().stats().reverse.delta_edge_count,
4054 delta_rev_before,
4055 "reverse delta unchanged"
4056 );
4057 assert_eq!(graph.files().len(), files_before, "file count unchanged");
4058 }
4059
4060 #[test]
4061 fn code_graph_remove_file_clears_file_segments_entry() {
4062 // Iter-1 Codex review fix: a file's `FileSegmentTable` entry
4063 // must be cleared on `remove_file`. Without this, a later
4064 // `FileId` recycle (via `FileRegistry::free_list`) would
4065 // inherit the previous file's stale node-range and
4066 // `reindex_files` (`build/reindex.rs`) would tombstone the
4067 // wrong slots. This unit test seeds a segment entry, removes
4068 // the file, and asserts the entry is gone.
4069 use crate::graph::unified::storage::segment::FileSegmentTable;
4070
4071 let (mut graph, file_a, _file_b, file_a_nodes, _file_b_nodes) = seed_two_file_graph(3);
4072
4073 // Seed a segment for file A. Production code sets this via
4074 // Phase 3 parallel commit; here we go through the crate-
4075 // internal accessor because we are a unit test inside the
4076 // crate. (The feature-gated `test_only_record_file_segment`
4077 // public helper exists for the integration tests in
4078 // `sqry-core/tests/incremental_remove_file_scale.rs`.)
4079 let first_index = file_a_nodes
4080 .iter()
4081 .map(|n| n.index())
4082 .min()
4083 .expect("per_file = 3");
4084 let last_index = file_a_nodes
4085 .iter()
4086 .map(|n| n.index())
4087 .max()
4088 .expect("per_file = 3");
4089 let slot_count = last_index - first_index + 1;
4090 let table: &mut FileSegmentTable = graph.file_segments_mut();
4091 table.record_range(file_a, first_index, slot_count);
4092 assert!(
4093 graph.file_segments().get(file_a).is_some(),
4094 "seed must install a segment for file_a before remove_file"
4095 );
4096
4097 // Remove the file.
4098 let _ = graph.remove_file(file_a);
4099
4100 // The segment entry must be gone. `FileSegmentTable::remove`
4101 // is idempotent (a no-op on unknown ids), so this assertion
4102 // holds whether or not the seeded range was contiguous.
4103 assert!(
4104 graph.file_segments().get(file_a).is_none(),
4105 "remove_file must clear the FileSegmentTable entry for file_a"
4106 );
4107 }
4108
4109 #[test]
4110 fn code_graph_remove_file_repeated_calls_are_idempotent() {
4111 let (mut graph, file_a, _file_b, file_a_nodes, _file_b_nodes) = seed_two_file_graph(3);
4112
4113 // First call does the work.
4114 let first = graph.remove_file(file_a);
4115 assert_eq!(first.len(), file_a_nodes.len());
4116
4117 // Snapshot post-first-call state.
4118 let nodes_after = graph.nodes().len();
4119 let delta_fwd_after = graph.edges().stats().forward.delta_edge_count;
4120 let delta_rev_after = graph.edges().stats().reverse.delta_edge_count;
4121 let files_after = graph.files().len();
4122
4123 // Second call must be a silent no-op — the bucket is empty,
4124 // the file is unregistered, and the arena slots are already
4125 // tombstoned (NodeArena::remove ignores stale generations).
4126 let second = graph.remove_file(file_a);
4127 assert!(
4128 second.is_empty(),
4129 "second remove_file on the same file must return an empty Vec"
4130 );
4131
4132 assert_eq!(graph.nodes().len(), nodes_after);
4133 assert_eq!(
4134 graph.edges().stats().forward.delta_edge_count,
4135 delta_fwd_after
4136 );
4137 assert_eq!(
4138 graph.edges().stats().reverse.delta_edge_count,
4139 delta_rev_after
4140 );
4141 assert_eq!(graph.files().len(), files_after);
4142 }
4143}