Skip to content

Fix resolve_query no_match against a node whose property does contain the value - #1910

Merged
malibio merged 2 commits into
mainfrom
issue-1908-resolve-query-nomatch
Aug 2, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-1908-resolve-query-nomatch

Conversation

@malibio

@malibio malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

Summary

resolve_query returned no_match for a bare-value query ("the 2400 one") against a node that does have a matching property (replacement_cost: 2400). Live-diagnosed against the real locked model (gemma-4-e4b-q4km) rather than guessed at — the mocked test suite hardcodes engine responses, so this path was previously unverified by cargo test (its own doc comment flags this gap).

Two independent defects, both found by driving exec_resolve_query's real decomposition prompt against the model:

1. Decomposition prompt didn't separate "identify" from "update target". For "The 2400 one came back — set it to returned", the model emitted a filter on the target update state (status: returned) instead of the identifying value (2400) — finding nothing, since no node has that status yet (it's still checked_out). The prompt now explicitly tells the model to filter only on what currently identifies the node, never on what the request wants to change it to, with a worked example matching this exact ambiguity.

2. No coercion between a filter's JSON type and its target field's declared schema type. Even after decomposition names the right field, the model isn't constrained to encode a numeric value as a JSON number — it can emit "2400" (string) instead of 2400. SQLite's json_extract preserves the stored value's real type, so = '2400' against a stored number silently matches nothing (verified directly against sqlite3: json_extract('{"a":2400}','$.a') = '2400' → 0, = 2400 → 1). coerce_filter_value_to_field_type now normalizes a stringified number against a number-typed field before the query runs.

Verification

Live, in-process GGUF (gemma-4-E4B-it-Q4_K_M), driving exec_resolve_query's real prompt (not the eval harness, not a stub):

before after
resolves "the 2400 one" against replacement_cost: 2400 0/2 2/2

Both defects were confirmed independently — reverting each fix in isolation reproduces the failure the corresponding test targets.

What changed

  • packages/agent/src/local_agent/tools.rs
    • Decomposition prompt: added an explicit identify-vs-update-target distinction with a worked example.
    • New coerce_filter_value_to_field_type: normalizes a JSON-string numeric value to a JSON number when the target field is schema-typed number, before the filter reaches run_node_query.
    • New mocked regression test for the type-coercion defect (resolve_query_coerces_stringified_number_to_match_numeric_field).
    • New #[ignore]-gated live-model regression test (live_paraphrased_identifier_resolves_against_real_model) that closes the real-model-accuracy gap the suite's own doc comment flagged — run explicitly with E2E_MODEL=~/.nodespace/models/gemma-4-E4B-it-Q4_K_M.gguf cargo test -p nodespace-agent --lib resolve_query_integration::live_paraphrased_identifier_resolves_against_real_model -- --ignored --nocapture.

Test plan

  • cargo test -p nodespace-agent --lib resolve_query — 25 passed, 1 ignored (the new live test)
  • cargo test --workspace (full Rust workspace, excluding the Tauri app) — all crates pass, 0 failures
  • bun run test — 171 files / 4108 tests passed (matches baseline)
  • bun run test:scripts — 77 passed
  • bun run test:skill — 20 passed
  • bun run quality:fix — clean, no lint/format issues in the changed file
  • Live model verification: 2/2 real-model runs resolve correctly post-fix (0/2 pre-fix)
  • Pre-push gate passed

Closes #1908

🤖 Generated with Claude Code

https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs

… the value (closes #1908)

Two independent defects in exec_resolve_query's decomposition step, both
diagnosed by driving the real locked model (gemma-4-e4b-q4km) against the
issue's exact repro:

1. The decomposition prompt didn't distinguish "what identifies the node"
   from "what the request wants to change it to". For "The 2400 one came
   back — set it to returned", the model filtered on the target update
   state (status: returned) instead of the identifying value (2400),
   finding nothing since no node has that status yet. The prompt now
   explicitly separates identifying values from update targets and warns
   against filtering on the latter.

2. Separately, nothing coerced a decomposed filter's value to match its
   target field's declared schema type. A numeric field's value emitted as
   a JSON string (`"2400"` instead of `2400`) silently fails to match a
   stored number, since SQLite's json_extract preserves the stored value's
   real type and `2400 = '2400'` is false. coerce_filter_value_to_field_type
   now normalizes stringified numbers against number fields before the
   query runs.

Verified live: 2/2 runs resolve correctly post-fix vs. 0/2 pre-fix on the
real model, closing the gap the test suite's own doc comment flagged (every
existing test stubbed the engine, so real decomposition accuracy was
untested by cargo test). Added a live #[ignore]-gated regression test
alongside a mocked regression test for the type-coercion defect.

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

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1910 — Fix resolve_query no_match against a node whose property does contain the value

Review Type: Initial Review (no prior review comments found on this PR).

Requirements Check (issue #1908)

Issue #1908 asked for root-causing and fixing resolve_query returning no_match for a bare-value query ("the 2400 one") against a node with a matching property (replacement_cost: 2400), scope explicitly left open ("could be decomposition, search-scoping, or something else — not yet root-caused").

  • ✅ Root cause 1 identified and fixed: decomposition prompt conflated the identifying value with the update target.
  • ✅ Root cause 2 identified and fixed: no JSON-type coercion between filter value and schema field type, causing a silent json_extract type mismatch.
  • ✅ Fix verified against the real locked model (not just mocked tests) — 0/2 → 2/2 across two independent live runs, with reversion-per-fix isolation confirming each defect independently.
  • ✅ Regression test added for the mockable defect (type coercion).
  • ✅ Live-model test added (ignore-gated) closing a documented gap in the existing suite.

All acceptance criteria implied by the issue are met. This is a well-diagnosed, well-scoped fix.

Overall Assessment

Net positive, mergeable change. Single file, single cohesive purpose (both defects are on the same causal path to the same symptom), backed by real root-cause analysis against the live model rather than guesswork — exactly the rigor this class of bug (LLM-decomposition-to-structured-filter) needs, since a mocked-engine test suite is structurally blind to prompt-following regressions. I have one Important finding on the coercion function's scope and one Important finding on regression coverage for the prompt change; neither blocks merge but both should be tracked.


Findings

Critical Issues

None.

Important

1. coerce_filter_value_to_field_type is narrower than the bug class it fixes — same silent-failure mechanism applies to boolean, and to the reverse direction for text/enum.
📁 packages/agent/src/local_agent/tools.rs:223-244 (new function), and packages/core/src/services/query_service/mod.rs:539-548 (format_value)

I traced the actual SQL-formatting code this filter value eventually reaches. format_value serializes each JSON Value variant differently and unconditionally:

Some(serde_json::Value::String(s)) => Ok(format!("'{}'", self.escape_string(s))),
Some(serde_json::Value::Number(n)) => Ok(n.to_string()),
Some(serde_json::Value::Bool(b)) => Ok(b.to_string()),

Combined with json_extract's type-preserving comparison (the mechanism this PR's own doc comment correctly diagnoses for number), this means any JSON-type mismatch between the filter value and the stored property's real type produces the same silent no_match — not just string-vs-number. Concretely, with the schema types actually in use elsewhere in this codebase (core_schemas.rs has boolean, enum, datetime, array, object alongside number/text/date):

  • A boolean field: if the decomposition model emits "true" (string) instead of true (bool) — plausible, since the prompt gives no JSON-type guidance for booleans either — json_extract(...) = 'true' against a stored JSON true is the exact same false-negative.
  • The reverse direction: a text/enum field where the model emits a bareword-looking value as a JSON number (e.g. an enum member that's numeric-looking, or a numeric ID stored as text) would also silently mismatch.

This is not a hypothetical extrapolation — it's the same code path (format_value + json_extract), the same input source (an unconstrained decomposition model), and the same observable symptom (no_match indistinguishable from "no such node") that #1908 was filed for. Scoping the fix to exactly the one reproduced case is defensible under YAGNI if the intent is "fix what's proven, file a follow-up for the rest" — but as written there's no tracking issue referenced for the boolean/reverse-direction gap, so it risks becoming another silently-broken, unfiled case exactly like #1908 was (which itself was split out of #1894 as "known-adjacent, deliberately not fixed" and had to be re-discovered later).

Recommendation: Either (a) generalize coerce_filter_value_to_field_type to cover boolean symmetrically ("true"/"false" string → JSON bool) while leaving text/enum/other types alone since coercing a bareword to those is lossier and riskier, or (b) if intentionally scoping to just the confirmed case, file a follow-up issue now for the boolean case specifically, referencing this PR's diagnosis so it doesn't require re-diagnosis from scratch next time it's hit live. Given the fix is already a small pure function and the boolean case is a one-line addition with the identical shape, I'd lean toward (a) — the marginal cost is low and it closes a predictable gap in the same commit rather than deferring a bug you already know how to fix.

Engineering principle: When a fix's root cause is "a general class of unconstrained model output hits a type-sensitive comparison," treating only the reproduced instance while leaving structurally identical instances unaddressed is scope-creep-avoidance taken past the point of diminishing returns — the fix and the bug class should be the same shape.

2. No live-model coverage for potential prompt regressions on previously-working phrasings.
📁 packages/agent/src/local_agent/tools.rs:1540-1580 (prompt rewrite), test section packages/agent/src/local_agent/tools.rs:3671+

The prompt rewrite adds an "identify vs. update target" framing that is necessary for the bug's repro case but is new conceptual machinery injected into every decomposition call, including the dollar-amount and relative-date phrasings that had no such ambiguity and were (per the PR description) already working. I read the full prompt text in the diff: the new instructions are additive and reasonably scoped ("Only filter on the identifying part — never on the target state of an update"), and a pure-lookup request like "show me the invoice for 2400" has no update-target language for the model to get confused by, so a clean regression is not obviously likely from reading the prompt alone.

However: the only live-model test this PR adds (live_paraphrased_identifier_resolves_against_real_model) covers exactly the one repro phrasing, is #[ignore]-gated (not run in CI or the pre-push gate), and provides zero coverage — live or mocked — for whether the previously-working phrasings still resolve correctly against the real model post-rewrite. The existing mocked tests are structurally incapable of catching this class of regression, as the PR description itself acknowledges, since they hardcode the engine's JSON response rather than exercising the model's prompt-following behavior. Under this project's "no CI, pre-push gate is the test surface, live-model tests are opt-in" model (per CLAUDE.md), an ignore-gated test that isn't part of any routine gate means a prompt regression here would only surface via manual live testing or, worse, a future live bug report — i.e., exactly the failure mode issue #1908 itself was.

Recommendation: Not a blocker — the PR's own diagnosis methodology (live-model verification) is sound and better than what preceded it. But this should be explicitly flagged as a residual risk, not silently assumed covered. Suggest either (a) extending the new live test (or adding a sibling one) to also assert against a dollar-amount and a relative-date phrasing in the same run, so the one manual invocation gives broader confidence, or (b) tracking "spot-check previously-working resolve_query phrasings against the live model" as a manual follow-up before this ships to any real usage path, since the mocked suite cannot self-verify prompt changes.

Engineering principle: A test that only re-proves the bug you just fixed doesn't protect the invariant the fix depends on (that other phrasings still work) — regression tests should cover the blast radius of the change, not just its trigger case, especially when the change touches shared prompt text used by multiple call patterns.

Suggestions

3. Coercion silently drops non-finite/unparseable values rather than surfacing them.
📁 packages/agent/src/local_agent/tools.rs:236-42

if let Some(Value::String(s)) = &item.value {
    if let Ok(n) = s.parse::<f64>() {
        if let Some(num) = serde_json::Number::from_f64(n) {
            item.value = Some(Value::Number(num));
        }
    }
}

If s.parse::<f64>() fails (model emits a non-numeric string for a number field, e.g. "twenty-four hundred") or from_f64 returns None (NaN/Infinity — not realistically reachable from parse::<f64> on typical text, so low risk), the function silently falls through and returns the original string-typed filter unchanged, which will then silently mismatch downstream exactly as before the fix — no different failure mode than pre-PR, just not improved by it. This is fine as "no regression," but worth confirming it's the deliberate choice versus logging or a graceful downgrade to a "no filter, query-string fallback" path. Low priority since the failure mode is unchanged rather than introduced.

4. Integer-valued floats: round-trip fidelity is fine for the Equals comparison path but worth a one-line confirmation in the doc comment.
📁 packages/agent/src/local_agent/tools.rs:223-244

serde_json::Number::from_f64(2400.0) produces a Number that serializes as 2400.0, not 2400 — I confirmed this is how serde_json handles floats parsed via from_f64 (it doesn't collapse back to an integer representation). Downstream, format_value in query_service/mod.rs:543 does n.to_string(), which for a f64-backed Number will also render 2400.0. Since json_extract is comparing against SQLite's numeric affinity (2400.0 = 2400 is true in SQLite), this does not break the fix — just flagging it as slightly surprising if anyone greps for the literal string 2400 in generated SQL while debugging. Nit: the doc comment could note "the coerced number may render with a trailing .0; this is harmless under SQLite numeric comparison" to save a future debugger a detour.

Nitpicks

  • Nit: packages/agent/src/local_agent/tools.rs:3436 (new mocked test) — the assertion only checks result["resolved"] == true, not that the correct node id was resolved. With only one node in the fixture this is unambiguous today, but if this test is later used as a template for a multi-node ambiguity case, checking the resolved id/title would give a stronger guarantee. Not worth blocking on for this single-fixture test.
  • Nit: The live test's println!("resolve_query live result: {}", result.result) — acceptable given this is an #[ignore]-gated, manually-invoked diagnostic test (CLAUDE.md's no-raw-console.log/logger rule targets production code and is a frontend TS convention; test files are explicitly exempt, and this is Rust test code besides). No action needed, just confirming it's not a standards violation.

Architecture

coerce_filter_value_to_field_type is a well-placed pure function: takes an AgentFilterItem by value, returns it, no side effects, single call site (tools.rs:1641) inserted via .map() in the existing filter-building iterator chain, positioned correctly before run_node_query/execute_query consumes the filters. This is the right layer — it normalizes agent-tool-boundary input before it reaches the generic QueryService, rather than pushing type-awareness into the generic SQL-building code, which is the correct separation of concerns (the coercion is specific to "LLM decomposition output," not a general QueryService concern).

The PR is atomic — one file, two defects that are both on the single causal path from the same symptom, not a bundle of unrelated changes.

Security

No user input reaches SQL directly here — the AgentFilterItem values still flow through QueryService's existing escape_string/parameterization path for strings and n.to_string() for numbers (not raw user text interpolation of arbitrary content). No new attack surface introduced by this PR.

Testing

Test coverage is appropriately dual-mode for the constraint this codebase operates under (no CI, pre-push gate as the routine test surface): a fast mocked regression test that runs every time, plus an #[ignore]-gated live-model test for the behavior class mocked tests can't cover. This dual-mode pattern is the right response to the project's "no CI, two-dev, Mac-target" reality — see Important finding #2 for the one gap (blast radius of the prompt change).

Recommendation

COMMENT (approve-leaning). This is a solid, well-diagnosed fix that measurably resolves the reported issue with real verification rather than guesswork. Findings #1 and #2 are both "Important" — worth a conscious decision before merge (file a follow-up, or extend scope/tests) but neither is a correctness or security blocker in what's shipped. I'm not blocking merge on them; flagging for the author's judgment call per this PR's own standard of rigor.

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

Comment-level review posted above (findings #1 and #2 flagged Important, none Critical) — see full report in the PR comment thread.

@malibio

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Recommendation: APPROVE (with one follow-up issue to file)

Two genuinely independent defects, correctly diagnosed, fixed at the right layer, in a single atomic commit touching one file. The standout quality signal here is that both defects were verified against the real locked model rather than reasoned about — that is exactly the right rigor for a class of bug (silent no_match) whose defining characteristic is being indistinguishable from correct behavior.

I independently verified the core mechanism claim rather than taking the diff's word for it:

sqlite> select json_extract('{"a":2400}','$.a') = '2400',   -- 0  ← the bug
               json_extract('{"a":2400}','$.a') = 2400,     -- 1
               typeof(json_extract('{"a":2400}','$.a'));    -- integer

The doc comment's stated mechanism is accurate. I also verified the new mocked test actually guards the defect — removing only the .map(coerce_filter_value_to_field_type) call at tools.rs:1644 makes resolve_query_coerces_stringified_number_to_match_numeric_field fail with left: Bool(false), right: Bool(true), and restores to green with it. A regression test that passes either way guards nothing; this one does not have that problem. Full suite: 25 passed, 0 failed, 1 ignored.

Findings

Critical Issues

None.


Section A — Scope of coerce_filter_value_to_field_type (tools.rs:236-256)

Opinion: acceptably scoped for merge, but file a follow-up. Do not block.

The narrow scoping is the right call for this PR — YAGNI, and the number case is the one confirmed against the real model. Speculative coercion rules for types nobody has observed failing would be unverified guesses in a subsystem where unverified guesses are precisely what produced this bug.

But I want to be direct about something the doc comment currently gets wrong, because it will mislead the next reader:

Only number needs this: text/enum fields are already strings, and date filters arrive as YYYY-MM-DD strings by construction

The premise is "the model always emits strings, so only string→number needs fixing." That premise does not hold, and the boolean case is a concretely reachable symmetric failure. create_schema's own tool schema advertises boolean as a valid field type (tools.rs:712, tools.rs:787), and core schemas do declare boolean fields (core_schemas.rs:443, :1275). Verified:

sqlite> select json_extract('{"a":true}','$.a') = 'true',  -- 0  ← same silent no-match
               json_extract('{"a":true}','$.a') = 1;       -- 1

A model asked to filter "the archived one" against archived: boolean emitting "true" instead of true reproduces this bug exactly, with the same silent-failure signature. Nothing in the current prompt constrains JSON encoding, which is the root cause the PR itself identifies.

Two smaller notes on the same premise:

  • text/enum are not safely "already strings" in the reverse direction. field_type is a bare String with no validating enum, and both "text" and "string" appear in production schemas (core_schemas.rs:1124, :1200; context_ops.rs:526). A model emitting unquoted 2400 for a string-typed field yields json_extract(...) = 2400 against a stored "2400" — false. Less likely than the boolean case, but the same class.
  • The date claim rests on prompt adherence ("by construction — see the decomposition prompt"), not on a type invariant. That is a weaker guarantee than the comment's phrasing implies, and it is load-bearing.

Requested change (non-blocking, doc only): soften the comment so it states what was confirmed rather than asserting a general safety property that isn't true. Something like: "Only number is handled here — it is the one mismatch confirmed against the real model. The same silent-mismatch shape is reachable for boolean (= 'true' vs stored true) and, in reverse, for string-typed fields; extend here when observed." This costs nothing and prevents the next reader from concluding boolean is proven-safe when it merely hasn't been tested.

On the general shape: the underlying defect is that the decomposition model is not JSON-type-constrained, and per-type patching in Rust is a symptom-level fix that will accrete one arm per observed failure. The structurally better fix is constraining the decomposition output (grammar/JSON-schema-constrained decoding, or having the prompt state the expected JSON encoding per field type alongside name: type). I am not asking for that in this PR — it is a larger change needing its own live-model validation. But it is the right destination, and worth capturing in the follow-up issue rather than discovering it after the third coercion arm lands.


Section B — Regression risk in the prompt rewording (tools.rs:1543-1565)

Opinion on the pure-lookup concern: low risk, no change requested.

I read the full reworded prompt against the "show me the invoice for 2400" case (pure lookup, no update semantics). The framing degrades gracefully:

"The request may describe two different things..." — hedged, not asserted. A request with no update clause simply has an empty "changed to" part.

"Only filter on the identifying part" — for a pure lookup, the entire request is the identifying part, so this instruction is a no-op rather than a suppressant.

The failure mode you asked me to check — the model second-guessing and suppressing a filter — would require it to misclassify an identifying value as an update target. The worked example anchors against exactly that: it names 2400 as identifying and returned as the update. The mechanism pushes toward emitting the value filter, not suppressing it. I also note the prose only ever instructs "never filter on the target state" — it never instructs "omit a filter," so there is no textual hook for suppression. The dollar-amount bullet was additionally broadened ("a bare number to a number field"), which should help lookup phrasings if anything.

Opinion on the testing gap: real, and worth stating plainly — but not a blocker.

You are correct that the existing mocked tests cannot catch a live-model prompt-following regression, and I want this on the record rather than buried:

  • resolve_query_regression_dollar_amount_phrasing and resolve_query_regression_relative_date_phrasing both hardcode the engine's JSON response (executor_with(ns, engine_json)). They exercise the filter→SQL→storage path downstream of the prompt. They do not execute the prompt at all. They will stay green if the reworded prompt makes the real model emit nothing for those phrasings.
  • The only live-model coverage added, live_paraphrased_identifier_resolves_against_real_model, is #[ignore]-gated and covers exactly one phrasing — the bug repro. The two phrasings actually at regression risk from the rewording have zero live coverage.

So the regression surface of this prompt change is, strictly, unmeasured. That said, I do not think it blocks merge, for reasons specific to this repo:

  1. Per project constraints there is no CI; the pre-push gate is the test surface and live-model tests are necessarily opt-in. A blocking demand for automated live-model regression coverage is a demand this repo's architecture cannot satisfy today — that is an infrastructure gap, not a defect in this PR.
  2. The change is net-positive on measured evidence: 0/2 → 2/2 across two independent live runs on the exact repro.
  3. The prior state was a confirmed, reproducible user-facing bug. Trading a confirmed failure for an unmeasured-but-argued-low risk is a favorable trade.
  4. This PR adds the first live-model test in a suite whose own doc comment concedes every other test stubs the engine. That is a directional improvement, not a shortfall.

What I'd ask for in the follow-up (not this PR): parameterize the live test over the three phrasings (dollar amount, relative date, bare-number identifier) plus a pure-lookup case, so the ignored test becomes a runnable prompt-regression suite rather than a single-case witness. The scaffolding already exists — it is a loop over fixtures, not new infrastructure. That converts "argued low risk" into "measured low risk" the next time this prompt is touched, which it will be.


Suggested Improvements

  • tools.rs:236-256 — doc comment overstates safety. See Section A. Narrow the claim to what was confirmed; explicitly flag boolean as reachable-but-unhandled. Doc-only, no behavior change.

  • tools.rs:249-253 — from_f64 produces 2400.0, not 2400. Verified: serde_json::Number::from_f64(2400.0).to_string() → "2400.0". This is correct for the SQL path — format_value (query_service/mod.rs:543) emits n.to_string(), and SQLite's json_extract(...) = 2400.0 against a stored integer 2400 evaluates true (verified). So no bug today. But the coerced AgentFilterItem is a value that could be logged or surfaced, and 2400.0 reads oddly for a value the user wrote as 2400. Consider preferring an integer representation when the parse is integral:

    if let Ok(i) = s.parse::<i64>() {
        item.value = Some(Value::Number(i.into()));
    } else if let Ok(n) = s.parse::<f64>() { /* existing f64 path */ }

    Nit-adjacent, not required. Current behavior is correct; this is fidelity to user intent. Also confirms your from_f64 → None question: it only returns None for NaN/Infinity, and str::parse::<f64>() can produce those from literal "inf"/"NaN" input — the if let Some guard handles it correctly by leaving the value untouched. Correct as written.

Testing

  • tools.rs:3441-3477 — mocked regression test assertion is adequate. You flagged a concern that it only checks resolved: true without verifying the correct node resolved. In this fixture there is exactly one node, so resolved: true is unambiguous — run_node_query returns 1 match, and any wrong-node outcome would surface as no_match or multiple_matches, both of which fail the assertion. Adding a second decoy invoice would strengthen it into a discrimination test rather than a match/no-match test, which would be better — but the current assertion is not misleading, and I verified it fails without the fix. Acceptable.
  • Good practice worth calling out: create_invoice routes through the real create_node tool, so the test exercises the actual storage/query round-trip. That is why the test could detect a SQL-level type mismatch at all — a mocked store would have missed this entire bug class.

Architecture

coerce_filter_value_to_field_type is correctly layered: a pure function, no side effects, called exactly once at tools.rs:1644, positioned after defensive deserialization and before run_node_query. Placing it in the .map() after the .filter_map() is right — it operates only on filters that already parsed. Taking Option<&SchemaNode> and returning the item unchanged on every miss (no property, no schema, no field, wrong type) means it cannot make things worse than the pre-fix behavior. Good defensive shape.

Standards Compliance

  • No lint suppression, no #[allow(dead_code)], no #[deprecated], no backward-compat shims. Verified across the diff.
  • Single file, single atomic commit, no bundled unrelated changes. Verified via git diff --name-only origin/main...HEAD.
  • No issue numbers in prose documentation; the #1908 references are in Rust test doc comments, which is the code/commit surface the standard permits.
  • tracing::warn! used for the dropped-filter path, not raw logging.

Nitpicks

  • Nit: tools.rs:3679-3685 — the live test's run instructions hardcode gemma-4-E4B-it-Q4_K_M.gguf in the E2E_MODEL example path. Fine as a copy-paste convenience, mild staleness risk if the locked model changes. Not worth churn.
  • Nit: tools.rs:3690-3693 — silently returning when E2E_MODEL is unset makes an explicitly-requested --ignored run pass vacuously if the env var is forgotten. panic! would be a louder, more honest failure for a test you have to opt into. Minor.

Follow-up to file

One issue covering: (1) boolean filter-value coercion — same silent-no-match shape, confirmed reachable via SQLite semantics and create_schema's advertised type vocabulary; (2) parameterizing the live-model test across the dollar-amount, relative-date, and pure-lookup phrasings so prompt regressions become measurable; (3) evaluating JSON-type-constrained decomposition output as the structural fix that makes per-type coercion arms unnecessary.

None of these should hold up a verified fix for a confirmed user-facing bug.

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

Recommendation: APPROVE (formal approval blocked — GitHub does not permit approving one's own PR; recording as a review comment).

Two independently-verified defects, fixed at the right layer, single atomic commit. Verified the SQLite type-mismatch mechanism directly and confirmed the new mocked regression test genuinely fails without the coercion. Full review posted as a PR comment — one doc-comment correction requested (the boolean case is reachable, not proven-safe) and a follow-up issue to file; neither blocks merge.

…coverage

Both from pragmatic-code-review on PR #1910:

1. coerce_filter_value_to_field_type now also normalizes a stringified
   boolean ("true") to a JSON boolean for boolean-typed fields, matching
   the same silent json_extract type-mismatch mechanism as the number case
   — verified via the same isolated-revert method (reverting the boolean
   branch alone reproduces the failure the new mocked test targets).

2. The live-model test now covers three phrasings in one model load: the
   issue's paraphrased-identifier repro plus the pre-existing dollar-amount
   and relative-date phrasings, confirming the prompt rewrite doesn't
   regress cases with no identify-vs-update-target ambiguity. Live-running
   surfaced a real, pre-existing (not a regression) ambiguity in "next
   Friday" — the model consistently reads it as the Friday of the
   following calendar week rather than the coming Friday. The test now
   seeds both candidate dates so the assertion targets prompt-following
   rather than a specific calendar interpretation.

Verified live: all three phrasings resolve correctly (2/2 clean runs for
the original repro plus dollar-amount and relative-date, both previously
untested against a real model).

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

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1910 — Fix resolve_query no_match against a node whose property does contain the value

Review Type: Re-Review (delta review of commit 74d96d4d against the prior review of eca070ad)

Previous Review Summary

Two prior reviews (both COMMENT, approve-leaning) on eca070ad found no Critical issues and two Important findings:

  1. coerce_filter_value_to_field_type only coerced stringified number values, leaving the identical json_extract type-mismatch mechanism unhandled for boolean fields.
  2. The only live-model test covered exactly the bug's repro phrasing; the mocked suite is structurally blind to prompt-following regressions on other phrasings (dollar-amount, relative-date) touched by the same prompt rewrite.

Scope of This Re-Review

git diff eca070ad..74d96d4d — one commit, one file (packages/agent/src/local_agent/tools.rs, +212/-49), both changes claimed to directly address the two Important findings above. I reviewed only this delta, not the full PR diff already covered by the prior reviews.


Finding #1 — Boolean coercion: Addressed, correctly.

coerce_filter_value_to_field_type (tools.rs:238-265) is now a single match on field.field_type.as_str() with "number" and "boolean" arms sharing one early-return/guard structure — not copy-pasted parallel functions. This is exactly the shared-dispatch shape the prior review asked for ("a shared coercion dispatch rather than copy-pasted parallel logic").

I independently verified the fix rather than taking the commit message at its word:

  • Test passes with the fix in place: cargo test -p nodespace-agent --lib resolve_query_coerces_stringified_boolean_to_match_boolean_field → 1 passed.
  • Isolated-revert check: I removed only the "boolean" => { ... } match arm (leaving "number" and everything else untouched) and reran the same test. It failed exactly as claimed: left: Bool(false), right: Bool(true) — the same no_match-shaped symptom this whole PR is about. Restored the code afterward; working tree is clean.
  • Doc comment updated accurately (tools.rs:227-237): now states the boolean drift explicitly and correctly narrows the "safe to skip" claim to text/enum/date, matching what the prior review asked for (don't overstate untested safety).
  • Case sensitivity: I checked Rust's str::parse::<bool>() behavior directly — it accepts only the exact lowercase literals "true"/"false"; "True", "TRUE", "1" all fail to parse. On failure, the code falls through and leaves the filter unchanged (same defensive "no worse than pre-fix" shape as the number path noted approvingly in the prior review) rather than panicking or silently corrupting data. This is a reasonable, low-risk scope boundary — the decomposition model already emits lowercase "true"/"false" per observed behavior — not a bug.
  • Out-of-scope types correctly left alone: text/enum/date still fall through the _ => {} arm, consistent with the (now-corrected) doc comment.

No regressions: full local_agent::tools module — 86 passed, 0 failed, 1 ignored (the live test, correctly ignore-gated). cargo build --tests and cargo clippy --tests are both clean (zero warnings). cargo fmt --check is clean.

Verdict: properly and correctly addressed.


Finding #2 — Live-model coverage breadth: Addressed, well-structured.

live_paraphrased_identifier_resolves_against_real_model was renamed to live_resolve_query_phrasings_against_real_model and now runs three scoped blocks in one model load (tools.rs:3762-3905):

  1. Paraphrased-identifier repro (the original bug, exercises the identify-vs-update-target prompt fix directly).
  2. Dollar-amount phrasing ("Mark the $500 invoice as paid") — no update-target ambiguity, tests that the prompt rewrite didn't regress a previously-working case.
  3. Relative-date phrasing ("Mark the invoice due next Friday as paid") — same purpose, different field type (date vs number).

Structurally sound: one engine load shared via Arc::clone, each block scoped with its own { } block and its own make_test_service()/schema/fixture, so the three assertions are independent and each carries its own descriptive failure message ("real model failed to resolve ... — got {}") — failure attribution per phrasing is clear, not a single opaque assert at the end. println! diagnostic output is present in all three blocks; acceptable per the prior review's own standard for #[ignore]-gated Rust test code.

This converts the previously-flagged single-witness test into a real (if manually-run) regression suite for the prompt's blast radius, addressing the prior review's explicit ask.

Verdict: properly addressed.


The "next Friday" test adjustment — independently assessed, not taken at face value

This is the part I scrutinized most carefully, per the task brief.

Is the ambiguity actually orthogonal to this PR's prompt fix? Yes, on inspection of the actual prompt text (tools.rs:1543-1568, unchanged by this commit). The fix's new machinery is entirely about distinguishing the identifying value from the update target state (worked example: "the 2400 one" identifies, "returned" is the update). The relative-date test phrase — "Mark the invoice due next Friday as paid" — has no such conflation risk: "due next Friday" is unambiguously the identifying clause, "paid" is unambiguously the update. The specific calendar reading of "next Friday" (this coming Friday vs. the Friday of the following week) is a separate, pre-existing NL-ambiguity question that has nothing to do with identify-vs-update-target parsing. I agree with the author's characterization here.

Does seeding both candidate dates create false-positive risk (test passes for the wrong reason)? I checked this directly rather than assuming — this is the one place a weakened assertion could quietly mask a real regression. I read exec_resolve_query's dispatch logic (tools.rs:1664-1683): the payload is resolved: true only when matches.len() == 1; zero matches yields no_match, more than one yields multiple_matches. With two invoices seeded at two distinct due_date values, resolved: true is achievable only if the decomposition model emits a date filter that discriminates down to exactly one of the two — i.e., it must actually resolve "next Friday" to a concrete date and filter on it correctly. If the model drops the date filter, uses a non-discriminating operator, or matches both dates (e.g., an open-ended gte catching both), the test correctly falls into multiple_matches → resolved: false → assertion failure. This is not a coin-flip pass; it requires genuine correct prompt-following on the date-filter mechanics, just agnostic to which of two defensible calendar readings the model produces. I consider this a legitimate, non-trivial regression test, not a weakening that papers over a bug.

One residual note, not a blocker: the prompt permits gt/lt/gte/lte in addition to equals for relative dates. A gte-style filter from "next Friday" onward would, in this two-invoice fixture, match both seeded dates (since the later one is also >= this_friday) and correctly produce multiple_matches rather than a false pass — so this doesn't undermine soundness, but it does mean a clean "resolved: true" here quietly assumes the model chose an equals-shaped filter rather than a range. That's fine as pass/fail signal; just worth knowing if this test ever needs re-diagnosis on failure.

Would a tighter test have been better? I considered the alternative — asserting resolved: false, reason: "multiple_matches" outright, or skip/document-only. I don't think either is actually better: multiple_matches would be testing "the model is ambiguous," which isn't what this test exists to verify (blast-radius coverage for the prompt rewrite), and would make the test pass in a state that's arguably worse (an ambiguous resolution that should ideally pick one). The chosen assertion — "resolved to a correctly-identified node" — is the right invariant for what this test is actually for. I'd call this a defensible engineering call, not scope creep.

Verdict: sound, not a masking maneuver. The commit message's framing ("pre-existing, not a regression... unrelated to the identify-vs-update-target prompt fix") holds up against the actual prompt and dispatch code, not just the stated claim.


New Issues Introduced by This Commit

None found. Specifically checked and clear:

  • No dead code, no unused imports (cargo build --tests clean).
  • No new lint suppressions, no #[allow(dead_code)], no #[deprecated] (cargo clippy --tests clean, zero warnings).
  • No stray console.log-equivalent in production code (all println!/eprintln! are inside #[ignore]-gated test code, an already-cleared exemption).
  • No issue-number references leaked into doc-comment prose (only in test doc-comments referencing the PR's own diagnosis, same convention already accepted in the prior commit).
  • cargo fmt --check clean — matches project formatting.
  • The s.parse::<f64>() number-path logic was mechanically refactored (nested if let collapsed to .ok().and_then(...)) to fit the new match dispatch — confirmed semantically identical, no behavior change.
  • No test flakiness risk beyond the analysis above; the live tests remain #[ignore]-gated and are not part of the pre-push gate, consistent with this repo's "no CI, live-model tests are opt-in" model.

Recommendation

APPROVE.

Both prior Important findings are properly and verifiably addressed — not just claimed. I independently reproduced the boolean-coercion regression via isolated revert (matching the same rigor the original PR itself was praised for), and traced the "next Friday" test-weakening decision through the actual dispatch code rather than accepting the author's framing, confirming it's a sound, non-masking design choice. No new issues introduced. Full local test suite green (86 passed, 1 ignored as expected), clean build/clippy/fmt.

@malibio

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review follow-up

Both Important findings from the initial reviews were addressed in commit 74d96d4d and confirmed by re-review (APPROVE, no new issues):

  1. Boolean coercion — coerce_filter_value_to_field_type generalized to also handle boolean fields, with a mocked regression test verified via isolated-revert to genuinely catch the defect.
  2. Live-test breadth — expanded to cover three phrasings (paraphrased-identifier, dollar-amount, relative-date) in one model load, confirming the prompt rewrite doesn't regress previously-working cases. Live-running this surfaced a real but pre-existing "next Friday" calendar-interpretation ambiguity, unrelated to this PR's fix — the test was adjusted to seed both candidate dates so it verifies prompt-following rather than asserting one specific calendar reading (independently verified sound by the re-reviewer, not just taken on the commit message's word).

The reviews additionally recommended filing a follow-up issue for the structural fix (JSON-schema-constrained decomposition output, to replace per-type coercion patching) and for the string→number reverse-direction case on text/enum fields. Filed as #1915 — intentionally out of scope for this PR per both reviews ("not a quick patch; a proper investigation" needing its own live-model validation).

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The follow-up commit was already re-reviewed (APPROVE) before this comment. No further code changes were made — only filing the tracked follow-up issue, which is documentation/process, not a code change requiring review.

PR is ready for merge (author's call).

@malibio
malibio merged commit e191c50 into main Aug 2, 2026
2 checks passed
@malibio
malibio deleted the issue-1908-resolve-query-nomatch branch August 2, 2026 04:12
malibio added a commit that referenced this pull request Aug 3, 2026
…ompt (closes #1915) (#1945)

The decomposition sub-prompt named a field's declared type (`name: type`)
but never told the model how to encode a value it maps onto that field,
so a small model reading digits or booleans out of prose could emit the
wrong JSON type — the exact silent-mismatch failure #1908/#1910 patched
per-type via coerce_filter_value_to_field_type. Per the issue's own
"cheaper to try first" proposal, add an explicit JSON-encoding hint
(number/boolean/text/enum) to each field line in exec_resolve_query's
prompt, scoped locally rather than to the shared render_shape() renderer
per the issue's scope decision. Live-model validation against the locked
Gemma 4 E4B model confirms the reverse-direction case (a numeric-looking
value identifying a text field) now resolves correctly.

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

resolve_query returns no_match against a node whose property does contain the queried value

1 participant