Skip to content

Guard the live tree builder against cyclic hierarchy data (closes #2417) - #2424

Merged
malibio merged 4 commits into
mainfrom
issue-2417-tree-cycle-guard
Sep 7, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2417-tree-cycle-guard

Conversation

@malibio

@malibio malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Problem

build_node_tree_recursive (packages/core/src/services/node_service/mod.rs) walked adjacency_list with no depth limit and no visited set.

The upstream WHERE s.depth < 100 bound in get_subtree_with_relationships applies to the SQL ID-collection query. The relationship set is queried separately and used to build adjacency_list in memory, so a has_child back-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 builder

So the symptom would have been the daemon dying when a user opens an affected page, with no error surfaced.

Fix

build_node_tree_recursive now returns Result<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_tree already returns Result<_, 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_DEPTH is 100, matching the depth < 100 SQL bound, so any subtree the collector accepts is one the builder accepts.

This is defence-in-depth. Write-time cycle prevention already exists (is_descendant on 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 → a returns CircularReference instead 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, uri fields, 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 cycle

Verification

  • bun run test:all — exit 0; 232 frontend test files / 4863 tests passing (matches baseline), all Rust suites ok
  • bun run quality:fix — 0 ESLint errors, 0 svelte-check problems, clippy clean under -D warnings
  • cargo check --workspace --all-targets — clean, no warnings
  • Pre-push test gate passed

Closes #2417

🤖 Generated with Claude Code

https://claude.ai/code/session_01VVLDBnc3qPG8DmmbmgHjSr

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

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2424

Review Type: Initial Review (zero prior reviews/comments)


Summary

This 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 (nodes.rs:1587-1607 fetches all has_child rows whose in_node is in the collected set, with no depth predicate), so a back-edge genuinely does reach the builder unfiltered. And because a Rust stack overflow aborts rather than unwinds, the unguarded recursion really was an unrecoverable daemon kill on a hot, user-facing path.

The chosen approach — change the signature to Result rather than degrade silently — is the right call of the two the issue offered. get_children_tree already returns Result<_, NodeServiceError>, so the error has a real channel to travel, and truncate-and-log would have silently served a partial tree the frontend would treat as authoritative. Good judgment there.

The change is atomic, adds no dependencies, introduces no backward-compat scaffolding, and carries no lint suppressions — CLAUDE.md compliant throughout. cargo clippy -p nodespace-core --lib --all-features and cargo fmt --check are both clean, and all five new tests pass.

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)

Acceptance criterion Status
build_node_tree_recursive cannot recurse unboundedly on cyclic or malformed adjacency_list data ✅ Both a depth ceiling and a path-visited set; either alone terminates the walk
A cycle or excessive depth produces a handled error, never a stack-overflow abort ✅ CircularReference / HierarchyViolation, propagated via ? out through get_children_tree
A regression test constructs an adjacency_list containing a back-edge and asserts the call returns rather than crashing ✅ ..._returns_error_on_back_edge (a→b→c→a) plus ..._returns_error_on_self_edge (a→a)
Existing get_children_tree behaviour on well-formed data is unchanged ⚠️ Mostly — pinned at the builder level by ..._builds_well_formed_tree_unchanged (order, uri, empty-children-array contract all asserted). But see 🟡 #1: a 100-edge-deep tree that the SQL layer collects and that previously rendered is now rejected. Narrow, but it is a behavioural change on well-formed data.

📝 Deviation note: the issue's suggested fix referenced the deleted SqliteStore implementation as a reference. This PR improves on it — that one used a global visited set semantics ("node appears multiple times"), whereas this correctly scopes to the current path. Deliberate divergence, and the better choice.


Findings

🟡 Important

1. Off-by-one: the depth ceiling rejects trees the SQL collector accepts — contradicting the comment that asserts it doesn't.

📁 packages/core/src/services/node_service/mod.rs:1841-1846 (const + doc) and :1884-1889 (the guard)

The doc comment makes an explicit, checkable claim:

Matches the depth < 100 bound on the WITH RECURSIVE walk in get_subtree_with_relationships, so any subtree the SQL collector accepts is one this builder accepts too.

The two are not measured the same way, so this claim is false by one level.

SQL (packages/core/src/db/sqlite_store/nodes.rs:1534-1541) seeds direct children at depth = 1, and expands any row with s.depth < 100 into children at s.depth + 1. The deepest row it can emit is therefore depth = 100 — i.e. 100 edges below the root.

Builder calls the root at depth = 0, each child at depth + 1, and rejects at depth >= 100. A node 100 edges below the root arrives with depth == 100 and is rejected. Deepest accepted is 99 edges below root.

I confirmed this empirically with a temporary probe against the real function (reverted; working tree is clean):

PROBE edges=98  ok=true
PROBE edges=99  ok=true
PROBE edges=100 ok=false   <-- SQL collects this tree; builder rejects it
PROBE edges=101 ok=false

So a legitimate, acyclic, 100-deep hierarchy is fetched successfully by the store and then fails page-open with Hierarchy constraint violated. That is exactly the regression the fourth acceptance criterion is guarding against, and exactly what the comment promises cannot happen.

The fix is one character — depth > MAX_TREE_DEPTH, or equivalently MAX_TREE_DEPTH = 101 — but I'd prefer changing the comparison and leaving the constant reading 100, since the constant is what a reader cross-references against the SQL literal.

Please also add a boundary test. The current depth test uses MAX_TREE_DEPTH + 5, which passes under both the correct and the off-by-one bound — it cannot detect this class of error. A test asserting exactly the deepest SQL-collectable chain builds successfully, plus one edge more failing, would have caught it and would pin the alignment permanently.

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. invalid_argument is the wrong client-facing status for server-side data corruption.

📁 packages/core/src/ops/mod.rs:78-83 → packages/daemon/src/services/node_service.rs:2016, 2023-2025

Tracing both errors through: CircularReference and HierarchyViolation both map to OpsError::ValidationFailed, which ops_error_to_status maps to Status::invalid_argument → gRPC InvalidArgument.

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 node_id; nothing about the request is invalid. What is wrong is the persisted graph. InvalidArgument tells the client "fix your request" — the client cannot; retrying identically will fail identically, and any client-side retry/backoff logic keyed on 4xx-equivalent semantics will draw the wrong conclusion. It also means the condition will not show up in server-error dashboards, which is precisely where a corrupted-hierarchy alarm belongs.

There is direct precedent for the distinction in this very file (node_service.rs:1371-1376), which comments the reasoning explicitly:

present schema node that failed to parse → internal (a stored-data bug, not a caller error)

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. NodeServiceError::CorruptHierarchy) mapped to OpsError::Internal, rather than re-pointing CircularReference wholesale — several other call sites legitimately want invalid_argument. If that feels heavier than the bug warrants, a follow-up issue is a reasonable pragmatic call; the abort is fixed either way, which is the part that matters. Flagging it as Important rather than Critical for that reason.

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.


🟢 Suggestions

3. Consider logging before returning — this is the only signal that the graph is corrupt.

📁 packages/core/src/services/node_service/mod.rs:1884-1895

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 tracing::error! (or warn!) with the node id at the point of detection would make this diagnosable from daemon logs without needing a user to report the toast — and would give you something to grep for when deciding whether the write-path guards have a hole.

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 get_children_tree error propagation.

📁 packages/core/src/services/node_service/mod.rs:5889+

The five tests exercise build_node_tree_recursive directly and are genuinely good — they'd fail against several weaker implementations, and I checked the depth test is truly acyclic (a linear n0→n1→… chain), so only the depth guard can stop it. The sibling-branch test is the standout: it would catch a naive global-visited-set implementation, which is the most likely wrong turn here.

What isn't covered is the seam this PR actually changed — get_children_tree propagating rather than swallowing. That's now a ? on the last expression so it's hard to get wrong, but it is the boundary a future refactor could regress silently. grep confirms there is currently no test of get_children_tree anywhere in packages/core or packages/daemon, so nothing else covers it either.

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.

📁 packages/core/src/services/node_service/mod.rs:1885-1893

"Maximum tree depth (100) exceeded at node 'x'" is sentence-cased; "node 'x' appears more than once on the same branch" is lower-cased. Both get a capitalised prefix from the thiserror display strings, so the lower-case one reads slightly better in composition — but pick one and apply it to both.


Performance

The node.id.clone() per node on the way down is fine — call it out only if it matters, and it doesn't. It is one short-String allocation per node, against a function that is already allocating a full serde_json::Value object per node and serialising every property. The clone is comfortably in the noise relative to work already being done, and the set is path-scoped so it holds at most MAX_TREE_DEPTH entries at a time, not one per tree node. No change recommended; optimising here would trade real clarity for unmeasurable gain.

The rewrite from filter_map/collect to an explicit for loop is necessary (? can't propagate out of the closure) and is not a readability regression.

Correctness notes that check out

  • Visited-set consistency on early return: when the depth guard fires or a child errors, visited.remove is skipped on the unwinding frames, leaving stale entries. This is harmless and I'd leave it alone — the error propagates via ? all the way out of build_node_tree_recursive, the HashSet is created fresh per top-level call (:1863) and dropped immediately, so no caller ever observes the inconsistent state. Worth knowing it's deliberate-by-consequence rather than by construction; if the guarded fn ever gained a recover-and-continue path this would become a live bug. Not worth restructuring today.
  • ? placement: push(build_node_tree_guarded(...)?) propagates before pushing, so no partial child is ever inserted. Correct.
  • Existing output contract preserved: children is still always present as an array on leaves, and child ordering (fractional-order sorted upstream in get_subtree_data) is preserved by the sequential loop. Both asserted.
  • CLAUDE.md: no issue numbers embedded in code comments, no suppressions, no #[allow(dead_code)], no deprecation, no migration. Compliant.

Recommendation

REQUEST 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 (invalid_argument vs internal) is a legitimate API-contract concern and I'd like a decision on it, but a follow-up issue is an acceptable resolution — it does not need to hold up the abort fix. #3-#5 are optional.

@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: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

malibio and others added 2 commits September 7, 2026 18:41
## 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
@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Address-Review Summary

All four review findings are now resolved — three fixed in e564b9df, and the deferred one folded in as 6168061a rather than left to a follow-up.

✅ 🟡 Off-by-one in the depth ceiling — FIXED (e564b9df)

The reviewer was right, and the comment was the worse half of the bug: it asserted the alignment as fact, so a maintainer would have trusted it instead of re-deriving the CTE semantics.

get_subtree_with_relationships seeds direct children at depth = 1 and expands while s.depth < 100, so its deepest row is 100 edges below the root. The builder started the root at depth = 0 and rejected at depth >= 100, so a node exactly 100 edges down was refused — a hierarchy the store returns happily would have failed to open. The guard against aborting on corrupt data would instead have broken valid data.

  • Comparison is now depth > MAX_TREE_DEPTH.
  • The doc comment states the seeding difference explicitly and says why > rather than >= is what keeps the two in step.
  • The old MAX_TREE_DEPTH + 5 test was replaced by two tests straddling the boundary, sharing a build_chain_of_depth helper: accepts_a_chain_at_exactly_max_depth (walks all 100 edges to the terminal node, proving the whole chain materialized) and returns_error_one_edge_past_max_depth.
  • Mutation-verified: with >= temporarily restored the boundary test fails; with > it passes. It is not a vacuous assertion.

✅ 🟡 invalid_argument for server-side corruption — FIXED (6168061a)

Initially deferred to #2425, then folded into this PR instead so the guards and their error semantics land together.

Remapping CircularReference/HierarchyViolation globally was not viable — they are raised in nine places across hierarchy.rs where the caller genuinely proposes the cycle and invalid_argument is correct. So a distinct variant was added:

NodeServiceError::CorruptHierarchy → OpsError::Internal → Status::internal

Following the precedent the reviewer cited at daemon/src/services/node_service.rs:1371 ("a stored-data bug, not a caller error" → internal).

Three mapping-layer tests pin the distinction: corrupt-hierarchy → internal (asserting the node id survives into the message), and both write-path variants → invalid_argument asserted together so the two classifications cannot silently collapse into one.

Also confirmed no frontend code matches on the old "Circular reference" / "Hierarchy violation" message prefixes, so changing them breaks no caller. #2425 is closed by this commit.

✅ 🟢 Guards did not log — FIXED (e564b9df)

Both guards now emit tracing::warn! with node_id and depth before returning (fully-qualified, matching hierarchy.rs:987). Without this a corrupt graph surfaced only as a failed page open that said nothing about which edge was bad. These fire on the error path only, immediately before returning, so there is no per-node log spam.

✅ 🟢 Inconsistent message casing — FIXED (e564b9df)

⏭️ 🟢 End-to-end get_children_tree propagation test — SKIPPED

Seeding a store with a cycle requires bypassing the write-path guards at the SQL level, which is disproportionate to covering a single ?. The NodeServiceError → OpsError → Status mapping it would exercise is now directly covered by the three tests above. Worth revisiting if a repair/diagnostic tool ever needs to construct corrupt fixtures deliberately — at that point the fixture cost is already paid.

Verification

  • cargo test -p nodespace-core --lib — 1231 passed, 0 failed
  • cargo test -p nodespace-daemon --lib — 181 passed, 0 failed
  • bun run quality:fix — 0 ESLint errors, 0 svelte-check problems, clippy clean under -D warnings
  • cargo check --workspace --all-targets — clean, no warnings
  • Pre-push test gate passed on both commits

Note: three unrelated flaky failures were observed across runs (a SIGSEGV, a SqliteStore::new panic in a shared test helper, and a query_service sort test), each passing on rerun or in isolation. They stem from parallel SQLite temp-DB contention and touch nothing in this change.

Re-Review Decision

RE-REVIEW NEEDED — e564b9df changed guard comparison logic and replaced a test; 6168061a added an error variant and rerouted both guards through it. That is corrected logic plus new error plumbing across three crates, not cosmetic cleanup, so it warrants a fresh pass rather than self-assessment.

@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

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

Review Type: Re-Review (against prior review of 013f9570, addressed by e564b9df and 6168061a)


Previous Review Summary

4 findings, 2 Important + 2 Suggestion, plus one deferred item that got its own commit:

# Finding Claimed status Verified
1 (Important) Off-by-one in depth ceiling (>= vs >) Fixed, e564b9d Confirmed
2 (Important) invalid_argument wrong for stored-data corruption Fixed, 6168061 Confirmed
3 (Suggestion) Guards did not log Fixed, e564b9d Confirmed
4 (Suggestion) Casing nit Fixed, e564b9d Confirmed
5 (Suggestion) Missing e2e get_children_tree propagation test Skipped, justified Justification holds

No new issues found that block merge. Two small nits noted below.


Requirements Check (issue #2417)

Acceptance criterion Status
build_node_tree_recursive cannot recurse unboundedly on cyclic/malformed data Met, depth ceiling + path-visited set
Cycle/excessive depth produces a handled error, never abort Met, now NodeServiceError::CorruptHierarchy maps to Status::internal
Regression test with a back-edge asserts return-not-crash Met, returns_error_on_back_edge and returns_error_on_self_edge
Existing get_children_tree behaviour on well-formed data is unchanged Now fully met. Previously partially met due to the off-by-one; re-derivation below confirms the fix closes the gap exactly, with a real boundary test pinning it.

Verification performed

  1. Re-derived the SQL/builder alignment independently.

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.

  1. Verified build_chain_of_depth is not off-by-one itself, which is the exact failure mode that would make this whole fix look green while being wrong.

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.

  1. Re-ran the mutation test myself rather than trusting the claim: reverted the guard comparison in mod.rs back to depth >= MAX_TREE_DEPTH, reran the boundary test, and it failed exactly as claimed, rejecting node n100. Restored the > comparison afterward and confirmed the working tree is clean with no diff left behind.

  2. Reviewed the CorruptHierarchy variant and its routing.

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.

  1. Checked the logging.

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.

  1. Assessed the skipped end-to-end test. The justification is sound: constructing a genuinely cyclic on-disk fixture means bypassing the write-path guards at the SQL level, which is meaningfully more machinery than the single question-mark it would cover, and the error-to-status mapping the seam actually depends on is now directly tested at the mapping layer. This is a reasonable proportionality call.

  2. Checked for collateral changes. Message text did change for these two call sites. Grepped the frontend for the old message prefixes; the only hit is an unrelated logger test about circular JSON references, not this error path. No frontend caller depends on the old message text. Clippy is clean across both crates with warnings denied.


Code Review Findings

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


Recommendation

APPROVE.

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

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

Guard the live build_node_tree_recursive against cyclic hierarchy data so a bad edge is an error, not a daemon abort

1 participant