vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Incremental index update logic.
//!
//! Detects changed files via content hashing, then re-indexes only
//! modified/new files and removes deleted files from the index.
//!
//! Parsing and embedding finish before stored rows are replaced. A read or
//! provider failure therefore leaves the previous index data available.
//!
//! The algorithm:
//! 1. Discover current files on disk
//! 2. Load stored content hashes from the metadata DB
//! 3. Classify each file as: unchanged, modified, new, or deleted
//! 4. For modified/new files: re-parse, re-chunk, re-embed, update stores
//! 5. For deleted files: remove chunks, vectors, BM25 entries, and hashes
//! 6. Return an UpdateSummary describing what changed

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::time::Instant;

use anyhow::{Context, Result, bail};
use rayon::prelude::*;
use sha2::{Digest, Sha256};
use tracing::{debug, info, warn};

use crate::CancellationToken;
use crate::config::VeraConfig;
use crate::discovery;
use crate::embedding::{
    EmbeddingError, EmbeddingProvider, embed_chunks_concurrent_with_progress_and_cancellation,
};
use crate::parsing;
use crate::storage::bm25::Bm25Index;
use crate::storage::metadata::{FileIndexState, FileIndexStatus, MetadataStore};
use crate::storage::vector::VectorStore;
use crate::types::Language;

use super::pipeline;
use super::pipeline::FileError;

/// Summary of an incremental update run.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UpdateSummary {
    /// Files that were modified and processed.
    pub files_modified: usize,
    /// New files that were processed.
    pub files_added: usize,
    /// Files that were deleted from the index.
    pub files_deleted: usize,
    /// Files that were unchanged (skipped).
    pub files_unchanged: usize,
    /// Number of processed files whose parse trees contained tree-sitter errors.
    pub files_with_tree_sitter_errors: usize,
    /// Number of processed files that fell back to Tier 0 chunking.
    pub files_using_tier0_fallback: usize,
    /// Files that failed to parse during the update.
    pub parse_errors: Vec<FileError>,
    /// Added or modified files deferred by the per-run file limit.
    pub files_deferred: usize,
    /// Total chunks after the update.
    pub total_chunks: u64,
    /// Wall-clock elapsed time in seconds.
    pub elapsed_secs: f64,
}

/// Optional controls for a single incremental update run.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct UpdateOptions {
    /// Maximum added or modified files to process. Deletions are always applied.
    pub max_files: Option<usize>,
}

/// Progress events emitted during an incremental update.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdateProgress {
    /// File discovery complete.
    DiscoveryDone { file_count: usize },
    /// Existing and discovered files have been classified.
    ClassificationDone {
        modified: usize,
        added: usize,
        deleted: usize,
        unchanged: usize,
        deferred: usize,
    },
    /// Changed files have been parsed into chunks.
    ParsingDone {
        file_count: usize,
        chunk_count: usize,
    },
    /// An embedding batch finished.
    EmbeddingProgress { done: usize, total: usize },
    /// All update embeddings have been generated.
    EmbeddingDone { count: usize },
    /// Updated index artifacts have been written to disk.
    StorageDone,
}

/// Parsed update data held in memory until embedding has succeeded.
struct PreparedFile {
    path: String,
    hash: String,
    modified: bool,
    chunks: Vec<crate::types::Chunk>,
    references: Vec<parsing::references::RawReference>,
    type_relations: Vec<parsing::type_relations::RawTypeRelation>,
    state: FileIndexState,
}

fn collect_prepared_results(
    results: Vec<(PreparedFile, Option<FileError>)>,
) -> (Vec<PreparedFile>, Vec<FileError>) {
    let mut prepared_files = Vec::with_capacity(results.len());
    let mut parse_errors = Vec::new();
    for (prepared, parse_error) in results {
        prepared_files.push(prepared);
        if let Some(parse_error) = parse_error {
            parse_errors.push(parse_error);
        }
    }
    (prepared_files, parse_errors)
}

fn processed_file_counts(files: impl IntoIterator<Item = bool>) -> (usize, usize) {
    files
        .into_iter()
        .fold((0, 0), |(modified, added), is_modified| {
            if is_modified {
                (modified + 1, added)
            } else {
                (modified, added + 1)
            }
        })
}

/// Compute a SHA-256 content hash for a file's contents.
pub fn content_hash(content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    let hash = hasher.finalize();
    hash.iter().fold(String::with_capacity(64), |mut s, b| {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
        s
    })
}

pub(crate) fn detect_language_for_path(file_path: impl AsRef<Path>) -> Language {
    let file_path = file_path.as_ref();
    file_path
        .file_name()
        .and_then(|n| n.to_str())
        .and_then(Language::from_filename)
        .unwrap_or_else(|| {
            let ext = file_path.extension().and_then(|e| e.to_str()).unwrap_or("");
            Language::from_extension(ext)
        })
}

pub(crate) fn hash_for_indexing_source(
    content: &str,
    rel_path: &str,
    language: Language,
    repo_root: &Path,
    max_file_size_bytes: u64,
) -> String {
    content_hash(&source_for_indexing_hash(
        content,
        rel_path,
        language,
        repo_root,
        max_file_size_bytes,
    ))
}

fn source_for_indexing_hash<'a>(
    content: &'a str,
    rel_path: &str,
    language: Language,
    repo_root: &Path,
    max_file_size_bytes: u64,
) -> Cow<'a, str> {
    if language != Language::Rst {
        return Cow::Borrowed(content);
    }

    let absolute_path = repo_root.join(rel_path);
    match parsing::sphinx::preprocess_rst_with_limit(
        content,
        &absolute_path,
        repo_root,
        max_file_size_bytes,
    ) {
        Ok(preprocessed) => Cow::Owned(preprocessed),
        Err(err) => {
            warn!(
                file = %rel_path,
                error = %err,
                "failed to preprocess rst for hashing; falling back to raw source"
            );
            Cow::Borrowed(content)
        }
    }
}

/// Incrementally update the index for a repository.
///
/// Only re-indexes files whose content has changed since the last index/update.
/// Handles:
/// - Modified files: re-parse, re-chunk, re-embed, update all stores
/// - New files: parse, chunk, embed, add to all stores
/// - Deleted files: remove from all stores
/// - Unchanged files: skip entirely
pub async fn update_repository<P: EmbeddingProvider>(
    repo_path: &Path,
    provider: &P,
    config: &VeraConfig,
    model_name: &str,
) -> Result<UpdateSummary> {
    update_repository_with_options_and_progress(
        repo_path,
        provider,
        config,
        model_name,
        &UpdateOptions::default(),
        |_| {},
    )
    .await
}

/// Incrementally update an index with progress reporting via a callback.
pub async fn update_repository_with_progress<P, F>(
    repo_path: &Path,
    provider: &P,
    config: &VeraConfig,
    model_name: &str,
    on_progress: F,
) -> Result<UpdateSummary>
where
    P: EmbeddingProvider,
    F: Fn(UpdateProgress) + Send + Sync,
{
    update_repository_with_options_and_progress(
        repo_path,
        provider,
        config,
        model_name,
        &UpdateOptions::default(),
        on_progress,
    )
    .await
}

/// Incrementally update an index with per-run options and progress reporting.
pub async fn update_repository_with_options_and_progress<P, F>(
    repo_path: &Path,
    provider: &P,
    config: &VeraConfig,
    model_name: &str,
    options: &UpdateOptions,
    on_progress: F,
) -> Result<UpdateSummary>
where
    P: EmbeddingProvider,
    F: Fn(UpdateProgress) + Send + Sync,
{
    update_repository_with_options_and_progress_and_cancellation(
        repo_path,
        provider,
        config,
        model_name,
        options,
        on_progress,
        &CancellationToken::new(),
    )
    .await
}

/// Incrementally update an index with progress reporting and cooperative cancellation.
///
/// Cancellation is observed through discovery, parsing, and embedding. Once publication
/// starts, all index stores are updated before the operation returns so callers never
/// receive a cancellation result while writes are still in progress.
pub async fn update_repository_with_options_and_progress_and_cancellation<P, F>(
    repo_path: &Path,
    provider: &P,
    config: &VeraConfig,
    model_name: &str,
    options: &UpdateOptions,
    on_progress: F,
    cancellation: &CancellationToken,
) -> Result<UpdateSummary>
where
    P: EmbeddingProvider,
    F: Fn(UpdateProgress) + Send + Sync,
{
    let start = Instant::now();
    cancellation.check()?;

    // ── 1. Validate path ─────────────────────────────────────────
    if !repo_path.exists() {
        bail!("path does not exist: {}", repo_path.display());
    }
    if !repo_path.is_dir() {
        bail!("path is not a directory: {}", repo_path.display());
    }

    let repo_root = repo_path
        .canonicalize()
        .with_context(|| format!("failed to resolve path: {}", repo_path.display()))?;

    let idx_dir = pipeline::index_dir(&repo_root);
    if !idx_dir.exists() {
        bail!(
            "no index found at {}. Run `vera index` first.",
            idx_dir.display()
        );
    }

    info!(path = %repo_root.display(), "starting incremental update");

    // ── 2. Discover current files on disk ────────────────────────
    let disc =
        discovery::discover_files_with_cancellation(&repo_root, &config.indexing, cancellation)
            .context("file discovery failed")?;
    on_progress(UpdateProgress::DiscoveryDone {
        file_count: disc.files.len(),
    });

    // ── 3. Load stored hashes and classify files ─────────────────
    let metadata_path = idx_dir.join("metadata.db");
    let metadata_store =
        MetadataStore::open(&metadata_path).context("failed to open metadata store")?;

    let mut stored_dim = config.embedding.max_stored_dim;

    // Check for provider mismatch.
    if let (Some(s_model), Some(s_dim)) = (
        metadata_store.get_index_meta("model_name").unwrap_or(None),
        metadata_store
            .get_index_meta("embedding_dim")
            .unwrap_or(None),
    ) {
        if !crate::config::model_names_match_with_aliases(
            &s_model,
            model_name,
            &config.embedding.model_aliases,
        ) {
            bail!(
                "Index was created with model '{}' ({} dimensions), but you are using model '{}'. Please re-index with matching provider.",
                s_model,
                s_dim,
                model_name
            );
        }
        // A changed document prefix means the stored vectors live in a
        // different vector space. Indexes written before this guard have no
        // stored prefix, and their documents were never prefixed.
        let stored_prefix = metadata_store
            .get_index_meta("document_prefix")
            .unwrap_or(None)
            .unwrap_or_default();
        let active_prefix = provider.document_prefix_identity();
        if stored_prefix != active_prefix {
            bail!(
                "Index was created with document prefix '{}', but the active provider uses '{}'. Please re-index to rebuild the vector space.",
                stored_prefix,
                active_prefix
            );
        }
        if let Ok(dim) = s_dim.parse::<usize>() {
            if let Some(provider_dim) = provider.expected_dim()
                && provider_dim < dim
            {
                bail!(
                    "Dimension mismatch: index has {} dimensions but active provider only returns {}. Please re-index with matching provider.",
                    dim,
                    provider_dim
                );
            }
            stored_dim = dim;
        }
    } else if let Some(s_dim) = metadata_store
        .get_index_meta("embedding_dim")
        .unwrap_or(None)
        && let Ok(dim) = s_dim.parse::<usize>()
    {
        stored_dim = dim;
    }

    let stored_files: HashSet<String> = metadata_store
        .tracked_files()
        .context("failed to list tracked files")?
        .into_iter()
        .collect();

    // File reads are independent and I/O-bound, so run them under rayon.
    // Unreadable files stay in `current_paths` below but not `current_files`,
    // preserving their existing index data instead of treating them as deleted.
    let read_results: Vec<(String, Option<String>)> = disc
        .files
        .par_iter()
        .map(|file| {
            cancellation.check()?;
            let content = match discovery::read_source_lossy_at(
                &disc.root_dir,
                Path::new(&file.relative_path),
            ) {
                Ok(content) => Some(content),
                Err(err) => {
                    warn!(file = %file.relative_path, error = %err, "failed to read file");
                    None
                }
            };
            Ok((file.relative_path.clone(), content))
        })
        .collect::<Result<_>>()?;
    cancellation.check()?;

    let current_files: HashMap<String, String> = read_results
        .into_iter()
        .filter_map(|(path, content)| content.map(|content| (path, content)))
        .collect();

    let current_paths: HashSet<&str> = disc
        .files
        .iter()
        .map(|file| file.relative_path.as_str())
        .collect();

    // Classify files.
    let mut modified = Vec::new();
    let mut added = Vec::new();
    let mut deleted = Vec::new();
    let mut unchanged = 0usize;

    for (rel_path, content) in &current_files {
        cancellation.check()?;
        let language = detect_language_for_path(rel_path);
        let normalized_source = source_for_indexing_hash(
            content,
            rel_path,
            language,
            &repo_root,
            config.indexing.max_file_size_bytes,
        );
        let hash = content_hash(&normalized_source);
        let normalized_source = (language == Language::Rst).then(|| normalized_source.into_owned());
        let stored_hash = metadata_store
            .get_file_hash(rel_path)
            .context("failed to get stored hash")?;

        if stored_files.contains(rel_path.as_str()) {
            // File exists in index.
            match stored_hash {
                Some(ref old_hash) if *old_hash == hash => {
                    unchanged += 1;
                }
                _ => {
                    modified.push((rel_path.clone(), content.clone(), hash, normalized_source));
                }
            }
        } else {
            // New file (not in index).
            added.push((rel_path.clone(), content.clone(), hash, normalized_source));
        }
    }

    for stored_path in &stored_files {
        if !current_paths.contains(stored_path.as_str()) {
            deleted.push(stored_path.clone());
        }
    }

    modified.sort_by(|left, right| left.0.cmp(&right.0));
    added.sort_by(|left, right| left.0.cmp(&right.0));
    deleted.sort();

    let pending_files = modified.len() + added.len();
    let files_to_process = options
        .max_files
        .unwrap_or(pending_files)
        .min(pending_files);
    let modified_to_process = modified.len().min(files_to_process);
    let added_to_process = added
        .len()
        .min(files_to_process.saturating_sub(modified_to_process));
    let files_deferred = pending_files - modified_to_process - added_to_process;
    modified.truncate(modified_to_process);
    added.truncate(added_to_process);

    info!(
        modified = modified.len(),
        added = added.len(),
        deleted = deleted.len(),
        unchanged,
        deferred = files_deferred,
        max_files = options.max_files,
        "file classification complete"
    );
    on_progress(UpdateProgress::ClassificationDone {
        modified: modified.len(),
        added: added.len(),
        deleted: deleted.len(),
        unchanged,
        deferred: files_deferred,
    });

    // ── 4. Prepare modifications and additions ───────────────────
    let files_to_index: Vec<(String, String, String, Option<String>, bool)> = modified
        .iter()
        .cloned()
        .map(|(path, content, hash, normalized_source)| {
            (path, content, hash, normalized_source, true)
        })
        .chain(
            added
                .iter()
                .cloned()
                .map(|(path, content, hash, normalized_source)| {
                    (path, content, hash, normalized_source, false)
                }),
        )
        .collect();
    let mut prepared_files = Vec::new();
    let mut parse_errors = Vec::new();

    if !files_to_index.is_empty() {
        // Parse and chunk new/modified files. Tree-sitter parsing is CPU-bound,
        // so this is parallelized with rayon (mirrors pipeline.rs's full-index
        // path). Results are still staged in `PreparedFile` and written only
        // after embedding succeeds. Parallelism here must not move any write
        // earlier.
        let parsed: Vec<(PreparedFile, Option<FileError>)> = files_to_index
            .par_iter()
            .map(
                |(rel_path, content, hash, normalized_source, is_modified)| {
                    cancellation.check()?;
                    let language = detect_language_for_path(rel_path);

                    // For RST, refs come from raw source; chunks from preprocessed.
                    // For all other languages, parse once for both.
                    let (chunks, refs, file_state, parse_error) = if language == Language::Rst {
                        let refs = parsing::parse_and_extract_references(content, language);
                        let src = normalized_source.as_deref().unwrap_or(content);
                        chunk_file_for_update(src, rel_path, language, config, Some(refs))
                    } else {
                        chunk_file_for_update(content, rel_path, language, config, None)
                    };

                    let type_relations = parsing::type_relations::extract_type_relations(&chunks);

                    debug!(
                        file = %rel_path,
                        chunks = chunks.len(),
                        refs = refs.len(),
                        type_relations = type_relations.len(),
                        "parsed file"
                    );

                    Ok((
                        PreparedFile {
                            path: rel_path.clone(),
                            hash: hash.clone(),
                            modified: *is_modified,
                            chunks,
                            references: refs,
                            type_relations,
                            state: file_state,
                        },
                        parse_error,
                    ))
                },
            )
            .collect::<Result<_>>()?;
        cancellation.check()?;

        // `files_to_index` order is preserved by `collect`, so the sequential
        // and parallel paths produce identical `prepared_files` ordering.
        (prepared_files, parse_errors) = collect_prepared_results(parsed);
    }

    let all_chunks: Vec<_> = prepared_files
        .iter()
        .flat_map(|file| file.chunks.iter().cloned())
        .collect();
    let file_states: Vec<_> = prepared_files
        .iter()
        .map(|file| file.state.clone())
        .collect();

    if !files_to_index.is_empty() {
        on_progress(UpdateProgress::ParsingDone {
            file_count: files_to_index.len(),
            chunk_count: all_chunks.len(),
        });
    } else {
        on_progress(UpdateProgress::ParsingDone {
            file_count: 0,
            chunk_count: 0,
        });
        on_progress(UpdateProgress::EmbeddingDone { count: 0 });
    }

    let mut embeddings = if all_chunks.is_empty() {
        if !files_to_index.is_empty() {
            on_progress(UpdateProgress::EmbeddingDone { count: 0 });
        }
        Vec::new()
    } else {
        let (batch_size, max_concurrent_requests) = config.embedding.bounded_parallelism();
        if batch_size != config.embedding.batch_size
            || max_concurrent_requests != config.embedding.max_concurrent_requests
        {
            info!(
                configured_batch_size = config.embedding.batch_size,
                configured_concurrency = config.embedding.max_concurrent_requests,
                max_in_flight_inputs = config.embedding.max_in_flight_inputs,
                batch_size,
                max_concurrent_requests,
                "clamped update embedding parallelism to the in-flight input bound"
            );
        }
        let progress_cb = |done: usize, total: usize| {
            on_progress(UpdateProgress::EmbeddingProgress { done, total });
        };
        let embedding_result = embed_chunks_concurrent_with_progress_and_cancellation(
            provider,
            &all_chunks,
            batch_size,
            max_concurrent_requests,
            config.indexing.max_chunk_bytes,
            cancellation.as_async_token(),
            progress_cb,
        )
        .await;
        let embeddings = match embedding_result {
            Ok(embeddings) => embeddings,
            Err(error) => {
                if matches!(error, EmbeddingError::Cancelled) {
                    cancellation.check()?;
                }
                return Err(error).context("embedding generation failed");
            }
        };
        on_progress(UpdateProgress::EmbeddingDone {
            count: embeddings.len(),
        });
        embeddings
    };
    cancellation.check()?;

    let final_stored_dim = if embeddings.is_empty() {
        stored_dim
    } else {
        super::truncate_embeddings(&mut embeddings, stored_dim)
    };
    let (processed_modified, processed_added) =
        processed_file_counts(prepared_files.iter().map(|file| file.modified));

    if !deleted.is_empty() || !prepared_files.is_empty() {
        let vector_path = idx_dir.join("vectors.db");
        let vector_store = VectorStore::open(&vector_path, final_stored_dim)
            .context("failed to open vector store for update")?;
        let bm25_dir = idx_dir.join("bm25");
        let bm25_index =
            Bm25Index::open(&bm25_dir).context("failed to open BM25 index for update")?;

        // Every path whose BM25 documents have to go is removed in one pass
        // before any per-file mutation. `delete_by_files` allocates a writer,
        // commits a segment and joins the merge threads, which costs tens of
        // milliseconds per call however little is actually deleted. The batch
        // must stay ahead of `insert_chunks`, or it would delete newly written docs.
        let mut bm25_deletions: Vec<&str> = deleted.iter().map(String::as_str).collect();
        let cleanup_chunk_data: Vec<bool> = prepared_files
            .iter()
            .map(|file| {
                metadata_store
                    .get_chunks_by_file(&file.path)
                    .with_context(|| format!("failed to inspect existing chunks for {}", file.path))
                    .map(|chunks| file.modified || !chunks.is_empty())
            })
            .collect::<Result<_>>()?;
        bm25_deletions.extend(
            prepared_files
                .iter()
                .zip(&cleanup_chunk_data)
                .filter(|(_, cleanup)| **cleanup)
                .map(|(file, _)| file.path.as_str()),
        );

        // All parsing, embedding, and read-only cleanup discovery is complete.
        // Writes below publish the prepared update and must run to completion.
        cancellation.check()?;
        bm25_index
            .delete_by_files(&bm25_deletions)
            .context("failed to delete BM25 entries for changed files")?;

        for file_path in &deleted {
            remove_file_from_index(&metadata_store, &vector_store, file_path)?;
        }

        // A previous attempt may have failed after writing one store but before
        // committing the file hash. Cleaning every prepared path makes retries
        // idempotent for both modified and newly added files.
        for (file, cleanup_chunks) in prepared_files.iter().zip(cleanup_chunk_data) {
            remove_file_parse_data(&metadata_store, &file.path)?;
            if cleanup_chunks {
                remove_file_chunk_data(&metadata_store, &vector_store, &file.path)?;
            }
            metadata_store
                .delete_file_state(&file.path)
                .with_context(|| format!("failed to delete file state for {}", file.path))?;
        }
        // Batched into a single transaction instead of up to two commits per
        // file. This stays at the same point in the sequence as the per-file
        // writes it replaces, so the "nothing is replaced until embedding
        // succeeds" guarantee is unchanged.
        let file_refs: Vec<(&str, &[parsing::references::RawReference])> = prepared_files
            .iter()
            .filter(|file| !file.references.is_empty())
            .map(|file| (file.path.as_str(), file.references.as_slice()))
            .collect();
        let file_type_relations: Vec<(&str, &[parsing::type_relations::RawTypeRelation])> =
            prepared_files
                .iter()
                .filter(|file| !file.type_relations.is_empty())
                .map(|file| (file.path.as_str(), file.type_relations.as_slice()))
                .collect();
        metadata_store
            .insert_parse_artifacts_batch_borrowed(&file_refs, &file_type_relations)
            .context("failed to store references and type relations")?;

        if !all_chunks.is_empty() {
            metadata_store
                .insert_chunks(&all_chunks)
                .context("failed to insert updated chunk metadata")?;
            let batch: Vec<(&str, &[f32])> = embeddings
                .iter()
                .map(|(id, vector)| (id.as_str(), vector.as_slice()))
                .collect();
            vector_store
                .insert_batch(&batch)
                .context("failed to insert updated vectors")?;
            bm25_index
                .insert_chunks(&all_chunks)
                .context("failed to insert updated BM25 documents")?;
        }

        if !file_states.is_empty() {
            metadata_store
                .insert_file_states(&file_states)
                .context("failed to update file index states")?;
        }
        let file_hashes: Vec<(&str, &str)> = prepared_files
            .iter()
            .map(|file| (file.path.as_str(), file.hash.as_str()))
            .collect();
        metadata_store
            .set_file_hashes_batch_borrowed(&file_hashes)
            .context("failed to update file hashes")?;
    }

    // ── 5. Get final counts ──────────────────────────────────────
    let total_chunks = metadata_store
        .chunk_count()
        .context("failed to count chunks")?;
    super::freshness::record_index_snapshot(&metadata_store, &config.indexing)
        .context("failed to update index freshness metadata")?;
    on_progress(UpdateProgress::StorageDone);

    let summary = UpdateSummary {
        files_modified: processed_modified,
        files_added: processed_added,
        files_deleted: deleted.len(),
        files_unchanged: unchanged,
        files_with_tree_sitter_errors: pipeline::count_tree_sitter_error_files(&file_states),
        files_using_tier0_fallback: pipeline::count_tier0_fallback_files(&file_states),
        parse_errors,
        files_deferred,
        total_chunks,
        elapsed_secs: start.elapsed().as_secs_f64(),
    };

    info!(
        modified = summary.files_modified,
        added = summary.files_added,
        deleted = summary.files_deleted,
        unchanged = summary.files_unchanged,
        deferred = summary.files_deferred,
        total_chunks = summary.total_chunks,
        elapsed = %format!("{:.2}s", summary.elapsed_secs),
        "incremental update complete"
    );

    Ok(summary)
}

/// Remove parse-phase rows (references, type relations) for a file.
/// Modified files re-insert these during parsing, so stale rows go first.
fn chunk_file_for_update(
    src: &str,
    rel_path: &str,
    language: Language,
    config: &VeraConfig,
    refs_override: Option<Vec<parsing::references::RawReference>>,
) -> (
    Vec<crate::types::Chunk>,
    Vec<parsing::references::RawReference>,
    FileIndexState,
    Option<FileError>,
) {
    let state =
        |status: FileIndexStatus, tree_has_error: bool, tier0_fallback: bool, chunk_count: u64| {
            FileIndexState {
                file_path: rel_path.to_string(),
                language: language.to_string(),
                status,
                tree_has_error,
                tier0_fallback,
                chunk_count,
            }
        };
    match parsing::parse_file_with_diagnostics(src, rel_path, language, &config.indexing) {
        Ok((chunks, parsed_refs, diagnostics)) => {
            let chunk_count = chunks.len() as u64;
            let refs = refs_override.unwrap_or(parsed_refs);
            (
                chunks,
                refs,
                state(
                    FileIndexStatus::Indexed,
                    diagnostics.tree_has_error,
                    diagnostics.used_tier0_fallback,
                    chunk_count,
                ),
                None,
            )
        }
        Err(err) => {
            let refs = refs_override.unwrap_or_default();
            if refs.is_empty() {
                warn!(file = %rel_path, error = %err, "parse error during update");
            } else {
                warn!(
                    file = %rel_path,
                    error = %err,
                    refs = refs.len(),
                    "failed to chunk rst during update; keeping extracted references"
                );
            }
            (
                Vec::new(),
                refs,
                state(FileIndexStatus::ParseError, false, false, 0),
                Some(FileError {
                    file_path: rel_path.to_string(),
                    error: err.to_string(),
                }),
            )
        }
    }
}

fn remove_file_parse_data(metadata_store: &MetadataStore, file_path: &str) -> Result<()> {
    metadata_store
        .delete_references_by_file(file_path)
        .context("failed to delete references for file")?;
    metadata_store
        .delete_type_relations_by_file(file_path)
        .context("failed to delete type relations for file")?;
    Ok(())
}

/// Remove vector and chunk metadata for a file.
///
/// The caller must delete the file's BM25 documents before calling this helper.
fn remove_file_chunk_data(
    metadata_store: &MetadataStore,
    vector_store: &VectorStore,
    file_path: &str,
) -> Result<()> {
    // Delete from vector store using file prefix pattern.
    let prefix = format!("{file_path}:");
    vector_store
        .delete_by_file_prefix(&prefix)
        .with_context(|| format!("failed to delete vectors for {file_path}"))?;

    // Delete chunk metadata.
    metadata_store
        .delete_chunks_by_file(file_path)
        .with_context(|| format!("failed to delete metadata for {file_path}"))?;

    debug!(file = %file_path, "removed file chunk data from index");

    Ok(())
}

/// Remove all data for a file from the index stores.
fn remove_file_from_index(
    metadata_store: &MetadataStore,
    vector_store: &VectorStore,
    file_path: &str,
) -> Result<()> {
    remove_file_parse_data(metadata_store, file_path)?;
    remove_file_chunk_data(metadata_store, vector_store, file_path)?;

    // Delete file hash.
    metadata_store
        .delete_file_hash(file_path)
        .with_context(|| format!("failed to delete file hash for {file_path}"))?;
    metadata_store
        .delete_file_state(file_path)
        .with_context(|| format!("failed to delete file state for {file_path}"))?;

    Ok(())
}

#[cfg(test)]
#[path = "update_tests.rs"]
mod tests;

#[cfg(test)]
mod regression_tests {
    use super::{content_hash, hash_for_indexing_source};
    use crate::config::VeraConfig;
    use crate::embedding::test_helpers::MockProvider;
    use crate::indexing::{
        UpdateOptions, detect_staleness, index_dir, index_repository, update_repository,
        update_repository_with_options_and_progress,
    };
    use crate::storage::bm25::Bm25Index;
    use crate::types::Language;
    use tempfile::tempdir;

    #[test]
    fn rst_update_hash_matches_the_preprocessed_source_the_pipeline_indexes() {
        // The pipeline hashes the preprocessed RST it chunks (even in its
        // parse-error branch), so the update-side hash must agree or the file
        // is re-parsed on every run.
        let temp = tempdir().unwrap();
        let source_path = temp.path().join("guide.rst");
        let source = "Guide\n=====\n\nSee :doc:`Other </other>`.\n";
        std::fs::write(&source_path, source).unwrap();

        let preprocessed = crate::parsing::sphinx::preprocess_rst_with_limit(
            source,
            &source_path,
            temp.path(),
            1024,
        )
        .unwrap();
        let update_hash =
            hash_for_indexing_source(source, "guide.rst", Language::Rst, temp.path(), 1024);

        assert_ne!(content_hash(source), update_hash);
        assert_eq!(content_hash(&preprocessed), update_hash);
    }

    #[tokio::test]
    async fn update_removes_old_chunks_when_modified_file_has_no_chunks() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("main.rs"), "fn old_name() {}\n").unwrap();
        let provider = MockProvider::new(8);
        let config = VeraConfig::default();

        index_repository(dir.path(), &provider, &config, "mock-model")
            .await
            .unwrap();
        let idx = index_dir(&dir.path().canonicalize().unwrap());
        let bm25 = Bm25Index::open(&idx.join("bm25")).unwrap();
        assert!(!bm25.search("old_name", 10).unwrap().is_empty());

        std::fs::write(dir.path().join("main.rs"), "\n \n").unwrap();
        update_repository(dir.path(), &provider, &config, "mock-model")
            .await
            .unwrap();

        assert!(bm25.search("old_name", 10).unwrap().is_empty());
    }

    #[tokio::test]
    async fn update_keeps_deferred_modified_files_stale() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("a.rs"), "fn a() {}\n").unwrap();
        std::fs::write(dir.path().join("b.rs"), "fn b() {}\n").unwrap();
        let provider = MockProvider::new(8);
        let config = VeraConfig::default();

        index_repository(dir.path(), &provider, &config, "mock-model")
            .await
            .unwrap();
        std::fs::write(dir.path().join("a.rs"), "fn updated_a() {}\n").unwrap();
        std::fs::write(dir.path().join("b.rs"), "fn updated_b() {}\n").unwrap();

        let summary = update_repository_with_options_and_progress(
            dir.path(),
            &provider,
            &config,
            "mock-model",
            &UpdateOptions { max_files: Some(1) },
            |_| {},
        )
        .await
        .unwrap();
        assert_eq!(summary.files_deferred, 1);

        let freshness = detect_staleness(dir.path(), &config.indexing).unwrap();
        assert_eq!(freshness.files_modified, 1);
    }
}