Skip to content

Make graph_resolver direction-aware so Play conditions can walk any relationship's reverse side (closes #2641) - #2730

Merged
malibio merged 4 commits into
mainfrom
issue-2641-direction-aware-resolver
Sep 17, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2641-direction-aware-resolver

Conversation

@malibio

@malibio malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Closes #2641.

A Play condition could only walk relationships forward. fetch_related_nodes hardcoded direction: "out", so reading an edge from the end that did not declare it was unreachable — a task could not read its project, assignee, or parent.

Approach: share the resolution that already existed

ops::rel_ops::resolve_relationship_name already mapped a reverse name to its stored forward name and flipped the direction, for the CLI's read path. Rather than write a second rule in the playbook resolver, this promotes that function to pub and calls it from graph_resolver.rs, so both consumers answer a given name identically.

It had learned two things worth keeping that a fresh implementation would likely have missed:

  • Forward wins over a same-spelled reverse name on another schema, so reverse support can never redirect a traversal that already worked.
  • Inbound results are narrowed to the declaring type. The store keys an "in" query on relationship_type alone, so every schema declaring that forward name answers. This is live, not hypothetical: core schemas declare tasks on both project and person, so an unnarrowed node.assignee would also return the project.

Deviation from the issue spec, flagged for review

The issue proposes resolving against #2638's reverse_relationship_type column. This resolves against schema declarations instead, reaching the same edges. The resolver needs schema context the column does not carry — target type, untyped-declaration probing, source-type narrowing. The column remains what makes the store-layer reverse read efficient.

Built-ins: fixed for both consumers

resolve_relationship_name short-circuited on built-in forward names before any reverse lookup, so child_of was unresolvable for the CLI too. Resolving it from BUILTIN_RELATIONSHIPS fixes both at once.

This made reserving the built-in inverses load-bearing. They were free to declare while nothing could traverse by them; now a schema declaring reverseName: "child_of" would be accepted and permanently shadowed — the same inert-declaration failure the forward guard already prevents. is_reserved_relationship_name now covers both halves.

Behavior difference between the two consumers, by design

An undeclared name stays an error on the CLI path (an empty result is indistinguishable from "declared, but no edges yet"). In a Play it degrades to an empty traversal: a segment reaches the relationship resolver only after failing as a property, so "not a relationship either" is the ordinary way a path goes missing — which CEL reads as a false condition.

Second commit: a cache bug found by a test written for something else

The segment cache was keyed on path segments alone, with no notion of the root node. Two nodes asking the same path shared one entry — the second walk got the first's answer, a wrong node returned with no error anywhere.

Not reachable from either production caller (both bind a resolver to a single trigger node), and pre-existing. Fixed rather than noted because reverse traversal makes reuse across roots (child_of, then has_child from the parent) the natural thing to reach for, turning a documented invariant into a trap.

Acceptance criteria

  • Resolves a reverse-direction segment generically, not hardcoded per relationship
  • Multi-hop and collection comprehensions work through a reverse segment (node.assignee.email, node.child_of.has_child.all(...))
  • All existing forward-direction tests pass unmodified (26 of them)
  • Coverage for one built-in (has_child → child_of) and one schema-declared (person.tasks → assignee)
  • bun run test:all — passed via the pre-push gate
  • bun run quality:fix

Verification

Every change was mutation-tested — each mutation failed exactly the tests naming that behavior:

Mutation Tests failed
Remove source_type narrowing 1
Disable built-in reverse branch 2
Reservation back to forward-only 1
Cache key back to segments-only 2

33 resolver tests, 382 playbook tests, 1435 Rust lib tests pass.

Note on the gate

Two earlier pushes were blocked: a stale nodespaced binary (real, rebuilt), and a wall-clock assertion at packages/desktop-app/src/tests/performance/architecture-benchmarks.test.ts:257 that failed once in nine local runs of the identical commit. That test is timing-sensitive and unrelated to these Rust-only changes; worth its own issue.

Docs: NodeSpaceAI/nodespace-docs@67d5c94

🤖 Generated with Claude Code

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2730

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

Scope: 2 commits, 6 files, +608/−44. Verified against origin/main...HEAD, issue #2641's acceptance criteria, and a local run of bun run rust:test:lib (1481 passed, 0 failed).


Requirements Check (issue #2641)

Criterion Status
Resolves a reverse-direction segment generically, not hardcoded per relationship ✅ Met — fetch_related_nodes delegates wholly to rel_ops::resolve_relationship_name; no relationship name appears in resolver control flow
Multi-hop paths and comprehensions work through a reverse segment ⚠️ Met for paths of 3+ segments; see 🟡 finding #1 — node.assignee (the issue's own example) does not reach the resolver
All existing forward-direction tests pass unmodified ✅ Verified — no existing resolver test was edited; the diff to graph_resolver.rs tests is purely additive
Coverage for one built-in and one schema-declared reverse ✅ builtin_reverse_name_walks_to_the_parent, declared_reverse_name_resolves_and_chains
bun run test:all ✅ Per the pre-push gate; rust:test:lib re-verified locally
bun run quality:fix ✅ Clean

📝 On the deviation from the spec. The issue prescribes resolving against #2638's reverse_relationship_type column; the PR resolves against schema declarations instead. This is the better call and the PR's write-up defends it correctly. Resolution needs three things the column cannot supply: forward-wins precedence, untyped-declaration probing, and source-type narrowing. Resolving off the column would have produced a second resolution rule diverging from the CLI's — the exact DRY violation the chosen approach avoids. Nothing is lost: the column still does its job at the store layer. Reusing resolve_relationship_name rather than reimplementing it is the strongest architectural decision in this PR.


Findings

🟡 Important

1. The headline capability is unreachable for single-hop paths — node.assignee does not resolve.
📁 packages/core/src/playbook/graph_resolver.rs:290
📁 packages/core/src/playbook/actions.rs:421

Both callers gate the resolver behind a segment-count check:

// graph_resolver.rs:290  (enrich_context)
if path.root != "node" || path.segments.len() <= 2 {
    continue;  // "Single-level paths (node.status) are handled by existing context building"
}
// actions.rs:421  (resolve_trigger_path)
Err(_) if segments.len() > 2 => { /* ...only here is the resolver consulted... */ }

node.assignee is two segments (["node", "assignee"]), so it never reaches fetch_related_nodes. It falls through to node_to_cel_value(node), which exposes properties only — the path evaluates to NoSuchKey, i.e. a silently false condition.

This matters because node.assignee is issue #2641's own worked example ("Concretely: node.assignee … should resolve"), and because the failure is silent: an author writes a reverse condition, it compiles, it never fires, and nothing logs. The multi-hop forms (node.assignee.email, node.child_of.has_child) do work, and the PR's tests cover exactly those — which is why the gap survived. Note the tests call resolve_path directly, bypassing the two gates, so they cannot detect this.

The gate's own comment reveals the assumption: a 2-segment path was by definition a property, because a relationship always needed a further hop to yield a value. Reverse traversal breaks that assumption — node.assignee is now a meaningful terminal path.

Engineering principle: a capability is delivered at the boundary its users actually call, not at the unit that implements it. Testing the unit directly while the integration path gates it out is the classic false-positive coverage shape.

Recommendation: relax both gates to segments.len() >= 2 with a property-first attempt (the resolver already tries properties before relationships, so the ordering is preserved), and add one test that drives a single-hop reverse condition through evaluate_conditions rather than through resolve_path. If the author prefers to scope this separately, it should be filed before merge and the PR body's acceptance-criteria checkbox amended, since as written it overstates what ships.

2. Err(_) => return Ok(vec![]) discards genuine infrastructure failures.
📁 packages/core/src/playbook/graph_resolver.rs:239-241

Ok(resolved) => resolved,
// Undeclared in either direction — an empty traversal, not a failure.
Err(_) => return Ok(vec![]),

The comment is right about the intended variant, and the design rationale for degrading an undeclared name to empty is sound and well argued. But resolve_relationship_name returns OpsError::Internal for three distinct DB failures — get_schema_node, get_inbound_relationships, and the untyped-relationship probe (rel_ops.rs:206, :229, :243). A locked database or a corrupt schema row is swallowed into "this path is missing", producing a silently false Play condition with nothing in the logs.

Note the asymmetry within this very function: the get_related_nodes call five lines below does propagate its error (?), and resolve_path logs it at graph_resolver.rs:174-177. The same class of failure is therefore diagnosable when it happens on one line and invisible when it happens on the other.

Recommendation: match on the variant — treat "undeclared" as empty, propagate (or at minimum warn!) OpsError::Internal:

Err(OpsError::Internal(e)) => return Err(e),  // joins the existing logged path
Err(_) => return Ok(vec![]),                  // undeclared: an ordinary missing path

Engineering principle: error handling should discriminate between expected control flow and infrastructure failure. A blanket Err(_) conflates them, and the conflation is invisible precisely when you most need the signal.

3. Per-rule resolver construction turns one query into a schema round-trip per segment.
📁 packages/core/src/playbook/engine.rs:903-904, packages/core/src/playbook/workflow_state.rs:184

Both hot-path callers construct a GraphResolver inside the per-rule loop, so the segment cache is discarded between rules on the same node. Meanwhile each relationship segment now costs, before the traversal itself:

  • get_schema_node(node_type) — uncached, straight to the store (services/node_service/schema.rs:480)
  • get_inbound_relationships(node_type) → get_all_schemas() — loads and hydrates every schema in the workspace (relationship.rs:1444)
  • one get_related_nodes probe per untyped inbound declaration (rel_ops.rs:236-247)

Previously fetch_related_nodes was a single store query. For N rules on a node, the whole-workspace schema load now runs N times over. The PR's segment cache does not mitigate this — it caches resolved values, not resolutions, and it is thrown away per rule anyway.

Mitigating facts, which are why this is 🟡 and not 🔴: the untyped probe is free in practice (grep -c "target_type: None" core_schemas.rs → 0), schema counts are small, and this is local SQLite, not a network hop. It is a real regression on the rule-evaluation path, not a hypothetical one, but it is not a correctness problem.

Recommendation: not a blocker for this PR. Either hoist resolver construction out of the per-rule loops (the cache is already root-scoped after commit 2, so this is now safe — a nice second dividend of that fix), or memoize resolution per (node_type, name) inside the resolver. Worth a follow-up issue rather than expanding this PR's scope.

Engineering principle: sharing a resolution rule (correctly, per DRY) means inheriting its cost profile. A function written for a one-shot CLI read has different budget assumptions than one on a per-event evaluation loop.

🟢 Suggestions

4. reserved_relationship_names() allocates a Vec on every call.
📁 packages/core/src/models/schema.rs:113-119

It is only called on the error path of two validators, so the cost is irrelevant — but it is called to build an error message, and the data is fully const. Consider a const RESERVED_RELATIONSHIP_NAMES: [&str; 8] built the same way BUILTIN_RELATIONSHIP_NAMES already is, including the same const _: () = assert!(...) length guard that file already uses. That would also keep the two spellings-tables structurally parallel.

Nit: is_reserved_relationship_name now supersedes is_builtin_relationship at all three declaration-validation call sites. is_builtin_relationship remains used elsewhere legitimately (it means something different — forward-only), so there is nothing to delete; just confirming that was checked.

5. builtin_forward_name is checked before the node's own schema — correct, but the ordering is load-bearing and undertested.
📁 packages/core/src/ops/rel_ops.rs:187-196

The new built-in-inverse branch sits above the forward-declaration lookup. That is only safe because is_reserved_relationship_name now rejects those spellings at declaration time — the two changes are coupled, and the doc comment says so explicitly, which is good. What is not tested is the coupling itself: that a schema declaring child_of cannot exist, and therefore the early return can never shadow a live declaration. The reservation tests (schema_relationship_declarations_test.rs:378+) prove the rejection; nothing ties it to the resolver's ordering assumption. A comment is doing work a test could do — though since the declaration path is the only way to create one, this is defensible as-is.


What this PR gets right

Worth stating explicitly, because these are the decisions that make it a clear net improvement:

  • Reusing resolve_relationship_name instead of writing a second rule. The single most valuable choice here. Two resolution rules would have drifted, and the built-in short-circuit bug proves it — fixing it in the shared function repaired the CLI path as a side effect, which a duplicated implementation would not have done.
  • The source_type narrowing. Option<String> correctly distinguishes "narrow to the declaring schema" from "a built-in has no declarer, narrowing would delete valid answers." The test (reverse_name_excludes_another_schemas_same_forward_name) verifies a real collision (tasks on both project and person in the core schemas), not a contrived one, and asserts the identity of the returned node rather than a count — it would fail loudly on regression.
  • The InboundForward reasoning holds. Verified independently: that variant is only reached after the node's own schema fails to declare the name (rel_ops.rs:200-206), so under the old hardcoded "out" the store query WHERE r.in_node = ? AND r.relationship_type = ? could only match edges this node declared — by construction, none. Old behavior was an unconditional empty result. Serving real inbound nodes is new capability, not a redirect. No existing Play can change behavior.
  • The reserved-name break is complete. Verified no core or seeded schema declares any of child_of / has_member / mentioned_by / role_of as a name or reverseName. Both the create (schema/mod.rs) and update (services/node_service/schema.rs, two sites) paths were updated consistently. Per CLAUDE.md this pre-release break needs no migration, and it correctly has none.
  • Commit 2 is a genuine latent-bug fix, correctly scoped and separately committed. Keying on segments alone would serve one root's answer for another's. The commit message is honest that it is unreachable from current callers and says why it is worth fixing now anyway.
  • Test quality is high, with one exception. cache_does_not_leak_between_root_nodes asserts p2, not merely "a node" — it fails on regression. The narrowing test asserts node identity. No vacuous asserts found. The one caveat is the coverage-shape issue in finding Set up Tauri + Svelte project structure #1: tests exercise resolve_path directly, which is exactly the layer where the integration gates do not apply.
  • No lint suppression, no #[allow(dead_code)], no deprecation, no migration, no issue numbers in code comments. Compliant with CLAUDE.md throughout.

Recommendation: COMMENT

The core change is architecturally sound, correct on the direction-change question, well tested where it is tested, and a clear net improvement to code health. Nothing here is a correctness or security blocker, and I would not hold the merge over findings #2–#5.

The one thing to resolve first is finding #1: as it stands, node.assignee — the issue's own example, and the second acceptance criterion — does not resolve through either production caller, and fails silently when an author tries it. That is a two-line gate relaxation plus one integration-level test, or, if scoped out, a filed follow-up and an honest amendment to the PR body's checkbox. Either is fine; shipping the criterion checked as-is is not.

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

Automated pragmatic-code-review: COMMENT (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

malibio added a commit that referenced this pull request Sep 17, 2026
… errors

Findings from the review on PR #2730.

1. The headline capability did not reach either production caller.
`enrich_context` skipped any path of two segments and
`resolve_trigger_path` required more than two, both on the assumption
that a two-segment path must be a property — true only while a
relationship always needed a further hop to yield a value. A terminal
reverse segment breaks it: `node.assignee` IS the value. The issue's own
worked example therefore compiled, never fired, and logged nothing.

My tests missed this by calling `resolve_path` directly, below both
gates — the unit passed while the integration path gated it out. The new
test drives `enrich_context` instead, and fails without the fix.

The gate is now a property check rather than a length check, so
`node.status` still bypasses the resolver as intended.

2. `Err(_) => Ok(vec![])` swallowed infrastructure failures. Only
`InvalidParams` means "undeclared"; `Internal` means an unreadable schema
or a locked database, and turning that into a silently false condition
hid exactly the signal worth having — while the `get_related_nodes` call
five lines below propagated the same class of error.

3. Hoisted resolver construction out of both per-rule loops. Every rule
on a work item resolves from one trigger node, so rebuilding per rule
discarded a cache about to be asked the same questions. Safe now that
cache entries are root-scoped, which also blunts the per-segment schema
lookups this PR's shared resolution introduced.

4. `RESERVED_RELATIONSHIP_NAMES` is a const with a length assertion,
matching `BUILTIN_RELATIONSHIP_NAMES`, instead of allocating a Vec.

5. Added the test tying the reservation to the resolver's ordering: the
early return for a built-in inverse is only safe because no schema can
declare one, and that join was asserted by a comment alone.

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

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 5 of 5, none skipped

All findings are in 857fb9c2. The pre-push gate passed (full pyramid); 1482 Rust lib tests pass.

🟡 1 — node.assignee unreachable (the blocking one)

Confirmed before fixing: wrote a test at enrich_context and watched it fail. Both gates assumed a two-segment path is a property — true only while a relationship always needed a further hop to yield a value. A terminal reverse segment breaks that.

  • graph_resolver.rs — the gate is now a property check rather than a length check, so node.status still bypasses the resolver as intended (the gate's actual purpose) while node.assignee reaches it.
  • actions.rs — > 2 → >= 2. navigate_json has already failed by that point, so the property case is excluded and nothing resolvable without a query gets through.

On the coverage-shape critique — it was correct and is the most useful thing in this review. My tests called resolve_path directly, below both gates: the unit passed while the integration path gated the feature out. The new test drives enrich_context, and reverting the gate fails it.

I did not take the offered alternative of filing a follow-up and amending the checkbox. The criterion is the feature.

🟡 2 — Err(_) swallowed infrastructure failures

Fixed as recommended, matching on the variant:

Err(OpsError::InvalidParams(_)) => return Ok(vec![]),  // undeclared: ordinary missing path
Err(e) => return Err(e.to_string()),                   // infra failure: propagate + log

The asymmetry you pointed out — get_related_nodes five lines below propagating the same class of error — is what makes the original indefensible. I had rationalized this in the PR body; that was wrong.

🟡 3 — Per-rule resolver construction

Hoisted out of both loops (engine.rs, workflow_state.rs) rather than deferred. Every rule on a work item resolves from the same trigger node, so rebuilding per rule discarded a cache about to be asked the same questions. Safe because commit 2 made cache entries root-scoped — as you noted, a second dividend of that fix. Two one-line moves, so the follow-up issue isn't needed.

Thanks for running grep -c "target_type: None" core_schemas.rs → 0. That check is what reduces the untyped-declaration probe from alarming to free, and I hadn't run it.

🟢 4 — reserved_relationship_names() allocation

Now const RESERVED_RELATIONSHIP_NAMES: [&str; 8], spelled out per index with a const _: () = assert!(...) length guard — structurally parallel to BUILTIN_RELATIONSHIP_NAMES, as suggested.

🟢 5 — Untested coupling

Added a_builtin_inverse_always_resolves_to_the_builtin: asserts the declaration is refused and that child_of consequently resolves to has_child with source_type: None. The two halves were each tested; the join between them was held by a comment alone.


Verification

Mutation-tested, each failing exactly the tests naming that behavior:

Mutation Tests failed
Revert enrich_context gate to <= 2 1
Remove source_type narrowing 1
Disable built-in reverse branch 2
Reservation back to forward-only 1
Cache key back to segments-only 2

Re-review recommended — findings #1 and #3 changed behavior on the rule-evaluation path, not just style.

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2730 (Re-Review)

Review Type: Re-review. Prior review: COMMENTED, 2026-09-17T11:17:50Z, against af659ec7.

Scope: git diff af659ec7..857fb9c2 only — 8 files, +183/−22. The two earlier commits were reviewed previously and are not re-examined. Verified with bun run rust:test:lib (1482 passed, 0 failed, up from 1481) and cargo clippy -p nodespace-core --lib --all-targets (clean).


Previous Review Summary

Count
Prior recommendations 5 (🟡 1–3, 🟢 4–5)
Addressed 5
Partially addressed 0
Not addressed 0
New issues found in 857fb9c2 2 (🟢 2)

All five were addressed, and — checked independently rather than taken from the author's summary — each fix is correct. Finding #1's fix is better than the one I recommended. Finding #3's fix is safe, and the staleness question it raises resolves in its favor for a reason the author's comment does not state. Two 🟢 observations follow; neither blocks.


Requirements Check (issue #2641)

Criterion Status
Resolves a reverse segment generically, not hardcoded per relationship ✅ Unchanged from prior review
Multi-hop paths and comprehensions work through a reverse segment ✅ Now genuinely met. Was ⚠️ — see below
All existing forward-direction tests pass unmodified ✅ No existing test edited; diff to tests is purely additive (+58 / +52)
Coverage for one built-in and one schema-declared reverse ✅ Unchanged
bun run test:all ✅ Pre-push gate; rust:test:lib re-verified locally at 1482
bun run quality:fix ✅ Clippy clean

On criterion 2, end-to-end. The prior review's objection was that node.assignee never reached the resolver through either production caller. enrich_context is the boundary evaluate_conditions calls (cel.rs:498), and it now admits the path. The remaining layer — evaluate_conditions → CEL Program::execute() — consumes enrich_context's HashMap through the same injection path every already-passing multi-hop test uses. There is no gate or length assumption left between them. I consider the criterion met, with the caveat in 🟢 finding #7.


Findings

✅ Verified Fixed

Finding 1 — node.assignee unreachable through production callers. Fixed, and the chosen approach is better than the one recommended.

📁 packages/core/src/playbook/graph_resolver.rs:294-311
📁 packages/core/src/playbook/actions.rs:417-419

I recommended relaxing the gate to a length check (>= 2). The author instead made it a property check, and that is the stronger choice — worth stating why, because it turns on a detail easy to miss.

The original gate conflated two things: "this path is short" and "this path is a property already in the base CEL context." Only the second was ever its purpose. A bare >= 2 relaxation would have preserved correctness but sent every node.status through resolve_path — which would have re-derived the same answer from the same get_node_property call, one layer deeper, for nothing. The property check keeps the original intent intact while admitting exactly the new case.

On the ordering question — does the new gate match what resolve_path does internally? Yes, exactly, and this is the load-bearing detail:

// enrich_context gate, graph_resolver.rs:309
if path.segments.len() == 2 && get_node_property(root_node, &path.segments[1]).is_some()
// resolve_path's per-segment walk, graph_resolver.rs:126
if let Some(prop_val) = get_node_property(&current_node, segment) { /* Scalar */ }
// ...only then:
let related = self.fetch_related_nodes(&current_node, segment).await;

Same function, same argument, same precedence. So for a name that is both a property and a relationship, property wins in the gate and property wins in the resolver — they cannot disagree. The gate is a pure short-circuit of work resolve_path would have done identically. That is the correct invariant, and it is the one that makes this substitution safe rather than merely plausible. (Which should win is a separate design question, unchanged by this PR: property-first is the pre-existing semantics, and this commit preserves it rather than picking a new answer.)

actions.rs's > 2 → >= 2 is also correct, but for a different reason worth distinguishing: there the property case is excluded not by a gate but because navigate_json has already returned Ok and the Err(_) arm is unreachable for properties. Different mechanism, same net precedence. ✅

On the coverage choice. The author tested at enrich_context rather than evaluate_conditions, and said so openly rather than letting it pass as equivalent. I judge that sufficient: the defect was a gate, the gate lives in enrich_context, and enrich_context_resolves_a_terminal_reverse_segment (graph_resolver.rs:1751-1805) fails if it is reverted — the author's mutation table confirms 1 test failing on exactly that mutation. The layer above is shared with already-covered multi-hop paths. The credit here is the diagnosis, not just the fix: the author reproduced the failure before fixing it, which is what distinguishes this from a speculative patch.

Finding 2 — Err(_) swallowed DB failures. Fixed correctly. Variant discrimination independently verified.

📁 packages/core/src/playbook/graph_resolver.rs:239-246

I traced every error return in resolve_relationship_name (rel_ops.rs:187-321) rather than accepting the claim:

Line Variant Meaning
rel_ops.rs:205 Internal get_schema_node failed
rel_ops.rs:229 Internal get_inbound_relationships failed
rel_ops.rs:246 Internal untyped-relationship probe failed
rel_ops.rs:320 InvalidParams undeclared in either direction

InvalidParams is returned at exactly one site, and it is the undeclared case. There is no NotFound, Validation, or other variant on this function's error paths. The discrimination is exact, not approximate — no genuine failure is classified as "undeclared," and no undeclared name is classified as a failure. ✅

Caller behavior traced. resolve_path's Err(e) arm (graph_resolver.rs:172-180) warn!s and yields Missing. So a DB failure now logs and yields a false condition, where before it yielded a false condition silently. That is the entire intended delta. No caller behaves worse: Missing was already the outcome, so this adds a diagnostic without changing control flow. A genuinely-undeclared name stays non-noisy — it returns Ok(vec![]) and never reaches the warn!, which was the design constraint the original Err(_) existed to satisfy. Both halves preserved. ✅

Finding 3 — per-rule resolver construction discarded the cache. Fixed. Safe. The staleness question resolves in its favor — see below.

📁 packages/core/src/playbook/engine.rs:895-900
📁 packages/core/src/playbook/workflow_state.rs:183-187

Root-scoping claim — verified for both sites.

  • workflow_state.rs: the loop is for rule_ref in &candidate_refs, and every iteration passes the same node (the function's single parameter) into evaluate_one_condition. There is no second node in scope. Trivially one root. ✅
  • engine.rs: the loop is for rule_ref in &work_item.rules, and every iteration passes &work_item.trigger_node. ExecutionWorkItem (types.rs:283-290) carries exactly one trigger_node field — not a collection. Structurally, a work item cannot carry multiple trigger nodes. ✅

No nested loop, no action-produced node, and no alternate root reaches either resolver. And even if one did, the (String, Vec<String>) key from commit 2 would keep the entries apart — so root-scoping is a genuine second line of defense here, not the only one.

Staleness — investigated specifically, as the highest-risk aspect. The concern is real in shape: in engine.rs the resolver now outlives execute_actions (engine.rs:961), and actions genuinely mutate the graph — execute_update_node (actions.rs:1295) and execute_add_relationship (actions.rs:1345) both write. So rule 1's action can change a node that rule 2's condition reads, and rule 2 would now read a cached pre-mutation value where before it re-fetched.

It is nonetheless not a regression, for a reason the author's comment does not give. Two independent facts:

  1. Sequential rules on one work item already evaluated against a stale snapshot. work_item.trigger_node is described in types.rs:288 as a pre-fetched node, captured when the work item was built. Every rule in the loop evaluates against that same frozen Node value. If rule 1's action updates the trigger node, rule 2 already reads the pre-action copy — before this commit and after it. The engine's existing semantics for a work item are "evaluate all rules against the state that triggered them." Caching related nodes across rules is consistent with that contract, not a departure from it. A resolver that re-fetched related nodes while the root stayed frozen was arguably the more incoherent of the two.
  2. Rule-triggered mutations re-enter through the event queue, not this loop. Actions run against scoped_for_playbook (actions.rs:922, node_service/mod.rs:2301), which tags mutations with a PlaybookExecutionContext so they emit events that produce new work items with freshly-fetched trigger nodes and fresh resolvers. The cascade is served by re-entry, which is exactly where the re-read happens.

So the staleness window is bounded by one work item, and within that window the engine was already snapshot-based. No behavioral regression. I would, however, have liked this stated in the comment — see 🟢 finding #6.

Finding 4 — reserved_relationship_names() → const. Fixed correctly.

📁 packages/core/src/models/schema.rs:110-131

Verified against BUILTIN_RELATIONSHIPS (schema.rs:67-72): all 8 spellings present, in source order, forward-then-reverse per pair — member_of, has_member, has_child, child_of, mentions, mentioned_by, has_role, role_of. No transposition, no omission.

The assertion is load-bearing, and slightly better than the one it parallels. BUILTIN_RELATIONSHIP_NAMES's guard compares len() == len(); this one compares len() * 2 == len(), which is the right relation for a two-per-entry table. It fires at compile time on a fifth BUILTIN_RELATIONSHIPS entry. ✅

All three call sites updated — schema/mod.rs:465, node_service/schema.rs:784, node_service/schema.rs:879. grep for reserved_relationship_names across packages/ returns zero remaining references, so no dead function was left behind (CLAUDE.md: delete, don't deprecate). ✅

Finding 5 — untested coupling between reservation and resolver ordering. Fixed. The test asserts something real.

📁 packages/core/tests/schema_relationship_declarations_test.rs:451-508

a_builtin_inverse_always_resolves_to_the_builtin has two halves and both bite:

  • expect_err("precondition: a built-in inverse cannot be declared") — fails if the reservation is relaxed.
  • assert_eq!(forward_name, "has_child") and assert_eq!(source_type, None) — fails if the built-in-inverse branch (rel_ops.rs:192-197) is removed or moved below the schema lookup, and the match has a panic! catch-all rather than a silent pass.

Asserting source_type == None is the detail that makes this more than a smoke test: it pins the "a built-in has no declarer, so do not narrow" decision, which is where a plausible future refactor would go wrong. The author's mutation table reports 1 and 2 test failures for the two relevant mutations, consistent with this. ✅


🟢 New — Suggestions (neither blocks)

6. The hoisting comments assert cache safety without naming the staleness reason.
📁 packages/core/src/playbook/engine.rs:895-899
📁 packages/core/src/playbook/workflow_state.rs:183-186

Both comments say the same thing: "Safe because cache entries are scoped to the root they came from." That is true and it is the right answer to the wrong-node question — but it is not the answer to the question a future reader will actually ask at engine.rs:895, which is: "actions run at line 961, inside this loop; how is a later rule not reading a stale cached related node?" Root-scoping does not address that at all; the two facts in finding #3 above do.

This is the one place in a heavily- and thoughtfully-commented diff where the comment defends a narrower claim than the code needs. The risk is concrete: the next person to widen the loop, or to reorder actions relative to conditions, will read this comment, find it satisfied, and not realize the snapshot contract was the load-bearing premise.

Suggested addition at engine.rs:895 (the workflow_state.rs one is fine as-is — it has no actions in its loop):

// Stale reads are not a concern here: every rule already evaluates against
// the same pre-fetched `work_item.trigger_node`, so a work item is a
// snapshot by construction. A rule's own mutations re-enter through the
// event queue as a fresh work item with a fresh node and resolver.

Engineering principle: a safety comment should discharge the strongest objection to the code, not the most obvious one. A comment that answers a lesser question reads as complete and thereby suppresses the larger one.

7. actions.rs's >= 2 change has no test coverage at all.
📁 packages/core/src/playbook/actions.rs:417

Confirmed by exhaustive grep: BindingContext::new is called with Some(resolver) at exactly two sites (actions.rs:925, actions.rs:1461), both production. Every one of the ~40 test constructions passes None — which routes straight to the else branch at actions.rs:445 and never reaches the changed >= 2 guard. The author flagged this honestly in the PR comment; I am confirming it holds, and noting what it means.

The practical exposure is smaller than it sounds. The two halves of this PR's user-facing capability differ:

  • Play conditions (node.assignee in a when clause) go through enrich_context — covered by the new test.
  • Play action bindings ({{node.assignee}} in an action parameter) go through resolve_trigger_path — not covered.

Both are reachable by a Play author, and the second is now silently untested on the path this commit changed. It is a real gap rather than a theoretical one: a single-hop reverse binding in an action parameter is exactly as natural to write as one in a condition.

Mitigating: the change is one comparison operator, the logic is shared with resolve_path below it, and the property case is excluded upstream by navigate_json rather than by the guard — so the blast radius of a mistake here is narrow. Which is why this is 🟢 and not 🟡.

Worth noting for its own sake: BindingContext::new's third parameter is Option<GraphResolver>, and the fact that no test has ever passed Some means the resolver-backed branch of resolve_trigger_path was already untested before this PR. This commit did not create that gap, but it is the first commit to change code inside it. A follow-up issue adding one Some(resolver) binding test would close a pre-existing hole, not just this one.

Engineering principle: an Option dependency that every test supplies as None is a seam where coverage silently stops — the tests compile, pass, and prove nothing about the branch that production always takes.


CLAUDE.md compliance

Re-checked across 857fb9c2 specifically:

  • ✅ No lint suppression, no #[allow(dead_code)], no #[deprecated] — and reserved_relationship_names() was deleted rather than left beside its replacement, which is the rule applied correctly.
  • ✅ No migration, no backfill, no version gate, no schema-version check.
  • ✅ No GitHub issue numbers in code comments or doc comments. (The PR body references them; that is process, not documentation content, and is fine.)
  • ✅ No .md files added to this repo.
  • ✅ Clippy clean at --all-targets.

What this round gets right

  • The property-check gate. Substituting the right predicate rather than loosening the wrong one, and matching resolve_path's own get_node_property-first ordering so the two provably cannot disagree. This is a better fix than the review asked for.
  • Reproducing before fixing. "Wrote a test at enrich_context and watched it fail" is the difference between a fix and a guess, and the mutation table generalizes that discipline to all five findings.
  • Exact variant discrimination in finding Create design system foundation #2, verified against every error site rather than the likely one.
  • Declining the offered escape hatch. The prior review explicitly permitted filing a follow-up and amending the checkbox instead of fixing finding Set up Tauri + Svelte project structure #1. The author fixed it — "the criterion is the feature" — which is the correct call and one that cost more than the alternative.
  • Honest disclosure of the coverage gap in actions.rs rather than letting the passing suite imply coverage. Finding Svelte frontend renders with placeholder panels #7 exists because the author volunteered it.

Recommendation: APPROVE

All five prior findings are genuinely and correctly addressed — verified independently against the code, not accepted from the summary. The two changes that altered runtime behavior (#1 and #3) are both correct: the gate substitution preserves resolve_path's own property-first precedence exactly, and the resolver hoisting is safe on both root-identity and staleness grounds, the latter because a work item was already a snapshot before this commit.

1482 Rust lib tests pass, clippy is clean, and issue #2641's second acceptance criterion is now met end-to-end through the boundary Play conditions actually call.

Findings #6 and #7 are 🟢 and do not block: #6 is a comment that should discharge a stronger objection than it does, and #7 documents a pre-existing coverage seam in BindingContext's optional resolver that this commit changed code inside but did not create. Both are worth a follow-up; neither is worth another round.

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

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Round 2 addressed — 2 of 2, none skipped

Both in 74d2eb89. Gate passed; 1483 Rust lib tests pass (up from 1482).

Neither finding blocked — the verdict was APPROVE — but both were one comment and one test respectively, so deferring them to a follow-up would have cost more than doing them.

🟢 6 — the hoisting comment answered the wrong objection

You were right, and the gap was in my reasoning rather than the code. I justified the longer-lived cache with "entries are scoped to the root they came from." That answers "could a rule be served another node's answer?" — but actions run inside that loop, so the question a reader actually arrives with is "how does a later rule not read a stale node?" Root-scoping is silent on that.

engine.rs now states the two facts that actually carry it: a work item is a snapshot by construction (every rule evaluates against one pre-fetched trigger_node), and a rule's own mutations re-enter through the event queue as a fresh work item with a fresh resolver.

Left workflow_state.rs as-is per your note — no actions in that loop, so root-scoping really is the whole answer there.

Worth saying plainly: I flagged staleness to the reviewer as something I hadn't reasoned about. It resolved in the code's favor, but my comment was asserting a narrower claim than the code needed, which is exactly how a future widening of that loop would look safe on a premise that never covered it.

🟢 7 — actions.rs's >= 2 had no coverage

Added action_binding_resolves_a_single_hop_reverse_path — the first test in the file to construct BindingContext with Some(resolver). It asserts {{trigger.node.assignee}} resolves to the assignee node, and that {{trigger.node.assignee.email}} still chains.

Verified load-bearing: reverting the guard to > 2 fails it with path segment 'assignee' not found.

This closes the pre-existing hole you identified, not just this PR's slice of it. Both halves of the capability are now covered — conditions through enrich_context, action bindings through resolve_trigger_path.


Cumulative verification

Every behavioral change in this PR is mutation-tested, each failing exactly the tests that name it:

Mutation Tests failed
actions.rs guard back to > 2 1
enrich_context gate back to <= 2 1
Remove source_type narrowing 1
Disable built-in reverse branch 2
Reservation back to forward-only 1
Cache key back to segments-only 2

No re-review needed — one comment and one test, no behavior change.

malibio and others added 4 commits September 17, 2026 14:18
A Play condition could only walk relationships forward:
fetch_related_nodes hardcoded direction "out", so reading an edge from
the end that did not declare it was unreachable — a task could not read
its project, assignee or parent.

Rather than add a second resolution rule, share the one that already
exists. ops::rel_ops::resolve_relationship_name maps a reverse name to
its stored forward name and flips the direction, and had learned two
things worth keeping: forward names win over same-spelled reverse names
on another schema, and inbound results must be narrowed to the declaring
type. That narrowing is load-bearing here — core schemas declare `tasks`
on both `project` and `person`, so an unnarrowed `node.assignee` would
also return the project.

Built-ins previously short-circuited before any reverse lookup, leaving
`child_of` unresolvable for the CLI too; resolving it from
BUILTIN_RELATIONSHIPS fixes both consumers at once.

The two consumers differ where they should: an undeclared name stays an
error on the CLI path, but degrades to an empty traversal in a Play,
since a segment reaches the relationship resolver only after failing as
a property — CEL reads that as a false condition.

Reserving the built-in inverses became load-bearing as a result. They
were free to declare while nothing could traverse by them; now a schema
declaring `reverseName: "child_of"` would be accepted and permanently
shadowed, the same inert-declaration failure the forward guard prevents.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The cache was keyed on path segments alone, so two nodes asking the same
path shared one entry — the second walk got the first's answer, a wrong
node returned with no error anywhere.

Not reachable from either production caller, which bind a resolver to a
single trigger node, and caught by a test written for something else.
Fixing it now rather than noting it: reverse traversal makes reuse across
roots (`child_of`, then `has_child` from the parent) the natural thing to
reach for, which turns a documented invariant into a trap.

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

Findings from the review on PR #2730.

1. The headline capability did not reach either production caller.
`enrich_context` skipped any path of two segments and
`resolve_trigger_path` required more than two, both on the assumption
that a two-segment path must be a property — true only while a
relationship always needed a further hop to yield a value. A terminal
reverse segment breaks it: `node.assignee` IS the value. The issue's own
worked example therefore compiled, never fired, and logged nothing.

My tests missed this by calling `resolve_path` directly, below both
gates — the unit passed while the integration path gated it out. The new
test drives `enrich_context` instead, and fails without the fix.

The gate is now a property check rather than a length check, so
`node.status` still bypasses the resolver as intended.

2. `Err(_) => Ok(vec![])` swallowed infrastructure failures. Only
`InvalidParams` means "undeclared"; `Internal` means an unreadable schema
or a locked database, and turning that into a silently false condition
hid exactly the signal worth having — while the `get_related_nodes` call
five lines below propagated the same class of error.

3. Hoisted resolver construction out of both per-rule loops. Every rule
on a work item resolves from one trigger node, so rebuilding per rule
discarded a cache about to be asked the same questions. Safe now that
cache entries are root-scoped, which also blunts the per-segment schema
lookups this PR's shared resolution introduced.

4. `RESERVED_RELATIONSHIP_NAMES` is a const with a length assertion,
matching `BUILTIN_RELATIONSHIP_NAMES`, instead of allocating a Vec.

5. Added the test tying the reservation to the resolver's ordering: the
early return for a built-in inverse is only safe because no schema can
declare one, and that join was asserted by a comment alone.

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

Both findings from the re-review of the prior commit. The verdict was
APPROVE and neither blocks; both are cheap enough that deferring them costs
more than doing them.

The engine's hoisting comment answered the wrong objection. It said cache
entries are root-scoped, which is true and is the right answer to "could a
rule be served another node's answer?" But actions run inside that loop, so
the question a reader actually arrives with is "how does a later rule not
read a stale cached node?" Root-scoping says nothing about that. The real
reasons are that a work item is a snapshot by construction (every rule
evaluates against one pre-fetched trigger_node) and that a rule's own
mutations re-enter as a fresh work item. Now stated, so that widening the
loop later does not look safe on a premise that never covered it.

The action-binding half of reverse traversal had no test. Play conditions
go through enrich_context and are covered; action bindings go through
resolve_trigger_path, which every existing test routed past by passing None
for the resolver. That branch was exercised only in production, and was
already untested before this work changed code inside it. The new test is
the first to pass Some(resolver).

Rebased onto the aggregate-binding work, which independently relaxed the
same resolve_trigger_path guard from `> 2` to `> 1` — arriving there from
for_each/sum collections rather than reverse names. Two features needing
the same guard relaxed is good evidence it encoded a walk-length assumption
rather than a rule; kept their more thorough comment and folded in the
reverse-name case.

That work also made a declared "many" relationship resolve to a Collection
regardless of current row count, so `another_schemas_forward_name_walks_inbound`
now expects a one-item Collection on its outbound leg. The inbound leg still
expects a Node: its reverseCardinality is "one", and the two ends are asked
about independently.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio
malibio force-pushed the issue-2641-direction-aware-resolver branch from 74d2eb8 to 06c238d Compare September 17, 2026 12:26
@malibio
malibio merged commit 1071030 into main Sep 17, 2026
@malibio
malibio deleted the issue-2641-direction-aware-resolver branch September 17, 2026 12:27
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.

Make graph_resolver.rs direction-aware so Play conditions can walk any relationship's reverse side

1 participant