Skip to content

Collapse the five-step migration ladder into a single current-shape schema bootstrap - #2698

Merged
malibio merged 2 commits into
mainfrom
issue-2688-collapse-migration-ladder
Sep 17, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2688-collapse-migration-ladder

Conversation

@malibio

@malibio malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Closes #2688.

What and why

A fresh database was running five migrations in sequence — including v004, a data migration over rows that cannot exist — to arrive at a shape a single CREATE TABLE batch produces directly. Every part of that apparatus existed to carry a database created by an older build across a schema change. NodeSpace has no releases and no user databases, so no such database exists.

CLAUDE.md's carve-out licenses creating the tables; it had been read to also license the ladder, the version ratchet, and the backup system layered on top.

The ladder was propagating the banned pattern

This surfaced while scoping #2638, which cites v004 in its Technical Specifications as the precedent migration to follow. Following it faithfully would have meant writing a backfill of the new column from existing properties JSON — exactly what the no-data-migration policy prohibits. v002 likewise carried a compatibility workaround for "a database that already applied it under the old code," a shape no user ever had.

Changes

Added packages/core/src/db/schema.rs — one create_schema() holding the current DDL, idempotent via IF NOT EXISTS so reopening a database is a no-op. Folds in every migration's final effect: embedding.origin and the origin-leading idx_emb_modified (v002), the partial expression indexes (v003), and the conflict journal tables (v005).

Deleted

  • v001–v005 and migrations/mod.rs (942 lines)
  • the PRAGMA user_version ratchet: LATEST_VERSION, run_up_to, apply_migration, migration_name, newer-than-supported guard
  • the backup system: backup_before_pending_migrations, db_has_data, prune_backups, MAX_BACKUPS, VACUUM INTO snapshots
  • db/schema.sql — a hand-maintained "current schema" reference that had already drifted: missing v005's conflict tables and the FTS5/vec0 virtual tables entirely. schema.rs is now the single executable definition, so the duplicate cannot drift again.

Corrected backfill_fts_if_stale, which justified itself with "user DBs are never reset — same reason the migration runner exists" — the opposite of this project's stance. The mechanism is still worth having as index-integrity repair (an interrupted write, or rows reaching node by a path the triggers did not see, desyncs FTS), so the code stays and only the rationale changes.

Updated CLAUDE.md's carve-out to point at the new path and state plainly that there is no migration ladder and no schema version.

Testing

migrations_test.rs → schema_test.rs, asserting what now matters:

  • a fresh database gets the complete table/index/trigger set, including the late-arriving ones a naive collapse would silently drop
  • idx_emb_modified lands on the v002 shape (origin leading), not v001's — the cloud-push sweep depends on it
  • re-creating the schema preserves data

The store-level backup test becomes one that reopening a database preserves its rows.

Full cargo test -p nodespace-core --tests: 28 binaries, 0 failures. Pre-push gate (frontend, scripts, skill, Rust, e2e) passed. Rebased onto #2637 and #2651.

Note for #2638

#2638 is specced to add a v006 migration for reverse_relationship_type. With this merged, that becomes a column in the bootstrap schema instead, and that acceptance criterion needs restating on the issue.

🤖 Generated with Claude Code

…2688)

NodeSpace has no released builds and no user databases, so there is no
older on-disk shape to carry forward — yet a fresh database was running
five migrations in sequence (including v004, a data migration over rows
that cannot exist) to reach a shape one CREATE TABLE batch produces.

Everything deleted here existed to serve a database created by an older
build: the v001-v005 ladder, the PRAGMA user_version ratchet, and the
pre-migration backup system with its VACUUM INTO snapshots and 5-backup
retention.

The ladder was also actively propagating the banned pattern. #2638 cites
v004 as the precedent to follow for a relationship-table change;
following it faithfully would mean writing a backfill. v002 carried a
compatibility workaround for "a database that already applied it under
the old code" — a shape no user ever had.

Replaced with db/schema.rs: one create_schema() holding the current DDL,
idempotent via IF NOT EXISTS so reopening a database is a no-op. It folds
in every migration's final effect — embedding.origin and the
origin-leading idx_emb_modified (v002), the partial expression indexes
(v003), and the conflict journal tables (v005).

Also deletes db/schema.sql, a hand-maintained "current schema" reference
that had already drifted: it was missing v005's conflict tables and the
FTS5/vec0 virtual tables entirely. schema.rs is now the single executable
definition, so the duplicate cannot drift again.

backfill_fts_if_stale is kept but rewritten: it justified itself with
"user DBs are never reset — same reason the migration runner exists",
which is the opposite of this project's stance. The mechanism is still
worth having as index-integrity repair (an interrupted write or a path
the triggers did not see can desync FTS from node), so the code stays and
the rationale is corrected.

Tests: migrations_test.rs is replaced by schema_test.rs, asserting the
bootstrap produces the complete table/index/trigger set, that
idx_emb_modified lands on the v002 shape rather than v001's, and that
re-creating the schema preserves data. The store-level backup test
becomes one that reopening a database preserves its rows.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2698

Review Type: Initial review (no prior reviews or comments on this PR)
Scope: 16 files, +445/−1436 · git diff origin/main...HEAD


Summary

This is a clear net-positive change and a genuinely well-executed one. It deletes ~940 lines of apparatus whose only purpose was carrying a database created by an older build forward — something that cannot exist in a project with zero releases — and replaces it with one readable current-shape DDL definition. The motivation is not merely aesthetic: v004 was a real data migration that the policy bans, and it was actively being cited as the precedent to imitate in a downstream issue. Removing it removes the teaching example, which is the most valuable part of this change.

I verified schema equivalence empirically rather than by eye. I reconstructed the old v001→v005 ladder as SQL, built both databases in SQLite, and diffed sqlite_master plus PRAGMA table_info / foreign_key_list / index_list / index_info for every table. The only difference in the entire schema is the ordinal position of embedding.origin (cid 14 in the new schema vs cid 16 under the ladder, where ALTER TABLE appended it last). Every table, every index, every index column list and order, every foreign key with its ON DELETE action, every STRICT modifier, every DEFAULT, every trigger body, and both virtual tables are byte-identical. Details in finding 🟢-1.

The areas flagged as highest-risk all check out:

  • embedding.origin — present, TEXT NOT NULL DEFAULT 'local' ✅
  • idx_emb_modified — (origin, modified_at, node_id, chunk_index), the v002 rebuilt shape, not v001's 3-column one ✅ (and asserted by a test)
  • All five v003 partial expression indexes, including the WHERE node_type = ... partial clauses ✅
  • conflict / conflict_participant — conflict_id cascades, conflict_participant.node_id correctly has no FK to node, composite PK intact ✅
  • node_fts FTS5 external-content table + all three triggers ✅
  • vec_embeddings vec0 virtual table ✅

Standards compliance is clean: no lint suppressions, no #[allow(dead_code)], no #[deprecated], no backward-compat code, no data migrations, no new .md files in this repo, cargo clippy -p nodespace-core --all-targets produces zero warnings. The old schema.sql's (#182/#183) and (#97/#182) issue references were correctly dropped rather than carried into schema.rs — the new file has no issue numbers anywhere.

The findings below are two stale-comment cleanups and one test-coverage regression. None of them block merge.


Requirements Check — issue #2688 acceptance criteria

# Criterion Status
1 schema.rs creates the complete current schema in one batch ✅ Verified structurally equivalent
2 v001…v005 and migrations/mod.rs deleted ✅
3 user_version ratchet deleted ✅ No occurrence anywhere in the repo
4 Backup system deleted ✅ No occurrence anywhere in the repo
5 Call sites use create_schema; no reference to db::migrations remains ⚠️ Code references gone; six stale doc comments remain — see 🟡-1
6 Schema equivalent to post-v005, verified by a test ✅ Verified empirically + test asserts tables/indexes/triggers/origin
7 Bootstrap idempotent ✅ Verified; also recovers a partially-created schema
8 backfill_fts_if_stale rationale corrected or code removed, decision documented ✅ Corrected, rationale sound — see 🟢-2
9 migrations_test.rs rewritten against the bootstrap ✅ → schema_test.rs, but see 🟡-2
10 CLAUDE.md DDL carve-out updated ✅ Good addition: explicitly bans re-adding a ladder
11 Tests pass ✅ schema_test 3/3; --lib db:: 93/93; clippy clean
12 quality:fix ✅ Clippy clean, tree clean

11 of 12 fully met; #5 met in substance with cosmetic residue.


Findings

🟡 Important

🟡-1 — Six doc comments still name deleted files, so rg v001_initial_schema now returns dangling pointers

Acceptance criterion #5 says "no reference to db::migrations remains anywhere." The code references are all gone, but six comments still point readers at files that no longer exist. The PR was careful to update three of these (conflicts.rs, connections.rs:235, models/conflict.rs) — these six were simply missed by the same sweep.

  • 📁 packages/core/src/db/sqlite_store/nodes.rs:4478 — "the node_fts FTS5 sync triggers (v001_initial_schema)" → db::schema
  • 📁 packages/core/src/services/query_service/query_service_test.rs:1495 — "Migration v003_property_indexes.rs hardcodes partial expression indexes" → db/schema.rs
  • 📁 packages/core/src/db/sqlite_store/mod.rs:87-88 — "to exercise the migration runner directly … since migration 1 creates a vec0 table" → create_schema
  • 📁 packages/core/src/db/sqlite_store/mod.rs:1897 — "busy_timeout (set by migration 1, applied per-connection in initialize_schema)" — this one is also factually wrong independently of the rename: busy_timeout was never set by migration 1. Both v001's module doc and the new schema.rs doc state explicitly that it is a per-connection session setting, not schema state, applied in apply_connection_pragmas.
  • 📁 packages/core/src/db/sqlite_store/connections.rs:74 — "no reader connection exists until after migrations have run" → "until after the schema is created" (the sibling comment at line 233 in the same file was updated; this one was missed)
  • 📁 packages/core/benches/query_crud.rs:16, 35, 451 — "migration v003's idx_task_status", "see schema migration 1"

Why it matters: the stated value of this PR is that schema.rs becomes "the single executable definition, so the duplicate cannot drift again." Comments pointing at deleted files are a second, softer form of exactly the drift the PR removes — and they're the first thing a future reader greps. Mechanical fix, no behavior change.

🟡-2 — schema_test.rs drops the EXPLAIN QUERY PLAN assertion that was the only real guard on expression-index coverage

📁 packages/core/tests/schema_test.rs (new) vs the deleted migrations_test.rs::task_status_filter_uses_partial_expression_index

The new test asserts idx_task_status exists by name. The deleted test asserted the query planner actually chooses it for the exact filter shape QueryService generates — and the deleted test's own comment explains precisely why that is stronger:

"a stronger guarantee than a string-equality check, since SQLite silently ignores an index whose expression doesn't match byte-for-byte."

That comment is the whole point. A partial expression index is invisible to the planner unless the query's expression text matches the index's byte-for-byte; an index that exists and an index that is used are different properties, and only the second one is worth anything. The surviving tests in query_service_test.rs (test_resolve_field_matches_indexed_expression, test_build_property_filter_matches_indexed_expression) are string-equality tests on the query side only — they are the weaker check the deleted comment was contrasting against, and they pin the query generator without pinning the index it must match.

This is a coverage regression introduced by the rewrite, not a pre-existing gap. Note the asymmetry: the analogous sweep index idx_emb_modified does keep its EQP assertion (📁 packages/core/src/db/sqlite_store/mod.rs:1372-1392, which also asserts no TEMP B-TREE filesort) — so the pattern is already established in the codebase and this is the one place it was dropped.

Suggested: port the deleted test into schema_test.rs more or less verbatim, swapping migrations::run for schema::create_schema. I confirmed the behavior still holds — inserting one task row and running EQP on that filter shape yields SEARCH node USING INDEX idx_task_status_due_date (<expr>=?), so an expression-coverage assertion will pass. (Worth noting the planner picks the composite index on a 1-row table, so a port should assert index coverage generally rather than idx_task_status by exact name, or seed enough rows that the stats favor the single-column index — the deleted test's exact-word match may be stat-dependent.)

🟢 Suggestions

🟢-1 — embedding.origin moves from column ordinal 16 to 14; inert here, worth a one-line note

📁 packages/core/src/db/schema.rs:97-103

The sole structural difference I found between old and new. Under the ladder, ALTER TABLE ... ADD COLUMN appended origin after created_at/modified_at; the new DDL places it in its logical position before them.

I checked whether anything depends on ordinal position: every query against embedding names its columns explicitly — there is no SELECT * and no positional INSERT (📁 packages/core/src/db/sqlite_store/embeddings.rs:124 spells out all 17 columns; :229, :269 spell out their selects). SQLite's STRICT mode doesn't care either. So this is behaviorally inert and the placement is genuinely better — grouping origin with the other data columns rather than stranding it after the timestamps is exactly the kind of tidy-up collapsing the ladder is supposed to buy.

Flagging only because it is the one place where "equivalent in effect" is not "identical," and a future reader diffing a pre-existing dev database's table_info against this file would see the discrepancy and wonder. Nit: a short comment, or a line in the PR body, would preempt that.

🟢-2 — The backfill_fts_if_stale rewrite is the right call; one clause in the new rationale is weaker than the others

📁 packages/core/src/db/sqlite_store/mod.rs:285-297

Keeping the code is justified. The mechanism is genuinely cheap and genuinely load-bearing: it reads two count(*)s, compares them, and rebuilds only on disagreement. The failure it guards against is silent and permanent — a desynced FTS index omits rows from bm25_search_roots forever with no error — which is exactly the profile where a cheap startup check earns its place. And the staleness signal is subtle in a way that deserves the comment it has: node_fts_docsize rather than count(*) FROM node_fts, because the latter reads rowids from the content table and therefore always equals the node count regardless of index population. Deleting this would have been the wrong call; the old rationale was wrong, not the code.

Two of the three cited causes hold cleanly under current policy (interrupted write; bulk restore). The third — "or an ALTER TABLE rebuild" — is on shakier ground, since an ALTER TABLE that rewrites the node table is close to the pattern this very PR removes. Not wrong (SQLite itself rewrites the table for some ALTER forms, and VACUUM can renumber rowids), but it is the one example a reader could reasonably read as sanctioning what CLAUDE.md bans. Nit: consider dropping that clause, or swapping it for VACUUM/rowid renumbering, which is the same hazard without the policy overtone.

🟢-3 — ANALYZE placement is correct; I measured the cost

📁 packages/core/src/db/schema.rs:220-222

Three concerns were raised about this; all three come back benign, and I'd keep it exactly where it is.

Is it meaningful on an empty database? Nearly a no-op — on a fresh DB it writes 2 sqlite_stat1 rows, both for node_fts internals; node doesn't appear at all, because SQLite omits stats for empty tables. Harmless, not useful.

Is running it on every startup a performance concern? No. I timed it on a 50k-node database with a fully populated FTS index: ~10ms, stable across five consecutive runs. ANALYZE scans indexes, not table content, and the cost is flat in repeat invocations. It will not be felt at startup.

Does it belong there at all? Yes, and arguably more than it did in v003. In the old ladder it ran once, inside a migration that ran at most once per database — meaning stats were computed against whatever the table looked like at that instant and never refreshed. Running it on each open is strictly better: stats stay current as the corpus grows, which is what keeps the planner choosing the partial expression indexes. Nit only: the comment says "so the expression indexes above are picked immediately, instead of waiting for organic churn" — accurate for the first open but undersells the recurring case, where the real benefit is keeping stats fresh rather than bootstrapping them.

🟢-4 — The naive ; splitter is safe, including against the newly added comments

📁 packages/core/src/db/schema.rs:159

I extracted SCHEMA_SQL from the source and ran the same split(';') the code does. It yields 23 statements, all well-formed. No statement contains a semicolon inside a string literal or expression — I specifically checked the json_extract(properties, '$.task.status') expressions and the 'local' / '{}' / 'nomic-embed-text-v1.5' defaults.

On the SQL comments: seven of the 23 fragments begin with a -- comment block carried over from the preceding split. This is fine — SQLite accepts leading line comments before a statement, and the comment bodies contain no semicolons. I confirmed by executing the extracted SQL directly against SQLite: all 23 statements execute cleanly. The one case worth having checked was the -- ... 'local' ... comment at line 97-99 (an apostrophe-quoted token inside a comment), which is inert since the splitter is not quote-aware but the comment has no semicolon either.

The guard comment at lines 154-158 correctly states the invariant and explains why triggers and virtual tables are created separately. That comment is doing real work — it is the reason a future author won't paste a trigger into SCHEMA_SQL and break the split — and it's an improvement on v001's version of the same warning.

Nit, well below the bar for this PR: the invariant is enforced only by that comment. If it ever wants belt-and-braces, a debug assertion that no fragment contains BEGIN would make the constraint executable. Genuinely optional — YAGNI probably wins here.

🟢-5 — Losing the per-migration transaction is not a regression

The old runner wrapped each migration in a transaction so a crash never left a database between two versions. The new create_schema executes statement-by-statement outside any transaction, which reads like a durability downgrade but isn't: with no version counter, there is no "between two versions" state to be stranded in, and every statement is IF NOT EXISTS, so an interrupted bootstrap is simply completed by the next open. I verified this — created a database with only the node table, then ran the full schema over it; it completed cleanly and produced all 36 sqlite_master entries. This is a case where removing the version ratchet removed the problem the transaction existed to solve, which is the strongest argument for the change.


Additional verification performed

  • cargo test -p nodespace-core --test schema_test — 3 passed, 0 failed
  • cargo test -p nodespace-core --lib db:: — 93 passed, 0 failed
  • cargo clippy -p nodespace-core --all-targets — zero warnings
  • Full-repo grep across .rs/.ts/.md/.toml/.json/.svelte for db::migrations, migrations::, LATEST_VERSION, run_up_to, apply_migration, migration_name, user_version, backup_before_pending_migrations, prune_backups, MAX_BACKUPS, db_has_data, schema.sql, v00[1-5]_ — zero live code references; only the six doc comments in 🟡-1
  • Structural old-vs-new schema diff over sqlite_master + table_info + foreign_key_list + index_list + index_info for all tables

Recommendation

APPROVE (posted as a comment — GitHub does not permit approving one's own PR)

Net-positive and then some. The schema is equivalent where it matters, the risky parts were done carefully, and the deletion removes a pattern that was actively propagating into new work. 🟡-1 is a mechanical comment sweep and 🟡-2 restores a test the rewrite dropped; both are worth doing but neither should hold the merge. 🟢-1 through 🟢-5 are informational — several are confirmations that the flagged concerns are benign, not requests.

One follow-up beyond this PR's scope, already correctly noted in the PR body: #2638's acceptance criteria still call for a v006 migration and need restating as a column in the bootstrap DDL before that work starts. Worth doing promptly — leaving it unstated is precisely the "cite the ladder as precedent" failure mode this PR exists to eliminate.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verdict: APPROVE (posted as a comment — GitHub rejects self-approval).

Full review: #2698 (comment)

Schema equivalence verified empirically, not by eye: I rebuilt the old v001→v005 ladder as SQL, constructed both databases, and diffed sqlite_master + table_info + foreign_key_list + index_list + index_info across every table. The only difference in the entire schema is the ordinal position of embedding.origin (cid 14 vs 16, where ALTER TABLE had appended it) — behaviorally inert, since every query names its columns explicitly. All tables, indexes, index column orders, FK cascades, STRICT modifiers, defaults, triggers and both virtual tables are identical.

All highest-risk items check out: idx_emb_modified on the v002 (origin, modified_at, node_id, chunk_index) shape; all five v003 partial expression indexes with their WHERE clauses; conflict_participant.node_id correctly carrying no FK while conflict_id cascades; the FTS5 table and all three triggers; the vec0 table. The ;-splitter is safe (23 statements, verified by executing the extracted SQL). ANALYZE measured at ~10ms on a 50k-node DB — keep it. The old schema.sql's (#182/#183) and (#97/#182) issue references were correctly dropped rather than carried into schema.rs.

Two non-blocking items: six doc comments still name deleted files (v001_initial_schema, v003_property_indexes.rs, "migration 1") — the same sweep that correctly fixed three others missed these; and schema_test.rs drops the EXPLAIN QUERY PLAN assertion proving the planner actually uses the partial expression index, keeping only an existence-by-name check. The deleted test's own comment explained why that is the weaker property.

11 of 12 acceptance criteria fully met, the 12th in substance. cargo clippy --all-targets clean; schema_test 3/3; --lib db:: 93/93.

…mments

🟡-1 — Six doc comments still named deleted migration files, so grepping
for them returned dangling pointers. The PR's value is that schema.rs is
the single definition that cannot drift; comments pointing at deleted
files are a softer form of the same drift.

  nodes.rs:4478, query_service_test.rs:1495, mod.rs:87-88,
  connections.rs:74, query_crud.rs:16/35/451 — renamed to db::schema.

  mod.rs:1897 also said busy_timeout was "set by migration 1", which was
  wrong independently of the rename: it is a per-connection session
  setting applied in apply_connection_pragmas, never schema state. Both
  the old v001 doc and the new schema.rs doc say so explicitly.

🟡-2 — Restored the EXPLAIN QUERY PLAN assertion dropped in the test
rewrite. Asserting an index exists by name is strictly weaker than
asserting the planner picks it: SQLite silently ignores an expression
index whose expression doesn't match the query byte-for-byte, so the
name check passes while the query full-scans. That was a coverage
regression I introduced, not a pre-existing gap.

Ported asserting index *coverage* rather than one index by name — both
idx_task_status and idx_task_status_due_date cover this filter and which
one wins is stat-dependent (on a 1-row table the planner picks the
composite). Either proves the expression still matches, which is the
property that can silently break.

Verified the test is load-bearing: breaking both index expressions makes
it fail with "SEARCH node USING INDEX idx_node_type" — the full-partition
scan fallback — rather than passing vacuously.

🟢-2 — Dropped "an ALTER TABLE rebuild" from the FTS rationale for
"a VACUUM that renumbers rowids": same hazard, without reading as
sanctioning the table-rewrite pattern this PR removes.

🟢-3 — The ANALYZE comment undersold the recurring case. It now notes
that running on every open keeps stats current as the corpus grows, and
that the cost is flat (single-digit ms on a populated database).

Skipped, with reasoning:

🟢-1 (note embedding.origin's ordinal moving 16→14) — verified inert:
every embedding query names columns explicitly, no SELECT * and no
positional INSERT, and STRICT mode doesn't care. A comment about a
non-difference is noise; the PR body already records it.

🟢-4 (debug assertion that no SCHEMA_SQL fragment contains BEGIN) —
the reviewer called it "genuinely optional — YAGNI probably wins". The
existing guard comment explains the invariant and why triggers are
created separately, which is what stops the next author breaking it.

🟢-5 (per-migration transaction loss) — informational; the reviewer's own
analysis concluded it is not a regression, since removing the version
ratchet removed the state the transaction protected.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 71a8662b

Addressed 4, skipped 3.

✅ 🟡-1 — Stale doc comments

All six renamed to db::schema: nodes.rs:4478, query_service_test.rs:1495, mod.rs:87-88, connections.rs:74, query_crud.rs:16/35/451.

mod.rs:1897 got a real correction, not just a rename — it claimed busy_timeout was "set by migration 1", which was wrong independently of this PR. It's a per-connection session setting applied in apply_connection_pragmas, never schema state; both the old v001 doc and the new schema.rs doc say so explicitly. Good catch.

Repo-wide grep for db::migrations, v001_initial_schema, v003_property_indexes, migration runner, migration 1, schema.sql now returns nothing. (One unrelated hit in agent/src/local_agent/tools.rs:2275 uses "schema migration" about NodeSpace schema convergence, not DB migrations — left alone.)

✅ 🟡-2 — Restored the EQP assertion

Agreed this was a coverage regression I introduced. Ported into schema_test.rs as task_status_filter_uses_a_partial_expression_index.

Took the suggested adjustment: asserts index coverage rather than one index by exact name, since idx_task_status and idx_task_status_due_date both cover the filter and which one wins is stat-dependent — on a 1-row table the planner picks the composite, exactly as predicted.

Verified the test is load-bearing rather than trusting that it passes: breaking both index expressions ($.task.status → $.task.WRONG) makes it fail with SEARCH node USING INDEX idx_node_type — the full-partition-scan fallback — then restored. So it catches precisely the silent byte-for-byte mismatch the deleted test's comment warned about.

✅ 🟢-2 — FTS rationale

Dropped "an ALTER TABLE rebuild" for "a VACUUM that renumbers rowids". Same hazard, without reading as sanctioning the table-rewrite pattern this PR removes.

✅ 🟢-3 — ANALYZE comment

Now notes that running on every open keeps stats current as the corpus grows (not just bootstrapping them), and that the cost is flat — single-digit ms on a populated database, per your measurement.

⏭️ Skipped

🟢-1 (note embedding.origin's ordinal 16→14) — your own verification found it inert: every embedding query names columns explicitly, no SELECT *, no positional INSERT, and STRICT doesn't care. A code comment about a non-difference is noise; the PR body already records it for anyone diffing an old dev database.

🟢-4 (debug assertion that no SCHEMA_SQL fragment contains BEGIN) — you called it "genuinely optional — YAGNI probably wins", and I agree. The existing guard comment states the invariant and explains why triggers are created separately, which is what actually stops the next author pasting one in.

🟢-5 (per-migration transaction loss) — informational; your analysis concluded it isn't a regression, since removing the version ratchet removed the state the transaction existed to protect.


Verification: schema_test 4/4 · quality:fix clean (eslint, svelte-check 2532 files, design tokens, cargo fmt, clippy -D warnings) · full pre-push gate green.

Thanks for the empirical schema diff — reconstructing the ladder and comparing sqlite_master + table_info + foreign_key_list + index_info is a much stronger check than I'd have gotten by eye, and finding the ordinal shift as the only difference is exactly the confirmation this change needed.

@malibio
malibio merged commit 2be681f into main Sep 17, 2026
@malibio
malibio deleted the issue-2688-collapse-migration-ladder branch September 17, 2026 08:43
malibio added a commit that referenced this pull request Sep 17, 2026
* Store a relationship's reverse name as a queryable column (closes #2638)

An edge is named from both ends, but only the declaring side's name was
ever a column. The reverse lived inside the row's `properties` JSON blob
for schema-declared relationships, and nowhere at all for the four
built-in structural ones — `has_child` et al. predate the
`SchemaRelationship` naming convention and have no declaration behind
them, so `child_of` did not exist as data anywhere.

Adds `relationship.reverse_relationship_type`, plus `idx_rel_reverse` on
`(out_node, reverse_relationship_type)` mirroring `idx_rel_out`, so
reading an edge from the end that did not declare it is a column lookup
rather than a scan-and-decode.

Two sources feed the column, and only one of them is new:

- A schema-declared relationship already carries the author's own
  `SchemaRelationship.reverse_name` — required rather than derived,
  because naming an inverse is a modeling decision only the author can
  make. `set_schema_declarations` (and its `_in_tx` twin) now writes that
  value straight into the column, on both the INSERT and UPDATE paths so
  a changed declaration updates it too.

- The four built-ins get fixed inverses, defined once in
  `BUILTIN_RELATIONSHIPS`: has_child→child_of, member_of→has_member,
  mentions→mentioned_by, has_role→role_of. `has_child`'s was set by the
  issue; the other three were left to implementation. Rule: `has_X` →
  `X_of`, verbs take the passive, so `has_child`/`child_of` and
  `has_role`/`role_of` invert identically. `member_of` → `has_member`
  necessarily breaks the pattern, being already named from the member's
  side; `contains` was rejected as too easily confused with `has_child`,
  which is the real containment edge.

`BUILTIN_RELATIONSHIP_NAMES` is now derived from that table rather than
duplicating the names.

Every write path populates the column. The literal-typed sites carry the
reverse name inline, so each statement reads self-describing; the two
generic paths take `rel_type` dynamically and derive it in SQL via
`builtin_reverse_name_sql`, following the existing
`builtin_exclusion_sql` precedent in the same module. That covers 17
production sites across three modules plus 2 test fixtures.

Because "did you get all of them?" is the failure mode here — a
reverse-traversal query that silently misses rows written by one
forgotten path is worse than no column — the test that matters asserts
no row in the table may have the column unset, after exercising a spread
of write paths. Named write-path tests would each pass while leaving
that hole open.

Note the column stays nullable: a row with no reverse name is a bug, not
a supported state, and NOT NULL would have turned that assertion into a
constraint error at the wrong layer with no diagnostic about which path
was at fault.

Also adds a debug assertion that every `SCHEMA_SQL` fragment begins a
statement. This was the reviewer's 🟢-4 on #2698, which I skipped as
YAGNI — then immediately hit: a semicolon inside the new column's comment
split the CREATE TABLE in half. It is a second line of defense rather
than a first (SQLite rejects the leading half before the malformed tail
is reached), but it names the cause instead of reporting `incomplete
input`.

No backfill: per the pre-release policy there are no existing rows to
carry forward, and after #2688 there is no migration mechanism that
could. Reset the database.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Address review: carry the declaration's reverse name onto instance edges

🔴-1 — Declared relationships' INSTANCE edges were writing NULL.

The bug, and my own doc comment asserting the opposite, both rested on
conflating two different rows. `set_schema_declarations` writes the
DECLARATION edge (schema→schema: "a task may have a `blocks`"). It does
not write the INSTANCE edge (task→task: an actual `blocks` between two
real tasks). Instance edges of declared relationships go through
`create_generic_relationship`, where the built-in `CASE` finds no match
and a `CASE` without `ELSE` yields NULL.

So every user-declared relationship — `blocks`, `tasks`,
`reported_tasks`, and anything a user defines — got NULL, which is the
larger of the two edge populations and exactly what the column exists to
serve. Reverse traversal would have returned nothing for them while
working fine for `child_of`, and #2641's resolver would have inherited
that split.

Fixed by threading the declaration's `reverse_name` from the service
layer, where schema validation already has it in hand, into both
`create_generic_relationship` twins as an `Option<&str>`. The SQL uses
`COALESCE(?8, <builtin CASE>)`: a declared name when passed, the derived
built-in otherwise, so neither kind can be NULL.

🟡-1 — The completeness guard passed vacuously for most paths.

Confirmed by mutation: NULLing all seven `has_child` sites in nodes.rs
previously left every test green. The guard's design was right — it
caught 🔴-1 the instant the path ran — but its setup only reached about
three of 18 production sites.

The setup now also drives a declared instance edge (the `CASE`-miss
branch, where the bug was), a re-parenting `move_node`, the auto-ordering
`append_child_edge`, the bulk cold-sweep attach, and a collection add.
Re-ran the mutations against the new setup: NULLing the nodes.rs sites
now fails three tests.

Also added a correctness check, not just a presence check. The guard only
looked for NULL/empty, so a path writing a *wrong* value still passed —
verified by tagging `append_child_edge` with a bogus name and watching it
ship green. Built-in rows are now asserted to carry the reverse their
forward name maps to.

🟡-2 — `schema_declared_edges_store_the_authors_reverse_name` filtered on
`reverse_relationship_type IS NOT NULL`, so a row regressing to NULL —
the exact failure in its title — was excluded before the assertion saw
it. It would not have caught 🔴-1. Now reads every declared row and
asserts the stored value IS the declaration's name.

Writing that turned up a subtlety worth recording: `tasks` is declared
twice, on `project` (reverse `project`) and on `person` (reverse
`assignee`), so a forward name does not identify a declaration. The
expectation table is keyed by forward name and therefore excludes it,
with a comment explaining why rather than leaving the omission to look
like an oversight.

🟡-3 — `reverse_name` is a required `String`, but nothing rejected `""`.
An empty one stores verbatim, satisfies every NULL check, populates the
index and names nothing. Both `set_schema_declarations` twins now reject
it alongside the existing reserved-name and duplicate-name checks.

🟢-1 — Documented that `builtin_reverse_name_sql`'s `type_expr` is
interpolated unescaped and must be a placeholder or column name.

🟢-7 — `BUILTIN_RELATIONSHIP_NAMES` spelled out `[0].0`…`[3].0` would
silently drop a fifth entry. Added a const length assertion.

Skipped: 🟢-3's suggestion to revisit NOT NULL once every path provably
writes a value. It is a fair follow-up but a schema change beyond this
PR's scope, and the correctness check above now covers more than NOT NULL
would (it catches wrong values, not just missing ones).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Address re-review: cover the transactional path's fix

🟡-4 — `create_relationship_in_tx`'s half of the NULL fix had no test.

Confirmed by mutation before writing one: reverting only the in-tx
threading, leaving the direct path intact, left all 29 core test binaries
green. Reintroducing the bug on that path was completely invisible.

The path is `pub(crate)` and reached in production only through a
playbook `add_relationship` action, so no integration test can drive it —
and the existing invariant tests only exercise `member_of`, a built-in
whose reverse is derived in SQL and therefore never touches the parameter
that carried the bug. That is why extending the integration suite could
not have closed this.

Added an in-crate test that drives `with_transaction` →
`create_relationship_in_tx` with `blocks`, a declared relationship, and
asserts the stored reverse is `blocked_by`. Verified load-bearing: with
the in-tx threading reverted it fails `left: None, right:
Some("blocked_by")` — the exact NULL regression.

This was the one item inconsistent with the PR's own "did you get all of
them?" claim — one of the two paths that carried the bug had no guard
against its return. Worth the few lines.

🟢-8 — Added `reported_tasks` → `creator` to the expectation table. It is
uniquely declared, so it costs nothing.

Not addressed, deliberately:

🟡-5 (8 literal-typed sites still individually unexercised:
nodes.rs:227/2567/2948/3030/3091, relationships.rs:117/1242/1347). Each
is a static inline literal in an INSERT whose only failure mode is a
hand-edit typo, and the whole-table guard already catches any newly added
path that forgets the column — which is the regression that actually
happens. Driving all eight would need fixtures for sync cold-sweep and
streaming-create paths whose setup cost exceeds what they would protect.
Recorded here so the gap is known rather than assumed closed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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.

Collapse the five-step migration ladder into a single current-shape schema bootstrap

1 participant