sqry_core/graph/unified/build/parallel_commit.rs
1//! Parallel commit pipeline for pre-allocated ID ranges.
2//!
3//! Replaces the serial commit loop with a four-phase pipeline:
4//! Phase 2: Count + range assignment via prefix sums
5//! Phase 3: Parallel commit into disjoint pre-allocated ranges
6//! Phase 4: String dedup, remap, index build, edge bulk insert
7//!
8//! # Phase 3 Architecture
9//!
10//! Phase 3 uses `split_at_mut` to carve disjoint sub-slices from pre-allocated
11//! arena and interner ranges, then uses `rayon` to commit each file's staging
12//! graph in parallel without locks:
13//!
14//! ```text
15//! NodeArena slots: [ file0 | file1 | file2 ]
16//! StringInterner: [ file0 | file1 | file2 ]
17//! ↑ ↑ ↑
18//! split_at_mut split_at_mut remainder
19//! ```
20//!
21//! Each file's `commit_single_file` receives its own disjoint slices and
22//! operates independently without contention.
23
24use std::collections::HashMap;
25use std::ops::Range;
26use std::sync::Arc;
27
28use rayon::prelude::*;
29
30use crate::graph::unified::edge::delta::{DeltaEdge, DeltaOp};
31#[cfg(test)]
32use crate::graph::unified::edge::kind::ResolvedVia;
33use crate::graph::unified::edge::kind::{EdgeKind, MqProtocol};
34use crate::graph::unified::file::FileId;
35use crate::graph::unified::node::NodeId;
36use crate::graph::unified::storage::NodeArena;
37use crate::graph::unified::storage::arena::{NodeEntry, Slot};
38use crate::graph::unified::storage::c_indirect::LocalScopeIndex;
39use crate::graph::unified::string::StringId;
40
41use super::pass3_intra::PendingEdge;
42use super::staging::{
43 GoEmbeddingHint, GoFunctionSignatureHint, GoMethodReceiverHint, GoMethodSignatureHint,
44 GoNamedTypeConversionHint, GoReceiverCallHint, GoReceiverHintKind, PendingBinding,
45 PendingIndirectCallsite, StagingGraph, StagingOp,
46};
47
48/// Running offsets carried across chunks for deterministic ID assignment.
49///
50/// Each chunk's ranges begin where the previous chunk ended, ensuring
51/// globally unique, contiguous ID spaces.
52#[derive(Debug, Clone, Default)]
53pub struct GlobalOffsets {
54 /// Next available node slot index.
55 pub node_offset: u32,
56 /// Next available string slot index.
57 pub string_offset: u32,
58}
59
60/// Per-file commit plan with pre-assigned ID ranges.
61#[derive(Debug, Clone)]
62pub struct FilePlan {
63 /// Index into the chunk's `ParsedFile` vec.
64 pub parsed_index: usize,
65 /// Pre-assigned `FileId` from batch registration.
66 pub file_id: FileId,
67 /// Node slot range [start..end) in `NodeArena`.
68 pub node_range: Range<u32>,
69 /// String slot range [start..end) in `StringInterner`.
70 pub string_range: Range<u32>,
71}
72
73/// Plan for parallel commit of a single chunk.
74#[derive(Debug, Clone)]
75pub struct ChunkCommitPlan {
76 /// Per-file plans in deterministic file order.
77 pub file_plans: Vec<FilePlan>,
78 /// Total nodes across all files in this chunk.
79 pub total_nodes: u32,
80 /// Total strings across all files in this chunk.
81 pub total_strings: u32,
82 /// Total edges across all files in this chunk.
83 pub total_edges: u64,
84}
85
86/// Compute commit plan from parsed files using prefix-sum range assignment.
87///
88/// Each file gets contiguous, non-overlapping ranges for nodes and strings.
89/// Ranges start from the given global offsets, which carry forward across
90/// chunks.
91///
92/// # Arguments
93///
94/// * `node_counts` - Per-file node counts (from `StagingGraph::node_count_u32()`)
95/// * `string_counts` - Per-file string counts
96/// * `edge_counts` - Per-file edge counts (used for `total_edges` only)
97/// * `file_ids` - Pre-assigned `FileId`s from batch registration
98/// * `node_offset` - Running global node offset across chunks
99/// * `string_offset` - Running global string offset across chunks
100///
101/// # Panics
102///
103/// Panics in debug builds if the per-chunk accounting arrays do not have
104/// identical lengths.
105#[must_use]
106pub fn compute_commit_plan(
107 node_counts: &[u32],
108 string_counts: &[u32],
109 edge_counts: &[u32],
110 file_ids: &[FileId],
111 node_offset: u32,
112 string_offset: u32,
113) -> ChunkCommitPlan {
114 debug_assert_eq!(node_counts.len(), string_counts.len());
115 debug_assert_eq!(node_counts.len(), edge_counts.len());
116 debug_assert_eq!(node_counts.len(), file_ids.len());
117
118 let mut plans = Vec::with_capacity(node_counts.len());
119 let mut node_cursor = node_offset;
120 let mut string_cursor = string_offset;
121 let mut total_edges: u64 = 0;
122
123 for i in 0..node_counts.len() {
124 let nc = node_counts[i];
125 let sc = string_counts[i];
126
127 let node_end = node_cursor
128 .checked_add(nc)
129 .expect("node ID space overflow in commit plan");
130 let string_end = string_cursor
131 .checked_add(sc)
132 .expect("string ID space overflow in commit plan");
133
134 plans.push(FilePlan {
135 parsed_index: i,
136 file_id: file_ids[i],
137 node_range: node_cursor..node_end,
138 string_range: string_cursor..string_end,
139 });
140
141 node_cursor = node_end;
142 string_cursor = string_end;
143 total_edges += u64::from(edge_counts[i]);
144 }
145
146 ChunkCommitPlan {
147 file_plans: plans,
148 total_nodes: node_cursor - node_offset,
149 total_strings: string_cursor - string_offset,
150 total_edges,
151 }
152}
153
154/// Execute Phase 2: count + range assignment for a parsed chunk.
155///
156/// Extracts per-file counts from staging graphs and delegates to
157/// [`compute_commit_plan`] for prefix-sum range assignment.
158#[must_use]
159pub fn phase2_assign_ranges(
160 staging_graphs: &[&StagingGraph],
161 file_ids: &[FileId],
162 offsets: &GlobalOffsets,
163) -> ChunkCommitPlan {
164 let node_counts: Vec<u32> = staging_graphs
165 .iter()
166 .map(|sg| sg.node_count_u32())
167 .collect();
168 let string_counts: Vec<u32> = staging_graphs
169 .iter()
170 .map(|sg| sg.string_count_u32())
171 .collect();
172 let edge_counts: Vec<u32> = staging_graphs
173 .iter()
174 .map(|sg| sg.edge_count_u32())
175 .collect();
176
177 compute_commit_plan(
178 &node_counts,
179 &string_counts,
180 &edge_counts,
181 file_ids,
182 offsets.node_offset,
183 offsets.string_offset,
184 )
185}
186
187/// Phase 3 result: per-file edges, per-file node IDs, and total written
188/// counts for validation.
189pub struct Phase3Result {
190 /// Per-file edge collections for Phase 4 bulk insert.
191 pub per_file_edges: Vec<Vec<PendingEdge>>,
192 /// Per-file node IDs actually committed. Indexed identically to
193 /// `per_file_edges` — element `i` is the Vec of NodeIds committed
194 /// for `plan.file_plans[i]`. Empty Vec when that file wrote no
195 /// nodes (slot overflow skip, or a staging graph with only strings).
196 ///
197 /// Used by the caller to populate
198 /// [`crate::graph::unified::storage::registry::FileRegistry::record_node`],
199 /// which feeds the Gate 0c bucket-bijection debug invariant.
200 pub per_file_node_ids: Vec<Vec<NodeId>>,
201 /// Total nodes actually written (for validation against planned totals).
202 pub total_nodes_written: usize,
203 /// Total strings actually written (for validation against planned totals).
204 pub total_strings_written: usize,
205 /// Total edges collected across all files.
206 pub total_edges_collected: usize,
207 /// Per-chunk drained C indirect-call staging payloads (DESIGN §8.2).
208 ///
209 /// Populated when any file in the chunk staged a
210 /// [`super::staging::CIndirectStagingPayload`] (C plugin Phase 1, U10).
211 /// `None` for chunks containing no C files, keeping the wire-shape
212 /// budget unchanged for non-C workspaces.
213 ///
214 /// Consumed by [`apply_c_indirect_drain`] from `entrypoint.rs` after
215 /// Phase 4c-prime cross-file unification rebuilds the qualified-name
216 /// index — see U11 plumbing for the full Phase 3 → Phase 4 hand-off.
217 pub c_indirect_drain: Option<PhaseCIndirectDrain>,
218}
219
220/// Drained C indirect-call staging payload, resolved to owned `String`s.
221///
222/// The per-file
223/// [`super::staging::CIndirectStagingPayload`] contains:
224/// * `pending_address_taken_names: Vec<StringId>` — staging-local string
225/// ids that we resolve to owned `String`s via `staging.resolve_local_string`
226/// here so the post-4c-prime applier can re-intern through the canonical
227/// interner without holding any staging-graph reference;
228/// * `pending_struct_field_signatures: Vec<(String, String, String)>` —
229/// already owned;
230/// * `pending_bindings: Vec<PendingBinding>` — already owned;
231/// * `pending_indirect_callsites: Vec<PendingIndirectCallsite>` — already
232/// owned (carrier-side stamping of `FileId` happens here so the applier
233/// does not need per-file context);
234/// * `local_scope_index: Option<LocalScopeIndex>` — moved verbatim.
235///
236/// The applier ([`apply_c_indirect_drain`]) interns the owned strings into
237/// the **post-Phase-4a-dedup** graph interner, resolves names to canonical
238/// `NodeId`s via [`crate::graph::unified::storage::indices::AuxiliaryIndices::by_qualified_name`]
239/// (with a `by_name` fallback for languages whose canonical qualified name
240/// equals the semantic name and therefore leaves
241/// [`NodeEntry::qualified_name`] unset — e.g. C, where `cb_alpha` is its
242/// own qualified name), and writes them into
243/// [`CodeGraph::c_indirect_tables_mut`].
244///
245/// Per DESIGN §8.2, this drain bridges the parallel-parse-and-commit
246/// boundary (Phase 3) to the post-unification application step (Phase 4
247/// finalisation, just after Phase 4c-prime returns).
248#[derive(Debug, Default)]
249pub struct PhaseCIndirectDrain {
250 /// Address-taken function qualified-name entries to mark post-unification.
251 ///
252 /// Each entry pairs the bare/qualified function name the C plugin
253 /// captured in `helper.mark_function_address_taken_by_name(...)` with
254 /// the source `FileId` (always a C-language file by construction —
255 /// only the C plugin populates `CIndirectStagingPayload`).
256 ///
257 /// Per DESIGN §8.2 lines 1239-1241: "A pending list of
258 /// `(function_qualified_name, file_id)` for address-taken marks". The
259 /// `file_id` is the *origin* file (where the address-take site lives),
260 /// not the file of the resolved callable target. It is carried so the
261 /// applier can constrain the workspace-global `by_name` fallback in
262 /// [`crate::graph::unified::build::entrypoint::apply_deferred_address_taken_marks`]
263 /// to candidate nodes whose own owning file's language is `C` — a
264 /// non-C namesake (e.g. a Rust `fn cb_alpha`) must NOT be marked by
265 /// the C-scoped contract of SPEC §3.1.2.
266 ///
267 /// Duplicates on `function_qualified_name` are tolerated —
268 /// [`crate::graph::unified::storage::metadata::NodeMetadataStore::mark_address_taken`]
269 /// is idempotent.
270 pub address_taken_names: Vec<DeferredAddressTakenEntry>,
271 /// `(struct_tag, field_name, signature)` triples — DESIGN §3.2.2.
272 ///
273 /// Drained verbatim from the staging payload. The applier interns each
274 /// leg via `graph.strings_mut().intern(...)` and inserts into
275 /// `CIndirectSideTables::struct_field_fnptr`.
276 pub struct_field_signatures: Vec<(String, String, String)>,
277 /// Binding-plane entries (DESIGN §7.1) paired with their origin `FileId`.
278 ///
279 /// The applier resolves `instance_name` and `target_fn_name` to
280 /// canonical `NodeId`s and inserts a [`BindingEntry`] under the
281 /// interned `(struct_tag, field_name)` key in
282 /// `CIndirectSideTables::bindings_by_field`. The `FileId` is the
283 /// origin file (the C TU that staged the binding), retained for the
284 /// same C-language-scoped fallback rationale as
285 /// [`Self::address_taken_names`].
286 pub bindings: Vec<(FileId, PendingBinding)>,
287 /// Indirect callsites paired with their owning `FileId`. The applier
288 /// resolves `caller_qualified_name` to a `NodeId` and pushes an
289 /// [`IndirectCallsite`] onto `CIndirectSideTables::pending_callsites`.
290 /// `FileId` is stamped here from the per-file `FilePlan` so the applier
291 /// does not need per-file context.
292 pub indirect_callsites: Vec<(FileId, PendingIndirectCallsite)>,
293 /// Per-file block-scope arenas (DESIGN §4.1). Moved verbatim into
294 /// `CIndirectSideTables::local_scope_indices` keyed by `FileId`.
295 pub local_scope_indices: Vec<(FileId, LocalScopeIndex)>,
296}
297
298/// One deferred address-taken mark, carrying the origin `FileId`
299/// alongside the qualified function name (DESIGN §8.2 lines 1239-1241).
300///
301/// The origin `FileId` is always a C-language file by construction (only
302/// the C plugin populates `CIndirectStagingPayload`). It is retained on
303/// the drain so the post-unification applier can constrain the
304/// workspace-global `by_name` fallback to candidate nodes whose own
305/// owning file's language is `C` — defending against the SPEC §3.1.2
306/// "Every C `NodeKind::Function`" contract being widened to mark
307/// same-named non-C nodes (e.g. Rust `fn cb_alpha`, Python `def
308/// cb_alpha`) that happen to share a bare name with a C symbol.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct DeferredAddressTakenEntry {
311 /// Qualified function name as captured by
312 /// `helper.mark_function_address_taken_by_name(...)`.
313 pub function_qualified_name: String,
314 /// Origin C file that staged this address-taken site. Used only as
315 /// metadata for DESIGN §8.2 conformance and provenance — the
316 /// candidate-language filter in the applier compares each
317 /// candidate's owning-file language to `Language::C`, not to this
318 /// `file_id` directly (cross-TU address-takes are legal: a
319 /// `cb_alpha` declared in `a.c` may have its address taken in
320 /// `b.c`).
321 pub file_id: FileId,
322}
323
324impl PhaseCIndirectDrain {
325 /// Returns `true` when every drained vec/map is empty.
326 ///
327 /// Used by the chunk-accumulator in `entrypoint.rs` to skip Phase 4
328 /// application entirely for non-C workspaces, keeping the
329 /// `CodeGraph.c_indirect_tables` slot at its default `None`.
330 #[must_use]
331 pub fn is_empty(&self) -> bool {
332 self.address_taken_names.is_empty()
333 && self.struct_field_signatures.is_empty()
334 && self.bindings.is_empty()
335 && self.indirect_callsites.is_empty()
336 && self.local_scope_indices.is_empty()
337 }
338
339 /// Merge another drain into this one, taking ownership of its contents.
340 ///
341 /// Used by the chunk-loop in `entrypoint.rs` to accumulate per-chunk
342 /// drains into a single workspace-global drain before invoking
343 /// [`apply_c_indirect_drain`].
344 pub fn merge(&mut self, mut other: PhaseCIndirectDrain) {
345 self.address_taken_names
346 .append(&mut other.address_taken_names);
347 self.struct_field_signatures
348 .append(&mut other.struct_field_signatures);
349 self.bindings.append(&mut other.bindings);
350 self.indirect_callsites
351 .append(&mut other.indirect_callsites);
352 self.local_scope_indices
353 .append(&mut other.local_scope_indices);
354 }
355}
356
357/// Execute Phase 3: parallel commit into disjoint pre-allocated ranges.
358///
359/// Pre-splits arena and interner slices into per-file disjoint sub-slices
360/// using `split_at_mut`, then uses `rayon` `par_iter` for lock-free parallel
361/// writes. Each file's staging graph is committed independently.
362///
363/// Returns [`Phase3Result`] with per-file edges and written counts so the
364/// caller can validate against plan totals and truncate allocations on
365/// mismatch.
366///
367/// # Parameterisation over the mutation target
368///
369/// As of Task 4 Step 4 Phase 1, this function is generic over
370/// `G: GraphMutationTarget`. At the full-build call site in
371/// `build_unified_graph_inner` the target is `CodeGraph`; at the
372/// Task 4 Step 4 Phase 2+ incremental rebuild call site the target
373/// will be `RebuildGraph`. Both impls live in
374/// [`crate::graph::unified::mutation_target`]; see that module's
375/// docs for the field-coverage contract.
376///
377/// The function accesses exactly two fields via the trait —
378/// [`GraphMutationTarget::nodes_and_strings_mut`] — and pre-splits
379/// those two slices for the per-file parallel commit. Every other
380/// piece of the pipeline (the CSR/delta edge store, auxiliary
381/// indices, file registry, etc.) is untouched by this helper: the
382/// `PendingEdge` vectors in the returned [`Phase3Result`] are
383/// threaded through to Phase 4d (`pending_edges_to_delta` +
384/// `BidirectionalEdgeStore::add_edges_bulk_ordered`) by the caller.
385///
386/// # Panics
387///
388/// Panics if `plan.total_nodes` or `plan.total_strings` exceeds the
389/// pre-allocated range in the arena or interner.
390#[must_use]
391pub(crate) fn phase3_parallel_commit<
392 G: crate::graph::unified::mutation_target::GraphMutationTarget,
393>(
394 plan: &ChunkCommitPlan,
395 staging_graphs: &[&StagingGraph],
396 graph: &mut G,
397) -> Phase3Result {
398 if plan.file_plans.is_empty() {
399 return Phase3Result {
400 per_file_edges: Vec::new(),
401 per_file_node_ids: Vec::new(),
402 total_nodes_written: 0,
403 total_strings_written: 0,
404 total_edges_collected: 0,
405 c_indirect_drain: None,
406 };
407 }
408
409 // Determine the start of the pre-allocated ranges.
410 let node_start = plan.file_plans[0].node_range.start;
411 let string_start = plan.file_plans[0].string_range.start;
412
413 // Borrow the arena and interner disjointly via the mutation-plane
414 // trait. This is the one-and-only field access this helper makes
415 // on the graph; every downstream step operates on the resulting
416 // slices without revisiting `graph`.
417 let (arena, interner) = graph.nodes_and_strings_mut();
418
419 // Get mutable slices covering the entire pre-allocated region.
420 let node_slice = arena.bulk_slice_mut(node_start, plan.total_nodes);
421 let (str_slice, rc_slice) = interner.bulk_slices_mut(string_start, plan.total_strings);
422
423 // Pre-split into per-file disjoint sub-slices using split_at_mut.
424 let mut node_remaining = &mut *node_slice;
425 let mut str_remaining = &mut *str_slice;
426 let mut rc_remaining = &mut *rc_slice;
427
428 #[allow(clippy::type_complexity)]
429 let mut file_work: Vec<(
430 &mut [Slot<NodeEntry>],
431 &mut [Option<Arc<str>>],
432 &mut [u32],
433 &FilePlan,
434 usize,
435 )> = Vec::with_capacity(plan.file_plans.len());
436
437 for (i, file_plan) in plan.file_plans.iter().enumerate() {
438 let nc = (file_plan.node_range.end - file_plan.node_range.start) as usize;
439 let sc = (file_plan.string_range.end - file_plan.string_range.start) as usize;
440
441 let (n, nr) = node_remaining.split_at_mut(nc);
442 let (s, sr) = str_remaining.split_at_mut(sc);
443 let (r, rr) = rc_remaining.split_at_mut(sc);
444
445 file_work.push((n, s, r, file_plan, i));
446 node_remaining = nr;
447 str_remaining = sr;
448 rc_remaining = rr;
449 }
450
451 // Parallel commit — each closure owns disjoint slices, no contention.
452 let results: Vec<FileCommitResult> = file_work
453 .into_par_iter()
454 .map(|(node_slots, str_slots, rc_slots, file_plan, idx)| {
455 commit_single_file(
456 staging_graphs[idx],
457 file_plan,
458 node_slots,
459 str_slots,
460 rc_slots,
461 )
462 })
463 .collect();
464
465 let total_nodes_written: usize = results.iter().map(|r| r.nodes_written).sum();
466 let total_strings_written: usize = results.iter().map(|r| r.strings_written).sum();
467 let total_edges_collected: usize = results.iter().map(|r| r.edges.len()).sum();
468 let mut per_file_edges = Vec::with_capacity(results.len());
469 let mut per_file_node_ids = Vec::with_capacity(results.len());
470
471 // Cluster B3 (Go T1): aggregate per-file remapped Go hints. Each
472 // file's hints have already been remapped through that file's
473 // local→global NodeId / StringId tables inside `commit_single_file`,
474 // so the merge into the live target is a straightforward extend.
475 let mut all_embedding_hints: Vec<GoEmbeddingHint> = Vec::new();
476 let mut all_named_type_conversion_hints: Vec<GoNamedTypeConversionHint> = Vec::new();
477 let mut all_receiver_call_hints: Vec<GoReceiverCallHint> = Vec::new();
478 // Cluster D2.1: receiver-pointerness per Go method declaration. Same
479 // commit-time NodeId / StringId remap discipline as the other three
480 // vectors above; the consumer is Cluster D2's T1.1 pass and D2's
481 // tightening of D1's bucket classifier.
482 let mut all_method_receiver_hints: Vec<GoMethodReceiverHint> = Vec::new();
483 // Cluster D3 (Go T1): canonical signatures per Go method / function
484 // / named function-type declaration. Same remap discipline as the
485 // four hint vectors above. Consumer is the tightened T1.1
486 // satisfaction predicate and the new T1.3 function-signature
487 // implementation pass.
488 let mut all_method_signature_hints: Vec<GoMethodSignatureHint> = Vec::new();
489 let mut all_function_signature_hints: Vec<GoFunctionSignatureHint> = Vec::new();
490
491 for r in results {
492 per_file_edges.push(r.edges);
493 per_file_node_ids.push(r.node_ids);
494 all_embedding_hints.extend(r.embedding_hints);
495 all_named_type_conversion_hints.extend(r.named_type_conversion_hints);
496 all_receiver_call_hints.extend(r.receiver_call_hints);
497 all_method_receiver_hints.extend(r.method_receiver_hints);
498 all_method_signature_hints.extend(r.method_signature_hints);
499 all_function_signature_hints.extend(r.function_signature_hints);
500 }
501
502 // Cluster B3 / D2.1 / D3: merge aggregated hints into the live
503 // target. This closes the deferred wire-through noted in Cluster A:
504 // every per-file `StagingGraph::go_hints` now lands in the live
505 // target's `GoHints` buffer during Phase 3, with all NodeId /
506 // StringId references remapped to global identities. The
507 // post-Phase-4e `pass_go_method_set_satisfaction` will drain this
508 // buffer.
509 if !all_embedding_hints.is_empty()
510 || !all_named_type_conversion_hints.is_empty()
511 || !all_receiver_call_hints.is_empty()
512 || !all_method_receiver_hints.is_empty()
513 || !all_method_signature_hints.is_empty()
514 || !all_function_signature_hints.is_empty()
515 {
516 let go_hints = graph.go_hints_mut();
517 go_hints.embeddings.extend(all_embedding_hints);
518 go_hints
519 .named_type_conversions
520 .extend(all_named_type_conversion_hints);
521 go_hints.receiver_calls.extend(all_receiver_call_hints);
522 go_hints.method_receivers.extend(all_method_receiver_hints);
523 go_hints
524 .method_signatures
525 .extend(all_method_signature_hints);
526 go_hints
527 .function_signatures
528 .extend(all_function_signature_hints);
529 }
530
531 // --- C indirect-call drain (DESIGN §8.2 / U11) ---
532 //
533 // Sequentially walk the per-file staging graphs and drain each
534 // `CIndirectStagingPayload` into a single per-chunk
535 // [`PhaseCIndirectDrain`]. Sequential (not parallel) because: (a) the
536 // payloads are typically tiny — even a large C TU stages ~tens of
537 // bindings + ~dozens of callsites — and (b) the address-taken names
538 // need their staging-local `StringId`s resolved to owned strings while
539 // we still hold the source `StagingGraph` reference; once Phase 3
540 // returns, the chunk-local `ParsedFile`s drop and the staged strings
541 // become unrecoverable.
542 //
543 // Local-string resolution: `pending_address_taken_names` contains
544 // staging-local `StringId`s interned by `helper.intern(name)` (see
545 // `helper::mark_function_address_taken_by_name`). The applier needs
546 // the underlying `&str` to re-intern through the **post-dedup** graph
547 // interner, so we resolve here via `staging.resolve_local_string`.
548 // The string already had its `intern` ref-count bumped on stage —
549 // the post-4c-prime applier's re-intern produces the canonical global
550 // `StringId` independent of the staging-local id.
551 let c_indirect_drain = collect_c_indirect_drain(plan, staging_graphs);
552
553 Phase3Result {
554 per_file_edges,
555 per_file_node_ids,
556 total_nodes_written,
557 total_strings_written,
558 total_edges_collected,
559 c_indirect_drain,
560 }
561}
562
563/// Drain per-file C indirect-call staging payloads from the chunk.
564///
565/// Returns `Some(PhaseCIndirectDrain)` when at least one file in the chunk
566/// staged a `CIndirectStagingPayload`; otherwise `None` (non-C workspaces).
567/// Sequential rather than parallel — see commentary in
568/// [`phase3_parallel_commit`] for the rationale.
569fn collect_c_indirect_drain(
570 plan: &ChunkCommitPlan,
571 staging_graphs: &[&StagingGraph],
572) -> Option<PhaseCIndirectDrain> {
573 debug_assert_eq!(plan.file_plans.len(), staging_graphs.len());
574
575 let mut drain = PhaseCIndirectDrain::default();
576
577 for (file_plan, staging) in plan.file_plans.iter().zip(staging_graphs.iter()) {
578 let Some(payload) = staging.c_indirect() else {
579 continue;
580 };
581
582 // Resolve local string ids → owned Strings for address-taken names.
583 // A `None` from `resolve_local_string` would indicate a staging-API
584 // misuse (a non-local id was pushed). Skip with a warn rather than
585 // panic so a buggy plugin can't take down the build pipeline.
586 //
587 // Each captured entry pairs the resolved name with the origin
588 // `file_plan.file_id` (DESIGN §8.2 lines 1239-1241), allowing the
589 // post-unification applier to scope the workspace-global by_name
590 // fallback to C-language nodes.
591 for &local_id in &payload.pending_address_taken_names {
592 match staging.resolve_local_string(local_id) {
593 Some(name) => drain.address_taken_names.push(DeferredAddressTakenEntry {
594 function_qualified_name: name.to_owned(),
595 file_id: file_plan.file_id,
596 }),
597 None => log::warn!(
598 "Phase 3 C-indirect drain: address-taken name local string id \
599 {:?} did not resolve in staging graph for file {:?} — skipping. \
600 This indicates the C plugin staged a non-local StringId via \
601 helper.mark_function_address_taken_by_name.",
602 local_id,
603 file_plan.file_id,
604 ),
605 }
606 }
607
608 // `pending_struct_field_signatures` is already `Vec<(String, String, String)>`
609 // — clone the triple set into the drain. We clone (rather than
610 // mutate-take) because `staging` is a `&StagingGraph` shared borrow.
611 drain
612 .struct_field_signatures
613 .extend(payload.pending_struct_field_signatures.iter().cloned());
614
615 // `pending_bindings` is `Vec<PendingBinding>` (owned Strings).
616 // Stamp each binding with its origin `file_plan.file_id` so the
617 // post-unification applier can scope the by_name fallback for
618 // `instance_name` / `target_fn_name` resolution to C-language
619 // nodes (same rationale as `address_taken_names` above).
620 drain.bindings.extend(
621 payload
622 .pending_bindings
623 .iter()
624 .cloned()
625 .map(|b| (file_plan.file_id, b)),
626 );
627
628 // Stamp each indirect callsite with its FileId from the plan, then
629 // append. The applier needs the FileId to construct the persisted
630 // `IndirectCallsite` (which carries `caller: NodeId` + `file_id:
631 // FileId` rather than staging's `caller_qualified_name: String`).
632 drain.indirect_callsites.extend(
633 payload
634 .pending_indirect_callsites
635 .iter()
636 .cloned()
637 .map(|cs| (file_plan.file_id, cs)),
638 );
639
640 // Move the per-file scope index by clone (we hold `&StagingGraph`,
641 // so cannot take). `LocalScopeIndex: Clone` — see
642 // `c_indirect/scope_index.rs:21` documentation header.
643 if let Some(scope_index) = payload.local_scope_index.as_ref() {
644 drain
645 .local_scope_indices
646 .push((file_plan.file_id, scope_index.clone()));
647 }
648 }
649
650 if drain.is_empty() { None } else { Some(drain) }
651}
652
653/// Commit a single file's staging graph into pre-allocated disjoint ranges.
654///
655/// This function operates on slices that belong exclusively to this file,
656/// so it requires no locks or synchronization.
657///
658/// # Steps
659///
660/// 1. **Strings**: Extract `InternString` ops, write `Arc<str>` values into
661/// pre-allocated string slots, build local→global `StringId` remap.
662/// 2. **Nodes**: Extract `AddNode` ops, apply string remap to each `NodeEntry`,
663/// set `file_id`, write into pre-allocated node slots, build expected→actual
664/// `NodeId` remap.
665/// 3. **Edges**: Extract `AddEdge` ops, apply node ID remap to source/target,
666/// assign pre-computed sequence numbers, return as `PendingEdge` vec.
667// Result of committing a single file: edges + committed NodeIds + actual written counts.
668struct FileCommitResult {
669 edges: Vec<PendingEdge>,
670 /// Every `NodeId` committed into the arena for this file, in
671 /// commit order. Used by the sequential post-commit step that
672 /// populates `FileRegistry::per_file_nodes`.
673 node_ids: Vec<NodeId>,
674 nodes_written: usize,
675 strings_written: usize,
676 /// Cluster B3 (Go T1 implements-and-promotion): per-file
677 /// [`GoEmbeddingHint`] / [`GoNamedTypeConversionHint`] /
678 /// [`GoReceiverCallHint`] entries, with their staging-local
679 /// `NodeId` / `StringId` fields remapped to global identities via
680 /// the same tables that drive node + edge commit. The sequential
681 /// post-rayon step in [`phase3_parallel_commit`] aggregates these
682 /// across files and flushes the result into
683 /// [`crate::graph::unified::mutation_target::GraphMutationTarget::go_hints_mut`].
684 ///
685 /// Non-Go staging graphs leave all four vectors empty — no work
686 /// is performed for them.
687 embedding_hints: Vec<GoEmbeddingHint>,
688 named_type_conversion_hints: Vec<GoNamedTypeConversionHint>,
689 receiver_call_hints: Vec<GoReceiverCallHint>,
690 /// Cluster D2.1: per-method receiver-pointerness hints recovered from
691 /// the Go plugin's Phase-1 method emission sites. `method_node` and
692 /// `receiver_type_qualified_name` are remapped via the per-file
693 /// remap tables in the same `commit_single_file` step that drives
694 /// the other three hint vectors.
695 method_receiver_hints: Vec<GoMethodReceiverHint>,
696 /// Cluster D3: canonical-signature hints for Go method declarations
697 /// (top-level methods and interface methods). `method_node` is
698 /// remapped via the per-file node table. `canonical_signature` is a
699 /// plain `String` so no `StringId` remap is needed.
700 method_signature_hints: Vec<GoMethodSignatureHint>,
701 /// Cluster D3: canonical-signature hints for Go function
702 /// declarations and named function-type declarations. `function_node`
703 /// is remapped via the per-file node table; `canonical_signature` is
704 /// plain text.
705 function_signature_hints: Vec<GoFunctionSignatureHint>,
706}
707
708fn commit_single_file(
709 staging: &StagingGraph,
710 plan: &FilePlan,
711 node_slots: &mut [Slot<NodeEntry>],
712 str_slots: &mut [Option<Arc<str>>],
713 rc_slots: &mut [u32],
714) -> FileCommitResult {
715 let ops = staging.operations();
716
717 // --- Step 1: Write strings, build local→global remap ---
718 let (string_remap, strings_written) = write_strings(ops, plan, str_slots, rc_slots);
719
720 // --- Step 2: Write nodes, build expected→actual node ID remap ---
721 let (node_remap, nodes_written, node_ids) = write_nodes(ops, plan, node_slots, &string_remap);
722
723 // --- Step 3: Collect remapped edges with pre-assigned sequence numbers ---
724 let edges = collect_edges(ops, plan, &node_remap, &string_remap);
725
726 // --- Step 4 (Cluster B3 / D2.1 / D3): Remap Go side-channel hints ---
727 //
728 // The Go plugin captures staging-local NodeId / StringId values in
729 // GoHints during Phase-1 parse. Both ID spaces are file-local until
730 // Phase 3 writes the file's nodes and strings into the globally
731 // assigned ranges; once node_remap / string_remap exist, every hint
732 // gets the same identity rewrite as a PendingEdge.
733 let RemappedGoHints {
734 embeddings: embedding_hints,
735 named_type_conversions: named_type_conversion_hints,
736 receiver_calls: receiver_call_hints,
737 method_receivers: method_receiver_hints,
738 method_signatures: method_signature_hints,
739 function_signatures: function_signature_hints,
740 } = remap_go_hints(staging, &node_remap, &string_remap, plan);
741
742 FileCommitResult {
743 edges,
744 node_ids,
745 nodes_written,
746 strings_written,
747 embedding_hints,
748 named_type_conversion_hints,
749 receiver_call_hints,
750 method_receiver_hints,
751 method_signature_hints,
752 function_signature_hints,
753 }
754}
755
756/// Bundle returned by [`remap_go_hints`] so the per-file commit step can
757/// destructure without juggling a tuple of six vectors. Each field
758/// matches its sibling on [`FileCommitResult`].
759struct RemappedGoHints {
760 embeddings: Vec<GoEmbeddingHint>,
761 named_type_conversions: Vec<GoNamedTypeConversionHint>,
762 receiver_calls: Vec<GoReceiverCallHint>,
763 method_receivers: Vec<GoMethodReceiverHint>,
764 method_signatures: Vec<GoMethodSignatureHint>,
765 function_signatures: Vec<GoFunctionSignatureHint>,
766}
767
768/// Remap a `NodeId` through the per-file node-remap table.
769///
770/// Hint construction in the plugin uses staging-local NodeIds (assigned
771/// by `StagingGraph::add_node` / equivalents). After Phase 3 commit the
772/// canonical NodeId for each staged node lives in `node_remap`; the
773/// remap is identity for already-global IDs.
774fn remap_node_id_hint(id: NodeId, node_remap: &HashMap<NodeId, NodeId>) -> NodeId {
775 node_remap.get(&id).copied().unwrap_or(id)
776}
777
778/// Remap a `StringId` through the per-file string-remap table.
779///
780/// Local-tagged staging StringIds are mapped to their global slot ID;
781/// already-global IDs are passed through unchanged.
782fn remap_string_id_hint(id: StringId, string_remap: &HashMap<StringId, StringId>) -> StringId {
783 if id.is_local() {
784 string_remap.get(&id).copied().unwrap_or(id)
785 } else {
786 id
787 }
788}
789
790/// Drain the staging graph's Go hint vectors, remap each entry's
791/// staging-local `NodeId` / `StringId` fields through the per-file
792/// remap tables built by Phase 3 commit, and return four globally-
793/// addressable vectors ready to be merged into the live target.
794///
795/// Non-Go staging graphs return empty vectors with no allocations
796/// beyond the empty `Vec::new()` headers.
797fn remap_go_hints(
798 staging: &StagingGraph,
799 node_remap: &HashMap<NodeId, NodeId>,
800 string_remap: &HashMap<StringId, StringId>,
801 plan: &FilePlan,
802) -> RemappedGoHints {
803 let hints = staging.go_hints();
804 if hints.embeddings.is_empty()
805 && hints.named_type_conversions.is_empty()
806 && hints.receiver_calls.is_empty()
807 && hints.method_receivers.is_empty()
808 && hints.method_signatures.is_empty()
809 && hints.function_signatures.is_empty()
810 {
811 return RemappedGoHints {
812 embeddings: Vec::new(),
813 named_type_conversions: Vec::new(),
814 receiver_calls: Vec::new(),
815 method_receivers: Vec::new(),
816 method_signatures: Vec::new(),
817 function_signatures: Vec::new(),
818 };
819 }
820
821 let embeddings: Vec<GoEmbeddingHint> = hints
822 .embeddings
823 .iter()
824 .map(|h| GoEmbeddingHint {
825 outer: remap_node_id_hint(h.outer, node_remap),
826 inner_qualified_name: remap_string_id_hint(h.inner_qualified_name, string_remap),
827 pointerness: h.pointerness,
828 file: plan.file_id,
829 })
830 .collect();
831
832 let named_type_conversions: Vec<GoNamedTypeConversionHint> = hints
833 .named_type_conversions
834 .iter()
835 .map(|h| GoNamedTypeConversionHint {
836 call_site: remap_node_id_hint(h.call_site, node_remap),
837 target_type_qualified_name: remap_string_id_hint(
838 h.target_type_qualified_name,
839 string_remap,
840 ),
841 argument_node: remap_node_id_hint(h.argument_node, node_remap),
842 file: plan.file_id,
843 })
844 .collect();
845
846 let receiver_calls: Vec<GoReceiverCallHint> = hints
847 .receiver_calls
848 .iter()
849 .map(|h| GoReceiverCallHint {
850 call_site: remap_node_id_hint(h.call_site, node_remap),
851 callee_method: remap_node_id_hint(h.callee_method, node_remap),
852 method_name: remap_string_id_hint(h.method_name, string_remap),
853 receiver: match &h.receiver {
854 GoReceiverHintKind::LocalIdent { binding_local } => {
855 GoReceiverHintKind::LocalIdent {
856 binding_local: remap_node_id_hint(*binding_local, node_remap),
857 }
858 }
859 // The Type-/Pointer-Prefixed and CallReturn variants
860 // carry plain `String` text — no remap required.
861 GoReceiverHintKind::TypePrefixed { type_text } => {
862 GoReceiverHintKind::TypePrefixed {
863 type_text: type_text.clone(),
864 }
865 }
866 GoReceiverHintKind::PointerPrefixed { type_text } => {
867 GoReceiverHintKind::PointerPrefixed {
868 type_text: type_text.clone(),
869 }
870 }
871 GoReceiverHintKind::CallReturn { callee_qn } => GoReceiverHintKind::CallReturn {
872 callee_qn: callee_qn.clone(),
873 },
874 },
875 argument_count: h.argument_count,
876 is_async: h.is_async,
877 file: plan.file_id,
878 })
879 .collect();
880
881 let method_receivers: Vec<GoMethodReceiverHint> = hints
882 .method_receivers
883 .iter()
884 .map(|h| GoMethodReceiverHint {
885 method_node: remap_node_id_hint(h.method_node, node_remap),
886 receiver_type_qualified_name: remap_string_id_hint(
887 h.receiver_type_qualified_name,
888 string_remap,
889 ),
890 receiver_pointerness: h.receiver_pointerness,
891 file: plan.file_id,
892 })
893 .collect();
894
895 // Cluster D3: method-signature and function-signature hints. Only
896 // the NodeId field requires remap; `canonical_signature` is a plain
897 // `String` produced by `canonicalise_go_signature` and is identity
898 // across the commit boundary.
899 let method_signatures: Vec<GoMethodSignatureHint> = hints
900 .method_signatures
901 .iter()
902 .map(|h| GoMethodSignatureHint {
903 method_node: remap_node_id_hint(h.method_node, node_remap),
904 canonical_signature: h.canonical_signature.clone(),
905 file: plan.file_id,
906 })
907 .collect();
908
909 let function_signatures: Vec<GoFunctionSignatureHint> = hints
910 .function_signatures
911 .iter()
912 .map(|h| GoFunctionSignatureHint {
913 function_node: remap_node_id_hint(h.function_node, node_remap),
914 canonical_signature: h.canonical_signature.clone(),
915 file: plan.file_id,
916 })
917 .collect();
918
919 RemappedGoHints {
920 embeddings,
921 named_type_conversions,
922 receiver_calls,
923 method_receivers,
924 method_signatures,
925 function_signatures,
926 }
927}
928
929/// Write staged strings into pre-allocated interner slots.
930///
931/// Validates that each `InternString` op has a local `StringId` and that
932/// no duplicate local IDs exist (matching the serial `commit_strings` checks).
933///
934/// Returns `(remap, strings_written)`.
935fn write_strings(
936 ops: &[StagingOp],
937 plan: &FilePlan,
938 str_slots: &mut [Option<Arc<str>>],
939 rc_slots: &mut [u32],
940) -> (HashMap<StringId, StringId>, usize) {
941 let mut remap = HashMap::new();
942 let mut string_cursor = 0usize;
943
944 for op in ops {
945 if let StagingOp::InternString { local_id, value } = op {
946 // Validate: only local IDs are allowed in staging (matching serial commit_strings)
947 assert!(
948 local_id.is_local(),
949 "non-local StringId {:?} in InternString op for file {:?}",
950 local_id,
951 plan.file_id,
952 );
953 // Validate: no duplicate local IDs (matching serial commit_strings)
954 assert!(
955 !remap.contains_key(local_id),
956 "duplicate local StringId {:?} in InternString op for file {:?}",
957 local_id,
958 plan.file_id,
959 );
960
961 if string_cursor >= str_slots.len() {
962 log::warn!(
963 "string slot overflow in file {:?}: cursor={string_cursor}, slots={}, skipping remaining strings",
964 plan.file_id,
965 str_slots.len()
966 );
967 break;
968 }
969
970 // The global StringId for this string is the pre-allocated slot index.
971 #[allow(clippy::cast_possible_truncation)] // cursor is bounded by allocated slot count
972 let global_id = StringId::new(plan.string_range.start + string_cursor as u32);
973
974 // Write the string into the pre-allocated slot.
975 str_slots[string_cursor] = Some(Arc::from(value.as_str()));
976 rc_slots[string_cursor] = 1;
977
978 remap.insert(*local_id, global_id);
979 string_cursor += 1;
980 }
981 }
982
983 (remap, string_cursor)
984}
985
986/// Remap all `StringId` fields in a `NodeEntry` using a local→global table.
987///
988/// Required field (`name`) is always remapped if local.
989/// Optional fields (`signature`, `doc`, `qualified_name`, `visibility`)
990/// are remapped if present and local.
991fn remap_node_entry_string_ids(entry: &mut NodeEntry, remap: &HashMap<StringId, StringId>) {
992 remap_required_local(&mut entry.name, remap);
993 remap_option_local(&mut entry.signature, remap);
994 remap_option_local(&mut entry.doc, remap);
995 remap_option_local(&mut entry.qualified_name, remap);
996 remap_option_local(&mut entry.visibility, remap);
997}
998
999/// Remap all local `StringId` fields in an `EdgeKind`.
1000///
1001/// Uses the same exhaustive match as `remap_edge_kind_string_ids`, but
1002/// only remaps local IDs (those with `LOCAL_TAG_BIT` set).
1003#[allow(clippy::match_same_arms)]
1004fn remap_edge_kind_local_string_ids(kind: &mut EdgeKind, remap: &HashMap<StringId, StringId>) {
1005 match kind {
1006 EdgeKind::Imports { alias, .. } => remap_option_local(alias, remap),
1007 EdgeKind::Exports { alias, .. } => remap_option_local(alias, remap),
1008 EdgeKind::TypeOf { name, .. } => remap_option_local(name, remap),
1009 EdgeKind::TraitMethodBinding {
1010 trait_name,
1011 impl_type,
1012 ..
1013 } => {
1014 remap_required_local(trait_name, remap);
1015 remap_required_local(impl_type, remap);
1016 }
1017 EdgeKind::HttpRequest { url, .. } => remap_option_local(url, remap),
1018 EdgeKind::GrpcCall { service, method } => {
1019 remap_required_local(service, remap);
1020 remap_required_local(method, remap);
1021 }
1022 EdgeKind::DbQuery { table, .. } => remap_option_local(table, remap),
1023 EdgeKind::TableRead { table_name, schema } => {
1024 remap_required_local(table_name, remap);
1025 remap_option_local(schema, remap);
1026 }
1027 EdgeKind::TableWrite {
1028 table_name, schema, ..
1029 } => {
1030 remap_required_local(table_name, remap);
1031 remap_option_local(schema, remap);
1032 }
1033 EdgeKind::TriggeredBy {
1034 trigger_name,
1035 schema,
1036 } => {
1037 remap_required_local(trigger_name, remap);
1038 remap_option_local(schema, remap);
1039 }
1040 EdgeKind::MessageQueue { protocol, topic } => {
1041 if let MqProtocol::Other(s) = protocol {
1042 remap_required_local(s, remap);
1043 }
1044 remap_option_local(topic, remap);
1045 }
1046 EdgeKind::WebSocket { event } => remap_option_local(event, remap),
1047 EdgeKind::GraphQLOperation { operation } => remap_required_local(operation, remap),
1048 EdgeKind::ProcessExec { command } => remap_required_local(command, remap),
1049 EdgeKind::FileIpc { path_pattern } => remap_option_local(path_pattern, remap),
1050 EdgeKind::ProtocolCall { protocol, metadata } => {
1051 remap_required_local(protocol, remap);
1052 remap_option_local(metadata, remap);
1053 }
1054 // Variants without StringId fields — exhaustive, no wildcard.
1055 EdgeKind::Defines
1056 | EdgeKind::Contains
1057 | EdgeKind::Calls { .. }
1058 | EdgeKind::References
1059 | EdgeKind::Inherits
1060 | EdgeKind::Implements
1061 | EdgeKind::LifetimeConstraint { .. }
1062 | EdgeKind::MacroExpansion { .. }
1063 | EdgeKind::FfiCall { .. }
1064 | EdgeKind::WebAssemblyCall
1065 | EdgeKind::GenericBound
1066 | EdgeKind::AnnotatedWith
1067 | EdgeKind::AnnotationParam
1068 | EdgeKind::LambdaCaptures
1069 | EdgeKind::ModuleExports
1070 | EdgeKind::ModuleRequires
1071 | EdgeKind::ModuleOpens
1072 | EdgeKind::ModuleProvides
1073 | EdgeKind::TypeArgument
1074 | EdgeKind::ExtensionReceiver
1075 | EdgeKind::CompanionOf
1076 | EdgeKind::SealedPermit => {}
1077 }
1078}
1079
1080/// Remap a required local `StringId` in place.
1081///
1082/// Panics if a local ID has no mapping, matching the serial
1083/// `apply_string_remap` behavior that returned `UnmappedLocalStringId`.
1084fn remap_required_local(id: &mut StringId, remap: &HashMap<StringId, StringId>) {
1085 if id.is_local() {
1086 let global = remap.get(id).unwrap_or_else(|| {
1087 panic!("unmapped local StringId {id:?} — missing intern_string op?")
1088 });
1089 *id = *global;
1090 }
1091}
1092
1093/// Remap an optional local `StringId` in place.
1094fn remap_option_local(opt: &mut Option<StringId>, remap: &HashMap<StringId, StringId>) {
1095 if let Some(id) = opt
1096 && id.is_local()
1097 {
1098 let global = remap.get(id).unwrap_or_else(|| {
1099 panic!("unmapped local StringId {id:?} — missing intern_string op?")
1100 });
1101 *id = *global;
1102 }
1103}
1104
1105/// Write staged nodes into pre-allocated arena slots.
1106///
1107/// Returns `(remap, nodes_written, node_ids)`. `node_ids` is the Vec of
1108/// every `NodeId` committed for this file, in commit order, for use by
1109/// the sequential bucket-population post-step.
1110fn write_nodes(
1111 ops: &[StagingOp],
1112 plan: &FilePlan,
1113 node_slots: &mut [Slot<NodeEntry>],
1114 string_remap: &HashMap<StringId, StringId>,
1115) -> (HashMap<NodeId, NodeId>, usize, Vec<NodeId>) {
1116 let mut node_remap = HashMap::new();
1117 let mut node_cursor = 0usize;
1118 let mut node_ids: Vec<NodeId> = Vec::with_capacity(node_slots.len());
1119
1120 for op in ops {
1121 if let StagingOp::AddNode {
1122 entry, expected_id, ..
1123 } = op
1124 {
1125 if node_cursor >= node_slots.len() {
1126 log::warn!(
1127 "node slot overflow in file {:?}: cursor={node_cursor}, slots={}, skipping remaining nodes",
1128 plan.file_id,
1129 node_slots.len()
1130 );
1131 break;
1132 }
1133
1134 let mut entry = entry.clone();
1135
1136 // Apply string remap to all StringId fields in the entry.
1137 remap_node_entry_string_ids(&mut entry, string_remap);
1138
1139 // Set the file ID from the plan.
1140 entry.file = plan.file_id;
1141
1142 // The actual NodeId is the pre-allocated slot index with generation 1.
1143 #[allow(clippy::cast_possible_truncation)] // cursor is bounded by allocated slot count
1144 let actual_index = plan.node_range.start + node_cursor as u32;
1145 let actual_id = NodeId::new(actual_index, 1);
1146
1147 // Write into the pre-allocated slot.
1148 node_slots[node_cursor] = Slot::new_occupied(1, entry);
1149
1150 if let Some(expected) = expected_id {
1151 node_remap.insert(*expected, actual_id);
1152 }
1153
1154 node_ids.push(actual_id);
1155 node_cursor += 1;
1156 }
1157 }
1158
1159 (node_remap, node_cursor, node_ids)
1160}
1161
1162/// Collect staged edges with remapped node IDs, string IDs, and pre-assigned
1163/// sequence numbers.
1164fn collect_edges(
1165 ops: &[StagingOp],
1166 plan: &FilePlan,
1167 node_remap: &HashMap<NodeId, NodeId>,
1168 string_remap: &HashMap<StringId, StringId>,
1169) -> Vec<PendingEdge> {
1170 let mut edges = Vec::new();
1171
1172 for op in ops {
1173 if let StagingOp::AddEdge {
1174 source,
1175 target,
1176 kind,
1177 spans,
1178 ..
1179 } = op
1180 {
1181 let actual_source = node_remap.get(source).copied().unwrap_or(*source);
1182 let actual_target = node_remap.get(target).copied().unwrap_or(*target);
1183
1184 // Clone and remap any local StringIds in the EdgeKind.
1185 let mut remapped_kind = kind.clone();
1186 remap_edge_kind_local_string_ids(&mut remapped_kind, string_remap);
1187
1188 edges.push(PendingEdge {
1189 source: actual_source,
1190 target: actual_target,
1191 kind: remapped_kind,
1192 file: plan.file_id,
1193 spans: spans.clone(),
1194 });
1195 }
1196 }
1197
1198 edges
1199}
1200
1201/// Remap a required `StringId` using the dedup remap table.
1202///
1203/// If the ID is in the remap table, it is replaced with the canonical ID.
1204/// Otherwise, it is left unchanged (identity mapping).
1205#[allow(clippy::implicit_hasher)]
1206pub fn remap_string_id(id: &mut StringId, remap: &HashMap<StringId, StringId>) {
1207 if let Some(&canonical) = remap.get(id) {
1208 *id = canonical;
1209 }
1210}
1211
1212/// Remap an optional `StringId` using the dedup remap table.
1213#[allow(clippy::implicit_hasher)]
1214pub fn remap_option_string_id(id: &mut Option<StringId>, remap: &HashMap<StringId, StringId>) {
1215 if let Some(inner) = id {
1216 remap_string_id(inner, remap);
1217 }
1218}
1219
1220/// Exhaustive remap of all `StringId` fields in an `EdgeKind`.
1221///
1222/// No wildcard arm — the compiler ensures completeness when new variants
1223/// are added to `EdgeKind`.
1224#[allow(clippy::match_same_arms, clippy::implicit_hasher)] // Arms are separated by category for documentation clarity
1225pub fn remap_edge_kind_string_ids(kind: &mut EdgeKind, remap: &HashMap<StringId, StringId>) {
1226 match kind {
1227 // === Variants WITH StringId fields ===
1228 EdgeKind::Imports { alias, .. } => remap_option_string_id(alias, remap),
1229 EdgeKind::Exports { alias, .. } => remap_option_string_id(alias, remap),
1230 EdgeKind::TypeOf { name, .. } => remap_option_string_id(name, remap),
1231 EdgeKind::TraitMethodBinding {
1232 trait_name,
1233 impl_type,
1234 ..
1235 } => {
1236 remap_string_id(trait_name, remap);
1237 remap_string_id(impl_type, remap);
1238 }
1239 EdgeKind::HttpRequest { url, .. } => remap_option_string_id(url, remap),
1240 EdgeKind::GrpcCall { service, method } => {
1241 remap_string_id(service, remap);
1242 remap_string_id(method, remap);
1243 }
1244 EdgeKind::DbQuery { table, .. } => remap_option_string_id(table, remap),
1245 EdgeKind::TableRead { table_name, schema } => {
1246 remap_string_id(table_name, remap);
1247 remap_option_string_id(schema, remap);
1248 }
1249 EdgeKind::TableWrite {
1250 table_name, schema, ..
1251 } => {
1252 remap_string_id(table_name, remap);
1253 remap_option_string_id(schema, remap);
1254 }
1255 EdgeKind::TriggeredBy {
1256 trigger_name,
1257 schema,
1258 } => {
1259 remap_string_id(trigger_name, remap);
1260 remap_option_string_id(schema, remap);
1261 }
1262 EdgeKind::MessageQueue { protocol, topic } => {
1263 if let MqProtocol::Other(s) = protocol {
1264 remap_string_id(s, remap);
1265 }
1266 remap_option_string_id(topic, remap);
1267 }
1268 EdgeKind::WebSocket { event } => remap_option_string_id(event, remap),
1269 EdgeKind::GraphQLOperation { operation } => remap_string_id(operation, remap),
1270 EdgeKind::ProcessExec { command } => remap_string_id(command, remap),
1271 EdgeKind::FileIpc { path_pattern } => remap_option_string_id(path_pattern, remap),
1272 EdgeKind::ProtocolCall { protocol, metadata } => {
1273 remap_string_id(protocol, remap);
1274 remap_option_string_id(metadata, remap);
1275 }
1276 // === Variants WITHOUT StringId fields — exhaustive, no wildcard ===
1277 EdgeKind::Defines
1278 | EdgeKind::Contains
1279 | EdgeKind::Calls { .. }
1280 | EdgeKind::References
1281 | EdgeKind::Inherits
1282 | EdgeKind::Implements
1283 | EdgeKind::LifetimeConstraint { .. }
1284 | EdgeKind::MacroExpansion { .. }
1285 | EdgeKind::FfiCall { .. }
1286 | EdgeKind::WebAssemblyCall
1287 | EdgeKind::GenericBound
1288 | EdgeKind::AnnotatedWith
1289 | EdgeKind::AnnotationParam
1290 | EdgeKind::LambdaCaptures
1291 | EdgeKind::ModuleExports
1292 | EdgeKind::ModuleRequires
1293 | EdgeKind::ModuleOpens
1294 | EdgeKind::ModuleProvides
1295 | EdgeKind::TypeArgument
1296 | EdgeKind::ExtensionReceiver
1297 | EdgeKind::CompanionOf
1298 | EdgeKind::SealedPermit => {}
1299 }
1300}
1301
1302// === Phase 4: Post-chunk Finalization ===
1303
1304/// Apply global string dedup remap to all `StringId` fields in a `NodeEntry`.
1305///
1306/// This is the Phase 4 counterpart to `remap_node_entry_string_ids` (Phase 3).
1307/// Phase 3 remaps local→global; Phase 4 remaps duplicate global→canonical global.
1308#[allow(clippy::implicit_hasher)]
1309pub fn remap_node_entry_global(entry: &mut NodeEntry, remap: &HashMap<StringId, StringId>) {
1310 remap_string_id(&mut entry.name, remap);
1311 remap_option_string_id(&mut entry.signature, remap);
1312 remap_option_string_id(&mut entry.doc, remap);
1313 remap_option_string_id(&mut entry.qualified_name, remap);
1314 remap_option_string_id(&mut entry.visibility, remap);
1315}
1316
1317/// Apply global string dedup remap to all nodes in the arena and all pending edges.
1318///
1319/// This is Phase 4b of the parallel commit pipeline. After `build_dedup_table()`
1320/// produces a remap table, this function applies it to every `StringId` in:
1321/// - All `NodeEntry` fields in the arena
1322/// - All `EdgeKind` fields in the pending edges
1323#[allow(clippy::implicit_hasher)]
1324pub fn phase4_apply_global_remap(
1325 arena: &mut NodeArena,
1326 all_edges: &mut [Vec<PendingEdge>],
1327 remap: &HashMap<StringId, StringId>,
1328) {
1329 if remap.is_empty() {
1330 return;
1331 }
1332
1333 // Remap all nodes
1334 for (_id, entry) in arena.iter_mut() {
1335 remap_node_entry_global(entry, remap);
1336 }
1337
1338 // Remap all edges
1339 for file_edges in all_edges.iter_mut() {
1340 for edge in file_edges.iter_mut() {
1341 remap_edge_kind_string_ids(&mut edge.kind, remap);
1342 }
1343 }
1344}
1345
1346/// Statistics from Phase 4c-prime cross-file node unification.
1347#[derive(Debug, Default)]
1348pub struct UnificationStats {
1349 /// Total (qualified_name, kind) groups of size >= 2 examined.
1350 pub candidate_pairs_examined: usize,
1351 /// Number of loser nodes merged into winners.
1352 pub nodes_merged: usize,
1353 /// Number of PendingEdge fields rewritten.
1354 pub edges_rewritten: usize,
1355 /// Number of loser nodes (metadata merged into winners, slot kept inert).
1356 pub nodes_inert: usize,
1357 /// Time spent in the unification pass (milliseconds).
1358 pub elapsed_ms: u64,
1359}
1360
1361/// Phase 4c-prime: Unify cross-file duplicate nodes sharing the same
1362/// canonical qualified name and a call-compatible kind.
1363///
1364/// Runs after `rebuild_indices` (Phase 4c) which populates `by_qualified_name`,
1365/// and before `pending_edges_to_delta` (Phase 4d) so the remap operates on
1366/// `PendingEdge` targets, not committed `DeltaEdge`s.
1367///
1368/// **Winner selection**: Among nodes sharing a qualified name and call-compatible
1369/// kinds, the node with `start_line > 0` wins. Tie-break in order:
1370/// 1. Wider `end_line - start_line` span.
1371/// 2. **Lexicographically smallest file path** (resolved via the rebuild
1372/// plane's [`FileRegistry`]). Phase 3e correctness requires the
1373/// path-based tie-break rather than the previous `FileId` comparison,
1374/// because `FileId` slot assignment differs between a fresh full
1375/// rebuild and an incremental rebuild — the incremental path clones
1376/// the existing `FileRegistry` and appends new paths, while the full
1377/// path assigns FileIds in filesystem-walk order from an empty
1378/// registry. Two builds of the same logical workspace therefore
1379/// disagree on which `FileId` is smaller when duplicate definitions
1380/// tie on span width, flipping the unification winner and stranding
1381/// `qualified_name` on the wrong side of the merge. Tie-breaking on
1382/// the (stable-across-builds) path makes winner selection
1383/// representation-independent.
1384/// 3. Final fallback: smaller `NodeId::index()` when paths also tie
1385/// (e.g. two definitions in the same file — rare but possible via
1386/// duplicate declarations). `NodeId` is deterministic within a
1387/// single build so this keeps the fallback stable for any individual
1388/// build even if it isn't invariant across representations.
1389///
1390/// **Safety**: Caller must hold an exclusive write lock on the graph.
1391pub(crate) fn phase4c_prime_unify_cross_file_nodes<
1392 G: crate::graph::unified::mutation_target::GraphMutationTarget,
1393>(
1394 graph: &mut G,
1395 all_edges: &mut [Vec<PendingEdge>],
1396) -> UnificationStats {
1397 use crate::graph::unified::mutation_target::GraphMutationTarget;
1398
1399 use super::helper::CALL_COMPATIBLE_KINDS;
1400 use super::unification::{NodeRemapTable, merge_node_into};
1401 use std::time::Instant;
1402
1403 let start = Instant::now();
1404 let mut stats = UnificationStats::default();
1405
1406 // Collect candidates: walk arena, group by qualified_name for nodes
1407 // with call-compatible kinds. Only groups of size >= 2 need unification.
1408 let mut qn_groups: HashMap<crate::graph::unified::string::StringId, Vec<NodeId>> =
1409 HashMap::new();
1410
1411 for (node_id, entry) in GraphMutationTarget::nodes(graph).iter() {
1412 if !CALL_COMPATIBLE_KINDS.contains(&entry.kind) {
1413 continue;
1414 }
1415 if let Some(qn_id) = entry.qualified_name {
1416 qn_groups.entry(qn_id).or_default().push(node_id);
1417 }
1418 }
1419
1420 // Filter to groups with 2+ members
1421 let groups_to_unify: Vec<Vec<NodeId>> = qn_groups
1422 .into_values()
1423 .filter(|group| {
1424 if group.len() >= 2 {
1425 stats.candidate_pairs_examined += 1;
1426 true
1427 } else {
1428 false
1429 }
1430 })
1431 .collect();
1432
1433 // Now perform merges
1434 let mut remap = NodeRemapTable::with_capacity(groups_to_unify.len());
1435
1436 // Pre-resolve every candidate node's canonical path-based tie-break
1437 // key into an owned `String` keyed by `NodeId`. Lifting the resolution
1438 // here instead of inside the `max_by` comparator avoids re-borrowing
1439 // `graph` immutably from a closure that lives across the
1440 // `merge_node_into(&mut graph, …)` call below. Without this
1441 // precomputation the borrow checker rejects the mutation loop because
1442 // the comparator closure captures the immutable borrow of `graph`
1443 // required by `path_key`.
1444 //
1445 // Path conversion goes through `Arc<Path>::to_string_lossy()` because
1446 // `Path` does not implement `Ord` lexicographically across platforms
1447 // consistently; forcing a canonical string form keeps the tie-break
1448 // deterministic on any host filesystem. When the registry can't
1449 // resolve a `FileId` (shouldn't happen in practice — every live
1450 // node's `FileId` was registered before the node was allocated) we
1451 // fall back to an empty string so the comparison still produces a
1452 // total order. Empty resolves tie-break each other stably (then fall
1453 // through to the `NodeId` index tie-break).
1454 let path_keys: HashMap<NodeId, String> = {
1455 let arena = GraphMutationTarget::nodes(graph);
1456 let files = GraphMutationTarget::files(graph);
1457 let mut out: HashMap<NodeId, String> =
1458 HashMap::with_capacity(groups_to_unify.iter().map(Vec::len).sum());
1459 for group in &groups_to_unify {
1460 for &nid in group {
1461 if out.contains_key(&nid) {
1462 continue;
1463 }
1464 let key = arena
1465 .get(nid)
1466 .and_then(|entry| files.resolve(entry.file))
1467 .map_or_else(String::new, |path| path.to_string_lossy().into_owned());
1468 out.insert(nid, key);
1469 }
1470 }
1471 out
1472 };
1473 let empty_path_key = String::new();
1474
1475 for group in &groups_to_unify {
1476 // Pick winner: prefer start_line > 0, tie-break by wider span,
1477 // then smaller path (stable across rebuild representations),
1478 // then smaller NodeId index.
1479 let winner_id = *group
1480 .iter()
1481 .max_by(|&&a, &&b| {
1482 let ea = GraphMutationTarget::nodes(graph).get(a);
1483 let eb = GraphMutationTarget::nodes(graph).get(b);
1484 match (ea, eb) {
1485 (Some(ea), Some(eb)) => {
1486 // Primary: prefer non-zero start_line
1487 let a_real = ea.start_line > 0;
1488 let b_real = eb.start_line > 0;
1489 match (a_real, b_real) {
1490 (true, false) => std::cmp::Ordering::Greater,
1491 (false, true) => std::cmp::Ordering::Less,
1492 _ => {
1493 // Tie-break 1: prefer wider span
1494 let a_range = ea.end_line.saturating_sub(ea.start_line);
1495 let b_range = eb.end_line.saturating_sub(eb.start_line);
1496 a_range
1497 .cmp(&b_range)
1498 .then_with(|| {
1499 // Tie-break 2: prefer smaller path
1500 // (reversed because `max_by` picks the
1501 // greater side — we want smaller path
1502 // to win, so invert the direct compare).
1503 let pa = path_keys.get(&a).unwrap_or(&empty_path_key);
1504 let pb = path_keys.get(&b).unwrap_or(&empty_path_key);
1505 pb.cmp(pa)
1506 })
1507 .then_with(|| {
1508 // Tie-break 3: smaller NodeId index
1509 // (stable within a single build;
1510 // deterministic fallback for co-located
1511 // duplicate definitions).
1512 b.index().cmp(&a.index())
1513 })
1514 }
1515 }
1516 }
1517 (Some(_), None) => std::cmp::Ordering::Greater,
1518 (None, Some(_)) => std::cmp::Ordering::Less,
1519 (None, None) => std::cmp::Ordering::Equal,
1520 }
1521 })
1522 .expect("group is non-empty");
1523
1524 // Merge all losers into winner
1525 for &node_id in group {
1526 if node_id == winner_id {
1527 continue;
1528 }
1529 match merge_node_into(GraphMutationTarget::nodes_mut(graph), node_id, winner_id) {
1530 Ok(()) => {
1531 remap.insert(node_id, winner_id);
1532 stats.nodes_merged += 1;
1533 stats.nodes_inert += 1;
1534 }
1535 Err(e) => {
1536 log::debug!("Phase 4c-prime: skipping merge ({e})");
1537 }
1538 }
1539 }
1540 }
1541
1542 // Apply remap table to all pending edges AND to every committed
1543 // edge already in the graph's edge store.
1544 //
1545 // The `apply_to_edges` call keeps PendingEdges (the output of this
1546 // chunk's parallel commit) pointing at canonical winners before
1547 // Phase 4d converts them into `DeltaEdge`s. On a full build that is
1548 // sufficient — no committed edges exist yet.
1549 //
1550 // The `apply_to_committed_edges` call closes the Phase 3e incremental
1551 // gap: the rebuild plane clones the pre-edit graph's committed edges
1552 // via `clone_for_rebuild`, so a newly-reparsed file whose definition
1553 // becomes the unification winner can leave surviving cross-file
1554 // edges pointing at what is now an inert loser slot. Retargeting the
1555 // committed edges through `remap` is the only way those edges
1556 // observe the canonical winner after finalize. On a full build the
1557 // second call is a no-op (edge store is empty).
1558 if !remap.is_empty() {
1559 let pre_count: usize = all_edges.iter().map(|v| v.len()).sum();
1560 remap.apply_to_edges(all_edges);
1561 remap.apply_to_committed_edges(GraphMutationTarget::edges(graph));
1562 stats.edges_rewritten = pre_count; // conservative: all edges walked
1563
1564 // Keep FileRegistry::per_file_nodes consistent with the arena.
1565 //
1566 // [`merge_node_into`] (see `unification.rs`) intentionally does
1567 // **not** vacate the loser slot — the slot stays `Occupied` but
1568 // inert so `NodeArena::slot_count()` (which CSR row_ptr sizing
1569 // depends on) is preserved. Because the slot is still live per
1570 // `NodeArena::iter()`, the §F.1 bucket bijection would panic
1571 // with "live node absent from all buckets" if we purged losers
1572 // from their home bucket.
1573 //
1574 // Therefore: losers stay in whichever per-file bucket Phase 3
1575 // first committed them to. That bucket's `FileId` matches the
1576 // loser's `NodeEntry.file`, so (c) passes. Each loser is in
1577 // exactly one bucket, so (b) passes. Every live arena slot is
1578 // accounted for by some bucket, so (d) passes. The §K master
1579 // matrix already admits this semantics — inert merged-losers
1580 // are semantically equivalent to any other live `NodeArena`
1581 // entry for bucket-membership purposes.
1582 //
1583 // Name-resolution containment (Gate 0d iter-1 blocker).
1584 //
1585 // `merge_node_into` now ALSO clears the loser's `name` and
1586 // `qualified_name` fields (to `StringId::INVALID` / `None`), and
1587 // `AuxiliaryIndices::build_from_arena` skips any arena entry
1588 // whose `name == StringId::INVALID` when rebuilding the name,
1589 // qualified-name, kind, and file buckets. The second
1590 // `rebuild_indices()` call in `build_unified_graph_inner`
1591 // (entrypoint.rs:571, right below this function) runs AFTER
1592 // unification, so the buckets surfaced by `indices.by_name` /
1593 // `by_qualified_name` / `by_kind` / `by_file` contain only
1594 // winners — every public name-resolution surface
1595 // (`resolution::exact_qualified_bucket`,
1596 // `graph::find_by_pattern`, etc.) is therefore free of
1597 // unified-away duplicates. The only publish-visible bucket that
1598 // still references losers is `FileRegistry::per_file_nodes`,
1599 // which preserves the §F.1 bucket bijection without surfacing
1600 // them through name resolution.
1601 //
1602 // Historical note: an earlier iteration of this pass called
1603 // `retain_nodes_in_buckets` to purge losers; that matched a
1604 // stale understanding where `merge_node_into` was expected to
1605 // vacate the slot. Gate 0d's bucket-bijection invariant
1606 // surfaced the mismatch (every full rebuild produced a live
1607 // slot with no bucket entry). The fix is to align with the
1608 // unification contract: inert slots remain in their home
1609 // bucket, but `AuxiliaryIndices` treats them as name-invisible.
1610 }
1611
1612 stats.elapsed_ms = start.elapsed().as_millis() as u64;
1613 stats
1614}
1615
1616/// Convert per-file `PendingEdge` collections to per-file `DeltaEdge` collections
1617/// with monotonically increasing sequence numbers.
1618///
1619/// The sequence numbers are assigned file-by-file, edge-by-edge, starting from
1620/// `seq_start`. This produces the deterministic ordering required by
1621/// `BidirectionalEdgeStore::add_edges_bulk_ordered()`.
1622#[must_use]
1623pub fn pending_edges_to_delta(
1624 per_file_edges: &[Vec<PendingEdge>],
1625 seq_start: u64,
1626) -> (Vec<Vec<DeltaEdge>>, u64) {
1627 let mut seq = seq_start;
1628 let mut result = Vec::with_capacity(per_file_edges.len());
1629
1630 for file_edges in per_file_edges {
1631 let mut delta_vec = Vec::with_capacity(file_edges.len());
1632 for edge in file_edges {
1633 delta_vec.push(DeltaEdge::with_spans(
1634 edge.source,
1635 edge.target,
1636 edge.kind.clone(),
1637 seq,
1638 DeltaOp::Add,
1639 edge.file,
1640 edge.spans.clone(),
1641 ));
1642 seq += 1;
1643 }
1644 result.push(delta_vec);
1645 }
1646
1647 (result, seq)
1648}
1649
1650/// Rebuild the auxiliary indices on `graph` from its current node arena.
1651///
1652/// Generic counterpart to the inherent [`CodeGraph::rebuild_indices`].
1653/// Takes a [`GraphMutationTarget`] so both the full-build
1654/// (`build_unified_graph_inner`) and incremental-rebuild
1655/// (`incremental_rebuild` on `RebuildGraph`) pipelines can share the
1656/// same helper. The inherent method now delegates here so the
1657/// implementation lives in exactly one place.
1658///
1659/// Internally uses [`GraphMutationTarget::nodes_and_indices_mut`] to
1660/// acquire a disjoint `(&NodeArena, &mut AuxiliaryIndices)` pair, then
1661/// hands them to [`AuxiliaryIndices::build_from_arena`] which clears
1662/// the existing indices and rebuilds in a single pass without
1663/// per-element duplicate checking.
1664///
1665/// [`CodeGraph::rebuild_indices`]: crate::graph::unified::concurrent::CodeGraph::rebuild_indices
1666/// [`AuxiliaryIndices::build_from_arena`]: crate::graph::unified::storage::indices::AuxiliaryIndices::build_from_arena
1667pub(crate) fn rebuild_indices<G: crate::graph::unified::mutation_target::GraphMutationTarget>(
1668 graph: &mut G,
1669) {
1670 let (nodes, indices) = graph.nodes_and_indices_mut();
1671 indices.build_from_arena(nodes);
1672}
1673
1674/// Phase 4d — bulk-insert every pending edge into the graph via the
1675/// deterministic `DeltaEdge` conversion path.
1676///
1677/// Wraps the pure [`pending_edges_to_delta`] conversion + the
1678/// [`BidirectionalEdgeStore::add_edges_bulk_ordered`] call that
1679/// `build_unified_graph_inner` ran inline between Phase 4c-prime and
1680/// Phase 4e. The wrapper is generic over [`GraphMutationTarget`] so
1681/// the Task 4 Step 4 Phase 3 `incremental_rebuild` body can call it
1682/// against a [`RebuildGraph`] without duplicating the seq-counter +
1683/// flatten logic.
1684///
1685/// Returns the final edge sequence counter (for callers that need to
1686/// continue allocating deterministic sequence numbers downstream).
1687/// The counter flows from
1688/// [`BidirectionalEdgeStore::forward().seq_counter()`] on the way in
1689/// and advances by one per inserted edge.
1690///
1691/// # Semantics
1692///
1693/// * `per_file_edges` is consumed by-reference; the function does not
1694/// mutate the caller's buffer. Callers who no longer need the
1695/// vectors may drop them after the call.
1696/// * If `per_file_edges` is empty (or every inner vector is empty),
1697/// the edge store is left untouched.
1698/// * The helper does not `bump_epoch()` on the graph — Phase 4d is
1699/// edge-level only; the full pipeline bumps epoch separately.
1700///
1701/// # Edge-source-identity invariant (`C_EDGE_MIGRATE`)
1702///
1703/// Phase 4d does NOT dedup edges by `(source, target, kind)`. Every
1704/// `PendingEdge` from every file becomes one `DeltaEdge` with a unique
1705/// monotonically increasing `seq` number; the
1706/// [`BidirectionalEdgeStore::add_edges_bulk_ordered`] insertion contract
1707/// preserves that 1:1 mapping. This is what lets the Cluster C
1708/// `C_EDGE_MIGRATE` DAG unit (2026-04-29 BadLiveware Go batch) move the
1709/// `TypeOf{Field}` edge source from the struct node to the per-field
1710/// `Property` node without touching this helper: the new
1711/// Property-sourced edge addresses a distinct `(source, target)` pair
1712/// from the legacy struct-sourced edge, and Phase 4d emits both shapes
1713/// with no collapsing. Plugins that only emit the new shape (Go after
1714/// `C_EDGE_MIGRATE`) therefore produce a clean Property-sourced
1715/// `TypeOf{Field}` edge set with no struct-sourced shadows. Plugins
1716/// outside Cluster C's scope (`C_OTHER_PLUGINS`) keep emitting the
1717/// legacy shape until they migrate; the bulk-insert path treats both
1718/// shapes identically.
1719///
1720/// Determinism: per-file `PendingEdge` order is fixed by the parser
1721/// pass, and `pending_edges_to_delta` walks the per-file vectors in
1722/// the input order. So `phase4d_bulk_insert_edges` produces a
1723/// byte-identical `DeltaEdge` sequence on every fresh rebuild of the
1724/// same source tree, which is what guarantees the
1725/// `SnapshotReader → SnapshotWriter` round-trip identity required by
1726/// the `C_EDGE_MIGRATE` acceptance criteria.
1727///
1728/// [`BidirectionalEdgeStore::add_edges_bulk_ordered`]: crate::graph::unified::edge::bidirectional::BidirectionalEdgeStore::add_edges_bulk_ordered
1729/// [`RebuildGraph`]: crate::graph::unified::rebuild::rebuild_graph::RebuildGraph
1730pub(crate) fn phase4d_bulk_insert_edges<
1731 G: crate::graph::unified::mutation_target::GraphMutationTarget,
1732>(
1733 graph: &mut G,
1734 per_file_edges: &[Vec<PendingEdge>],
1735) -> u64 {
1736 // Start seq numbering from the edge store's current counter to
1737 // support non-empty graphs (incremental rebuild carries forward
1738 // the prior build's counter).
1739 let edge_seq_start = graph.edges().forward().seq_counter();
1740 let (delta_edge_vecs, final_seq) = pending_edges_to_delta(per_file_edges, edge_seq_start);
1741 let total_edge_count: u64 = delta_edge_vecs.iter().map(|v| v.len() as u64).sum();
1742 if total_edge_count > 0 {
1743 graph
1744 .edges_mut()
1745 .add_edges_bulk_ordered(&delta_edge_vecs, total_edge_count);
1746 }
1747 final_seq
1748}
1749
1750#[cfg(test)]
1751mod tests {
1752 use super::*;
1753
1754 #[test]
1755 fn test_compute_commit_plan_basic() {
1756 let file_ids = vec![FileId::new(0), FileId::new(1), FileId::new(2)];
1757 let node_counts = vec![3, 0, 5];
1758 let string_counts = vec![2, 1, 3];
1759 let edge_counts = vec![4, 0, 6];
1760
1761 let plan = compute_commit_plan(
1762 &node_counts,
1763 &string_counts,
1764 &edge_counts,
1765 &file_ids,
1766 0,
1767 1, // string_offset=1 for sentinel
1768 );
1769
1770 assert_eq!(plan.total_nodes, 8);
1771 assert_eq!(plan.total_strings, 6);
1772 assert_eq!(plan.total_edges, 10);
1773
1774 // File 0: nodes [0..3), strings [1..3)
1775 assert_eq!(plan.file_plans[0].node_range, 0..3);
1776 assert_eq!(plan.file_plans[0].string_range, 1..3);
1777
1778 // File 1: nodes [3..3), strings [3..4) — empty nodes
1779 assert_eq!(plan.file_plans[1].node_range, 3..3);
1780 assert_eq!(plan.file_plans[1].string_range, 3..4);
1781
1782 // File 2: nodes [3..8), strings [4..7)
1783 assert_eq!(plan.file_plans[2].node_range, 3..8);
1784 assert_eq!(plan.file_plans[2].string_range, 4..7);
1785 }
1786
1787 #[test]
1788 fn test_compute_commit_plan_with_offsets() {
1789 let file_ids = vec![FileId::new(5)];
1790 let plan = compute_commit_plan(&[10], &[5], &[7], &file_ids, 100, 50);
1791 assert_eq!(plan.file_plans[0].node_range, 100..110);
1792 assert_eq!(plan.file_plans[0].string_range, 50..55);
1793 assert_eq!(plan.total_nodes, 10);
1794 assert_eq!(plan.total_strings, 5);
1795 assert_eq!(plan.total_edges, 7);
1796 }
1797
1798 #[test]
1799 fn test_compute_commit_plan_empty() {
1800 let plan = compute_commit_plan(&[], &[], &[], &[], 0, 1);
1801 assert_eq!(plan.total_nodes, 0);
1802 assert_eq!(plan.total_strings, 0);
1803 assert_eq!(plan.total_edges, 0);
1804 assert!(plan.file_plans.is_empty());
1805 }
1806
1807 #[test]
1808 fn test_remap_string_id_basic() {
1809 let mut remap = HashMap::new();
1810 remap.insert(StringId::new(1), StringId::new(100));
1811
1812 let mut id = StringId::new(1);
1813 remap_string_id(&mut id, &remap);
1814 assert_eq!(id, StringId::new(100));
1815 }
1816
1817 #[test]
1818 fn test_remap_string_id_not_in_remap() {
1819 let remap = HashMap::new();
1820 let mut id = StringId::new(42);
1821 remap_string_id(&mut id, &remap);
1822 assert_eq!(id, StringId::new(42)); // unchanged
1823 }
1824
1825 #[test]
1826 fn test_remap_option_string_id() {
1827 let mut remap = HashMap::new();
1828 remap.insert(StringId::new(5), StringId::new(50));
1829
1830 let mut some_id = Some(StringId::new(5));
1831 remap_option_string_id(&mut some_id, &remap);
1832 assert_eq!(some_id, Some(StringId::new(50)));
1833
1834 let mut none_id: Option<StringId> = None;
1835 remap_option_string_id(&mut none_id, &remap);
1836 assert_eq!(none_id, None);
1837 }
1838
1839 #[test]
1840 fn test_remap_edge_kind_imports() {
1841 let mut remap = HashMap::new();
1842 remap.insert(StringId::new(1), StringId::new(100));
1843
1844 let mut kind = EdgeKind::Imports {
1845 alias: Some(StringId::new(1)),
1846 is_wildcard: false,
1847 };
1848 remap_edge_kind_string_ids(&mut kind, &remap);
1849 assert!(
1850 matches!(kind, EdgeKind::Imports { alias: Some(id), .. } if id == StringId::new(100))
1851 );
1852 }
1853
1854 #[test]
1855 fn test_remap_edge_kind_trait_method_binding() {
1856 let mut remap = HashMap::new();
1857 remap.insert(StringId::new(1), StringId::new(100));
1858 remap.insert(StringId::new(2), StringId::new(200));
1859
1860 let mut kind = EdgeKind::TraitMethodBinding {
1861 trait_name: StringId::new(1),
1862 impl_type: StringId::new(2),
1863 is_ambiguous: false,
1864 };
1865 remap_edge_kind_string_ids(&mut kind, &remap);
1866 assert!(
1867 matches!(kind, EdgeKind::TraitMethodBinding { trait_name, impl_type, .. }
1868 if trait_name == StringId::new(100) && impl_type == StringId::new(200))
1869 );
1870 }
1871
1872 #[test]
1873 fn test_remap_edge_kind_no_op_variants() {
1874 let remap = HashMap::new();
1875
1876 // Defines — no StringId fields
1877 let mut kind = EdgeKind::Defines;
1878 remap_edge_kind_string_ids(&mut kind, &remap);
1879 assert!(matches!(kind, EdgeKind::Defines));
1880
1881 // Calls — no StringId fields
1882 let mut kind = EdgeKind::Calls {
1883 argument_count: 3,
1884 is_async: true,
1885 resolved_via: ResolvedVia::Direct,
1886 };
1887 remap_edge_kind_string_ids(&mut kind, &remap);
1888 assert!(matches!(
1889 kind,
1890 EdgeKind::Calls {
1891 argument_count: 3,
1892 is_async: true,
1893 resolved_via: ResolvedVia::Direct,
1894 }
1895 ));
1896 }
1897
1898 fn placeholder_entry() -> NodeEntry {
1899 use crate::graph::unified::node::NodeKind;
1900 NodeEntry::new(NodeKind::Function, StringId::new(0), FileId::new(0))
1901 }
1902
1903 #[test]
1904 fn test_phase2_assign_ranges_basic() {
1905 use super::super::staging::StagingGraph;
1906
1907 // Create 2 staging graphs with known counts
1908 let mut sg0 = StagingGraph::new();
1909 let mut sg1 = StagingGraph::new();
1910
1911 // sg0: 2 nodes, 1 string, 1 edge
1912 let entry0 = placeholder_entry();
1913 let n0 = sg0.add_node(entry0.clone());
1914 let n1 = sg0.add_node(entry0.clone());
1915 sg0.intern_string(StringId::new_local(0), "hello".into());
1916 sg0.add_edge(
1917 n0,
1918 n1,
1919 EdgeKind::Calls {
1920 argument_count: 0,
1921 is_async: false,
1922 resolved_via: ResolvedVia::Direct,
1923 },
1924 FileId::new(0),
1925 );
1926
1927 // sg1: 1 node, 2 strings, 0 edges
1928 sg1.add_node(entry0);
1929 sg1.intern_string(StringId::new_local(0), "world".into());
1930 sg1.intern_string(StringId::new_local(1), "foo".into());
1931
1932 let file_ids = vec![FileId::new(10), FileId::new(11)];
1933 let offsets = GlobalOffsets {
1934 node_offset: 5,
1935 string_offset: 3,
1936 };
1937
1938 let plan = phase2_assign_ranges(&[&sg0, &sg1], &file_ids, &offsets);
1939
1940 // sg0: 2 nodes, 1 string, 1 edge
1941 assert_eq!(plan.file_plans[0].node_range, 5..7);
1942 assert_eq!(plan.file_plans[0].string_range, 3..4);
1943
1944 // sg1: 1 node, 2 strings, 0 edges
1945 assert_eq!(plan.file_plans[1].node_range, 7..8);
1946 assert_eq!(plan.file_plans[1].string_range, 4..6);
1947
1948 assert_eq!(plan.total_nodes, 3);
1949 assert_eq!(plan.total_strings, 3);
1950 assert_eq!(plan.total_edges, 1);
1951 }
1952
1953 #[test]
1954 fn test_phase3_parallel_commit_basic() {
1955 use super::super::staging::StagingGraph;
1956 use crate::graph::unified::concurrent::CodeGraph;
1957 use crate::graph::unified::node::NodeKind;
1958 // The `nodes_mut` / `strings_mut` method calls below resolve
1959 // to inherent methods on `CodeGraph`; the `GraphMutationTarget`
1960 // trait impl provides the same surface for `RebuildGraph`
1961 // (see `phase3_parallel_commit_runs_against_rebuild_graph`).
1962 // No trait import is needed here because inherent-method
1963 // resolution wins for `CodeGraph`.
1964
1965 // Create a staging graph with 2 nodes, 1 string, 1 edge
1966 let mut sg = StagingGraph::new();
1967 let local_name = StringId::new_local(0);
1968 sg.intern_string(local_name, "my_func".into());
1969
1970 let entry = NodeEntry::new(NodeKind::Function, local_name, FileId::new(0));
1971 let n0 = sg.add_node(entry.clone());
1972
1973 let entry2 = NodeEntry::new(NodeKind::Variable, local_name, FileId::new(0));
1974 let n1 = sg.add_node(entry2);
1975
1976 sg.add_edge(
1977 n0,
1978 n1,
1979 EdgeKind::Calls {
1980 argument_count: 0,
1981 is_async: false,
1982 resolved_via: ResolvedVia::Direct,
1983 },
1984 FileId::new(0),
1985 );
1986
1987 let file_ids = vec![FileId::new(5)];
1988
1989 // Pre-allocate with non-zero offsets to verify remap works,
1990 // against a full `CodeGraph` so the new generic signature is
1991 // exercised end-to-end via `GraphMutationTarget`.
1992 let mut graph = CodeGraph::new();
1993 graph
1994 .nodes_mut()
1995 .alloc_range(10, &placeholder_entry())
1996 .unwrap();
1997 let string_start = graph.strings_mut().alloc_range(1).unwrap();
1998 assert_eq!(string_start, 1); // past sentinel
1999
2000 let offsets = GlobalOffsets {
2001 node_offset: 10, // file's nodes start at index 10
2002 string_offset: string_start,
2003 };
2004 let plan = phase2_assign_ranges(&[&sg], &file_ids, &offsets);
2005 assert_eq!(plan.file_plans[0].node_range, 10..12);
2006
2007 // Pre-allocate the actual ranges for Phase 3.
2008 graph
2009 .nodes_mut()
2010 .alloc_range(plan.total_nodes, &placeholder_entry())
2011 .unwrap();
2012 graph.strings_mut().alloc_range(plan.total_strings).unwrap();
2013
2014 // Phase 3 — generic over `G: GraphMutationTarget`. Passing
2015 // `&mut graph` infers `G = CodeGraph`.
2016 let result = phase3_parallel_commit(&plan, &[&sg], &mut graph);
2017
2018 // Verify written counts
2019 assert_eq!(result.total_nodes_written, 2);
2020 assert_eq!(result.total_strings_written, 1);
2021
2022 // Verify strings were written
2023 let global_name = StringId::new(string_start);
2024 assert_eq!(&*graph.strings().resolve(global_name).unwrap(), "my_func");
2025
2026 // Verify 1 file, 1 edge
2027 assert_eq!(result.per_file_edges.len(), 1);
2028 assert_eq!(result.per_file_edges[0].len(), 1);
2029
2030 // Verify edge was remapped to global IDs (node_offset=10)
2031 let edge = &result.per_file_edges[0][0];
2032 assert_eq!(edge.file, FileId::new(5));
2033 assert_eq!(edge.source, NodeId::new(10, 1)); // first node at slot 10
2034 assert_eq!(edge.target, NodeId::new(11, 1)); // second node at slot 11
2035
2036 // Gate 0c (iter-2 B2): per-file node IDs must be recorded in
2037 // commit order, one Vec per FilePlan, so the caller can
2038 // populate FileRegistry::per_file_nodes deterministically.
2039 assert_eq!(result.per_file_node_ids.len(), 1);
2040 assert_eq!(
2041 result.per_file_node_ids[0],
2042 vec![NodeId::new(10, 1), NodeId::new(11, 1)]
2043 );
2044 }
2045
2046 #[test]
2047 fn test_phase3_parallel_commit_empty() {
2048 use crate::graph::unified::concurrent::CodeGraph;
2049
2050 let mut graph = CodeGraph::new();
2051
2052 let plan = ChunkCommitPlan {
2053 file_plans: vec![],
2054 total_nodes: 0,
2055 total_strings: 0,
2056 total_edges: 0,
2057 };
2058
2059 let result = phase3_parallel_commit(&plan, &[], &mut graph);
2060 assert!(result.per_file_edges.is_empty());
2061 assert!(result.per_file_node_ids.is_empty());
2062 assert_eq!(result.total_nodes_written, 0);
2063 assert_eq!(result.total_strings_written, 0);
2064 }
2065
2066 /// Task 4 Step 4 Phase 1 — exercise the `GraphMutationTarget`
2067 /// trait's second implementor.
2068 ///
2069 /// Builds a tiny staging graph, hosts it in a fresh `RebuildGraph`,
2070 /// and asserts the committed nodes land in the **rebuild-local**
2071 /// arena — not in a `CodeGraph`. The test also confirms the
2072 /// per-file edges / node-id vectors the helper returns agree with
2073 /// the `CodeGraph` call-path result shape.
2074 ///
2075 /// If a future refactor accidentally routed Phase 3 back to a
2076 /// `CodeGraph` (e.g. through a hidden static `Arc::make_mut`), this
2077 /// test would observe an empty rebuild arena and fail.
2078 #[test]
2079 #[cfg(feature = "rebuild-internals")]
2080 fn phase3_parallel_commit_runs_against_rebuild_graph() {
2081 use super::super::staging::StagingGraph;
2082 use crate::graph::unified::concurrent::CodeGraph;
2083 use crate::graph::unified::mutation_target::GraphMutationTarget;
2084 use crate::graph::unified::node::NodeKind;
2085
2086 // Staging graph: 2 nodes + 1 string + 1 Calls edge (identical
2087 // shape to the CodeGraph test above, so any behavioural drift
2088 // between the two paths surfaces as different assertions).
2089 let mut sg = StagingGraph::new();
2090 let local_name = StringId::new_local(0);
2091 sg.intern_string(local_name, "rebuild_target".into());
2092 let entry = NodeEntry::new(NodeKind::Function, local_name, FileId::new(0));
2093 let n0 = sg.add_node(entry.clone());
2094 let entry2 = NodeEntry::new(NodeKind::Variable, local_name, FileId::new(0));
2095 let n1 = sg.add_node(entry2);
2096 sg.add_edge(
2097 n0,
2098 n1,
2099 EdgeKind::Calls {
2100 argument_count: 0,
2101 is_async: false,
2102 resolved_via: ResolvedVia::Direct,
2103 },
2104 FileId::new(0),
2105 );
2106
2107 // Produce a RebuildGraph from an empty CodeGraph; drop the
2108 // CodeGraph immediately so any subsequent mutation observed in
2109 // the rebuild cannot possibly be leaking back to a shared Arc.
2110 let mut rebuild = {
2111 let graph = CodeGraph::new();
2112 graph.clone_for_rebuild()
2113 };
2114
2115 // Pre-allocate leading slots on the rebuild-local arena +
2116 // interner so the file's ranges begin at a non-zero offset —
2117 // this is the same pattern the CodeGraph test uses, verifying
2118 // the trait's disjoint-borrow combinator threads through
2119 // identically.
2120 rebuild
2121 .nodes_mut()
2122 .alloc_range(10, &placeholder_entry())
2123 .unwrap();
2124 let string_start = rebuild.strings_mut().alloc_range(1).unwrap();
2125 assert_eq!(string_start, 1);
2126
2127 let file_ids = vec![FileId::new(5)];
2128 let offsets = GlobalOffsets {
2129 node_offset: 10,
2130 string_offset: string_start,
2131 };
2132 let plan = phase2_assign_ranges(&[&sg], &file_ids, &offsets);
2133
2134 rebuild
2135 .nodes_mut()
2136 .alloc_range(plan.total_nodes, &placeholder_entry())
2137 .unwrap();
2138 rebuild
2139 .strings_mut()
2140 .alloc_range(plan.total_strings)
2141 .unwrap();
2142
2143 // Phase 3 against the RebuildGraph. Inferred `G = RebuildGraph`.
2144 let result = phase3_parallel_commit(&plan, &[&sg], &mut rebuild);
2145
2146 // === Invariant: the written data lives in the rebuild-local
2147 // arena, not in any CodeGraph field. ===
2148 //
2149 // Two slot ranges exist on the rebuild's arena now:
2150 // * slots 0..10 = pre-fill placeholders (each `Function` /
2151 // `StringId::new(0)` — note every alloc_range writes a
2152 // clone of the template entry).
2153 // * slots 10..12 = the two committed nodes from `sg`.
2154 //
2155 // Fetch the two committed NodeIds and resolve their names
2156 // through the rebuild-local interner; the string must match
2157 // the staged value "rebuild_target", proving the commit ran
2158 // on the rebuild's own fields.
2159 let committed_ids = &result.per_file_node_ids[0];
2160 assert_eq!(
2161 committed_ids,
2162 &vec![NodeId::new(10, 1), NodeId::new(11, 1)],
2163 "Phase 3 must commit into slots 10..12 on the rebuild-local arena"
2164 );
2165
2166 let resolved_name = rebuild
2167 .nodes_mut()
2168 .get(NodeId::new(10, 1))
2169 .map(|entry| entry.name)
2170 .expect("committed node must exist in rebuild arena");
2171 // The name StringId on the committed node is a global ID
2172 // (Phase 3 remaps local → global); resolving it through the
2173 // rebuild-local interner must produce the staged value.
2174 let resolved_str = rebuild
2175 .strings_mut()
2176 .resolve(resolved_name)
2177 .expect("name must resolve in rebuild-local interner");
2178 assert_eq!(&*resolved_str, "rebuild_target");
2179
2180 // === Shape invariants match the CodeGraph path ===
2181 assert_eq!(result.total_nodes_written, 2);
2182 assert_eq!(result.total_strings_written, 1);
2183 assert_eq!(result.per_file_edges.len(), 1);
2184 assert_eq!(result.per_file_edges[0].len(), 1);
2185 let edge = &result.per_file_edges[0][0];
2186 assert_eq!(edge.file, FileId::new(5));
2187 assert_eq!(edge.source, NodeId::new(10, 1));
2188 assert_eq!(edge.target, NodeId::new(11, 1));
2189 }
2190
2191 #[test]
2192 fn test_commit_single_file_string_remap() {
2193 use super::super::staging::StagingGraph;
2194 use crate::graph::unified::node::NodeKind;
2195
2196 let mut sg = StagingGraph::new();
2197 let local_0 = StringId::new_local(0);
2198 let local_1 = StringId::new_local(1);
2199 sg.intern_string(local_0, "alpha".into());
2200 sg.intern_string(local_1, "beta".into());
2201
2202 let mut entry = NodeEntry::new(NodeKind::Function, local_0, FileId::new(0));
2203 entry.signature = Some(local_1);
2204 sg.add_node(entry);
2205
2206 let plan = FilePlan {
2207 parsed_index: 0,
2208 file_id: FileId::new(42),
2209 node_range: 10..11,
2210 string_range: 20..22,
2211 };
2212
2213 let mut node_slots = vec![Slot::new_occupied(1, placeholder_entry())];
2214 let mut str_slots: Vec<Option<Arc<str>>> = vec![None, None];
2215 let mut rc_slots: Vec<u32> = vec![0, 0];
2216
2217 let result = commit_single_file(&sg, &plan, &mut node_slots, &mut str_slots, &mut rc_slots);
2218
2219 // Strings written
2220 assert_eq!(str_slots[0].as_deref(), Some("alpha"));
2221 assert_eq!(str_slots[1].as_deref(), Some("beta"));
2222 assert_eq!(rc_slots[0], 1);
2223 assert_eq!(rc_slots[1], 1);
2224 assert_eq!(result.strings_written, 2);
2225
2226 // Node entry has remapped StringIds
2227 if let crate::graph::unified::storage::SlotState::Occupied(entry) = node_slots[0].state() {
2228 assert_eq!(entry.name, StringId::new(20)); // global slot 20
2229 assert_eq!(entry.signature, Some(StringId::new(21))); // global slot 21
2230 assert_eq!(entry.file, FileId::new(42));
2231 } else {
2232 panic!("Expected occupied slot");
2233 }
2234 assert_eq!(result.nodes_written, 1);
2235
2236 // Per-file node IDs are recorded in commit order (Gate 0c bucket contract).
2237 assert_eq!(result.node_ids, vec![NodeId::new(10, 1)]);
2238
2239 // No edges
2240 assert!(result.edges.is_empty());
2241 }
2242
2243 #[test]
2244 fn test_remap_edge_kind_message_queue_other() {
2245 let mut remap = HashMap::new();
2246 remap.insert(StringId::new(10), StringId::new(110));
2247 remap.insert(StringId::new(20), StringId::new(220));
2248
2249 let mut kind = EdgeKind::MessageQueue {
2250 protocol: MqProtocol::Other(StringId::new(10)),
2251 topic: Some(StringId::new(20)),
2252 };
2253 remap_edge_kind_string_ids(&mut kind, &remap);
2254 assert!(matches!(
2255 kind,
2256 EdgeKind::MessageQueue {
2257 protocol: MqProtocol::Other(proto),
2258 topic: Some(topic),
2259 } if proto == StringId::new(110) && topic == StringId::new(220)
2260 ));
2261 }
2262
2263 // === Phase 4 tests ===
2264
2265 #[test]
2266 fn test_phase4_apply_global_remap_basic() {
2267 use crate::graph::unified::node::NodeKind;
2268 use crate::graph::unified::storage::NodeArena;
2269
2270 let mut arena = NodeArena::new();
2271
2272 // Allocate two nodes with duplicate string IDs (2 and 3 are dupes of 1)
2273 let entry1 = NodeEntry::new(NodeKind::Function, StringId::new(1), FileId::new(0));
2274 let mut entry2 = NodeEntry::new(NodeKind::Variable, StringId::new(2), FileId::new(0));
2275 entry2.signature = Some(StringId::new(3));
2276
2277 arena.alloc(entry1).unwrap();
2278 arena.alloc(entry2).unwrap();
2279
2280 // Edges with string IDs that need remapping
2281 let mut all_edges = vec![vec![PendingEdge {
2282 source: NodeId::new(0, 1),
2283 target: NodeId::new(1, 1),
2284 kind: EdgeKind::Imports {
2285 alias: Some(StringId::new(3)),
2286 is_wildcard: false,
2287 },
2288 file: FileId::new(0),
2289 spans: vec![],
2290 }]];
2291
2292 // Dedup remap: 2→1, 3→1
2293 let mut remap = HashMap::new();
2294 remap.insert(StringId::new(2), StringId::new(1));
2295 remap.insert(StringId::new(3), StringId::new(1));
2296
2297 phase4_apply_global_remap(&mut arena, &mut all_edges, &remap);
2298
2299 // Check that node 1's name was remapped from 2→1
2300 let (_, entry) = arena.iter().nth(1).unwrap();
2301 assert_eq!(entry.name, StringId::new(1));
2302 assert_eq!(entry.signature, Some(StringId::new(1)));
2303
2304 // Check that edge's alias was remapped from 3→1
2305 if let EdgeKind::Imports { alias, .. } = &all_edges[0][0].kind {
2306 assert_eq!(*alias, Some(StringId::new(1)));
2307 } else {
2308 panic!("Expected Imports edge");
2309 }
2310 }
2311
2312 #[test]
2313 fn test_phase4_apply_global_remap_empty() {
2314 use crate::graph::unified::storage::NodeArena;
2315
2316 let mut arena = NodeArena::new();
2317 let mut edges: Vec<Vec<PendingEdge>> = vec![];
2318 let remap = HashMap::new();
2319
2320 // Should be a no-op
2321 phase4_apply_global_remap(&mut arena, &mut edges, &remap);
2322 }
2323
2324 #[test]
2325 fn test_pending_edges_to_delta_basic() {
2326 let edges = vec![
2327 vec![
2328 PendingEdge {
2329 source: NodeId::new(0, 1),
2330 target: NodeId::new(1, 1),
2331 kind: EdgeKind::Calls {
2332 argument_count: 0,
2333 is_async: false,
2334 resolved_via: ResolvedVia::Direct,
2335 },
2336 file: FileId::new(0),
2337 spans: vec![],
2338 },
2339 PendingEdge {
2340 source: NodeId::new(1, 1),
2341 target: NodeId::new(2, 1),
2342 kind: EdgeKind::References,
2343 file: FileId::new(0),
2344 spans: vec![],
2345 },
2346 ],
2347 vec![PendingEdge {
2348 source: NodeId::new(3, 1),
2349 target: NodeId::new(4, 1),
2350 kind: EdgeKind::Defines,
2351 file: FileId::new(1),
2352 spans: vec![],
2353 }],
2354 ];
2355
2356 let (deltas, final_seq) = pending_edges_to_delta(&edges, 100);
2357
2358 assert_eq!(deltas.len(), 2);
2359 assert_eq!(deltas[0].len(), 2);
2360 assert_eq!(deltas[1].len(), 1);
2361 assert_eq!(final_seq, 103);
2362
2363 // Check sequence numbers are monotonic
2364 assert_eq!(deltas[0][0].seq, 100);
2365 assert_eq!(deltas[0][1].seq, 101);
2366 assert_eq!(deltas[1][0].seq, 102);
2367
2368 // Check all are Add operations
2369 assert!(matches!(deltas[0][0].op, DeltaOp::Add));
2370 assert!(matches!(deltas[1][0].op, DeltaOp::Add));
2371 }
2372
2373 #[test]
2374 fn test_pending_edges_to_delta_empty() {
2375 let edges: Vec<Vec<PendingEdge>> = vec![];
2376 let (deltas, final_seq) = pending_edges_to_delta(&edges, 0);
2377 assert!(deltas.is_empty());
2378 assert_eq!(final_seq, 0);
2379 }
2380
2381 // ==================================================================
2382 // Task 4 Step 4 Phase 2: rebuild-plane coverage for migrated helpers.
2383 //
2384 // Each test below proves that the migrated helper runs against a
2385 // `RebuildGraph` (not just a `CodeGraph`) and that the mutation
2386 // lands on the rebuild-local state. Together with the CodeGraph
2387 // tests that still exercise the same helpers on the full-build
2388 // path, they form the "runs on both implementors" coverage
2389 // contract for `GraphMutationTarget` consumers.
2390 // ==================================================================
2391
2392 /// Seed two call-compatible nodes (both `NodeKind::Function`) under
2393 /// the same qualified-name StringId across two distinct files, then
2394 /// run [`phase4c_prime_unify_cross_file_nodes`] against a
2395 /// [`RebuildGraph`]. Verify the loser node is tombstoned
2396 /// (name + qualified_name cleared per `merge_node_into`'s contract)
2397 /// and that pending edges pointing at the loser are rewritten to
2398 /// the winner.
2399 #[test]
2400 #[cfg(feature = "rebuild-internals")]
2401 fn phase4c_prime_unify_cross_file_nodes_runs_against_rebuild_graph() {
2402 use crate::graph::unified::concurrent::CodeGraph;
2403 use crate::graph::unified::mutation_target::GraphMutationTarget;
2404 use crate::graph::unified::node::NodeKind;
2405
2406 let mut rebuild = {
2407 let graph = CodeGraph::new();
2408 graph.clone_for_rebuild()
2409 };
2410
2411 // Intern a shared qualified name. On the rebuild-local
2412 // interner; strings() resolves it for later assertions.
2413 let qname_sid = rebuild.strings_mut().intern("my_mod::my_func").unwrap();
2414
2415 // Register two files that host the duplicate Function nodes.
2416 let file_a = FileId::new(7);
2417 let file_b = FileId::new(8);
2418
2419 // Build two `NodeKind::Function` entries sharing the same
2420 // qualified_name. Winner has a wider span (start_line > 0 and
2421 // end_line > start_line) to exercise the winner-selection
2422 // tie-break.
2423 let mut winner_entry = NodeEntry::new(NodeKind::Function, qname_sid, file_a);
2424 winner_entry.qualified_name = Some(qname_sid);
2425 winner_entry.start_line = 10;
2426 winner_entry.end_line = 30;
2427
2428 let mut loser_entry = NodeEntry::new(NodeKind::Function, qname_sid, file_b);
2429 loser_entry.qualified_name = Some(qname_sid);
2430 // Narrower span → loses the tie-break.
2431 loser_entry.start_line = 5;
2432 loser_entry.end_line = 6;
2433
2434 let winner_id = rebuild.nodes_mut().alloc(winner_entry).unwrap();
2435 let loser_id = rebuild.nodes_mut().alloc(loser_entry).unwrap();
2436
2437 // A pending edge whose target is the loser — the remap table
2438 // should rewrite it to point at the winner.
2439 let mut all_edges = vec![vec![PendingEdge {
2440 source: winner_id, // any valid source — the helper only rewrites targets here
2441 target: loser_id,
2442 kind: EdgeKind::Calls {
2443 argument_count: 0,
2444 is_async: false,
2445 resolved_via: ResolvedVia::Direct,
2446 },
2447 file: file_b,
2448 spans: vec![],
2449 }]];
2450
2451 let stats = phase4c_prime_unify_cross_file_nodes(&mut rebuild, &mut all_edges);
2452
2453 // Stats shape
2454 assert_eq!(stats.nodes_merged, 1, "exactly one loser was tombstoned");
2455 assert_eq!(stats.candidate_pairs_examined, 1);
2456 assert_eq!(stats.edges_rewritten, 1);
2457
2458 // Winner node survived with qualified_name intact.
2459 let winner_entry_after = GraphMutationTarget::nodes(&rebuild)
2460 .get(winner_id)
2461 .expect("winner must remain live");
2462 assert_eq!(
2463 winner_entry_after.qualified_name,
2464 Some(qname_sid),
2465 "winner keeps its qualified_name"
2466 );
2467
2468 // Loser entry was merged via `merge_node_into`, which clears
2469 // `name` and `qualified_name` to make the slot name-invisible.
2470 let loser_entry_after = GraphMutationTarget::nodes(&rebuild)
2471 .get(loser_id)
2472 .expect("loser slot remains live (inert) per §F.1 bijection");
2473 assert_eq!(
2474 loser_entry_after.qualified_name, None,
2475 "loser qualified_name cleared by merge_node_into"
2476 );
2477
2478 // Pending edge target rewritten winner-ward.
2479 assert_eq!(
2480 all_edges[0][0].target, winner_id,
2481 "PendingEdge.target rewritten from loser → winner"
2482 );
2483 }
2484
2485 /// Lock in the Phase 4c-prime tie-break ordering Codex blessed in iter-1:
2486 /// primary = `start_line > 0`, tie-break 1 = wider span, tie-break 2 =
2487 /// lexicographically smaller **file path** (stable across rebuild
2488 /// representations), final fallback = smaller `NodeId::index()`.
2489 ///
2490 /// This test exercises the tie-break 2 path: two candidates with real
2491 /// spans of identical width, hosted in two different files that differ
2492 /// only in filename ordering. The winner must be the node whose file
2493 /// path sorts earlier, regardless of NodeId allocation order.
2494 #[test]
2495 #[cfg(feature = "rebuild-internals")]
2496 fn phase4c_prime_tie_break_prefers_lex_smaller_path_over_node_id() {
2497 use crate::graph::unified::concurrent::CodeGraph;
2498 use crate::graph::unified::node::NodeKind;
2499 use std::path::Path;
2500
2501 let mut graph = CodeGraph::new();
2502 let qname = graph.strings_mut().intern("shared_qname").unwrap();
2503 // Register two paths whose lexical ordering is the reverse of
2504 // the registration (and hence NodeId) order. This isolates the
2505 // path-based tie-break from any accidental NodeId-ordering
2506 // coincidence: if the helper fell back to NodeId the "wrong"
2507 // node would win.
2508 let high_path_file = graph
2509 .files_mut()
2510 .register(Path::new("zzz_late.rs"))
2511 .unwrap();
2512 let low_path_file = graph
2513 .files_mut()
2514 .register(Path::new("aaa_early.rs"))
2515 .unwrap();
2516
2517 // Allocate the `zzz_late.rs` node first so its NodeId::index() is
2518 // numerically smaller than the `aaa_early.rs` node's. With
2519 // identical spans, NodeId-only tie-break would incorrectly pick
2520 // the `zzz_late.rs` node. The correct behaviour is that the
2521 // path-based tie-break picks the `aaa_early.rs` node.
2522 let mut high_entry = NodeEntry::new(NodeKind::Function, qname, high_path_file);
2523 high_entry.qualified_name = Some(qname);
2524 high_entry.start_line = 10;
2525 high_entry.end_line = 20;
2526 let high_node = graph.nodes_mut().alloc(high_entry).unwrap();
2527
2528 let mut low_entry = NodeEntry::new(NodeKind::Function, qname, low_path_file);
2529 low_entry.qualified_name = Some(qname);
2530 // Identical span width — forces the tie-break to ignore primary
2531 // + tie-break 1 (span width) and reach tie-break 2 (path).
2532 low_entry.start_line = 10;
2533 low_entry.end_line = 20;
2534 let low_node = graph.nodes_mut().alloc(low_entry).unwrap();
2535
2536 graph.rebuild_indices();
2537
2538 let mut all_edges: Vec<Vec<PendingEdge>> = Vec::new();
2539 let stats = phase4c_prime_unify_cross_file_nodes(&mut graph, &mut all_edges);
2540
2541 assert_eq!(
2542 stats.nodes_merged, 1,
2543 "one of the duplicate nodes must be merged into the other"
2544 );
2545
2546 // The `aaa_early.rs` node wins because its path sorts lexically
2547 // smaller. Verify its qualified_name is intact.
2548 let low_after = graph
2549 .nodes()
2550 .get(low_node)
2551 .expect("winner slot remains live");
2552 assert_eq!(
2553 low_after.qualified_name,
2554 Some(qname),
2555 "path-earlier node keeps qualified_name as the unification winner"
2556 );
2557
2558 // And the `zzz_late.rs` node — despite a numerically smaller
2559 // NodeId::index() — was merged away.
2560 let high_after = graph
2561 .nodes()
2562 .get(high_node)
2563 .expect("loser slot remains inert (Gate 0d bijection contract)");
2564 assert_eq!(
2565 high_after.qualified_name, None,
2566 "path-later node loses even when its NodeId::index() is smaller"
2567 );
2568 }
2569
2570 /// When the path-based tie-break ALSO ties (two duplicate nodes in the
2571 /// same file — rare but possible via duplicate definitions), the
2572 /// deterministic fallback is `b.index().cmp(&a.index())` which picks
2573 /// the node with the **smaller** NodeId index. Lock that in so future
2574 /// refactors of the tie-break don't accidentally flip the fallback
2575 /// direction.
2576 #[test]
2577 #[cfg(feature = "rebuild-internals")]
2578 fn phase4c_prime_tie_break_falls_back_to_smaller_node_id_on_identical_path() {
2579 use crate::graph::unified::concurrent::CodeGraph;
2580 use crate::graph::unified::node::NodeKind;
2581 use std::path::Path;
2582
2583 let mut graph = CodeGraph::new();
2584 let qname = graph.strings_mut().intern("shared_qname").unwrap();
2585 let file = graph.files_mut().register(Path::new("shared.rs")).unwrap();
2586
2587 // Allocate two duplicate nodes in the SAME file with identical
2588 // spans. The only thing that differs between them is their
2589 // NodeId index (allocation order). Tie-breaks 1 (span width)
2590 // and 2 (path) both return Equal; the final `b.index().cmp(&a.index())`
2591 // fallback picks the smaller index as the winner.
2592 let mut first_entry = NodeEntry::new(NodeKind::Function, qname, file);
2593 first_entry.qualified_name = Some(qname);
2594 first_entry.start_line = 1;
2595 first_entry.end_line = 5;
2596 let first_node = graph.nodes_mut().alloc(first_entry).unwrap();
2597
2598 let mut second_entry = NodeEntry::new(NodeKind::Function, qname, file);
2599 second_entry.qualified_name = Some(qname);
2600 second_entry.start_line = 1;
2601 second_entry.end_line = 5;
2602 let second_node = graph.nodes_mut().alloc(second_entry).unwrap();
2603
2604 assert!(
2605 first_node.index() < second_node.index(),
2606 "precondition: first_node's arena slot precedes second_node's"
2607 );
2608
2609 graph.rebuild_indices();
2610
2611 let mut all_edges: Vec<Vec<PendingEdge>> = Vec::new();
2612 let stats = phase4c_prime_unify_cross_file_nodes(&mut graph, &mut all_edges);
2613
2614 assert_eq!(stats.nodes_merged, 1);
2615
2616 // Smaller NodeId::index() wins.
2617 let winner_after = graph.nodes().get(first_node).expect("winner live");
2618 assert_eq!(
2619 winner_after.qualified_name,
2620 Some(qname),
2621 "smaller-index node wins the same-path / same-span tie-break"
2622 );
2623 let loser_after = graph.nodes().get(second_node).expect("loser inert");
2624 assert_eq!(
2625 loser_after.qualified_name, None,
2626 "larger-index node loses the same-path / same-span tie-break"
2627 );
2628 }
2629
2630 /// Drive the free [`rebuild_indices`] function against both a
2631 /// `RebuildGraph` and a `CodeGraph` seeded with identical data,
2632 /// and verify the resulting `AuxiliaryIndices` are structurally
2633 /// equivalent (same name buckets, same kind buckets).
2634 #[test]
2635 #[cfg(feature = "rebuild-internals")]
2636 fn rebuild_indices_runs_against_rebuild_graph() {
2637 use crate::graph::unified::concurrent::CodeGraph;
2638 use crate::graph::unified::mutation_target::GraphMutationTarget;
2639 use crate::graph::unified::node::NodeKind;
2640
2641 // === CodeGraph baseline ===
2642 let mut code_graph = CodeGraph::new();
2643 let alpha_id_code = code_graph.strings_mut().intern("alpha").unwrap();
2644 let mut code_entry = NodeEntry::new(NodeKind::Function, alpha_id_code, FileId::new(1));
2645 code_entry.qualified_name = Some(alpha_id_code);
2646 let code_node_id = code_graph.nodes_mut().alloc(code_entry).unwrap();
2647 rebuild_indices(&mut code_graph);
2648 let code_buckets_function: Vec<NodeId> =
2649 code_graph.indices().by_kind(NodeKind::Function).to_vec();
2650
2651 // === RebuildGraph path ===
2652 let mut rebuild = {
2653 let graph = CodeGraph::new();
2654 graph.clone_for_rebuild()
2655 };
2656 let alpha_id_rebuild = rebuild.strings_mut().intern("alpha").unwrap();
2657 let mut rebuild_entry =
2658 NodeEntry::new(NodeKind::Function, alpha_id_rebuild, FileId::new(1));
2659 rebuild_entry.qualified_name = Some(alpha_id_rebuild);
2660 let rebuild_node_id = rebuild.nodes_mut().alloc(rebuild_entry).unwrap();
2661 rebuild_indices(&mut rebuild);
2662
2663 // The node ids are both the first allocation on their
2664 // respective arenas, so they share slot indices and
2665 // generations.
2666 assert_eq!(code_node_id, rebuild_node_id);
2667
2668 // The trait-method accessor routes through the impl on
2669 // `RebuildGraph`; the returned indices came from the
2670 // rebuild-local `AuxiliaryIndices` (not a CodeGraph's).
2671 let rebuild_buckets_function: Vec<NodeId> = GraphMutationTarget::indices(&rebuild)
2672 .by_kind(NodeKind::Function)
2673 .to_vec();
2674
2675 assert_eq!(
2676 code_buckets_function, rebuild_buckets_function,
2677 "rebuild_indices must produce equivalent Function buckets on both paths"
2678 );
2679 // Name bucket also present on the rebuild side.
2680 let by_name: Vec<NodeId> = GraphMutationTarget::indices(&rebuild)
2681 .by_name(alpha_id_rebuild)
2682 .to_vec();
2683 assert_eq!(by_name, vec![rebuild_node_id]);
2684 }
2685
2686 /// Drive [`phase4d_bulk_insert_edges`] against a `RebuildGraph`.
2687 /// Seed two nodes, construct a per-file `PendingEdge` vector, and
2688 /// prove the edges land on the rebuild-local edge store with the
2689 /// expected monotonically-advancing sequence counter.
2690 #[test]
2691 #[cfg(feature = "rebuild-internals")]
2692 fn phase4d_bulk_insert_edges_runs_against_rebuild_graph() {
2693 use crate::graph::unified::concurrent::CodeGraph;
2694 use crate::graph::unified::mutation_target::GraphMutationTarget;
2695 use crate::graph::unified::node::NodeKind;
2696
2697 let mut rebuild = {
2698 let graph = CodeGraph::new();
2699 graph.clone_for_rebuild()
2700 };
2701
2702 let name_sid = rebuild.strings_mut().intern("edge_target").unwrap();
2703 let file = FileId::new(3);
2704
2705 let n_source = rebuild
2706 .nodes_mut()
2707 .alloc(NodeEntry::new(NodeKind::Function, name_sid, file))
2708 .unwrap();
2709 let n_target = rebuild
2710 .nodes_mut()
2711 .alloc(NodeEntry::new(NodeKind::Variable, name_sid, file))
2712 .unwrap();
2713
2714 // Pre-condition: no edges in the rebuild-local forward store.
2715 let pre_counter = GraphMutationTarget::edges(&rebuild).forward().seq_counter();
2716
2717 let per_file_edges = vec![vec![
2718 PendingEdge {
2719 source: n_source,
2720 target: n_target,
2721 kind: EdgeKind::Calls {
2722 argument_count: 0,
2723 is_async: false,
2724 resolved_via: ResolvedVia::Direct,
2725 },
2726 file,
2727 spans: vec![],
2728 },
2729 PendingEdge {
2730 source: n_source,
2731 target: n_target,
2732 kind: EdgeKind::Calls {
2733 argument_count: 1,
2734 is_async: false,
2735 resolved_via: ResolvedVia::Direct,
2736 },
2737 file,
2738 spans: vec![],
2739 },
2740 ]];
2741
2742 let final_seq = phase4d_bulk_insert_edges(&mut rebuild, &per_file_edges);
2743
2744 // Seq counter advanced by exactly two edges.
2745 assert_eq!(
2746 final_seq,
2747 pre_counter + 2,
2748 "phase4d_bulk_insert_edges must advance seq by edge count"
2749 );
2750
2751 // Rebuild-local forward store now contains both edges.
2752 let forward = GraphMutationTarget::edges(&rebuild).forward();
2753 let after_counter = forward.seq_counter();
2754 assert_eq!(after_counter, pre_counter + 2);
2755 // Forward delta must carry the two new edges.
2756 assert!(
2757 forward.delta().iter().filter(|e| e.is_add()).count() >= 2,
2758 "expected at least two Add edges in the rebuild-local forward delta"
2759 );
2760 drop(forward);
2761
2762 // Empty input is a no-op on the edge store.
2763 let empty_final = phase4d_bulk_insert_edges(&mut rebuild, &[]);
2764 assert_eq!(empty_final, pre_counter + 2, "empty input is a no-op");
2765 }
2766
2767 /// `C_EDGE_MIGRATE` regression: when a Cluster C plugin migrates a
2768 /// `TypeOf{Field}` edge's source from a struct node to the per-field
2769 /// `Property` node, Phase 4d must NOT collapse the new shape onto
2770 /// any sibling edge. Both Property-sourced and struct-sourced
2771 /// edges - including a struct-sourced edge over the same target /
2772 /// kind tuple - must round-trip into the bulk-insert path with
2773 /// distinct `(source, target)` identities and stable seq ordering.
2774 ///
2775 /// This locks the property the
2776 /// `phase4d_bulk_insert_edges` doc-comment promises to plugin
2777 /// authors: per-file `PendingEdge` order is preserved 1:1 by
2778 /// `pending_edges_to_delta`, and no `(source, target, kind)` dedup
2779 /// fires inside Phase 4d. Without this guarantee the migration
2780 /// would silently drop the new Property-sourced edges whenever an
2781 /// older legacy snapshot mixed both shapes during a partial
2782 /// rebuild.
2783 #[test]
2784 fn phase4d_preserves_property_sourced_typeof_field_edges() {
2785 use crate::graph::unified::edge::kind::TypeOfContext;
2786
2787 // Synthetic NodeIds standing in for `main.SelectorSource` (struct),
2788 // `main.SelectorSource.NeedTags` (Property), and `bool` (target type).
2789 let struct_id = NodeId::new(10, 1);
2790 let property_id = NodeId::new(11, 1);
2791 let bool_id = NodeId::new(12, 1);
2792
2793 let typeof_field_kind = EdgeKind::TypeOf {
2794 context: Some(TypeOfContext::Field),
2795 index: Some(0),
2796 name: None,
2797 };
2798
2799 // Two PendingEdges over the same (target, kind) discriminator
2800 // but different sources - the post-migration Property-sourced
2801 // shape and a hypothetical legacy struct-sourced shadow that
2802 // could appear during a partial rebuild. Phase 4d must keep
2803 // both.
2804 let per_file_edges = vec![vec![
2805 PendingEdge {
2806 source: property_id,
2807 target: bool_id,
2808 kind: typeof_field_kind.clone(),
2809 file: FileId::new(0),
2810 spans: vec![],
2811 },
2812 PendingEdge {
2813 source: struct_id,
2814 target: bool_id,
2815 kind: typeof_field_kind.clone(),
2816 file: FileId::new(0),
2817 spans: vec![],
2818 },
2819 ]];
2820
2821 let (deltas, final_seq) = pending_edges_to_delta(&per_file_edges, 500);
2822
2823 // No dedup: both edges land in the per-file delta vector with
2824 // distinct seq numbers, in input order.
2825 assert_eq!(deltas.len(), 1);
2826 assert_eq!(deltas[0].len(), 2);
2827 assert_eq!(final_seq, 502);
2828
2829 assert_eq!(deltas[0][0].source, property_id);
2830 assert_eq!(deltas[0][0].target, bool_id);
2831 assert_eq!(deltas[0][0].seq, 500);
2832 assert!(matches!(
2833 deltas[0][0].kind,
2834 EdgeKind::TypeOf {
2835 context: Some(TypeOfContext::Field),
2836 ..
2837 }
2838 ));
2839
2840 assert_eq!(deltas[0][1].source, struct_id);
2841 assert_eq!(deltas[0][1].target, bool_id);
2842 assert_eq!(deltas[0][1].seq, 501);
2843
2844 // Determinism re-check: re-running the conversion against the
2845 // same input produces an identical DeltaEdge sequence (same
2846 // sources, same targets, same kinds, same seq numbers when
2847 // re-anchored to the same `seq_start`). This is the property
2848 // the SnapshotReader → SnapshotWriter byte-identity round-trip
2849 // assertion relies on for fresh-rebuild reproducibility.
2850 let (deltas_again, final_seq_again) = pending_edges_to_delta(&per_file_edges, 500);
2851 assert_eq!(final_seq_again, final_seq);
2852 assert_eq!(deltas_again.len(), deltas.len());
2853 assert_eq!(deltas_again[0].len(), deltas[0].len());
2854 for (a, b) in deltas[0].iter().zip(deltas_again[0].iter()) {
2855 assert_eq!(a.source, b.source);
2856 assert_eq!(a.target, b.target);
2857 assert_eq!(a.seq, b.seq);
2858 }
2859 }
2860}