Skip to content

fix(storage): harden project store authority and resolution - #506

Open
HashemKhalifa wants to merge 20 commits into
ScriptedAlchemy:masterfrom
HashemKhalifa:fix/consolidation-authority-20260808
Open

fix(storage): harden project store authority and resolution#506
HashemKhalifa wants to merge 20 commits into
ScriptedAlchemy:masterfrom
HashemKhalifa:fix/consolidation-authority-20260808

Conversation

@HashemKhalifa

@HashemKhalifa HashemKhalifa commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Summary

  • authorize only consolidation-owned staged databases during offline maintenance and keep volatile runtime telemetry out of stable plan fingerprints
  • validate the graph that the current branch would actually serve instead of assuming the root graph is active
  • reuse the already-open graph when an explicit selector resolves to the active project, while preserving separate routing for sibling worktrees and other projects
  • keep session correlation and identity-conflict diagnostics responsive with bounded presence probes instead of full-table and full-tree counts
  • keep daemon shutdown bounded when background maintenance holds the writer gate or watcher tasks are inside synchronous work
  • isolate branch recovery markers and avoid duplicate full-store crash-recovery validation

Root cause

Project resolution treated store comparison as an inventory operation even on authoritative and conflict-reporting paths. Preserved candidates therefore caused expensive graph and session-table diagnostics before ordinary graph tools could run. Branch-scoped stores could also be misclassified because health checks opened the root graph rather than the serving branch graph. An explicit selector for the already-active project opened the same store a second time, re-entering resolution and amplifying the delay.

A separate hot path remained in session correlation: ordinary requests traversed large correlation tables for diagnostic counts. During restart, scheduler shutdown could also wait indefinitely for writer administration, and watcher shutdown awaited one task before aborting the rest. The process could remain alive while the listener stopped making progress.

Crash recovery also validated the same non-empty database twice: the lifecycle performed a read-only preflight, then Database::open performed its own WAL-aware read-only validation before writable pragmas and migrations. Branch syncs additionally published a repository-wide legacy dirty marker, allowing one sibling worktree to trigger recovery in another branch graph. Dirty zero-length stores required an explicit guard because the ordinary open path correctly treats a zero-length database as fresh outside recovery.

Behavior after this change

  • selected exact-root stores use bounded read-only presence probes; actual serving opens still perform full integrity validation and fail closed
  • identity-conflict diagnostics report presence-only values and do not run full table or artifact-tree counts
  • unreadable graph, session, branch-metadata, or artifact state is reported as unhealthy and blocks marker or manifest repair
  • duplicate legacy stores remain untouched and recoverable; genuinely ambiguous stores continue to fail closed
  • same-project selectors use the active reader; different projects and explicit sibling-worktree paths still dispatch separately
  • ordinary session correlation uses bounded presence probes and labels populated-family values as count_mode: presence_only
  • daemon shutdown bounds writer-gate acquisition and joins; all watcher tasks are aborted before any join is awaited
  • non-empty crash recovery performs one WAL-aware validation before writable work
  • branch graphs publish and honor only graph-local dirty markers; the root graph retains legacy-marker recovery behavior
  • dirty zero-length or unreadable recovery sets fail before writable initialization and preserve their recovery evidence

Validation

  • 44 storage-resolver tests passed
  • focused read-only presence-probe, scheduler shutdown, blocked-watcher, session-correlation, and MCP correlation regressions passed
  • focused branch-marker, corrupt-branch, legacy-root-marker, and dirty-store regressions passed, including RED-first coverage for sibling marker isolation and zero-length recovery
  • cargo check --workspace
  • cargo fmt --check
  • git diff --check
  • optimized release build completed for the audited candidate
  • independent exact-commit audit: PASS, no critical or warning findings after remediation
  • managed-daemon restart completed and rebound the socket; cold graph access completed through startup catch-up, and repeated active-project and sibling-worktree graph calls completed without another storage recovery scan

One-time transcript catch-up and stale-index refresh remain cold-start work; they are separate from the repeated recovery scans fixed here.

commitlint was unavailable in this checkout (commitlint: command not found); all commit subjects follow the repository's conventional format.

Consolidation normalizes private session snapshots while holding the enclosing profile's exclusive maintenance lease. Map only its reserved staging directory to that profile authority, and keep append-only hook telemetry outside immutable confirmation fingerprints without dropping its bytes.
Reserve profile maintenance authority for the two session snapshots created by consolidation. Other files under the staging directory keep their independent database identity.
@changeset-bot

changeset-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 91944bc

The changes in this PR will be included in the next version bump.

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Branch-scoped stores must not inherit repository-wide dirty state from sibling worktree syncs. Reuse Database::open's read-only validation to avoid a second full recovery scan.
Dirty zero-length databases must fail before writable initialization so recovery bytes and markers remain available for offline repair.
@HashemKhalifa

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 043a047e03

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/tracedecay/lifecycle.rs Outdated
Comment thread src/tracedecay/lifecycle.rs Outdated
Comment thread src/tracedecay/lifecycle.rs
Treat unreadable auxiliary state as a conflict, validate the serving branch before identity repair, and recheck cached writable connections during dirty recovery.
Establish every bounded inventory health signal before populated graph or session data may authorize exact-root selection.
@HashemKhalifa

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 91944bc6ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +196 to +200
let Some(selector_path) = selector_path else {
return true;
};
if !GlobalDb::is_explicit_project_path_selector(selector_path) {
return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Route pathless selectors through the registered root

When the MCP server is attached to a linked worktree and the caller selects the shared project by project_id (or by a non-explicit basename), this returns the active TraceDecay solely because the project IDs match. Registration deliberately keeps canonical_root pinned to the primary checkout (src/tracedecay/lifecycle.rs:951-973), and the normal selected-reader path opens that root (src/mcp/tools/handlers/mod.rs:158-159); the primary checkout and active worktree can serve different branch databases. Consequently, an explicit registered-project query can silently return results from the active worktree instead of the selected canonical project, so the shortcut should also require the active root to match context.project.canonical_root when no explicit path is supplied.

Useful? React with 👍 / 👎.

Comment on lines +136 to +137
if selector_targets_active_project(active_cg, args, &context.project.project_id) {
return Ok(None);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve project-wide scope when reusing the active reader

When a server was started from a subdirectory and a graph tool explicitly selects the active project path, this new shortcut returns None; downstream, selected_cg.is_some() is therefore false and lines 415-419 retain the connection's scope_prefix. Before this optimization, the selected project was opened as a separate reader and its scope was cleared, just as it still is for every other registered-project selector. The same explicit project query can now silently omit files outside the server's startup subdirectory, so reusing the handle must be represented separately from having no project selector and must still clear the scope.

Useful? React with 👍 / 👎.

Comment on lines +1405 to +1408
let presence = (
table_presence(db.conn(), "nodes").await,
table_presence(db.conn(), "files").await,
table_presence(db.conn(), "memory_facts").await,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Treat absent pre-migration tables as empty during probing

When an identity-resolution candidate was last written by a supported pre-v11 TraceDecay version, memory_facts does not exist yet—the table is introduced by migration v11 in crates/tracedecay-runtime-core/src/db/migrations.rs:1321-1327. Because this read-only presence probe intentionally runs no migrations, the query errors even when nodes and files are healthy and populated; the fast path then rejects the selected store, and the full inventory labels it corrupt. The analogous unconditional LCM-table probes have the same problem for older session schemas. Thus an upgrade involving a preserved duplicate shard can fail during resolution before the normal writable open gets a chance to migrate it; a missing table from an older schema should contribute zero presence rather than unhealthy status.

Useful? React with 👍 / 👎.

Comment on lines +996 to +1002
if is_runtime_lock(&relative)
|| is_sqlite_sidecar(&relative)
|| is_volatile_hook_telemetry(&relative)
{
// Hooks may append this telemetry between dry-run and apply. It is
// omitted only from the confirmation fingerprint; backup and
// artifact merge still copy and checksum every telemetry byte.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reconcile volatile telemetry when resuming consolidation

If consolidation is interrupted after DestinationReady or ArtifactsMerged and a hook then appends to either input's hook_analytics.jsonl, excluding this file keeps the old confirmation token valid on retry. The ledger resumes after the relevant artifact-copy phase, so the prepared destination is not refreshed from the target and an already-completed source artifact merge is not rerun; the newly appended rows are therefore absent from the consolidated store after marker cutover even though the retry succeeds. Keep the token stable if desired, but resumptions must recopy or append-merge this volatile file before cutover rather than skipping change detection without reconciling it.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant