Skip to content

Refuse deleting an extended or core schema (closes #2889) - #3095

Merged
malibio merged 4 commits into
mainfrom
issue-2889-schema-delete-guard
Sep 26, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2889-schema-delete-guard

Conversation

@malibio

@malibio malibio commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes the remaining gaps in schema deletion. The extends case in #2889 was already guarded: the store's assert_schema_deletable counts a live child's extends row against the parent, so deleting an extended schema directly is refused with schema_has_declarations on every delete path. Two real holes remained, and this PR fixes both in that same store guard:

The agent skill rule and the generated references/cli.md now mention the core-type refusal. There is also one unrelated rustfmt hunk in node_service/mod.rs that quality:fix insists on.

Tests

  • test_delete_core_schema_refused
  • test_delete_refused_when_subtree_contains_an_extended_schema
  • test_delete_refused_when_subtree_contains_a_core_schema
  • test_delete_allowed_when_subtree_holds_an_unreferenced_schema
  • The core-schema reseed test now removes its fixture with the unchecked store delete.
  • core + daemon + agent + cli nextest: all pass. The direct-target extends cases stay covered by schema_relationship_declarations_test.rs.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3095

Review Type: Initial Review

Summary

This is a small, focused change that improves code health. delete_node now refuses a schema target that is core (isCore: true) or that another schema extends, and returns a typed SchemaDeleteRefused error naming the direct children. The guard sits in the one production delete path that every client uses (Tauri → gRPC DeleteNode → node_ops::delete_node → NodeService::delete_node; the CLI schema delete uses the same path). It runs before the transaction, like the ADR-041 access gate. The three new tests pass locally with cargo nextest. The schema DDL confirms why this matters: relationship.in_node/out_node are ON DELETE CASCADE, so deleting a parent schema silently dropped the children's extends edges.

I verified the bypass paths:

  • NodeService::bulk_delete, delete_with_version_check and delete_node_unchecked have no non-test callers.
  • store.delete_nodes_by_ids_unchecked (re-import prune) only removes the old children of replaced docs, never schemas.
  • replace_seed_guidance deletes seed-guidance children, not schemas.
  • The playbook lifecycle never deletes schemas.

No legitimate flow needs to delete a core or extended schema.

Requirements Check

  • ✅ (a) Refuse delete_node on a schema that other schemas extend, with a typed error naming the direct child schemas. The error is SchemaDeleteRefused { schema_id, reason }, and reason lists the children sorted, e.g. "extended by bug — delete those schemas first".
  • ✅ (b) Refuse deleting core schemas (isCore: true) in the same change. This is checked first, and test_delete_core_schema_refused covers it.

Code Review Findings

🟡 Improvements

  1. 📁 packages/core/src/services/node_service/crud.rs:1912-1914: The guard only checks the delete target, not the has_child subtree. validate_move only stops date nodes from moving and only checks that the new parent is a container. So a schema node can be moved under a text or task node with move_node. Deleting that ancestor then removes the schema inside delete_subtree_atomic without going through ensure_schema_deletable, including a core schema like task. subtree_ids is already computed a few lines below, and the delete uses exactly that set.

    • Recommendation: Run the guard over every schema-typed node in subtree_ids, not just the root. One query is enough: SELECT id, properties FROM node WHERE node_type='schema' AND id IN (...), plus the extends lookup. Alternatively, and arguably more correct, stop schema nodes from ever having a parent (reject in validate_move/create). Then "target only" holds by construction and can be stated in the doc comment.
    • Principle: Enforce an invariant at every path that can break it. An invariant that holds only for the common path turns into a silent-corruption bug later.
  2. 📁 packages/cli/src/commands/schema.rs:30-36: The user-facing doc for schema delete is now incomplete, and it was already partly wrong. It says the daemon refuses while relationship declarations remain. I found no such guard: the relationship table cascades on delete. It says nothing about the two refusals this PR adds.

    • Recommendation: Rewrite the help text to describe the real rules: core schemas cannot be deleted, and extending schemas must be deleted first. Drop the declaration claim, or file an issue if that guard was meant to exist.
    • Principle: Help text is the API contract that users and agents read. A stale contract costs a round-trip through an error.

🟢 Nits / Minor

  1. 📁 crud.rs ensure_schema_deletable: get_extends_parent_map() loads every extends edge to find one parent's children. Edge counts are tiny today, but a targeted store method would state the intent directly and use idx_rel_out: SELECT in_node FROM relationship WHERE relationship_type = 'extends' AND out_node = ?. The current approach is fine for now (YAGNI). The change is optional.

  2. 📁 packages/core/src/ops/mod.rs:153-155: SchemaDeleteRefused → OpsError::ValidationFailed → gRPC INVALID_ARGUMENT. In gRPC terms this refusal is FAILED_PRECONDITION: the request is well-formed, but the system is not in a state that allows it. PlayRuleRejected already uses that code, so there is precedent. It also matches CollectionCycle, which uses ValidationFailed, so the current choice is consistent. Optional, but the typed variant would let a client tell "fix your input" apart from "change state first".

  3. 📁 crud.rs:1912: TOCTOU. A child schema created with extends on this parent between the pre-transaction check and delete_subtree_atomic loses its edge through the cascade. The access gate has the same trade-off, and it needs a concurrent schema-create race on a local single-user store, so accepting it is reasonable. A one-line note in the doc comment would make the trade-off deliberate rather than accidental.

  4. 📁 packages/core/src/schema/schema_test.rs: The tests cover refusal, the allowed-after-children-removed path and the core schema. Two small gaps:

    • A grandchild chain (A ← B ← C: deleting A is refused naming only b, and deleting B is refused naming c). This pins the "direct children only" contract that the doc comment states.
    • If you take finding 1, a test that deletes a text-node ancestor of a moved schema.
  5. 📁 crud.rs ordering: the schema guard runs before OCC, so a stale version on a protected schema returns SchemaDeleteRefused rather than VersionConflict. This matches the access gate ("gate precedes OCC") and is fine. Mentioning it only for awareness.

Project rules: There is no backward-compat code, no issue numbers in code comments (ADR references only) and no lint suppressions. The error variant has a constructor that follows the existing pattern.

Recommendation: APPROVE

This is a net positive and meets both maintainer decisions. Finding 1 (subtree bypass) is worth fixing in this PR or a quick follow-up, because it is the one remaining route to the exact corruption this PR prevents. Finding 2 is a two-line doc fix. Neither blocks 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: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review (740085b)

core + daemon + agent + cli nextest: 3506 passed. Re-review needed: the guard's scope changed from the target to the whole subtree.

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3095 (re-review of 740085b)

Review Type: Re-Review

Previous Review Summary: 7 recommendations. 4 were addressed (#1, #2, #5, #6). 3 were skipped with a stated reason, and all 3 skips are justified (#3, #4, #7). This pass adds 1 new 🔴 issue, 2 new 🟡 issues and 3 new 🟢 issues. The 🔴 comes from an error in my previous review.

Correction to the previous review

Finding #2 said "I found no such guard: the relationship table cascades on delete." That was wrong. The store already has SqliteStore::assert_schema_deletable (packages/core/src/db/sqlite_store/relationships.rs:2459). It runs inside delete_subtree_atomic (nodes.rs:1357), delete_node and bulk_delete. It refuses any schema that has relationship declarations pointing at it or from it, and returns schema_has_declarations: … N relationship declaration(s). That count includes an extends row where the schema is the parent side (count_schema_declaration_edges, relationships.rs:2496). Two existing tests cover it:

  • deleting_a_schema_with_declarations_is_blocked_on_both_ends
  • deleting_an_extending_schema_succeeds_but_deleting_its_parent_is_still_blocked (packages/core/tests/schema_relationship_declarations_test.rs)

A third test asserts that the CLI surfaces this error: packages/cli/tests/cli_integration.rs:1058. So the old CLI help text was accurate, and the edit made in response to my finding introduced a regression. My apologies for the bad steer.

Verification of the new commit

  • Candidate selection is correct. The core ids from get_core_schemas() match every non-test is_core: true definition. The only other isCore: true literals are in #[cfg(test)] modules. Extends parents come from the map values, which is right because the map is keyed child → parent. The node_type == "schema" filter guards against a non-schema node that happens to share an id with a core schema.
  • The doomed-set exemption is correct for the case it targets. A parent is exempt only when every one of its extends children is in the subtree being deleted. test_delete_allowed_when_subtree_holds_the_whole_chain pins this.
  • get_nodes_by_ids is safe on large lists. It chunks at 900 ids per query (nodes.rs:641), and the candidate list is bounded by the number of core schemas plus the number of extends parents, so it is small anyway.
  • Tests: I ran all 10 delete-guard tests, the new ones plus the pre-existing store-guard tests, with cargo nextest. All pass. The new tests are well targeted: the leaf-first chain test checks that only direct children are named, and the core and extended subtree tests and the whole-chain test cover the doomed-set logic.

Code Review Findings

🔴 Must fix

  1. 📁 packages/cli/src/commands/schema.rs:32-34: The help text now states the opposite of what the daemon does. It says "Relationship declarations on or pointing at the type are removed with it." In fact the store refuses the delete with schema_has_declarations while any declaration remains. The agent skill prose tells agents to clear declarations first (packages/agent/src/skill_rules.rs:126), and the CLI integration test asserts the refusal.
    • Recommendation: Keep the original declaration sentence and add the new refusals. For example: "The daemon refuses to delete a core schema or a schema other schemas extends (delete or re-target the extending schemas first). It also refuses while relationship declarations remain on or pointing at the type: remove them first with schema update and remove_relationships, including declarations on other types that target this one."
    • Principle: Help text is the contract that agents act on. A wrong contract sends the agent straight into a refusal it was told would not happen.

🟡 Improvements

  1. 📁 crud.rs ensure_schemas_deletable vs relationships.rs:2459 assert_schema_deletable: There are now two schema-delete guards on two layers, and their scope differs.

    • The service guard covers core schemas and extends parents across the whole subtree.
    • The store guard covers all declarations, including extends parents, for the target only. Its comment at nodes.rs:1354 ("Only the target can be a schema node… descendants are … ordinary content") is false, as this PR's own move_node_unchecked tests show.

    Consequences:

    • (a) The subtree hole that finding Set up Tauri + Svelte project structure #1 closed for extends is still open for ordinary declarations. Move a schema that declares widgets under a text node, delete the text node, and the declaration rows cascade away silently. This is the same class of corruption this PR fixes.
    • (b) For a directly targeted extended parent, the typed SchemaDeleteRefused now preempts schema_has_declarations. skill_rules.rs:126 still says such a schema "stays blocked with the same schema_has_declarations rejection", so that sentence is stale. It also still recommends re-targeting the children, which remains valid.
    • (c) A small inconsistency with the new doc comment: if the parent schema is the delete target and its child sits in its has_child subtree, the service guard exempts the child, but the store guard still refuses with schema_has_declarations. This errs conservative, so it causes no corruption, but it contradicts "a parent whose children are all in the same subtree is deletable".

    Recommendation: Make one guard own the invariant. The cleanest fix is to move the core and subtree checks into the store's assert_schema_deletable, run it over every schema node in subtree_ids, and apply the same doomed-set exemption to declarations whose other endpoint is also doomed. The alternative is to extend ensure_schemas_deletable to count declarations across the subtree and fix the stale store comment. At minimum, fix the nodes.rs:1354 comment and the skill_rules.rs sentence in this PR, and file a follow-up for (a).

    • Principle: DRY / single source of truth for an invariant. Two partial guards at different layers drift, and this one has already drifted.
  2. 📁 crud.rs doc comments: the delete_node "Schema guard" paragraph and NodeServiceError::SchemaDeleteRefused (error.rs:50-53) present this PR's guard as if it were the first protection against the extends hazard. Once Create design system foundation #2 is decided, a single sentence pointing at the other guard, or its removal, would prevent the next reader from making the mistake I made.

🟢 Nits / Minor

  1. Nit: 📁 crud.rs candidate filter: parent_map.values().any(|p| p == *id) costs O(subtree × edges) for every delete. Collect the values into a HashSet<&str> once. Edge counts are tiny today, so this matters only for large subtrees.
  2. Nit: 📁 crud.rs ensure_schemas_deletable: every delete, including ordinary text deletes, now runs one full extends edge scan, and get_core_schemas() builds about 19 full SchemaNodes (field vectors, Utc::now()) just to read their ids. The cost is negligible next to the delete I/O. A const/LazyLock id list would state the intent and avoid the allocations.
  3. Nit: 📁 crud.rs:1903-1908: target_exists reads the whole row only to call .is_some(), but store.node_exists (nodes.rs ~l.628) already exists for exactly this check.

Recommendation: REQUEST CHANGES

The subtree logic in this commit is correct and well tested, and the PR as a whole is still a net positive. However, #1 is a documentation regression that I caused, and it tells agents the opposite of what the daemon does, so it should not merge as is. The fix is two lines. #2 does not block merge on its own: at minimum fix the stale nodes.rs:1354 comment and the skill_rules.rs error-name sentence here, and track the unification (and the declaration subtree hole) as a follow-up.

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

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed re-review (b532ca0)

  • ✅ 🔴 CLI help regression: reverted to the original text, which was accurate.
  • ✅ 🟡 Two guards: removed the service-level ensure_schemas_deletable and the SchemaDeleteRefused variant. The existing store guard now owns the rule: core refusal added, and it runs over the whole subtree. The stale "only the target can be a schema" comment is replaced.
  • ✅ 🟡 Stale docs: the skill rule still names schema_has_declarations for extended parents, which is correct again, and it now adds schema_is_core.
  • ✅ 🟢 Nits (HashSet, core id list, node_exists): moot, since that code is gone.
  • ⏭️ Doomed-set exemption dropped: a parent and child in the same subtree are now refused (the safe direction). Delete the child first.

Re-review needed: the design changed.

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3095 (re-review 2, of b532ca0)

Review Type: Re-Review

Previous Review Summary: Re-review 1 raised 1 🔴, 2 🟡 and 3 🟢. All are resolved:

  • 🔴 The CLI help regression is reverted to the original, accurate text (schema.rs:30-35), and it is no longer in the net diff.
  • 🟡 Two guards: the service-level guard and SchemaDeleteRefused are removed. The existing store guard assert_schema_deletable now owns the rule.
  • 🟡 Stale docs: the nodes.rs "only the target can be a schema" comment is replaced. skill_rules.rs names schema_has_declarations for extended parents, which is correct again, and adds schema_is_core.
  • 🟢 The three nits are moot because that code is gone.

The one deliberate trade-off is that the doomed-set exemption is dropped. A parent and child in the same subtree are now refused, which errs in the safe direction. I accept it. Deleting the child first is a clear, actionable path.

Verification

  • Net diff: 6 files, +161/−16. This is a much smaller and better-placed change than the first two iterations. It extends one existing guard instead of adding a parallel one (DRY, single owner for the invariant).

  • Guard ordering in delete_subtree_atomic: target lookup, then the subtree schema guard, then the OCC pre-check, then the write lock, then the in-transaction OCC re-check.

    • This is the same position the target-only guard already had, so the change adds no new race.
    • A stale version on a protected schema reports the schema refusal rather than VersionConflict. Both are refusals, so this is acceptable.
    • The pre-lock TOCTOU (a concurrent extends child created between the check and the commit) is unchanged from before this PR. On a local single-writer store it is acceptable.
  • delete_node / bulk_delete in the store both call assert_schema_deletable per target, so they get the core refusal automatically. NodeService::delete_node_unchecked and delete_with_version_check route through store delete_node, so they are covered too.

  • Production paths that could now break. None reach a core schema through a guarded path:

    • replace_seed_guidance deletes the children of a seed root. These are guidance content, not schemas.
    • The markdown child replace (markdown/mod.rs:2227) and delete_collection (daemon node_service.rs:2229) go through delete_node on user content. delete_collection follows has_child, not membership.
    • The import prune uses delete_nodes_by_ids_unchecked, which is unguarded by design.
    • Seeding and reseed create or update schemas and never delete them.
    • Methodology install has no delete calls.

    If a user moved a core schema under a doc, these paths now fail loudly instead of silently destroying it. That is the intended behavior.

  • schema_nodes_among: SQL-filtered by node_type = 'schema' AND id IN (...), chunked at 900 ids, and reads through the read connection. An ordinary content delete therefore costs one indexed PK lookup that returns zero rows, which is negligible.

  • Tests:

    • I ran all of nodespace-core, nodespace-daemon, nodespace-cli and nodespace-agent with nextest: 3503 passed, 0 failed.
    • The four new tests cover the direct core-schema refusal, a nested extended schema, a nested core schema, and the allowed case of a nested unreferenced schema. They assert that nothing was deleted on refusal (both the holder and the schema survive). The direct-target extends/declaration cases stay in the existing schema_relationship_declarations_test.rs, which avoids duplication.
  • Skill docs: bun run skill:check reports "Skill content is up to date." cli.md matches the skill_rules.rs prose.

  • rustfmt hunk (node_service/mod.rs:5885): this is a genuine fmt fix. The unformatted line came from Enforce the container-type check in move_node_unchecked (closes #3011) #3085 on main and is still unformatted on current origin/main. cargo fmt --all --check is clean on the branch, and the branch merges cleanly with current main. It is harmless, and the alternative is a dirty quality:fix.

Code Review Findings

🟡 Improvements (non-blocking, follow-up)

  1. 📁 packages/core/src/db/sqlite_store/nodes.rs:1503-1506 (delete_children_subtree_unchecked) and its _in_tx twin: the same false premise this PR just removed from delete_subtree_atomic is still stated here. The comment says descendants are "never schema nodes themselves". validate_move (hierarchy.rs:309) only restricts date nodes, though, so a user can move a schema, including a core one, under another schema's description subtree. The next replace_description_subtree on the outer schema, triggered by an update_schema description change, then cascades the nested schema and its declarations away with no guard. The reach is narrow because it needs a deliberate schema-under-schema move, but it is the same corruption class this issue addresses.
    • Recommendation: The root-cause fix is to refuse moving a schema node under any parent in validate_move, and to refuse parent_id on schema create. Every "a schema only sits at the root" assumption, including the one in the new delete_subtree_atomic comment, then holds by construction, and the subtree scan becomes belt-and-braces. File a follow-up issue rather than expanding this PR.
    • Principle: Enforce an invariant at its source instead of guarding each consumer. Consumer-side guards drift, and this is the third one found.

🟢 Nits

  1. Nit: 📁 packages/core/src/services/node_service/mod.rs:3906-3910: the reseed fixture now calls delete_nodes_by_ids_unchecked with a schema id, which the method's own doc comment says not to do (nodes.rs:1558-1560). It is correct for a test that simulates a missing core schema, and the new inline comment explains why. A short "(test-only simulation; the doc-comment prohibition is about production callers)" would stop the next reader from treating it as a precedent.
  2. Nit: 📁 packages/core/src/db/sqlite_store/nodes.rs:1382-1384: the new comment says "A schema normally sits at the root". It is accurate today. If finding 1 lands, reword it to "always sits at the root; the subtree scan is defensive".
  3. Nit: 📁 relationships.rs:2464-2468: isCore is read from the properties JSON, so the refusal is only as strong as the protection on that property against a generic update_node. This is pre-existing surface and out of scope here. I am noting it because this PR now makes isCore load-bearing for deletion.

Recommendation: APPROVE

The design is now right: one guard, at the store layer, which every delete path already passes through, extended to cover core schemas and the whole subtree. The previous 🔴 and 🟡 findings are resolved, the tests are targeted and green across all affected crates, and the skill docs are in sync. Finding 1 is a follow-up that fixes the root cause, not a blocker.

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

@malibio

malibio commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed re-review 2 (2df0b4c)

No re-review needed: the only change is a comment.

malibio and others added 4 commits September 26, 2026 22:40
delete_node now refuses a schema target with SchemaDeleteRefused when it
is a core schema, or when another schema extends it — every extends-chain
resolver skips a missing ancestor, so deleting a parent silently stripped
its descendants of all inherited fields and relationships (ADR-078).
Delete the extending schemas first.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- Run the schema guard over every node in the has_child subtree, not
  just the target: a schema moved under a text node was deleted along
  with it, bypassing the guard. A parent whose children are all in the
  same subtree stays deletable. Candidates are limited to core ids and
  extends parents, so an ordinary delete reads no extra nodes.
- Document the pre-transaction TOCTOU window, same as the access gate.
- Fix the stale `schema delete` CLI help (it described a relationship-
  declaration refusal that doesn't exist).
- Tests: grandchild chain unwinds leaf-first; subtree holding an
  extended or core schema is refused; subtree holding the whole chain
  is allowed.

Skipped: targeted out_node query (the subtree check needs the whole
parent map anyway); FAILED_PRECONDITION status (would need a new OpsError
variant; INVALID_ARGUMENT matches CollectionCycle today).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The store's assert_schema_deletable already refused deleting a schema
another schema extends (the extends parent row counts as a declaration),
on every delete path — so the service-level guard duplicated it. Removed
it, and instead:

- assert_schema_deletable refuses core schemas (`schema_is_core`).
- delete_subtree_atomic runs the guard on every schema in the subtree,
  not just the target: move_node can put a schema under ordinary content,
  and deleting that container cascaded the schema away unchecked.
- CLI `schema delete` help restored (it was accurate); agent skill rule
  and the generated cli.md mention the core-type refusal.
- The core-schema reseed test now removes its fixture schema with the
  unchecked store delete.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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.

1 participant