From fbb59ad363f3c428560afe26177ab72480cc3de2 Mon Sep 17 00:00:00 2001 From: Bradley Hilton Date: Thu, 29 Oct 2026 06:21:05 +0100 Subject: [PATCH] feat: report repository and redb diagnostics --- README.md | 2 +- .../src/commands/diagnostics/collect.rs | 2 + .../src/commands/diagnostics/metrics.rs | 272 ++++++++++++++++++ atomic-cli/src/commands/diagnostics/mod.rs | 10 +- atomic-cli/src/commands/diagnostics/render.rs | 89 ++++++ .../tests/it/diagnostics_integration_test.rs | 199 +++++++++++++ atomic-core/src/pristine/txn/pristine.rs | 23 +- atomic-repository/src/repository/mod.rs | 38 ++- .../tests/it/legacy_database_merge_test.rs | 18 ++ 9 files changed, 641 insertions(+), 12 deletions(-) create mode 100644 atomic-cli/src/commands/diagnostics/metrics.rs diff --git a/README.md b/README.md index 621e2792..0a4d2f76 100644 --- a/README.md +++ b/README.md @@ -592,7 +592,7 @@ Every change stores two parallel representations: | `atomic agent status` | Show sessions, hook liveness, and failures (`--json` for tooling) | | `atomic agent explain ` | Generate AI reasoning summary for a session | | `atomic agent attest` | List and inspect attestations | -| `atomic diagnostics` | Read-only support report: version, integrations, skills, enabled agents, Git shim (`--json`) | +| `atomic diagnostics` | Read-only support report: version, integrations, skills, hooks, Git shim, repository counts and selected redb table statistics (`--json`) | Hook health is computed from session-scoped logs, so concurrent agents retain their own outcomes and a child's success cannot hide a parent's failure. See diff --git a/atomic-cli/src/commands/diagnostics/collect.rs b/atomic-cli/src/commands/diagnostics/collect.rs index 397c3573..955e4a9f 100644 --- a/atomic-cli/src/commands/diagnostics/collect.rs +++ b/atomic-cli/src/commands/diagnostics/collect.rs @@ -39,6 +39,7 @@ pub(crate) struct Report { pub generated_at: String, pub atomic: AtomicInfo, pub workspace: Workspace, + pub repository: super::metrics::RepositoryMetrics, pub integrations: Integrations, pub skills: Skills, /// Every agent Atomic has an adapter for, and whether its hooks are active. @@ -770,6 +771,7 @@ pub(crate) fn collect_from( reason: reason.to_string(), }, }, + repository: super::metrics::collect(&sources.workspace), integrations: Integrations { root: sources .integrations_root diff --git a/atomic-cli/src/commands/diagnostics/metrics.rs b/atomic-cli/src/commands/diagnostics/metrics.rs new file mode 100644 index 00000000..0a960bda --- /dev/null +++ b/atomic-cli/src/commands/diagnostics/metrics.rs @@ -0,0 +1,272 @@ +//! Read-only repository and redb observations for diagnostics. + +use std::path::{Path, PathBuf}; + +use atomic_core::pristine::tables::{ + node_type, CHANGE_META, GRAPH, NODE_TYPES, VAULT_ENTRIES, VAULT_MANIFEST, VIEWS, +}; +use atomic_core::pristine::vault::VaultManifest; +use redb::{ReadableDatabase, ReadableTable, ReadableTableMetadata}; +use serde::Serialize; + +use super::collect::SourceError; + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum Observation { + Available { value: T }, + Unavailable { reason: &'static str }, +} + +impl Observation { + fn available(value: T) -> Self { + Self::Available { value } + } + + fn unavailable(reason: &'static str) -> Self { + Self::Unavailable { reason } + } +} + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub(crate) enum RepositoryMetrics { + NotApplicable { + reason: &'static str, + }, + Unavailable { + reason: &'static str, + database_bytes: Option, + }, + Available { + database_bytes: Observation, + registered_changes: Observation, + views: Observation, + intents: Observation, + current_view: Observation, + tables: Vec, + last_compacted: Observation, + }, +} + +#[derive(Debug, Default, Serialize)] +pub(crate) struct IntentCounts { + pub total: u64, + pub backlog: u64, + pub planned: u64, + pub in_progress: u64, + pub needs_review: u64, + pub done: u64, + pub icebox: u64, + pub other: u64, +} + +#[derive(Debug, Serialize)] +pub(crate) struct CurrentViewCounts { + pub own: u64, + pub inherited: u64, + pub membership: u64, +} + +#[derive(Debug, Serialize)] +pub(crate) struct TableMetric { + pub name: &'static str, + #[serde(flatten)] + pub statistics: Observation, +} + +#[derive(Debug, Serialize)] +pub(crate) struct TableStatistics { + pub entries: u64, + pub stored_bytes: u64, + pub metadata_bytes: u64, + pub fragmented_bytes: u64, + pub tree_height: u32, + pub leaf_pages: u64, + pub branch_pages: u64, +} + +fn statistics(table: &impl ReadableTableMetadata) -> Result { + let stats = table.stats().map_err(|_| ())?; + Ok(TableStatistics { + entries: table.len().map_err(|_| ())?, + stored_bytes: stats.stored_bytes(), + metadata_bytes: stats.metadata_bytes(), + fragmented_bytes: stats.fragmented_bytes(), + tree_height: stats.tree_height(), + leaf_pages: stats.leaf_pages(), + branch_pages: stats.branch_pages(), + }) +} + +fn table_metric(name: &'static str, value: Result) -> TableMetric { + TableMetric { + name, + statistics: match value { + Ok(value) => Observation::available(value), + Err(()) => Observation::unavailable("table statistics unavailable"), + }, + } +} + +fn current_view(root: &Path) -> Observation { + let result = (|| { + let repo = atomic_repository::Repository::open_readonly_without_migration(root).ok()?; + let id = repo.working_copy_id()?; + let name = repo.desired_view_name(id).ok()?; + let info = repo.get_view_info(&name).ok()?; + Some(CurrentViewCounts { + own: info.own_change_count, + inherited: info.inherited_change_count, + membership: info + .own_change_count + .checked_add(info.inherited_change_count)?, + }) + })(); + match result { + Some(value) => Observation::available(value), + None => Observation::unavailable("current working-copy view cannot be verified"), + } +} + +fn intents(txn: &redb::ReadTransaction) -> Observation { + let result = (|| { + let table = txn.open_table(VAULT_MANIFEST).ok()?; + let value = table.get("manifest").ok()??; + let manifest: VaultManifest = serde_json::from_slice(value.value()).ok()?; + let mut counts = IntentCounts::default(); + for intent in manifest.intents.values() { + counts.total += 1; + match intent.status.as_str() { + "backlog" => counts.backlog += 1, + "planned" => counts.planned += 1, + "in_progress" => counts.in_progress += 1, + "needs-review" => counts.needs_review += 1, + "done" => counts.done += 1, + "icebox" => counts.icebox += 1, + _ => counts.other += 1, + } + } + Some(counts) + })(); + match result { + Some(value) => Observation::available(value), + None => Observation::unavailable("vault manifest unavailable or unreadable"), + } +} + +pub(crate) fn collect(workspace: &Result, SourceError>) -> RepositoryMetrics { + let root = match workspace { + Ok(Some(root)) => root, + Ok(None) => { + return RepositoryMetrics::NotApplicable { + reason: "not inside an Atomic workspace", + } + } + Err(_) => { + return RepositoryMetrics::Unavailable { + reason: "workspace cannot be determined", + database_bytes: None, + } + } + }; + let dot = match atomic_repository::Repository::canonical_dot_dir(root) { + Ok(dot) => dot, + Err(_) => { + return RepositoryMetrics::Unavailable { + reason: "repository database location unavailable", + database_bytes: None, + } + } + }; + let path = dot.join(atomic_repository::DATABASE_FILE); + let size = std::fs::metadata(&path).ok().map(|m| m.len()); + // A legacy layout (including an interrupted merge) cannot be interpreted + // as the authoritative current database without the migration protocol. + match std::fs::metadata(dot.join(atomic_repository::LEGACY_PRISTINE_FILE)) { + Ok(_) => { + return RepositoryMetrics::Unavailable { + reason: "legacy repository layout requires migration", + database_bytes: size, + }; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => { + return RepositoryMetrics::Unavailable { + reason: "repository layout cannot be verified", + database_bytes: size, + }; + } + } + let database = match redb::ReadOnlyDatabase::open(&path) { + Ok(database) => database, + Err(_) => { + return RepositoryMetrics::Unavailable { + reason: "repository database cannot be read or is in use", + database_bytes: size, + } + } + }; + let txn = match database.begin_read() { + Ok(txn) => txn, + Err(_) => { + return RepositoryMetrics::Unavailable { + reason: "repository database cannot be read", + database_bytes: size, + } + } + }; + let changes = txn + .open_table(CHANGE_META) + .map_err(|_| ()) + .and_then(|table| statistics(&table)); + let views = txn + .open_table(VIEWS) + .map_err(|_| ()) + .and_then(|table| statistics(&table)); + let vault = txn + .open_table(VAULT_ENTRIES) + .map_err(|_| ()) + .and_then(|table| statistics(&table)); + let graph = txn + .open_multimap_table(GRAPH) + .map_err(|_| ()) + .and_then(|table| statistics(&table)); + // Changes used by the graph are registered here; their content is stored + // in change files, not necessarily in redb's optional CHANGE_META table. + let registered_changes = match (|| { + let table = txn.open_table(NODE_TYPES).ok()?; + let mut count = 0u64; + for row in table.iter().ok()? { + let (_, kind) = row.ok()?; + if kind.value() == node_type::CHANGE { + count = count.checked_add(1)?; + } + } + Some(count) + })() { + Some(count) => Observation::available(count), + None => Observation::unavailable("registered change count unavailable"), + }; + let view_count = match &views { + Ok(value) => Observation::available(value.entries), + Err(()) => Observation::unavailable("view count unavailable"), + }; + RepositoryMetrics::Available { + database_bytes: match std::fs::metadata(&path) { + Ok(metadata) => Observation::available(metadata.len()), + Err(_) => Observation::unavailable("database size unavailable"), + }, + registered_changes, + views: view_count, + intents: intents(&txn), + current_view: current_view(root), + tables: vec![ + table_metric("change_meta", changes), + table_metric("views", views), + table_metric("vault_entries", vault), + table_metric("graph", graph), + ], + last_compacted: Observation::unavailable("last compaction is not recorded"), + } +} diff --git a/atomic-cli/src/commands/diagnostics/mod.rs b/atomic-cli/src/commands/diagnostics/mod.rs index 09a3c8f8..22d69608 100644 --- a/atomic-cli/src/commands/diagnostics/mod.rs +++ b/atomic-cli/src/commands/diagnostics/mod.rs @@ -3,7 +3,14 @@ //! Collects the context a support conversation otherwise asks for one //! follow-up at a time: the Atomic version and install source, installed //! agent integration packages and their versions, installed skills, which -//! agents have Atomic hooks enabled, and whether the Git shim is enabled. +//! agents have Atomic hooks enabled, whether the Git shim is enabled, and +//! repository counts and selected read-only redb table statistics. +//! +//! Registered changes are repository-wide graph identities, not a count of +//! content files. Intent counts come from the vault manifest. Current-view +//! counts include direct ancestor membership, without dependency expansion. +//! Table fragmentation describes internal +//! redb page space, not reclaimable database space or compaction history. //! //! Values that cannot be read are reported as unknown with a safe reason. //! No configuration is written, repaired, or fetched; normal command logging @@ -22,6 +29,7 @@ //! ``` mod collect; +mod metrics; mod render; use clap::Args; diff --git a/atomic-cli/src/commands/diagnostics/render.rs b/atomic-cli/src/commands/diagnostics/render.rs index 19507b92..b0fa0d8f 100644 --- a/atomic-cli/src/commands/diagnostics/render.rs +++ b/atomic-cli/src/commands/diagnostics/render.rs @@ -10,6 +10,7 @@ use super::collect::{ AgentState, Enabled, FileCounts, FileState, GitHooks, HookActivity, IntegrationState, Report, ShimStatus, SkillMetadataStatus, SkillsPackage, Workspace, }; +use super::metrics::{Observation, RepositoryMetrics}; /// Width of the label column. const LABEL: usize = 16; @@ -39,6 +40,7 @@ pub(crate) fn render_text(report: &Report) -> String { field(o, "Workspace", &workspace); blank(o); + render_repository(o, &report.repository); render_integrations(o, report); render_skills(o, report); render_agents(o, &report.agents); @@ -52,6 +54,87 @@ pub(crate) fn render_text(report: &Report) -> String { out } +fn render_repository(o: &mut String, repository: &RepositoryMetrics) { + section(o, "Repository and redb"); + match repository { + RepositoryMetrics::NotApplicable { reason } => { + field(o, "Status", &format!("not applicable — {reason}")) + } + RepositoryMetrics::Unavailable { + reason, + database_bytes, + } => { + field(o, "Status", &format!("unknown — {reason}")); + if let Some(bytes) = database_bytes { + field(o, "Database size", &format!("{bytes} bytes")); + } + } + RepositoryMetrics::Available { + database_bytes, + registered_changes, + views, + intents, + current_view, + tables, + last_compacted, + } => { + field( + o, + "Database size", + &display_number(database_bytes, " bytes"), + ); + field( + o, + "Registered changes", + &display_number(registered_changes, ""), + ); + field(o, "Views", &display_number(views, "")); + match current_view { + Observation::Available { value } => field( + o, + "Current view", + &format!( + "{} direct membership ({} own, {} inherited)", + value.membership, value.own, value.inherited + ), + ), + Observation::Unavailable { reason } => { + field(o, "Current view", &format!("unknown — {reason}")) + } + } + match intents { + Observation::Available { value } => field(o, "Intent manifest", &format!("{} total ({} backlog, {} planned, {} in progress, {} needs review, {} done, {} icebox, {} other)", value.total, value.backlog, value.planned, value.in_progress, value.needs_review, value.done, value.icebox, value.other)), + Observation::Unavailable { reason } => field(o, "Intent manifest", &format!("unknown — {reason}")), + } + match last_compacted { + Observation::Available { value } => field(o, "Last compacted", value), + Observation::Unavailable { reason } => { + field(o, "Last compacted", &format!("unknown — {reason}")) + } + } + field(o, "redb tables", ""); + for table in tables { + match &table.statistics { + Observation::Available { value } => line(o, &format!(" {}: {} entries; {} stored, {} metadata, {} fragmented bytes; height {}, {} leaf / {} branch pages", table.name, value.entries, value.stored_bytes, value.metadata_bytes, value.fragmented_bytes, value.tree_height, value.leaf_pages, value.branch_pages)), + Observation::Unavailable { reason } => line(o, &format!(" {}: unknown — {reason}", table.name)), + } + } + line( + o, + " Table fragmentation is not a reclaimable-space estimate.", + ); + } + } + blank(o); +} + +fn display_number(value: &Observation, suffix: &str) -> String { + match value { + Observation::Available { value } => format!("{value}{suffix}"), + Observation::Unavailable { reason } => format!("unknown — {reason}"), + } +} + fn render_integrations(o: &mut String, report: &Report) { section(o, "Agent integrations (installed packages)"); let integrations = &report.integrations; @@ -269,6 +352,9 @@ mod tests { arch: "x86_64", }, workspace: Workspace::NotFound, + repository: RepositoryMetrics::NotApplicable { + reason: "not inside an Atomic workspace", + }, integrations: Integrations { root: Some("~/.atomic/integrations".to_string()), root_overridden: false, @@ -369,6 +455,9 @@ Atomic Platform: linux x86_64 Workspace: none (not inside an Atomic workspace) +Repository and redb + Status: not applicable — not inside an Atomic workspace + Agent integrations (installed packages) Receipts: ~/.atomic/integrations Claude Code (claude-code) diff --git a/atomic-cli/tests/it/diagnostics_integration_test.rs b/atomic-cli/tests/it/diagnostics_integration_test.rs index 0d05084c..2d71f345 100644 --- a/atomic-cli/tests/it/diagnostics_integration_test.rs +++ b/atomic-cli/tests/it/diagnostics_integration_test.rs @@ -225,6 +225,187 @@ fn claude_enabled_requires_an_active_hook_not_unrelated_text() { } } +#[test] +fn repository_metrics_are_explicit_outside_a_workspace() { + let fixture = Fixture::new(); + assert_eq!(fixture.json()["repository"]["status"], "not_applicable"); +} + +#[test] +fn repository_metrics_report_real_repository_without_modifying_database() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let path = fixture.work.path().join(".atomic/atomic.redb"); + let before = std::fs::read(&path).unwrap(); + let report = fixture.json(); + let repo = &report["repository"]; + assert_eq!(repo["status"], "available", "{repo}"); + assert!(repo["views"]["value"].as_u64().unwrap() >= 1, "{repo}"); + assert_eq!(repo["current_view"]["status"], "available", "{repo}"); + let current = &repo["current_view"]["value"]; + assert_eq!( + current["membership"].as_u64().unwrap(), + current["own"].as_u64().unwrap() + current["inherited"].as_u64().unwrap() + ); + assert!( + repo["registered_changes"]["value"].as_u64().unwrap() + >= current["membership"].as_u64().unwrap() + ); + assert_eq!(repo["last_compacted"]["status"], "unavailable"); + assert!(repo["database_bytes"]["value"].as_u64().unwrap() > 0); + assert_eq!(std::fs::read(&path).unwrap(), before); + let text = fixture.ok(&["diagnostics"]); + assert!(text.contains("Repository and redb")); + assert!(text.contains("Last compacted: unknown")); + assert_eq!(std::fs::read(path).unwrap(), before); +} + +#[test] +fn repository_metrics_track_changes_and_do_not_reveal_content() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let before = fixture.json(); + std::fs::write( + fixture.work.path().join("private.txt"), + "SYNTHETIC_PRIVATE_CONTENT\n", + ) + .unwrap(); + fixture.ok(&["add", "private.txt"]); + fixture.ok(&["record", "-m", "private record"]); + let json = fixture.ok(&["diagnostics", "--json"]); + let after: Value = serde_json::from_str(&json).unwrap(); + assert_eq!( + after["repository"]["registered_changes"]["value"] + .as_u64() + .unwrap(), + before["repository"]["registered_changes"]["value"] + .as_u64() + .unwrap() + + 1 + ); + assert_eq!( + after["repository"]["current_view"]["value"]["membership"] + .as_u64() + .unwrap(), + before["repository"]["current_view"]["value"]["membership"] + .as_u64() + .unwrap() + + 1 + ); + assert!(!json.contains("SYNTHETIC_PRIVATE_CONTENT")); + assert!(!json.contains("private.txt")); + assert!(!json.contains("private record")); +} + +#[test] +fn repository_metrics_distinguish_view_membership_from_registered_changes() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main", "--no-vault"]); + let base = fixture.json(); + let parent_count = base["repository"]["current_view"]["value"]["membership"] + .as_u64() + .unwrap(); + let registered = base["repository"]["registered_changes"]["value"] + .as_u64() + .unwrap(); + fixture.ok(&[ + "view", "create", "feature", "--draft", "--parent", "main", "--switch", + ]); + let draft = fixture.json(); + assert_eq!(draft["repository"]["current_view"]["value"]["own"], 0); + assert_eq!( + draft["repository"]["current_view"]["value"]["inherited"], + parent_count + ); + std::fs::write(fixture.work.path().join("draft.txt"), "draft\n").unwrap(); + fixture.ok(&["add", "draft.txt"]); + fixture.ok(&["record", "-m", "draft"]); + let draft = fixture.json(); + assert_eq!(draft["repository"]["current_view"]["value"]["own"], 1); + assert_eq!( + draft["repository"]["current_view"]["value"]["membership"], + parent_count + 1 + ); + fixture.ok(&["view", "switch", "main"]); + let parent = fixture.json(); + assert_eq!( + parent["repository"]["current_view"]["value"]["membership"], + parent_count + ); + assert_eq!( + parent["repository"]["registered_changes"]["value"], + registered + 1 + ); +} + +#[test] +fn repository_metrics_count_manifest_intents_without_exposing_titles() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let before = fixture.json(); + fixture.ok(&["intent", "new", "private intent title"]); + let text = fixture.ok(&["diagnostics", "--json"]); + let after: Value = serde_json::from_str(&text).unwrap(); + assert_eq!( + after["repository"]["intents"]["value"]["total"] + .as_u64() + .unwrap(), + before["repository"]["intents"]["value"]["total"] + .as_u64() + .unwrap() + + 1 + ); + assert!(!text.contains("private intent title")); +} + +#[test] +fn repository_metrics_fail_closed_when_database_is_busy() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let path = fixture.work.path().join(".atomic/atomic.redb"); + let database = redb::Database::open(&path).unwrap(); + let report = fixture.json(); + assert_eq!(report["repository"]["status"], "unavailable", "{report}"); + assert!(report["repository"]["database_bytes"].as_u64().unwrap() > 0); + drop(database); +} + +#[test] +fn repository_metrics_do_not_migrate_a_legacy_layout() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let dot = fixture.work.path().join(".atomic"); + let current = dot.join("atomic.redb"); + let legacy = dot.join("pristine.redb"); + std::fs::rename(¤t, &legacy).unwrap(); + let before = std::fs::read(&legacy).unwrap(); + let report = fixture.json(); + assert_eq!(report["repository"]["status"], "unavailable", "{report}"); + assert_eq!(std::fs::read(&legacy).unwrap(), before); + assert!(!current.exists()); +} + +#[test] +fn repository_metrics_do_not_guess_when_tables_are_absent() { + let fixture = Fixture::new(); + fixture.ok(&["init", "--view", "main"]); + let path = fixture.work.path().join(".atomic/atomic.redb"); + std::fs::rename(&path, path.with_extension("saved")).unwrap(); + drop(redb::Database::create(&path).unwrap()); + let before = std::fs::read(&path).unwrap(); + let report = fixture.json(); + let repo = &report["repository"]; + assert_eq!(repo["status"], "available", "{repo}"); + assert_eq!( + repo["registered_changes"]["status"], "unavailable", + "{repo}" + ); + assert_eq!(repo["views"]["status"], "unavailable", "{repo}"); + assert_eq!(repo["intents"]["status"], "unavailable", "{repo}"); + assert_eq!(repo["current_view"]["status"], "unavailable", "{repo}"); + assert_eq!(std::fs::read(path).unwrap(), before); +} + #[test] fn built_in_claude_hooks_work_without_a_receipt() { let fixture = Fixture::new(); @@ -878,6 +1059,11 @@ fn linked_atomic_workspace_finds_active_workspace_hooks() { std::fs::write(settings, r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"atomic agent hooks claude-code stop"}]}]}}"#).unwrap(); let report = fixture.json(); assert_eq!(report["workspace"]["status"], "found"); + assert_eq!(report["repository"]["status"], "available", "{report}"); + assert_eq!( + report["repository"]["current_view"]["status"], "unavailable", + "an unregistered linked worktree cannot borrow another working copy's view" + ); assert_eq!( find(&report["agents"], "name", "claude-code")["enabled"], "yes" @@ -887,6 +1073,19 @@ fn linked_atomic_workspace_finds_active_workspace_hooks() { .contains("Claude Code (claude-code): yes")); } +#[test] +fn repository_metrics_read_registered_linked_worktree_view() { + let fixture = Fixture::new(); + fixture.linked_git_worktree(true); + drop(atomic_repository::Repository::open(fixture.work.path()).unwrap()); + let report = fixture.json(); + assert_eq!(report["repository"]["status"], "available", "{report}"); + assert_eq!( + report["repository"]["current_view"]["status"], "available", + "{report}" + ); +} + #[test] fn broken_linked_git_administration_makes_workspace_unknown() { let fixture = Fixture::new(); diff --git a/atomic-core/src/pristine/txn/pristine.rs b/atomic-core/src/pristine/txn/pristine.rs index ff5543d3..f4487687 100644 --- a/atomic-core/src/pristine/txn/pristine.rs +++ b/atomic-core/src/pristine/txn/pristine.rs @@ -469,27 +469,39 @@ impl Pristine { /// // Read operations... /// ``` pub fn open_readonly>(path: P) -> PristineResult { - Self::open_readonly_with_schema_check(path, true) + Self::open_readonly_with_schema_check(path, true, true) + } + + /// Open for inspection without performing database upgrade or recovery. + /// + /// Unlike [`Self::open_readonly`], this returns an error when redb needs + /// a writable open to upgrade its format or recover after a crash. + pub fn open_readonly_without_recovery>(path: P) -> PristineResult { + Self::open_readonly_with_schema_check(path, true, false) } /// Open an existing database for read-only repair inspection without /// initializing tables or requiring a completed PATH_CLAIMS schema. /// - /// This method performs no writes. + /// A legacy redb format or interrupted transaction can require a writable + /// upgrade or recovery before the database is reopened read-only. pub fn open_readonly_for_repair>(path: P) -> PristineResult { - Self::open_readonly_with_schema_check(path, false) + Self::open_readonly_with_schema_check(path, false, true) } fn open_readonly_with_schema_check>( path: P, require_complete_path_claims: bool, + allow_recovery: bool, ) -> PristineResult { let cache_bytes = 8 * 1024 * 1024 * 1024; // 8 GiB let mut builder = Builder::new(); builder.set_cache_size(cache_bytes); let db = match builder.open_read_only(path.as_ref()) { Ok(db) => db, - Err(redb::DatabaseError::UpgradeRequired(_) | redb::DatabaseError::RepairAborted) => { + Err(redb::DatabaseError::UpgradeRequired(_) | redb::DatabaseError::RepairAborted) + if allow_recovery => + { // Migration and crash recovery need a writable handle. Close // it cleanly to persist allocator state before acquiring the // shared read lock. Never retry ordinary lock contention here. @@ -1013,6 +1025,9 @@ mod tests { .unwrap(); txn.commit().unwrap(); } + let before = std::fs::read(&path).unwrap(); + assert!(Pristine::open_readonly_without_recovery(&path).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), before); // The legacy fixture has no PATH_CLAIMS completion marker, so the // schema-strict read-only open correctly refuses it. The repair // variant still exercises the read-only upgrade path end to end. diff --git a/atomic-repository/src/repository/mod.rs b/atomic-repository/src/repository/mod.rs index 643de979..32538826 100644 --- a/atomic-repository/src/repository/mod.rs +++ b/atomic-repository/src/repository/mod.rs @@ -831,7 +831,7 @@ default = "{}" /// format upgrade; afterwards the database is reopened read-only. pub fn open_readonly>(path: P) -> Result { Self::wait_for_database(DEFAULT_DATABASE_WAIT, || { - Self::open_readonly_mode(path.as_ref(), false) + Self::open_readonly_mode(path.as_ref(), false, false) }) } @@ -843,14 +843,30 @@ default = "{}" pub fn open_readonly_for_operation_inspection>( path: P, ) -> Result { - Self::open_readonly_mode(path.as_ref(), true) + Self::open_readonly_mode(path.as_ref(), true, false) + } + + /// Open an existing current-layout repository without migration or repair. + /// + /// This narrow inspection mode rejects legacy layouts and sandboxes rather + /// than invoking their migration or provisioning paths. + pub fn open_readonly_without_migration>( + path: P, + ) -> Result { + Self::open_readonly_mode(path.as_ref(), false, true) } fn open_readonly_mode( path: &Path, operation_inspection: bool, + no_migration: bool, ) -> Result { if let Some((working_root, canonical, view)) = sandbox::detect_sandbox(path) { + if no_migration { + return Err(RepositoryError::InvalidOperation { + message: "non-migrating sandbox inspection is unavailable".to_string(), + }); + } return Self::open_sandbox_readonly(working_root, canonical, &view); } let layout = working_copy::discover_layout(path)?; @@ -859,9 +875,17 @@ default = "{}" // Open the pristine database in read-only mode. Identity validation below // performs no repair and reports a typed migration-required error. - let pristine = Arc::new( - Pristine::open_readonly(ensure_database(&dot_dir)?).map_err(RepositoryError::from)?, - ); + let database = if no_migration { + database::require_current_database(&dot_dir)? + } else { + ensure_database(&dot_dir)? + }; + let pristine = if no_migration { + Pristine::open_readonly_without_recovery(database) + } else { + Pristine::open_readonly(database) + }; + let pristine = Arc::new(pristine.map_err(RepositoryError::from)?); let (working_copy_id, current_view) = working_copy::load_registered_identity(&pristine, &layout)?; @@ -961,7 +985,9 @@ default = "{}" path: P, timeout: std::time::Duration, ) -> Result { - Self::wait_for_database(timeout, || Self::open_readonly_mode(path.as_ref(), false)) + Self::wait_for_database(timeout, || { + Self::open_readonly_mode(path.as_ref(), false, false) + }) } fn wait_for_database( diff --git a/atomic-repository/tests/it/legacy_database_merge_test.rs b/atomic-repository/tests/it/legacy_database_merge_test.rs index c13e6404..f3457c03 100644 --- a/atomic-repository/tests/it/legacy_database_merge_test.rs +++ b/atomic-repository/tests/it/legacy_database_merge_test.rs @@ -164,6 +164,24 @@ fn read_only_open_merges_a_legacy_repository() { assert_merged(&legacy); } +#[test] +fn non_migrating_read_only_open_leaves_legacy_databases_untouched() { + let legacy = legacy_repository(true); + let dot = legacy.root.join(".atomic"); + let graph = std::fs::read(dot.join(LEGACY_PRISTINE_FILE)).unwrap(); + let changes = std::fs::read(dot.join(LEGACY_CHANGE_STORE_FILE)).unwrap(); + assert!(Repository::open_readonly_without_migration(&legacy.root).is_err()); + assert_eq!( + std::fs::read(dot.join(LEGACY_PRISTINE_FILE)).unwrap(), + graph + ); + assert_eq!( + std::fs::read(dot.join(LEGACY_CHANGE_STORE_FILE)).unwrap(), + changes + ); + assert!(!dot.join(DATABASE_FILE).exists()); +} + #[test] fn legacy_repository_without_a_change_store_merges() { let legacy = legacy_repository(false);