Repository navigation
Collapse the five-step migration ladder into a single current-shape schema bootstrap - #2698
Conversation
…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]>
Pragmatic Code Review — PR #2698Review Type: Initial review (no prior reviews or comments on this PR) SummaryThis 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: I verified schema equivalence empirically rather than by eye. I reconstructed the old The areas flagged as highest-risk all check out:
Standards compliance is clean: no lint suppressions, no The findings below are two stale-comment cleanups and one test-coverage regression. None of them block merge. Requirements Check — issue #2688 acceptance criteria
11 of 12 fully met; #5 met in substance with cosmetic residue. Findings🟡 Important🟡-1 — Six doc comments still name deleted files, so Acceptance criterion #5 says "no reference to
Why it matters: the stated value of this PR is that 🟡-2 — 📁 The new test asserts
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 This is a coverage regression introduced by the rewrite, not a pre-existing gap. Note the asymmetry: the analogous sweep index Suggested: port the deleted test into 🟢 Suggestions🟢-1 — 📁 The sole structural difference I found between old and new. Under the ladder, I checked whether anything depends on ordinal position: every query against 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 🟢-2 — The 📁 Keeping the code is justified. The mechanism is genuinely cheap and genuinely load-bearing: it reads two Two of the three cited causes hold cleanly under current policy (interrupted write; bulk restore). The third — "or an 🟢-3 — 📁 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 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 📁 I extracted On the SQL comments: seven of the 23 fragments begin with a 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 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 🟢-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 Additional verification performed
RecommendationAPPROVE (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 |
malibio
left a comment
There was a problem hiding this comment.
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]>
Review addressed —
|
* 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]>
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 singleCREATE TABLEbatch 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
v004in its Technical Specifications as the precedent migration to follow. Following it faithfully would have meant writing a backfill of the new column from existingpropertiesJSON — exactly what the no-data-migration policy prohibits.v002likewise 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— onecreate_schema()holding the current DDL, idempotent viaIF NOT EXISTSso reopening a database is a no-op. Folds in every migration's final effect:embedding.originand theorigin-leadingidx_emb_modified(v002), the partial expression indexes (v003), and the conflict journal tables (v005).Deleted
v001–v005andmigrations/mod.rs(942 lines)PRAGMA user_versionratchet:LATEST_VERSION,run_up_to,apply_migration,migration_name, newer-than-supported guardbackup_before_pending_migrations,db_has_data,prune_backups,MAX_BACKUPS,VACUUM INTOsnapshotsdb/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.rsis 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 reachingnodeby 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:idx_emb_modifiedlands on the v002 shape (originleading), not v001's — the cloud-push sweep depends on itThe 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
v006migration forreverse_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