Skip to content

LLM-backed query decomposition + read-then-write turn completion before search_nodes/update_node - #1688

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1637-query-decomposition
Jul 18, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1637-query-decomposition

Conversation

@malibio

@malibio malibio commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1637

Summary

E4B reliably failed "Mark the $500 invoice as paid": it hand-wrote a multi-word search_nodes query ("$500 invoice due next Friday") that title-matching (SQL LIKE, whole-string substring) never found against the actual title "Invoice for $500 due next Friday" — and even a successful search could be followed by the model stopping before the matching update_node call.

Half A — query decomposition: adds resolve_query, a new agent tool whose handler makes its own scoped nested inference call (mirrors the existing single-shot pattern in agent_loop::maybe_summarize_history). It looks up the target type's real schema fields via NodeService::get_schema_node (deterministic, not the semantically-truncated schema summary in the main prompt), asks a narrow prompt to resolve ambiguous values (amounts, relative dates, paraphrased identifiers) against those fields, and returns ready-to-use search_nodes query/filters. GraphToolExecutor gains a SharedChatInferenceEngine handle (same shared-RwLock pattern as SharedEmbeddingService), wired at both replace_engine call sites in local_agent_service.rs.

agent_guidance.rs replaces the "ONE WORD ONLY" query-phrasing workaround (documented in the issue as verified ineffective — the model produced the same wrong query regardless of prompt wording) with an instruction to call resolve_query first for ambiguous update targets.

Half B — read-then-write completion: adds a rule that a successful search for a write instruction must continue to update_node/update_task_status in the same turn, not stop.

Follow-up fix (found via live eval): resolve_query returning filters-only output sometimes led the model to omit query entirely from the follow-up search_nodes call — which used to hard-error since query was a required field. Fixed by defaulting query to "" (matching its existing "skip title filter" semantics) and updating the JSON schema + 3 tests accordingly.

Verification

  • 9 new Rust unit tests for resolve_query: tool registration, schema validation, param parsing, and a real-schema + stub-engine integration test exercising the full path (schema lookup → prompt construction → nested generate() call → JSON parsing with prose/markdown-fence tolerance → empty-result fallback on unparseable output).
  • 3 updated tests for the search_nodes query-optional relaxation.
  • 2 new tests for the read-then-write / resolve_query guidance rules in agent_guidance.rs.
  • Live aichat-matrix run against gemma-4-e4b-q4km: 12/12 scenarios passing, up from the 11/12 baseline (PR Collapse execute_query into search_nodes as one agent query tool (closes #1640) #1687). Scenario 6 now calls resolve_query → search_nodes → update_node — confirming both halves of this issue land together, with no regression on the other 11 scenarios.
  • bun run test:all and bun run quality:fix clean.

Notes

  • The live matrix run needed a machine with enough free RAM for E4B's context window to not get memory-fit-floored (nlp-engine's compute_effective_n_ctx) — unrelated to this change, just a precondition for running the eval itself.

malibio and others added 2 commits July 18, 2026 02:28
…ule (closes #1637)

E4B reliably fails "Mark the $500 invoice as paid": it hand-writes a
multi-word search_nodes query ("$500 invoice due next Friday") that
title-matching (SQL LIKE, whole-string substring) never finds against
the actual title "Invoice for $500 due next Friday" — and even a
successful search can be followed by the model stopping before the
matching update_node call.

Adds resolve_query, a new agent tool whose handler makes its own scoped
nested inference call (mirrors the existing single-shot pattern in
agent_loop::maybe_summarize_history): it looks up the target type's
real schema fields via NodeService::get_schema_node (deterministic, not
the semantically-truncated schema summary in the main prompt), asks a
narrow prompt to resolve ambiguous values (amounts, relative dates,
paraphrased identifiers) against those fields, and returns ready-to-use
search_nodes query/filters. GraphToolExecutor gains a
SharedChatInferenceEngine handle (same shared-RwLock pattern as
SharedEmbeddingService) wired at both replace_engine call sites in
local_agent_service.rs.

agent_guidance.rs: replaces the "ONE WORD ONLY" query-phrasing
workaround (documented in the issue as verified ineffective — the
model produced the same wrong query regardless of prompt wording) with
an instruction to call resolve_query first for ambiguous update
targets. Also adds a read-then-write turn-completion rule: a
successful search for a write instruction must continue to
update_node/update_task_status in the same turn, not stop.

Verified via 9 new Rust unit tests, including a real-schema +
stub-engine integration test exercising the full resolve_query path
(schema lookup, prompt construction, nested generate() call, JSON
parsing with prose/markdown-fence tolerance, empty-result fallback on
unparseable output). Live aichat-matrix run against gemma-4-e4b-q4km
could not be completed in this environment: even after freeing two
other long-running sessions, available memory stayed too low for
sysinfo's memory-fit to grant more than the 4096-token floor, short of
the ~6600 tokens the 14-tool prompt needs — a pre-existing environment
constraint, not something this change introduces. Re-running the
matrix on a less memory-constrained machine is a follow-up.

Co-Authored-By: Claude <[email protected]>
Discovered via a substitute Gemma 4 E2B smoke-test of resolve_query
(the actual target model, E4B, requires more context than this
machine's available memory could grant): after resolve_query resolved
"Mark the $500 invoice as paid" into filters-only output, the model
built a follow-up search_nodes call with filters but no query field at
all — search_nodes required query, so the call hard-errored with
"missing field `query`" instead of finding the invoice.

query="" already means "skip the title filter" per its own
documentation; there's no reason a filters-only call must also
remember to echo back an empty string for it. Defaults
SearchNodesParams.query via #[serde(default)] and drops "query" from
the tool's JSON schema `required` list. Updates the three tests that
asserted the old hard-required behavior to assert the new default
instead.

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

malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review

This PR adds resolve_query, a nested-LLM-call agent tool that decomposes ambiguous natural-language update targets (e.g. "the $500 invoice") into structured search_nodes query/filters before the main tool-calling turn, plus a "read-then-write turn completion" guidance rule, plus a follow-up fix relaxing SearchNodesParams.query to optional. The design is sound and well-scoped: it mirrors the existing agent_loop::maybe_summarize_history nested-inference-call precedent, reuses the SharedEmbeddingService RwLock pattern for the new inference_engine handle, and reuses the existing, already-injection-safe filter → QueryService → parameterized-json_extract pipeline rather than inventing a new one. The two commits are cleanly atomic — the first lands the full feature, the second is a narrowly-scoped, credibly-motivated bugfix touching only the two files it needed to. This is a net positive change. One doc-comment/architecture-clarity issue on the new shared-engine handle is worth fixing before merge; everything else is a nit or a note for future iteration.

Requirements Check

Original scope (issue #1637, Half A):

  • ✅ Decision made and executed: pursued the decomposition step (resolve_query), abandoning the previously-documented-ineffective "ONE WORD ONLY" prompt workaround.
  • 🟡 "Prototype... and confirm it resolves reliably" — confirmed only via the human-reported, unverifiable-from-diff live aichat-matrix run (12/12, Scenario 6 passing). The 9 new unit tests verify the plumbing (schema lookup → prompt → parse → fallback) with a stub engine, not that a real E4B model reliably produces usable JSON. This is inherent to the nature of the criterion (model behavior can't be unit-tested), not a gap in this PR's own test suite.
  • ✅ Structured handoff documented: resolve_query's output ({query, filters}) is explicitly shaped to be passed directly into search_nodes's own parameters — not a re-worded prompt. Guidance text in agent_guidance.rs makes this handoff explicit ("pass its returned 'query' and 'filters' directly into search_nodes").
  • 🟡 "Verify no regression to single-pass cases" — the guidance text explicitly scopes resolve_query to ambiguous cases ("Skip resolve_query only when the identifier is already simple and unambiguous... call search_nodes directly"), and the human-reported matrix run claims no regression to the other 11 scenarios. Not independently verifiable from the diff; flagged as unfalsifiable per the review brief.

Half B (read-then-write):

  • ✅ New READ-THEN-WRITE TURN COMPLETION rule added to TOOL_STRATEGY_RULES, explicitly framing search-then-stop as a "FAILED turn." Covered by two new agent_guidance.rs tests asserting the rule's presence and the old ineffective instruction's removal.
  • 🟡 "aichat-matrix Scenario 6 passes... 12/12" — human-reported only, not independently verifiable.

Overall: the acceptance criteria that are code/architecture questions are fully met; the criteria that are empirical model-behavior claims rest on an unverifiable (from this review's vantage point) live eval report. That's a reasonable trust boundary given the task description explicitly calls this out as evaluated at face value.

Code Review Findings

🟡 Important: SharedChatInferenceEngine doc comments claim live-swap semantics the code doesn't implement

📁 packages/agent/src/local_agent/tools.rs:32-40 (type alias doc), :954-958 (struct field doc)
📁 packages/daemon/src/services/local_agent_service.rs:171-176 (replace_engine comment)

The doc comments explicitly claim this type "Mirrors SharedEmbeddingService's pattern: the daemon swaps the active engine... by writing through this handle, so the executor always reads the current engine rather than one captured at construction time" — and the replace_engine comment says the handle "needs the SAME engine this turn's main model uses, so its nested decomposition call swaps in lockstep with the active model."

That's not what the code does. Unlike embedding_service, which is a genuinely long-lived Arc<RwLock<...>> stored once in LocalAgentServiceInner and cloned so all executors share the same lock (and a background loader task later writes into that same lock via .write()), inference_engine is re-constructed fresh at every call site:

inference_engine: Arc::new(RwLock::new(Some(engine.clone()))),  // build_noop_service, line 155
inference_engine: Arc::new(RwLock::new(Some(engine.clone()))),  // replace_engine, line 179

Nothing in the codebase ever calls .write() on an existing inference_engine lock to update its contents in place — every engine change instead swaps the entire GraphToolExecutor (and the whole LocalAgentService) for a new one via self.inner.service's outer RwLock. Functionally this is harmless today (each swap rebuilds the executor from scratch anyway, so the fresh inner lock always holds the current engine at the moment it's needed), but the abstraction is misleading: a future maintainer reading these comments would reasonably conclude they can mutate the engine in-place through a stored inference_engine clone and have it "swap in lockstep," which is not true — only the embedding_service field has that property.

Recommendation: Either (a) simplify inference_engine to a plain Arc<dyn ChatInferenceEngine> (no RwLock) since it's always seeded once per executor construction and never mutated in place, removing the misleading "shared, live-swapped" framing entirely, or (b) if a future change genuinely needs live in-place swapping (e.g. to avoid rebuilding the executor on every model switch), make LocalAgentServiceInner own one persistent SharedChatInferenceEngine and have both build_noop_service and replace_engine write through it, matching embedding_service's actual pattern. As-is, the code and its own documentation describe two different designs.

Engineering principle: Documentation that describes an aspirational or superficially-similar-looking design rather than the actual code creates a hazard for the next reader — "self-documenting mismatches" are worse than no comment at all, since they actively mislead rather than leave a gap.

🟢 Suggestion: resolve_query_without_inference_engine_returns_error doesn't isolate its named failure mode

📁 packages/agent/src/local_agent/tools.rs:2244-2252

async fn resolve_query_without_inference_engine_returns_error() {
    let executor = test_executor();  // node_service: None, inference_engine: None
    ...
    assert!(result.is_err(), "resolve_query must fail without a node service/engine");
}

test_executor() sets both node_service and inference_engine to None/empty, and exec_resolve_query checks node_service()? before inference_engine()?. This test therefore verifies "fails when something is missing," not specifically "fails without an inference engine" as its name claims — it would pass identically even if the inference-engine check were deleted entirely, because the node-service check fires first.

Recommendation: Add a variant with a real (in-memory) node_service and inference_engine: None to isolate the inference-engine-missing path specifically, or rename the test to reflect what it actually asserts (both note the test's own docstring already hints at this ambiguity).

Engineering principle: A test's name is a contract with future readers about what regression it guards against; a test that can't fail for the reason its name implies gives false confidence when refactoring the code path it doesn't actually isolate.

🟢 Nit: prompt-injection surface is real but well-contained — worth a one-line comment

📁 packages/agent/src/local_agent/tools.rs:1121-1145

params.request (raw, unescaped user text) and schema field names/labels are interpolated directly into the nested-LLM prompt via format!. This is a real prompt-injection surface — a sufficiently adversarial user request could try to steer the nested call's output. I verified the blast radius is contained as the PR intends: the nested call's output only ever becomes search_nodes query/filters arguments, which flow through the pre-existing to_query_filter → QueryFilter → QueryService path. Property names are validated against [A-Za-z0-9_:-] via validate_identifier (packages/core/src/ops/query_ops.rs) and values are passed as bound serde_json::Values into json_extract conditions — never string-concatenated into SQL. So even a fully "hijacked" resolve_query response can, at worst, cause a weird/incorrect search or a rejected filter — not injection. Given how easy it'd be for a future refactor to change how filters are consumed downstream, a one-line comment at the resolve_query prompt-construction site noting "output is trusted only as far as search_nodes filter arguments — do not let it reach raw SQL/eval'd code without re-reviewing this containment" would pay for itself later.

🟢 Nit: SearchNodesParams.query relaxation is correctly scoped

📁 packages/core/src/agent_params.rs:16-23, packages/agent/src/local_agent/tools.rs:340

Confirmed via grep that SearchNodesParams has exactly one production consumer (exec_search_nodes in tools.rs), and that function already special-cased params.query.is_empty() in both the title-listing and typed-property branches before this PR (empty string meant "skip title filter"). The only behavior change is that the field can now be omitted entirely and default to the same already-handled empty case — no new code path, no embedding/empty-string search risk (this only affects search_nodes; search_semantic's own SearchSemanticParams.query is untouched and still required). The commit's stated justification (found via live testing, not designed upfront) is credible: resolve_query's filters-only output is a new call shape that didn't exist before this PR, so the gap plausibly wasn't visible until this PR's own new code exercised it.

🟢 Nit: NoOpInferenceEngine wiring correctly fails closed

📁 packages/daemon/src/services/local_agent_service.rs:147-156, packages/agent/src/local_agent/tools.rs:1100,1163-1167

Confirmed build_noop_service wires a NoOpInferenceEngine (whose generate() always returns Err(InferenceError::NoModelLoaded)) into inference_engine, and exec_resolve_query's engine.generate(...).await.map_err(...)? propagates that as a hard ToolError::ExecutionFailed rather than silently returning an empty/useless resolution. This is the correct behavior — no risk of resolve_query "silently succeeding" with a useless engine in the no-model-loaded state; it fails loudly instead, consistent with how a real caller (main ReAct loop) would already be unable to run at all without a loaded model.

Recommendation

APPROVE

The one 🟡 finding (misleading doc comments on SharedChatInferenceEngine) is a clarity/documentation issue, not a functional defect — the code behaves safely today, it just doesn't behave the way its own comments claim it does. It's worth fixing (either simplify the type or make the sharing real) but doesn't block merge given "net positive > perfection" and the absence of any actual correctness, security, or regression risk found. Commit scoping is clean, the new tool reuses existing safe containment (filter validation, parameterized queries) rather than introducing a new attack surface, the query-optional relaxation is narrowly scoped and low-risk, and the guidance-text changes are well-tested for their own presence/absence. Recommend addressing the doc-comment mismatch in a fast follow-up (or this PR, if cheap) before it misleads someone extending this code later.

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

Review recommendation: APPROVE (see full review above). Note: could not submit a formal --approve review — GitHub blocks self-approval since the PR author and this gh session are the same account (malibio).

…, isolate a test's failure path

Reviewer found two issues in PR #1688:

1. (Important) SharedChatInferenceEngine's doc comments claimed it mirrors
   SharedEmbeddingService's live-swap semantics (updated in place via a
   shared lock as a background loader finishes). It doesn't: both
   construction sites (build_noop_service, replace_engine) build a brand
   new Arc<RwLock<..>> every time rather than writing into an existing
   one, because the daemon already rebuilds the whole GraphToolExecutor
   on every model load/switch. The lock was doing nothing but adding a
   misleading doc comment and an unnecessary .await. Simplified the type
   to a plain Option<Arc<dyn ChatInferenceEngine>> and fixed the comments
   at both construction sites to describe what's actually true.

2. (Suggestion) resolve_query_without_inference_engine_returns_error used
   test_executor(), which has node_service: None too — since
   exec_resolve_query checks node_service()? first, the test couldn't
   fail for the reason its name claimed. Moved it into the
   resolve_query_integration submodule with a real node_service (reusing
   the existing make_test_service fixture) and inference_engine: None,
   isolating the intended failure path.

Skipped: a suggested one-line comment on the injection-containment of
resolve_query's prompt interpolation — folded that note into the
SharedChatInferenceEngine doc comment instead of adding a separate one,
since I was already touching that block.

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

malibio commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

✅ Addressed (2/2 non-verification findings):

  1. [Important] SharedChatInferenceEngine doc comments claimed live-swap semantics the code didn't implement. Fixed by dropping the unnecessary RwLock — the type is now a plain Option<Arc<dyn ChatInferenceEngine>>, since the daemon already rebuilds the whole GraphToolExecutor (with a fresh engine) on every model load/switch; there was never a "write into an existing lock later" path to support. Doc comments at both construction sites (build_noop_service, replace_engine) and the field/type declarations now describe what's actually true.

  2. [Suggestion] resolve_query_without_inference_engine_returns_error used test_executor(), which also has node_service: None — so it couldn't isolate the failure it claimed to test (node_service is checked first in exec_resolve_query). Moved it into the resolve_query_integration submodule with a real node_service (reusing the existing make_test_service fixture) and inference_engine: None, so it now genuinely isolates the intended path.

⏭️ Folded in rather than separately addressed: the suggested one-line comment on resolve_query's prompt-injection containment — added it to the SharedChatInferenceEngine doc comment instead of as a standalone comment, since that block was already being rewritten.

Verification: cargo build/test clean on both nodespace-agent and nodespace-daemon (299 + 76 tests passing), bun run quality:fix clean, full pre-push gate (test:all + cargo build --bin nodespaced + e2e suite) passed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: Both changes are narrow, low-risk simplifications directly matching the reviewer's own suggested fix (drop the RwLock since it's write-once per executor) and test-isolation nit. No new functionality, no architectural changes, no behavior change to resolve_query itself — only its internal storage type and a test's fixture. All existing tests pass unchanged in behavior; one test was relocated and its assertion updated to match its own stated intent.

@malibio
malibio merged commit 81847a3 into main Jul 18, 2026
@malibio
malibio deleted the worktree-issue-1637-query-decomposition branch July 18, 2026 02:38
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 must return a resolved node, not query fragments

1 participant