Repository navigation
Store a relationship's reverse name as a queryable column - #2709
Conversation
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]>
Code Review: PR #2709 — Store a relationship's reverse name as a queryable columnReview Type: Initial review (no prior reviews or comments on this PR) SummaryThis is a well-constructed change with unusually good commit/PR narrative — the reasoning about why the completeness guard is the test that matters is exactly right, and the reverse-name derivation rule ( However, I found one functional gap that I was able to reproduce, plus a test-efficacy problem that hides it. Both go to the exact question the PR sets as its own bar — "did you get all of them?" — so I'm raising them rather than waving them through. Verdict: REQUEST CHANGES on 🔴-1. Everything else is improvement-or-below. Requirements Check against #2638Assessed against the acceptance criteria as restated by the spec-update comment (no
Criterion 2 is where the gap lives. It is met literally — declaration edges (schema → schema) do store the author's reverse name. But instance edges of those same declared relationships do not. See 🔴-1. Completeness audit (independent enumeration)I enumerated every write to the Count correction: I find 18 production sites + 2 test fixtures, not 17 + 2. Every one of the 20 populates the column. Mapped to their enclosing functions:
No Desync check (UPDATE paths): I checked all 7
Findings🔴 Critical🔴-1 —
(CASE ?4 WHEN 'member_of' THEN 'has_member' WHEN 'has_child' THEN 'child_of'
WHEN 'mentions' THEN 'mentioned_by' WHEN 'has_role' THEN 'role_of' END)A That premise does not hold. I reproduced this. Adding a probe to the completeness test that creates two The completeness guard does catch it — the moment the path is exercised. It simply never exercises it (see 🟡-1). Why this is critical rather than an improvement: it defeats the stated purpose for the larger of the two edge populations. Built-in edges get their reverse name; declared instance edges — The fix needs the declaration's
The first is clearer and avoids widening the generated SQL. 🟡 Improvements🟡-1 — The completeness guard exercises far less than it appears to, and passes vacuously for most paths The test's framing ("after exercising a spread of write paths") oversells what it reaches. I verified this by mutation testing. Experiment A: I removed Experiment B: I changed Experiment C: I tagged So of 18 production sites, the suite exercises roughly three: The guard's design is right — asserting over the whole table is the correct shape, and it caught 🔴-1 immediately once the path ran. The problem is purely the setup's coverage. Concretely, the setup should additionally drive: a cross-parent Nit within this: the 🟡-2 — The query filters The 🟡-3 — Nothing rejects an empty
A 🟢 Confirmations and minor notes🟢-1 — SQL injection: no risk. 🟢-2 — Parameter renumbering: verified correct at all 6 changed sites. I walked each placeholder against its
No silent column-swap anywhere. 🟢-3 — Nullable was the right call, but the reasoning should be inverted. The PR argues nullable + test gives a better diagnostic than a The reason to keep it nullable anyway is different: 🟢-4 — The debug assertion's logic is correct, with one narrow false-negative. 📁 It strips leading blank and False negatives: a 🟢-5 — Naming: no collisions, one convergence worth knowing about. I grepped
This is convergent, not conflicting — Also note 🟢-6 — Duplicate storage of the reverse name. For declaration edges the reverse name now lives in both the column and the serialized 🟢-7 — Nit: 🟢-8 — Standards: all clean. No lint suppression, no RecommendationREQUEST CHANGES 🔴-1 is a real, reproduced correctness gap: declared instance edges — the majority of non-structural edges a real database will hold — get 🟡-1 and 🟡-2 are what let 🔴-1 through, and I'd fix them in the same pass: the completeness guard's design is right and it catches the bug the instant the path is exercised, so extending its setup to drive a declared instance edge, a 🟡-3 and the 🟢 items are non-blocking. Everything else about this change — the enumeration discipline, the parameter renumbering, the SQL derivation helper, the index, the naming rationale, the no-backfill posture, the commit message — is solid work, and the completeness-over-per-path testing instinct is the correct one. It just needs the setup to match the ambition. |
malibio
left a comment
There was a problem hiding this comment.
Verdict: REQUEST CHANGES (posted via --comment — GitHub rejects --approve/--request-changes on a self-authored PR).
Full review: #2709 (comment)
🔴-1 (blocking): create_generic_relationship writes NULL for every declared instance edge. The CASE in builtin_reverse_name_sql has no ELSE, and its doc comment's premise — that declared edges get their reverse from set_schema_declarations — holds only for declaration rows (schema→schema), not instance rows (task→task). Reproduced: a blocks edge between two tasks lands reverse_relationship_type IS NULL. That silently defeats reverse traversal for every user-declared relationship, which is the failure mode the PR body itself calls "worse than no column at all."
🟡-1: The completeness guard passes vacuously for ~15 of 18 production sites. Mutation-tested: deleting the column from create_child_node_atomic, and corrupting append_child_edge, both leave all 5 tests green. Only create_has_child_edge_in_tx is actually reached. The guard's design is right and it catches 🔴-1 the instant that path runs — it just never runs it.
🟡-2: schema_declared_edges_store_the_authors_reverse_name filters WHERE reverse_relationship_type IS NOT NULL, so the regression it's named for is excluded before the assertion sees it. The seen > 0 guard does prevent full vacuity (core schemas seed 6 such rows unconditionally), but it can't fail on a NULL.
Verified clean: all 18 production + 2 fixture write sites populate the column (count is 18, not 17); no UPDATE desyncs relationship_type from the reverse; parameter renumbering correct at all 6 changed sites including the ?3/?4→?4/?5 shift; no injection risk; no backfill or data migration; no lint suppression; no .md docs in this repo; reverse names collide with nothing (mentioned_by converges with the existing RelationshipType::MentionedBy, same semantics — a point in its favor).
Nice work on the enumeration discipline and the commit message. The completeness-over-per-path testing instinct is the correct one; the setup just needs to match it.
🔴-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]>
Review addressed —
|
Re-Review: PR #2709 —
|
| Finding | Status |
|---|---|
| 🔴-1 — declared instance edges wrote NULL | ✅ Fixed, and genuinely regression-tested |
| 🟡-1 — completeness guard passed vacuously | 🟨 Substantially improved, partially addressed (8 of 14 literal sites now covered, was ~3) |
| 🟡-2 — test filtered out its own regression | ✅ Fixed |
🟡-3 — empty reverse_name unrejected |
✅ Fixed (backstop; primary rejection already existed) |
🟢-1 — document type_expr interpolation |
✅ Addressed |
🟢-7 — BUILTIN_RELATIONSHIP_NAMES length drift |
✅ Addressed (const assertion) |
🟢-3 — NOT NULL follow-up |
⏭️ Skipped with sound reasoning — agreed, out of scope |
Addressed: 6. Partially addressed: 1. New findings: 2 (one 🟡, one 🟢 nit).
Verification of 🔴-1
Confirmed fixed, independently. I reverted the threading (declared_reverse_name = None at both sites) and re-ran:
no_write_path_leaves_the_reverse_name_unpopulated ... FAILED
every relationship row must carry its correct reverse name;
these write paths did not: blocks (1 rows)
That is exactly the bug, caught by exactly the guard that missed it before. The fix is real and the regression test holds.
Parameter binding is correct. libsql::params![] is positional: the 8th element is reverse_name.map(str::to_string), so ?8 resolves to it, and rel_type remains 4th so the CASE ?4 still reads the forward name. Verified at both relationships.rs:521 and :1416.
COALESCE semantics — not a hazard. A caller could pass an explicit reverse name for a built-in and override the derived one. In practice this is unreachable: the only non-test callers are create_relationship/create_relationship_in_tx, both of which populate declared_reverse_name strictly inside the else branch of if is_builtin. A built-in therefore always passes None. The precedence (passed value wins) is also the right default — where a declaration exists it is authoritative.
Both twins fixed. create_relationship_in_tx (relationship.rs:820) mirrors the non-tx version correctly. See 🟡-4 below on its test coverage.
Mutation Testing (the load-bearing verification)
I re-ran the prior review's methodology, tagging each site's reverse-name literal with 'TAG_BOGUS' — which exercises both the NULL check and the new correctness check — and running reverse_relationship_name_test per mutation. Every mutation was reverted; git status is clean.
packages/core/src/db/sqlite_store/nodes.rs — 2 of 7 covered
| Line | Function | Mutation caught? |
|---|---|---|
| 227 | create_child_node_atomic |
❌ green |
| 346 | create_has_child_edge_in_tx |
✅ 3 tests fail |
| 2459 | move_node |
✅ 1 test fails |
| 2567 | move_children_to_parent |
❌ green |
| 2948 | bulk_create_hierarchy |
❌ green |
| 3030 | bulk_create_hierarchy_in_tx |
❌ green |
| 3091 | create_node_streaming |
❌ green |
packages/core/src/db/sqlite_store/relationships.rs — 3 of 6 covered
| Line | Function | Mutation caught? |
|---|---|---|
| 117 | create_mention |
❌ green |
| 331 | append_child_edge |
✅ 1 test fails |
| 641 | add_to_collection |
✅ 1 test fails |
| 1028 | bulk_create_has_child |
✅ 1 test fails |
| 1242 | bulk_add_to_collections |
❌ green |
| 1347 | bulk_create_mentions |
❌ green |
Generic paths
| Path | Mutation caught? |
|---|---|
create_generic_relationship declared threading |
✅ fails with blocks (1 rows) |
create_generic_relationship_in_tx declared threading |
❌ green across the entire 29-binary core suite |
Net: coverage went from ~3 sites to 8. The author's claim that the nodes.rs mutation "now fails three tests" is accurate as an aggregate, though it holds because site 346 is reached — five nodes.rs sites individually remain silent. This is real, measurable improvement, and the highest-value sites (the generic declared path, the auto-order append, the bulk attach, the collection add, re-parenting) are now covered.
Requirements Check
| # | Criterion | Status |
|---|---|---|
| 1 | Column in SCHEMA_SQL |
✅ schema.rs:77 |
| 2 | Declaration rows store reverse_name |
✅ Both twins, INSERT + UPDATE |
| 2b | Instance rows of declared relationships store it | ✅ Now fixed — was the 🔴-1 gap |
| 3 | has_child writes child_of at every site |
✅ All sites populate (coverage varies — see 🟡-5) |
| 4 | Built-in reverses decided and documented | ✅ BUILTIN_RELATIONSHIPS |
| 5 | Indexed | ✅ idx_rel_reverse |
| 6 | No backfill / data migration | ✅ Verified — no UPDATE ... SET reverse_relationship_type outside the declaration-update path |
| 7 | Tests pass | ✅ cargo test -p nodespace-core --tests → 29 binaries, 0 failures |
| 8 | Clippy clean | ✅ cargo clippy -p nodespace-core --all-targets emits nothing |
Verified claims. The tasks double-declaration is real: core_schemas.rs:435 declares it on project (reverse project) and :1400 on person (reverse assignee). Excluding it from a forward-name-keyed table is correct, and the comment explaining why is the right call — it does not leave a meaningful hole, since three other declared relationships are still checked against their declarations.
The new correctness check works and has no false positives. It resolves expectations through builtin_reverse_name rather than a second hardcoded table, so it cannot drift from BUILTIN_RELATIONSHIPS. I confirmed it fires on a wrong value — every ✅ row above is a TAG_BOGUS mutation caught by this check, not by the NULL check.
Findings
🟡 Improvements
🟡-4 (new) — create_generic_relationship_in_tx's declared-name fix has zero test coverage
📁 packages/core/src/services/node_service/relationship.rs:820
The _in_tx twin received the identical fix, and the code is correct. But I set declared_reverse_name = None at line 820 only — leaving the non-tx path intact — and ran the entire nodespace-core test suite: 29 binaries, 0 failures. Reintroducing 🔴-1 on the transactional path is invisible.
The cause: this path is reached via the playbook add_relationship action (playbook/actions.rs:1514), and playbook_invariant_integration_test.rs only ever exercises member_of (:240, :331) — a built-in, which takes the CASE branch and never touches the new parameter. Nothing drives a declared relationship through create_relationship_in_tx.
This matters more than a generic coverage gap because the two twins are a known duplication pair. The entire thesis of 🔴-1 was that a path can silently write NULL; one of the two paths that had the bug still has no guard against its return. A playbook invariant whose add_relationship action creates a blocks edge — or a direct create_relationship_in_tx call in the guard test's setup — would close it in a few lines, and is the natural fifth line in the setup that was already extended.
Principle: duplicated logic needs its test at both copies. A fix without a failing-first test is a fix that can regress silently.
🟡-5 (carried forward, partially addressed) — eight literal-typed sites remain unexercised
📁 nodes.rs:227, 2567, 2948, 3030, 3091 · relationships.rs:117, 1242, 1347
Per the tables above, create_child_node_atomic, move_children_to_parent, both bulk_create_hierarchy variants, create_node_streaming, create_mention, bulk_add_to_collections and bulk_create_mentions all ship green under a TAG_BOGUS mutation.
To be clear this is not a blocker: these are all literal-inline 'child_of' / 'mentioned_by' / 'has_member' strings inside a static SQL string. The failure mode is a hand-edit typo, far less likely than the dynamic-derivation bug 🔴-1 actually was, and the guard's whole-table shape means any newly added write path is caught the moment its rows exist. The dangerous paths are covered. I record it so the residual hole is known rather than assumed closed, since the PR narrative reads as though the guard is now comprehensive.
🟢 Notes
🟢-8 (new) — Nit: reported_tasks could join the expectation table at no cost
📁 packages/core/tests/reverse_relationship_name_test.rs:218-222
The table covers blocks, relates_to, duplicates. reported_tasks (core_schemas.rs:1411, reverse creator) is declared exactly once across all core schemas, so it satisfies the table's own stated key constraint and would widen checked_against_declaration for free. The tasks exclusion is correct and well documented; reported_tasks's omission reads as incidental rather than reasoned.
🟢-9 — the 🟡-3 rejection is a backstop, not the primary gate, and is untested.
📁 relationships.rs:1785-1795, :1921-1931
Worth recording that a blank reverseName was already rejected before this commit, at the schema/API layer — schema_test.rs:2945 (create_schema_rejects_null_or_blank_reverse_fields) covers json!(null) and json!(" "). The new store-level check is therefore defense-in-depth for callers that construct SchemaRelationship directly and bypass handle_create_schema. That is a legitimate and cheap guard at the right layer and I would keep it. It has no test of its own, but given the outer gate is tested, I would not ask for one. No regression: the full suite is green, so no seeded schema or existing test declares an empty reverse name.
🟢-10 — the 7 test-caller None updates are all correct.
I checked each. mod.rs:773 (member_of), mod.rs:788 / nodes.rs:4328 (mentions), nodes.rs:4388 (has_child) are built-ins — None is exactly right, the CASE derives them. The three assigned_to calls (node_service/mod.rs:6244, 6464, 6468) are the interesting case: assigned_to is a declared type, so None means those rows land NULL.
This is acceptable and masks nothing. They are store-level tests calling create_generic_relationship directly, deliberately bypassing the service layer that resolves the declaration; they assert query and cardinality behavior keyed on relationship_type, never on the reverse column. Passing a hand-written reverse name there would fabricate a value the store has no business deriving. The completeness guard runs against its own database and is unaffected by these fixtures.
🟢-11 — standards clean. No lint suppression, no #[allow] / #[deprecated], no backfill or data migration, no .md docs added to this repo, no issue numbers in code comments or SQL. The const assertion compiles. Clippy silent. Docs correctly went to nodespace-docs (0393722).
Recommendation
APPROVE — with 🟡-4 recommended before merge, and 🟡-5 / 🟢-8 as optional follow-ups.
🔴-1 is properly fixed, not nominally fixed: I reproduced the failure by reverting the change and watched the guard catch it with the exact message. The COALESCE is correct, the binding is right, both twins got the fix, and the empty-name and const-assertion items are all genuinely addressed.
The mutation testing shows the strengthened guard went from ~3 covered sites to 8, including every dynamic path — the ones where a real bug could hide. The new wrong-value check is a genuine improvement over presence-only, and it is what caught most of my mutations.
The one thing worth closing is 🟡-4. The _in_tx twin carries the same fix for the same bug, and nothing across 29 test binaries notices if it is removed. Given this PR's own thesis — that "did you get all of them?" is the failure mode, and a silently-NULL path is worse than no column — leaving one of the two repaired paths unguarded is the single item thematically inconsistent with the rest of the work, and it is a few lines in a setup already extended once.
Everything else here is strong: the commit message's diagnosis is honest and precise about why the original reasoning failed, the tasks double-declaration is a real subtlety that was reasoned about rather than papered over, and skipping the NOT NULL change with a stated rationale is the right scope call.
malibio
left a comment
There was a problem hiding this comment.
Re-review complete — see the detailed report above (#issuecomment-5712271728).
APPROVE, with one recommendation.
🔴-1 is genuinely fixed and regression-tested: reverting the declared-name threading makes the completeness guard fail with blocks (1 rows). Parameter binding on ?8 is correct, COALESCE precedence is sound and unreachable as a hazard, and both twins got the fix. 🟡-2, 🟡-3, 🟢-1 and 🟢-7 are all addressed. Mutation testing confirms the guard went from ~3 covered write sites to 8, including every dynamic path.
One new 🟡: create_generic_relationship_in_tx's half of the 🔴-1 fix has no test — setting declared_reverse_name = None at relationship.rs:820 alone leaves all 29 core test binaries green. Recommended before merge, since it is one of the two paths that carried the original bug.
🟡-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]>
Re-review addressed —
|
Closes #2638.
What and why
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
propertiesJSON for schema-declared relationships, and nowhere at all for the four built-in structural ones —has_childand friends predate theSchemaRelationshipnaming convention and have no declaration behind them, sochild_ofdid not exist as data anywhere.Adds
relationship.reverse_relationship_typeplusidx_rel_reverseon(out_node, reverse_relationship_type), mirroringidx_rel_out. Reading an edge from the end that did not declare it becomes a column lookup rather than a scan-and-decode.Two sources, only one of them new
Schema-declared relationships already carry 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_declarationsand its_in_txtwin now write that value 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_childchild_ofmember_ofhas_membermentionsmentioned_byhas_rolerole_ofhas_child's was set by the issue; the other three were left to implementation. Rule:has_X→X_of, verbs take the passive — sohas_child/child_ofandhas_role/role_ofinvert identically.member_of→has_membernecessarily breaks the pattern, being already named from the member's side.containswas considered and rejected as too easily confused withhas_child, which is the real containment edge. These become user-visible query keys once #2641 lands, so they are recorded on the issue too rather than only here.BUILTIN_RELATIONSHIP_NAMESis now derived from that table instead of duplicating the names.Covering every write path
17 production sites across three modules, plus 2 test fixtures. The literal-typed sites carry the reverse name inline so each statement reads self-describing; the two generic paths take
rel_typedynamically and derive it in SQL viabuiltin_reverse_name_sql, following the existingbuiltin_exclusion_sqlprecedent in the same module.The test that matters asserts no row in the table may have the column unset, after exercising a spread of write paths. "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 at all, and named per-path tests would each pass while leaving that hole open.
The column stays nullable deliberately: an unset row is a bug, not a supported state, and
NOT NULLwould turn that assertion into a constraint error at the wrong layer with no diagnostic about which path was at fault.A note on the debug assertion
create_schemagains a debug assertion that everySCHEMA_SQLfragment begins a statement. This was the reviewer's 🟢-4 on #2698, which I skipped as YAGNI — and then hit within the hour: a semicolon inside this PR's new column comment split theCREATE TABLEin half, surfacing asSQLite failure: incomplete input. 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.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.
Testing
New
reverse_relationship_name_test.rs(5 tests): built-in names are defined and unambiguous (no duplicate forward/reverse, no reverse colliding with a forward name),has_childedges storechild_of, an edge is findable from the target end by reverse name, declared edges store the author's own name, and the completeness guard above.schema_test.rsgains the column and index to its shape assertions.cargo test -p nodespace-core --tests: 29 binaries, 0 failures. Full pre-push gate green.Docs
typed-relationships.mdanddata-layer.mdupdated in nodespace-docs (6d6bc5f). The former documentedreverseNameas real and load-bearing but only as a properties field, and said nothing about the built-ins having no reverse name at all.Unblocks
#2641 (direction-aware
graph_resolver.rs) needshas_child's reverse name to exist as real data — that is now true. #2641 in turn unblocks #2636.🤖 Generated with Claude Code