Skip to content

Bind QueryService filter values as parameters instead of interpolating them - #2751

Merged
malibio merged 2 commits into
mainfrom
issue-2744-bind-query-params
Sep 18, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2744-bind-query-params

Conversation

@malibio

@malibio malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Closes #2744.

What changed

QueryService built its WHERE clause by formatting operands into the SQL string, with safety resting on escape_string doubling single quotes at every call site. As the issue notes, that was correct — but correct-by-audit: every new operator was a fresh chance to interpolate a value without escaping it, and nothing in the type system would have caught it.

Values now reach SQL as bound parameters. A small BoundSql struct carries the statement and its parameter vector, and its bind is the only way to place a value: it pushes the value and returns the matching ?N in the same step. A placeholder cannot exist without its value, and a value cannot be supplied without the numbering advancing, so the two cannot drift. format_value and escape_string are deleted.

The four points the issue flagged for confirmation

  • execute_query_for_ids — query_node_ids_raw now takes a parameter vector alongside the SQL.
  • Variable-length IN — generates one placeholder per member, numbered consecutively.
  • Identifier positions — untouched. SQL cannot bind a table, column or JSON path segment, so those are still interpolated and still arrive allowlisted by query_ops::validate_identifier. Every caller funnels through execute_query_nodes, which validates.
  • escape_string_for_like — keeps its job but loses its quote-doubling, which is the one real behavior change here. Wildcard escaping is LIKE pattern semantics: binding stops a value being read as SQL, but not as a pattern, so % and _ still need escaping. Quote-doubling was syntax, which binding subsumes — leaving it in would have made a contains search for it's match a literal doubled quote and find nothing.

The LIKE pattern's own % delimiters are now concatenated in SQL (LOWER(x) LIKE LOWER('%' || ?1 || '%')) rather than wrapped around an interpolated string.

build_property_filter's output still starts with the exact expression idx_task_status is built on, so the index-coupling tests hold and filters keep using their indexes. LIMIT stays formatted rather than bound — a usize has no string representation SQL could misinterpret, and it keeps the limit visible to the query planner.

Testing

Five new tests, and each was verified to fail against the previous implementation by reverting the binding and re-running:

  • property filters and relationship subqueries emit placeholders and bind their operands
  • IN generates one placeholder per member
  • a value containing a quote is matched literally
  • LIKE wildcards in a contains value stay literal
  • non-string operands bind as their SQLite counterparts (bool as 0/1)

Worth noting: the quote test initially used task.status, which is a validated enum that rejected the quoted value before it ever reached SQL — so the test was green while proving nothing. It now uses free-text content.

All 1573 Rust lib tests pass (existing coverage unchanged, as the issue asked). quality:fix clean including clippy under -D warnings. Full pre-push gate green.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2751

Review Type: Initial Review


Requirements Check

From issue #2744:

  • ✅ Filter values are bound as parameters rather than formatted into the SQL string — Verified by exhaustive grep: the only remaining '{}' interpolation in query_service/mod.rs is the relationship-type literal at line 752, which is chosen by the match arm, not caller input. format_value and escape_string are deleted, not deprecated.
  • ✅ Identifier positions still go through validate_identifier — Untouched. query_ops.rs:297/301/307 still validate target_type, filter property and sort field before QueryService sees them.
  • ✅ LIKE wildcard escaping is preserved for contains — escape_string_for_like retains \, %, _ escaping. Verified empirically that LOWER(x) LIKE LOWER('%' || ?N || '%') ESCAPE '\' still treats % and _ as literals through the LOWER() wrapper.
  • ✅ Existing coverage passes unchanged — 51 query_service tests pass (bun run rust:test:lib query_service). cargo check -p nodespace-core --lib --tests and cargo clippy --lib --tests are clean with no suppressions.
  • ✅ A test covers a value containing a quote — Two, in fact: test_quote_in_value_is_matched_literally (equality) and test_quote_in_contains_value_is_matched_literally (LIKE path).

📝 The PR body's note that the quote test originally used task.status — a validated enum that rejected the value before it reached SQL, making the test green while proving nothing — is the kind of self-correction worth calling out. Moving it to free-text content is what makes the criterion actually met.


Code Review Findings

I went looking for the failure modes this refactor class usually has, and did not find them. Below is what I verified rather than a list of problems.

Verified — no findings

Placeholder/param correspondence cannot drift.
📁 packages/core/src/services/query_service/mod.rs:165-174

The BoundSql::bind design is the right one: pushing the value and returning ?{len} in the same expression makes it structurally impossible to emit a placeholder without its value or to advance the number without binding. This is the difference between correct-by-construction and correct-by-audit that the issue asked for, and it is the load-bearing idea in the PR.

I specifically checked the ordering concern — conditions are accumulated into a Vec<String> and joined after binding. This is safe because conditions.push happens in the same iteration order as the binds, and the ORDER BY/LIMIT tails bind nothing. The node_type bind at line 398 correctly precedes all filter binds, which is why ?1 is the target type and filter operands start at ?2.

Type mapping in bind_json_value matches storage semantics.
📁 packages/core/src/services/query_service/mod.rs:762-790

The bool-as-integer mapping was the highest-risk item and it checks out. I confirmed against SQLite 3.46 that json_extract on a JSON true returns integer 1 (typeof = integer), so = 1 matches and = 'true' does not. The old format_value emitted the bare keyword true, which SQLite evaluates to 1 — so old and new are equivalent, and the new form is the more explicit of the two. The u64 > i64::MAX bail is correct: no lossless SQLite counterpart exists, and failing beats silently wrapping.

NULL comparison semantics are unchanged.
📁 packages/core/src/services/query_service/mod.rs:787

Equals with a JSON null produces x = ?N with a NULL param, which is never true. The old format_value returned the literal "NULL", producing x = NULL — also never true. Verified both return zero rows. Pre-existing quirk (Exists is the operator that actually works here), not a regression this PR introduces. Not worth blocking on.

Index coupling holds, including with the newly-bound node_type.
📁 packages/core/src/db/schema.rs:48

This one deserved real scrutiny, because binding node_type means the partial index predicate WHERE node_type = 'task' is no longer literally provable at prepare time. I built the index against a populated table and compared plans: node_type = ?1 AND json_extract(properties, '$.task.status') = ?2 produces SEARCH node USING INDEX idx_task_status (<expr>=?) — byte-identical to the fully-literal form. I also ran a correctness counter-test binding a different node_type and confirmed the right rows come back with a plain SCAN, so SQLite is re-qualifying on the bound value rather than wrongly assuming the partial predicate. No perf or correctness regression. The guard tests test_resolve_field_matches_indexed_expression and test_build_property_filter_matches_indexed_expression both still pass.

The LIKE quote-doubling removal is correct, and the reasoning in the PR body is sound.
📁 packages/core/src/services/query_service/mod.rs:798-803

I reproduced all three variants against SQLite directly, searching for IT'S A in a row containing it's a note:

variant result
old: doubled + interpolated ✅ 1 row
doubled + bound (the bug avoided) ❌ 0 rows
new: not doubled + bound ✅ 1 row

Leaving the doubling in would have silently broken every apostrophe search — no error, just zero results. Removing it restores exactly the pre-refactor behavior. The distinction the comment draws (quote-doubling is syntax, subsumed by binding; wildcard escaping is pattern semantics, still needed) is precise and worth keeping in the docstring, which it is.

Relationship filter refactor preserves every column mapping.
📁 packages/core/src/services/query_service/mod.rs:744-749

Checked each arm against the deleted originals in the diff: Children (out_node, in_node, has_child), Parent (in_node, out_node, has_child), Mentions (out_node, in_node, mentions), MentionedBy (in_node, out_node, mentions). All four match exactly. Collapsing four near-identical format! blocks into one tuple-driven template is a genuine DRY win here — the four strings differed only in two identifiers, so the duplication was carrying no information.

LIMIT left unbound is justified.
📁 packages/core/src/services/query_service/mod.rs:445-450

query.limit is a usize, so it has no representation SQL could misinterpret — the type system is the guarantee, not escaping. Keeping it in the text also keeps it visible to the planner. The comment states both reasons. Fine as-is.

Project standards. No lint suppressions, no #[allow(dead_code)], no #[deprecated], no compat shims, no data migrations, no docs added to this repo, no issue numbers embedded in code comments. Compliant.

🟢 Suggestion

📁 packages/core/src/services/query_service/query_service_test.rs:1936 and :2043

Two assertions hardcode placeholder numbers: contains("json_extract(properties, '$.task.status') = ?2") and contains("content = ?2"). These are correct today, but they couple the test to the global bind ordering rather than to the property being tested — inserting any future bind ahead of the filters (a soft-delete predicate, a workspace scope) would fail these tests for a reason unrelated to what they are pinning.

The ?2 is load-bearing in one of them, though: test_property_filter_binds_its_value follows it with an exact assert_eq! on built.params, which is what actually pins the ordering, and the ?2 in the SQL is what ties position 2 in that vector to this filter. That pairing is worth keeping. test_quote_in_value_is_matched_literally is the weaker case — it asserts content = ?2 without a corresponding params assertion, so the number is doing nothing the !built.sql.contains(quoted) assertion above it doesn't already do.

Principle (tests should fail for one reason): consider relaxing the second to a regex or contains("content = ?"), or adding the matching params assertion so the number earns its brittleness. Genuinely optional — the suite is small and the coupling is easy to fix when it breaks.

Test quality assessment

The five new tests are real, not ceremonial. Three of them (quote_in_contains, contains_wildcards_remain_literal, quote_in_value) are behavioral — they insert rows, execute against SQLite, and assert on which rows come back, so they would catch a regression that a SQL-text assertion would miss. The wildcard test in particular is well-constructed: two rows chosen so that a % leaking through as a wildcard matches both, and the assertion checks both the count and which row, so it cannot pass by accident.

test_non_string_values_bind_by_type asserting libsql::Value::Integer(1) for json!(true) is exactly the right place to pin the bool mapping, given it is the subtlest part of bind_json_value.

📝 Minor observation, not a finding: nothing covers IN with an empty array, which generates IN (). SQLite accepts this and returns zero rows. Behavior is identical to before the refactor, so it is pre-existing and out of scope here.


Recommendation

APPROVE

This is a clean, well-motivated structural refactor that does exactly what issue #2744 asked and nothing more. The BoundSql abstraction is the correct shape for the problem — it moves the safety property from "every future contributor remembers to call escape_string" into the type system, which is the entire point of the issue.

Two things raise my confidence above the usual for a change in this area. First, the one deliberate behavior change (dropping quote-doubling from escape_string_for_like) is the subtle kind that would normally slip through as a silent zero-results bug, and it is both reasoned correctly in the code comment and pinned by a behavioral test. Second, the author caught and disclosed a test that was passing vacuously — a validated enum rejecting the input before it reached SQL — rather than letting the green check stand. Both are signs of the change having been actually verified rather than assumed.

The single suggestion above is a nit about test brittleness and should not gate the merge.


Verification run: cargo check -p nodespace-core --lib --tests ✅ · cargo clippy -p nodespace-core --lib --tests clean ✅ · bun run rust:test:lib query_service → 51 passed, 0 failed ✅ · SQLite semantics for bool/NULL/LIKE-escape/partial-index-with-bound-param verified independently against sqlite 3.46 · working tree left 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: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review Response

One recommendation in the review (🟢 Suggestion, hardcoded placeholder numbers). Addressed one of the two call sites, kept the other deliberately — the reviewer's own analysis is what splits them.

✅ Addressed — test_quote_in_value_is_matched_literally

The ?2 here had no paired params assertion, so the number pinned nothing the preceding !contains(quoted) check didn't already establish. It was pure brittleness.

The reviewer offered two fixes: relax to contains("content = ?"), or add a params assertion so the number earns its coupling. I took the second and dropped the number, which is strictly stronger than the original:

assert!(built.sql.contains("content = ?"), ...);
assert!(
    built.params.contains(&libsql::Value::Text(quoted.to_string())),
    "the quoted value must be bound verbatim, with no escaping applied: {:?}",
    built.params
);

Verified it bites: re-introducing .replace('\'', "''") on the content-equality path leaves the old assertion green, while the new one fails naming the defect —

the quoted value must be bound verbatim, with no escaping applied: [Text("text"), Text("it''s a note")]

So the test now catches a regression class it previously missed (correct placeholder, wrong bound value), while no longer failing for unrelated reasons if a future bind is inserted ahead of the filters.

⏭️ Kept as-is — test_property_filter_binds_its_value

The ?2 is load-bearing here, exactly as the review noted: it's paired with an exact assert_eq! on built.params, and the placeholder number is what ties vector position 2 to that specific filter. Relaxing it would weaken the only test that pins bind ordering. The brittleness is the point — if a future bind shifts the numbering, this test should fail, because the ordering guarantee is what it exists to protect.

Verification

mod.rs is byte-identical to the reviewed commit (git diff --stat empty) — the change is test-only. 51 query_service tests pass, quality:fix clean.

Re-review: not needed. Test-only, single assertion, no production-code or logic change.

…g them (closes #2744)

QueryService built its WHERE clause by formatting operands into the SQL
string, with safety resting on `escape_string` doubling single quotes at
every call site. That was correct, but correct-by-audit: each new operator
was a fresh chance to interpolate a value without escaping it, and nothing
in the type system would have caught it.

Values now reach SQL as bound parameters. `BoundSql` carries the statement
and its parameter vector, and its `bind` is the only way to place a value:
it pushes the value and returns the matching `?N` in one step, so a
placeholder cannot exist without its value and the numbering cannot drift.
`format_value` and `escape_string` are gone.

Identifier positions are unchanged — SQL cannot bind a table, column or
JSON path segment, so those are still interpolated and still arrive
allowlisted by `query_ops::validate_identifier`.

`escape_string_for_like` keeps its job but loses its quote-doubling. LIKE
wildcard escaping is about pattern semantics, not SQL syntax: binding stops
a value being read as SQL but not as a pattern, so `%` and `_` still need
escaping. Quote-doubling was syntax, which binding subsumes — leaving it in
would have matched a literal doubled quote. The LIKE pattern's own `%`
delimiters are now concatenated in SQL rather than wrapped around an
interpolated string.

`query_node_ids_raw` takes a parameter vector alongside the SQL.

Five new tests cover the boundary; each was verified to fail against the
previous implementation:
- property filters and relationship subqueries emit placeholders and bind
- IN generates one placeholder per member, numbered consecutively
- a value containing a quote is matched literally, via free text rather
  than the validated `task.status` enum
- non-string operands bind as their SQLite counterparts (bool as 0/1)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio
malibio force-pushed the issue-2744-bind-query-params branch from 561cdbe to 66edbfd Compare September 17, 2026 19:57
@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main — conflict with #2749, and it needed a real decision

main moved while this was in review: #2749 ("Count query matches with COUNT(*)", closes #2743) landed and restructured the same function. GitHub flipped the PR to CONFLICTING. Now rebased and MERGEABLE again, but the resolution was not mechanical, so here is what changed and why.

The conflict

#2749 extracted build_where_clause out of build_query so a new build_count_query could count exactly the rows the select selects. That is the same function this PR rewrote to bind parameters.

The two are complementary, and the resolution is better than either side alone: build_where_clause now returns BoundSql. Since every caller-supplied value lives in the WHERE clause, both build_query and build_count_query inherit binding by sharing it — and neither can reintroduce interpolation on its own.

This matters beyond fixing the conflict. Taking #2749's side verbatim would have left build_count_query as a second SQL-building path still interpolating values — re-opening exactly what #2744 exists to close, on a path that did not exist when this PR was reviewed.

Consequent changes not in the reviewed diff

  • count_nodes_raw(sql, params) — now takes a parameter vector, mirroring query_node_ids_raw. Its doc comment said the caller "owns escaping every value it interpolates"; that contract is obsolete, so it now describes the binding contract. It stays pub(crate), but for the reason that still applies: the caller assembles identifier positions, which binding does not cover.
  • test_count_query_shares_where_clause_with_select (from Count query matches with COUNT(*) instead of materializing rows (closes #2743) #2749) asserted node_type = 'task' — the interpolated form this PR removes. Updated to node_type = ?, plus a new assertion that the count binds the same params as the shared clause. Sharing the text but rebuilding the params would still let a count count other rows, which the original assertion could not have caught.
  • test_count_query_ignores_sorting_and_limit adjusted for the BoundSql return.

Verification

  • 1578 Rust lib tests pass (main's 1573 + the 5 binding tests); 56 in query_service, both sets intact
  • No interpolation remains: the only '{}' in the file is the relationship-type literal chosen by the match arm, not caller input
  • quality:fix clean, made no changes
  • Full pre-push gate green

📝 One note for the record: the first push attempt failed the gate on a frontend test. This change is Rust-only, and bun run test (256 files, 5214 tests) and bun run test:all both pass directly with exit 0 — it was a flake under CPU contention from two concurrent worktree builds, not a regression. The retry passed the identical gate.

Re-review: I'd suggest yes. The reviewed diff was test-only-since-approval, but this rebase changed production code — a new signature on count_nodes_raw and a reshaped build_where_clause — and integrated with code that was not on main when the review ran.

@malibio

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — RE-REVIEW

Review Type: Re-Review (post-rebase onto c6a6415e / #2749)

Previous Review Summary

Previous recommendations 1 (🟢 Suggestion — hardcoded ?2 placeholder numbers in two test assertions)
Addressed 1 / 1 (commit 561cdbe6)
Not addressed 0
New issues found this round 0 Critical, 0 Important, 1 Suggestion

The post-review fix survived the rebase verbatim. git show 561cdbe6 -- query_service_test.rs applies identically to the current file: test_quote_in_value_is_matched_literally still asserts contains("content = ?") (number relaxed) plus the added "the quoted value must be bound verbatim, with no escaping applied" params assertion, with its explanatory comment intact. test_property_filter_binds_its_value still keeps its deliberate ?2 paired with the exact assert_eq! on built.params.


Requirements Check — issue #2744 (re-verified post-rebase)

Criterion Status Evidence
Filter values bound as parameters, not formatted into SQL ✅ format_value and escape_string are fully deleted — grep -rn "format_value|escape_string\b" packages/core/src/ returns zero hits. Every operand routes through BoundSql::bind.
Identifier positions still go through validate_identifier ✅ query_ops.rs:258 unchanged; allowlist [A-Za-z0-9_:-] + *, with validate_identifier_rejects_injection still green.
LIKE wildcard escaping preserved for contains ✅ escape_string_for_like escapes \, %, _ and no longer doubles quotes (correctly — binding subsumes that). test_contains_wildcards_remain_literal pins it behaviorally.
Existing coverage passes unchanged ✅ bun run rust:test:lib → 1578 passed, 0 failed. bun run rust:test:lib query_service → 56 passed.
A test covers a quote-containing value at the boundary ✅ test_quote_in_value_is_matched_literally (equality path) + test_quote_in_contains_value_is_matched_literally (LIKE path).

Every criterion still met after the rebase.


Rebase Integration Assessment

Verdict: the resolution is correct, complete, and faithful to both PRs' invariants.

The net production delta versus the previously-approved commit 561cdbe6 is small and well-contained. git diff 561cdbe6 HEAD -- query_service/mod.rs touches exactly one region: the body that was build_query is split so the WHERE-assembly becomes build_where_clause, and count / build_count_query are added from #2749. No binding logic was altered by the rebase — build_filter_condition, build_content_condition, build_relationship_condition, bind_json_value and escape_string_for_like are byte-identical to the approved version.

1. Is the count path actually bound? ✅ Yes, end to end. build_count_query returns the full BoundSql (sql + params) from the shared clause; count() passes built.params to count_nodes_raw, which forwards to count_from_sql(sql, params) → conn.query(sql, params) (sqlite_store/mod.rs:495, generic over IntoParams). There is no second interpolating SQL-building path — which was precisely the risk of taking #2749's side verbatim. Taking BoundSql up into the shared clause was the right call: it makes binding structural rather than something each caller must remember.

2. Do select and count still match? ✅ Yes, and the sharing is what guarantees it. Both callers take the whole BoundSql by value and mutate only .sql:

built.sql = format!("SELECT * FROM node{}", built.sql);        // build_query
built.sql = format!("SELECT COUNT(*) FROM node{};", built.sql); // build_count_query

params is never cloned into a new vec, reordered, filtered or truncated on either path. Because BoundSql is a private struct with params reachable only via bind (which pushes and returns the matching ?N in one step), the two can't drift.

Mutation-verified. I temporarily added built.params.clear() to build_count_query and re-ran: 3 tests fail, including #2749's own integration tests:

  • test_count_query_shares_where_clause_with_select — "count must bind exactly the values the shared WHERE clause bound" (the newly added assertion, failing by name)
  • test_count_matches_executed_rows — "Should count only the open tasks"
  • test_count_ignores_limit — "count must report the true total"

The mutation was reverted; git status is clean. The new assertion is load-bearing, not decorative, and #2749's invariant is independently defended by its own tests.

3. Placeholder numbering across the two callers. ✅ No off-by-one, and no path can bind ahead of the clause. build_where_clause starts from BoundSql::default() (empty params → first bind yields ?1). Both callers prepend literal text (SELECT * FROM node, SELECT COUNT(*) FROM node) and build_query appends ORDER BY / LIMIT — none of which binds anything. resolve_order_field returns a pure String and takes no &mut BoundSql, so it structurally cannot bind; LIMIT is a usize formatted into the text (correct — and the inline comment rightly notes this keeps the limit visible to the planner).

On whether the doc-comment constraint ("a caller must not bind anything of its own ahead of this clause") is enforced or merely documented: it is enforced by construction for the current callers — neither holds a BoundSql before calling build_where_clause, so there is no instant at which either could bind first. It is not enforced against a hypothetical future caller that constructs its own BoundSql, binds, then tries to splice in this clause. That is the correct place to draw the line, though: encoding it in the type (e.g. a builder that only accepts a clause first) would be YAGNI for two callers in one private impl block, and the doc comment names the constraint precisely where a future author would read it. Documenting an invariant the type cannot express is the right trade here, not a gap.

4. count_nodes_raw signature and pub(crate) justification. ✅ The rewritten comment is accurate and the visibility remains justified — for a narrower but real reason than before. Pre-rebase the rationale was "the caller owns escaping every value it interpolates"; binding retires that, and the main agent correctly did not leave the stale claim in place. The new rationale — the SQL text is still caller-assembled, so identifier positions remain the caller's obligation, and pub(crate) keeps that obligation with callers this crate can audit — is factually true: json_extract(properties, '$.{}.{}') is still interpolated from target_type and property. Keeping the restriction is the conservative and right call. query_node_ids_raw remains pub, which is a pre-existing asymmetry this PR does not introduce (see Suggestion below).

5. Modified tests from #2749 — faithful, and strictly stronger. ✅ test_count_query_shares_where_clause_with_select changed from asserting node_type = 'task' to node_type = ? — that is not a weakening, it is the same assertion updated to the new representation, since the interpolated form no longer exists to assert. The test's actual intent (select and count derive from one clause) is preserved by the two structural assertions, and the claim that it is strictly stronger holds: it now also asserts build_count_query(...).params == where_clause.params, a dimension the original could not check because params did not exist. Mutation testing above confirms the added assertion detects a defect the original assertions would have missed at the SQL-text level. test_count_query_ignores_sorting_and_limit changed only to read built.sql instead of a bare String — semantics identical.

6. Did any of #2749's test coverage get lost? ✅ No. This was the flagged highest-risk area, so I checked it mechanically rather than by reading. Extracting every fn name from git show c6a6415e:...query_service_test.rs and diffing against the current file:

  • Functions in main missing from HEAD: none (54 → 61)
  • Functions in the approved 561cdbe6 missing from HEAD: none (55 → 61)
  • Net new: exactly the 7 expected (test_property_filter_binds_its_value, test_in_operator_binds_each_member, test_quote_in_value_is_matched_literally, test_quote_in_contains_value_is_matched_literally, test_contains_wildcards_remain_literal, test_relationship_filter_binds_node_id, test_non_string_values_bind_by_type)

The test-file diff against main is additions plus exactly three signature-forced modifications (the build_property_filter call now passing &mut built, and two sql → built.sql field accesses). Nothing was silently dropped.

7. Regressions in previously-approved work. ✅ None. All 5 binding tests plus the 2 added later survived; the "the quoted value must be bound verbatim" assertion is present at query_service_test.rs:2224.

Re-confirmed spot checks:

  • Only remaining '{}' in mod.rs is line 810 — the relationship-type literal chosen by the match arm (has_child / mentions), never caller input. Correct; the match-arm tuple refactor also collapsed 4 near-identical format strings into one, a genuine DRY win.
  • escape_string_for_like correctly no longer doubles quotes (doing so post-binding would have produced literal '' in the pattern — test_quote_in_contains_value_is_matched_literally pins exactly this).
  • Index-coupling / priority-rank sort tests all pass unchanged.

On the frontend gate flake: I found no evidence it was real. This branch's net diff versus main is three Rust files (git diff c6a6415e HEAD --stat: nodes.rs, query_service/mod.rs, query_service_test.rs) — zero frontend files touched, so no frontend test can have a causal path to this change. Treating it as CPU-contention flake is supported.


Verification Run

Command Result
cargo check -p nodespace-core --lib --tests ✅ Clean, no warnings
bun run rust:test:lib ✅ 1578 passed, 0 failed
bun run rust:test:lib query_service ✅ 56 passed, 0 failed
Mutation: build_count_query drops params ✅ 3 tests fail by name (reverted; tree clean)

Code Review Findings

🔴 Critical

None.

🟡 Important

None.

🟢 Suggestions

📁 packages/core/src/db/sqlite_store/nodes.rs:3503 — query_node_ids_raw is pub while its counterpart count_nodes_raw is pub(crate), and the two now carry an identical contract: caller-assembled SQL text where identifier positions remain the caller's obligation. The rewritten count_nodes_raw comment makes that symmetry explicit ("Same contract as that method"), which makes the asymmetric visibility read as an accident rather than a decision. Since QueryService is the only caller of either (grep confirms: two call sites, both in query_service/mod.rs), narrowing query_node_ids_raw to pub(crate) would let the compiler enforce the same audit boundary the sibling's doc comment argues for — principle of least privilege, and consistency between two methods documented as sharing one contract.

This is pre-existing (the asymmetry arrived with #2749, not with this PR) and genuinely optional — it is a one-word change with no behavioral effect, and leaving it does not block anything. Flagging it because this PR is what made the two contracts identical, so it is the natural moment. Equally fine to file separately or skip.

Nit: execute_query_for_ids does built.params.clone() (mod.rs:375) while count moves built.params. The clone is forced by the &BoundSql receiver, and the vectors are tiny, so the cost is irrelevant — but taking BoundSql by value there (matching count) would remove the clone and the asymmetry. Truly cosmetic.


Assessment

This is a textbook conflict resolution. The temptation in a rebase like this is to take one side and move on; the resolution instead identified that doing so would have left build_count_query as a second interpolating path — silently re-opening the very issue #2744 exists to close, on code that did not exist when the PR was approved. Hoisting BoundSql into the shared build_where_clause resolves it at the right altitude: both #2749's invariant (select and count match) and #2744's invariant (no value reaches the SQL text) now hold for the same structural reason rather than by two separate disciplines.

The highest-risk part of the resolution — the wholesale-take-and-re-append on the test file — verified clean under mechanical comparison: zero tests from either parent were lost. The doc comments were updated rather than left stale, including the count_nodes_raw rationale that binding genuinely invalidated.

Net effect on code health is strongly positive: format_value and escape_string are deleted rather than deprecated (consistent with the pre-release no-backward-compatibility standard), the relationship-filter match arms collapse 4 duplicated format strings into 1, and safety moves from correct-by-audit to correct-by-construction.

Recommendation

APPROVE — no blocking findings. The one 🟢 Suggestion is optional and pre-existing.

@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 re-review flagged that `query_node_ids_raw` is `pub` while its
counterpart `count_nodes_raw` is `pub(crate)`, now that both carry an
identical contract.

Taking it despite being flagged optional and pre-existing, because this PR
is what made the contracts identical: both bind their values, leaving only
identifier positions to the caller. The comment written here in this PR
says "Same contract as that method" — so the asymmetric visibility is an
inconsistency this PR introduced, and it reads as accident rather than
decision.

`QueryService` is the only caller of either, and both call sites are
in-crate, so the compiler now enforces the audit boundary that the sibling's
comment argues for. Verified by `cargo check --workspace --all-targets`,
which is what proves no out-of-crate caller existed rather than a grep
asserting it.

The nit about `execute_query_for_ids` cloning `params` while `count` moves
it is left alone: it is forced by the `&BoundSql` receiver, and changing the
receiver to satisfy a cosmetic asymmetry would be the tail wagging the dog.

Severity: 🟢 Suggestion

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

malibio commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review Response

One 🟢 Suggestion from the re-review. Applied, despite it being flagged optional and pre-existing.

✅ Narrowed query_node_ids_raw to pub(crate)

The reviewer's own framing is what decided it: the asymmetry is pre-existing, but this PR is what made the two contracts identical. Both methods now bind their values and leave only identifier positions to the caller — and the count_nodes_raw comment written in this PR says, in as many words, "Same contract as that method."

So one being pub and its twin pub(crate) is an inconsistency this PR introduced into a sentence this PR wrote. It reads as accident rather than decision, which is exactly the kind of thing that gets copied forward. One word, compiler-enforced, squarely in scope.

Verified by cargo check --workspace --all-targets rather than by grep — the compiler is what proves no out-of-crate caller existed, whereas a grep only asserts it.

⏭️ Left alone — the params.clone() nit

execute_query_for_ids clones params while count moves it. It's forced by the &BoundSql receiver, and reshaping the receiver to remove a cosmetic asymmetry would be the tail wagging the dog. The reviewer marked it cosmetic; I agree.

Verification

1578 Rust lib tests pass · cargo check --workspace --all-targets clean · quality:fix clean, no changes · full pre-push gate green.


📝 On the gate flakes — worth recording, since this is now the second one.

This push first failed the gate at test:e2e; the earlier one failed at the frontend suite. Neither reproduced: bun run test:e2e passes 27/27 directly, bun run test:all exits 0, and both retries passed the identical gate.

The cause looks environmental rather than coincidental — git worktree list shows five active worktrees, several running their own sessions. The e2e suite starts a real daemon and dev-proxy, so concurrent gate runs from sibling worktrees contend for the same ports and sockets. That failure mode is invisible to a re-run once the neighbours go quiet, which is exactly the pattern seen twice here.

Not something this PR introduces (its net diff is three Rust files, zero frontend), but if these keep landing it's worth a separate issue about gate isolation across worktrees rather than absorbing it as noise each time.

Re-review: not needed. One visibility keyword plus its doc comment; no logic, no signature, no behavior change.

@malibio
malibio merged commit 9096eb3 into main Sep 18, 2026
@malibio
malibio deleted the issue-2744-bind-query-params branch September 18, 2026 06:35
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.

QueryService interpolates filter values into SQL instead of binding them

1 participant