Skip to content

Enforce that schema nodes are always roots and isCore is fixed (closes #3102) - #3126

Merged
malibio merged 4 commits into
mainfrom
issue-3102-schema-root-invariant
Sep 27, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-3102-schema-root-invariant

Conversation

@malibio

@malibio malibio commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Closes #3102

Summary

  • schema_not_root tree invariant (new TreeInvariantRule::SchemaNotRoot, wire name schema_not_root). Schemas are refused a parent at the same sites that refuse collections: create-with-parent, create_child_node_atomic, move and bulk reparent (assert_may_gain_parent), generic has_child relationship create, and merge. The schema_is_root_edge and schema_is_root_type triggers enforce it on every write path. This mirrors ADR-059's collection-is-root enforcement.
  • isCore is fixed at creation. All five generic update paths reject a change to whether a node is a core schema. They return InvalidUpdate with the message schema_is_core: …. The schema_core_status_fixed trigger also enforces this in the database, and it covers retyping a core schema away from schema, which would otherwise get around the delete refusal.
  • Comments in nodes.rs corrected. delete_children_subtree_unchecked and its _in_tx twin now say that descendants are never schemas, which is guaranteed by construction. The subtree scan in delete_subtree_atomic is now described as defensive.
  • TS TreeInvariantRule union and the dev-tools mapping doc now include the new rule.

Tests

  • schema_is_always_a_root: the create, move, relationship create, raw edge insert, and type-switch paths are all refused.
  • schema_core_status_cannot_change_through_generic_updates: update_node, bulk_update, raw isCore clear, and raw retype are all refused.
  • The three subtree-delete tests from Refuse deleting an extended or core schema (closes #2889) #3095 now build their nested schema by dropping the edge trigger. That stands in for a database where the invariant was broken, so the defensive scan keeps its coverage.
  • Full nodespace-core suite passes (2271 tests), and the push check passes.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3126

Review Type: Initial Review

Summary

This is a net improvement and ready to land. It gives schemas the same "always a root" enforcement that collections got in ADR-059:

  • Typed Rust refusals at the create, move, relationship and merge sites.
  • DB triggers behind them as a backstop.
  • The comments that were false before are now true by construction.

The isCore freeze is covered on all five service update paths plus bulk update, and a trigger covers raw writes. I traced the other write paths. Core schema seeding goes through store.create_node (an insert with no parent). update_schema, rename_schema_field and the friendly-name rename all rebuild properties with "isCore": schema.is_core. Neither path trips the new triggers. There is no sync-apply path or node ON CONFLICT upsert in core for the triggers to get in the way of. No migration or back-compat code; the DDL-only change to schema.rs is legitimate.

One real gap remains, and this PR makes it worse: a user schema can still be created with isCore: true through the generic create path. With this PR it can then never be cleared or deleted. There are also a few small consistency and test-coverage items. None blocks the merge.

Requirements Check

  • ✅ Moving a schema node under any parent is rejected. assert_may_gain_parent now counts schema as an offender (move + bulk reparent). Merge refuses in conflicts.rs. The schema_is_root_edge trigger backs this up.
  • ✅ Creating a schema node with a parent_id is rejected. Covered in create_node_with_parent (crud.rs), create_child_node_atomic (nodes.rs), the has_child path of create_relationship, and the trigger. schema_is_root_type also refuses retyping a child into a schema.
  • ✅ isCore cannot be changed through generic node updates. ensure_schema_core_status_unchanged runs in update_node_unchecked, update_node_unchecked_in_tx, update_node_in_tx, update_with_version_check_returning_node_in_tx and bulk_update. The schema_core_status_fixed trigger covers raw writes, including retyping a core schema away from schema. (Creation is not covered; see finding 1.)
  • ✅ Stale comments in nodes.rs are corrected. delete_subtree_atomic now calls its scan defensive. The delete_children_subtree_unchecked comment and its _in_tx twin are now true.

Code Review Findings

🟡 1. A user schema can be created with isCore: true, and now it can never be undone

📁 packages/core/src/services/node_service/crud.rs (the create_node_with_parent / create_node schema branch, around lines 280-330 and 540-600)

Context: SchemaNodeBehavior::validate accepts any isCore value. So a generic create_node / create_node_with_parent call with node_type: "schema" and properties: {"isCore": true} succeeds. The new test schema_core_status_cannot_change_through_generic_updates shows this path is open, since it builds Widget through create_node_with_parent with a caller-chosen isCore. Before this PR, a schema created that way could be fixed by updating it to isCore: false. Now both the service check and the trigger refuse that update. The result is a user type that can never be deleted, recoverable only by resetting the DB. The invariant as documented ("whether a schema is core is fixed when it is created") only holds if creation can't lie.

Recommendation: In the service create paths, refuse node_type == "schema" with isCore == true. Use the same InvalidUpdate("schema_is_core: …") shape. Core seeding writes through SqliteStore::create_node directly, so the refusal won't affect it. Add one assertion to the existing test. If you'd rather keep this PR tight, file a follow-up issue instead.

Principle: An invariant is only as strong as its weakest entry point. Freezing a value without validating it at creation makes a recoverable mistake permanent.

🟢 2. The trigger and the Rust check disagree on non-boolean isCore

📁 packages/core/src/db/schema.rs:364-368 vs packages/core/src/services/node_service/crud.rs:36-39 and relationships.rs:2476 (assert_schema_deletable)

Context: Rust decides "is core" with as_bool() == Some(true). The trigger uses coalesce(json_extract(..., '$.isCore'), 0) = 1. SQLite returns integer 1 for both JSON true and JSON 1: json_extract('{"a":1}','$.a') is 1, and json_type gives integer vs true. A schema stored with isCore: 1 is therefore not core to Rust (the service allows the update and the delete) but core to the trigger. An update that drops the key then fails with the raw trigger error. This is an edge case, but the two layers are meant to state one rule.

Recommendation: In the trigger, use json_type(old.properties, '$.isCore') = 'true' (and the same for new). That matches as_bool() == Some(true) exactly and makes the coalesce unnecessary.

Principle: A single source of truth. A backstop that is stricter than the rule it backs up produces errors the typed layer can't explain.

🟢 3. The transactional has_child relationship path has no typed root refusal

📁 packages/core/src/services/node_service/relationship.rs around lines 1040-1062 (the _in_tx twin, reached by a Play's add_relationship)

Context: The non-tx create_relationship now refuses has_child onto a schema, and onto a collection, with a typed TreeInvariantViolation. The tx twin checks only single-parent. The trigger still blocks the write, but the Play surfaces an untyped query error rather than schema_not_root. This gap already existed for collection_not_root, so this PR matches the pattern rather than regressing it.

Recommendation: Optional. Hoist the collection and schema target checks into the tx twin, or into a shared helper, so both twins refuse the same way. A follow-up is fine.

Principle: DRY across twin code paths. The comment on the tx twin says "enforce where every surface converges", and today it does that only for single-parent.

🟢 4. Test coverage misses two of the new Rust refusal sites

📁 packages/core/src/db/sqlite_store/conflicts.rs:385-389, packages/core/src/db/sqlite_store/nodes.rs:372-379

Context: schema_is_always_a_root covers service create, move, relationship create, a raw edge insert and a raw retype. It does not cover the merge refusal (a schema survivor that would inherit the loser's parent) or create_child_node_atomic with node_type = "schema". The trigger catches both in any case, so this is only about keeping the typed errors from regressing silently.

Recommendation: Add two short assertions to the existing test.

Principle: Every branch that produces a user-facing error contract should have a test pinning it.

🟢 5. Nit: create_child_node_atomic reports the raw content as the node id

📁 packages/core/src/db/sqlite_store/nodes.rs:376-378

Context: schema_not_root(content) puts e.g. "My Widget" into node_id. The service path uses normalize_schema_id(&params.content), which gives "my-widget". Clients reading node_id from the gRPC trailer get two shapes for the same refusal.

Recommendation: Pass normalize_schema_id(content) (the function is already referenced in the comment right above).

🟢 6. Nit: a doc comment in nodes.rs went stale in this PR

📁 packages/core/src/db/sqlite_store/nodes.rs:2705-2711 (assert_may_gain_parent doc)

Context: "One chunked query finds both kinds of offender" is now three kinds (collection, schema, member). The rewrapped line "every write path; checking here gives the reparent paths a readable error. One chunked query finds both kinds of" also runs far past the surrounding width.

Recommendation: Say "every kind of offender" and rewrap.

🟢 7. Nit: a rejected schema or collection create under a date id still auto-creates the date container

📁 packages/core/src/services/node_service/crud.rs:476-493

Context: Step 2 (ensure_date_exists) runs before the Step 3 collection and schema refusals. That goes against the Step 1 comment's goal that a rejected call should leave no auto-created date container behind. The collection check already had this problem; the new schema check copies the ordering.

Recommendation: Move the two node_type refusals above Step 2. They only read params.

✅ Checked and fine

  • Test approach in schema_test.rs: dropping schema_is_root_edge on the per-test tempdir DB and inserting the edge raw is a reasonable way to simulate a broken invariant. It keeps the defensive delete_subtree_atomic scan covered without adding a production escape hatch. The doc comment explains why.
  • Trigger cost: schema_core_status_fixed runs on every properties update, but the WHEN clause short-circuits on old.node_type = 'schema' for non-schema rows. schema_is_root_edge adds one primary-key lookup per has_child insert. Both are negligible.
  • Frontend and dev-tools: the TreeInvariantRule union, the runtime list and the gRPC mapping doc are updated consistently, with a test.
  • CLAUDE.md compliance: no data migration, no back-compat code, and CREATE TRIGGER IF NOT EXISTS matches the existing collection triggers.

Recommendation

APPROVE, with finding 1 strongly suggested, either in this PR or as an immediate follow-up. Findings 2-7 are optional polish.

@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 27, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed (cc5f3b9)

✅ Fixed: 7/7

⏭️ Skipped: none.

🧪 nodespace-core: 2271 passed. Push check passed.

Re-review needed: yes. #1 adds a new create-time refusal and #3 changes the transactional relationship path.

@malibio

malibio commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — Re-Review (PR #3126, commit cc5f3b9)

Review Type: Re-Review
Previous Review Summary: 7 previous recommendations (1 🟡, 6 🟢). 7 addressed, 0 not addressed. 0 new blocking issues; 2 new 🟢 nits.

Requirements Check (issue #3102):

  • ✅ Moving a schema under a parent is rejected (service move, assert_may_gain_parent, schema_is_root_* triggers; plus a new merge-survivor test)
  • ✅ Creating a schema with parent_id is rejected (the service create refuses before the date container is auto-created; create_child_node_atomic now returns a typed SchemaNotRoot with the normalized id)
  • ✅ isCore cannot be changed through generic updates. Service guard and trigger now use the same test, and creating a schema as core is refused too
  • ✅ Stale nodes.rs comments corrected (assert_may_gain_parent doc now reads "every kind of offender")

Verification of previous findings

  1. 🟡 User schema creatable with isCore: true: fixed. ensure_not_creating_core_schema runs in insert_node_in_tx_no_invariant_dispatch (crud.rs) and in all three bulk create paths (bulk.rs:147, 378, 563). I checked each legitimate producer:

    • Core seeding (seed_core_schemas_if_needed, mod.rs ~1904) writes via store.create_node directly, so the service guard never sees it. seed_core_schemas_reconciles_missing_schema_on_next_service_new passes.
    • create_schema (schema/mod.rs) always builds isCore: false.
    • update_schema, rename_schema_field and the friendly-name path carry schema.is_core through an update, which the unchanged-status guard allows.
    • Playbook actions, cron_runner, workflow_state, graph_resolver, validation and benches only create with isCore: false.
    • The only other isCore: true literals are in model/behavior unit tests that never persist (schema_node.rs, behaviors/mod.rs, skill_ops/context_ops test helpers, nodespace-types convert).
    • Import creates markdown content nodes, not schemas.

    No legitimate path breaks.

  2. 🟢 Trigger vs as_bool mismatch: fixed. I checked the new expression in sqlite3 and got these results:

    • {} → 0 (json_type returns NULL, NULL='true' gives NULL, coalesce gives 0)
    • {"isCore":true} → 1
    • {"isCore":1} → 0
    • {"isCore":false} → 0
    • For a non-schema row, (0 AND NULL) evaluates to 0, so the IS NOT comparison stays well-defined.

    This now matches is_core_schema in Rust exactly.

  3. 🟢 _in_tx has_child typed refusal: fixed via the shared refuse_parent_for_root_only_type (relationship.rs:24). Both twins call it.

  4. 🟢 Tests: added. They cover the merge-with-schema-survivor refusal, the create_child_node_atomic refusal (asserts rule plus normalized id my_widget), the date-parent refusal leaving no date row (checked via store().get_node, not the virtual-synthesizing service getter, which is the right thing to check), and the create-as-core refusal. I ran all 4 targeted tests locally and they pass.

  5. 🟢 Raw content reported as id: fixed with normalize_schema_id(content) (nodes.rs:377).

  6. 🟢 Stale doc: fixed.

  7. 🟢 Date container created before refusal: fixed. The root-only refusal is hoisted above ensure_date_exists (crud.rs:496-511).

Code Review Findings

🟢 Tx has_child target lookup doesn't synthesize virtual dates
📁 packages/core/src/services/node_service/relationship.rs:1055-1059
The new tx-path lookup uses SqliteStore::get_node_in_tx. The non-tx twin uses self.get_node, which synthesizes a virtual date node. So for a has_child edge whose child is an unpersisted date id, the tx path now returns node_not_found where the non-tx path would pass the type check. That outcome is still correct: relationship.in_node/out_node both REFERENCES node(id), so the edge insert would fail on the FK anyway, and the new error is clearer than an FK abort. If you want exact parity with the non-tx twin and with the source lookups in the same function, use the existing get_node_in_tx_or_virtual_date helper (relationship.rs:677). Optional. Principle: consistency between twin code paths.

🟢 Nit: create refusal uses the invalid_update variant
📁 packages/core/src/services/node_service/crud.rs:266-274
ensure_not_creating_core_schema refuses a create but builds NodeServiceError::invalid_update. The schema_is_core: message prefix makes it readable, and callers only check for a refusal, so this is cosmetic. Use a create/validation variant if one fits. Principle: accurate error taxonomy aids debugging.

Positive notes

  • Extracting is_core_schema and refuse_parent_for_root_only_type removes the duplicated predicates (DRY). The Rust guard, the trigger and the delete refusal now share one definition of "core".
  • Hoisting the refusal above side effects follows the fail-before-mutating principle, and the test asserts the absence against the store, not the synthesizing getter.

Recommendation: APPROVE. All 7 prior findings are resolved correctly and no legitimate create path regresses. Both remaining items 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 (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review feedback addressed (5fb35cd)

✅ Fixed (1/2)

  • 🟢 The transactional has_child target lookup now uses get_node_in_tx_or_virtual_date. It now handles virtual dates the same way as the non-tx path and the source lookups in the same function.

⏭️ Skipped (1/2)

  • 🟢 Switching the core-schema create refusal from InvalidUpdate to ValidationFailed(InvalidProperties) would wrap the message as Node validation failed: Properties validation failed: schema_is_core: …. That buries the leading schema_is_core: code that callers key on and that the delete refusal also leads with. I'd revisit this if a create-specific error variant is added.

🧪 nodespace-core: 2271 passed. Push check passed.

Re-review needed: no. This is a one-line parity change with no new behavior.

@malibio
malibio force-pushed the issue-3102-schema-root-invariant branch from 5fb35cd to fd3b07a Compare September 27, 2026 10:45
malibio and others added 4 commits September 27, 2026 13:30
…#3102)

- New tree invariant `schema_not_root`: create-with-parent, move, bulk
  reparent, generic has_child relationship create and merge refuse to give a
  schema a parent. `schema_is_root_edge` / `schema_is_root_type` triggers back
  it up on every write path, mirroring the collection-is-root enforcement.
- Whether a schema is core is fixed at creation: the generic update paths
  (single, tx, versioned, bulk) refuse an `isCore` change or retyping a core
  schema, backed by the `schema_core_status_fixed` trigger.
- Corrected the nodes.rs comments: descendants are never schemas by
  construction; the subtree scan in delete_subtree_atomic is defensive.
- Subtree-delete tests now build their nested schema by dropping the trigger,
  simulating a broken invariant for the defensive scan.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… refusal

- Service create paths (single, tx, bulk, bulk hierarchy) refuse a schema
  with isCore: true; core schemas are only seeded straight into the store.
  Now that core status is fixed, such a schema could never be undone.
- schema_core_status_fixed uses json_type = 'true', matching the Rust
  as_bool() check and the delete refusal exactly.
- The transactional has_child path (Play add_relationship) returns the typed
  collection/schema root refusal via a helper shared with the non-tx path.
- Root-only refusals run before the date container auto-create, so a
  rejected create under a date leaves nothing behind.
- create_child_node_atomic reports the normalized schema id.
- Tests: create_child_node_atomic, merge with a schema survivor, create under
  a date, creating a core schema; assert_may_gain_parent doc reworded.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ookup

Matches the non-tx twin and the source lookups in the same function.
Skipped: switching the create-time core-schema refusal to ValidationFailed —
it would bury the leading `schema_is_core:` code callers key on.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DVzwQZA6rU2wweT5gFN3iv
The rule joins the TreeInvariantRule union, so the exhaustive switch in
describeMergeRefusal (added on main) needs a case for it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DVzwQZA6rU2wweT5gFN3iv
@malibio
malibio force-pushed the issue-3102-schema-root-invariant branch from fd3b07a to 08bb342 Compare September 27, 2026 11:36
@malibio
malibio merged commit ce11dde into main Sep 27, 2026
@malibio
malibio deleted the issue-3102-schema-root-invariant branch September 27, 2026 11:36
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.

Enforce that schema nodes are always roots (no parent via move/create)

1 participant