Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 67 additions & 7 deletions crates/codegraph-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1384,6 +1384,8 @@ fn recover_dead_owner_sidecars(paths: &codegraph_core::IndexPaths, project_root:
/// The returned `Store` OWNS that same lease, so retaining it across pid/socket
/// publication requires no second acquisition: there is no nested lock and no
/// window between validation and publication for another writer to reclassify.
/// A refusal therefore proves only that this daemon published no pid or socket;
/// the detached parent may already have opened the project-local log redirect.
fn authorize_daemon_startup(project_root: &Path) -> Result<codegraph_daemon::StartupAuthorization> {
let paths = index_paths(project_root)?;
recover_dead_owner_sidecars(&paths, project_root);
Expand All @@ -1404,8 +1406,11 @@ fn authorize_daemon_startup(project_root: &Path) -> Result<codegraph_daemon::Sta
};
bail!(
"refusing to start a daemon for {}: {error}; index state is {status} and its \
uninitialized tombstone is {tombstone}. No daemon pid, socket, or log was \
published. Run `codegraph init` to rebuild.",
uninitialized tombstone is {tombstone}. This daemon did not publish a pid or \
socket; a detached parent may already have opened {}. Run `codegraph status \
\"{}\"` for state-specific recovery guidance.",
project_root.display(),
paths.daemon_log().display(),
project_root.display()
)
}
Expand Down Expand Up @@ -1660,8 +1665,13 @@ fn cmd_status(path: Option<PathBuf>, json_output: bool) -> Result<()> {
.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 lockless_missing =
extraction_status == ExtractionStatus::Missing && is_lockless_missing_root(&resolved)?;
let extraction_status_detail = if lockless_missing {
lockless_missing_detail(&project, &resolved)
} else {
status_extraction_detail(&extraction_status, owner_mismatch_recoverable, &project)
};
let store = status_open.into_store();
if store.is_none() {
if json_output {
Expand All @@ -1687,6 +1697,9 @@ fn cmd_status(path: Option<PathBuf>, json_output: bool) -> Result<()> {
json!(format!("codegraph index --force {}", project.display()));
} else if owner_mismatch_recoverable {
status["recoveryCommand"] = json!(format!("codegraph init {}", project.display()));
} else if lockless_missing {
status["recoveryCommand"] =
json!(format!("codegraph init \"{}\"", project.display()));
}
print_json(&status)?;
} else {
Expand Down Expand Up @@ -1725,6 +1738,9 @@ fn cmd_status(path: Option<PathBuf>, json_output: bool) -> Result<()> {
ExtractionStatus::Corrupt { .. } => {
println!("Manual recovery is required.");
}
ExtractionStatus::Missing if lockless_missing => {
println!("{extraction_status_detail}");
}
_ => {
println!("Not initialized");
println!("Run \"codegraph init\" to initialize");
Expand Down Expand Up @@ -5447,7 +5463,10 @@ fn explicit_init_observes_readable_current(project: &Path) -> Result<bool> {
drop(store);
Ok(true)
}
Err(codegraph_store::StoreError::CurrentTombstoned { .. }) => Ok(false),
Err(
codegraph_store::StoreError::CurrentTombstoned { .. }
| codegraph_store::StoreError::StateWithoutPermanentLock { .. },
) => Ok(false),
Err(error) => Err(error.into()),
}
}
Expand Down Expand Up @@ -5476,8 +5495,9 @@ fn has_lifecycle_namespace(project: &Path) -> bool {
}

/// 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.
/// authorizing mutation. Only an all-present-slot OwnerMismatch or a Missing
/// existing root with no permanent lock names explicit init; mixed or other
/// corruption continues to require manual recovery.
fn resolve_required_project(path: Option<PathBuf>) -> Result<PathBuf> {
let start = absolute_path(path.unwrap_or_else(|| PathBuf::from(".")));
index_paths(&start)?;
Expand Down Expand Up @@ -5507,6 +5527,9 @@ fn resolve_required_project(path: Option<PathBuf>) -> Result<PathBuf> {
if first_existing_database_artifact(&paths)?.is_some() {
bail!("{}", missing_state_with_database_detail(&project));
}
if is_lockless_missing_root(&paths)? {
bail!("{}", lockless_missing_detail(&project, &paths));
}
bail!(
"CodeGraph not initialized in {}; run `codegraph init {}` to create or replace the index",
project.display(),
Expand Down Expand Up @@ -5562,6 +5585,43 @@ fn missing_state_with_database_detail(project: &Path) -> String {
)
}

/// Detect the recoverable filesystem shape after the caller has classified the
/// namespace Missing. Both path probes are non-following and inspection errors
/// propagate, so aliases and inaccessible entries cannot masquerade as recovery.
fn is_lockless_missing_root(paths: &codegraph_core::IndexPaths) -> Result<bool> {
let root = paths.current_root();
let root_metadata = match fs::symlink_metadata(root) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => {
return Err(error).with_context(|| format!("failed to inspect {}", root.display()));
}
};
if !root_metadata.file_type().is_dir() {
return Ok(false);
}

let lock = paths.permanent_lock();
match fs::symlink_metadata(&lock) {
Ok(_) => Ok(false),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(error) => Err(error).with_context(|| format!("failed to inspect {}", lock.display())),
}
}

fn lockless_missing_detail(project: &Path, paths: &codegraph_core::IndexPaths) -> String {
let lock = paths.permanent_lock();
let root = lock
.parent()
.expect("the permanent lock always belongs to the current index root");
format!(
"CodeGraph index directory exists at {}, but its permanent lock is missing at {}; a failed background daemon start can leave this stale namespace. Run `codegraph init \"{}\"` to create the lock and rebuild the index.",
root.display(),
lock.display(),
project.display()
)
}

fn resolve_required_rebuild_project(path: Option<PathBuf>) -> Result<PathBuf> {
let start = absolute_path(path.unwrap_or_else(|| PathBuf::from(".")));
index_paths(&start)?;
Expand Down
88 changes: 88 additions & 0 deletions crates/codegraph-cli/tests/batch_m_finalizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,94 @@ fn slot_bytes(paths: &IndexPaths) -> [Option<Vec<u8>>; 2] {
})
}

fn lock_not_found_error(paths: &IndexPaths) -> String {
format!(
"existing index namespace has no permanent lock file at {}; a failed background daemon start can leave this stale shape. Run `codegraph status` from the project root to classify it; only `State: missing` is safe to recover with `codegraph init`.",
paths.permanent_lock().display()
)
}

fn wait_for_daemon_error(log: &Path) -> String {
let until = Instant::now() + Duration::from_secs(10);
while Instant::now() < until {
if let Ok(contents) = std::fs::read_to_string(log) {
let normalized = normalize(&contents);
if contents.ends_with('\n')
&& normalized.lines().any(|line| {
line.strip_prefix("Error: ")
.is_some_and(|body| !body.is_empty())
})
{
return final_error_body(&contents);
}
}
std::thread::yield_now();
}
panic!(
"detached daemon did not publish its final error to {}",
log.display()
);
}

#[test]
fn lockless_root_recovery_building_without_lock_refuses_init_unchanged() {
let dir = TestDir::new("lockless-building-init");
let project = dir.path().join("mini");
copy_tree(&mini_fixture(), &project);
let paths = IndexPaths::resolve(&project, None).expect("resolve default index paths");
stage_interrupted_building(&paths, false);
let before = slot_bytes(&paths);
std::fs::remove_file(paths.permanent_lock()).expect("remove permanent lock");

let init = run_in(
dir.path(),
&["init", project.to_str().expect("UTF-8 project path")],
);
assert!(!init.ok, "lockless Building must refuse init");
assert_eq!(normalize(&init.stdout), "");
assert_eq!(final_error_body(&init.stderr), lock_not_found_error(&paths));
assert_eq!(slot_bytes(&paths), before);
assert!(!paths.permanent_lock().exists());
assert!(!paths.current_db().exists());
assert_eq!(
Store::extraction_status(&paths),
ExtractionStatus::Building {
built: codegraph_store::CURRENT_EXTRACTION_VERSION,
}
);
}

#[test]
fn lockless_root_recovery_daemon_refusal_reports_only_pid_socket_guarantee() {
let dir = TestDir::new("lockless-daemon-refusal");
let project = dir.path().join("mini");
copy_tree(&mini_fixture(), &project);
let paths = IndexPaths::resolve(&project, None).expect("resolve default index paths");
stage_interrupted_building(&paths, false);
let before = slot_bytes(&paths);
let status = Store::extraction_status(&paths);
let store_error = Store::open_for_read(&paths, deadline(), || false)
.expect_err("Building must refuse a read open")
.to_string();

codegraph_daemon::spawn_detached_daemon(&bin(), &project, false)
.expect("spawn detached daemon against Building namespace");
let body = wait_for_daemon_error(&paths.daemon_log());
assert_eq!(
body,
format!(
"running as detached MCP daemon: refusing to start a daemon for {}: {store_error}; index state is {status} and its uninitialized tombstone is absent. This daemon did not publish a pid or socket; a detached parent may already have opened {}. Run `codegraph status \"{}\"` for state-specific recovery guidance.",
project.display(),
paths.daemon_log().display(),
project.display()
)
);
assert!(!paths.daemon_pid().exists());
assert!(!paths.daemon_socket().exists());
assert_eq!(slot_bytes(&paths), before);
assert_eq!(Store::extraction_status(&paths), status);
}

#[test]
fn building_state_recovery_status_guides_only_stale_building() {
let dir = TestDir::new("status-stale-building");
Expand Down
Loading
Loading