Skip to content

Generalize flatten_chain_fields for relationships, run per-hop resolve calls concurrently - #2862

Merged
mstomar125 merged 4 commits into
mainfrom
issue-2830-resolver-caching
Sep 23, 2026
Merged

mstomar125 merged 4 commits into
mainfrom
issue-2830-resolver-caching

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Closes #2830. Two of the three findings in that issue are addressed; the third (a shared cache for resolve_field_owners/resolve_relationships/resolve_type_chain) is deliberately left out — see below.

  • Generalized dedup helper. resolve_relationships (packages/core/src/services/node_service/schema.rs) hand-rolled its own chain-walk + HashSet<String>-based dedup loop, duplicating the shape flatten_chain_fields (extends_chain.rs) already provides for fields. Extracted a generic flatten_chain_by_name<T>(chain_items, name_of) in extends_chain.rs; flatten_chain_fields is now a thin field-specific wrapper around it, and resolve_relationships was rewritten to build its per-schema relationship lists (with the existing type-system-relationship filter and owners map) the same way resolve_field_owners builds its field lists, then call the shared helper. Added a direct unit test (flatten_chain_by_name_generalizes_over_relationships) exercising the generalization over relationships.
  • Concurrent per-hop resolution. Both hot per-hop call sites called resolve_field_owners and resolve_relationships sequentially even though neither depends on the other's result:
    • validation.rs's validate_schema_path now uses tokio::try_join! — both arms react identically to either call failing (push one SchemaResolutionFailed and return), so collapsing to the first error loses no information.
    • workflow_state.rs's walk_path_against_schema uses tokio::join! instead (not try_join!): its two calls have genuinely independent degrade-and-fallback handling (distinct degraded_reasons messages, distinct schema-local fallbacks) that try_join! would collapse — a failure in one call would cancel the still-in-flight other call and discard a result that would otherwise have succeeded. tokio::join! preserves the existing independent-failure semantics while still running both concurrently.

Deliberately out of scope

No shared cache over resolve_type_chain/resolve_field_owners/resolve_relationships. The issue's own suggested approach calls this the "ideal" fix but flags it as the largest slice, and notes a smaller well-justified slice is acceptable. NodeService has no existing cache over the extends-chain edges the way PlaybookLifecycleManager::ancestor_cache does for its own consumer (graph-event/scheduled trigger matching), and building one raises real design questions this PR doesn't want to rush: cache scope (per-request vs. process-lifetime on NodeService), invalidation (a set_schema_relationships/schema-update write must invalidate it), and thread-safety. None of the three call sites this issue names are on the live engine's trigger-dispatch path — get_workflow_state is an explicitly out-of-band diagnostic query per its own module doc, and validate_schema_path runs at Play-authoring/validation time, not per-event. Left for a focused follow-up rather than folded into this change.

Test plan

  • cargo test -p nodespace-core --lib for schema::extends_chain::, playbook:: (workflow_state + validation), and services::node_service:: — all passing (18 + 446 + 162 tests)
  • cargo check -p nodespace-core clean
  • bun run quality:fix clean (rustfmt + clippy -D warnings -D clippy::unused-async)
  • Pre-push gate (bun run test:all + cargo build --bin nodespaced + test:e2e) passed in full

🤖 Generated with Claude Code

…e calls concurrently (closes #2830)

resolve_relationships now reuses the same nearest-scope-wins dedup as
resolve_field_owners via a new flatten_chain_by_name generic (keyed by a
name_of closure), replacing its own hand-rolled HashSet dedup loop.
flatten_chain_fields becomes a thin field-specific wrapper around it.

workflow_state.rs's walk_path_against_schema and validation.rs's
validate_schema_path each called resolve_field_owners and
resolve_relationships sequentially per hop despite neither depending on
the other's result. Both now run concurrently: validate_schema_path via
tokio::try_join! (both arms react identically to either call failing, so
collapsing to the first error loses nothing), and
walk_path_against_schema via tokio::join! instead, since its two calls
have genuinely independent degrade-and-fallback handling that try_join!
would collapse (cancelling the still-in-flight call and discarding a
result that would otherwise have succeeded).

Not done: caching resolve_type_chain/resolve_field_owners/
resolve_relationships across calls. NodeService has no cache over the
extends-chain edges the way PlaybookLifecycleManager's ancestor_cache
does for its own consumer, and none of the three call sites here are on
the live engine's trigger-dispatch path (get_workflow_state is an
explicitly out-of-band diagnostic query per its own module doc), so a
shared-cache primitive is left for a follow-up rather than folded into
this change.

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

Copy link
Copy Markdown
Contributor Author

Pragmatic Code Review — PR #2862 (closes #2830)

Scope check against issue #2830. The issue flagged three findings; this PR addresses #2 (sequential → concurrent per-hop resolve calls) and #3 (hand-rolled dedup → generalized flatten_chain_by_name), and explicitly defers #1 (shared cache). The issue's own "Impact" section says these call sites are diagnostic/out-of-band (get_workflow_state's module doc confirms "not the live engine's trigger-dispatch path"), and its "Suggested approach" section already treats caching as a separate, structurally harder concern (no existing cache primitive on NodeService, no design consensus on invalidation/scope). Deferring #1 to a follow-up is a reasonable, well-justified slice — not scope creep avoidance. Verdict: scope decision is sound.


1. Architectural Design & Integrity

flatten_chain_by_name<T: Clone>(chain_items: &[Vec<T>], name_of: impl Fn(&T) -> &str) is the right generalization: resolve_field_owners and the rewritten resolve_relationships now build a per-schema Vec<Vec<T>> the same way, then call one shared flattening routine instead of two divergent dedup implementations. flatten_chain_fields becomes a one-line wrapper, so no existing caller's behavior or signature changes. This is a clean DRY move with no abstraction-leakage (name_of is the natural minimal parameter, not an overgeneralized trait). Good.

2. Functionality & Correctness

  • Verified resolve_relationships's rewrite is behaviorally identical to the original hand-rolled version: type-system relationships are filtered out before both the owners map population and the chain_relationships collection (matches the original's continue inside the same loop); owners.entry(...).or_insert_with(...) reproduces the original's !owners.contains_key(...) → insert nearest-first-wins semantics exactly; flatten_chain_by_name's seen.insert dedup reproduces the original's first-occurrence-wins/chain-order output exactly. Confirmed via a full read of both old and new code side by side, not just typechecking.
  • New test flatten_chain_by_name_generalizes_over_relationships correctly exercises the generic helper over SchemaRelationship (a type with no .name-adjacent SchemaField shape), asserting nearest-scope-wins ordering. Good, targeted regression coverage for the generalization itself.
  • All 3 call sites' downstream consumers (resolve_field_owners's (fields, owners, chain) triple, resolve_relationships's (relationships, owners) pair) are unchanged in shape, so validation.rs/workflow_state.rs needed no logic changes beyond the concurrency restructuring — confirmed by diff.

3. Concurrency correctness (the PR's most subtle claim — given special scrutiny per instructions)

validation.rs (tokio::try_join!): Both original sequential error arms push an identical PlayValidationError::SchemaResolutionFailed { node_type, error: e.to_string(), location } and return — no arm inspects which call failed beyond stringifying the error. Collapsing to try_join!'s single winning error is lossless for control flow. One nuance worth naming (not blocking): previously, if resolve_field_owners failed, the reported error was deterministically its error (the second call was never invoked). With try_join!, if both calls happen to fail, the reported error is whichever future resolves first — which could now be resolve_relationships's error instead. Since both functions share the exact same resolve_type_chain/get_schema_node call shape internally, the two errors will almost always describe the same underlying failure (e.g., a DB read error), so this is a cosmetic, not semantic, difference. Improvement (non-blocking): worth one sentence in the code comment acknowledging this to preempt "why did the reported error change" confusion later.

workflow_state.rs (tokio::join!, deliberately not try_join!): I verified this against tokio::join!'s actual documented semantics rather than taking the PR description's word for it: tokio::join! polls all branches to completion and returns a tuple of their raw outputs (here, (Result<_,_>, Result<_,_>)), never short-circuiting or cancelling a sibling branch on an Err — that behavior is unique to try_join!/?-propagating combinators. The PR's claim — that try_join! here would cancel the still-in-flight, possibly-successful sibling and discard a usable result — is correct per tokio's documented contract for these two macros. I also confirmed the code's structure honors this: field_owners_result and relationship_result are extracted from tokio::join!'s output and handled by two fully independent match blocks afterward, each with its own degrade-and-fallback path and its own record_degradation call, exactly mirroring the pre-PR sequential-await structure — so the fix is a pure concurrency change with no reordering of the degradation-reporting logic (confirmed no test asserts degraded_reasons ordering, only emptiness on the happy path, so even if there were a reordering it wouldn't have been silently broken — but there isn't one).

  • Underlying safety: both resolve_field_owners/resolve_relationships only perform reads (self.store.get_extends_parent_map/get_schema_node, both via SqliteStore's dedicated read-connection path, not the writer). Running them concurrently introduces no new race on shared mutable state — this is pure read/read parallelism, and the codebase already has precedent for exactly this pattern (embedding_service.rs's tokio::join! for concurrent KNN/BM25 lookups). No new concurrency risk introduced.
  • Nit: no test forces one of the two join!-ed calls to fail while the other succeeds, which is the one scenario that would directly distinguish join!'s behavior from try_join!'s in an integration test. I looked for a way to construct this with the existing test_service() harness (real SqliteStore over a tempdir, no fault-injection seam) and don't think it's practical without new test infrastructure — flagging only for future awareness, not requesting it here.

4. Security

No new input handling, no new trust boundaries, no secrets. N/A.

5. Maintainability & Readability

Doc comments are updated to match the new implementation, not left stale — resolve_relationships's doc now correctly describes reuse via flatten_chain_by_name rather than the old "kept here rather than reused directly" rationale that the code no longer follows. Both validation.rs and workflow_state.rs sites gained explicit inline comments explaining why try_join! vs join! was chosen at that call site — this is exactly the kind of "why, not what" comment that will save the next reader from re-deriving the same reasoning. Verified via cargo doc that none of the new intra-doc links ([`flatten_chain_by_name`], etc.) are broken — the pre-existing doc-warning list (26 warnings, all pre-existing and unrelated to files touched here) contains nothing referencing this PR's new items.

6. Testing Strategy

Ran the full targeted suite locally: cargo build -p nodespace-core --lib (clean), cargo test --lib schema::extends_chain (18/18 pass, including the new generalization test), cargo test --lib playbook:: (446/446 pass, including all extends-chain-merge integration tests: test_inherited_field_through_relationship_passes_validation, test_inherited_relationship_through_relationship_passes_validation, test_own_relationship_shadows_inherited_field_of_same_name, unmet_relationship_reports_not_yet_met, etc.), cargo clippy --lib -- -D warnings (clean), cargo fmt --check (clean). Coverage is proportionate: the generalized helper gets a direct unit test, and the concurrency restructuring is exercised transitively by the existing (now-passing) integration suite for both call sites. See the "Nit" above re: no direct fault-injection test for the join!-preserves-both-results scenario — reasonable given harness limitations, not a blocker.

7. Performance & Scalability

Directly addresses the issue's finding #2 (sequential → concurrent), consistent with an existing codebase pattern for independent read-parallelism. Finding #1 (caching) is correctly left out — see scope discussion above.

8. Dependencies & Documentation

No new dependencies (tokio::join!/try_join! are already-used facilities). No public API/contract changes — function signatures are unchanged, so no external doc updates needed. Commit message and PR description accurately describe the change (verified against the actual diff, not just trusted).


Summary

This is a clean, well-scoped, well-tested refactor. The flatten_chain_by_name generalization is a straightforward DRY win with a matching regression test. The join!/try_join! split is not just plausible-sounding — I independently verified it against tokio's actual macro semantics and against the surrounding code's control flow, and it holds: try_join! is provably lossless in validation.rs (identical error arms) and join! is necessary in workflow_state.rs (independent degrade-and-fallback paths that try_join! would truncate). The scope decision to defer caching (#2830 finding #1) is well-justified by the issue's own text and by get_workflow_state's documented out-of-band status. All local checks (build, targeted tests, clippy -D warnings, fmt) are clean.

Nothing found rises to blocking. Two non-blocking suggestions noted above (a one-line comment on the try_join! error-collapsing nuance; awareness that direct fault-injection tests for the join! divergence path aren't practical with the current harness).

Recommendation: APPROVE

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor 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: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

mstomar125 and others added 2 commits September 23, 2026 06:59
…schema_path

Pragmatic-code-review on PR #2862 flagged (Improvement, non-blocking) that
collapsing the two independent resolve calls into tokio::try_join! means
the reported error string can now come from whichever call loses the
race, rather than always resolve_field_owners as before. Documents that
this is harmless: both calls fail for the same underlying chain-walk
reason against the same node type, and SchemaResolutionFailed's
node_type/location fields stay identical either way.

Skipped: the review's other (Nit) finding — no integration test forces
one of workflow_state.rs's two tokio::join!-ed calls to fail while the
other succeeds, the one scenario that would directly distinguish join!
from try_join! in a running test. The reviewer itself flagged this as
"not requested here" (the current test harness uses a real SqliteStore
over a tempdir with no fault-injection seam, so adding one would be
disproportionate scope creep for this PR).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The ultra-review's "angle J" finding: flatten_chain_by_name took
chain_items by reference (&[Vec<T>]) and cloned every surviving item,
where resolve_relationships's original hand-rolled loop moved owned
values out of schema.relationships at zero cost. Given this whole PR is
about removing per-call inefficiency, cloning on every merge was a
self-inflicted regression for the one caller (resolve_relationships)
that previously paid nothing here.

Every caller of flatten_chain_by_name/flatten_chain_fields builds its
chain_items/chain_fields buffer fresh per call and never reads it again
afterward, so there is nothing a &[Vec<T>] + Clone signature buys over
taking ownership and moving surviving items into the result. Switched
both to take Vec<Vec<T>> by value; flatten_chain_fields, resolve_field_owners,
resolve_relationships, and resolve_effective_fields (schema/mod.rs) all
updated to pass ownership instead of a borrow. This also drops the
Clone bound entirely — SchemaRelationship never needed to satisfy it.

Folded in a second small fix while touching this function: check
`seen.contains(name)` before allocating the owned String for `seen.insert`,
so a shadowed (redeclared, discarded) item costs a &str comparison
instead of a throwaway allocation — same dedup semantics, cheaper on
the common "already seen" path.

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

Copy link
Copy Markdown
Contributor Author

Address-review summary

Two review passes ran on this PR: the pragmatic-code-review agent (APPROVE, posted above) and a separate ultra-level multi-angle review (10 finder angles, posted above as a JSON findings list). Combined, all non-blocking findings were triaged as follows.

Addressed

  • [Improvement, pragmatic review] validation.rs's tokio::try_join! doc comment now notes that the reported SchemaResolutionFailed error string can vary between the two calls (whichever loses the race) where a sequential await always blamed resolve_field_owners first — documented as harmless, since both calls fail for the same underlying chain-walk reason against the same node_type.
  • [Cleanup/efficiency, ultra review — "angle J"] The real one: flatten_chain_by_name took chain_items: &[Vec<T>] and cloned every surviving item, which was a genuine regression for resolve_relationships specifically — its original hand-rolled loop moved owned values out of schema.relationships at zero cost. Fixed by having flatten_chain_by_name/flatten_chain_fields take Vec<Vec<T>> by value and move survivors instead of cloning (every caller builds that buffer fresh per call and never reuses it, so there was nothing the borrow+Clone signature bought). This also drops the Clone bound entirely. Folded in a related one-line cheapening: check seen.contains(name) before allocating the owned String for seen.insert, so a shadowed/discarded item costs a &str comparison instead of a throwaway allocation.

Skipped (with reasoning)

  • [Nit, pragmatic review] No integration test forces one of workflow_state.rs's two tokio::join!-ed calls to fail while the other succeeds (the one scenario that would directly distinguish join! from try_join! in a running test). The reviewer itself flagged this as "not requested here" — the current test harness uses a real SqliteStore over a tempdir with no fault-injection seam, so adding one would be disproportionate scope creep for this PR.
  • ["Root redundancy" / combinator finding, ultra review] Restates this PR's own documented out-of-scope decision (issue resolve_field_owners/resolve_relationships: uncached, sequential per-hop, duplicated chain-flatten logic #2830 finding 1 — no shared cache/combined resolver over resolve_type_chain). Not implemented here for the same reasons already in the PR description: no existing cache primitive on NodeService, real invalidation/scope design questions, and none of the three call sites are on the live engine's trigger-dispatch path.
  • [Loop-body duplication + implicit owners/chain_items agreement, ultra review] Valid architectural observations (both resolve_field_owners and resolve_relationships still separately walk-and-own before calling the shared flatten helper). A shared resolve_chain_owned_items-style combinator would remove this too, but that edges toward the same "combined resolver" shape the issue explicitly scoped out for a follow-up rather than this PR. Left as-is; resolve_field_owners's loop shape predates this PR and resolve_relationships was deliberately written to mirror it exactly (per the issue's own suggested approach), so this is pre-existing design being extended consistently, not new debt.

Verification after changes

  • cargo check -p nodespace-core clean
  • cargo test -p nodespace-core --lib — full suite, 1639/1639 passing (was individually verified at 18+446+162 for the touched modules before the ownership fix, then the full lib suite after)
  • bun run quality:fix clean (rustfmt + clippy -D warnings -D clippy::unused-async, full workspace incl. desktop-app/skill installer)
  • Pre-push gate (full test:all + cargo build --bin nodespaced + test:e2e) passed twice — once per commit pushed after review

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The doc-comment addition is text-only. The flatten_chain_by_name ownership change is mechanical (borrow+clone → move-by-value) with no change to dedup/shadowing semantics — every call site was updated consistently, and the full pre-push gate (unit tests, Rust test pyramid, e2e suite) passed clean twice after the change. No new functionality, no architectural change, low risk, straightforward.

The PR is ready for merge (pending the user's own sign-off, per CLAUDE.md's merge-is-not-automatic policy).

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.

resolve_field_owners/resolve_relationships: uncached, sequential per-hop, duplicated chain-flatten logic

1 participant