Repository navigation
Guard the live tree builder against cyclic hierarchy data (closes #2417) - #2424
Conversation
build_node_tree_recursive walked the adjacency list with no depth limit and no visited set. The adjacency list is built from relationship rows fetched separately from the depth-bounded SQL ID walk in get_subtree_with_relationships, so a has_child back-edge in that set reached the builder unfiltered by the upstream `depth < 100` cap. That matters because a Rust stack overflow aborts the process instead of unwinding, so it cannot be caught and turned into an error response. The call path is user-facing and hot — it runs on opening a page — so the symptom would have been the daemon dying with nothing surfaced to the client. The builder now returns Result<serde_json::Value, NodeServiceError> rather than degrading silently: get_children_tree already returns that error type, and NodeServiceError::CircularReference maps through OpsError::ValidationFailed to Status::invalid_argument, so a corrupt hierarchy reaches the client as a real error instead of a truncated-but-plausible tree. The visited set is path-scoped (inserted descending, removed ascending), so it rejects a genuine cycle without rejecting a node legitimately reachable through two sibling branches. MAX_TREE_DEPTH is 100, matching the SQL bound, so any subtree the collector accepts is one the builder accepts. Defence-in-depth: write-time cycle prevention already exists in is_descendant-on-move and validate_no_member_of_cycle. This covers a write-path bug, a direct DB edit, an import, or a partially-applied write. Five unit tests cover the back-edge, the self-edge, a chain past the depth ceiling, an unchanged well-formed tree (child order, leaf children arrays, uri fields), and the sibling-branch repeat that must NOT be reported as a cycle. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr
Pragmatic Code Review — PR #2424Review Type: Initial Review (zero prior reviews/comments) SummaryThis is a well-targeted, genuinely net-positive defence-in-depth fix. The problem statement is correct and precisely diagnosed: the adjacency list is built from relationship rows fetched separately from the depth-bounded SQL ID walk ( The chosen approach — change the signature to The change is atomic, adds no dependencies, introduces no backward-compat scaffolding, and carries no lint suppressions — CLAUDE.md compliant throughout. The path-scoped visited set (insert descending, remove ascending) is the correct design, not the simpler global-visited alternative — a global set would falsely reject the legitimate DAG-ish shape where a node hangs off two sibling branches, and the PR both understands this and pins it with a test. That is the detail most implementations get wrong. One real defect found: the depth ceiling is off by one against the SQL bound it explicitly claims to match, which I verified empirically rather than by reading. Details below. Requirements Check (issue #2417)
📝 Deviation note: the issue's suggested fix referenced the deleted Findings🟡 Important1. Off-by-one: the depth ceiling rejects trees the SQL collector accepts — contradicting the comment that asserts it doesn't. 📁 The doc comment makes an explicit, checkable claim:
The two are not measured the same way, so this claim is false by one level. SQL ( Builder calls the root at I confirmed this empirically with a temporary probe against the real function (reverted; working tree is clean): So a legitimate, acyclic, 100-deep hierarchy is fetched successfully by the store and then fails page-open with The fix is one character — Please also add a boundary test. The current depth test uses Principle: a comment asserting an invariant between two separately-maintained constants is only as good as the test that enforces it. An off-by-one in a safety bound is minor in isolation; an off-by-one that a comment actively tells future readers cannot exist is what makes it worth fixing now — the next person will trust the comment instead of re-deriving the CTE semantics. 2. 📁 Tracing both errors through: For the pre-existing call sites (move/reorder, where the caller proposed the cycle) that is exactly right. For this new one it is misleading in a way that matters operationally. The caller passed a perfectly valid There is direct precedent for the distinction in this very file (
I'd suggest the same treatment here. The cleanest route that doesn't disturb the existing move/reorder mappings is a dedicated variant (e.g. Principle: status codes are an API contract about who can act on the failure. Reporting a server-side data-integrity fault as a client input error misroutes both the retry decision and the alert. 🟢 Suggestions3. Consider logging before returning — this is the only signal that the graph is corrupt. 📁 Both guard arms return silently. Given the issue frames this as defence-in-depth against a write-path bug, a bad import, or a direct DB edit, the error text reaching a frontend toast may be the only trace that data corruption exists. A Principle: a defence-in-depth guard that fires is evidence of a bug elsewhere; it should be observable to operators, not only to the end user who happened to open the page. 4. Test gap: no end-to-end coverage of 📁 The five tests exercise What isn't covered is the seam this PR actually changed — Also worth one more case: a cycle nested deep inside an otherwise-large well-formed tree, asserting it errors rather than being masked by the depth guard firing first. The current cycle tests are all 1-3 nodes at the root, so they don't distinguish which guard caught it. Both are additive and neither blocks merge. 5. Nit: error message casing is inconsistent between the two guards. 📁
PerformanceThe The rewrite from Correctness notes that check out
RecommendationREQUEST CHANGES — narrowly, for finding #1. To be clear about proportionality: the core fix is correct and I'd be happy to see it merged. The one thing I do want changed before merge is the off-by-one, because it is a real (if narrow) behavioural regression against acceptance criterion 4, the fix is a single character, and the accompanying comment currently tells future maintainers the bug is impossible — that comment is what turns a triviality into something worth blocking on. Add the boundary test alongside it so the SQL/builder alignment stays pinned. Finding #2 ( |
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
## Fixed the depth guard's off-by-one (review 🟡) The ceiling was misaligned with the SQL walk it claimed to match, and the doc comment asserted the alignment as fact — so a future maintainer would have trusted it rather than re-deriving the CTE semantics. get_subtree_with_relationships seeds direct children at `depth = 1` and expands while `s.depth < 100`, so the deepest row it emits is 100 edges below the root. The builder starts the root at `depth = 0` and rejected at `depth >= MAX_TREE_DEPTH`, so a node exactly 100 edges down arrived with `depth == 100` and was refused — a hierarchy the store returns happily would have failed page-open with "Hierarchy constraint violated". The guard meant to prevent an abort on corrupt data would instead have broken valid data. Rejecting at `depth > MAX_TREE_DEPTH` restores the alignment, and the comment now spells out the seeding difference that makes `>` rather than `>=` correct. The old test used MAX_TREE_DEPTH + 5, which passes under both the correct and the off-by-one bound and so could not detect this class of error. It is replaced by two tests straddling the boundary, sharing a chain-builder helper: - accepts_a_chain_at_exactly_max_depth — builds and walks all 100 edges to the bottom, proving the whole chain materialized, not just the root - returns_error_one_edge_past_max_depth — one edge further must still error Verified the boundary test actually pins the behavior: with `>=` temporarily restored it fails, and passes with `>`. It is not a vacuous assertion. ## Logged both guards before returning (review 🟢) Neither guard left a server-side trace, so a corrupt stored graph surfaced only as a failed page open that says nothing about which edge is bad. Both now emit a tracing::warn! with node_id and depth first. Also lowercased the depth message to match the cycle arm (review 🟢 nit). ## Deferred: gRPC status code for stored-data corruption (review 🟡) Filed as a follow-up rather than fixed here. CircularReference and HierarchyViolation map through OpsError::ValidationFailed to Status::invalid_argument, which is right for the write paths that raise these same variants (is_descendant on move, validate_no_member_of_cycle) where the caller genuinely proposed the cycle — but misleading on this read path, where the request is valid and the persisted graph is not. Both variants are raised in nine places across hierarchy.rs, so remapping them globally would wrongly reclassify the write-path cases. Honest reporting needs a new variant threaded through OpsError and the status mapper — shared error plumbing that deserves its own change and review, not a rider on this one. ## Skipped: end-to-end get_children_tree propagation test (review 🟢) Seeding a store with a cycle requires bypassing the write-path guards at the SQL level, which is disproportionate to covering a single `?`. The error mapping it would exercise is already covered. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr
…loses #2425) Folds in the status-code finding deferred from the review of this PR. The two read-path guards raised CircularReference/HierarchyViolation, which map through OpsError::ValidationFailed to Status::invalid_argument. That told the client its request was bad when the request was fine and the *stored graph* was not — nothing the caller could change, retrying identically fails identically, and the corruption was counted as client misuse rather than landing in server-error reporting. Remapping those two variants globally was not an option: they are raised in nine places across hierarchy.rs (is_descendant on move, member_of validation), where the caller genuinely does propose the cycle and invalid_argument is the honest answer. So this adds a distinct variant instead: NodeServiceError::CorruptHierarchy -> OpsError::Internal -> Status::internal Follows the precedent already set for a schema node that exists but fails to parse — "a stored-data bug, not a caller error" -> internal. Three tests pin the distinction at the mapping layer, where it actually matters: - corrupt_hierarchy_returns_internal, also asserting the offending node id survives into the message - caller_proposed_cycle_stays_invalid_argument, covering both write-path variants together so the two classifications cannot silently collapse into one - the three builder guard tests now assert CorruptHierarchy Checked that no frontend code matches on the old "Circular reference" / "Hierarchy violation" message prefixes, so changing them breaks no caller. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr
Address-Review SummaryAll four review findings are now resolved — three fixed in ✅ 🟡 Off-by-one in the depth ceiling — FIXED (
|
Pragmatic Code Review — PR #2424 (Re-Review)Review Type: Re-Review (against prior review of Previous Review Summary4 findings, 2 Important + 2 Suggestion, plus one deferred item that got its own commit:
No new issues found that block merge. Two small nits noted below. Requirements Check (issue #2417)
Verification performed
SQL (packages/core/src/db/sqlite_store/nodes.rs:1534-1541) seeds direct children at depth = 1 in the WITH RECURSIVE walk, and expands a row only while s.depth < 100, producing a child at depth + 1 which can reach at most 100. Deepest emitted row: depth = 100, i.e. 100 edges below root. This matches the commit message claim exactly. Builder (mod.rs:1865-1899): root at depth = 0, guard fires on depth > MAX_TREE_DEPTH (100). A node 100 edges down arrives with depth == 100; 100 > 100 is false, so it is accepted. A node 101 edges down arrives with depth == 101 and is rejected. This exactly matches the SQL reach: everything the SQL collector can return, the builder accepts; the first thing it rejects is exactly one edge past the SQL ceiling. No new over-claim in the doc comment — its specific numeric claims (seed at 1, expand while less than 100, deepest row 100 edges below root) are all independently verified accurate, unlike the prior comment which asserted an alignment that was not actually there.
The helper builds ids for (0..=edges), giving edges+1 node ids, n0 through n{edges}. Taking windows(2) over that list yields exactly edges adjacent pairs, i.e. exactly edges parent-to-child edges. So build_chain_of_depth(MAX_TREE_DEPTH) produces a chain of exactly 100 edges, matching the SQL deepest reachable row precisely, not 99 or 101. The helper is correct. accepts_a_chain_at_exactly_max_depth also walks all 100 child hops down to the terminal node and asserts its id is n100, so it proves the entire chain materialized, not merely that the root call did not error. That would catch a bug where the guard let the call through but silently truncated the chain somewhere in the middle. Ran the tests directly and both passed: build_node_tree_recursive_accepts_a_chain_at_exactly_max_depth and build_node_tree_recursive_returns_error_one_edge_past_max_depth.
NodeServiceError::CorruptHierarchy(String) in services/error.rs maps to OpsError::Internal in ops/mod.rs, which the existing Internal arm of the status mapper turns into Status::internal. This classification is correct: the caller request was well-formed, the persisted graph is not, retrying identically cannot help, and this now lands in server-error reporting rather than being counted as client misuse, matching the precedent already set for a schema node that exists but fails to parse. Confirmed via grep that all nine write-path call sites in hierarchy.rs are untouched and still construct hierarchy_violation or circular_reference; none were accidentally rerouted to CorruptHierarchy. Only the two new read-path guard sites in mod.rs use the new variant. The core crate compiles clean with no wildcard added to the From for OpsError match, confirming the match stayed exhaustive and every existing arm is intact. Ran the three new or changed tests directly: error_mapping_caller_proposed_cycle_stays_invalid_argument, which asserts both old variants together, and error_mapping_corrupt_hierarchy_returns_internal, which asserts both the status code and that the offending node id survives into the message. These are not vacuous: a wrong mapping would fail the code assertion, and collapsing the two write-path variants onto Internal would fail the paired test. Searched the whole workspace for other exhaustive matches on NodeServiceError that might need updating for the new variant. None of the other matching sites match exhaustively on NodeServiceError itself; that only happens once, in ops/mod.rs. Nothing missed.
Both guards use fully-qualified tracing::warn! with structured fields, consistent with the existing convention elsewhere in hierarchy.rs. On spam risk: the call graph propagates the error via question-mark on the very first failing child, so the first guard to fire anywhere in the walk aborts the entire call immediately and sibling subtrees are never visited afterward. Exactly one warning fires per failed top-level build call, not one per node. No spam risk.
Code Review FindingsNo Critical or Important findings. Two optional nits: Nit, in services/error.rs and ops/mod.rs: CorruptHierarchy carries a plain String, matching HierarchyViolation shape rather than the struct-variant shape CircularReference uses. Fine as-is since both shapes already coexist in this enum; pre-existing style, not something this PR needs to fix. Nit, in services/node_service/mod.rs around the two guards: they duplicate the log-then-construct-error shape. A tiny helper could de-dup a few lines, but each arm carries different structured fields so the savings are marginal, not worth the churn for two call sites. RecommendationAPPROVE. All four prior findings are genuinely fixed, not just claimed-fixed. The off-by-one was independently re-derived from the SQL and confirmed to match exactly at both boundaries. The test helper that pins it was checked for its own off-by-one and is correct. The mutation claim was reproduced live: reverting failed, restoring passed, and the working tree was left clean. The CorruptHierarchy routing was traced end-to-end through ops/mod.rs and confirmed not to have touched any of the nine legitimate write-path invalid_argument sites. The new tests pin the actual distinctions rather than passing vacuously. No regressions, no message-string breakage, clean clippy, all tests pass. This is ready to merge. |
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): APPROVE (posted as a comment, GitHub blocks self-approval). Full findings in the review comment above.
Conflict in packages/core/src/services/node_service/mod.rs was purely positional: both sides appended tests to the end of the same `mod tests` block — the tree-guard tests here, and the enum-edge-field tests from #2387 on main. No overlapping logic, so both sets are kept. The conflict boundary had also swallowed the closing brace of the last tree-guard test; restored. Verified after resolution: 1252 core lib tests pass (both the 6 tree-guard tests and main's enum-edge-field tests among them), cargo check --lib --tests clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr
Problem
build_node_tree_recursive(packages/core/src/services/node_service/mod.rs) walkedadjacency_listwith no depth limit and no visited set.The upstream
WHERE s.depth < 100bound inget_subtree_with_relationshipsapplies to the SQL ID-collection query. The relationship set is queried separately and used to buildadjacency_listin memory, so ahas_childback-edge present there is not filtered by that cap — the in-memory rebuild was unguarded.This matters because a Rust stack overflow aborts the process rather than unwinding, so it cannot be caught and turned into an error response. The call path is user-facing and hot — it runs on opening a page:
backend-adapter.ts→ Tauri command (commands/nodes.rs) → gRPC daemon (daemon/src/services/node_service.rs) →get_children_tree(hierarchy.rs) → the unguarded builderSo the symptom would have been the daemon dying when a user opens an affected page, with no error surfaced.
Fix
build_node_tree_recursivenow returnsResult<serde_json::Value, NodeServiceError>and delegates to a guarded body carrying a depth counter and a visited set.Error, not graceful degradation. The issue flagged this as worth deciding deliberately.
get_children_treealready returnsResult<_, NodeServiceError>, and the mapping is already wired end to end —NodeServiceError::CircularReference→OpsError::ValidationFailed→Status::invalid_argument. So a corrupt hierarchy reaches the client as a real error rather than a truncated-but-plausible tree that hides the corruption.The visited set is path-scoped — inserted descending, removed ascending. That rejects a genuine cycle without falsely rejecting a node legitimately reachable through two sibling branches (malformed-but-acyclic data, which should still render).
MAX_TREE_DEPTHis 100, matching thedepth < 100SQL bound, so any subtree the collector accepts is one the builder accepts.This is defence-in-depth. Write-time cycle prevention already exists (
is_descendanton move,validate_no_member_of_cycle); this covers a write-path bug, a direct DB edit, an import, or a partially-applied write. Low probability, high blast radius, cheap fix.Tests
Five unit tests on the pure builder (no DB needed):
..._returns_error_on_back_edge—a → b → c → areturnsCircularReferenceinstead of recursing..._returns_error_on_self_edge— the tightest cycle, a node listed as its own child..._returns_error_beyond_max_depth— an acyclic chain past the ceiling, so only the depth guard can stop it..._builds_well_formed_tree_unchanged— child order,urifields, and empty-array-not-missing-key on leaves..._allows_repeat_across_sibling_branches— a node under two branches must build, not be reported as a cycleVerification
bun run test:all— exit 0; 232 frontend test files / 4863 tests passing (matches baseline), all Rust suitesokbun run quality:fix— 0 ESLint errors, 0 svelte-check problems, clippy clean under-D warningscargo check --workspace --all-targets— clean, no warningsCloses #2417
🤖 Generated with Claude Code
https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr