Skip to content

Count query matches with COUNT(*) instead of materializing rows (closes #2743) - #2749

Merged
malibio merged 2 commits into
mainfrom
issue-2743-count-query
Sep 17, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2743-count-query

Conversation

@malibio

@malibio malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Closes #2743.

Problem

The query editor's Preview answered "how many nodes match these filters?" by running the query and calling .length on the result — fetching up to 500 full node payloads, transferring them over gRPC, deserializing them, and discarding every byte past the count.

It also saturated: a filter narrowing 50,000 tasks to 12,000 rendered as 500+. True, but useless for judging whether the filter did what the user meant.

Approach

Added a CountQuery RPC over ExecuteQueryRequest returning a scalar, mirroring the existing QueryNodesSimple/CountNodes pairing.

The core of the change is extracting QueryService::build_where_clause as the single authority on which rows a query matches. Both build_query (select) and build_count_query (count) are now built from it, so a filter cannot select one set of rows while counting another. Ordering and limiting are not part of matching and stay with the caller — a count has neither.

Threaded through every layer: proto → QueryService/SqliteStore/query_ops → daemon → Tauri command → dev-proxy → adapter interface and all three implementations → the Svelte preview handler. The editor's 500+ suffix is gone, since a COUNT(*) has no row cap to saturate against.

Acceptance criteria

  • A count RPC exists for the ExecuteQuery filter shape, reusing QueryService's WHERE-clause generation rather than duplicating it
  • handleQueryPreview uses it and no longer materializes rows
  • The preview reports an exact total with no 500+ saturation
  • Sorting is not requested for a count (it cannot affect one)

Testing

  • Rust lib: 1571 passed, including 5 new QueryService count tests
  • Daemon gRPC round-trip: count_query_reports_exact_total_ignoring_limit_and_sorting passes — pins the no-saturation behavior end-to-end and asserts execute_query/count_query agree on the same filters
  • Frontend: 5214 passed / 256 files — identical to the pre-change baseline, no regressions
  • quality:fix: clean (0 errors, 0 warnings, clippy clean, no new design-token violations)

I verified test_count_ignores_limit genuinely fails against the real pre-fix behavior (reports 2 instead of 7) rather than passing vacuously. Worth noting for reviewers: appending LIMIT to the COUNT SQL does not fail that test, because SQLite's LIMIT caps result rows rather than counted rows — the mutation that reproduces the bug is at the call site.

🤖 Generated with Claude Code

#2743)

The query editor's Preview answered "how many nodes match these filters?"
by running the query and calling `.length` on the result: up to 500 full
node payloads fetched, transferred over gRPC and deserialized, with every
byte past the count discarded. It also saturated — a filter matching 12,000
tasks rendered as "500+", true but useless for judging whether the filter
did what the user meant.

Add a `CountQuery` RPC over `ExecuteQueryRequest` returning a scalar,
mirroring the existing `QueryNodesSimple`/`CountNodes` pairing.
`QueryService::build_where_clause` is extracted so the select and the count
are built from one clause and cannot select one set of rows while counting
another; `build_count_query` wraps it in COUNT(*) with no ORDER BY and no
LIMIT, neither of which can affect a total.

The preview now reports an exact total at any size.

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

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #2749 — Count query matches with COUNT(*) instead of materializing rows

Review Type: Initial Review
Commits reviewed: 05d46cf8 (single commit), full diff vs origin/main
Files changed: 14 (proto, core, daemon, Tauri, dev-proxy, adapters, 2 Svelte components, 2 test files)


Summary

Clean, well-scoped, net-positive change that does exactly what the issue asked and nothing more. The central design decision — extracting build_where_clause as the single authority on "which rows match", so build_query and build_count_query cannot drift — is the right one, and it is the decision that makes the feature trustworthy rather than merely fast. The change is atomic, mirrors an existing precedent (QueryNodesSimple/CountNodes) rather than inventing a new pattern, and the doc comments explain why rather than restating mechanics.

Correctness claims were verified empirically rather than by reading alone — including mutation-testing the two tests flagged as possibly tautological. Both catch real regressions.

Verification performed:

  • bun run rust:test:lib — 1571 passed, 0 failed
  • bun run test — 256 files, 5214 tests passed
  • Two source mutations to probe test strength (restored; working tree confirmed clean)

Requirements Check (issue #2743)

  • ✅ A count RPC exists for the ExecuteQuery filter shape, reusing QueryService's WHERE-clause generation rather than duplicating it
    CountQuery(ExecuteQueryRequest) returns (CountNodesResponse) in node_service.proto:103-110. Reuse is structural, not conventional: build_count_query calls the same build_where_clause as build_query — there is no second copy of the condition logic to drift.

  • ✅ handleQueryPreview uses it and no longer materializes rows
    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:477-480 — now return await backendAdapter.countQuery({...}). No executeQuery, no .length, and the limit: MAX_QUERY_ROWS argument is gone.

  • ✅ The preview reports an exact total with no 500+ saturation
    📁 query-editor.svelte:230-233 — the previewCount >= MAX_QUERY_ROWS ? '+' : '' suffix is removed. Backed end-to-end: the daemon's count_query passes limit: None, and build_count_query emits no LIMIT, so nothing caps the number on any hop.

  • ✅ Sorting is not requested for a count (it cannot affect one)
    Enforced at three independent layers: the frontend omits sorting; the daemon sets sorting: None (node_service.rs:1066); and build_count_query structurally cannot emit an ORDER BY because it never calls resolve_order_field. test_count_ignores_sorting asserts the generated SQL contains neither ORDER BY nor LIMIT.

All four acceptance criteria met.


Deep-dive on high-scrutiny areas

1. SQL injection — no new surface. Confirmed safe.
The count path inherits the entirety of the existing defense because it reuses the same builder, not a parallel one:

  • target_type → gated by query_ops::validate_identifier (query_ops.rs:258-279, charset [A-Za-z0-9_:-] plus *), reached via the shared to_query_definition, so the count entry point cannot bypass it.
  • Filter values → escaped inside the four filter builders via escape_string (quote-doubling) and escape_string_for_like (quote + \ + % + _, with ESCAPE '\'). All four live inside build_where_clause, so the count gets every one.
  • count_nodes_raw delegates to the pre-existing count_from_sql with () params — exactly the contract query_node_ids_raw already had.

Net: the count path's injection surface is a strict subset of the select path's (no ORDER BY interpolation at all).

2. Select/count divergence — no input found where they disagree.

  • Wildcard *: build_where_clause omits the type condition for * on both paths (one code path, one behavior).
  • Relationship filters: built inside the shared clause; no post-SQL relationship filtering exists in execute.
  • lifecycle_status / archived: neither path filters on it. build_where_clause never references the column, and get_node (nodes.rs:380-396) is a bare SELECT * FROM node WHERE id = ?1. Both include archived nodes — consistent, which is what matters.
  • Scope projection: verified by mechanism, not reasoning. project_nodes_to_scope (node_service/query.rs:450-480) is a .into_iter().map(...).collect() — a pure map, no filter, no flat_map. Cardinality-preserving by construction, so it cannot change a row count. Omitting it from the count path is correct.
  • Subtype/extends (ADR-078, landed in the immediately preceding commit): clean — QueryService has no subtype expansion at all. Both paths emit exact-match node_type = '<target>'.

One theoretical difference: execute drops a row if get_node returns None between the id query and hydration. Narrow TOCTOU on concurrent deletion, pre-existing, inherent to execute's two-phase design. Not introduced here; not actionable.

3. int64 across the wire — correct.
dev-proxy.ts:602-606 does Number(res.count ?? 0) with a comment naming the cause (longs: String in grpc-client.ts). Without it the adapter's Promise<number> would receive a string and previewCount === 1 would silently fail for a one-result preview. The Tauri path returns i64 → serde_json number → TS number, exact below 2^53.

4. limit semantics — correct. count_query is new with exactly one caller, which wants the uncapped total. Dropping limit is the feature. Matches the count_nodes precedent (node_service.rs:955-957).

5. Test quality — mutation-tested; neither flagged test is tautological.

Mutation A — build_count_query drops the filters:

test_count_matches_executed_rows ................... FAILED
test_count_query_shares_where_clause_with_select ... FAILED

Mutation B — count built as SELECT COUNT(*) FROM (<full select, ORDER BY + LIMIT and all>):

test_count_ignores_limit ........................... FAILED
test_count_ignores_sorting ......................... FAILED
test_count_query_shares_where_clause_with_select ... FAILED

test_count_ignores_sorting earns its place via the SQL-shape assertion (the behavioral half alone would pass under Mutation B). test_count_query_shares_where_clause_with_select is the strongest in the set, failing under both. test_count_empty_result_is_zero guards count_from_sql's ok_or_else(... "No result for count"), which would error on a genuinely empty rowset.

6. Dead code / leftovers — clean. MAX_QUERY_ROWS remains legitimately used in query-node-viewer.svelte (62, 165, 264, 293) and adapter-core.test.ts; removing the query-editor.svelte import is correct. All three BackendAdapter impls implement countQuery. No #[allow(dead_code)], no #[deprecated], no backward-compat shim, no any, no raw console.*, no issue numbers in code comments, no new .md files.


Findings

🔴 Critical

None.

🟡 Important

None.

🟢 Suggestions

🟢 Nit: an unbounded COUNT(*) is a new (small) cost surface
📁 packages/daemon/src/services/node_service.rs:1060-1067

Every other query RPC clamps to MAX_ROW_LIMIT; count_query deliberately does not, which is correct — the uncapped total is the feature. Worth noting only that this makes it the one query RPC that can provoke an arbitrarily long full scan on a huge table with an unindexed filter. In practice almost certainly a non-issue: local SQLite file, single-user desktop app, and COUNT(*) with no hydration is far cheaper than the 500-row materialization it replaces. Flagging so the trade-off is recorded rather than rediscovered.

Principle: removing a limit is a deliberate cost/correctness trade — worth naming explicitly so a future reader doesn't "fix" it by reinstating a cap that would silently reintroduce the saturation bug this PR removes.

🟢 Nit: count_nodes_raw's safety contract is documented but not enforced
📁 packages/core/src/db/sqlite_store/nodes.rs:3513-3520

Takes fully-assembled SQL and relies on the caller to have escaped everything. The doc comment states this and notes QueryService is the only caller. Exactly matches the pre-existing query_node_ids_raw, so no new risk — but it widens by one the number of pub methods accepting raw SQL on trust. If that surface grows, pub(crate) or a TrustedSql newtype would let the compiler carry the invariant. Matching the existing neighbor is the right call today.

Principle: invariants enforced by the type system survive refactors; invariants enforced by doc comments survive only as long as people read them. Worth escalating when the surface grows, not at N=2.


Recommendation: APPROVE

Clear net improvement to code health, no critical or important findings. Three things stand out:

  1. The abstraction is at the right altitude. build_where_clause is extracted because select and count must agree on which rows match — not because two functions happened to share lines. DRY applied to a semantic invariant rather than to text.
  2. It follows an existing pattern instead of inventing one. Mirroring QueryNodesSimple/CountNodes means the next reader already knows how CountQuery behaves.
  3. The tests pin behavior, not implementation. Confirmed by mutation rather than inspection; the suite caught every mutation introduced.

Both suggestions are optional and neither should block the merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above: 0 critical, 0 important, 2 optional nits. All four acceptance criteria met.

Both review findings were 🟢 nits on an APPROVE; neither changes behavior.

- Document why `count_query` is the one query RPC that does not clamp to
  MAX_ROW_LIMIT, and that reinstating a cap would reintroduce the saturation
  bug the RPC exists to remove — so the trade is recorded at the site rather
  than rediscovered by someone "fixing" it.
- Narrow `count_nodes_raw` from `pub` to `pub(crate)`. Its only caller,
  QueryService, is in-crate, so the compiler now enforces the
  caller-escapes-everything contract the doc comment had been carrying alone.

Skipped the reviewer's optional `TrustedSql` newtype: it would require
converting the pre-existing `query_node_ids_raw` to match, extending this PR
into code it does not otherwise touch. `pub(crate)` gets the same
compiler-enforced-invariant benefit at a fraction of the surface. Worth
revisiting if the raw-SQL surface grows past these two methods.

Co-Authored-By: Claude Opus 5 (1M context) <[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.

Query preview materializes up to 500 rows to display one integer

1 participant