Skip to content

Store a relationship's reverse name as a queryable column - #2709

Merged
malibio merged 3 commits into
mainfrom
issue-2638-reverse-rel-name-column
Sep 17, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-2638-reverse-rel-name-column

Conversation

@malibio

@malibio malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

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 properties JSON for schema-declared relationships, and nowhere at all for the four built-in structural ones — has_child and friends 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. 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_declarations and its _in_tx twin 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:

forward reverse
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 considered and rejected as too easily confused with has_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_NAMES is 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_type dynamically and derive it in SQL via builtin_reverse_name_sql, following the existing builtin_exclusion_sql precedent 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 NULL would 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_schema gains a debug assertion that every SCHEMA_SQL fragment 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 the CREATE TABLE in half, surfacing as SQLite 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_child edges store child_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.rs gains 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.md and data-layer.md updated in nodespace-docs (6d6bc5f). The former documented reverseName as 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) needs has_child's reverse name to exist as real data — that is now true. #2641 in turn unblocks #2636.

🤖 Generated with Claude Code

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]>
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #2709 — Store a relationship's reverse name as a queryable column

Review Type: Initial review (no prior reviews or comments on this PR)


Summary

This 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 (has_X → X_of, verbs take the passive) is defensible and documented. Parameter renumbering is correct at every site I checked. Clippy is clean, there are no lint suppressions, no #[allow(dead_code)], no #[deprecated], no backfill, and no .md docs added to this repo.

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 #2638

Assessed against the acceptance criteria as restated by the spec-update comment (no v006 migration expected — #2688 removed the ladder).

# Criterion Status
1 reverse_relationship_type TEXT column in SCHEMA_SQL ✅ packages/core/src/db/schema.rs:71-76
2 set_schema_declarations/_in_tx write reverse_name into the column ✅ Both INSERT and UPDATE paths, both twins
3 has_child edges write child_of at every site that creates one ✅ All 10 has_child INSERT sites
4 member_of/mentions/has_role get decided, documented reverse names ✅ has_member/mentioned_by/role_of, in BUILTIN_RELATIONSHIPS
5 Indexed for lookup by reverse name ✅ idx_rel_reverse ON (out_node, reverse_relationship_type)
6 No backfill; fresh DB populates from write time ✅ Verified — zero backfill/UPDATE ... SET reverse_relationship_type outside the declaration-update path
7 nodespace-docs updated ✅ Out of this repo, per PR body (6d6bc5f)
8 Tests pass ✅ reverse_relationship_name_test 5/5, schema_test 4/4
9 quality:fix clean ✅ cargo clippy -p nodespace-core --all-targets emits nothing

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 relationship table across all of packages/, all file types, including dynamically-built SQL, batch inserts, and INSERT OR IGNORE / OR REPLACE forms.

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:

sqlite_store/nodes.rs (7 production + 1 fixture)

  • :227 create_child_node_atomic · :346 create_has_child_edge_in_tx · :2459 move_node · :2567 move_children_to_parent · :2948 bulk_create_hierarchy · :3030 bulk_create_hierarchy_in_tx · :3091 create_node_streaming
  • :4573 seed_flat_subtree (test fixture)

sqlite_store/relationships.rs (10 production)

  • :113 create_mention · :327 append_child_edge · :514 create_generic_relationship_in_tx · :633 add_to_collection · :1020 bulk_create_has_child · :1234 bulk_add_to_collections · :1339 bulk_create_mentions · :1406 create_generic_relationship · :1836 set_schema_declarations · :1955 set_schema_declarations_in_tx

services/node_service/hierarchy.rs (1 fixture)

  • :1204 seed_flat_children (test fixture)

No REPLACE INTO relationship, no dynamic table-name interpolation, and no non-Rust (TS/SQL/Svelte) writer exists. Nothing is missed.

Desync check (UPDATE paths): I checked all 7 UPDATE relationship sites. None mutates relationship_type, so the two columns cannot drift:

  • conflicts.rs:461 re-points in_node/out_node only
  • mod.rs:1128, relationships.rs:1509, nodes.rs:2259, nodes.rs:2438 touch properties only
  • relationships.rs:1818/:1937 correctly update the reverse alongside the declaration

Findings

🔴 Critical

🔴-1 — create_generic_relationship writes NULL for every declared instance edge
📁 packages/core/src/db/sqlite_store/relationships.rs:1406 and :514

builtin_reverse_name_sql("?4") generates:

(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 CASE with no ELSE yields NULL on no match. The doc comment says that is intentional — "NULL for anything not built-in, which is correct: a schema-declared edge's reverse name comes from its own declaration, written explicitly by set_schema_declarations."

That premise does not hold. set_schema_declarations writes the declaration edge (schema node → schema node, the row that says "a task may have a blocks"). It does not write the instance edge (task → task, the actual blocks between two real tasks). Instance edges of declared relationships flow through NodeService::create_relationship → store.create_generic_relationship (services/node_service/relationship.rs:697) — the generic path, where the CASE misses and the column lands NULL.

I reproduced this. Adding a probe to the completeness test that creates two task nodes and a blocks edge between them:

PROBE create_relationship blocks -> true
PROBE instance edge blocks: reverse IS NULL = 1
panicked: every relationship row must carry a reverse name;
          these write paths left it unset: blocks (1 rows)

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 — blocks, tasks, reported_tasks, held_at, every user-defined relationship — get NULL. A reverse-traversal query over (out_node, reverse_relationship_type) silently returns nothing for exactly those, which is the failure mode the PR body names as "worse than no column at all." It also means #2641's direction-aware resolver will work for child_of and break for everything a user declares.

The fix needs the declaration's reverse_name at instance-write time. Two workable shapes:

  • Resolve it in Rust in NodeService::create_relationship — the declared branch already fetches schema_node.get_relationship(relationship_name) at relationship.rs:542-550, so relationship.reverse_name is in hand a few lines above the write; thread it into create_generic_relationship as an Option<String> and let the built-in CASE be the fallback.
  • Or resolve it in SQL as a correlated subquery against the declaration row, with the CASE as COALESCE fallback.

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
📁 packages/core/tests/reverse_relationship_name_test.rs:200-281

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 reverse_relationship_type entirely from the INSERT at nodes.rs:227 (create_child_node_atomic). All 5 tests still passed.

Experiment B: I changed append_child_edge (relationships.rs:327) to write a bogus 'TAG_rel327'. All 5 tests still passed.

Experiment C: I tagged create_has_child_edge_in_tx (nodes.rs:346). Two tests failed — so that is the only one of the 10 has_child production sites any test in this suite reaches.

So of 18 production sites, the suite exercises roughly three: create_has_child_edge_in_tx, create_mention, and the declaration writer. The 9 remaining has_child sites, both member_of sites, bulk_create_mentions, and both generic sites are unverified. A future edit dropping the column from move_node, bulk_create_hierarchy, create_node_streaming or add_to_collection would ship green.

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 move_node, a bulk_create_hierarchy, an add_to_collection, and a declared instance edge. Each is a few lines and each converts a currently-vacuous assertion into a real one.

Nit within this: the mentions edge at :224-226 is commented "A generic edge through the dynamic-type path" — but mentions is a built-in, so it only exercises the CASE-hit branch. The CASE-miss branch, which is where the bug is, has no coverage at all. Swapping/adding a declared type here is the single highest-value line in the file.

🟡-2 — schema_declared_edges_store_the_authors_reverse_name cannot fail on the thing it names
📁 packages/core/tests/reverse_relationship_name_test.rs:161-194

The query filters WHERE reverse_relationship_type IS NOT NULL, then asserts the rows it got back are non-empty and non-built-in. Any row that regressed to NULL — the exact failure this test's title describes — is filtered out of the result set before the assertion sees it.

The seen > 0 guard is sufficient to prevent full vacuity (I confirmed core schemas unconditionally seed 6 declared relationships with reverse names — core_schemas.rs:241,254,267,440,1405,1416), so the test does prove something. But it proves "at least one declared row has a non-null reverse," not "declared rows store the author's name." Dropping the IS NOT NULL filter and asserting each declared row's reverse equals its declaration's reverse_name would make it test its title. As written it would not have caught 🔴-1 either.

🟡-3 — Nothing rejects an empty reverse_name, and nullable-plus-test can't catch it
📁 packages/nodespace-types/src/schema.rs:262, packages/core/src/schema/mod.rs

reverse_name: String is required by the type system — good, that's the right call over Option. But no validation path rejects "". set_schema_declarations will happily write an empty string into the column, which is NOT NULL-satisfying, index-populating, and semantically meaningless. The completeness guard's trim(...) = '' check would catch it for seeded schemas, but a user-declared schema created at runtime is never covered by that test.

A reverse_name.trim().is_empty() rejection alongside the existing duplicate-name and reserved-name checks at relationships.rs:1760-1775 would close this at the right layer.


🟢 Confirmations and minor notes

🟢-1 — SQL injection: no risk. builtin_reverse_name_sql interpolates only BUILTIN_RELATIONSHIPS, a const [(&str, &str); 4] of compile-time literals containing no quotes or metacharacters. type_expr is a caller-supplied &str but both call sites pass the literal "?4". The generated SQL is well-formed, and the ?4 usage is sound — SQLite binds the parameter once and the CASE reads the bound value, so relationship_type and the derived reverse always agree within a row. This mirrors the pre-existing builtin_exclusion_sql precedent in the same module, which is the right consistency call. Worth noting the function is only safe because callers pass a placeholder; a doc line saying type_expr must be a placeholder or column name, never user input, would make that contract explicit for the next caller.

🟢-2 — Parameter renumbering: verified correct at all 6 changed sites. I walked each placeholder against its libsql::params![] ordering:

  • relationships.rs:1818 / :1937 (the set_schema_declarations UPDATEs, shifted ?3/?4 → ?4/?5): out_node→?1, props_json→?2, reverse_name→?3, now→?4, id→?5. ✅ Matches.
  • relationships.rs:1836 / :1955 (the INSERTs, column added mid-list): rel_id, schema_id, out_node, rel.name, rel.reverse_name, props_json, now, now → ?1–?8. ✅ Matches.
  • relationships.rs:514 / :1406 (generic): the CASE sits between ?4 and ?5 but consumes no new placeholder, so props_json correctly stays ?5. ✅ Matches. This was the most likely off-by-one and it's right.

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 NOT NULL constraint error. I'd agree with the conclusion for a different reason: NOT NULL would be stricter and would have caught 🔴-1 at the first instance-edge write, in any test touching a declared relationship, rather than requiring the guard to happen to exercise it. That's a better failure mode, not a worse one — a constraint error naming the table beats a green test suite hiding a NULL.

The reason to keep it nullable anyway is different: NOT NULL on a column populated by a CASE that legitimately yields NULL for non-built-ins would make the generic path un-writable until 🔴-1 is fixed. So — nullable now, but I'd suggest revisiting NOT NULL once 🔴-1 lands and every path provably writes a value. At that point the constraint becomes a genuine invariant rather than a trap, and it enforces at write time what the test currently checks after the fact. Worth an ADR note if you'd rather not.

🟢-4 — The debug assertion's logic is correct, with one narrow false-negative. 📁 packages/core/src/db/schema.rs:176-186

It strips leading blank and -- lines, then requires the first substantive line to start with CREATE. I verified SCHEMA_SQL (lines 24–160) contains only CREATE TABLE/CREATE INDEX — the INSERT-bodied FTS triggers live outside it at :200-219 and are executed individually, so no false positive.

False negatives: a ; inside a trailing comment on the last line of a fragment would leave a tail that is blank-after-stripping, hit stmt.is_empty(), and continue before the assertion. Also a ; inside a string literal mid-statement could leave a tail beginning with CREATE if the literal itself contained one. Both are contrived. As a second line of defense that names the cause instead of incomplete input, this earns its place — and the PR body's honesty about having skipped it as YAGNI on #2698 and then immediately hitting it is a good note to have written down.

🟢-5 — Naming: no collisions, one convergence worth knowing about. I grepped child_of, has_member, mentioned_by, role_of across all of packages/ and scripts/ (.rs/.ts/.svelte/.json).

  • child_of, has_member, role_of: appear only in this PR's own code. Clean.
  • mentioned_by: already exists as RelationshipType::MentionedBy (services/query_service/mod.rs:102), its serde wire name "mentioned_by" (ops/query_ops.rs:141), the NodeQuery.mentioned_by field (nodes.rs:1421), a benchmark group, and a test fixture in schema_relationship_declarations_test.rs:274.

This is convergent, not conflicting — query_service/mod.rs:562 implements MentionedBy as out_node = X AND relationship_type = 'mentions', which is precisely "the reverse reading of a mentions edge." Same concept, same name, arrived at twice. I'd call that a point in the naming's favor rather than a problem. It does suggest a follow-up: once #2641 lands, RelationshipType::MentionedBy's hand-rolled subquery could be re-expressed against (out_node, reverse_relationship_type) and use idx_rel_reverse. Not this PR's job.

Also note schema_relationship_declarations_test.rs:274 declares a user relationship literally named mentions with reverseName: "mentioned_by" — that would be rejected today by the reserved-name check at relationships.rs:1761, so it's a pre-existing oddity in a fixture, not something this PR breaks.

🟢-6 — Duplicate storage of the reverse name. For declaration edges the reverse name now lives in both the column and the serialized SchemaRelationship inside properties. Keeping the blob intact is the right call for this PR — it's the serialization boundary and narrowing it is a separate change — but the two can now drift if anything ever writes properties without the column. Nothing does today (the UPDATE at :1818/:1937 writes both together), so this is a note for whoever eventually makes the column authoritative, not an action item.

🟢-7 — Nit: BUILTIN_RELATIONSHIP_NAMES spelling out BUILTIN_RELATIONSHIPS[0].0 … [3].0 is correct and const-evaluable, but silently wrong if the array ever grows to 5 — you'd get a 4-element array missing the new entry, with no compile error. A const assertion tying the lengths, or a comment on BUILTIN_RELATIONSHIPS saying "adding an entry requires extending BUILTIN_RELATIONSHIP_NAMES," would prevent a quiet mismatch.

🟢-8 — Standards: all clean. No lint suppression, no #[allow(dead_code)], no #[deprecated], no backward-compat or transition code, no backfill or data migration of any kind (I specifically verified no UPDATE ... SET reverse_relationship_type exists outside the legitimate declaration-update path, and no startup/lazy format upgrade), no .md files added to this repo, no GitHub issue numbers in code comments or SQL comments. The schema change is pure bootstrap DDL, which is the sanctioned exception.


Recommendation

REQUEST CHANGES

🔴-1 is a real, reproduced correctness gap: declared instance edges — the majority of non-structural edges a real database will hold — get NULL, which silently defeats reverse traversal for exactly the relationships users define. It needs fixing before merge.

🟡-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 move_node, a bulk path and a collection add is both the regression test for 🔴-1 and the thing that makes the guard live up to its own docstring.

🟡-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 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: 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]>
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 0eb54de3

Addressed 6, skipped 1. 🔴-1 was a real bug and the review is right about why my reasoning failed.

✅ 🔴-1 — Declared instance edges wrote NULL

Reproduced before fixing: adding a blocks edge between two tasks to the completeness guard gives blocks (1 rows).

My doc comment claimed set_schema_declarations covered this path. It doesn't, and the review names the conflation exactly: that function writes the declaration edge (schema→schema, "a task may have a blocks"), not the instance edge (task→task, an actual blocks). Instance edges go through create_generic_relationship, where the built-in CASE misses and a CASE without ELSE yields NULL. So every user-declared relationship got NULL — the larger population, and precisely what the column exists to serve.

Fixed by threading the declaration's reverse_name from the service layer — where schema validation already holds it, a few lines above the write, as you noted — into both create_generic_relationship twins as Option<&str>. SQL is now COALESCE(?8, <builtin CASE>): declared name when passed, derived built-in otherwise. I took the Rust-side option over the correlated subquery for the reason given.

✅ 🟡-1 — The guard passed vacuously

Confirmed your Experiment A independently: NULLing all seven has_child sites in nodes.rs left every test green.

Setup now also drives a declared instance edge (the CASE-miss branch), a re-parenting move_node_unchecked, the auto-ordering append_child_edge, the bulk cold-sweep attach, and a collection add. Re-ran the mutation: NULLing the nodes.rs sites now fails three tests.

One thing your experiments surfaced that I'd missed: the guard only checked for NULL/empty, so a wrong value still passed — I tagged append_child_edge with a bogus name and it shipped green even after the setup was extended. Added a correctness check asserting built-in rows carry the reverse their forward name maps to. That mutation now fails with has_child stored Some("TAG_BOGUS"), expected "child_of".

✅ 🟡-2 — Test couldn't fail on its own title

Right — WHERE reverse_relationship_type IS NOT NULL filtered out the exact regression, and 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 something worth recording: tasks is declared twice — on project (reverse project) and on person (reverse assignee) — so a forward name doesn't identify a declaration. My first attempt asserted tasks → project and failed with left: "assignee", right: "project". The expectation table is keyed by forward name and now excludes tasks, with a comment explaining why so the omission doesn't read as an oversight.

✅ 🟡-3 — Empty reverse_name

Both set_schema_declarations twins now reject it alongside the existing reserved-name and duplicate-name checks.

✅ 🟢-1 / 🟢-7

Documented that builtin_reverse_name_sql's type_expr is interpolated unescaped and must be a placeholder or column name. Added a const length assertion so a fifth BUILTIN_RELATIONSHIPS entry can't silently fall out of BUILTIN_RELATIONSHIP_NAMES.

⏭️ Skipped — 🟢-3's NOT NULL follow-up

Fair suggestion, and your correction of my reasoning is right: NOT NULL would have caught 🔴-1 earlier and is the stricter failure mode, not the worse one. Skipping it here because it's a schema change beyond this PR, and the correctness check now covers strictly more than NOT NULL would — it catches wrong values, not just missing ones. Worth revisiting as its own change.

Docs

typed-relationships.md updated (0393722) — it implied the declaration write populated everything, which was the same conflation that produced 🔴-1.

Notes on your 🟢 confirmations

🟢-5 on mentioned_by is a genuinely useful find: RelationshipType::MentionedBy already implements out_node = X AND relationship_type = 'mentions' — the same concept arrived at independently. Agreed it's convergent rather than conflicting, and re-expressing it against idx_rel_reverse once #2641 lands is a real simplification. Not this PR.

🟢-4's false-negative analysis is correct and matches what I hit writing this PR — a ; in a trailing comment leaves a tail that's blank after stripping and continues before the assertion.


Verification: cargo test -p nodespace-core --tests 29 binaries / 0 failures · quality:fix clean (clippy -D warnings across all packages) · full pre-push gate green.

Thanks for the mutation testing — Experiments A and B are what turned "the guard is the right shape" into "the guard actually holds," and neither the NULL bug nor the wrong-value gap would have been found without them.

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review: PR #2709 — 0eb54de3 (fix commit)

Review Type: Re-review. Prior review was on a4c20284; this reviews git diff a4c20284..0eb54de3 and verifies the prior feedback.


Previous Review Summary

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 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.

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]>
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed — 6f7c9416

✅ 🟡-4 — The transactional path's fix had no coverage

Confirmed your mutation before writing anything: reverting only the in-tx threading, leaving the direct path intact, left all 29 core test binaries green. The bug's return on that path was completely invisible.

Your diagnosis of why is what made this fixable — create_relationship_in_tx is pub(crate) and reached in production only through a playbook add_relationship, and the existing invariant tests only exercise member_of, a built-in whose reverse is derived in SQL and never touches the new parameter. So no amount of extending the integration suite could have closed it; the test had to go in-crate.

Added in_tx_declared_instance_edge_carries_the_declarations_reverse_name, driving with_transaction → create_relationship_in_tx with blocks and asserting the stored reverse is blocked_by. Verified load-bearing: with the threading reverted it fails left: None, right: Some("blocked_by") — the exact NULL regression.

You were right that this was the one item inconsistent with the PR's own thesis. One of the two paths that carried 🔴-1 had no guard against its return, while the commit message claimed completeness.

✅ 🟢-8 — Added reported_tasks → creator to the expectation table.

⏭️ 🟡-5 — Not addressed, deliberately

The eight still-unexercised literal sites (nodes.rs:227/2567/2948/3030/3091, relationships.rs:117/1242/1347). Your own framing — "static inline literals whose failure mode is a hand-edit typo" — is why I'm leaving them: the whole-table guard already catches any newly added path that forgets the column, which is the regression that actually occurs. Driving all eight needs fixtures for the sync cold-sweep and streaming-create paths whose setup cost exceeds what they'd protect.

Recorded in the commit message so the gap is known rather than assumed closed. That was the fair criticism — not the gap itself, but the narrative reading as though the guard were comprehensive.

On your per-site numbers

Your breakdown corrected my aggregate claim. I'd said "NULLing nodes.rs now fails three tests," which is true but holds because site :346 is reached — five of those seven sites individually stay silent. Fair correction; the commit message now states coverage per-path rather than in aggregate.


Verification: cargo test -p nodespace-core --tests 29 binaries / 0 failures · quality:fix clean · full pre-push gate green. Working tree clean, all mutation experiments restored.

Thanks — three rounds of mutation testing found one real bug and two tests that couldn't fail on what they were named for. The _in_tx gap in particular was invisible to every signal I had.

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.

Store relationship_type's reverse name as a queryable column on the relationship edge table

1 participant