-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbuild_pipeline.rs
More file actions
1677 lines (1565 loc) · 63.5 KB
/
build_pipeline.rs
File metadata and controls
1677 lines (1565 loc) · 63.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Full Rust build orchestrator — runs the entire build pipeline with zero
//! napi boundary crossings after the initial `build_graph()` call.
//!
//! Replaces the JS `runPipelineStages()` in `pipeline.ts` when the native
//! engine is available. The JS pipeline remains as the WASM fallback.
//!
//! Pipeline stages (all internal, single rusqlite connection):
//! 1. Deserialize config/aliases/opts
//! 2. Collect files (with gitignore + extension filter)
//! 3. Detect changes (tiered: journal/mtime/hash)
//! 4. Parse files in parallel (existing `parallel::parse_files_parallel`)
//! 5. Insert nodes (existing `insert_nodes::do_insert_nodes`)
//! 6. Resolve imports (existing `import_resolution::resolve_imports_batch`)
//! 6b. Re-parse barrel candidates (incremental only)
//! 7. Build import edges + call edges + barrel resolution
//! 8. Structure metrics + role classification
//! 9. Finalize (metadata, journal)
use crate::change_detection;
use crate::config::{BuildConfig, BuildOpts, BuildPathAliases};
use crate::constants::{FAST_PATH_MAX_CHANGED_FILES, FAST_PATH_MIN_EXISTING_FILES};
use crate::file_collector;
use crate::import_edges::{self, ImportEdgeContext};
use crate::import_resolution;
use crate::journal;
use crate::parallel;
use crate::ast_db::{self, AstInsertNode, FileAstBatch};
use crate::roles_db;
use crate::structure;
use crate::types::{FileSymbols, ImportResolutionInput};
use rusqlite::Connection;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::time::Instant;
/// Timing result for each pipeline phase (returned as JSON to JS).
#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PipelineTiming {
pub setup_ms: f64,
pub collect_ms: f64,
pub detect_ms: f64,
pub parse_ms: f64,
pub insert_ms: f64,
pub resolve_ms: f64,
pub edges_ms: f64,
pub structure_ms: f64,
pub roles_ms: f64,
pub ast_ms: f64,
pub complexity_ms: f64,
pub cfg_ms: f64,
pub dataflow_ms: f64,
pub finalize_ms: f64,
}
/// Result of the build pipeline.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildPipelineResult {
pub phases: PipelineTiming,
pub node_count: i64,
pub edge_count: i64,
pub file_count: usize,
pub early_exit: bool,
/// Analysis scope: files whose content genuinely changed (reverse-dep-only
/// files excluded). `None` for full builds (all files), `Some` for
/// incremental builds. Consumers (e.g. the JS analysis phase) use this to
/// scope expensive AST/complexity/CFG/dataflow work.
#[serde(skip_serializing_if = "Option::is_none")]
pub changed_files: Option<Vec<String>>,
pub changed_count: usize,
pub removed_count: usize,
pub is_full_build: bool,
/// Whether the Rust pipeline handled the structure phase (directory nodes,
/// contains edges, file and directory metrics). Always true — the Rust
/// pipeline handles both the small-incremental fast path and full builds.
pub structure_handled: bool,
/// Whether the Rust pipeline wrote AST/complexity/CFG/dataflow to the DB.
/// When true, the JS caller can skip `runPostNativeAnalysis` entirely.
pub analysis_complete: bool,
}
/// Normalize path to forward slashes.
fn normalize_path(p: &str) -> String {
p.replace('\\', "/")
}
/// Make a path relative to root_dir, normalized.
fn relative_path(root_dir: &str, abs_path: &str) -> String {
let root = Path::new(root_dir);
let abs = Path::new(abs_path);
match abs.strip_prefix(root) {
Ok(rel) => normalize_path(rel.to_str().unwrap_or("")),
Err(_) => normalize_path(abs_path),
}
}
/// Run the full build pipeline in Rust.
///
/// Called from `NativeDatabase.build_graph()` via napi.
pub fn run_pipeline(
conn: &Connection,
root_dir: &str,
config_json: &str,
aliases_json: &str,
opts_json: &str,
) -> Result<BuildPipelineResult, String> {
let total_start = Instant::now();
let mut timing = PipelineTiming::default();
// ── Stage 1: Deserialize config ────────────────────────────────────
let t0 = Instant::now();
let config: BuildConfig =
serde_json::from_str(config_json).map_err(|e| format!("config parse error: {e}"))?;
let aliases: BuildPathAliases =
serde_json::from_str(aliases_json).map_err(|e| format!("aliases parse error: {e}"))?;
let opts: BuildOpts =
serde_json::from_str(opts_json).map_err(|e| format!("opts parse error: {e}"))?;
let napi_aliases = aliases.to_napi_aliases();
let incremental = opts.incremental.unwrap_or(config.build.incremental);
let include_dataflow = opts.dataflow.unwrap_or(true);
let include_ast = opts.ast.unwrap_or(true);
// Check engine/schema/version mismatch for forced full rebuild
let force_full_rebuild = check_version_mismatch(conn);
timing.setup_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 2: Collect files ─────────────────────────────────────────
let t0 = Instant::now();
// For scoped builds, track all scoped relative paths (including deleted files)
// so detect_removed_files only flags scoped files as removed, not everything.
let scoped_rel_paths: Option<HashSet<String>> = opts.scope.as_ref().map(|scope| {
scope
.iter()
.map(|f| normalize_path(f))
.collect()
});
let collect_result = collect_source_files(conn, root_dir, &config, &opts, incremental, force_full_rebuild);
timing.collect_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 3: Detect changes ────────────────────────────────────────
let t0 = Instant::now();
let change_result = change_detection::detect_changes(
conn,
&collect_result.files,
root_dir,
incremental,
force_full_rebuild,
scoped_rel_paths.as_ref(),
);
timing.detect_ms = t0.elapsed().as_secs_f64() * 1000.0;
// Filter out metadata-only changes
let parse_changes: Vec<&change_detection::ChangedFile> = change_result
.changed
.iter()
.filter(|c| !c.metadata_only)
.collect();
// Early exit: no changes
if !change_result.is_full_build && parse_changes.is_empty() && change_result.removed.is_empty()
{
// Heal metadata if needed
change_detection::heal_metadata(conn, &change_result.metadata_updates);
journal::write_journal_header(root_dir, now_ms());
return Ok(BuildPipelineResult {
phases: timing,
node_count: 0,
edge_count: 0,
file_count: collect_result.files.len(),
early_exit: true,
changed_files: Some(vec![]),
changed_count: 0,
removed_count: 0,
is_full_build: false,
structure_handled: true,
analysis_complete: true,
});
}
// Save reverse-dep → changed-file edges before purge so we can reconnect
// them to new node IDs after Stage 5 (#1012). This matches the WASM/JS
// strategy and lets us skip re-parsing reverse-dep files entirely:
// parse/insert/structure/roles/analysis all scope to truly-changed files.
let mut saved_reverse_dep_edges: Vec<change_detection::SavedReverseDepEdge> = Vec::new();
// Files that import a removed file. Save+reconnect doesn't apply (the
// target node is gone for good), but their role records go stale because
// edges to the deleted file's nodes get purged in Stage 3. Reclassify them
// in Stage 8 so fan-out reflects reality. (#1027 review)
let mut removal_reverse_deps: Vec<String> = Vec::new();
// Handle full build: clear all graph data
if change_result.is_full_build {
let has_embeddings = change_detection::has_embeddings(conn);
change_detection::clear_all_graph_data(conn, has_embeddings);
} else {
// Incremental: save reverse-dep edges (if reverse-dep tracking is enabled),
// then purge changed files only.
let changed_paths: Vec<String> =
parse_changes.iter().map(|c| c.rel_path.clone()).collect();
if !opts.no_reverse_deps.unwrap_or(false) {
saved_reverse_dep_edges =
change_detection::save_reverse_dep_edges(conn, &changed_paths);
if !change_result.removed.is_empty() {
let removed_set: HashSet<String> =
change_result.removed.iter().cloned().collect();
removal_reverse_deps =
change_detection::find_reverse_dependencies(conn, &removed_set, root_dir)
.into_iter()
.collect();
}
}
let files_to_purge: Vec<String> = change_result
.removed
.iter()
.chain(parse_changes.iter().map(|c| &c.rel_path))
.cloned()
.collect();
// Pass empty reverse_dep_files: purge already deletes both directions
// for changed files (which removes the saved reverse-dep → changed-file
// edges from the live table), and other outgoing edges from reverse-dep
// files remain valid and must NOT be deleted — they will be reconnected
// to new target IDs after insert.
change_detection::purge_changed_files(conn, &files_to_purge, &[]);
}
// ── Stage 4: Parse files ───────────────────────────────────────────
// Only truly-changed files are parsed. Reverse-dep files are not re-parsed —
// their edges to changed files are reconstructed via save+reconnect (#1012).
let t0 = Instant::now();
let files_to_parse: Vec<String> =
parse_changes.iter().map(|c| c.abs_path.clone()).collect();
let parsed =
parallel::parse_files_parallel(&files_to_parse, root_dir, include_dataflow, include_ast);
// Build file symbols map (relative path → FileSymbols)
let mut file_symbols: HashMap<String, FileSymbols> = HashMap::new();
for mut sym in parsed {
let rel = relative_path(root_dir, &sym.file);
sym.file = rel.clone();
file_symbols.insert(rel, sym);
}
timing.parse_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 5: Insert nodes ──────────────────────────────────────────
let t0 = Instant::now();
let insert_batches = build_insert_batches(&file_symbols);
let file_hashes = build_file_hash_entries(&parse_changes);
let _ = crate::insert_nodes::do_insert_nodes(
conn,
&insert_batches,
&file_hashes,
&change_result.removed,
);
// Also heal metadata-only updates
change_detection::heal_metadata(conn, &change_result.metadata_updates);
timing.insert_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 6: Resolve imports ───────────────────────────────────────
let t0 = Instant::now();
let mut batch_inputs: Vec<ImportResolutionInput> = Vec::new();
for (rel_path, symbols) in &file_symbols {
let abs_file = Path::new(root_dir).join(rel_path);
// Normalize to forward slashes so batch_resolved keys match Stage 6b lookups on Windows.
let abs_str = abs_file.to_str().unwrap_or("").replace('\\', "/");
for imp in &symbols.imports {
batch_inputs.push(ImportResolutionInput {
from_file: abs_str.clone(),
import_source: imp.source.clone(),
});
}
}
let known_files: HashSet<String> = collect_result
.files
.iter()
.map(|f| relative_path(root_dir, f))
.collect();
let resolved = import_resolution::resolve_imports_batch(
&batch_inputs,
root_dir,
&napi_aliases,
Some(&known_files),
);
// Build batch_resolved map: "absFile|importSource" -> resolved path
let mut batch_resolved: HashMap<String, String> = HashMap::new();
for r in &resolved {
let key = format!("{}|{}", r.from_file, r.import_source);
batch_resolved.insert(key, r.resolved_path.clone());
}
timing.resolve_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 6b: Re-parse barrel candidates (incremental only) ─────────
if !change_result.is_full_build {
reparse_barrel_candidates(
conn, root_dir, &napi_aliases, &known_files,
&mut file_symbols, &mut batch_resolved,
);
}
// ── Stage 7: Build edges ───────────────────────────────────────────
let t0 = Instant::now();
// Build import edge context
let mut import_ctx = ImportEdgeContext {
batch_resolved,
reexport_map: HashMap::new(),
barrel_only_files: HashSet::new(),
file_symbols: file_symbols.clone(),
root_dir: root_dir.to_string(),
aliases: napi_aliases.clone(),
known_files,
};
// Build reexport map and detect barrel files
import_ctx.reexport_map = import_edges::build_reexport_map(&import_ctx);
import_ctx.barrel_only_files = import_edges::detect_barrel_only_files(&import_ctx);
// Build import edges
let import_edge_rows = import_edges::build_import_edges(conn, &import_ctx);
import_edges::insert_edges(conn, &import_edge_rows);
// Build call edges using existing Rust edge_builder (internal path)
// For now, call edges are built via the existing napi-exported function's
// internal logic. We load nodes from DB and pass to the edge builder.
build_and_insert_call_edges(conn, &file_symbols, &import_ctx, !change_result.is_full_build);
// Reconnect saved reverse-dep edges to new node IDs (#1012). Mirrors
// `reconnectReverseDepEdges` in build-edges.ts — for each saved edge,
// look up the new target node and recreate the edge with the original
// source_id (still valid; reverse-dep nodes were never purged).
if !saved_reverse_dep_edges.is_empty() {
let (reconnected, dropped) =
change_detection::reconnect_reverse_dep_edges(conn, &saved_reverse_dep_edges);
if dropped > 0 {
eprintln!(
"[codegraph] reconnect_reverse_dep_edges: {reconnected} reconnected, {dropped} dropped (target nodes not found)"
);
}
}
timing.edges_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 8: Structure + roles ─────────────────────────────────────
let t0 = Instant::now();
let line_count_map = structure::build_line_count_map(&file_symbols, root_dir);
// file_symbols only contains truly-changed files (reverse-deps are not
// re-parsed; their edges are reconnected via save+reconnect — #1012), so
// analysis_scope == changed_files.
let changed_files: Vec<String> = file_symbols.keys().cloned().collect();
let analysis_scope: Option<Vec<String>> = if change_result.is_full_build {
None
} else {
Some(changed_files.clone())
};
let existing_file_count = structure::get_existing_file_count(conn);
let use_fast_path =
!change_result.is_full_build && parse_changes.len() <= FAST_PATH_MAX_CHANGED_FILES && existing_file_count > FAST_PATH_MIN_EXISTING_FILES;
if use_fast_path {
structure::update_changed_file_metrics(
conn,
&changed_files,
&line_count_map,
&file_symbols,
);
} else {
// Full structure: directory nodes, contains edges, file + directory metrics.
let changed_for_structure: Option<Vec<String>> = if change_result.is_full_build {
None
} else {
Some(changed_files.clone())
};
structure::build_full_structure(
conn,
&file_symbols,
&collect_result.directories,
root_dir,
&line_count_map,
changed_for_structure.as_deref(),
);
}
timing.structure_ms = t0.elapsed().as_secs_f64() * 1000.0;
let t0 = Instant::now();
// Role classification needs the truly-changed files plus reverse-deps of
// any removed files. `do_classify_incremental` expands to neighbours via
// the edges table, so reverse-deps of *changed* files are picked up
// automatically when their fan-in/fan-out is affected. Reverse-deps of
// *removed* files have to be added explicitly — the deleted file's nodes
// are gone, so neighbour expansion can't reach the importer. Without this
// seed, removal-only builds skip role classification entirely. (#1027)
let changed_file_list: Option<Vec<String>> = if change_result.is_full_build {
None
} else {
let mut files = changed_files;
if !removal_reverse_deps.is_empty() {
let existing: HashSet<String> = files.iter().cloned().collect();
for f in removal_reverse_deps {
if !existing.contains(&f) {
files.push(f);
}
}
}
Some(files)
};
if let Some(ref files) = changed_file_list {
if !files.is_empty() {
let _ = roles_db::do_classify_incremental(conn, files);
}
} else {
let _ = roles_db::do_classify_full(conn);
}
timing.roles_ms = t0.elapsed().as_secs_f64() * 1000.0;
// ── Stage 8b: Analysis persistence (AST, complexity, CFG, dataflow) ──
// Write analysis data from parsed file_symbols directly to DB tables,
// eliminating the JS runPostNativeAnalysis step and its WASM re-parse.
let include_complexity = opts.complexity.unwrap_or(true);
let include_cfg = opts.cfg.unwrap_or(true);
let do_analysis = include_ast || include_dataflow || include_cfg || include_complexity;
let mut analysis_ok = true;
if do_analysis {
// Determine which files to analyze (excludes reverse-dep files)
let analysis_file_set: HashSet<&str> = match &analysis_scope {
Some(files) => files.iter().map(|s| s.as_str()).collect(),
None => file_symbols.keys().map(|s| s.as_str()).collect(),
};
// Build node ID lookup: (file, name, line) -> node_id
let node_id_map = build_analysis_node_map(conn, &analysis_file_set);
// AST nodes
if include_ast {
let t0 = Instant::now();
let ast_batches = build_ast_batches(&file_symbols, &analysis_file_set);
if ast_db::do_insert_ast_nodes(conn, &ast_batches).is_err() {
analysis_ok = false;
}
timing.ast_ms = t0.elapsed().as_secs_f64() * 1000.0;
}
// Complexity metrics
if include_complexity {
let t0 = Instant::now();
if !write_complexity(conn, &file_symbols, &analysis_file_set, &node_id_map) {
analysis_ok = false;
}
timing.complexity_ms = t0.elapsed().as_secs_f64() * 1000.0;
}
// CFG blocks + edges
if include_cfg {
let t0 = Instant::now();
if !write_cfg(conn, &file_symbols, &analysis_file_set, &node_id_map) {
analysis_ok = false;
}
timing.cfg_ms = t0.elapsed().as_secs_f64() * 1000.0;
}
// Dataflow edges
if include_dataflow {
let t0 = Instant::now();
if !write_dataflow(conn, &file_symbols, &analysis_file_set) {
analysis_ok = false;
}
timing.dataflow_ms = t0.elapsed().as_secs_f64() * 1000.0;
}
}
// ── Stage 9: Finalize ──────────────────────────────────────────────
let t0 = Instant::now();
let (node_count, edge_count) = finalize_build(conn, root_dir);
timing.finalize_ms = t0.elapsed().as_secs_f64() * 1000.0;
// Include total time in setup for overhead accounting.
// Clamp to 0.0 to avoid negative values from floating-point rounding.
let stage_sum = timing.collect_ms
+ timing.detect_ms
+ timing.parse_ms
+ timing.insert_ms
+ timing.resolve_ms
+ timing.edges_ms
+ timing.structure_ms
+ timing.roles_ms
+ timing.ast_ms
+ timing.complexity_ms
+ timing.cfg_ms
+ timing.dataflow_ms
+ timing.finalize_ms;
let overhead = total_start.elapsed().as_secs_f64() * 1000.0 - stage_sum;
timing.setup_ms += overhead.max(0.0);
Ok(BuildPipelineResult {
phases: timing,
node_count,
edge_count,
file_count: collect_result.files.len(),
early_exit: false,
changed_files: analysis_scope,
changed_count: parse_changes.len(),
removed_count: change_result.removed.len(),
is_full_build: change_result.is_full_build,
structure_handled: true,
analysis_complete: do_analysis && analysis_ok,
})
}
/// Stage 2: Collect source files with strategy selection (scoped, journal-fast, or full).
fn collect_source_files(
conn: &Connection,
root_dir: &str,
config: &BuildConfig,
opts: &BuildOpts,
incremental: bool,
force_full_rebuild: bool,
) -> file_collector::CollectResult {
if let Some(ref scope) = opts.scope {
// Scoped rebuild
let files: Vec<String> = scope
.iter()
.map(|f| {
let abs = Path::new(root_dir).join(normalize_path(f));
abs.to_str().unwrap_or("").to_string()
})
.filter(|f| Path::new(f).exists())
.collect();
file_collector::CollectResult {
directories: files
.iter()
.filter_map(|f| {
Path::new(f)
.parent()
.map(|p| p.to_str().unwrap_or("").to_string())
})
.collect(),
files,
}
} else if incremental && !force_full_rebuild {
// Try fast collect from DB + journal
let journal = journal::read_journal(root_dir);
let has_entries =
journal.valid && (!journal.changed.is_empty() || !journal.removed.is_empty());
if has_entries {
let db_files: Vec<String> = conn
.prepare("SELECT file FROM file_hashes")
.and_then(|mut stmt| {
stmt.query_map([], |row| row.get::<_, String>(0))
.map(|rows| rows.filter_map(|r| r.ok()).collect())
})
.unwrap_or_default();
if !db_files.is_empty() {
file_collector::try_fast_collect(
root_dir,
&db_files,
&journal.changed,
&journal.removed,
&config.include,
&config.exclude,
)
} else {
file_collector::collect_files(
root_dir,
&config.ignore_dirs,
&config.include,
&config.exclude,
)
}
} else {
file_collector::collect_files(
root_dir,
&config.ignore_dirs,
&config.include,
&config.exclude,
)
}
} else {
file_collector::collect_files(
root_dir,
&config.ignore_dirs,
&config.include,
&config.exclude,
)
}
}
/// Stage 6b: Re-parse barrel candidates for incremental builds.
///
/// Barrel files (re-export-only index files) may not be in file_symbols because
/// they weren't changed or reverse-deps. Without their symbols, barrel resolution
/// in Stage 7 can't create transitive import edges.
///
/// Discovery is iterative: a barrel that imports another barrel (e.g.
/// `parser.ts → extractors/index.ts → extractors/<lang>.ts`) needs both
/// loaded so Stage 7 can emit the barrel-through edges from the first barrel
/// to the leaf targets. Without the loop, only the first level of barrels
/// gets merged into `file_symbols`; the deeper chain has no entry in
/// `reexport_map`, so `resolve_barrel_export` returns `None` and the
/// barrel-through edges are silently dropped on every incremental rebuild
/// (#1174). Convergence is guaranteed because `file_symbols` grows
/// monotonically and is bounded by the set of barrel files in the project.
fn reparse_barrel_candidates(
conn: &Connection,
root_dir: &str,
napi_aliases: &crate::types::PathAliases,
known_files: &HashSet<String>,
file_symbols: &mut HashMap<String, FileSymbols>,
batch_resolved: &mut HashMap<String, String>,
) {
// Find all barrel files from DB (files that have 'reexports' edges)
let barrel_files_in_db: HashSet<String> = {
let rows: Vec<String> = match conn.prepare(
"SELECT DISTINCT n1.file FROM edges e \
JOIN nodes n1 ON e.source_id = n1.id \
WHERE e.kind = 'reexports' AND n1.kind = 'file'",
) {
Ok(mut stmt) => match stmt.query_map([], |row| row.get::<_, String>(0)) {
Ok(mapped) => mapped.filter_map(|r| r.ok()).collect(),
Err(_) => Vec::new(),
},
Err(_) => Vec::new(),
};
rows.into_iter().collect()
};
// Seed: barrels imported by the initial file_symbols (= changed files),
// plus barrels that re-export FROM any changed file. The reexport-from
// seed only fires on the initial pass — re-parsed barrels haven't
// changed in content, so they can't trigger new reexport-from candidates.
let initial_files: Vec<String> = file_symbols.keys().cloned().collect();
let mut barrel_paths_to_parse: Vec<String> = collect_imported_barrel_candidates(
root_dir,
&initial_files,
batch_resolved,
&barrel_files_in_db,
file_symbols,
);
barrel_paths_to_parse.extend(collect_reexport_from_barrels(
conn,
root_dir,
&initial_files,
file_symbols,
));
// Iterative re-parse: each pass merges the queued barrels into file_symbols,
// then scans their imports for additional barrel candidates the previous
// pass couldn't see.
while !barrel_paths_to_parse.is_empty() {
barrel_paths_to_parse.sort();
barrel_paths_to_parse.dedup();
let to_parse = std::mem::take(&mut barrel_paths_to_parse);
// Re-parse barrel candidates — these may be hybrid barrels (reexports
// AND local definitions / call sites, see #979). Dataflow/AST analysis
// is skipped because the barrel is not itself a "changed" file; Stage 7
// will reconstruct all outgoing edge kinds from the fresh parse.
let barrel_parsed = parallel::parse_files_parallel(&to_parse, root_dir, false, false);
let mut newly_added: Vec<String> = Vec::with_capacity(barrel_parsed.len());
for mut sym in barrel_parsed {
let rel = relative_path(root_dir, &sym.file);
sym.file = rel.clone();
// Delete every outgoing edge kind that Stage 7 re-emits for re-parsed
// barrel candidates. Previously only 'imports' and 'reexports' were
// purged, so 'calls', 'receiver', 'extends', 'implements',
// 'imports-type', and 'dynamic-imports' accumulated duplicates on
// every incremental rebuild (#979).
//
// Use a negative filter (`NOT IN`) rather than an allowlist so any
// future edge kind added to Stage 7 is automatically covered. Only
// 'contains' and 'parameter_of' must be preserved: those are emitted
// by Stage 5 (insert_nodes) which only runs on the original
// file_symbols (changed + reverse-deps). Barrel candidates are
// merged into file_symbols here in Stage 6b *after* Stage 5 has
// already run, so wiping contains/parameter_of would permanently
// drop them.
let _ = conn.execute(
"DELETE FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?1) \
AND kind NOT IN ('contains', 'parameter_of')",
rusqlite::params![&rel],
);
// Re-resolve imports for the barrel file
// Normalize to forward slashes so batch_resolved keys match get_resolved lookups on Windows.
let abs_str =
Path::new(root_dir).join(&rel).to_str().unwrap_or("").replace('\\', "/");
for imp in &sym.imports {
let input = ImportResolutionInput {
from_file: abs_str.clone(),
import_source: imp.source.clone(),
};
let resolved_batch = import_resolution::resolve_imports_batch(
&[input],
root_dir,
napi_aliases,
Some(known_files),
);
for r in &resolved_batch {
let key = format!("{}|{}", r.from_file, r.import_source);
batch_resolved.insert(key, r.resolved_path.clone());
}
}
file_symbols.insert(rel.clone(), sym);
newly_added.push(rel);
}
// Scan just-merged barrels for further barrel imports (next level of
// the chain). batch_resolved is now up to date for these imports.
barrel_paths_to_parse = collect_imported_barrel_candidates(
root_dir,
&newly_added,
batch_resolved,
&barrel_files_in_db,
file_symbols,
);
}
}
/// Walk the imports of `from_files` and return absolute paths of any barrel
/// candidates (files in `barrel_files_in_db` not yet in `file_symbols`) that
/// exist on disk.
fn collect_imported_barrel_candidates(
root_dir: &str,
from_files: &[String],
batch_resolved: &HashMap<String, String>,
barrel_files_in_db: &HashSet<String>,
file_symbols: &HashMap<String, FileSymbols>,
) -> Vec<String> {
let mut out = Vec::new();
for rel_path in from_files {
let symbols = match file_symbols.get(rel_path) {
Some(s) => s,
None => continue,
};
let abs_file = Path::new(root_dir).join(rel_path);
let fwd = abs_file.to_str().unwrap_or("").replace('\\', "/");
for imp in &symbols.imports {
let key = format!("{}|{}", fwd, imp.source);
if let Some(resolved) = batch_resolved.get(&key) {
if barrel_files_in_db.contains(resolved)
&& !file_symbols.contains_key(resolved)
{
let abs = Path::new(root_dir).join(resolved);
if abs.exists() {
out.push(abs.to_str().unwrap_or("").to_string());
}
}
}
}
}
out
}
/// Find barrels that re-export from any of `changed_files`. Used as a seed
/// for the iterative re-parse so a renamed/removed symbol in a changed file
/// re-emits the affected barrel's outgoing edges.
fn collect_reexport_from_barrels(
conn: &Connection,
root_dir: &str,
changed_files: &[String],
file_symbols: &HashMap<String, FileSymbols>,
) -> Vec<String> {
let mut out = Vec::new();
let mut stmt = match conn.prepare(
"SELECT DISTINCT n1.file FROM edges e \
JOIN nodes n1 ON e.source_id = n1.id \
JOIN nodes n2 ON e.target_id = n2.id \
WHERE e.kind = 'reexports' AND n1.kind = 'file' AND n2.file = ?1",
) {
Ok(stmt) => stmt,
Err(_) => return out,
};
for changed in changed_files {
if let Ok(rows) =
stmt.query_map(rusqlite::params![changed], |row| row.get::<_, String>(0))
{
for row in rows.flatten() {
if !file_symbols.contains_key(&row) {
let abs = Path::new(root_dir).join(&row);
if abs.exists() {
out.push(abs.to_str().unwrap_or("").to_string());
}
}
}
}
}
out
}
/// Stage 9: Finalize build — persist metadata, write journal, return counts.
fn finalize_build(conn: &Connection, root_dir: &str) -> (i64, i64) {
let node_count = conn
.query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get::<_, i64>(0))
.unwrap_or(0);
let edge_count = conn
.query_row("SELECT COUNT(*) FROM edges", [], |row| row.get::<_, i64>(0))
.unwrap_or(0);
// Persist build metadata
let version = env!("CARGO_PKG_VERSION");
let meta_sql = "INSERT OR REPLACE INTO build_meta (key, value) VALUES (?, ?)";
if let Ok(mut stmt) = conn.prepare(meta_sql) {
let _ = stmt.execute(["engine", "native"]);
let _ = stmt.execute(["engine_version", version]);
let _ = stmt.execute(["codegraph_version", version]);
let _ = stmt.execute(["node_count", &node_count.to_string()]);
let _ = stmt.execute(["edge_count", &edge_count.to_string()]);
let _ = stmt.execute(["last_build", &now_ms().to_string()]);
// Persist repo root so downstream commands (e.g. `codegraph embed`)
// can resolve relative file paths regardless of invoking cwd.
let root_canon = std::fs::canonicalize(root_dir)
.ok()
.and_then(|p| p.to_str().map(|s| s.to_string()))
.unwrap_or_else(|| root_dir.to_string());
let _ = stmt.execute(["root_dir", &root_canon]);
}
// Write journal header
journal::write_journal_header(root_dir, now_ms());
(node_count, edge_count)
}
/// Check if engine/schema/version changed since last build (forces full rebuild).
fn check_version_mismatch(conn: &Connection) -> bool {
let get_meta = |key: &str| -> Option<String> {
conn.query_row("SELECT value FROM build_meta WHERE key = ?", [key], |row| {
row.get(0)
})
.ok()
};
let current_version = env!("CARGO_PKG_VERSION");
if let Some(prev_engine) = get_meta("engine") {
if prev_engine != "native" {
return true;
}
}
// Compare against engine_version (the addon's own version), not
// codegraph_version (the npm package version). The JS post-processing
// overwrites codegraph_version with the npm version, which may differ
// from CARGO_PKG_VERSION — causing a perpetual full-rebuild loop (#928).
if let Some(prev_version) = get_meta("engine_version") {
if prev_version != current_version {
return true;
}
}
false
}
/// Build InsertNodesBatch from parsed file symbols.
fn build_insert_batches(
file_symbols: &HashMap<String, FileSymbols>,
) -> Vec<crate::insert_nodes::InsertNodesBatch> {
file_symbols
.iter()
.map(
|(rel_path, symbols)| crate::insert_nodes::InsertNodesBatch {
file: rel_path.clone(),
definitions: symbols
.definitions
.iter()
.map(|d| crate::insert_nodes::InsertNodesDefinition {
name: d.name.clone(),
kind: d.kind.clone(),
line: d.line,
end_line: d.end_line,
visibility: None,
children: d
.children
.as_ref()
.map(|kids| {
kids.iter()
.map(|c| crate::insert_nodes::InsertNodesChild {
name: c.name.clone(),
kind: c.kind.clone(),
line: c.line,
end_line: c.end_line,
visibility: None,
})
.collect()
})
.unwrap_or_default(),
})
.collect(),
exports: symbols
.exports
.iter()
.map(|e| crate::insert_nodes::InsertNodesExport {
name: e.name.clone(),
kind: e.kind.clone(),
line: e.line,
})
.collect(),
},
)
.collect()
}
/// Build FileHashEntry from changed files.
///
/// For full builds, `detect_changes` returns `hash: None` because it skips
/// reading file content. In that case we read and hash each file here so
/// that `file_hashes` is populated for subsequent incremental builds.
fn build_file_hash_entries(
changed: &[&change_detection::ChangedFile],
) -> Vec<crate::insert_nodes::FileHashEntry> {
changed
.iter()
.filter_map(|c| {
let hash = match c.hash.as_ref() {
Some(h) => h.clone(),
None => {
// Full build path: read file and compute hash now
match std::fs::read_to_string(&c.abs_path) {
Ok(content) => {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(content.as_bytes());
format!("{:x}", hasher.finalize())
}
Err(_) => return None,
}
}
};
let (mtime, size) = if c.mtime == 0 && c.size == 0 {
// Full build: read metadata from filesystem
std::fs::metadata(&c.abs_path)
.ok()
.map(|m| {
let mtime = m
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as f64)
.unwrap_or(0.0);
let size = m.len() as f64;
(mtime, size)
})
.unwrap_or((0.0, 0.0))
} else {
(c.mtime as f64, c.size as f64)
};
Some(crate::insert_nodes::FileHashEntry {
file: c.rel_path.clone(),
hash,
mtime,
size,
})
})
.collect()
}
/// Build call edges using the Rust edge_builder and insert them.
///
/// `is_incremental`: when true, the set of nodes loaded from the DB may be
/// scoped to the files being processed plus their resolved import targets.
/// Scoping is gated on:
/// - small incremental change set (`file_symbols.len() <= SMALL_FILES`)
/// - large-enough existing codebase (`file-node count > MIN_EXISTING`)
/// Both gates mirror the JS path in `build-edges.ts` (#976) to avoid
/// exercising the scoped path on tiny fixtures where the scoped set can
/// miss transitively-required nodes (e.g. a call site whose receiver type
/// is declared in a file that isn't a direct import target).
///
/// Full builds always load every node — there is no smaller set anyway.
fn build_and_insert_call_edges(
conn: &Connection,
file_symbols: &HashMap<String, FileSymbols>,
import_ctx: &ImportEdgeContext,
is_incremental: bool,
) {
use crate::edge_builder::*;
let node_kind_filter = "kind IN ('function','method','class','interface','struct','type','module','enum','trait','record','constant')";
// Gate parity with `loadNodes` in `src/domain/graph/builder/stages/build-edges.ts`:
// isFullBuild = false
// && fileSymbols.size <= smallFilesThreshold (5)
// && existingFileCount > FAST_PATH_MIN_EXISTING_FILES (20)
// Small fixtures skip the scoped path entirely — the savings are
// negligible at that scale and the scoped set can miss nodes that the
// edge builder needs for receiver-type resolution (#976).
let existing_file_count: i64 = conn
.query_row(
"SELECT COUNT(*) FROM nodes WHERE kind = 'file'",
[],
|row| row.get(0),
)
.unwrap_or(0);
let scope_eligible = is_incremental
&& file_symbols.len() <= crate::constants::FAST_PATH_MAX_CHANGED_FILES