Skip to content

Enforce reverse_cardinality on create_relationship - #2902

Merged
mstomar125 merged 6 commits into
mainfrom
issue-2804-reverse-cardinality
Sep 23, 2026
Merged

mstomar125 merged 6 commits into
mainfrom
issue-2804-reverse-cardinality

Conversation

@mstomar125

@mstomar125 mstomar125 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

create_relationship enforced cardinality on the declaring (forward) side but never checked reverse_cardinality against the target, so a relationship end declared one (e.g. a task's assignee, the inverse of person's outbound tasks) silently accepted edges from any number of sources.

  • Adds the reverse-cardinality check at both call sites (relationship.rs's create_relationship and its transactional twin create_relationship_in_tx), evicting/counting existing edges into the target for the same relationship type.
  • The check is scoped to the schema that actually declared the relationship being validated (via resolve_relationships' owner map and type_satisfies' ADR-078 subtype check), not a raw row count — two different schemas can declare the same forward name toward the same target type as logically distinct relationships (person.tasks → reverse assignee, project.tasks → reverse project, both targeting task), and the store keys an edge on relationship_type alone. A raw count would have rejected a legitimate edge from the second schema.

Decision: reject vs. replace

The issue flagged this as open: should a second edge into a cardinality-one end be rejected, or replace the existing one? Reject was tried first (matching the existing forward-side behavior), applied identically to both forward and reverse checks.

The pre-push gate's full test run caught a real regression under reject: the shipped linear-cycle-rollover recipe reassigns a task between cycles via add-then-remove — add the edge to the new cycle, then remove it from the old one — deliberately in that order (per its own doc comment) so a crash between the two steps leaves the task visibly in both cycles rather than silently in neither. Rejecting the "add" while the old edge is still present breaks that recipe outright.

Switched both checks to replace: the prior edge is evicted (with its own RelationshipDeleted event) before the new edge is inserted. This keeps the add-then-remove pattern working, and matches what the downstream UI issues (#2805, #2806 — single-select assign/reassign controls) already assume "a second write" means. A same-target (forward) or same-source (reverse) repeat call is left alone so the existing idempotency check still short-circuits it.

Tradeoff, called out rather than hidden: this makes replace the semantics for every create_relationship/create_relationship_in_tx caller (CLI, agent tools, the daemon RPC surface, playbook/actions.rs's add_relationship action), not just the add-then-remove reassignment pattern that motivated it. A caller that previously relied on reject as a safety net against accidentally overwriting an existing cardinality-one assignment now gets a silent replace instead of a clear error, with no conflict signal surfaced to the frontend (see the updated doc comment on the Tauri create_relationship command). A narrower design — an explicit replace flag, or a separate reassign_relationship used only by flows that actually want replace semantics — would avoid this, but the issue explicitly asks for one consistent answer on both ends, and every caller this PR could find already treats "create over an existing cardinality-one edge" as an intentional reassignment, not an accidental one. Flagging the tradeoff here for visibility rather than redesigning the API surface in this PR.

Review findings fixed after the first pass

Three real issues surfaced by review, on top of the reject→replace change:

  1. Non-atomic replace — the evict-then-insert ran as two separate auto-committed store calls in the non-tx path; a crash/cancellation between them left a cardinality-one end with zero edges (worse than the reject behavior it replaced). Fixed by routing a declared relationship's entire create_relationship call through create_relationship_in_tx inside one NodeService::with_transaction, which also collapsed the replace logic from two near-duplicate copies down to one.
  2. Required-relationship bypass — eviction deleted the other end's edge via a raw store call, bypassing the required: true last-edge protection delete_relationship normally enforces. Evicting person1's sole tasks edge to hand a task to person2 could silently leave person1 violating their own schema's required declaration. Eviction now goes through remove_relationship_in_tx, which reproduces that protection and fails the whole reassignment with an actionable error instead.
  3. A with_transaction race (pre-existing, exposed by fix Set up Tauri + Svelte project structure #1) — NodeService::with_transaction's nesting guard (batch_state, a single service-wide slot) transitioned to Transactional before requesting the store's write guard, so two genuinely concurrent callers could both observe Immediate and the second would silently clobber the first's in-flight event buffer. Fixed by moving the check-and-set (and the reset back to Immediate) inside the closure passed to the store's own transaction, gated by the write guard it already holds by that point — a second caller's guard acquisition now blocks until the first's is fully released. This is a foundational fix (every with_transaction caller benefits), verified with a dedicated test that races six callers via tokio::sync::Barrier under a multi-thread tokio runtime.

Testing

  • create_relationship_replaces_prior_edge_into_reverse_cardinality_one_target — two different people assigning the same task; the second replaces the first.
  • create_relationship_replaces_prior_edge_from_cardinality_one_source — forward-side replace, isolated via a dedicated reverseCardinality: many schema pair.
  • add_then_remove_reassignment_survives_reverse_cardinality_one_replace — the exact add-before-remove sequence the Linear recipe relies on, plus confirms the trailing delete_relationship of the already-evicted edge is a no-op.
  • concurrent_reassignment_never_leaves_two_live_edges_into_a_reverse_cardinality_one_target — six real OS threads race to become a task's sole assignee; exactly one edge survives, every call succeeds.
  • person_task_assignee_relationship_assigns_and_clears_end_to_end (pre-existing) still passes unchanged.
  • Full cargo test -p nodespace-core --lib (1669 passed) and --tests (every integration binary, including methodology_linear_execution_test and store_concurrency_test) green locally; pre-push gate (frontend + skill + Rust + e2e + Tauri-seam) passed.

Second review pass

A follow-up /pragmatic-code-review (multiple angles: A-E, reuse, simplification/efficiency, altitude) found no further correctness issues — only low-severity, pre-existing-pattern duplication nits, none warranting a code change:

  • The new get_relationship_edges_from_source/get_relationship_edges_into_target store method pairs follow a slightly different shape than the existing direction-based relationship queries.
  • The tx/non-tx twin duplication these methods add follows the same pattern already used throughout sqlite_store/relationships.rs (ADR-069 §1a), which is repo-wide existing debt, not something newly introduced here.
  • Edge-data normalization (serde_json::json!(edge_data.as_object().cloned().unwrap_or_default())) appears in both create_relationship and create_relationship_in_tx, matching the pre-existing shape.
  • The forward/reverse eviction loops in create_relationship_in_tx share a similar shell (fetch existing edges, skip the caller's own, evict via remove_relationship_in_tx) — could be factored into a shared helper, but the two loops differ enough (forward has no ADR-078 scoping step, reverse does) that inlining stayed clearer for now.
  • check_relationship_exists (forward count) and the new edge-list methods (used for reverse) answer overlapping questions with different shapes for different needs — kept as-is rather than unifying, since squeezing them into one shape would obscure the forward/reverse asymmetry.

None of these are correctness bugs and all match existing codebase convention, so no further code changes were made for them.

Third review pass — a real must-fix bug found

Further review (multiple independent confirmations) found the biggest remaining gap: a cardinality: One relationship that is ALSO required: true could never be reassigned at all — the exact use case this whole PR exists to support. Root cause: the forward eviction ran BEFORE the new edge was inserted, so remove_relationship_in_tx's required-last-edge guard always counted exactly 1 existing edge at eviction time (cardinality:One guarantees at most one) and always rejected, even though a replacement was about to land in the same transaction.

Fixed by reordering: create_relationship_in_tx now only gathers which edges need evicting during validation, inserts the new edge first, then evicts the gathered edges afterward — still inside one transaction. New test required_cardinality_one_relationship_can_still_be_reassigned covers both the fix and that a genuine last-edge deletion (no replacement) still correctly stays rejected.

Also fixed in this pass:

  • Added get_node_in_tx_or_virtual_date, the tx-scoped counterpart to get_node's virtual-date-node synthesis, for create_relationship_in_tx's source/target lookups. (Investigated whether skipping this was an actual regression from collapsing the non-tx path into the transactional one — empirically it is not: an edge to a genuinely unpersisted date node fails identically before and after, at the DB's foreign-key constraint, since nothing in create_relationship persists the date node first. Kept the fallback anyway as a harmless, more-correct improvement.)
  • Deleted the two get_relationship_edges_from_source/into_target (non-tx) store methods — dead code once the non-tx create_relationship path was fully collapsed into the transactional implementation.
  • Investigated a claimed race in begin_batch_emit sharing with_transaction's old bug — not applicable; unlike with_transaction's original two-separate-locks bug, begin_batch_emit's check-and-set has always lived inside one lock scope.

Filed as follow-ups rather than fixed here (different scope/subsystem each):

Closes #2804. Unblocks #2805, de-risks #2806.

🤖 Generated with Claude Code

mstomar125 and others added 6 commits September 23, 2026 09:58
create_relationship checked the declaring (forward) cardinality against
the source but never checked reverse_cardinality against the target, so
a relationship end declared "one" (e.g. a task's assignee, the inverse
of person's outbound `tasks`) silently accepted edges from any number of
different sources.

Adds the counterpart check at both call sites (relationship.rs and its
create_relationship_in_tx twin): count existing edges into the target
for the same relationship type and reject a second one, matching the
existing forward-side reject behavior so both ends of a declaration
enforce cardinality the same way.

The count is scoped to the schema that actually declared the
relationship being validated (via resolve_relationships' owner map and
type_satisfies' ADR-078 subtype check), not a raw row count — two
different schemas can declare the same forward name toward the same
target type as logically distinct relationships (person.tasks ->
assignee, project.tasks -> project, both targeting task), and the store
keys an edge on relationship_type alone.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The first version of this check rejected a second edge on either a
forward or reverse cardinality-one relationship. The pre-push gate
caught a real regression: the shipped `linear-cycle-rollover` recipe
reassigns a task between cycles via add-then-remove (add the edge to
the new cycle, then remove it from the old one), deliberately in that
order so a crash between the two steps leaves the task visibly in both
cycles rather than silently in neither. Rejecting the add while the old
edge is still present breaks that recipe outright.

Enforce as replace instead, on both the forward and reverse checks:
evicting the prior edge before inserting the new one lets add-then-
remove keep working (the add absorbs the eviction, and the subsequent
remove becomes a harmless no-op on an edge that's already gone), and
matches what the downstream UI issues (single-select assign/reassign
controls) already assume "second write" means. A same-target/same-
source repeat is left alone so the existing idempotency check still
short-circuits it, rather than needlessly evicting and recreating.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Three review findings addressed:

1. Non-atomic replace: create_relationship's forward/reverse cardinality
   replace (evict old edge, insert new) ran as separate auto-committed
   store calls in the non-tx path, so a crash or cancellation between
   them left a cardinality-one end with zero edges. A declared
   relationship's whole create_relationship path (validation, replace,
   idempotency, insert) now runs through create_relationship_in_tx
   inside one NodeService::with_transaction call, making the non-tx
   entry point (CLI, agent tools, the daemon RPC surface) transactional
   the same way an invariant Play's add_relationship action already was.
   This also collapses what was near-duplicate replace logic between
   the two functions down to one copy.

2. Required-relationship bypass: both replace eviction blocks deleted
   the OTHER end's edge via a raw store call, bypassing the
   required-relationship last-edge protection delete_relationship
   normally enforces. Evicting person1's sole `tasks` edge to hand a
   task to person2 could silently leave person1 violating their own
   schema's `required: true` declaration. Eviction now goes through
   remove_relationship_in_tx, which reproduces that protection and
   fails the whole reassignment (with an actionable error) rather than
   silently violating it.

3. with_transaction race: fixing (1) surfaced a genuine, pre-existing
   bug in NodeService::with_transaction's nesting guard. batch_state is
   a single service-wide slot (shared by every clone of a NodeService),
   but the check-and-set into BatchState::Transactional happened BEFORE
   requesting the store's write guard — so two concurrent callers could
   both observe Immediate, and the second would silently clobber the
   first's in-flight event buffer with a fresh empty one (a debug_assert
   catches this in debug builds; release builds would misattribute
   events between the two transactions). The check-and-set, and the
   reset back to Immediate, now both happen inside the closure passed to
   the store's own with_transaction, gated by the write guard it already
   holds by that point — a second caller's own guard acquisition blocks
   until the first's is released, by which point batch_state is
   provably back to Immediate. Verified with a new test that races six
   callers via tokio::sync::Barrier under a multi-thread runtime.

Also documents the reject-was-tried-first, evict-was-tried-first
decision history in create_relationship's doc comment, and updates the
Tauri create_relationship command's doc comment, which claimed the
daemon rejects a cardinality conflict — it now replaces silently
instead, with no conflict signal returned to the frontend.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…everse-cardinality

# Conflicts:
#	packages/core/src/services/node_service/relationship.rs
Real bug found by review, confirmed independently multiple times: a
cardinality:One relationship that is ALSO required:true could never be
reassigned. create_relationship_in_tx evicted the source's prior edge
via remove_relationship_in_tx BEFORE inserting the new one; that
method's required-last-edge guard counts the source's current edge
count for the relationship, which under cardinality:One is always
exactly 1 at eviction time (the replacement hasn't landed yet) — so it
always concluded "this is the last edge" and always rejected, even
though a replacement was about to be inserted in the same transaction
and the invariant was never actually going to be violated.

Fixed by reordering: the forward- and reverse-cardinality-one checks
now only GATHER which edges need evicting during validation. The new
edge is inserted first, then the gathered edges are evicted afterward
— all inside the same transaction. At eviction time the source
briefly holds both edges, so the required-check correctly sees more
than one and evicts cleanly; a real deletion with no replacement still
correctly sees only one and stays rejected. The store's unique index
is on (in_node, out_node, relationship_type), not (out_node,
relationship_type), so briefly holding both edges mid-transaction
doesn't violate any DB constraint. New test in
relationship_editing_test.rs using the existing
service_with_gizmo_schema("one", true) helper covers both the
reassignment succeeding and the still-correct last-edge rejection for
a plain delete.

Also adds get_node_in_tx_or_virtual_date, the create_relationship_in_tx
counterpart to get_node's virtual-date-node synthesis — the raw
SqliteStore::get_node_in_tx had no such fallback, unlike the service-
level lookup every custom relationship used before this issue's non-tx
path was collapsed into the transactional one. (Investigated whether
this was an actual behavioral regression: it is not — an edge to a
genuinely unpersisted date node fails identically, before and after,
at the DB's foreign-key constraint, since nothing in create_relationship
persists the date node first. Kept the fallback anyway as a harmless,
more-correct validation-layer improvement.)

Deletes the two get_relationship_edges_from_source/into_target (non-tx)
store methods, now dead: nothing calls them since create_relationship's
custom-relationship path was collapsed entirely into the transactional
_in_tx implementation.

Filed as follow-ups rather than fixed here (different scope):
- core#2908: merge_nodes_in_tx's dedup-merge edge repointing bypasses
  cardinality/reverse_cardinality enforcement entirely (separate
  subsystem)
- core#2909: reverse-cardinality scoping's ancestor-chain-membership
  check can diverge from ownership-equality if set_schema_relationships
  is used directly to shadow an inherited relationship — not reachable
  through any real caller today
- core#2910: cardinality-one replace has no visible signal across
  frontend/CLI/agent surfaces (real UX-review scope, touches
  packages/agent/ which needs sign-off)

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125
mstomar125 merged commit f33701a into main Sep 23, 2026
@mstomar125
mstomar125 deleted the issue-2804-reverse-cardinality branch September 23, 2026 10:25
mstomar125 added a commit that referenced this pull request Sep 25, 2026
* Enforce cardinality-one on merge_nodes_in_tx's edge repoint

SqliteStore::merge_nodes_in_tx re-points every relationship edge
touching a merge's loser onto the survivor via a raw endpoint UPDATE,
with no notion of a declared relationship's cardinality/
reverse_cardinality — the checks create_relationship_in_tx enforces
(core#2804, replace semantics per #2902). A repoint could therefore
leave the survivor with two live edges where a cardinality: One or
reverse_cardinality: One relationship allows at most one, e.g. when
survivor and loser each held their own compliant edge toward
different targets before the merge.

merge_nodes_in_tx now returns the raw repointed edges (relationship
type, new source, new target) instead of just a count, since the
store layer has no schema-resolution access to check cardinality
itself. NodeService::merge_nodes, which already resolves declared
relationships for create_relationship_in_tx, closes the gap in the
same transaction via a new enforce_cardinality_after_merge_in_tx:
for each repointed edge on a cardinality-one end, it evicts the
edge via the existing remove_relationship_in_tx primitive, keeping
the survivor's pre-existing edge and dropping the loser's repointed
one. Built-in relationship types (has_child, mentions, member_of,
has_role) carry no declared cardinality and are skipped.

Adds two merge_nodes_test.rs cases covering the forward
(cardinality: One) and reverse (reverse_cardinality: One) directions;
the existing suite is unchanged and still passes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Address review: document and test the reverse-cardinality rollback trap

enforce_cardinality_after_merge_in_tx's reverse branch can evict an edge
belonging to a node other than the merge survivor (the repointed edge's
own source). If that relationship is also required: true on the source's
schema and this was its only edge, remove_relationship_in_tx's last-edge
guard rejects the eviction, and the Err aborts the entire merge
transaction rather than just that one edge's repoint. This is a real,
reachable, and correct (fail-closed) outcome for what is a genuinely
irreconcilable conflict, but was previously undocumented and untested.

- Expand enforce_cardinality_after_merge_in_tx's doc comment to explain
  the reverse branch's failure mode explicitly, why it's safe (atomic
  rollback, verified against SqliteStore::with_transaction), and note the
  has_child two-parent gap (filed separately as #2945) is unaffected by
  this method rather than implying it's currently guaranteed.
- Add merge_rolls_back_entirely_when_reverse_cardinality_eviction_would_violate_a_required_relationship,
  exercising the trap end-to-end and asserting the rollback leaves zero
  partial state (loser stays active, both edges land back where they
  started).
- Swap the reverse branch's source lookup from a raw get_node_in_tx to
  get_node_in_tx_or_virtual_date, matching create_relationship_in_tx's own
  resolver for a relationship's source instead of silently skipping
  enforcement for a not-yet-persisted virtual node.

Addresses feedback from two independent review passes on PR #2937.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

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

Labels

None yet

Projects

None yet

1 participant