Skip to content

create_schema paths disagree on whether field names carry a namespace prefix - #1788

Merged
malibio merged 4 commits into
mainfrom
worktree-issue-1785-schema-field-namespace
Jul 28, 2026
Merged

malibio merged 4 commits into
mainfrom
worktree-issue-1785-schema-field-namespace

Conversation

@malibio

@malibio malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Closes #1785

malibio and others added 2 commits July 28, 2026 23:00
The description path namespaced inferred fields with `custom:` while the
explicit-fields path stored caller-supplied names verbatim, so the same user
intent produced different stored keys depending on the call shape. Stored names
are user-visible — titleTemplate tokens, CEL selectors, query filters, frontend
lookups — so the divergence surfaced later as templates that render empty and
filters that match nothing.

Per ADR-063, namespace prefixes scope to types NodeSpace owns:

- Fields of user-defined types are stored bare on both routes. create_schema
  only ever creates user-defined types (isCore is hardcoded false), so dropping
  the inference-time prefix cannot weaken core-property protection.
- Extending a core type now requires a prefix. update_schema's add_fields path
  rejects a bare name there, which is where a future core property could collide.
  The field-name validator cannot enforce this — it sees a name with no
  indication of the type it belongs to.

Also fixes two defects found while implementing:

- The reserved-core-property warning was never delivered. Warnings were
  snapshotted before normalization, which is the step that appends it, so every
  collision was silently dropped. Warnings are now collected after.
- Title-template tokens matched `\w+` in TypeScript but any run of characters in
  Rust, so `{custom:capacity}` and `{first-name}` resolved on the backend and
  passed through literally in the UI, leaving optimistic and persisted titles
  disagreeing. Both evaluators now share one pattern mirroring the Rust scanner.

The path-agreement test was verified to fail against the pre-fix behavior.

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the worktree-issue-1785-schema-field-namespace branch from e30d898 to 57152c8 Compare July 28, 2026 21:06
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Initial review — PR #1788, 2 commits (d875c8b9, 57152c8e) against origin/main. No prior reviews or comments on the PR.


Requirements Check (issue #1785)

# Criterion Status
1 Convention decided and recorded as an ADR in nodespace-docs ✅
2 Both create_schema paths produce the same stored field name ✅
3 validate_schema_field_name updated + doc comment reflects the rule ✅
4 Agent create_schema tool schema and guidance match the convention ✅
5 A test asserts the two paths agree ✅

1 — ADR ✅. nodespace-docs/decisions/063-namespace-prefixes-scope.md exists, Status Accepted, committed and pushed (721f412). It is a genuinely good ADR: it states the rejected alternative, explains that it was rejected for cost, not correctness, and its Consequences section names the real downside (the rule becomes conditional and "will be re-litigated"). It also flags out-of-scope name-inference divergence ("capacity number" → capacity_number) rather than quietly leaving it undocumented.

2 — Paths agree ✅, verified by execution. normalize_inferred_fields (📁 packages/core/src/schema/mod.rs:1247) no longer applies format!("custom:{}", …). The explicit path was already verbatim. test_create_schema_paths_agree_on_stored_field_names asserts on the persisted node via get_schema_node, not the return value — the right assertion target, since the stored key is what downstream call sites resolve against.

3 — Validator ✅. The chosen direction makes neither form invalid at the name level, so no code change to validate_schema_field_name was correct. The doc comment (📁 packages/core/src/behaviors/mod.rs:1249) was rewritten and now states the actual rule, including why it can't be enforced there ("sees a name with no indication of the type it belongs to"). This is the kind of comment that explains intent rather than mechanics.

4 — Agent side ✅, independently verified. grep -rn "custom:" packages/agent/src/ returns zero hits. def_create_schema (📁 packages/agent/src/local_agent/tools.rs:597) and agent_guidance.rs use bare names throughout (invoice_number, status, due_date). The claim that no lockstep change was needed holds.

5 — Test ✅ and it is a real guard. I re-ran the new tests against reverted implementations:

  • Reverting the is_core guard to if false → test_update_schema_core_type_requires_namespace_prefix FAILS (adding an unprefixed field to a core schema should be rejected: … "success": Bool(true)).
  • Reverting TEMPLATE_TOKEN_RE to /\{(\w+)\}/g → 3 of the TS tests FAIL (expected '{custom:status}' to be 'On Hold').

No trivially-passing tests found among the new additions.


Verification of the Two Bundled Fixes

Warning delivery (defect 4) — correct. The old code snapshotted f.warnings before normalize_and_namespace_fields appended the reserved-core-property warning, so that warning was constructed and immediately discarded. The refactor to return (Vec<SchemaField>, Vec<String>) makes the data flow honest — a function that produces warnings now returns them, rather than mutating a value the caller has already copied. Delivery to the JSON response is intact: warnings flows into CreateSchemaOutput at 📁 packages/core/src/schema/mod.rs:315, and skip_serializing_if = "Option::is_none" only elides the field when there are genuinely no warnings.

Title-template parity (defect 5) — correct, and parity is exact. I diffed the two implementations against three edge cases:

Template (props {"": "EMPTYVAL", "a": "A"}) Rust TS
[{}] [EMPTYVAL] [EMPTYVAL]
[{a] (unclosed) [{a] [{a]
{a{b}} (nested) } }

They agree on all three, including the pathological nested case. On the specific {} concern: both sides look up the empty-string key and both resolve it identically, so the widened pattern does not introduce a divergence — it removes one. Rust genuinely scans to the next } (📁 packages/core/src/utils/markdown.rs:143), so /\{([^}]*)\}/g is the faithful mirror, not an over-widening.

Shared-regex lastIndex — not a bug. TEMPLATE_TOKEN_RE carries /g, so it is stateful, but I confirmed only two call sites exist (📁 title-template.ts:40, :91) and both are String.prototype.replace, which resets lastIndex to 0 on entry and exit. A repo-wide grep found no .test() / .exec() / .matchAll() usage and no other brace-token regex anywhere in packages/desktop-app/src. Safe as written — see the suggestion below for making it stay that way.

create_schema cannot weaken core protection — verified. handle_create_schema hardcodes "isCore": false (📁 packages/core/src/schema/mod.rs:272) and rejects an existing schema_id before any write (📁 :257). It therefore cannot target a core schema, and dropping inference-time prefixing cannot reach one. The justification holds.


Code Review Findings

🟡 Important

📁 packages/core/src/schema/mod.rs:698-714 — rename_fields bypasses the core-type prefix guard entirely.

The guard is placed in the add_fields block, but handle_update_schema processes renames in Phase 1, before the guard's block is reached — and rename_schema_field (📁 packages/core/src/services/node_service/schema.rs:236) validates only that the source exists and the destination doesn't. It never consults schema.is_core.

I confirmed this empirically:

add_fields  [{name: "custom:effort"}]        on "task" → accepted (correct)
rename_fields [{from: "custom:effort", to: "effort"}] on "task" → ACCEPTED
stored names: ["status", "priority", "due_date", "started_at", "completed_at", "assignee", "effort"]

A bare effort now sits on the core task schema — exactly the state the guard exists to prevent, reached in two calls where one call is blocked. This is not theoretical: rename_fields is exposed to the agent in def_update_schema (📁 packages/agent/src/local_agent/tools.rs:673) and the description actively advertises it ("Use rename_fields to safely rename a field"), so the agent is the likely caller. It also migrates the underlying property data, so the bare key lands on every existing node instance.

Principle — an invariant enforced at one entry point is not an invariant. The rule "core schemas carry no unprefixed user fields" is a property of the schema's post-state, but it's currently checked against one input channel. The robust placement is a single post-state validation after Phase 1 and Phase 2 have both been applied — validate the final fields vector rather than each mutation kind separately. That also closes the same hole for any future mutation path added to update_schema, and it is barely more code than the current loop.

I'd note this is a pre-existing gap being newly exposed rather than something this PR broke — before this PR there was no guard at all. It's a net improvement either way. But since #1785's stated goal is "the divergence cannot silently return," leaving the cheapest bypass open undercuts the guarantee the PR is claiming.

🟢 Suggestions

📁 packages/core/src/schema/mod.rs:707 — contains(':') is a loose proxy for "has a valid namespace prefix."

I checked whether it can be fooled and mostly it can't: a:b:c and : are both rejected, because validate_schema_field_name runs later at persistence and enforces exactly-one-colon with non-empty parts on both sides. So the composition is correct today. The reason to still tighten it is that the guard's correctness currently depends on a validator in a different module that has no stated contract with it — if validate_schema_field_name is ever relaxed, this guard silently degrades to "contains a colon somewhere." Reusing the same well-formedness check here, or a shared has_namespace_prefix(name) helper, makes the two agree by construction rather than by coincidence. Low priority — a defensive tidy, not a live defect.

📁 packages/desktop-app/src/lib/utils/title-template.ts:26 — the /g regex is safe today only because both call sites happen to be replace.

The doc comment says "Kept in one place so both template evaluators stay in sync," which is the right instinct, but a shared /g RegExp is a mutable module-level singleton: the first .test() or .exec() a future contributor adds will start returning alternating results, and that failure mode is notoriously hard to attribute. Two options that cost nothing: drop the module constant and export a factory (const tokenRe = () => /\{([^}]*)\}/g), or add a line to the comment saying the constant is safe for .replace only and must not be used with .test/.exec. The former removes the hazard; the latter documents it.

📁 packages/core/src/schema/mod.rs — no test asserts the reserved-core-property warning survives to the JSON response.

The unit tests cover normalize_inferred_fields returning the warning, which is the part that was broken. But the defect being fixed was specifically "the warning never reached callers" — an end-to-end assertion (call handle_create_schema with description: "status", assert result["warnings"] is present and mentions status) would guard the actual reported symptom. As written, someone could reintroduce a snapshot-before-normalize at the handle_create_schema level and only the unit test's contract would notice, which it wouldn't. Cheap test, closes the loop on the stated bug.

📁 nodespace-docs/components/schema-management.md:66-77 — still states the superseded universal rule.

That file says "User-defined properties MUST use namespace prefixes" with custom:priority_score as the example, and ADR-063 links to it as "states the namespace convention this decision scopes." A reader arriving at schema-management.md from the CLAUDE.md link at the top of that section gets the pre-ADR rule with nothing indicating it's been narrowed. CLAUDE.md was updated correctly; its downstream reference wasn't. Separate repo, so out of scope for this PR's diff — worth a follow-up commit to nodespace-docs adding at minimum a pointer to ADR-063.

📁 nodespace-docs/decisions/063-namespace-prefixes-scope.md, Decision section — one internally inconsistent sentence.

"The validator accepts a prefix only where the target type is core, and rejects an unprefixed name there" describes behavior the implementation deliberately does not have — the Verification section three paragraphs later correctly states the opposite ("enforced where the target schema is known, not in the field-name validator"). Since the whole point of the ADR's own Consequences note is that this distinction "will be re-litigated," the one sentence that misstates it is worth deleting. Docs-repo follow-up, not a blocker here.

Nits

  • 📁 packages/core/src/schema/mod.rs:228 — the binding is still named namespaced_fields after the change that stopped namespacing anything. stored_fields or fields would match what it now holds. Naming that outlives its meaning is how the next reader infers the wrong invariant.

What This PR Does Well

Worth stating explicitly, since the findings above are all secondary:

  • The decision is recorded before the code. The ADR reasons from the rule's rationale rather than its wording, and correctly identifies that the collision hazard only exists on types NodeSpace ships. That's the substantive insight; the code change is the easy part.
  • Comments explain why, not what. The rewritten doc comments on validate_schema_field_name and normalize_inferred_fields both answer "why is it this way" — including why the enforcement lives elsewhere. That is exactly the comment that prevents the next contributor from "fixing" the validator.
  • The bundled fixes are justified, not scope creep. Both defect 4 (warnings dropped) and defect 5 (token-pattern divergence) are the same class of bug as create_schema paths disagree on whether field names carry a namespace prefix #1785 — two implementations of one convention drifting apart — and defect 5 is directly caused by namespaced field names in templates. Bundling them is cohesive under a single purpose rather than a grab-bag.
  • Tests assert on persisted state. get_schema_node rather than the return value is the correct assertion target for a stored-key convention, and it's what makes the test a real regression guard.

Recommendation

COMMENT — approve-with-followup in spirit. This is a clear net improvement: it closes a real correctness divergence, records the reasoning durably, and fixes two adjacent defects with tests I verified are genuine guards rather than tautologies. Nothing here is a security issue or an architectural regression, and I would not hold the merge over the suggestions.

The one item I'd want a decision on before merge is the rename_fields bypass. It's a two-line-equivalent fix (move the check to validate the post-state fields vector after Phase 2, instead of iterating add_fields), it's agent-reachable via a tool whose description recommends the path, and it directly undercuts criterion 5's "cannot silently return." Either fixing it here or filing it as a tracked follow-up is fine — but it shouldn't be dropped, because the guard reads as complete and isn't.

Everything else is a follow-up: the schema-management.md staleness and the ADR's one contradictory sentence both live in nodespace-docs and can't be fixed from this diff.

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

Initial pragmatic code review posted as a PR comment. Summary: net improvement, recommendation COMMENT. Verified all 5 acceptance criteria and confirmed the new tests are real guards (they fail against reverted implementations). One item worth a decision before merge: the core-type prefix guard in update_schema's add_fields path is bypassable via rename_fields, which runs in Phase 1 before the guard and never checks is_core — reproduced empirically.

The guard added in the previous commit only inspected add_fields, so a bare
name could still reach a core schema in two calls: add custom:effort, then
rename it to effort. rename_fields is exposed to the agent and its tool
description actively recommends it, and because renames migrate property data
the bare key would land on every existing node instance.

Moving the check to a post-state validation would not work: rename_schema_field
rewrites the schema and migrates node data per rename as it goes, so validating
afterwards returns an error with the offending rename already committed. The
check therefore runs before any rename executes, covering both routes that can
introduce a name — add_fields directly, and rename_fields turning an already
prefixed field bare.

Also from review:

- Replace contains(':') with has_namespace_prefix, which requires exactly one
  ':' with non-empty segments either side. The old check was correct only
  because validate_schema_field_name rejects the malformed forms first; a guard
  that depends on validation order in another module is one refactor away from
  admitting the names it exists to exclude.
- Assert the reserved-core-property warning reaches the response JSON. The
  defect fixed earlier was that it never reached callers, which a unit test on
  the normalization function alone would not have caught.
- Rename the stale namespaced_fields binding to stored_fields.

Both new guards were verified to fail against the unguarded behavior.

Co-Authored-By: Claude <[email protected]>
The token pattern was a module-level `/g` RegExp shared by both evaluators.
That is safe only while every call site uses String.replace, which resets
lastIndex — the first .test() or .exec() a later change adds would start
returning alternating results, a failure mode that is hard to trace back to a
regex declared in another function. A factory removes the hazard rather than
documenting it, at no cost: both call sites now get a fresh instance.

Completes the review recommendations from the initial review of this PR.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review recommendations addressed

All findings from the initial review are addressed. Nothing skipped.

🟡 Important — rename_fields bypassed the core-type guard

Commit 26e01fd9. Confirmed the reported bypass, and investigating it changed the fix.

The suggested "validate the post-state after Phase 2" approach does not work here: rename_schema_field migrates node property data and rewrites the schema per rename as it goes, so a check running afterwards would return an error with the offending rename already committed across every node instance — reporting failure having already done the damage.

The guard therefore runs before any rename executes (Phase 0), covering both routes that can introduce a name: add_fields directly, and rename_fields turning an already-prefixed field bare. Renaming between two namespaced names stays allowed.

Verified as a real guard: disabling the rename check makes test_update_schema_core_type_rename_cannot_drop_namespace_prefix fail with {"fieldsRenamed": 1, "success": true} — the exact bypass from the review.

🟢 Suggestions

Finding Resolution
contains(':') a loose proxy Replaced with has_namespace_prefix — exactly one :, non-empty segments either side. Unit-tested against :capacity, custom:, a:b:c, :, "". No longer depends on validation order in another module.
/g regex singleton lastIndex hazard Commit 874a8635. Took the factory option (templateTokenRe()) rather than the comment option — removes the hazard instead of documenting it, at no cost.
No test that the warning reaches the JSON response Added test_create_schema_reserved_property_warning_reaches_response, asserting on result["warnings"] from handle_create_schema. This guards the actual reported symptom.
schema-management.md states superseded rule Fixed in nodespace-docs e828106 — scoped table (core → prefix, user-defined → bare) plus ADR-063 link.
ADR-063 internally inconsistent sentence Fixed in nodespace-docs e828106 — removed; replaced with what the implementation actually does.
Nit: namespaced_fields binding Renamed to stored_fields.

Follow-up filed

#1789 — the description route folds the type keyword into the inferred name ("capacity number" → capacity_number). Separate from namespacing, noted in ADR-063, and why test_create_schema_paths_agree_on_stored_field_names uses "capacity".

Tests

Frontend 4106 / 170 files · browser 20 · Rust 1026 + 309 + 3. Zero failures. Rust core is up from 1022 — four new tests. Full pre-push gate passed.

@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Re-review — PR #1788, delta 57152c8e..874a8635 (2 new commits, 3 files, +231/−27). Earlier commits reviewed in comment 5109717515 and re-examined here only to judge whether prior feedback was properly addressed.

Previous Review Summary

Previous recommendations 7 (1 🟡 Important, 5 🟢 Suggestions, 1 Nit)
Addressed 7
Not addressed 0
New issues found 1 (🟢 cosmetic — duplicate Phase 0 label)

Every item was verified by execution or by reading the landed source, not taken on the summary's word.


Verification of Prior Recommendations

🟡 Important — rename_fields bypassed the core-type guard → Addressed, and the deviation was correct

The implementer did not follow my suggested "validate the post-state after Phases 1 and 2." I asked for that reasoning to be scrutinized rather than accepted. It holds, and their approach is strictly better than what I proposed.

The stated reason checks out at the source. 📁 packages/core/src/services/node_service/schema.rs:236 — rename_schema_field performs two independent writes with no transaction spanning them:

// Step 1: Migrate all node property data
let affected = self.store.rename_schema_field(type_id, from, to).await…?;
// Step 2: Update schema definition — rename field in the fields list
self.update_node_unchecked(type_id, update).await…?;

handle_update_schema then calls this once per rename in a loop (📁 mod.rs:809), with no rollback across iterations. A post-state check would therefore have returned an error after the offending key was already written across every node instance — reporting failure having already done the damage. My original suggestion was wrong on this point.

I confirmed the batch case empirically, which is where the difference actually bites. Given rename_fields: [{custom:a → custom:a2}, {custom:b → bare_b}] on core task:

result:       Err("Field 'bare_b' renamed on core schema 'task' must carry a namespace prefix…")
stored names: ["status", …, "custom:a", "custom:b"]   ← unchanged

Rename #1 was legal and still did not execute. Phase 0 rejects the whole batch before any write, so there is no partial application. Under my suggested design, rename #1 would have committed and only then would the error surface — leaving the schema in a state neither the caller nor the guard intended. Validating inputs before a non-atomic sequence is the correct pattern when the sequence cannot be rolled back; validating the post-state is only sound when the mutation is transactional, and this one isn't.

Phase 0 coverage is complete. I probed every route I could construct for a bare name to reach a core schema:

Route Result
add_fields: [{name: "effort"}] ✅ Rejected
rename_fields: [{to: "effort"}] ✅ Rejected
remove_fields: ["status"] + add_fields: [{name: "status"}] (same call) ✅ Rejected — add_fields is checked regardless of removals
Multi-rename batch, one bad entry ✅ Rejected atomically, zero partial application
add_relationships ⚪ N/A — relationships are a separate namespace, not validated by validate_schema_field_name, and explicitly outside ADR-063's scope

create_schema remains unreachable: it hardcodes "isCore": false (📁 mod.rs:301) so it cannot target a core schema.

🟢 contains(':') was a loose proxy → Addressed

Replaced with has_namespace_prefix (📁 packages/core/src/schema/mod.rs:101). I checked it against validate_schema_field_name (📁 behaviors/mod.rs:1266) and the two use structurally identical split(':') triple-match logic, so they agree by construction rather than by coincidence — which was the entire point of the finding. has_namespace_prefix is deliberately the weaker check (it does not test the alphanumeric charset), which is the right relationship: it may pass a name that the validator later rejects, but it can never pass one the validator would consider unprefixed. No name is accepted that should be rejected. The doc comment states exactly why it doesn't lean on the other module.

test_has_namespace_prefix covers :capacity, custom:, a:b:c, :, and "".

🟢 /g regex lastIndex hazard → Addressed

📁 packages/desktop-app/src/lib/utils/title-template.ts:32 — took the factory option (const templateTokenRe = () => /\{([^}]*)\}/g), which removes the hazard rather than documenting it. Verified:

  • grep -rn "TEMPLATE_TOKEN_RE" packages/ → zero hits, no stale references.
  • Both call sites (:46, :97) use the factory.
  • 26/26 title-template tests pass. Behavior unchanged — each replace now gets a fresh instance.

🟢 No test that the warning reaches the JSON response → Addressed, and it is a real guard

test_create_schema_reserved_property_warning_reaches_response asserts on result["warnings"] from handle_create_schema. I independently confirmed it fails when the delivery is broken by forcing the handler to elide warnings:

panicked: warnings should be present in the response when a field collides

It guards the reported symptom, not just the extracted function.

🟢 schema-management.md stated the superseded universal rule → Addressed

nodespace-docs e828106. Now carries the scoped table (core → prefix required, user-defined → bare name) plus the ADR-063 link, and explicitly documents the rename route: "update_schema rejects an unprefixed name on a core type, both when adding a field and when renaming one to a bare name." Matches the implementation.

🟢 ADR-063 Decision section contradicted its own Verification section → Addressed

nodespace-docs e828106. The sentence "The validator accepts a prefix only where the target type is core…" is gone (grep confirms). The Decision section now states what the implementation actually does, and agrees with the Verification section at line 68.

Nit: namespaced_fields binding → Addressed

Renamed to stored_fields at both use sites (📁 mod.rs:259, :303, :343).


New Test Verification

Both remaining new tests independently confirmed as real guards, not tautologies:

test_update_schema_core_type_rename_cannot_drop_namespace_prefix — disabling the rename check reproduces exactly the bypass from the initial review:

panicked: renaming a core-schema field to a bare name should be rejected:
  Object {"fieldsRenamed": Number(1), "schemaId": String("task"), "success": Bool(true)}

It also asserts the negative — that custom:effort survives the rejected rename and effort never appears — so it guards against a rejection that still mutates.

test_update_schema_user_defined_type_allows_bare_names — forcing schema_is_core to always return true makes it fail:

panicked: bare names on a user-defined type should be accepted:
  InvalidParams("Field 'address' added to core schema 'venue' must carry a namespace prefix…")

This is the test I most wanted to see, because it pins the over-rejection direction. Without it, a future tightening of schema_is_core would break every user-defined type silently.

cargo test -p nodespace-core --lib schema:: → 61 passed, 0 failed on restored source.

Over-rejection analysis

I checked whether the guard can fire on something legitimate:

  • Can a user-defined type have is_core == true? No. is_core: true is written only by NodeSpace's shipped models/core_schemas.rs; every user-reachable creation path hardcodes false (📁 mod.rs:301). A user-defined type cannot trip the guard.
  • Can schema_is_core return false for a genuinely core schema? Only via the missing-schema → false mapping, which is unreachable: the pre-existing Phase 0 already returns "Schema '{id}' not found" before this call. The fallback is defensive, and the doc comment says so.

Code Review Findings

🟢 Suggestions

📁 packages/core/src/schema/mod.rs:613 and :682 — two consecutive blocks both labelled "Phase 0".

The pre-existing block (// --- Phase 0: Verify schema exists, validate renames, run playbook impact check ---) and the new one (// --- Phase 0: Reject unprefixed field names on a type NodeSpace owns ---) are separate blocks under the same number, separated by ~70 lines. The numbering exists to convey ordering, and two things sharing a number defeats that — the next reader has to determine whether these are one phase interrupted or two independent ones, and the answer isn't visible locally.

The placement is correct (both must precede Phase 1); only the label is ambiguous. Cheapest fix is to fold the heading into the existing one — // --- Phase 0: Validate everything that must be checked before any mutation --- — or number the new block Phase 0b. Cosmetic; not worth another round-trip on its own.

📁 packages/core/src/schema/mod.rs:682 — schema_is_core re-fetches a schema the function already fetched.

The pre-existing Phase 0 at :613 calls get_schema_node(&params.schema_id) and discards the result (it only needs the existence check); schema_is_core then fetches the same row again. That is one redundant read on every update_schema call.

Not a correctness concern — update_schema is a low-frequency agent-driven operation, both reads happen before any mutation so there is no TOCTOU window that matters, and the value is re-fetched again at Phase 2 anyway. It is genuinely also a readability win as written: schema_is_core(node_service, &id) states the question at the call site far better than threading a SchemaNode binding down from :613 would. Binding the existing fetch and reading .is_core off it would save the read but couple the two blocks. I'd leave this as-is — flagging only so the trade-off is recorded rather than looking like an oversight.


What the Delta Does Well

  • The deviation was reasoned from the code, not from convenience. The implementer investigated my suggestion, found it would corrupt data, and said so explicitly with the mechanism named. Pushing back on a reviewer with evidence is the correct outcome here — and the batch-rename probe shows their design is strictly stronger than mine, not merely equivalent.
  • The fix is placed where the invariant actually holds. My original framing ("an invariant enforced at one entry point is not an invariant") was right about the problem and wrong about the remedy. Phase 0 enforces it across all input channels in one block, which achieves the same robustness property — a future mutation kind added to update_schema needs its check added here, and the co-located block makes that obvious.
  • Comments carry the reasoning forward. The Phase 0 comment explains why it isn't a post-state check — precisely the question the next reader (or reviewer) will ask, pre-answered. Same for has_namespace_prefix's note on not depending on validation order, and the templateTokenRe factory's note on lastIndex.
  • Tests assert the negative direction too. test_update_schema_user_defined_type_allows_bare_names and the "original field survives a rejected rename" assertions guard against over-rejection and partial application, not just the happy path.

Recommendation

APPROVE

All 7 prior recommendations are addressed, verified by execution rather than by claim. The one deviation from my guidance was correct, well-reasoned, and produces a stronger guarantee than what I suggested — Phase 0 rejects a mixed rename batch atomically where post-state validation would have committed the legal renames first.

The 🟡 Important finding that held the previous review at COMMENT is closed: the rename_fields bypass is shut, remove_fields + re-add is covered, no partial application is possible, and the three new tests all fail when their guards are disabled. The two remaining findings are cosmetic and I would not hold a merge for either.

Working tree left clean; all probe edits reverted and verified with git status --porcelain.

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

Re-review posted above: all 7 prior recommendations addressed and verified by execution. The deviation from my suggested post-state validation was correct — Phase 0 rejects mixed rename batches atomically where post-state validation would have committed the legal renames first. APPROVE.

@malibio
malibio merged commit 42e395b into main Jul 28, 2026
2 checks passed
@malibio
malibio deleted the worktree-issue-1785-schema-field-namespace branch July 28, 2026 22:02
malibio added a commit that referenced this pull request Jul 29, 2026
Resolves an import-block conflict in local_agent_service.rs: main added
ChatModelSpec (#1791) while this branch added PriorWrite and the
agent_loop imports for the duplicate-write guard. Both are needed, so
the resolution is the union of the two import lists.

No logic conflict. The SelfLimitingWrite doc's claims about
handle_update_schema were re-verified against the merged schema/mod.rs
(#1788 touched that file): adds still error on an existing name, removes
are still retain() calls that converge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
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.

create_schema paths disagree on whether field names carry a namespace prefix

1 participant