Skip to content

fix(db): version the tracking and recall schema migrations - #4894

Merged
KuSh merged 1 commit into
rtk-ai:developfrom
KuSh:fix/schema-version-enum
Nov 18, 2026
Merged

KuSh merged 1 commit into
rtk-ai:developfrom
KuSh:fix/schema-version-enum

Conversation

@KuSh

@KuSh KuSh commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The tracking DB's SCHEMA_VERSION was a plain const, and a stale user_version re-ran every migration. Two PRs that each add a migration make the same 2 → 3 edit, so git merges them silently, and a database already stamped 3 by a build with only the first one never runs the second one's migration. The recall DB had no version at all and re-ran its schema on every open.

This moves the SQLite open and migration engine into a new core::db, used by both databases:

  • Versions. Each database has a versions enum with explicit values and a Next sentinel (tracking: Initial = 1, EngineTables = 2, InitialRecheck = 3; recall: Initial = 1, Recalled = 2), one step per version in MIGRATIONS, and a const assertion that fails the build unless they match. A new schema change adds a variant above the marker line and its step; two PRs doing that at once conflict.
  • Steps. A database stamped N applies steps N+1 … latest in order, each in its own IMMEDIATE transaction that re-reads the stamp under the lock and stamps its own version, so a failed step leaves the previous version and the next open tries again, and concurrent openers apply each step once. A current database costs one unlocked read. rtk init re-applies every step (tracking always, recall when its store exists and recall is enabled) and leaves each database at this build's version, as develop does.
  • Identity. Each file is tagged with application_id = 0x5254_4B00 | kind ("RTK" plus a database number from a DbKind enum). The tag is read with the stamp and checked before anything is written, so pointing one database's path at the other's file (or at another application's) is refused instead of silently skipping steps, and a refused file that could be read is left as it was.
  • Errors. The migration statements that used to discard their errors (the commands ALTERs, the NULL backfill, the project index, recall's recalled ALTER) now fail their step, through add_column_if_missing. Releases that stamped 1 or 2 could have skipped part of the Initial schema that way, so InitialRecheck re-applies it once on those databases.
  • Failed steps. A step that fails on a normal open does not fail the open: it rolls back, keeps the stamp, and the database is used as it is, as on develop. Every rtk gain report says why on stderr, a query that needs what is missing says so, rtk gain --reset replays the steps first, and rtk init still warns. Refusing a file that is not this database's stays fatal.
  • Permissions. The file is read before its permissions and directory are touched. When a create, open or first read fails, the file is read again with immutable=1, which needs no sidecar: one that is not a database or not this one is refused with its modes kept. Otherwise a directory or file its owner cannot use is given back (0700, 0600) and the open is tried again, so everything develop repaired before opening still opens. A file that only this made readable and that is then refused gets its modes back. The sidecars are found through a symlink, and repaired before a step writes to them.
  • Read-only filesystems. A WAL-mode file there cannot create its -shm, so it failed on develop. It now opens with that immutable=1 read, unless a -wal or a hot -journal holds data the read would miss.

The parent-directory chmod of a configured database path is unchanged (#4280).

Behaviour changes:

  • a tracking DB at 1 or 2 re-applies its Initial statements once and is stamped 3; a recall store is versioned (stamp 2) on its next open, and both files get their tag on their next migrating write.
  • a failing migration statement fails its step and is retried on the next open, instead of being stamped as applied. Meanwhile the database is used as it is: rtk gain prints rtk: tracking database was not upgraded: <cause> on stderr, and a query that needs what is missing fails with no such column: x (tracking database was not upgraded: <cause>). Writes are still attempted. A reset replays the steps, then clears what it can reach: a table a failed step left out stops it, with the cause.
  • the hook no longer prints a logging failure when the database is read-only or lacks what a failed step would have created; it still prints any other failure. rtk discover no longer suggests rtk init for a failed step.
  • a recall store at its stamp that lost a table prints rtk: recall database looks corrupted (…). Run rtk init to recreate it., as tracking does, instead of being recreated on open.
  • a database path that points at the other rtk database or at another application's file is refused, e.g. … is the rtk recall database, not the tracking one; set RTK_DB_PATH or [tracking] database_path to another file.
  • rtk init also repairs an existing recall store; a failure prints [warn] Failed to prepare recall database: … and init carries on.
  • rtk gain --reset still resets tracking when the recall store is unusable, says so on stdout and exits 1 with rtk: recall stats were not reset: …. rtk gain --recalls fails on it as on develop, with rtk: Recall store unavailable: ….
  • an existing recall store in a locked directory has the directory repaired on open, including on read paths, where develop left it locked.
  • rtk init and rtk discover --verbose print the whole error chain, so the SQLite cause follows the step that failed. rtk recall says store unavailable only when the store cannot be opened, and prints other failures as they are.

Test plan

  • Upgrades: unversioned, v1 and v2 tracking DBs (including a v2 DB missing commands.project_path), unversioned recall stores; a fresh DB of each kind; steps at or below the stamp never replayed (a probe step that fails when run twice)
  • Concurrency: a second connection holding the lock while it migrates, the waiter replays nothing and still applies the next step; a current DB opens with another connection holding the write lock and no busy timeout
  • rtk init: replays, never lowers a stamp mid-run, hands a newer build's DB back at this build's version, leaves a missing or disabled recall store alone
  • Failures: a failed step rolls back and keeps the previous stamp, the next open retries it, a step SQLite rolled back is not stamped, each formerly discarded statement fails its step and is named in the error; on a normal open the database stays usable with the cause reported, rtk init fails, a file tagged since the first read is still refused
  • Unwritable and stuck databases behind on their stamp, through the real binary: a read-only bind mount (with rollback journal and WAL), a symlink into a 0555 directory, a write lock held by another process, a step that always fails; every rtk gain report, --reset, rtk discover and the hook on them
  • Recovery: a non-database file and a foreign WAL file keep their modes when refused, including at 0000 or 0200 or in a directory at 0000 or 0300, which get their modes back; a path that is not UTF-8; a -wal or -journal holding data keeps the failure; a path that needs escaping or starts with two slashes; a step never writes to a loose sidecar
  • Identity: each refusal message, from both databases and both modes; a refused file keeps its content, journal mode, permissions and directory; untagged legacy files accepted or refused per database; the tag never written by a gated open with nothing to apply
  • Files: write-protected own DB made writable and written; owner-only DB, -wal, -shm and directory under umask 022; recall's connection cache never serves another path, a removed store or a recreated one
  • Locked states: directory at 0555/0500/0000 with an existing or missing file, file at 0000/0200, both at once, a read-only file behind a symlink, a missing store left alone
  • Against develop's binary at this PR's base (8bb6096b): rtk ls, rtk gain and rtk init on 600 tracking states (directory mode, file mode, journal mode or leftover sidecars, symlink, including one into another directory) and rtk recall --list, rtk gain --recalls and rtk init on 189 recall states; nothing develop handles fails here (rtk ls and rtk gain work on develop in 549 of the 600 tracking states, and the same 51 fail on both). Tracking's final directory and file modes after rtk ls and rtk gain are the same on every state develop handles. For recall, the only directory-mode difference is the documented one: a directory at 0555, 0500 or 0300 comes out at 0700
  • rtk gain --reset / --recalls and rtk init's recall warning through the real binary
  • Every new test fails under the mutation of the code it pins; two branches each adding a variant conflict in git merge-file; one more variant added to both DBs leaves the suite green
  • cargo fmt, cargo clippy --all-targets, cargo test --all, the same with --no-default-features, and a x86_64-pc-windows-gnu check

🤖 Generated with Claude Code

@rtk-wshm-sync-bot

Copy link
Copy Markdown

wshm · Automated triage by AI

📊 Automated PR Analysis

🐛 Type bug-fix
🔴 Risk high

Summary

Fixes SQLite schema migration bugs in rtk's tracking and recall databases, where a stale user_version could skip migrations or merge conflicts could silently drop one. Introduces a shared core::db module with explicit version enums, ordered per-version migration steps, application_id file tagging to prevent cross-database path mixups, and propagates previously-swallowed migration errors. Also updates rtk init/gain commands to handle a failing or unusable recall store gracefully instead of hard-…

Review Checklist

  • Tests present
  • Breaking change
  • Docs updated

Analyzed automatically by wshm · This is an automated analysis, not a human review.

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two regressions against develop, both in src/core/db.rs.

1. Tracking DB directory not writable. develop chmodded the parent before opening; the PR reads the identity first, and on a WAL file that read has to create -shm.

D=$(mktemp -d); export RTK_DB_PATH=$D/history.db
rtk git status
chmod 0555 $D
rtk gain
# develop: works, directory repaired to 0700
# PR: Failed to read the tracking DB version: … SQLITE_READONLY_DIRECTORY; `rtk init` fails the same way

Same with no DB yet (mkdir -m 0555): develop creates it, the PR fails in pre_create.

2. Read-only tracking DB behind a symlink. SQLite creates -wal/-shm next to the resolved target; restrict_sidecars chmods <link>-wal/<link>-shm, which never exist, so the reopened connection stays read-only.

D=$(mktemp -d); export RTK_DB_PATH=$D/history.db.real
rtk git status; sqlite3 $D/history.db.real 'PRAGMA user_version = 2'
chmod 0444 $D/history.db.real; ln -s history.db.real $D/history.db
RTK_DB_PATH=$D/history.db rtk gain
# develop: works
# PR: Failed to start migration InitialRecheck of the tracking DB: attempt to write a readonly database
# ls -la $D: history.db.real-shm is still 0444; chmod u+w on it makes the PR succeed

On a DB already at stamp 3 the symptom is silent: inserts fail where develop recorded.

@KuSh
KuSh force-pushed the fix/schema-version-enum branch from f8f8180 to d3a5497 Compare November 4, 2026 18:27
@KuSh

KuSh commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, both reproduced and fixed. Reading the file before repairing anything was the cause of the first one, and it went further than your repro: a DB at 0000 or 0200 also failed. Now, when the first create, open or read fails on a directory or file its owner cannot use, it is given back (0700, 0600) and the open is retried. Sidecars are found through the symlink.

To look for others of the same kind, I ran develop's binary and this one on 450 tracking states (directory mode, file mode, journal mode or leftover sidecars, symlink) and 189 recall states. Nothing develop handles fails now.

One difference stays on this PR alone, with its fix in #4901: a tracking DB or recall store that is really unwritable (read-only mount, another user's file), behind on its stamp and not in WAL mode, still fails to open here because a step has to write. #4901 opens it as it is, for both; I checked that on a read-only bind mount. In WAL mode it fails on develop too.

@KuSh
KuSh requested a review from aeppling November 4, 2026 23:36

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Both fixed on d3a5497b. Two cases still fail here and work on develop; both were already there at f8f81805.

1. Unwritable DB behind on its stamp. chflags uchg stands in for a read-only mount or another user's file.

D=$(mktemp -d); export RTK_DB_PATH=$D/history.db
rtk git status; sqlite3 $D/history.db 'PRAGMA user_version = 2'
chmod 0444 $D/history.db; chflags uchg $D/history.db
rtk gain
# develop: works
# PR: Migration InitialRecheck of the tracking DB failed: Failed to backfill commands.project_path: attempt to write a readonly database

2. DB reached through a symlink into an unwritable directory.

D=$(mktemp -d); mkdir $D/store $D/data
RTK_DB_PATH=$D/store/history.db rtk git status
sqlite3 $D/store/history.db 'PRAGMA user_version = 2; PRAGMA journal_mode = DELETE'
ln -s ../store/history.db $D/data/history.db; chmod 0555 $D/store
RTK_DB_PATH=$D/data/history.db rtk gain
# develop: works
# PR: Failed to stamp the tracking DB at InitialRecheck: attempt to write a readonly database: SQLITE_READONLY_DIRECTORY

Same cause: a stamp-2 DB has to take the InitialRecheck write before it opens, and a failed step fails the open. Suggestion: a failed step rolls back, keeps the stamp, is reported by gain/init, and the DB is used as it is, as on develop. Refusing a foreign file stays fatal. That covers both without needing #4901.

@KuSh
KuSh force-pushed the fix/schema-version-enum branch from d3a5497 to 5c66e2a Compare November 6, 2026 18:18
@KuSh

KuSh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, both reproduced on Linux (a read-only bind mount in place of chflags uchg) and fixed, going with your suggestion. A step that fails on a normal open rolls back, keeps the stamp and is retried on the next open, and the database is used as it is. Every rtk gain report prints rtk: tracking database was not upgraded: <cause> on stderr, a query that needs what is missing adds that note, rtk init still warns, and refusing a foreign file stays fatal. Recall behaves the same way.

It also covers a case the read-only handling in #4901 did not: a stamp-2 database whose write lock another process holds failed after the 5 s busy timeout, and now works after it.

Two more changes came with it:

  • A clean WAL file on a read-only filesystem now opens, with immutable=1. It failed on develop too.
  • A file that fails to open is read that way before anything is repaired, so a non-database or foreign file keeps its permissions. A file its owner cannot read at all gets just enough to read its tag, and its modes back when it is refused.

The develop comparison now includes your symlink into another directory: 12 of those states failed at d3a5497b, and none of the 600 tracking or 189 recall states fails now where develop works.

Two consequences to weigh:

  • A step that keeps failing is retried on every open. With a table blocking the project index on a 100k-row history, a release build goes from 2.0 ms to 5.9 ms per run; at 1k rows it stays at 2.0 ms.
  • immutable=1 trusts the file not to change. On a read-only mount of a directory something else is writing, such as a container's :ro volume, a read can see stale data or an error.

This makes #4901 unnecessary, so I am closing it. #4909 is rebased on this.

SCHEMA_VERSION is now derived from a SchemaVersion enum, and each variant
has its own migration step, applied in order from the database's
user_version and stamped in its own transaction. Two changes adding a
schema version now conflict instead of merging into one shared bump.

The open and the migration engine live in core::db, which the recall
database now uses with its own versions, replacing its swallowed ALTER.
Each file carries an application_id naming its database, and a file
tagged as another database's is refused before rtk changes anything on it.

A step that fails rolls back and keeps the stamp, so the next open tries
again, and the database is used as it is. rtk gain says why it was not
upgraded, a query that needs what is missing says so, rtk gain --reset
gives the migration another chance, and rtk init reports the failure.

A file that cannot be opened normally is read without its sidecars before
anything is repaired, so one that is not rtk's keeps its permissions, and
a WAL-mode file on a read-only mount opens when its -wal holds nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@KuSh
KuSh force-pushed the fix/schema-version-enum branch from 9690e12 to 94aa52e Compare November 17, 2026 00:32
@aeppling

Copy link
Copy Markdown
Contributor

Hey @KuSh

LGTM,

On the two consequences, both are fine:

  • Step retried on every open: 9.7 ms to 16.4 ms per command on a 100k-row history with a permanently failing step. Acceptable for a state that rare.

  • immutable=1 on a read-only mount with a writer: with the writer connected, the immutable read is never used. With a writer connecting and disconnecting in a loop, develop fails 514 of 800 rtk gain reads and this PR fails 1, with no wrong total.

@KuSh
KuSh merged commit 76be19c into rtk-ai:develop Nov 18, 2026
19 checks passed
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Nov 18, 2026
@KuSh
KuSh deleted the fix/schema-version-enum branch November 18, 2026 20:19
yungSNAT added a commit to yungSNAT/PascalsLetter that referenced this pull request Nov 24, 2026
* Merge pull request rtk-ai#4894 from KuSh/fix/schema-version-enum

fix(db): version the tracking and recall schema migrations

Ported from upstream rtk-ai/rtk 76be19c, with 24ff226 (rtk-ai#5180, clippy on
Windows FileId). tracking.rs keeps the fork's seen_by_agent cap helpers;
retriever.rs keeps a test-only open_existing for the tee and posthook tests.

Co-authored-by: Nicolas Le Cam <[email protected]>
Co-authored-by: LeviReisJs <[email protected]>

* test(db): databases from the fork's last release migrate, and a failed step leaves them usable

* fix(db): build against the fork's rusqlite 0.41 (MAIN_DB, busy_handler takes &mut)

* style(db): rustfmt

* test(db): a failed recall step and a step failing at its last statement leave the release's files usable

---------

Co-authored-by: Nicolas Le Cam <[email protected]>
Co-authored-by: LeviReisJs <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants