From 866f695dfd72d92d8bfa08960010d0c679374897 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Tue, 4 Aug 2026 12:19:11 +0000 Subject: [PATCH] fix(index): recover an index whose project was moved or copied A project identity is the device and inode number of its directory, so a disk snapshot, a VM migration, a `cp -r`, a restored backup, a remount, or a rebuilt container image all give the same directory a new identity. The state slots still record the old one, so the namespace classifies corrupt and every command refuses it -- including the three a user would reach for. The only way out was deleting the index directory by hand, which the error text never mentioned. The error text now does, and `init` no longer needs the manual step. Under the one exclusive lease it already holds, an explicit init removes state slots that name a different filesystem location, which leaves the namespace in the same missing-state shape a pre-v2 index has -- and that shape already had a working takeover. So this reuses a proven path rather than adding a second one. The permission is deliberately narrow. `OwnerMismatch` is the only corruption reason with an unambiguous cause and a safe recovery: it is not damaged data, it is metadata naming a different object, and a symlink or bind mount cannot produce it because those share a device and inode with their target. Every slot that exists must independently carry that reason -- one mismatched slot beside a checksum failure is mixed damage and stays refused, as does every other corruption reason, as does a namespace from a newer version that may still be writing. Reads keep failing closed everywhere; only an explicit init destroys anything, and only `sync` ever silently skips. The diagnostic and the authorization share one per-slot predicate, so the message can never name a recovery the gate would refuse. --- crates/codegraph-cli/src/main.rs | 113 ++++++-- crates/codegraph-cli/tests/batch_m_uninit.rs | 275 ++++++++++++++++++- crates/codegraph-store/src/connection.rs | 7 + crates/codegraph-store/src/index_state.rs | 3 + crates/codegraph-store/src/rebuild.rs | 100 ++++++- 5 files changed, 467 insertions(+), 31 deletions(-) diff --git a/crates/codegraph-cli/src/main.rs b/crates/codegraph-cli/src/main.rs index e8d1f6bb..b9e094b7 100644 --- a/crates/codegraph-cli/src/main.rs +++ b/crates/codegraph-cli/src/main.rs @@ -26,7 +26,7 @@ use codegraph_graph::query::{SearchOptions, search_nodes}; use codegraph_mcp::{McpServer, RunUntilAdoption}; use codegraph_resolve::ReferenceResolver; use codegraph_store::queries::SearchResult; -use codegraph_store::{ExtractionStatus, IndexLease, Store}; +use codegraph_store::{CorruptReason, ExtractionStatus, IndexLease, SlotOutcome, Store}; use indicatif::{ParallelProgressIterator, ProgressBar, ProgressDrawTarget, ProgressStyle}; use rayon::prelude::*; use serde::Serialize; @@ -1468,6 +1468,9 @@ fn cmd_sync(path: Option, quiet: bool) -> Result<()> { // authorized to sync or recreate residue. let project = resolve_required_rebuild_project(path)?; let paths = index_paths(&project)?; + if let Some(reason) = owner_mismatch_only_reason(&paths) { + bail!("{}", owner_mismatch_recovery_error(&project, &reason)); + } if Store::extraction_status(&paths) == codegraph_store::ExtractionStatus::Missing && paths.current_db().is_file() { @@ -1656,6 +1659,9 @@ fn cmd_status(path: Option, json_output: bool) -> Result<()> { .status .clone() .expect("a non-busy status probe always classifies the namespace"); + let owner_mismatch_recoverable = owner_mismatch_only_reason(&resolved).is_some(); + let extraction_status_detail = + status_extraction_detail(&extraction_status, owner_mismatch_recoverable, &project); let store = status_open.into_store(); if store.is_none() { if json_output { @@ -1668,7 +1674,7 @@ fn cmd_status(path: Option, json_output: bool) -> Result<()> { "dbPath": db, "dbExists": db_exists, "extractionStatus": extraction_status_name(&extraction_status), - "extractionStatusDetail": extraction_status.to_string(), + "extractionStatusDetail": extraction_status_detail, "legacyIndexPresent": legacy_index_present, "legacyIndexPaths": legacy_index_paths, "daemonRunning": daemon_running, @@ -1679,6 +1685,8 @@ fn cmd_status(path: Option, json_output: bool) -> Result<()> { if matches!(&extraction_status, ExtractionStatus::Building { .. }) { status["recoveryCommand"] = json!(format!("codegraph index --force {}", project.display())); + } else if owner_mismatch_recoverable { + status["recoveryCommand"] = json!(format!("codegraph init {}", project.display())); } print_json(&status)?; } else { @@ -1696,16 +1704,31 @@ fn cmd_status(path: Option, json_output: bool) -> Result<()> { "Daemon: {}", if daemon_running { "running" } else { "stopped" } ); - if matches!(&extraction_status, ExtractionStatus::Building { .. }) { - println!("Index is not readable while the build is incomplete."); - println!( - "Recovery: run `codegraph index --force {}` to rebuild the interrupted index; `codegraph init {}` is also supported.", - project.display(), - project.display() - ); - } else { - println!("Not initialized"); - println!("Run \"codegraph init\" to initialize"); + match &extraction_status { + ExtractionStatus::Building { .. } => { + println!("Index is not readable while the build is incomplete."); + println!( + "Recovery: run `codegraph index --force {}` to rebuild the interrupted index; `codegraph init {}` is also supported.", + project.display(), + project.display() + ); + } + ExtractionStatus::Corrupt { .. } if owner_mismatch_recoverable => { + println!( + "Index belongs to a different filesystem location because the project was moved or copied." + ); + println!( + "Recovery: run `codegraph init {}` to replace it.", + project.display() + ); + } + ExtractionStatus::Corrupt { .. } => { + println!("Manual recovery is required."); + } + _ => { + println!("Not initialized"); + println!("Run \"codegraph init\" to initialize"); + } } } return Ok(()); @@ -1828,6 +1851,54 @@ fn extraction_status_name(status: &codegraph_store::ExtractionStatus) -> &'stati } } +fn owner_mismatch_only_reason( + paths: &codegraph_core::IndexPaths, +) -> Option { + let classification = codegraph_store::classify(paths); + let reason = match classification.status() { + ExtractionStatus::Corrupt { + reason: reason @ CorruptReason::OwnerMismatch { .. }, + } => reason.clone(), + _ => return None, + }; + let mut present = false; + for index in 0..2 { + match classification.slot(index) { + SlotOutcome::Absent => {} + SlotOutcome::Invalid(CorruptReason::OwnerMismatch { .. }) => present = true, + SlotOutcome::Valid(_) | SlotOutcome::FutureProtocol(_) | SlotOutcome::Invalid(_) => { + return None; + } + } + } + present.then_some(reason) +} + +fn owner_mismatch_recovery_error(project: &Path, reason: &CorruptReason) -> String { + format!( + "CodeGraph index state in {} is corrupt: {reason}; the index belongs to a different filesystem location because the project was moved or copied; run `codegraph init {}` to replace it", + project.display(), + project.display() + ) +} + +fn status_extraction_detail( + status: &ExtractionStatus, + owner_mismatch_recoverable: bool, + project: &Path, +) -> String { + match status { + ExtractionStatus::Corrupt { reason } if owner_mismatch_recoverable => format!( + "{reason}; the index belongs to a different filesystem location because the project was moved or copied; run `codegraph init {}` to replace it", + project.display() + ), + ExtractionStatus::Corrupt { reason } => { + format!("{reason}; manual recovery is required") + } + _ => status.to_string(), + } +} + fn cmd_query( search: String, path: Option, @@ -5404,6 +5475,9 @@ fn has_lifecycle_namespace(project: &Path) -> bool { Store::extraction_status(&paths) != codegraph_store::ExtractionStatus::Missing } +/// Resolve a readable project and report lifecycle-specific recovery without +/// authorizing mutation. Only an all-present-slot OwnerMismatch names explicit +/// init; mixed or other corruption continues to require manual recovery. fn resolve_required_project(path: Option) -> Result { let start = absolute_path(path.unwrap_or_else(|| PathBuf::from("."))); index_paths(&start)?; @@ -5448,11 +5522,16 @@ fn resolve_required_project(path: Option) -> Result { "CodeGraph index in {} was built by a newer CodeGraph version (extraction version {built}); upgrade CodeGraph before reading it", project.display() ), - ExtractionStatus::Corrupt { reason } => bail!( - "CodeGraph index state in {} is corrupt: {reason}; run `codegraph status {}` for details; manual recovery is required", - project.display(), - project.display() - ), + ExtractionStatus::Corrupt { reason } => { + if owner_mismatch_only_reason(&paths).is_some() { + bail!("{}", owner_mismatch_recovery_error(&project, &reason)); + } + bail!( + "CodeGraph index state in {} is corrupt: {reason}; run `codegraph status {}` for details; manual recovery is required", + project.display(), + project.display() + ) + } } } diff --git a/crates/codegraph-cli/tests/batch_m_uninit.rs b/crates/codegraph-cli/tests/batch_m_uninit.rs index 6d8f81ac..c1e3b2b3 100644 --- a/crates/codegraph-cli/tests/batch_m_uninit.rs +++ b/crates/codegraph-cli/tests/batch_m_uninit.rs @@ -13,8 +13,8 @@ use std::time::{Duration, Instant}; use codegraph_core::IndexPaths; use codegraph_store::{ - CURRENT_EXTRACTION_VERSION, CURRENT_STORAGE_PROTOCOL, ExtractionStatus, IndexLease, StatePhase, - Store, checksum_hex, classify, publish_index_state, + CURRENT_EXTRACTION_VERSION, CURRENT_STORAGE_PROTOCOL, CorruptReason, ExtractionStatus, + IndexLease, SlotOutcome, StatePhase, Store, checksum_hex, classify, publish_index_state, }; fn bin() -> PathBuf { @@ -547,6 +547,63 @@ fn stage_lifecycle_state(paths: &IndexPaths, status: &str) { drop(lease); } +fn slot_bytes(paths: &IndexPaths) -> [Option>; 2] { + paths.state_slots().map(|slot| match std::fs::read(&slot) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => panic!("read state slot {}: {error}", slot.display()), + }) +} + +fn stage_owner_mismatch(dir: &TestDir, label: &str) -> (PathBuf, IndexPaths) { + let source = dir.path().join(format!("{label}-source")); + copy_tree(&mini_fixture(), &source); + let source_arg = source.to_str().expect("UTF-8 source project path"); + let init = run_in(dir.path(), &["init", source_arg]); + assert!( + init.ok, + "setup: source init must succeed: stdout={}, stderr={}", + init.stdout, init.stderr + ); + + let moved = dir.path().join(format!("{label}-moved")); + copy_tree(&source, &moved); + let source_paths = IndexPaths::resolve(&source, None).expect("resolve source index paths"); + let moved_paths = IndexPaths::resolve(&moved, None).expect("resolve moved index paths"); + assert_ne!( + source_paths.project_identity(), + moved_paths.project_identity(), + "copying a project directory must produce a distinct filesystem identity" + ); + assert!( + matches!( + Store::extraction_status(&moved_paths), + ExtractionStatus::Corrupt { + reason: CorruptReason::OwnerMismatch { .. } + } + ), + "a copied initialized project must classify as OwnerMismatch" + ); + (moved, moved_paths) +} + +fn owner_mismatch_reason(paths: &IndexPaths) -> CorruptReason { + match Store::extraction_status(paths) { + ExtractionStatus::Corrupt { + reason: reason @ CorruptReason::OwnerMismatch { .. }, + } => reason, + other => panic!("expected OwnerMismatch, got {other:?}"), + } +} + +fn owner_mismatch_cli_error(project: &Path, reason: &CorruptReason) -> String { + format!( + "CodeGraph index state in {} is corrupt: {reason}; the index belongs to a different filesystem location because the project was moved or copied; run `codegraph init {}` to replace it", + project.display(), + project.display() + ) +} + fn assert_query_error(dir: &TestDir, project: &Path, expected: &str) { let project_arg = project.to_str().expect("UTF-8 test project path"); let run = run_in( @@ -561,6 +618,220 @@ fn assert_query_error(dir: &TestDir, project: &Path, expected: &str) { assert_eq!(final_error_body(&run.stderr), expected); } +#[test] +fn owner_mismatch_read_and_status_diagnostics_name_explicit_init_recovery() { + let dir = TestDir::new("owner-mismatch-diagnostics"); + let (project, paths) = stage_owner_mismatch(&dir, "diagnostics"); + let reason = owner_mismatch_reason(&paths); + let expected_error = owner_mismatch_cli_error(&project, &reason); + assert_query_error(&dir, &project, &expected_error); + + let project_arg = project.to_str().expect("UTF-8 moved project path"); + let human = run_in(dir.path(), &["status", project_arg]); + assert!( + human.ok, + "human status must describe OwnerMismatch: stdout={}, stderr={}", + human.stdout, human.stderr + ); + assert_eq!(normalize(&human.stderr), ""); + assert_eq!( + human.stdout, + format!( + "\nCodeGraph Status\n\nProject: {}\nDB Path: {}\nState: corrupt: {reason}\nDaemon: stopped\nIndex belongs to a different filesystem location because the project was moved or copied.\nRecovery: run `codegraph init {}` to replace it.\n", + project.display(), + paths.current_db().display(), + project.display() + ) + ); + + let json_run = run_in(dir.path(), &["status", "--json", project_arg]); + assert!( + json_run.ok, + "JSON status must describe OwnerMismatch: stdout={}, stderr={}", + json_run.stdout, json_run.stderr + ); + assert_eq!(normalize(&json_run.stderr), ""); + let value: serde_json::Value = + serde_json::from_str(json_run.stdout.trim()).expect("status emits JSON"); + assert_eq!(value["initialized"], false); + assert_eq!(value["extractionStatus"], "corrupt"); + assert_eq!( + value["extractionStatusDetail"], + format!( + "{reason}; the index belongs to a different filesystem location because the project was moved or copied; run `codegraph init {}` to replace it", + project.display() + ) + ); + assert_eq!( + value["recoveryCommand"], + format!("codegraph init {}", project.display()) + ); +} + +#[test] +fn explicit_init_recovers_an_owner_mismatched_namespace() { + let dir = TestDir::new("owner-mismatch-init"); + let (project, paths) = stage_owner_mismatch(&dir, "init"); + + let init = run_in( + dir.path(), + &["init", project.to_str().expect("UTF-8 moved project path")], + ); + assert!( + init.ok, + "explicit init must recover OwnerMismatch: stdout={}, stderr={}", + init.stdout, init.stderr + ); + assert_eq!(Store::extraction_status(&paths), ExtractionStatus::Current); + let store = Store::open_for_read(&paths, deadline(), || false) + .expect("recovered OwnerMismatch namespace must be readable"); + assert!( + store.counts().expect("read recovered counts").node_count > 0, + "recovered namespace must contain the rebuilt graph" + ); +} + +#[test] +fn mixed_owner_mismatch_and_checksum_damage_refuses_init_without_changing_slots() { + let dir = TestDir::new("owner-mismatch-mixed"); + let (project, paths) = stage_owner_mismatch(&dir, "mixed"); + let [slot0, slot1] = paths.state_slots(); + let mut second: serde_json::Value = + serde_json::from_slice(&std::fs::read(&slot1).expect("read copied second state slot")) + .expect("parse copied second state slot"); + second["checksum"] = serde_json::Value::String("0".repeat(64)); + std::fs::write( + &slot1, + serde_json::to_vec(&second).expect("serialize checksum-damaged slot"), + ) + .expect("write checksum-damaged slot"); + + let classification = classify(&paths); + assert!(matches!( + classification.slot(0), + SlotOutcome::Invalid(CorruptReason::OwnerMismatch { .. }) + )); + assert!(matches!( + classification.slot(1), + SlotOutcome::Invalid(CorruptReason::ChecksumMismatch { .. }) + )); + let reason = match classification.status() { + ExtractionStatus::Corrupt { reason } => reason.clone(), + other => panic!("mixed slot damage must classify Corrupt, got {other:?}"), + }; + let before = slot_bytes(&paths); + let project_arg = project.to_str().expect("UTF-8 moved project path"); + + let status = run_in(dir.path(), &["status", project_arg]); + assert!(status.ok, "status must report mixed corruption"); + assert_eq!(normalize(&status.stderr), ""); + assert_eq!( + status.stdout, + format!( + "\nCodeGraph Status\n\nProject: {}\nDB Path: {}\nState: corrupt: {reason}\nDaemon: stopped\nManual recovery is required.\n", + project.display(), + paths.current_db().display() + ), + "a mixed namespace must not recommend init merely because slot 0 supplies the aggregate OwnerMismatch reason" + ); + let json_status = run_in(dir.path(), &["status", "--json", project_arg]); + assert!(json_status.ok, "JSON status must report mixed corruption"); + assert_eq!(normalize(&json_status.stderr), ""); + let value: serde_json::Value = + serde_json::from_str(json_status.stdout.trim()).expect("status emits JSON"); + assert_eq!( + value["extractionStatusDetail"], + format!("{reason}; manual recovery is required") + ); + assert!(value.get("recoveryCommand").is_none()); + + let init = run_in(dir.path(), &["init", project_arg]); + assert!(!init.ok, "mixed corruption must refuse explicit init"); + assert_eq!( + final_error_body(&init.stderr), + format!("state-gated Store open rejected index state corrupt: {reason}") + ); + assert_eq!( + slot_bytes(&paths), + before, + "a refused mixed-damage init must preserve both state slots byte-for-byte" + ); + assert!(slot0.is_file()); +} + +#[test] +fn another_corrupt_reason_keeps_manual_recovery_and_refuses_init() { + let dir = TestDir::new("other-corrupt"); + let project = dir.path().join("project"); + std::fs::create_dir_all(&project).expect("create corrupt project"); + let paths = IndexPaths::resolve(&project, None).expect("resolve corrupt index paths"); + stage_lifecycle_state(&paths, "corrupt"); + let reason = match Store::extraction_status(&paths) { + ExtractionStatus::Corrupt { reason } => reason, + other => panic!("expected staged Corrupt state, got {other:?}"), + }; + assert!(matches!(reason, CorruptReason::EqualSequence { .. })); + let before = slot_bytes(&paths); + let project_arg = project.to_str().expect("UTF-8 corrupt project path"); + + let human = run_in(dir.path(), &["status", project_arg]); + assert!(human.ok, "status must report corruption: {}", human.stderr); + assert_eq!(normalize(&human.stderr), ""); + assert_eq!( + human.stdout, + format!( + "\nCodeGraph Status\n\nProject: {}\nDB Path: {}\nState: corrupt: {reason}\nDaemon: stopped\nManual recovery is required.\n", + project.display(), + paths.current_db().display() + ) + ); + let json_status = run_in(dir.path(), &["status", "--json", project_arg]); + assert!(json_status.ok, "JSON status must report corruption"); + assert_eq!(normalize(&json_status.stderr), ""); + let value: serde_json::Value = + serde_json::from_str(json_status.stdout.trim()).expect("status emits JSON"); + assert_eq!( + value["extractionStatusDetail"], + format!("{reason}; manual recovery is required") + ); + assert!(value.get("recoveryCommand").is_none()); + + let init = run_in(dir.path(), &["init", project_arg]); + assert!(!init.ok, "non-OwnerMismatch corruption must refuse init"); + assert_eq!( + final_error_body(&init.stderr), + format!("state-gated Store open rejected index state corrupt: {reason}") + ); + assert_eq!( + slot_bytes(&paths), + before, + "a refused corrupt init must preserve both state slots byte-for-byte" + ); +} + +#[test] +fn sync_never_deletes_owner_mismatched_state_slots() { + let dir = TestDir::new("owner-mismatch-sync"); + let (project, paths) = stage_owner_mismatch(&dir, "sync"); + let reason = owner_mismatch_reason(&paths); + let before = slot_bytes(&paths); + + let sync = run_in( + dir.path(), + &["sync", project.to_str().expect("UTF-8 moved project path")], + ); + assert!(!sync.ok, "sync must fail closed on OwnerMismatch"); + assert_eq!( + final_error_body(&sync.stderr), + owner_mismatch_cli_error(&project, &reason) + ); + assert_eq!( + slot_bytes(&paths), + before, + "sync must preserve OwnerMismatch state slots byte-for-byte" + ); +} + #[test] fn building_state_recovery_reports_exact_per_state_query_diagnostics() { for status in ["building", "uninitialized", "outdated", "future", "corrupt"] { diff --git a/crates/codegraph-store/src/connection.rs b/crates/codegraph-store/src/connection.rs index 58a48955..4d47cc52 100644 --- a/crates/codegraph-store/src/connection.rs +++ b/crates/codegraph-store/src/connection.rs @@ -431,6 +431,9 @@ impl Store { /// fully corroborated `Current` database whose tombstone remains after the /// prior finalizer published Current but failed to remove that tombstone. /// The namespace is still not readable until the explicit retry completes. + /// A copied project's all-`OwnerMismatch` slots are normalized to `Missing` + /// by `crate::rebuild` under the same lease before this gate; this function + /// itself never accepts a `Corrupt` classification. pub(crate) fn open_for_explicit_init_rebuild( paths: &IndexPaths, lease: IndexLease, @@ -465,6 +468,10 @@ impl Store { lease.validate_exclusive(paths)?; let status = Self::extraction_status(paths); + // Every Corrupt classification that reaches this gate is refused. The + // explicit-init OwnerMismatch-only normalization, when applicable, has + // already removed every mismatched present slot under this same lease, + // so it reaches this gate as Missing rather than weakening this rule. if matches!( status, ExtractionStatus::Future { .. } | ExtractionStatus::Corrupt { .. } diff --git a/crates/codegraph-store/src/index_state.rs b/crates/codegraph-store/src/index_state.rs index 66014ee7..c48647d8 100644 --- a/crates/codegraph-store/src/index_state.rs +++ b/crates/codegraph-store/src/index_state.rs @@ -349,6 +349,9 @@ pub enum CorruptReason { supported: u64, }, /// `projectIdentity` does not match the owner identity of the namespace. + /// This is the deterministic moved/copied-project signal: explicit init may + /// replace the namespace only when every present slot has this reason; + /// mixed slot damage remains unrecoverable automatically. OwnerMismatch { /// Slot index (0 or 1). slot: u8, diff --git a/crates/codegraph-store/src/rebuild.rs b/crates/codegraph-store/src/rebuild.rs index 13b4d8ab..74bee657 100644 --- a/crates/codegraph-store/src/rebuild.rs +++ b/crates/codegraph-store/src/rebuild.rs @@ -3,11 +3,13 @@ //! Frozen plan `upstream-v1.5-portable-fixes.md` lines 548-556: under ONE //! retained exclusive [`IndexLease`], a destructive rebuild //! -//! 1. classifies the namespace and takes its write authorization, -//! 2. publishes `phase=building` BEFORE deleting or mutating the database, -//! 3. removes only the v2 `codegraph.db`, `-wal`, and `-shm`, -//! 4. rebuilds into a fresh state-gated writer database, and -//! 5. finalizes: restore default pragmas -> final checkpoint + compaction -> +//! 1. for explicit init only, normalizes an all-`OwnerMismatch` copied namespace +//! to `Missing` by removing those unusable slots under the retained lease, +//! 2. classifies the namespace and takes its write authorization, +//! 3. publishes `phase=building` BEFORE deleting or mutating the database, +//! 4. removes only the v2 `codegraph.db`, `-wal`, and `-shm`, +//! 5. rebuilds into a fresh state-gated writer database, and +//! 6. finalizes: restore default pragmas -> final checkpoint + compaction -> //! stamp extraction version -> checkpoint that stamp into the main database -> //! close the final SQLite connection. //! @@ -30,8 +32,8 @@ use crate::connection::{ first_existing_database_artifact, }; use crate::{ - IndexLease, IndexLeaseError, IndexLeaseValidationError, StatePhase, StatePublishError, - publish_index_state, + CorruptReason, IndexLease, IndexLeaseError, IndexLeaseValidationError, SlotOutcome, StatePhase, + StatePublishError, classify, publish_index_state, }; /// Which lifecycle command is performing the destructive rebuild. @@ -143,6 +145,14 @@ pub enum RebuildError { /// Operating-system error. source: io::Error, }, + /// An identity-mismatched state slot could not be removed under the lease. + #[error("cannot remove identity-mismatched index state slot {path}: {source}")] + RemoveStateSlot { + /// Exact fixed-slot path. + path: PathBuf, + /// Operating-system error. + source: io::Error, + }, /// An interrupted-uninit namespace was reached by an ordinary reindex. #[error( "index namespace {path} was left uninitialized; only an explicit `init` may rebuild it" @@ -212,8 +222,9 @@ pub struct ActiveFullRebuild { store: Option, } -/// Acquire the single outer exclusive lease, classify under it, publish -/// `phase=building`, and remove the previous database files. +/// Acquire the single outer exclusive lease, optionally normalize an explicit +/// init's all-`OwnerMismatch` slots to `Missing`, classify under that same lease, +/// publish `phase=building`, and remove the previous database files. pub fn begin_full_rebuild( paths: &IndexPaths, kind: RebuildKind, @@ -232,9 +243,12 @@ fn begin_full_rebuild_with( ) -> Result { let lease = acquire_outer_exclusive(paths, deadline, cancelled)?; checkpoint(fault, RebuildCheckpoint::BeforeWriteAuthorization)?; + if kind == RebuildKind::ExplicitInit { + remove_owner_mismatched_state_slots(paths, &lease)?; + } // Classification happens through the state gate under the already-held - // exclusive capability; a Future/Corrupt namespace is refused before any - // byte changes. + // exclusive capability. Future and every Corrupt shape except the explicit + // init normalization above are refused before any byte changes. let authorized = if kind == RebuildKind::ExplicitInit { Store::open_for_explicit_init_rebuild(paths, lease.clone())? } else { @@ -260,6 +274,66 @@ fn begin_full_rebuild_with( begin_from_authorization(paths, lease, kind, authorization, fault) } +/// Normalize only the copied/moved-project shape: every PRESENT fixed slot must +/// independently be an [`CorruptReason::OwnerMismatch`]. A mixed namespace is +/// genuine damage and remains untouched for the ordinary state gate to refuse. +fn remove_owner_mismatched_state_slots( + paths: &IndexPaths, + lease: &IndexLease, +) -> Result<(), RebuildError> { + let classification = classify(paths); + if !matches!( + classification.status(), + crate::ExtractionStatus::Corrupt { + reason: CorruptReason::OwnerMismatch { .. } + } + ) { + return Ok(()); + } + + let mut mismatched_slots = Vec::new(); + for index in 0..2 { + match classification.slot(index) { + SlotOutcome::Absent => {} + SlotOutcome::Invalid(CorruptReason::OwnerMismatch { path, .. }) => { + mismatched_slots.push(path.clone()); + } + SlotOutcome::Valid(_) | SlotOutcome::FutureProtocol(_) | SlotOutcome::Invalid(_) => { + return Ok(()); + } + } + } + if mismatched_slots.is_empty() { + return Ok(()); + } + + lease.validate_exclusive(paths)?; + for path in &mismatched_slots { + lease.validate_exclusive(paths)?; + match std::fs::remove_file(path) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(RebuildError::RemoveStateSlot { + path: path.clone(), + source, + }); + } + } + } + let removed = mismatched_slots + .iter() + .map(|path| path.display().to_string()) + .collect::>() + .join(", "); + tracing::info!( + slots = %removed, + reason = "project identity mismatch after move or copy", + "replaced stale foreign index state slots" + ); + Ok(()) +} + /// Escalate an ALREADY-AUTHORIZED namespace to a destructive full rebuild using /// the exclusive lease the authorization still retains. /// @@ -307,7 +381,9 @@ fn resume_full_rebuild_with( /// Shared destructive prologue: publish `phase=building` BEFORE deleting any /// database byte, then remove only the database files — all under the one -/// already-held exclusive lease carried by `authorization`. +/// already-held exclusive lease carried by `authorization`. Any explicit-init +/// OwnerMismatch slot normalization is already complete before this authorized +/// prologue and did not touch a database byte. fn begin_from_authorization( paths: &IndexPaths, lease: IndexLease,