Skip to content

Honour sorting on a filterless search (closes #2249) - #2252

Merged
malibio merged 3 commits into
mainfrom
issue-2249-sorting-filterless-search
Aug 23, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-2249-sorting-filterless-search

Conversation

@malibio

@malibio malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator

Summary

search_nodes accepted a sorting argument and silently dropped it whenever filters was empty — returning an arbitrary row while reporting success. A model answering "which is the longest-running one?" via sorting + limit: 1 was handed the wrong node with no error to notice.

run_node_query branched on filters.is_empty() alone:

  • filters empty → node_ops::query_nodes, whose QueryNodesInput has no sorting field at all.
  • filters non-empty → query_ops::execute_query, which honours sorting.

So the same logical request behaved differently depending on whether an unrelated filter happened to be present.

Fix

Direction 2 from the issue: route on the presence of sorting as well, so a sorted request reaches execute_query regardless of filters.

let sorted = sorting.as_ref().is_some_and(|s| !s.is_empty());
let output = if filters.is_empty() && !sorted { /* query_nodes */ } else { /* execute_query */ };

Direction 1 (plumbing sorting into QueryNodesInput) was considered and rejected as materially larger: NodeFilter/NodeQuery have no ordering support today, so it would push ORDER BY down through the store layer.

Behavior change, scoped

Unsorted filterless searches are untouched — they keep the query_nodes title-keyword path. The one shifted shape is a sorted search carrying a keyword: on the QueryService path the keyword becomes a content filter rather than a title filter, since QueryService has no title path. For nodes created through create_node the two coincide (title is derived from content), so the keyword still narrows. a_sorted_search_still_narrows_by_keyword pins exactly that, because a keyword that quietly stopped matching would trade one silent-wrong-answer bug for another.

Tests

  • filterless_search_silently_ignores_sorting → filterless_search_honours_sorting. The deliberate bug pin now asserts the correct 21-day result.
  • scenario_12_sorted_single_result_route_is_also_accepted: compensating gt 0 filter removed, as the issue asked. It passes on the plain phrasing now.
  • a_sorted_search_still_narrows_by_keyword: new, covering the shifted keyword+sorting shape.

All three were verified to fail with the fix reverted and pass with it, so none is vacuous.

bun run test:all clean (frontend 227 files / 4794 tests, matching baseline; no Rust failures). bun run quality:fix clean — clippy passes under -D warnings, no stray reformatting. Full pre-push gate passed.

🤖 Generated with Claude Code

https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG

`run_node_query` branched on `filters.is_empty()` alone. The filterless
branch calls `node_ops::query_nodes`, whose input struct has no sorting
field, so `sorting` was parsed, accepted, and dropped — the call returned
an arbitrary row and reported success. A model answering "which is the
longest-running one?" via `sorting` + `limit: 1` was handed the wrong
node with nothing to notice.

Route on the presence of `sorting` as well, so a sorted request reaches
`query_ops::execute_query`, which honours it. Unsorted filterless
searches keep their title-keyword path unchanged; only a sorted call
shifts to matching content instead of title, and `a_sorted_search_still_
narrows_by_keyword` pins that the keyword still narrows there.

Flips the deliberate `filterless_search_silently_ignores_sorting` pin to
a regression test and drops the compensating `gt 0` filter from
`scenario_12_sorted_single_result_route_is_also_accepted`. All three
sorting tests were verified to fail with the fix reverted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG
@malibio

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2252

Review Type: Initial Review


Requirements Check

Against issue #2249:

Ask Status
Fix: sorting no longer silently dropped on a filterless search ✅ Verified — direction 2 implemented, measured working
"Update that test to assert the correct (21-day) result" ✅ filterless_search_silently_ignores_sorting → filterless_search_honours_sorting, asserts large and not small
"Remove the compensating filters argument from scenario_12_sorted_single_result_route_is_also_accepted" ✅ gt 0 predicate removed; test passes on the plain phrasing
Rejected alternatives documented ✅ PR explains why direction 1 (plumbing sorting into QueryNodesInput) was declined

Both explicit asks are done, and the core bug is genuinely fixed. The three tests are non-vacuous — I confirmed the discriminating shape of each.


Code Review Summary

The routing change is correct, minimal, and the right call. let sorted = sorting.as_ref().is_some_and(|s| !s.is_empty()) is exactly the predicate the problem calls for, and declining direction 1 (pushing ORDER BY through NodeFilter/NodeQuery) is well-reasoned — that would be a far larger change for the same user-visible outcome. Net code health is clearly improved.

However, the PR makes one specific empirical claim that I measured and found to be false in general, and it is the exact claim the PR itself identifies as the thing that must hold:

"For nodes created through create_node the two coincide (title is derived from content), so the keyword still narrows."

Title is not derived from content when the node's schema defines a title_template — compute_title (packages/core/src/services/node_service/crud.rs:2013-2072) checks schema.title_template first and only falls through to strip_markdown(&node.content) when there is none. create_schema accepts title_template as a first-class field, and the agent's own tool description at tools.rs:1138 actively instructs the model to use it. So a create_node-created node with a templated title is an ordinary, reachable case, not an exotic one.

I ran this against a live SqliteStore + NodeService + GraphToolExecutor using the PR's own harness. Three findings below are measured, not inferred.


Code Review Findings

🔴 Critical

📁 packages/agent/src/local_agent/tools.rs:1994-2001, 2028-2034 — the shifted keyword shape silently returns ZERO results for any type with a title_template

The PR's stated safety property does not hold. Measured, with a schema carrying title_template: "{vname} hall" and three nodes whose content is "body text unrelated" and whose titles are payments hall, payments hall, indexer hall:

UNSORTED (title path):  count: 2   ← both "payments hall" nodes
SORTED   (content path): count: 0   ← nothing

Adding a sorting argument to a working keyword search turned 2 results into 0. This is not a narrower or a broader match — it is a total loss of the result set, and it reports success with count: 0. Per exec_search_nodes's own comment at tools.rs:2113-2118, a zero-result type-scoped search is "the one outcome the model cannot read" — the model is told the workspace genuinely has no match.

The converse also reproduces. With title_template: "WU-{estimated_days}" and content "payments retry" / "payments ledger" / "search indexer":

UNSORTED (title path):   count: 0
SORTED   (content path): count: 2   ← payments ledger, payments retry

So the same query: "payments" returns either 0 or 2 depending purely on whether an unrelated sorting argument is present. That is precisely the class of defect #2249 was filed about — "the same logical request behaves differently depending on whether an unrelated argument happens to be present" — reintroduced on the other axis, and the issue's own framing ("a loud error beats a wrong answer") applies with equal force here.

This is not hypothetical distance from the test: a_sorted_search_still_narrows_by_keyword creates its schema without a title_template, which is the one configuration in which the claim holds. The test passes because it tests the safe case.

Principle: the Principle of Least Astonishment, and correctness over silent degradation. A fix that trades a wrong-row bug for a zero-rows bug on an adjacent input has moved the failure, not removed it — and a count: 0 that means "your keyword was reinterpreted" is strictly harder for the caller to recover from than a wrong row, because nothing in the result distinguishes it from a genuinely empty workspace.

Suggested resolutions, in order of preference:

  1. Give QueryService a title path. FilterType (query_service/mod.rs:69) has Property | Content | Relationship | Metadata; title is a real indexed column on node, and build_metadata_filter already whitelists direct columns. Adding title to that whitelist (or a FilterType::Title) makes both branches mean the same thing by construction and deletes the divergence rather than documenting it. This looks like a genuinely small change and is the only option that makes the routing decision fully transparent, which is what run_node_query's doc comment already promises ("Routing is by capability, transparent to the model").
  2. Send both predicates — push the keyword as a title filter once (1) exists, keeping content as an OR. More faithful to the tool's advertised semantics ("Keyword or phrase to match against node titles").
  3. At minimum, do not silently swap semantics. If the divergence stays, the sorted-keyword case should be detectable by the caller — either reject the combination with a message naming the reason, or annotate the result. A silent reinterpretation is the one option the issue explicitly ruled out.

🟡 Important

📁 packages/agent/src/local_agent/tools.rs:2039-2045 — a typeless sorted search (target_type: "*") is not well-defined, and the fix newly routes calls there

node_type is optional on search_nodes ("Omit to search all types"), so search_nodes({query: "*", sorting: [...], limit: 3}) is a legal call that previously went to query_nodes and now reaches execute_query with target_type: "*". In that branch resolve_field (query_service/mod.rs:347-351) emits json_extract(properties, '$.estimated_days'), but properties are stored namespaced as $.<node_type>.<field> — so the SQL ORDER BY key is NULL for every row.

The consequence is not merely "unsorted". SQL applies LIMIT after that meaningless ORDER BY, and the Rust re-sort in execute (mod.rs:190-193, which does use the correct namespaced path via compare_nodes_by_field) runs only over what survived the truncation. Measured with three user nodes (4, 9, 21 days) in a fresh DB:

limit: 3  → schema nodes only ("Task", "Project", "Text") — the user's nodes never appear
limit: 50 → correct: 21, 9, 4 first

So a typeless superlative query at a small limit returns internal schema registry rows, sorted meaninglessly, reported as success. This is the same silent-wrong-answer family as the original bug, at a shape the fix newly makes reachable, and none of the three tests covers it — every one passes node_type.

Two things worth separating here:

  • The resolve_field / build_property_filter wildcard branch looks like a standing pre-existing defect in QueryService (it ignores the namespacing the rest of the file assumes) — reasonably out of scope to fix here.
  • But routing new traffic onto it is in scope. At minimum, keep node_type: None + sorting on the old path, or add a test that pins whatever the intended behavior is. Right now the behavior is neither chosen nor covered.

Principle: don't widen the blast radius of a known-broken code path. YAGNI cuts the other way too — if typeless sorting isn't meant to work, say so explicitly rather than leaving it silently reachable.

📁 packages/agent/src/local_agent/tools.rs:2028-2034 — the doc comment now states the divergence but frames it as settled

"matching on content rather than title is a real difference, and it is worth paying only to make the requested ordering actually happen."

This is honest about the trade and I appreciate that it's called out rather than buried. But given the Critical above, the cost is understated — the comment reads as "slightly different matching", where the measured behavior is "0 results instead of 2". If the divergence survives review, the comment should name the concrete failure (templated titles) so the next reader doesn't have to rediscover it. Also, run_node_query's own doc comment (tools.rs:1961-1967) still describes routing as purely "No property filters → …" and hasn't been updated for the new sorted term — it's now inaccurate at the top of the very function that changed.

Principle: comments should explain the "why" AND remain accurate; a stale routing summary directly above a changed routing decision is worse than no summary.


🟢 Suggestions

📁 packages/agent/tests/matrix_scenario_winnability.rs:672-742 — a_sorted_search_still_narrows_by_keyword tests only the safe configuration

The test is well-constructed for what it covers — the largest node deliberately doesn't match the keyword, so "narrowed then sorted" and "sorted, keyword ignored" are genuinely distinguishable, and the failure message correctly enumerates all three outcomes. The assertion substrings ("payments ledger", "search indexer") are specific enough not to collide with ids or schema names, and filterless_search_honours_sorting's !text.contains("small") guard is load-bearing at limit: 1. No vacuous assertions.

The gap is coverage, not quality: the schema it creates has no title_template, which is exactly the configuration where the property under test holds. Adding a sibling case with a title_template would have caught the Critical. Worth adding whichever way the Critical is resolved — as a passing test of the fixed behavior, or as a pinned characterization if the divergence is accepted.

📁 packages/core/src/services/query_service/mod.rs:206, 246-249 — NULL sort ordering is defensible but undocumented

Sorting on a property absent from some rows puts those rows first on asc and last on desc (compare_json_values maps None < Some). Measured: with a third node lacking estimated_days, desc, limit: 1 correctly returns the 21-day node; asc, limit: 1 returns the field-less node. That's SQL-NULLS-FIRST-like and reasonable, so no silent-wrong-answer here — but it's now reachable from a much more common call shape than before. Nit: worth a line in the tool description, since a model asking for "the smallest" will get a node with no value at all.

Sorting on a genuinely nonexistent field is benign — measured as returning all rows in insertion order, no error, no truncation surprise. Fine as-is.

📁 packages/agent/src/local_agent/tools.rs:1997 — Some(vec![]) treated as unsorted

is_some_and(|s| !s.is_empty()) is the right call. QueryService::build_query (mod.rs:310-311) and sort_nodes (mod.rs:201-203) both already no-op on an empty sorting vec, so Some(vec![]) is genuinely indistinguishable from None downstream — routing it to the cheaper title path is consistent, not a shortcut. Verified: an empty sorting: [] array returns the same order as omitting it entirely. No change needed.

Limit semantics — no user-visible divergence found. run_node_query passes None for collection/collection_id, so query_nodes' in-memory collection pagination branch is unreachable from here; both paths take an explicit limit (defaulted once, upstream, to DEFAULT_SEARCH_LIMIT), so neither internal default (query_nodes' 100, execute_query_nodes' 50) is ever hit. The only ordering difference on the unsorted path is OrderBy::CreatedDesc vs. unspecified, which is by definition what a sorted call is overriding. Good.

CLAUDE.md compliance — clean. No lint suppression, no #[allow(...)], no dead code, no backward-compat shims, no deprecation. The doc-comment rewrites correctly strip the #2249 reference from the test comments per the no-issue-refs-in-code rule, and the removed bug-pin prose is deleted rather than commented out. resolve_query passes sorting: None so it is provably unaffected by the routing change.


Recommendation

REQUEST CHANGES

The routing fix is right and I'd merge it happily on its own. The blocker is narrow and specific: the PR rests on a stated safety property — "for nodes created through create_node the two coincide" — that is false whenever the schema defines a title_template, and the one test written to pin that property uses a schema without one. Measured, the sorted path returns 0 results where the unsorted path returns 2 on that input, and the reverse on another.

That's a real regression on a reachable shape, in the same silent-wrong-answer family the issue was filed to eliminate. Adding a title path to QueryService looks like the small change that removes the divergence outright rather than documenting it, and would let the fix stand without the caveat.

The target_type: "*" finding (🟡) should at least be pinned by a test or explicitly excluded from the new routing, even if the underlying QueryService wildcard-namespacing defect is deferred to its own issue.


Findings marked "measured" were reproduced against a live SqliteStore + NodeService + GraphToolExecutor using this PR's own make_executor() harness. Probe code was run in a scratch copy and not committed; the worktree is clean.

@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: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

…rt key

The first commit's safety claim was wrong. It asserted that title and
content coincide for `create_node`-created nodes, so routing a sorted
search to QueryService (which matched content) was harmless. A schema
carrying a `title_template` builds the title from properties instead —
`compute_title` checks the template first and only falls back to
`strip_markdown(content)` when there is none.

Measured: same `query: "payments"`, `count: 2` unsorted and `count: 0`
sorted. Adding `sorting` silently dropped both real matches while
reporting success — the dropped-`sorting` bug traded for a
dropped-keyword one. The test written to pin that shift passed only
because it built its schema WITHOUT a template, the one shape where the
claim holds.

Fixed at the source rather than documented: `title` is a real indexed
column, so QueryService now accepts it as a metadata field (whitelist,
`resolve_field`, and the in-Rust re-sort comparator), and
`run_node_query` sends its keyword as a title filter. Both paths now
select on title, so which backend runs cannot change what a keyword
means. `query_ops::category()` routes a bare `property: "title"` to
metadata for the same reason `content` is already special-cased —
otherwise it builds an always-NULL `json_extract`.

Also fixes the wildcard sort key the routing change made reachable. With
`target_type: "*"` the properties namespace differs per row, so a fixed
`$.<field>` path was NULL for every row; SQL ordered and limited on that
NULL before the in-Rust re-sort could see anything. Measured at
`limit: 3`: three schema-registry rows instead of the seeded data,
reported as success. Now resolved per row via `'$.' || node_type || …`,
in both the ORDER BY and the property filter. `build_property_filter`
deliberately does NOT reuse `resolve_field` — its metadata shortcut
would make a user field named `title` query the column instead.

Tests: the keyword test is rebuilt on a templated schema (the fixture
that discriminates) and verified to fail when the filter is switched
back to content; a new typeless-sorted test covers the wildcard case at
a limit small enough to expose it. All 11 winnability tests pass, core
is clean at 1178 + integration, test:all matches baseline.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG
@malibio

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback — commit 42df6ba

All three findings addressed. The 🔴 was confirmed independently before implementing, not taken on faith.

🔴 Critical — title/content divergence: fixed at the source

Reproduced exactly as reported. With title_template: "{vname} hall" and content sharing no word with the title:

UNSORTED count = 2
SORTED   count = 0

The reviewer is right and my PR description was wrong. compute_title (crud.rs:2013) checks schema.title_template first and only falls back to strip_markdown(content) when absent — so title is not derived from content for templated types. Worse than stated, even untemplated types only fall back to content for task/collection or root nodes; a non-root node of another type gets title: None.

Took the reviewer's preferred direction — give QueryService a title path — rather than documenting the divergence:

  • build_metadata_filter whitelist and resolve_field accept title (a real indexed TEXT column)
  • compare_nodes_by_field gains title, so the in-Rust re-sort agrees with the SQL ORDER BY
  • run_node_query sends its keyword as a title filter, matching the query_nodes branch
  • query_ops::category() routes a bare property: "title" to metadata, for the same reason content is already special-cased — otherwise it builds a structurally-always-NULL json_extract

Now UNSORTED = 2, SORTED = 2. Both paths select on title, so which backend runs cannot change what a keyword means.

The test was rebuilt on the fixture that discriminates. a_keyword_means_the_same_sorted_or_not_under_a_title_template uses a templated schema and asserts unsorted and sorted counts match. Verified to fail when the filter is switched back to content — the old test passed either way, which is exactly why it missed this.

🟡 Important — typeless sorted search: fixed, not just documented

Confirmed and worse than a latent concern — my change made it reachable:

before  limit=3  => ["", "", ""]          (schema-registry rows)
before  limit=50 => ["large","mid","small", ...]
after   limit=3  => ["large","mid","small"]

Under target_type: "*" the properties namespace differs per row, so the fixed $.<field> path is NULL for every row; SQL orders and limits on that NULL before the in-Rust re-sort sees anything. Resolved per row via '$.' || node_type || '.<field>' in both the ORDER BY and the property filter.

build_property_filter deliberately does not reuse resolve_field: its metadata shortcut would make a user field named title silently query the column instead. Kept explicit with a comment.

New test a_typeless_sorted_search_orders_by_the_property pins it at limit: 3 — a limit large enough to admit every row hides the bug, since the re-sort then repairs the order after the fact.

🟢 Suggestions

  • Stale doc comment — fixed. run_node_query's header claimed "the title index is the only path that filters by title", which my change made false. Rewritten to state the actual routing rule and the shared title semantics.
  • sorted predicate, limit semantics — confirmed correct by the reviewer's own verification; no change.
  • NULL sort ordering — not changed. None < Some is defensible and the wildcard fix removes the reachable failure; documenting ordering semantics is a separate concern from this bug.

Verification

  • 11/11 winnability tests pass; both new tests verified to fail against the unfixed code
  • cargo test -p nodespace-core: 1178 unit + all integration suites clean (shared query code changed, so the whole crate was exercised)
  • bun run test:all clean, frontend 227 files matching baseline; quality:fix clean under -D warnings; full pre-push gate passed

Re-review recommended — the fix moved into shared QueryService/query_ops code rather than staying in the agent tool, which is a wider blast radius than the original PR.

@malibio

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

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

Review Type: Re-Review of commit 42df6ba9 against previously-reviewed 8485c312


Previous Review Summary

# Prior finding Status
🔴 Keyword silently returns 0 results for title_template types (title/content divergence) ✅ Addressed at the source — not documented around
🟡 Typeless sorted search (target_type: "*") returns schema-registry rows at small limits ✅ Fixed, not merely pinned
🟡 run_node_query doc comment stale / understated cost ✅ Addressed
🟢 Test covers only the safe (untemplated) configuration ✅ Rebuilt on the discriminating fixture
🟢 NULL sort ordering undocumented ⚪ Declined — reasonably (see below)
🟢 Some(vec![]) predicate, limit semantics ⚪ No change needed (confirmed correct in prior review)

3 addressed / 1 reasonably declined / 0 new blocking issues found.

The author took the harder and better of the two offered directions on the 🔴 — giving QueryService a real title path rather than accepting and documenting the divergence. That removes the failure mode by construction instead of narrating it, which is the difference between a fix and a caveat.


Verification Performed

I did not take the response summary on faith. Reproduced independently in this worktree:

1. The keyword test genuinely discriminates. Reverted the filter to content (filter_type: "content", property: None) and re-ran:

a_keyword_means_the_same_sorted_or_not_under_a_title_template ... FAILED
  left: Number(0)   right: 2

Exactly the claimed 2→0 collapse, with the failure message correctly naming the cause. The old test passed under both filters; this one does not. Claim verified.

2. The typeless test's limit: 3 is genuinely load-bearing. Reverted resolve_field's wildcard branch to the literal '$.<field>' path:

limit: 3  → FAILED — returned ["nodespace://task", "nodespace://project", "nodespace://text"]
                     (schema-registry rows, count: 3, reported as success)
limit: 50 → ok      — passes even against the UNFIXED code

The comment's claim that a large limit hides the bug (the in-Rust re-sort repairs order after the fact) is exactly right. Both new tests fail against their respective unfixed code and pass against the fix.

3. Full core suite clean. cargo test -p nodespace-core: 1178 unit + 32 + 39 + 36 + every integration suite + 126 doctests — 0 failed. cargo test -p nodespace-agent --test matrix_scenario_winnability: 11/11 pass. Worktree clean, all probe edits reverted.


Blast-Radius Analysis (the wider-surface concern)

The response flags the wider blast radius honestly. I audited each vector; none regress.

title as a queryable metadata field

build_metadata_filter whitelist — purely additive. title previously hit anyhow::bail!("Invalid metadata field"); a call that now succeeds could not have worked before. No caller can regress off a hard error. (test_metadata_filter_invalid_field still passes — it uses invalid_field.)

resolve_field direct-column list — the only behavior change is for a sorting entry whose field is literally title. Before: json_extract(properties, '$.<type>.title') — structurally NULL for every row on a concrete type, so an ORDER BY that sorted nothing. After: the real indexed column. A user-defined field named title was therefore never queryable via sort — it resolved to a path that never matched. This trades dead behavior for correct behavior; there is no working caller to break. Note also title is not in RESERVED_CORE_PROPERTIES (schema/mod.rs:16), so create_schema does not warn on it — but since the prior path was inert, that is a pre-existing gap this PR does not widen.

query_ops::category() routing — correctly scoped. The inference branch runs only when filter_type is absent or names a non-category, because is_known_category(t) returns early on any explicit valid category. So an explicit type: "property", property: "title" still routes to the property path unchanged; only a bare property: "title" reroutes — and that previously built the same always-NULL json_extract. This exactly mirrors the pre-existing content special case, so it is consistent rather than novel.

The deliberate resolve_field / build_property_filter asymmetry — I think this is the right call, and it is applied consistently. A property filter is an explicit statement about the properties JSON, so honoring a title column there would be a genuine semantic change; a sorting entry is an ordering hint with no such contract. The asymmetry is documented in-place with the reason, which is what keeps it from reading as an oversight to the next reader. The one seam — a sorting entry naming a user field called title now hitting the column — resolves to dead-path → working-column, so the inconsistency costs nothing real.

The wildcard '$.' || node_type || '.<field>' change

Behavior change for existing callers: real in principle, inert in practice. It does widen wildcard property filters from "matches nothing" to "actually matches" — but a filter that structurally returned zero rows cannot have had a caller depending on its output. I checked: no existing test anywhere combines target_type: "*" with FilterType::Property — every wildcard test uses Metadata, Content, or Relationship filters, all untouched. That absence is consistent with the path being dead rather than load-bearing.

SQL injection surface — unchanged and safe. field/property both pass validate_identifier (query_ops.rs:251), allowlisting [A-Za-z0-9_:-] and rejecting quotes, spaces, and dots. The new interpolation places them in the same string-literal position as before; node_type is a column reference, not interpolated text, so it introduces no new attacker-controlled surface. Enforced at all three entry points (target_type, filter property, sort field) — and the gRPC handler routes through the same execute_query_nodes, so it inherits the validation.

Index usage — not defeated. Every index in v003_property_indexes is a partial index (WHERE node_type = 'task' / 'project') built on a literal '$.task.status' expression. Those only ever apply when target_type is concrete, and the concrete branch is byte-for-byte untouched — confirmed by test_resolve_field_matches_indexed_expression and test_build_property_filter_matches_indexed_expression, both still passing. The wildcard branch never had index coverage (a NULL-yielding expression matches no index), so there is nothing to lose. Worth noting the concatenated expression is not sargable, but it replaces a full scan yielding wrong rows with a full scan yielding right ones — correctness at unchanged cost.

Correctness for non-root untemplated nodes

This is the sharpest remaining question, and the answer is favorable. compute_title (crud.rs:2051-2070) returns None for a non-root node of a type outside task/collection. Both paths now filter on title, so they agree — and they agree on nothing matching, since INSTR(NULL, …)/LOWER(NULL) LIKE … are NULL, never true.

Did search_nodes lose reach? No. The unsorted path went through query_nodes' title index, which had the identical blind spot — such nodes were already unreachable by keyword. The sorted path is the one that changed, and it changed toward the unsorted path's semantics. So this PR does not remove a capability; it makes an existing, pre-existing limitation uniform across both backends instead of divergent. Making the gap consistent is strictly better than having a keyword mean two different things — and a uniform gap is now visible in one place, which is the precondition for fixing it later.

This is worth a follow-up issue, not a blocker: untitled non-root nodes are keyword-unreachable via search_nodes on both paths. That is a pre-existing reach limitation this PR inherits and surfaces rather than introduces, and fixing it (e.g. title-OR-content, or FTS) is a genuinely separate design decision about what a keyword should mean.


Code Review Findings

🟢 Suggestions

📁 packages/core/src/services/query_service/mod.rs:345-360 — the resolve_field comment explains the wildcard fix but not the title addition

The wildcard comment is excellent — it names the mechanism (per-row namespace), the failure (NULL for every row), and the consequence (LIMIT cuts before the re-sort). By contrast title just joins the direct-column array with a one-word doc-line update. Since title is the entry with a real subtlety — it is the one whose meaning depends on not being reused by build_property_filter 20 lines below — a half-line noting that asymmetry from the resolve_field side would make the pairing legible from either direction. Currently only the build_property_filter side explains it, so a reader arriving at resolve_field first sees an unexplained list entry.

Principle: comments should explain the "why"; a deliberate asymmetry is exactly the kind of decision that reads as a bug when found from the side that doesn't document it.

📁 packages/core/src/services/query_service/mod.rs — no QueryService-level test for the two shared-code changes

Both new tests live in packages/agent/tests/matrix_scenario_winnability.rs and exercise the change through search_nodes. That is the right place for the behavioral contract, and coverage is real. But the changed code is now shared QueryService code with non-agent callers (gRPC ExecuteQuery, frontend query definitions, playbooks), and query_service_test.rs has a natural home for it — including the existing index-coupling block, which is precisely where a future editor will look before touching resolve_field. A direct unit test (wildcard property sort resolves per-row; title resolves to the column) would fail closer to the edit and protect the shared contract independently of the agent crate.

Principle: test at the layer that owns the invariant — a shared-code guarantee validated only through one downstream consumer is one refactor away from being silently unguarded.

NULL sort ordering (🟢 declined) — reasonably declined. None < Some is defensible SQL-NULLS-FIRST-like behavior; the wildcard fix removed the reachable failure (schema rows displacing real matches), and what remains is a documentation question about ordering semantics rather than a correctness defect. Deferring it keeps this PR atomic, which is the right instinct. The original nit — a line in the tool description, since a model asking for "the smallest" may get a node with no value — still stands as a genuine future improvement, but it belongs to the tool-description surface, not this bug fix.

CLAUDE.md compliance — clean. No lint suppression, no #[allow(...)], no #[deprecated], no dead code, no backward-compat shims or dual-mode paths. The old content-filter branch is deleted rather than retained behind a flag, and the stale doc-comment prose is rewritten rather than commented out. No issue numbers embedded in code or comments (the #2249 reference correctly lives only in the commit message). Test names describe the invariant (a_keyword_means_the_same_sorted_or_not_under_a_title_template) rather than a ticket.

Comment accuracy — verified. I checked each factual claim in the new comments against behavior rather than reading them for plausibility. run_node_query's rewritten routing summary now matches the actual predicate; the "both filter a keyword against title" claim is true post-fix; the resolve_field NULL-then-LIMIT explanation is precisely the mechanism I reproduced; and the limit: 3 comment's claim that a large limit masks the bug is confirmed by direct measurement. The comments explain why and are accurate — no drift.


Test Quality Assessment

Both tests are genuinely discriminating, verified by reversion rather than by inspection.

a_keyword_means_the_same_sorted_or_not_under_a_title_template is a notable improvement over its predecessor. It asserts the unsorted count first (2), establishing the comparison is meaningful before testing the sorted path — without that guard a fixture bug making both zero would pass vacuously. Content deliberately shares no word with the title, so a content match finds nothing; the largest head_count deliberately does not match the keyword, so "narrowed then sorted" and "sorted with keyword dropped" name different nodes. Assertions are exact equality on counts, not substring matching, so no accidental-substring risk.

a_typeless_sorted_search_orders_by_the_property uses substrings ("large", "mid", "small") — the one place to look for accidental passes. These are node contents, and the failure mode being tested returns schema-registry rows ("Task", "Project", "Text") with empty titles, which share no substring with any of the three. The top.contains("large") ordering assertion is checked against nodes[0] alone rather than the whole payload, which is the correct narrowing. Nit: the pattern is slightly fragile if the fixture ever gains a node whose content contains another's — exact-equality on an extracted content list would be marginally more robust. Not worth changing now.

The limit: 3 choice is the strongest part of the test: measured, limit: 50 passes against the unfixed code. A less careful author would have written the larger limit and shipped a test that proved nothing.


Recommendation

APPROVE

The blocking finding is genuinely resolved, and resolved the right way. Rather than documenting the title/content divergence, the author eliminated it — title is now a first-class queryable field, so both backends select on the same thing by construction and the routing decision is once again transparent to the model, as run_node_query's doc comment promises. The 🟡 was likewise fixed rather than deferred, and the previously-broken wildcard namespace path is now correct for filters as well as sorts.

I verified the two claims the fix rests on rather than accepting them: the keyword test fails 0-vs-2 when reverted to a content filter, and the typeless test passes against unfixed code at limit: 50 but fails at limit: 3. Both tests earn their place.

On blast radius — the stated reason for requesting re-review — I traced every vector into shared code and found no regression. The title and wildcard changes both convert structurally-dead paths (always-NULL json_extract) into working ones, so there is no prior behavior for a caller to have depended on; no existing test pairs a wildcard with a property filter; the injection surface is unchanged (validate_identifier allowlists [A-Za-z0-9_:-], and node_type is a column reference, not interpolated text); and no index is defeated, since all of v003's partial indexes are literal-expression and concrete-type-only, with their byte-for-byte coupling tests still green. The build_property_filter asymmetry is deliberate, correct, and documented.

The two 🟢s are non-blocking and can land as follow-ups. Separately, the untitled-non-root-node keyword gap deserves its own issue — this PR makes that pre-existing limitation uniform rather than divergent, which is a strict improvement and the right precondition for addressing it, but it is a real reach limitation worth tracking rather than losing.

Net code health is clearly improved: a silent-wrong-answer bug is fixed, a second one found during review is fixed, a latent shared-code defect is repaired, and the tests that pin all three are demonstrably non-vacuous.


Findings marked "verified"/"measured" were reproduced in this worktree by reverting each fix in isolation and re-running the affected test. All probe edits were reverted; git status is clean at 42df6ba9.

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

The two resolve the same field name differently on purpose: a sort entry
reads a same-named top-level column, a property filter always reads the
properties JSON. That asymmetry reads like an oversight without the
reason attached, and "unifying" it would silently redirect a property
filter to a column — answering a different question than the caller
asked.

Comment only; no behavior change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG
@malibio

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed re-review 🟢 items — commit e135bbd

All three triaged. One addressed, one filed as follow-up, one skipped with reasoning.

✅ Addressed — asymmetry note on resolve_field

📁 packages/core/src/services/query_service/mod.rs:344-352

Added the note explaining why resolve_field and build_property_filter resolve the same field name differently, and saying explicitly not to unify them without changing the contract first. This is the item most worth doing of the three — the asymmetry reads like an oversight without the reason attached, and "cleaning it up" would silently redirect property filters to top-level columns.

Comment only; no behavior change. 11/11 winnability tests still pass, quality:fix clean.

📋 Filed as follow-up — untitled non-root nodes unreachable by keyword

#2253

Pre-existing and correctly out of scope here, as the re-review noted. Worth its own issue because the class is larger than it first looks: compute_title derives a title from content only for task/collection or root nodes, so any non-root node of a template-less type is keyword-invisible on both paths — reported as count: 0, indistinguishable from "nothing matches".

The issue sketches three directions (widen to title OR content; populate title more broadly; surface the gap) and flags an open question worth settling first — whether the FTS path has the same blind spot, since if it doesn't, the two search surfaces disagree about what is findable.

⏭️ Skipped — QueryService-layer unit test

The behavior is already covered and the coverage is verified discriminating: both tests were confirmed to fail against the unfixed code, and the re-review independently reproduced that (0 vs 2 on the keyword test; limit: 3 failing while limit: 50 passes on the wildcard test).

Adding a second test at the QueryService layer would re-assert the same guarantees one level down. That is test-placement tidiness rather than a coverage gap, and it is not worth another round-trip on this PR. Reasonable to revisit if QueryService grows callers that exercise these paths independently of the agent tool — at that point the contract genuinely wants a test at the layer that owns it.


No re-review needed. The only code change is a comment; the two substantive fixes were already reviewed and approved in the prior round.

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.

1 participant