Repository navigation
Address ADR-078 cleanup items 1, 2, 3 and 5 (#2747) - #2750
Conversation
Item 4 is deliberately excluded — it is being fixed on #2636's branch, where it is a live correctness bug rather than cleanup. This branch does not touch graph_resolver.rs or cel.rs. ## 1. Derive the closure query's index from the direction `extends_closure_sql` derived its `INDEXED BY` target by string surgery on the endpoint column (`out_node` -> `out`). `INDEXED BY` against a wrong-but-existing index does not error — it silently pins a bad plan, and the only symptom is a slow query. The function now takes the whole `ExtendsDirection` and reads all three identifiers from `ExtendsDirection::columns`, so a second direction cannot produce a valid-but-wrong index name. The query-plan test now iterates every direction via `ALL_EXTENDS_DIRECTIONS` (adding a variant without listing it fails to compile) and asserts the pinned index matches the endpoint column before checking the plan — the mismatch a plan assertion cannot see. ## 2. Test refresh_ancestor_cache's call sites, and bound its failure All four call sites (startup, schema Created/Updated/Deleted) were uncovered; deleting any one broke no test. New `ancestry_cache_tests` module covers each one individually — verified by deleting each refresh in turn and confirming exactly one test fails. A failed refresh previously kept the previous cache with no retry and no dirty flag, so a transient DB error at startup left subtype trigger matching quietly degraded for the whole process lifetime. Added an `ancestry_dirty` flag: set on a failed refresh, checked in `handle_event`, cleared only once a new cache is installed. That bounds the degraded window to one event instead of the process, at the cost of one relaxed atomic load on the hot path. ## 3. Pin ScopeContext's no-per-row-SQL property `build_scope_context` resolves every schema read up front so `node_matches_property_filter` stays synchronous and store-free — nothing stopped a future edit putting an `await` back in the row loop. Pinned at compile time: the two filter functions are coerced to `fn` pointer type aliases, so making either `async` changes its type and stops compiling. Verified by making the filter `async` and watching the assertion fail. A runtime test cannot catch this, since there is no store handle in scope to count queries against — which is the property being asserted. A second test reads every `ScopeContext` accessor off a fully-constructed context with no `NodeService` in scope, covering the likelier regression: a field turned `Option<_>` and lazily filled. ## 5. Extract the repeated re-bucketing block The same ~12-line resolve-owners / re-bucket / validate block sat at four sites in crud.rs — the shape that produced the original wrong-bucket bug, where one site was missed. Extracted as `rebucket_and_validate(node, apply_defaults)`. Behaviour is identical at all four sites, including the asymmetric empty-fields case: a type change with no resolved fields validates nothing (no `else` branch in the original), which the `!apply_defaults` guard reproduces. The three load-bearing orderings are documented on the helper rather than re-derived per site. Tests: 1576 core lib tests pass; full `rust:test:core` green; `quality:fix` clean with no suppressions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Pragmatic Code Review — PR #2750Review Type: Initial Review (0 prior reviews, 0 prior comments; single commit Verification performed: this review did not take the PR description's mutation claims on trust. Each was independently re-run by mutating the source and observing the result, then reverting. Results are recorded per finding below. Requirements Check
📝 On item 4 — deferral is correct and properly evidenced. Issue #2747's comment thread establishes that item 4 is a live correctness bug ( 📝 On the flagged Code Review FindingsSummary: no Critical findings, no Important findings. Three minor observations, all optional. This is unusually careful work — the comments explain why rather than what, every non-obvious ordering is documented at the point it matters, and the tests were built to fail for the right reason rather than to raise a coverage number. ✅ Item 5 —
|
| Mutation | Result |
|---|---|
Delete the dirty-flag retry guard in handle_event |
✅ exactly 1 failure — a_dirty_cache_is_refreshed_before_the_next_event_is_matched |
Delete startup refresh (load_active_plays) |
✅ exactly 1 failure — startup_warms_the_cache_before_any_event |
Delete NodeCreated{schema} refresh |
✅ exactly 1 failure — a_created_schema_refreshes_the_cache |
Delete NodeDeleted{schema} refresh |
✅ exactly 1 failure — a_deleted_schema_refreshes_the_cache |
Delete handle_schema_updated refresh |
✅ exactly 1 failure — an_updated_schema_refreshes_before_the_drift_check_can_return |
Every claim in the PR description checks out. Each test fails for its own call site and no other — meaning these are four independent guards, not four tests coincidentally covered by one code path. That is the property that makes call-site coverage worth having, and it is rare to see it actually demonstrated.
The an_updated_schema_refreshes_before_the_drift_check_can_return test deserves specific credit: by passing an id resolving to no schema node, it pins the ordering (refresh precedes the drift check) rather than merely the presence of the call. Moving the refresh below the early return would fail it. That is testing the real invariant.
🟢 Suggestion: a_dirty_cache_is_refreshed_before_the_next_event_is_matched sets the flag directly — legitimate, and worth one added line
📁 packages/core/src/playbook/engine.rs:1856-1899
You asked whether setting ancestry_dirty directly, rather than inducing a real refresh failure, is "testing the test". It is not — but the reasoning is worth making explicit, because the distinction is genuinely fine.
The test would be circular if it asserted that the flag gets set on failure while setting the flag itself. It does not. It asserts the consumer behaviour: given a dirty flag and a cache known to be stale, the next unrelated event repairs it. The flag is the input to the behaviour under test, and constructing an input directly is ordinary arrange-phase work, not circularity. The producer side — that a successful refresh leaves the flag clear — is covered separately by a_successful_refresh_is_not_dirty. My mutation confirmed the consumer test genuinely bites: deleting the retry guard fails it and nothing else.
The test is also careful in a way that matters: it dispatches a task NodeCreated event, deliberately not a schema event, so none of the four schema call sites can fire. Only the dirty-flag retry can explain the recovery. Without that detail the test would prove nothing, and the inline comment says so.
What is not covered by any test is the producer half of the failure path: that refresh_ancestor_cache sets the flag when get_extends_parent_map returns Err. The doc comment reasonably argues that forcing a real I/O failure would test SQLite rather than this logic, and I agree that closing a DB handle mid-test is a poor trade. But there is a cheap middle path if you want it — assert the flag is still set after a failed refresh, i.e. that the early return at :313 does not fall through to the clear. As written, that guarantee rests on reading the control flow.
Nit / optional: this is a small gap in an otherwise thorough suite, and the existing tests cover the consequential half (recovery). Reasonable to leave. No change required.
Engineering principle: a test's value is what breaks it, not what it executes. Both of these break for the right reason.
✅ Item 1 — the index pin catches exactly the silent failure it names
📁 packages/core/src/db/sqlite_store/relationships.rs:32-60, :76-101, :2357-2435
Replacing step_from.trim_end_matches("_node") with an explicit index field on DirectionColumns removes a genuine silent-failure mode. The destructuring-bind of all three identifiers from one match means a future direction cannot supply columns without also supplying its index — the type system now enforces what a naming convention previously only suggested.
Mutation verification: I changed index: "idx_rel_out" to "idx_rel_in" — a wrong but existing index, the exact scenario the issue describes as undetectable. The test failed with the intended message. This is the finding worth highlighting, because it confirms the assertion ordering is deliberate and correct: the assert_eq! on the index name runs before the EXPLAIN QUERY PLAN check, catching a mismatch that the plan assertion structurally cannot see (a wrong-but-existing index still parses, still runs, and still returns correct rows — only slower). Had the assertions been ordered the other way, or had only the plan been checked, this mutation would have passed silently.
ALL_EXTENDS_DIRECTIONS as a const slice gives a compile-time nudge for new variants. Worth being precise about its strength: adding a variant does not by itself fail compilation, but columns()'s exhaustive match does force the author into this file, where the const sits adjacent. That is a reasonable ergonomic guard rather than an absolute one, and the comment's "fails to compile" phrasing is slightly stronger than the mechanism delivers.
🟢 Nit: consider softening that one phrase, or noting that the enforcement is the exhaustive match in columns() rather than the const itself. Purely a comment-accuracy point; the guard works.
✅ Item 3 — the compile-time pin is real, not ceremony
📁 packages/core/src/services/node_service/query.rs:666-746
You asked whether the fn-pointer aliases genuinely pin the property. They do, and I confirmed it rather than reasoning about it.
Mutation verification: I made node_matches_property_filter async. The crate failed to compile:
error[E0308]: mismatched types
706 | let _matches: MatchesFilter = NodeService::node_matches_property_filter;
| ------------- ^^^ expected fn pointer, found fn item
= note: expected fn pointer `for<'a,'b,'c> fn(&Node, &PropertyFilter, Option<_>) -> bool`
That is exactly the claimed guard, firing at compile time. The doc comment's note that bare fn items are required — a closure would coerce around an added parameter — is the detail that makes this bite rather than merely look like it does, and it is correct.
The principle is sound: a property that cannot be observed at runtime should be asserted at compile time. A runtime test genuinely cannot catch per-row I/O here, because the absence of a store handle in the signature is the property — there is nothing to count queries against. That is the honest justification, and the comment states it plainly instead of hand-waving.
The second test (scope_context_answers_every_read_from_owned_data) targets the likelier regression — a field turned Option<_> and lazily filled — by exercising every accessor with no NodeService in scope. Good instinct: it covers the realistic failure mode, not just the dramatic one.
On type_complexity: the two aliases exist because clippy's type_complexity fires on the inline signatures. I confirmed this was resolved by introducing named types — the lint's intended remedy — and not by suppression. cargo clippy --all-targets is clean with no #[allow] anywhere in the diff.
✅ The deleted-schema test's constraint — claim verified against the guard
📁 packages/core/src/playbook/engine.rs:1750-1760 (doc), guard at packages/core/src/db/sqlite_store/relationships.rs:2264-2278
The test deletes a schema outside the extends chain and documents why. I verified the claim rather than accepting it:
assert_schema_deletable calls count_schema_declaration_edges, which counts rows where (in_node = ?1 OR out_node = ?1) with both endpoints of node_type = 'schema', filtered by builtin_exclusion_sql. That exclusion is built from BUILTIN_RELATIONSHIP_NAMES (models/schema.rs:80), a 4-element array derived from BUILTIN_RELATIONSHIPS — and extends is not among them. An extends edge is therefore schema→schema and non-builtin, so it is counted, and deleting either endpoint is refused. The doc comment is accurate.
Does the test still earn its place? Yes. Given that constraint, the only reachable behaviour is "the NodeDeleted{schema} arm refreshes regardless of which schema went away" — and that is what the test pins. My mutation confirmed it: deleting that arm fails this test and only this test. The comment explaining why the subject is a non-chain schema is what stops a future reader from "fixing" the test into something that cannot run. That comment is doing real work.
✅ Project standards — clean
- No lint suppression: no
#[allow],#[expect],#[deprecated], or#[allow(dead_code)]anywhere in the diff.type_complexityresolved via named types, which is the correct remedy. - No backward-compat / migration code: the refactor deletes the old duplicated blocks outright rather than keeping them alongside. No dual-mode paths, no feature flags, no DDL or data-shape migration.
- No bare issue numbers in code comments: verified by grep over added comment lines — zero matches. Decisions are referenced as ADR-078 throughout, which is the required convention. The one
#2739-style reference that existed in the old code (— see insert_node_in_tx_no_invariant_dispatch) was replaced with a symbol reference (— see rebucket_and_validate), which is an incidental improvement. - No raw logging: the one touched log line uses the existing
warn!macro and was improved to inline formatting ({e}) plus a more actionable message ("...(will retry on next event)"). Good operational detail — the message now tells the reader the failure is bounded. - Docs: no
.mdfiles added to this repo, correct per the docs-live-in-nodespace-docsrule.
Recommendation: APPROVE
This is a clear net positive and I would merge it as-is. All four in-scope acceptance criteria are met, item 4's deferral is correct and well-evidenced, and 1576 tests pass with clippy silent.
What distinguishes this PR is that the tests were built to fail correctly rather than to execute code. I independently reproduced all seven mutation claims in the PR description and every one held, each failing exactly one test and no others. The two highest-value guards — the INDEXED BY mismatch and the async filter — both catch failure modes that are invisible to conventional runtime testing, which is precisely where a compile-time or plan-level assertion earns its keep.
The item 5 refactor, which carried the most risk, is equivalence-preserving at all four call sites including the asymmetric empty-fields case; and that asymmetry turns out to be a redundant round-trip rather than a validation gap, so the refactor is safe on a stronger basis than mere faithful copying.
The three 🟢 items are optional polish:
- A producer-side assertion that a failed refresh leaves the flag set (small, genuinely uncovered gap).
ALL_EXTENDS_DIRECTIONS's "fails to compile" comment slightly overstates its mechanism.- Nothing blocking.
None warrants another round. Merging is the author's call — this review does not merge.
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
All 7 mutation claims in the PR description were independently re-verified: each of the four refresh_ancestor_cache call sites fails exactly one test when deleted, the wrong-but-existing index name fails the plan test, the async filter fails compilation, and the dirty-flag retry guard fails its own test. 1576 lib tests pass; clippy clean with no suppressions. No Critical or Important findings; three optional 🟢 nits, none warranting another round.
…comment Both 🟢 nits from the review. No functional change. ## Test the producer side of the dirty flag Only the recovery out of the degraded state was covered, not the transition into it. A refresh that failed without setting the flag would never be retried — precisely the unbounded-window bug the flag exists to close — and no test would have noticed. `a_failed_refresh_keeps_the_previous_cache_and_marks_it_dirty` induces a real failure by dropping the `relationship` table, so `get_extends_parent_map`'s SELECT fails the way genuine I/O or corruption would, exercising the actual `Err` arm rather than a mock. Verified by mutation: removing the `ancestry_dirty.store(true, ...)` fails this test and only this test (8 others pass), which also confirms the induced store failure is genuinely reached. ## Correct the ALL_EXTENDS_DIRECTIONS comment The comment claimed adding a variant without listing it "fails to compile". That is wrong — a `const` array does not force exhaustiveness, and nothing rejects a missing variant. The real enforcement is the exhaustive `match` in `ExtendsDirection::columns`, which fails to compile on a new variant and lands the author in the right file to pick an index name. The comment now says that, and says plainly that the list is a checklist rather than the guard itself. Worth correcting rather than leaving: a comment that overstates a guarantee is worse than no comment, because a future reader may rely on enforcement that does not exist. Tests: 1577 core lib tests pass (up one). `quality:fix` clean, no suppressions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review addressed — commit
|
Closes part of #2747 — items 1, 2, 3 and 5.
Item 4 is deliberately excluded
Per the coordination comment on #2747, item 4 is a live correctness bug, not cleanup, and is being fixed on #2636's branch. This PR does not touch
graph_resolver.rsorcel.rs, so there is nothing to conflict with. #2747 stays open for item 4 to be ticked off by #2636's PR.1. Derive the closure query's index name from the direction
extends_closure_sqlderived itsINDEXED BYtarget by string surgery on the endpoint column (out_node→out). That is correct for the one direction that exists today, butINDEXED BYagainst a wrong but existing index does not error — it silently pins a bad query plan, and the only symptom is a slow query.The function now takes the whole
ExtendsDirectionand reads all three identifiers (step_from,step_to,index) fromExtendsDirection::columns(), so the index is named alongside the columns it belongs to rather than derived from one of them.The query-plan test now iterates
ALL_EXTENDS_DIRECTIONS— aconstslice that fails to compile if a variant is added without listing it — and asserts the pinned index matches the endpoint column before runningEXPLAIN QUERY PLAN. That first assertion is the one that matters: a mismatched-but-existing index still parses, still runs, and still returns correct rows, so the plan check alone cannot see it.Verified by mutation
Changing
indextoidx_rel_in(an index that exists) fails with:2. Test
refresh_ancestor_cache's call sites, and bound its failure windowCoverage. All four call sites — startup, and schema Created/Updated/Deleted — were uncovered; deleting any one broke no test. The new
ancestry_cache_testsmodule covers each individually.Verified by mutation — each call site deleted in turn
load_active_playsstartup_warms_the_cache_before_any_eventNodeCreated{schema}a_created_schema_refreshes_the_cacheNodeDeleted{schema}a_deleted_schema_refreshes_the_cachehandle_schema_updatedan_updated_schema_refreshes_before_the_drift_check_can_returna_dirty_cache_is_refreshed_before_the_next_event_is_matchedExactly one test fails per mutation — no test is standing in for another.
Bounding the failure window. A failed refresh kept the previous cache, with no retry and no dirty flag. Keeping the cache is right — stale ancestry beats dropping every Play's subtype matching — but on its own it is unbounded: a transient DB error at startup left subtype trigger matching quietly degraded for the whole process lifetime, after a single warning.
Added an
ancestry_dirtyflag: set when a refresh fails, checked at the top ofhandle_event, and cleared only once a new cache is actually installed. That turns "degraded forever" into "degraded until the next event", at the cost of one relaxed atomic load on the hot path in the common case.The
handle_schema_updatedtest passes an id that resolves to no schema node, which exercises the early-return path the refresh is deliberately ordered ahead of.3. Pin
ScopeContext's no-per-row-SQL propertybuild_scope_contextresolves every schema read up front sonode_matches_property_filterstays synchronous and store-free. The design genuinely has this property; nothing stopped a future edit putting anawaitback in the row loop — which at the 10,000-row fetch cap means up to 10,000 round-trips.Pinned at compile time: both filter functions are coerced to
fn-pointer type aliases, so making eitherasyncchanges its type fromfn(..) -> booltofn(..) -> impl Futureand stops compiling. A runtime test cannot catch this — there is no store handle in scope to count queries against, which is precisely the property being asserted.A second test reads every
ScopeContextaccessor off a fully-constructed context with noNodeServiceanywhere in scope, covering the likelier regression shape: a field changed toOption<_>and filled lazily on first use.Verified by mutation
Making
node_matches_property_filterasyncfails the coercion:5. Extract the repeated re-bucketing block
The same ~12-line resolve-owners / re-bucket / validate block sat at four sites in
crud.rs. Behaviour was correct at all four, but this is the shape that produced the original wrong-bucket bug — one site was missed. Extracted asrebucket_and_validate(node, apply_defaults).Behaviour is identical at all four sites, including the asymmetric empty-
fieldscase: on a node-type change with no resolved fields the original validated nothing at all (there was noelsebranch), which the!apply_defaultsguard reproduces exactly. The three load-bearing orderings — defaults before bucketing, bucketing before validation, and that empty-fields asymmetry — are now documented once on the helper rather than re-derived at each site.Net: −157 lines of duplication at the call sites.
Testing
bun run rust:test:lib— 1576 passed, 0 failedbun run rust:test:core— all suites greenbun run quality:fix— clean, no lint suppressions (clippy'stype_complexityon the fn-pointer assertions was resolved with type aliases, not an#[allow])test:all+cargo build+test:e2e) passed in fullNon-goals
No change to
extendssemantics, storage shape, or scope-projection behaviour — all settled in ADR-078.🤖 Generated with Claude Code