Skip to content

Make create_schema's result reflect the persisted row, and pin the CLI's target database - #2832

Merged
malibio merged 4 commits into
mainfrom
issue-2815-create-schema-false-success
Sep 22, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2815-create-schema-false-success

Conversation

@malibio

@malibio malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Closes #2815.

What was reported

A create_schema call returned is_error=false with result_field_count=2 and a fully-populated payload, and the schema was never persisted. The agent, correctly trusting its own tool result, told the user the type had been created.

What the investigation found

The write path is sound. A probe reproducing the reported two-call sequence (Company Sold To, then Event Venue) against a fresh database persisted both. with_transaction propagates commit errors, INSERT INTO node is a plain insert (node.id is PRIMARY KEY, so a duplicate errors rather than silently skipping), and there is no schema cache. The OCC bypassed warnings live on update_nodes_batch; no create_schema path reaches them — a red herring, as the issue suspected.

So AC#1's answer: not deterministic for that input, and the "write did not land" premise does not hold at the core layer.

What was actually broken is that nothing would have caught it if it had.

The three defects

1. The result was an echo of the request. CreateSchemaOutput was built from stored_fields/schema_id — both derived from the caller's arguments — and the id the transaction actually produced was discarded as _created_schema_id. A payload built that way is identical whether or not the write landed, so it cannot report the difference. It now reads the committed schema node back and is built from that. A schema that cannot be verified is an error that names it and says plainly that nothing was created.

2. The agent's no-op-success guard was structurally blind to this. agent_loop.rs counts result["fields"].len() on the premise that a result reports persisted state — but for create_schema that array was the model's own input echoed home, so every non-empty call reported a non-zero count regardless of what persisted. Only fields: [] could trip it, and core treats that as a valid relationship-only schema. The read-back makes the premise true; the comment now records that the guard depends on it.

3. The exists-check swallowed read failures. if let Ok(Some(..)) routed both Err and Ok(None) into the write, which then hit the primary-key constraint and surfaced as an opaque internal error naming neither the real problem nor the repair. An unreadable schema table is not evidence of an absent schema, so the error is propagated now.

Why there is a test seam

On every path reachable through the public API, an echoed payload and a read-back payload are byte-identical — I verified this for fields, derived friendly names, relationships and extends. And the store is sealed by design, so no test can make a committed row vanish. Without a seam the read-back is untestable and silently rots.

NodeService::set_write_verification_fault reaches that branch. It is inert unless armed, never called by the daemon, and defaults to ordinary behavior — following the existing set_subtree_access_gate / set_playbook_lifecycle injector pattern.

Verification

a_write_that_cannot_be_verified_is_an_error_not_a_populated_success was confirmed to fail with the fix reverted, reproducing the reported shape exactly:

create_schema reported SUCCESS for a schema it could not verify.
Payload was: {"fields":[{...booking_date...},{...capacity...}],
              "schemaId":"event_venue","version":1}
  • 5 new regression tests, all green with the fix
  • bun run rust:test:core — exit 0, 35 test binaries
  • bun run rust:test:libsql-linked — exit 0
  • bun run quality:fix — exit 0 (clippy -D warnings)
  • Full pre-push gate passed

Noted, not fixed here

The agent turn runs against its per-database NodeService, while a CLI nodespace search with no x-ns-database-id header resolves to registry.default_database. If the chat ran in a non-default database, the write landed correctly and the CLI read a different one — which fits the reported evidence. #2187/#2267 already routed the turn-state RPCs; what remains is CLI-side default resolution, which wants its own issue rather than widening this one.

🤖 Generated with Claude Code

…loses #2815)

`create_schema` returned `is_error=false` with a fully-populated field list
for a schema that was never persisted, and the agent — correctly trusting its
own tool result — told the user the type had been created.

Investigation: the write path is sound. A probe reproducing the reported
two-call sequence against a fresh database persisted both schemas. The
transaction machinery propagates commit errors, `INSERT INTO node` is a plain
insert (a duplicate id errors rather than silently skipping), and there is no
schema cache. The `OCC bypassed` warnings are on `update_nodes_batch` and no
create_schema path reaches them. So the failure is not deterministic for that
input, and the "write did not land" premise does not hold at the core layer.

What was actually broken is that nothing would have caught it if it had:

1. The result was an echo of the request. `CreateSchemaOutput` was built from
   `stored_fields`/`schema_id`, both derived from the caller's arguments, and
   the id the transaction actually produced was discarded as
   `_created_schema_id`. Such a payload is identical whether or not the write
   landed, so it cannot report the difference. It now reads the committed
   schema node back and is built from that; a schema that cannot be verified
   is an error naming the schema and stating plainly that nothing was created.

2. The agent's no-op-success guard was structurally blind to this. It counts
   `result["fields"].len()`, which for create_schema *was* the model's own
   input echoed home, so every non-empty call reported a non-zero count
   regardless of what persisted. Its doc comment asserted the opposite premise;
   the read-back now makes that premise true, and the comment says so.

3. The exists-check swallowed read failures. `if let Ok(Some(..))` routed both
   `Err` and `Ok(None)` into the write, which then hit the primary-key
   constraint and surfaced as an opaque internal error naming neither the real
   problem nor the repair. An unreadable schema table is not evidence of an
   absent schema, so the error is now propagated.

Testing the read-back needs a seam. On every path reachable through the public
API an echoed payload and a read-back payload are byte-identical — verified
for fields, derived friendly names, relationships and `extends` — and the
store is sealed by design, so no test can make a committed row vanish.
`NodeService::set_write_verification_fault` (inert unless armed, never called
by the daemon) reaches that branch. The regression test was confirmed to fail
with the fix reverted, reproducing the reported shape exactly: `is_error=false`,
two fields, `schemaId: event_venue`, and no such schema.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2832

Review Type: Initial Review (zero prior reviews, zero prior comments)
Scope: cc38ee53 only — c231a253 and 639e61cb are already on main.
Diff: 427 insertions / 15 deletions across 5 files.


Summary

This is a net positive change and I recommend merging after one small correctness fix.

The framing is the strongest thing about it. The reporter's premise ("the write did not land") turned out not to hold at the core layer, and rather than paper over that, the PR says so explicitly, keeps the investigation evidence in the commit message, and then fixes the thing that was genuinely broken: the result payload could not distinguish a write that landed from one that did not. That is the correct reduction. A tool result that is a function of its own input carries zero information about the world, and every downstream consumer — including agent_loop.rs's no-op guard, which counts result["fields"].len() — was reasoning from a premise the code did not actually uphold. Closing that by construction (build the output from the committed row) is a better fix than adding another guard on top of an unsound signal.

Defect 3 (if let Ok(Some(..)) swallowing Err into "does not exist") is a small, clean, independently-correct fix, and the reasoning in the comment — "An unreadable schema table is not evidence of an absent schema" — is exactly right.

I verified the 5 new tests build and pass (cargo test -p nodespace-core --test create_schema_result_reflects_persisted_state_test — 5 passed, 0 failed).


Requirements Check — acceptance criteria from #2815

AC Status Notes
Determine whether the failure is deterministic or intermittent, and record which ✅ Answered not deterministic, with the probe evidence recorded in both the commit message and the PR body. The PR also correctly disposes of the OCC bypassed red herring (those warnings are on update_nodes_batch; no create_schema path reaches them).
Root-cause why the write did not persist while the tool reported success ⚠️ Partial, and honestly labelled The write-side root cause was not reproduced; the PR states the premise does not hold at the core layer and offers the most likely explanation (database-id routing: the agent turn ran against its per-database NodeService while the CLI nodespace search with no x-ns-database-id header resolved to registry.default_database). That hypothesis is left unproven and deferred to a future issue. See 🟡-4 — this deferral is reasonable, but it should be a filed issue rather than a PR-body paragraph.
create_schema reports an error, or a result that does not claim fields, when the schema was not persisted ✅ packages/core/src/schema/mod.rs:1322-1340 — absent row → MarkdownError::internal_error, not a populated success.
The result payload reflects persisted state rather than requested state ✅ (one gap) fields, relationships, schema_id, is_core, version now come from persisted. description still comes from the request — see 🟡-3.
A regression test pins the failing case: revert the fix and confirm the test fails ✅ Author reports verifying the revert; the test's own logic holds up under inspection (analysis below).
Tests pass (bun run test:all) ✅ Full pre-push gate reported passing; I independently re-ran the new test binary.
Code passes bun run quality:fix ✅ Reported exit 0 with clippy -D warnings.

Findings

🔴 Critical

None. Nothing here is a security issue, a data-integrity regression, or an architectural regression.


🟡 Improvements

🟡-1 📁 packages/core/src/schema/mod.rs:1334-1339 — the "It was NOT created" error can be a false statement

This is the one finding I'd want addressed before merge, because it is the same class of bug the PR exists to fix: a message that asserts more than the code actually knows.

get_schema_node_verifying delegates to get_schema_node, which delegates to the store. And packages/core/src/db/sqlite_store/nodes.rs:3436-3443 does this:

match crate::models::SchemaNode::from_node(node) {
    Ok(mut schema) => { ... Ok(Some(schema)) }
    Err(e) => {
        tracing::warn!("Failed to parse schema node '{}': {}", id, e);
        Ok(None)          // <-- a PARSE failure becomes "absent"
    }
}

So Ok(None) at the verification site has two possible meanings: the row genuinely is not there, or the row is there and SchemaNode::from_node could not parse it. The new error hard-codes the first:

"Schema '{}' reported a successful write but is not present in the \
 database afterwards. It was NOT created."

In the parse-failure case that sentence is wrong in the direction that matters. The schema node was committed and is sitting in the node table. An agent told "It was NOT created" will retry create_schema, which will now hit the exists-check… except the exists-check also routes through get_schema_node, also gets Ok(None), also concludes "does not exist", and sends the retry into the write — where it hits the primary-key constraint and surfaces as the opaque internal error that defect 3 was specifically introduced to eliminate. The user is left with an undeletable, unrecreatable, invisible schema and three contradictory error messages.

The probability is low (it needs a malformed properties JSON on a row this same call just wrote). But the cost of being wrong is high and the fix is cheap. Two options:

  • Preferred: at the verification site, distinguish the two. A raw self.store.get_node(id) (or a SELECT 1 FROM node WHERE id = ?) in the None arm tells you which case you're in, and lets the message be true either way — "was created but its definition could not be parsed back; it may be corrupt" vs "was NOT created".
  • Cheaper: soften the claim to what the code actually knows — "could not be read back after a reported-successful write. Do not report it as created." — dropping the categorical "It was NOT created."

Principle: an error message is an assertion about the world, and an assertion the code cannot actually support is the same defect as a success payload the code cannot support. Also KISS in reverse: Ok(None) is an overloaded return that conflates "absent" with "unparseable", and the new call site is the first one where that conflation becomes user-visible and actively harmful.


🟡-2 📁 packages/core/src/services/node_service/mod.rs:2404-2420 — the pub test seam, and the asymmetry you flagged

You asked directly, so: the seam is acceptable, the asymmetry is not quite right, and there is one cleaner option.

On the seam itself — your reasoning holds. A self-verifying write path is observationally identical to an echoing one on every path where the write succeeds, and the store genuinely is sealed. Without a seam, the read-back is untestable, and an untestable guard is one refactor away from being deleted as dead weight by someone who can't see what it's for. The doc comment makes this argument well and I would not want it removed.

But the precedent cited is not quite the precedent claimed. set_subtree_access_gate and set_playbook_lifecycle are production injectors — packages/daemon/src/services/assembly.rs:279 and :316 call both on the real startup path. They are pub because production needs them. set_write_verification_fault is called from exactly one place in the entire workspace, a test file. It is the first purely-test-only pub mutator on NodeService, which makes it a new category rather than an instance of an existing one — and a new category on the public API of the core data layer deserves to be flagged rather than absorbed.

On the specific asymmetry you asked about (get_schema_node_verifying is pub(crate), set_write_verification_fault is pub): it's defensible but inverted in spirit. Each visibility is individually minimal for its call site — the reader is crate-internal, the arming is cross-crate. But the effect is that the safe half (a read) is locked down and the dangerous half (a mutator that makes a healthy database report a row as missing) is exposed to every consumer of nodespace-core, including the daemon. Nothing enforces the "test-only" claim except the doc comment.

The cleaner option you asked about: a test-support Cargo feature. The crate already uses feature gating (nlp), so the machinery is familiar:

[features]
test-support = []

[dev-dependencies]
nodespace-core = { path = ".", features = ["test-support"] }   # self-reference for integration tests

then #[cfg(feature = "test-support")] on both the pub fn and the struct field. The self-dependency trick is exactly the standard workaround for "#[cfg(test)] isn't visible to tests/", which is the constraint that drove you here — so this is the idiomatic answer to that specific problem. It makes the test-only claim compiler-enforced rather than comment-enforced, and it means a production build genuinely cannot call it.

Cost: one feature, one self-referencing dev-dependency, two attributes. That is real ceremony for one seam, which is why this is 🟡 and not 🔴 — the current form is a defensible pragmatic call and I would not block on it. But if a second test-only seam ever appears, the feature should be introduced then rather than accumulating a third and fourth pub injector that production never calls.

Principle: Interface Segregation / least privilege — a capability that only tests need should not be reachable from production code, and the strongest form of "should not" is "cannot compile".

Nit within this finding: if the seam stays pub, consider #[non_exhaustive] on WriteVerificationFault so a second fault mode later isn't a breaking change to the re-export at packages/core/src/services/mod.rs:187.


🟡-3 📁 packages/core/src/schema/mod.rs:1345 — description is still built from the request

The new CreateSchemaOutput reads five of its six substantive fields from persisted, and then:

description: description_text,      // still the request-derived value

This is not a correctness bug in the current code — description_text is the exact string handed to create_description_subtree_in_tx, so on the success path it does describe what was written. But it is a consistency gap in an invariant the PR just went to some trouble to establish. The whole argument of this change is "the result reports persisted state"; leaving one field on the old footing means the invariant is now "mostly true", and "mostly true" invariants are how the original bug got in. The next person to read this reasonably concludes the rule is universal and is wrong about one field.

I'd accept either resolution:

  • Read it back too (the description lives in a child subtree, so this means reading the subtree — probably not worth the cost), or
  • Leave it and say why, in one line, right at the field: "the description is not on the schema node — it is a child subtree — so it is reported from the value written rather than read back."

The second is fine and costs nothing. The point is that a reader should not have to work out which of the two situations they're in.

Principle: DRY applied to invariants — an invariant stated in a comment and violated one line below it is a duplicated fact that has already diverged.


🟡-4 📁 PR body, "Noted, not fixed here" — the database-routing hypothesis should be a filed issue

The PR closes #2815 while leaving its most load-bearing question — why did the user observe a missing schema? — answered only by a hypothesis in a PR description. The hypothesis is a good one and specific enough to act on (CLI-side default database resolution when no x-ns-database-id header is present). But PR bodies are not a backlog. Once this merges and #2815 closes, that paragraph is discoverable only by someone who already knows to go looking for it.

This does not block the merge — the change stands on its own merits regardless of what the CLI does. But file the follow-up issue before closing #2815, and reference it from the closing comment. Detection without root cause is a legitimate and often correct place to stop; silently dropping the root cause is not.

Principle: a defect is closed when it is understood or explicitly deferred, and "explicitly" means somewhere the backlog can see.


🟢 Nits

  • Nit: 📁 packages/core/src/db/sqlite_store/relationships.rs:1797-1809 — parse_declaration_row drops a malformed declaration row with a tracing::warn! and continues. This is now in the result-construction path: a schema created with three relationships, one of which fails to round-trip, returns success reporting two. Pre-existing, out of scope, and genuinely unlikely (the JSON was serialized by this same process moments earlier) — noting it only because the PR's own thesis is that silent drops on a reporting path are how false successes are born. Not worth acting on here.

  • Nit: 📁 packages/core/src/schema/mod.rs:1256-1260 — the comment on created_schema_id explains well why the transaction's id is preferred over the predicted one. Worth adding the consequence, since it's the actually-interesting part: if those two ever diverge, the verification read looks up the real one and the mismatch surfaces as a failed verification rather than as a silently wrong schemaId in the payload. That's a nice property and it's currently implicit.

  • Nit: 📁 packages/agent/src/local_agent/agent_loop.rs:2560-2576 — the expanded comment is accurate and the cross-package premise is worth recording. It is also now ~16 lines of prose above a one-line count. Fine as-is; flagging only that this file's comment-to-code ratio is climbing.


Answers to your specific questions

Is the read-back worth its cost? Yes, comfortably. create_schema is an administrative, human-initiated, low-frequency operation — a handful of calls per session at the very most, never in a loop, never on a hot path. One additional indexed primary-key lookup against a local SQLite file is microseconds. Set that against what it buys: the payload becomes evidence rather than an echo, and the agent_loop.rs guard's premise becomes true instead of aspirational. If this were on create_node I would push back and ask for it to be conditional; on create_schema it isn't a close call.

Does defect 3's fix change behavior for a caller relying on the swallow? No. I traced every handle_create_schema call site in the workspace — one production path (packages/daemon/src/services/node_service.rs:1871, which maps MarkdownError::Internal → Status::internal and was already prepared for an Err), plus test and playbook-engine call sites. The behavior change is confined to the case where the schema read errors, which previously proceeded into a doomed write and now returns early. Nothing can have depended on the old path: it produced a primary-key violation surfaced as an opaque internal error. Swapping one Err for a strictly more informative Err is not a contract change anyone can be relying on.

Does the regression test genuinely pin the fix? Yes — and notably, the test file is honest about which of its five tests does the pinning, which is unusual and good. a_write_that_cannot_be_verified_is_an_error_not_a_populated_success is the load-bearing one; it arms the fault, asserts Err, and asserts the message both names event_venue and contains "NOT created" / "not present". Revert the read-back and it fails on the Ok(payload) arm with a panic message that reproduces the reported bug verbatim. The other four are honestly documented as passing either way — result_field_list_is_not_an_echo_of_the_request in particular carries a doc comment admitting it does not actually distinguish an echo from a read-back, because normalization runs before the write so both forms agree. Writing that down rather than letting the test name overclaim is exactly right. duplicate_schema_is_rejected_with_an_actionable_error pins defect 3's user-visible half well, including the negative assertion that no raw UNIQUE constraint / PRIMARY KEY text leaks to the agent.

One gap, following from 🟡-1: there is no test for the parse-failure-reads-as-absent case, because that case currently produces a wrong message. If you take the preferred fix in 🟡-1, a test for it comes almost free.

Error message quality (model-facing). Good, and better than the repo average. Both new messages do the three things an agent-facing error needs: name the specific entity ('{schema_id}'), state the outcome unambiguously ("No schema was created." / "It was NOT created."), and — in the read-back-failed case — give the next action ("verify with get_node before relying on it"). They match the register of the existing duplicate-schema rejection nearby, which is the right local benchmark. My only substantive concern is 🟡-1: the categorical "It was NOT created." is the strongest possible claim and the code cannot always support it. Strong claims are right for agent-facing text when true — this one needs the code to earn it.

Minor observation: the "could not be read back to confirm" message tells the agent to verify with get_node, but a schema is fetched by get_schema_node / find_skills in most agent-facing surfaces. Worth checking that get_node is actually the tool name the model has available for this, or the advice sends it somewhere it can't go.


CLAUDE.md compliance

Rule Status
No lint suppression ✅ none added
No #[allow(dead_code)] ✅ none
No #[deprecated] ✅ none
No backward-compat / migration code ✅ — and worth stating plainly, since a "read the row back" change is adjacent to the banned shape: this adds no schema-version check, no backfill, and no on-read format upgrade. It reads the row it just wrote, in the shape it just wrote it. Not a migration.
No docs added to this repo ✅ no .md files, no docs/ directory
Logging standards ✅ Rust-only change; existing tracing usage untouched
No issue numbers in code comments ✅ — the new comments reference behavior and ADRs, not issue numbers
Test command discipline ✅ bun run rust:test:core used, not bare cargo test -p nodespace-core

Verdict

✅ APPROVE — with 🟡-1 requested before merge

The core change is right, the reasoning is unusually well documented, the investigation is honest about what it could and could not reproduce, and the test that matters genuinely pins the fix. This measurably improves code health: a tool result that was structurally incapable of reporting failure now is capable of it, and a cross-package guard that was resting on a false premise now rests on a true one.

Before merge:

  • 🟡-1 — make the "It was NOT created" claim one the code can support, or soften it. This is small and it is the same class of defect the PR fixes.

Before closing #2815:

  • 🟡-4 — file the CLI database-routing follow-up and reference it from the closing comment.

Author's call, no re-review needed:

  • 🟡-2 (test-support feature — defensible as-is; introduce the feature when a second seam appears), 🟡-3 (one comment line on description), and the nits.

@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 (with one item requested before merge) (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

malibio and others added 2 commits September 22, 2026 13:34
Review findings from PR #2832.

Addressed:

- The "It was NOT created" error could be a false statement, and in the
  damaging direction. `get_schema_node` folds two facts into one `Ok(None)`:
  the row is absent, or it is present and `SchemaNode::from_node` failed on
  it. Asserting the first without checking was this PR's own bug in
  miniature — claiming more than the read established. An agent told a schema
  it did commit was never created retries, the exists-check reads `Ok(None)`
  too, and the retry hits the primary-key collision the exists-check exists to
  prevent. One raw row read tells them apart, and each case now gets its
  honest diagnosis. New test verified to fail without the fix.

- `description` is the one output field still taken from the request. It is
  parsed into a markdown child subtree rather than stored on the schema node,
  so reading it back would mean reassembling prose from nodes and would not
  round-trip. Documented, with why it carries none of the weight that made
  echoing the field list a defect.

- `#[non_exhaustive]` on `WriteVerificationFault`, so a later variant is not a
  breaking change to the re-export.

- Recorded the consequence of a predicted/actual schema-id divergence: the
  verification read fails loudly rather than emitting a wrong `schemaId`.

- Documented that `pub` on `set_write_verification_fault` is forced, not
  chosen — the only caller is an integration test under `tests/`, a separate
  crate that neither `#[cfg(test)]` nor `pub(crate)` reaches.

Filed #2835 for the CLI database-routing divergence, rather than leaving the
hypothesis in a PR description. Verified before filing: the CLI stamps no
`x-ns-database-id` unless given `--database`, so a bare read resolves to the
daemon default while an agent turn writes to its own event watcher's database.

Skipped, with reasons:

- A `test-support` Cargo feature for the seam. The review rated this
  "introduce it when a second seam appears"; a feature plus a self-referencing
  dev-dependency is disproportionate for one. The asymmetry it correctly
  flagged is documented instead.
- `parse_declaration_row`'s warn-and-drop in relationships.rs — pre-existing
  and outside this change.
- Trimming the agent_loop.rs comment — it is the record of why the no-op
  guard's premise is now sound, which is the point of the change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The other half of the create_schema disappearance. #2815 fixed the tool
reporting a success it had not verified; this fixes the divergence that most
likely made a verified write look absent in the first place.

With no `--database`, the CLI stamped no `x-ns-database-id` header at all, so
the daemon resolved the request against whatever `registry.default_database`
held when it arrived. An agent turn, meanwhile, writes to the database its own
event watcher is bound to — the one the ai-chat node lives in. Chat in a
non-default database and the write lands correctly while a bare
`nodespace search` reads somewhere else.

Both paths reached the same database whenever the default happened to be the
right one, which is why this never showed up as an error. The failure mode is
silence: a wrong-database read returns a well-formed empty result,
indistinguishable from a write that never happened, and a user or an agent
verifying its own work concludes the data is gone.

`resolve_routing` now resolves the default to a concrete id and stamps it, so
the target is a fact the CLI knows rather than one the daemon decides per
request, and it stays fixed for the whole invocation rather than following a
default that changes mid-session. The single behavioral change: the id is
resolved once at startup. `None` is returned only when the daemon reports no
default at all, which is left for the command to surface — an unstamped
request would have failed downstream on the same condition.

`resolve_routing` becomes `pub` because it is the function whose contract
changed and the unit the regression test drives.

Regression test verified to fail without the fix (resolved `None` where the
seeded default's id was expected).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary

Two commits since the review: 494d8b1b (review fixes) and 0767be65 (the database-routing fix, folded in at the author's request).

Addressed

🟡-1 — the requested-before-merge fix. Correct and important catch: get_schema_node folds two facts into one Ok(None) — the row is absent, or it is present and SchemaNode::from_node failed on it. Asserting the first without checking was this PR's own bug in miniature, and misleading in the costly direction: an agent told a schema it did commit was never created retries, the exists-check reads Ok(None) too, and the retry hits the primary-key collision the exists-check exists to prevent. One raw row read tells them apart; each case now gets its honest diagnosis. WriteVerificationFault gained a ReportUnparseable variant so both states are modelled, and a_committed_but_unreadable_schema_is_not_reported_as_never_created was verified to fail without the fix (it produced exactly the false "It was NOT created").

🟡-3 — description from the request. Documented rather than changed. It is parsed into a markdown child subtree rather than stored on the schema node, so reading it back would mean reassembling prose from nodes and would not round-trip to the input string. The comment records that, and that nothing downstream counts or validates it — the no-op guard reads fields — so it carries none of the weight that made echoing the field list a defect.

🟡-4 — file the routing follow-up. Filed as #2835, then folded into this PR on the author's instruction (see below).

🟢 #[non_exhaustive] on WriteVerificationFault — added, and it immediately paid for itself when the second variant landed in the same commit.

🟢 created_schema_id comment — now states the consequence: a predicted/actual divergence fails the verification read loudly rather than emitting a wrong schemaId.

Correction accepted

The review was right that I mis-cited the precedent for the test seam. set_subtree_access_gate and set_playbook_lifecycle are production injectors (assembly.rs:279/:316); mine is the first purely test-only pub mutator on NodeService. The pub is forced rather than chosen — the only caller is an integration test under tests/, a separate crate that neither #[cfg(test)] nor pub(crate) reaches — and that is now documented at the definition, along with the test-support feature as the escape hatch if a second seam ever appears.

Also in scope now: #2835

Folded in at the author's request rather than left as a follow-up.

With no --database, the CLI stamped no x-ns-database-id header, so the daemon resolved each request against whatever registry.default_database held at arrival. An agent turn writes to its own event watcher's database. Chat in a non-default database and the write lands correctly while a bare nodespace search reads elsewhere — a well-formed empty result, indistinguishable from a write that never happened. That is the most likely explanation for the original report, and it is the half #2815's fix could only make visible, not prevent.

resolve_routing now resolves the default to a concrete id and stamps it. Regression test verified to fail without the fix. One behavioral change worth flagging for review: the id is resolved once at startup, so a CLI invocation no longer follows a default that changes mid-session.

Skipped, with reasons

  • 🟡-2 test-support Cargo feature. The review itself rated this "introduce it when a second seam appears." A feature plus a self-referencing dev-dependency is disproportionate for one seam; the asymmetry it correctly identified is documented instead.
  • 🟢 parse_declaration_row warn-and-drop (relationships.rs:1797) — pre-existing and outside this change, as the review noted.
  • 🟢 trimming the agent_loop.rs comment — it is the record of why the no-op guard's premise is now sound, which is the substance of that part of the change.

Verification

  • 7 regression tests (6 core + 1 CLI); the three load-bearing ones each verified to fail with their fix reverted
  • bun run rust:test:core — exit 0, 35 binaries
  • bun run rust:test:libsql-linked — exit 0
  • cargo test --test cli_integration — 49 passed
  • bun run quality:fix — exit 0, clippy -D warnings
  • Full pre-push gate passed on both commits

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: 0767be65 is new functionality in a subsystem the first review never saw — packages/cli routing, including a pub surface change and a behavioral change to how every CLI invocation resolves its target database. That is exactly the "new functionality added to address feedback" case. The 🟡-1 fix also added a public enum variant and a second read path, which is more than a touch-up. The 🟡-3/🟢 items are comment-only and need no scrutiny.

@malibio malibio added the bug Something isn't working label Sep 22, 2026
@malibio malibio changed the title Build create_schema's result from the persisted row, not the request Make create_schema's result reflect the persisted row, and pin the CLI's target database Sep 22, 2026
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

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

Review Type: Re-Review
Prior review: comment 5775585873 (APPROVE, 🟡-1 requested before merge)
Scope: git diff cc38ee53..HEAD — 494d8b1b (review fixes) + 0767be65 (CLI routing, new functionality)
Diff: 255 insertions / 26 deletions across 6 files.


Previous Review Summary

Item Status
🟡-1 — "It was NOT created" can be a false statement ✅ Addressed (preferred option taken, not the cheap one)
🟡-2 — test-support Cargo feature ⏭️ Skipped — justification sound
🟡-3 — description still from the request ✅ Addressed (documented, as the review offered)
🟡-4 — file the routing follow-up ✅ Addressed and then some — filed as #2835 and fixed here
🟢 #[non_exhaustive] ✅ Added
🟢 created_schema_id comment consequence ✅ Added
🟢 parse_declaration_row warn-and-drop ⏭️ Skipped — justification sound
🟢 trim agent_loop.rs comment ⏭️ Skipped — justification sound

Addressed: 5. Skipped with sound reasons: 3. New issues: 2 (both 🟡).

I verified every claim in the address-review summary against the diff rather than taking it at face value. All of them hold. I also re-ran the tests myself: create_schema_result_reflects_persisted_state_test — 6 passed; cli_integration routing_with_no_selection_pins_the_resolved_default_database_id — 1 passed; cargo build -p nodespace-cli clean.


1. Was 🟡-1 properly addressed? — Yes, correctly.

📁 packages/core/src/schema/mod.rs:1334-1372

The author took the preferred option, not the cheap one. The None arm now issues a raw get_node_verifying read and branches on raw_row_exists, so each of the two facts folded into Ok(None) gets its own honest message:

  • Row absent → "...is not present in the database afterwards. It was NOT created." — the categorical claim is retained, and it is now earned: two independent reads agree the row is gone.
  • Row present, unparseable → "...the stored row is present but unreadable. Do not report it as created, and do not retry: creating it again will collide with the existing row."

This is the right resolution on both counts I care about. The distinction is drawn correctly, and — the part that matters more — the second message closes the trap the prior review described. The retry loop I sketched (agent told "NOT created" → retries → exists-check also reads Ok(None) → write → primary-key violation) is now explicitly headed off by do not retry, with the reason given rather than just the instruction. An agent-facing error that says "don't do X" without saying why tends to get overridden; this one names the consequence.

The honesty is also right in a subtler place. "cannot be read back as a valid schema" does not claim to know why the row is unparseable — it reports exactly what the two reads established (present, and from_node declined it) and nothing more. That is the discipline the whole PR is about, applied to itself.

The fault model is faithful. 📁 packages/core/src/services/node_service/mod.rs:2447-2490 — get_schema_node_verifying returns Ok(None) for both variants, and the two diverge only in get_node_verifying: ReportMissing → Ok(None), ReportUnparseable → the real row. That is precisely the shape the production store produces (the warn!-and-Ok(None) arm at sqlite_store/nodes.rs:3436-3443 leaves the row in the node table untouched), so the seam simulates the real condition rather than a convenient fiction. The extracted write_verification_fault() helper removes the duplicated lock-and-deref. Good.

One deliberate detail worth naming as correct: get_node_verifying matches Some(ReportMissing) => Ok(None), _ => self.get_node(id). The wildcard is load-bearing here rather than lazy — combined with #[non_exhaustive], a future third variant defaults to "the raw row reads normally", which is the safe default, and the compiler still forces a decision at the get_schema_node_verifying site. Fine.

The test genuinely pins it. a_committed_but_unreadable_schema_is_not_reported_as_never_created asserts the negative (!msg.contains("NOT created")) and the positive steer ("do not retry" or "collide"). Asserting the absence of the wrong message is the assertion that actually fails when someone collapses the two branches back together — which is the regression worth pinning. The author reports verifying it fails with the fix reverted; the test's logic supports that claim on inspection.

🟡-1 is resolved. It does not block.


2. The new CLI work in 0767be65 — first-pass review

📁 packages/cli/src/lib.rs:385-427, packages/cli/src/commands/database.rs:133-156

The change is small and the reasoning is sound. I want to answer each of the four questions put to me directly, because two of them have non-obvious answers.

The design is right

The core argument holds: an unstamped request and a stamped-with-the-resolved-default request reach the same database, but only one of them is a fact the client knows. Given that this PR exists because a well-formed empty result was indistinguishable from a write that never happened, making the read target knowable is the correct complement to making the write target verifiable. #2815's fix makes the failure visible; this makes the class of it not happen. Folding it in was the right call — they are one defect seen from two ends.

🟢 On "resolved once at startup rather than per-request" — this is correct, not a regression

I traced this carefully because it was flagged as the thing to scrutinize. It is an improvement, and the alternative is the bug.

A single CLI invocation is a one-shot process. Under the old behavior, each request in one invocation was resolved independently against registry.default_database at arrival, so a database use landing mid-invocation could split one command across two databases — reading from A and writing to B with no indication. Pinning at startup makes an invocation atomic with respect to its target. For a CLI whose every command is short-lived, per-invocation stability is the property you want.

I checked the specific cases raised:

  • database use / all Command::Database — 📁 lib.rs:513-517 does not call resolve_routing at all (registry-global, by design, with a comment saying so). So database use is unaffected, and — importantly — the next invocation resolves the new default freshly. No staleness across invocations.
  • Command::Session — 📁 lib.rs:508 resolves once, same as before. Sessions are still one-shot RPCs from the CLI's side; there is no long-lived stream whose routing could drift.
  • Long-running commands — import, search, query are all single-invocation. Pinning is strictly better for these: a long import can no longer have its target changed out from under it midway.
  • Command::Mcp — 📁 lib.rs:545 forwards the raw cli.database selection (Option<String>, unresolved) to child processes, which each re-invoke this binary and resolve independently. So a long-lived nodespace mcp server does not pin a default for its whole lifetime; each dispatched tool call re-resolves. That is the correct behavior for the one genuinely long-lived case, and it happens to fall out of the existing design rather than needing care. Worth knowing it was checked.

No command is broken by this. Verdict: right call.

🟡-5 (NEW) 📁 packages/cli/src/lib.rs:409-412 — the extra round-trip is acceptable, but it is now unconditional on the connect, not just the list

The cost question deserves a precise answer rather than "it's local, it's fine."

The prior shape short-circuited: None => Ok((DatabaseIdInterceptor::none(), None)) returned without touching the network. The new shape hoists connect_database(sock).await? above the match, so every data-plane invocation now pays one UDS dial plus one ListDatabases RPC that it previously skipped whenever --database was absent — which is the common case.

On absolute cost I am not worried: a UDS connect and one registry list (an in-memory RwLock read over a small Vec, no SQLite I/O — 📁 database_manager.rs:415-442) is sub-millisecond. nodespace is an interactive, human- or agent-invoked one-shot; this is noise against process startup and gRPC channel setup.

What I'd flag instead is the failure-surface change, which is the part that actually costs something: an invocation that previously needed only the data-plane connection now has a second, earlier dependency on DatabaseService succeeding. If List fails for a reason unrelated to the command, the user gets "List RPC failed" from a nodespace search — an error in the registry's vocabulary for a command that never mentioned the registry. The prior review's own principle applies: the message should name what the caller was trying to do.

This is 🟡 and not blocking — DatabaseService and the data-plane services are served by the same daemon over the same socket (📁 router.rs:83), so a List failure almost certainly means the daemon is down, which connect_database already reports with the friendly connect_error_context. The realistic bad case is narrow. But a one-line .context() at the resolve_routing call boundary — "could not determine which database to target" — would keep the error in the caller's vocabulary for pennies. Author's call.

Principle: an error should be phrased in terms of the operation the caller requested, not the internal step that happened to fail.

🟡-6 (NEW) 📁 packages/cli/src/commands/database.rs:145-155 — resolve_default_database_id scans is_default while the response carries default_database_id

ListDatabasesResponse has two representations of the same fact: a default_database_id scalar and a per-entry is_default flag. The new function ignores the scalar and scans for the flag.

I checked whether these can disagree, and today they cannot — 📁 database_service.rs:88-97 builds both from one manager.list() snapshot, and 📁 database_manager.rs:430 derives is_default as default_database == Some(entry.id) from that same snapshot under one lock. So this is not a correctness bug, and I am not asking for a behavior change.

It is a robustness and clarity point. Reading the scalar is one field access against the authoritative value; scanning for the flag is a derived-data search that silently yields None if the invariant ever slips (e.g. a default id pointing at an unregistered entry — default_database_id would be populated, is_default would match nothing, and the CLI would quietly fall back to unstamped routing, which is exactly the behavior this commit exists to eliminate). The scalar also makes the intent self-evident: "ask the daemon which database is default" rather than "search the list for the one wearing the marker."

Note the scalar uses unwrap_or_default() → empty string for "no default", so reading it means filter(|s| !s.is_empty()) rather than a plain map. Still simpler than the scan.

Principle: prefer the authoritative representation over a derived one; when two encodings of one fact exist, depending on the derived one makes your code a hostage to an invariant you don't own.

Reasonable counter: resolve_database_id_by_selection directly above already scans listed.databases, so the new function is locally consistent with its neighbour. That's a fair defense and why this is 🟡, not 🔴.

🟢 Ok(None) when no default exists — degrades correctly

I checked this against the daemon rather than trusting the doc comment, and the comment is accurate.

When no default is set, resolve_default_database_id returns Ok(None) → DatabaseIdInterceptor::none() → unstamped request → daemon's resolve_database_id(None) hits 📁 database_manager.rs:888-892 and returns "no default database is set" as NOT_FOUND. So it is not a silent restoration of the old behavior: it reaches an explicit, correctly-phrased error, one hop later, from the component that owns the concept. Failing here instead would only change which layer's wording the user sees, and the daemon's is the better wording.

The one case where the two diverge is a daemon without the routing layer installed (📁 db_routing.rs:56-65): unstamped → Ok(None) → serve the single database; stamped → UNIMPLEMENTED. But that path is unreachable for this concern — no-default-set implies a manager exists to have been asked, and all four in-repo serve loops install the layer (📁 main.rs:1227/1314/1473/1582). Pro builds the same router via build_base_router. Correct as written.

🟢 pub on resolve_routing — justified

Unlike 🟡-2's seam, this one is not test-only plumbing. resolve_routing is genuine library API of nodespace_cli, a crate whose lib.rs already exposes connect, connect_import, connect_session, connect_local_agent, connect_database and run as pub — it is structured as a library with a thin main.rs, precisely so integration tests can drive it. resolve_routing returning the resolved id is the observable this commit changes, and there is no other honest way to assert on it: going through run() would test the id only indirectly via command output, which is a weaker assertion and a more brittle test.

So the pub is a coherent extension of an existing pattern, not a new category. No action. (Contrast with 🟡-2, where the prior review's objection was specifically that set_write_verification_fault was the first purely test-only pub mutator — that argument does not transfer here.)

The test itself is well-constructed: it asserts the resolved id equals the seeded default and that an explicit selection of the same database resolves identically, so the two paths are pinned as agreeing rather than one being special-cased. That second assertion is what catches a future refactor that "optimizes" the default path back into a None.


3. Skipped items — all three justifications are sound

  • 🟡-2 (test-support feature) — ✅ Sound, and the skip is the disciplined choice. The prior review explicitly rated this "introduce the feature when a second seam appears", and no second seam appeared. A Cargo feature plus a self-referencing dev-dependency is real ceremony for one call site. Critically, the author did the part that was actually owed: the correction is accepted and documented at the definition (📁 node_service/mod.rs:2428-2438), including the test-support escape hatch as the named next step. I re-verified the seam is still reachable from exactly one place (create_schema_result_reflects_persisted_state_test.rs) and never from production. YAGNI, applied correctly — with a signpost so the next person doesn't have to rediscover the reasoning.

  • 🟢 parse_declaration_row — ✅ Sound. Pre-existing, in a different file, outside this change's blast radius. I flagged it originally as an observation, explicitly "not worth acting on here." Fixing it would have widened the PR against the atomicity principle. Correctly left alone.

  • 🟢 agent_loop.rs comment trim — ✅ Sound. My original note said "fine as-is." The comment is the cross-package record of why the no-op guard's premise is now true — which is genuinely the substance of that part of the change, and exactly the "why" that comments should carry. Declining a purely aesthetic trim on substantive prose is the right call.

No disagreement with any of the three.


4. New issues

Both are the 🟡-5 and 🟡-6 above; both are in the CLI commit; neither blocks. Nothing new in 494d8b1b — it is a clean implementation of the requested fix.


CLAUDE.md compliance (new code)

Rule Status
No lint suppression ✅ none added
No #[allow(dead_code)] / #[deprecated] ✅ none
No backward-compat / migration / dual-mode ✅ — worth stating for the CLI change specifically: the old unstamped path is deleted, not kept behind a flag or a fallback. None now means "the daemon has no default", not "route the old way". That is the greenfield shape.
No docs added to this repo ✅ no .md, no docs/
No issue numbers in code comments ✅ — the new comments describe behavior; the #2835 reference is confined to the commit message, which is correct
Logging standards ✅ Rust-only; no new logging
Test discipline ✅ bun run rust:test:core reported; my own cargo test -p nodespace-cli --test cli_integration is a targeted single-test run, not the banned bare cargo test -p nodespace-core
Tests pass ✅ 6 core + 1 CLI verified green locally

Verdict

✅ APPROVE — no blocking items

🟡-1 was addressed with the preferred fix rather than the cheap one, and the result is better than what I asked for: both states are modelled in the fault enum, both get an honest message, and the unparseable case actively steers the agent away from the retry that would compound the problem. The distinction is drawn correctly and the new error claims exactly what the code can support.

The folded-in CLI work is a sound, well-scoped change that closes the other half of the original report. The behavioral change flagged for scrutiny — pinning the database id per invocation — is correct; I traced database use, session, long-running and MCP paths and found no case where it breaks something, and one case (mcp) where the right thing already happens for free.

Optional, author's call, no re-review needed:

  • 🟡-5 — wrap resolve_routing's failure in the caller's vocabulary (one .context()).
  • 🟡-6 — read default_database_id instead of scanning is_default.

Neither changes behavior today. Both are small enough to fold into a follow-up or drop entirely without loss.


Automated pragmatic re-review. Verified independently: cargo build -p nodespace-cli clean; create_schema_result_reflects_persisted_state_test 6/6; routing_with_no_selection_pins_the_resolved_default_database_id 1/1.

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

…its errors

Both items the re-review marked optional. Neither changes behavior today; both
protect the property the routing change exists to establish.

Read `default_database_id` rather than scanning entries for `is_default`. The
response carries the same fact twice — the scalar is the registry's answer, the
flag is derived from it — and they cannot disagree today, since both come from
one snapshot under one lock. The scalar is still the one to trust: were that to
slip (a default id naming an entry the listing omits), a scan would match
nothing and return `None`, quietly restoring exactly the unstamped routing this
function replaced. An empty string is the daemon's "unset", not an id, so it is
filtered rather than treated as one.

Re-frame a registry-side failure at the routing boundary. Every data-plane
command now resolves the default, including ones that never mention the
registry, so a bare "List RPC failed" could surface from `nodespace search` in
vocabulary that command never used.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary (round 2)

Commit f37a7eaa. Both re-review findings were marked optional and author's-call; I took both — each is a few lines, and 🟡-6 in particular guards the property the routing commit exists to establish.

Addressed

🟡-6 — read default_database_id instead of scanning is_default. The sharper of the two. The reviewer is right that these cannot disagree today (both built from one snapshot under one lock), but the failure mode if that ever slipped is the specific one this commit removes: a scan matching nothing returns None, which quietly restores unstamped routing. Trusting the registry's own scalar means a broken invariant surfaces as a wrong id rather than as a silent reversion. Filtered the empty string, since unwrap_or_default() is the daemon's "unset" and not an id.

🟡-5 — re-frame registry failures at the routing boundary. Added .context("could not determine which database to use"). Every data-plane command now resolves the default, so a bare "List RPC failed" could reach a user who ran nodespace search and never mentioned the registry.

Verification

  • cargo test --test cli_integration — 49 passed, including routing_with_no_selection_pins_the_resolved_default_database_id exercising the new scalar path
  • bun run quality:fix — exit 0, clippy -D warnings
  • Full pre-push gate passed

No new tests: neither change alters behavior in any state reachable today, which is exactly why both were optional. The existing routing test covers the path 🟡-6 rewrote, and it still pins (verified it runs through the new code, not around it).

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: Both changes are small, low-risk, and confined to code the re-review just examined in full. 🟡-6 swaps one read of a response field for another read of the same response — no new control flow, no new failure mode, and the reviewer had already traced that the two sources agree. 🟡-5 is a single .context() on an existing error path. Neither adds functionality, changes a signature, or touches a subsystem outside the prior review's scope. The re-review's verdict was APPROVE with these two listed as droppable without loss; implementing them as specified does not reopen anything.

The PR is ready for merge, pending the user's decision.

@malibio
malibio merged commit d571ad9 into main Sep 22, 2026
@malibio
malibio deleted the issue-2815-create-schema-false-success branch September 22, 2026 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

create_schema reports success with a populated field list for a schema that was never persisted

1 participant