Skip to content

Run a saved query by id or title, narrow it at run time, negate filters, and filter into object values - #3578

Merged
malibio merged 1 commit into
mainfrom
issue-3554-run-saved-query
Oct 5, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-3554-run-saved-query

Conversation

@malibio

@malibio malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Closes #3554. Implements ADR-094 §1 (build order step 1): a saved query can be run by id or title, narrowed at run time, and its filters can negate and reach into object values.

What changed

  • Negation. QueryFilter gains one optional negate flag. The query service compiles a negated filter as (<condition>) IS NOT TRUE, so a node with no value for the field is kept ("status is not done" keeps a task with no status; a negated exists is "has no value"). On a related filter it means "the path reaches no node matching the nested filter", and the nested filter can be negated too.
  • Paths into object values. A property filter's property and a sort's field accept a dotted path (repository.url). Each segment is held to the identifier characters before SQL is built, and a path of several segments is checked against the schema's declared fields (inherited ones included) when the query is saved and each time it runs. A wildcard query refuses a path.
  • Run a saved query. query_ops::run_saved_query_nodes, the RunSavedQuery RPC, nodespace query run <id|title> [--filters] [--limit], and the agent's run_query tool. Run-time filters are ANDed with the stored ones; a run-time limit lowers the stored limit and never raises it; nothing is written to the query node. A title matching no query, or several, fails saying which and lists the ids.
  • Agent tool. run_query is in the tool registry with nodespace query run as its CLI command, has a seeded tool node, and is offered by the Research & Search skill.
  • App. The client-side matcher that decides whether a node created elsewhere joins an open query view honours negate and dotted paths.
  • Skill docs. SKILL.md and references/cli.md document query run, narrowing, negation and object paths. The CLI-surface generator now lists a command's own arguments beside its subcommands (query runs both ways).

Things a reviewer should know

  • The link field type (Add a link field type: a title and URL pair for schema fields #3541) has not landed. Paths resolve through object fields' declared sub-fields. A link field's title / url need a small addition in check_property_path once that type exists.
  • The app has no filter editor. The viewer never rewrites a query's filters, so the "shown read-only rather than rewritten" criterion holds without new UI.
  • run_query joins the Research & Search tool list, which changes the tools on the most common routed turn. Its effect on the local model was not measured. search_nodes's own schema is unchanged; negate is exposed to the model only on run_query's filters.
  • checked_definition now validates identifiers before resolving paths against the schemas, so a malformed name is reported as malformed rather than undeclared.
  • The filter shape changes with no migration.

Tests

bun run test:changed passes (unit, browser, types:check, node-types:check, Rust workspace).

New coverage: the two queue queries from the issue ("no unfinished blocker", "no unapproved plan", including tasks with no blocker and no plan), run by id and title, sorting / limit / relative dates on a run, narrowing leaves the stored query unchanged, none / several / wrong-type references, object paths in filters and sorts, undeclared paths refused at save and run, JSON-path breakout attempts, negated Play selectors (inline and via saved query), the RPC and CLI end to end, the agent tool through GraphToolExecutor, and the app matcher.

Docs (components/query-node.md, architecture/data-layer.md) are updated in nodespace-docs and pushed with the merge.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic code review: PR #3578 (issue #3554)

Review type: initial review (no prior reviews or comments on the PR).

Verdict: COMMENT. No blocker. One Important finding (1) gives silently wrong queue membership for subtype nodes and should be fixed in this PR; the rest are smaller.

The SQL-safety work is sound. I tried to get a property or sort name out of the JSON path literal and could not: every route to SQL goes through build_where_clause_on, which calls validate_identifiers first, and a dotted name is only accepted when every segment is non-empty and made of [A-Za-z0-9_:-]. (cond) IS NOT TRUE is the right form, including for id IN (subquery), where a NULL in the subquery would break NOT IN.

Requirements check

# Criterion Status Notes
1 query run <id> / "<title>", filters, sorting, limit, relative dates, --json ✅ Core, RPC and CLI tests cover each. See finding 3 on a query with no stored limit.
2 Title matching none or several says which ✅ NotFound / InvalidArgument, ids listed.
3 Run-time filters ANDed, stored query unchanged ✅ Test compares properties and version before and after.
4 Negation, negated related, nested negation ✅ with a gap Correct when the far type is declared. Wrong for subtype rows when it is not (finding 1).
5 The two queue queries, including tasks with no blocker and no plan ✅ Both tested on blocked_by and a declared reverse name.
6 Path into an object field in a filter and a sort; undeclared path refused at save and run ✅ with a gap An inherited object field passes the check but is read from the wrong bucket on a subtype target (finding 1). link is disclosed as pending.
7 Name cannot break out of the JSON path ✅ At run time, always. At save time a malformed single-segment name is still stored (finding 2).
8 Agent tool by id or title, in the registry with its CLI command ✅
9 Play selector keeps working and accepts the new forms ✅ with a gap The new selector test passes for the wrong reason (finding 1).
10 Builder loads and saves every query; uneditable forms read-only ✅ No filter editor; filters pass through untouched (disclosed).
11 cli.md and SKILL.md ✅
12 Docs updated ✅ Uncommitted in nodespace-docs; one sentence there needs to change with finding 1.
13 / 14 quality:fix, test:changed Not re-run Taken from the PR body.

Findings

🟡 Important

1. A negated filter matches every subtype row whose field is inherited, because the property bucket is the target type's name, not the field's owner.
📁 packages/core/src/services/query_service/mod.rs:864-892 (build_property_filter), :1116-1125 (build_related_filter), packages/core/src/ops/query_ops.rs:284-328 (check_property_path), packages/core/src/playbook/cron_runner.rs (a_selector_accepts_negated_filters)

A subtype's node keeps an inherited field in the base type's bucket. build_property_filter reads $.<target_type>.<field>, or '$.' || node_type || '.<field>' when there is no single type. For a subtype row and an inherited field, that path is NULL. Before this PR that was a silent miss. With IS NOT TRUE, NULL becomes a match. Three ways to reach it:

  • Related filter over a built-in relationship (has_child, child_of, mentions: far type *). "Tickets with no child that is not closed": a parent whose only child is a closed sel_bug (extends sel_ticket) is excluded, because the child's state is read from $.sel_bug.state. I ran the two expressions in sqlite3: (json_extract('{"sel_ticket":{"state":"closed"}}', '$.' || 'sel_bug' || '.state') = 'closed') IS NOT TRUE is 1; the same read from $.sel_ticket.state is 0.
  • The PR's own selector test covers this up. a_selector_accepts_negated_filters makes OPEN_BUG (a sel_bug) the child of CLOSED_TICKET and expects the parent to be excluded. It is, but because the bug's state reads as NULL, not because it is open. Close the bug and the test would still pass.
  • Subtype target. nodespace query --type issue with status equals done, negate returns every issue, done ones included. check_property_path adds to this: it validates against resolve_field_owners ("its inherited ones included"), so repository.url on a subtype whose base declares repository is accepted as declared and then never matches, or always matches when negated.

The blocked_by queue in the issue is not affected: its far type is declared as task, so every blocker is read from $.task.status.

Recommendation: resolve the bucket from the field's owner. resolve_field_owners already returns the owner map, and resolve_filter already has the type in hand, so it can record the owning type for the first segment and the query service can format that in place of target_type. For the per-row wildcard form, either resolve owners per type or refuse a nested property filter when the far type is unknown. Then change the selector test so the child is a closed bug under one parent and an open bug under another. Principle: correctness of the core predicate; a validator must not accept what the executor cannot read.

Verified by: reading the builders and the storage rule (stated in a_target_type_matches_its_subtypes and components/query-node.md), plus the sqlite3 expression above. I did not run a failing Rust test, since that needs a file edit.

🟢 Suggestions

2. Save-time validation does not check identifier characters.
📁 packages/core/src/services/node_service/crud.rs:2699-2722
validate_query_paths calls resolve_filters and check_sorting but not validate_identifiers. A saved query with "property": "sta tus" or "sorting": [{"field": "a'b"}] is stored and then fails on every run. It is not an injection risk (the run-time gate holds), and a malformed dotted name is refused at save as undeclared. selector_query also resolves before it validates, so a malformed name there is reported as undeclared, which checked_definition was reordered to avoid. Routing all three through checked_definition gives one gate (DRY). Verified by reading.

3. A saved query with no stored limit returns 50 rows from query run and run_query, with no sign that it was cut.
📁 packages/core/src/ops/query_ops.rs (run_saved_query_nodes_excluding, DEFAULT_QUERY_LIMIT)
The same query shows up to FETCH_LIMIT rows in the app and selects every match in a Play. A team with 80 ready tasks and a "Ready tasks" query with no limit gets 50 from the CLI and the agent, and "how many are ready?" is answered 50. It is documented, so this is a design question: for a queue, either default to the transport ceiling (500) when the query names no limit, or say in the output that the result was cut. Verified by reading.

4. A bad run-time filter value reaches the agent as a hard tool error.
📁 packages/agent/src/local_agent/tools.rs (exec_run_query), packages/core/src/ops/query_ops.rs (running saved query failed)
{"property":"status","operator":"in","value":"done"} fails in the query service ("In requires array value") and is wrapped as OpsError::Internal, so run_query returns Err instead of the model-readable error_result it uses for InvalidParams. Over gRPC it is Internal, not InvalidArgument. execute_query has the same classification today, but run_query is new and has no counterpart to repair_scalar_in_operator_values. Verified by reading.

5. A negated nested filter starts its walk from nearly every node.
📁 packages/core/src/services/query_service/mod.rs:1125-1132
SELECT id FROM node WHERE (<cond>) IS NOT TRUE selects every node in the database that does not satisfy the condition, of any type, and walks back from all of them: one json_extract per node per run. path_reaches_condition's doc says the walk starts "from the few nodes the seed names", which no longer holds. Adding the far type's is_a condition to the seed when the far type is known keeps it small. It also means that for an untyped path, a child of any type with no such field counts as "not matching" (a text note under a task is "a child that is not done"); worth a line in the docs. Verified by reading.

6. An archived related node still counts.
📁 packages/core/src/db/sqlite_store/relationship_paths.rs:260-272
The walk passes through archived nodes by design. With negation, a task blocked by an archived, still-open task never enters "no unfinished blocker". That may be intended; it should be decided and written down, since ADR-087 says an archived node takes no part. Verified by reading.

Nitpicks

  • Nit: exec_run_query passes limit: 0 through as LIMIT 0, which reads to the model as "nothing matches". The CLI treats 0 as unset; the agent path could do the same.
  • Nit: query-node-model.ts exists treats '' as empty and the backend uses IS NOT NULL. The mismatch predates this PR, but negation inverts it: a negated exists on an empty-string field live-appends a node the backend excludes.
  • Nit: def_run_query indexes into def_search_nodes()'s schema by path. If that shape moves, serde_json's IndexMut builds a schema holding only negate. The registration test checks operator.enum, which catches it; a comment there saying so would help.
  • Nit: no test for a stored limit above MAX_ROW_LIMIT being capped by the RPC, which is the behaviour the last commit added.

What is good

  • One build_filter for top-level and nested filters, so negation is applied in exactly one place.
  • find_saved_query resolves the type through type_is_a, with no literal node_type comparison; the wire type is changed once and the TypeScript is generated.
  • No compatibility code, and negate is stored only when set.
  • Tests check outcomes (ids returned, version unchanged) rather than SQL text, apart from one deliberate compile test.

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

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (commit 21c963c)

bun run test:changed passes on this commit.

Addressed

  1. Inherited fields (Important). A property filter on a subtype target reads an inherited field from the bucket of the type that declares it (QueryFilter::property_scope, resolved with the paths, never serialized). Where rows have no one type (*, or a related filter over a built-in relationship) each row is read at its own type and then its ancestors through type_ancestry. A negated filter no longer matches every subtype row. New test: a_filter_on_a_subtype_reads_an_inherited_field_where_it_is_stored (plain field, object path, own-bucket field, and the built-in-relationship case). The selector test now separates a closed child from an open one.
  2. Save-time identifier check. validate_query_paths runs validate_identifiers before resolving; selector_query validates before it resolves.
  3. Unlimited query. A saved query with no limit returns every match up to the caller's row ceiling (500 over gRPC and the CLI). The agent tool keeps the 50-row page search_nodes uses. Test: a_callers_row_ceiling_bounds_the_stored_limit.
  4. Negated nested seed. The walk starts from nodes of the path's far type when that type is declared.
  • Nits: the agent tool treats limit: 0 as none given; def_run_query says what guards its indexed schema path; the row cap has a test.

Not changed

  1. A bad run-time filter value is still an execution error, as it is for an inline execute_query. The query service returns one error type for a bad operand and a database failure; separating them is a change to both paths.
  2. A path still walks through archived nodes. That is the walk's existing behaviour for every filter; it is now stated in components/query-node.md.
  • Sorting on a subtype target still reads the target type's own bucket (ordering only, predates this change).
  • The app matcher's empty-string exists check predates this change.

Re-review: needed. Finding 1 changed how the query service builds property conditions.

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic code review (re-review): PR #3578, commit 21c963c

Review type: re-review of c1704077..21c963cc only.

Verdict: APPROVE. The Important finding is fixed correctly and the new tests pin it. Nothing in this commit blocks the merge. Four suggestions below, none of them a regression.

Previous review summary

Count
Previous recommendations 10 (1 Important, 5 Suggestions, 4 nits)
Addressed 7 (findings 1, 2, 3, 5; nits: limit: 0, schema-path comment, row-cap test)
Not addressed, reason accepted 3 (findings 4 and 6; the exists empty-string nit)
New issues from this commit 0 Critical, 0 Important, 4 Suggestions

Status of each previous finding

# Finding Status Notes
1 Inherited field read from the wrong bucket Fixed See the checks below.
2 Save-time identifier check Fixed, untested See suggestion B.
3 Unlimited query cut at 50 Fixed for gRPC and the CLI; unchanged for the agent See suggestion C.
4 Bad run-time filter value is a hard tool error Not changed, accepted Same classification as the inline execute_query; separating a bad operand from a database failure touches both paths and is not this PR's change.
5 Negated nested seed starts from nearly every node Fixed where the far type is declared Unchanged for a built-in relationship, which has no far type to restrict to.
6 Walk passes through archived nodes Not changed, accepted Existing behaviour of every walk, and now stated in components/query-node.md (present in the docs working tree; I could not check whether it is committed).

Finding 1: what I checked

  • node is the right table in every statement. The condition is embedded in four statements: SELECT * FROM node…, SELECT COUNT(*) FROM node…, the membership COUNT, and the seed SELECT id FROM node WHERE … inside path_reaches_condition. None aliases node. The walk's own subqueries use node s, node t, relationship r and the h<n> tables, all inside their own scopes. Inside the seed, node.properties binds to the seed's node, not the outer one. I ran the generated shape in sqlite3 (outer query over node, seed with the COALESCE and the correlated type_ancestry subquery, both negations): the parent of a closed subtype child is kept and the parent of an open one is dropped, which is the result only the inner binding gives.
  • property_scope cannot come from input. It is #[serde(skip)], so no stored query, gRPC payload or tool call can set it. resolve_filter overwrites it on every pass. validate_filter_identifiers holds it to [A-Za-z0-9_:-] before any statement is built, so a definition built in code is checked as well.
  • The typed path keeps the index-matched expression. With no scope the text is json_extract(properties, '$.<target>.<field>'), byte for byte what it was. With a scope it is the declaring type's expression, so an issue query on status now reads $.task.status, the expression idx_task_status is built on.
  • Every production caller resolves first. checked_definition and selector_query are the only routes to QueryService, and both go through resolve_filters.
  • No new failure for an unknown type. A plain property filter on a typed target now calls resolve_field_owners, which it did not before. A type with no schema returns its own name as the chain and contributes no fields, so a query on an unknown or primitive type still returns nothing instead of failing.
  • Far-type restriction (item 2 of the request). (cond) IS NOT TRUE AND (node_type = ?N OR node_type IN (…ancestor = ?N)) is correct: the nested condition is already parenthesised by build_filter, the type is bound through built.bind, and is_a_bound_sql covers subtypes. It also makes the two cases agree: a non-task node at the end of blocked_by was "not done" before and is now ignored, as it already was for the plain form.

Tests

Ran: a_filter_on_a_subtype_reads_an_inherited_field_where_it_is_stored, a_callers_row_ceiling_bounds_the_stored_limit, a_selector_accepts_negated_filters. All three pass.

Read, not run against the old code (that needs a file edit): each would fail on c1704077.

  • Subtype filter: state equals closed on in_bug read $.in_bug.state and returned nothing; the test expects [CLOSED].
  • Built-in relationship case: both children read as NULL, so both parents were dropped; the test expects PARENT_OF_CLOSED to be kept.
  • Selector test: the closed child now has to read as closed for CLOSED_TICKET to be selected.
  • Row ceiling: Unlimited with a ceiling of 500 returned 4 only because there are 4 rows, so this one pins the cap (Some(2) gives 2), not the removal of the default of 50. See the nit.

Suggestions

A. 🟢 A sort on an inherited field still returns the wrong rows, not only the wrong order.
📁 packages/core/src/ops/query_ops.rs:345-354 (check_sorting), packages/core/src/services/query_service/mod.rs:753-770 (resolve_field), :412-426 (compare_nodes_by_field)

The response says this is "ordering only". With a limit it is not. nodespace query run always applies one (stored, 50, or 500), and LIMIT is applied in SQL after an ORDER BY whose every value is NULL.

Scenario: a saved query on issue, sorted by due_date (declared on task), limit 10. ORDER BY json_extract(properties, '$.issue.due_date') is NULL for every row, so the 10 rows are arbitrary, not the 10 earliest. The Rust re-sort reads the same bucket and cannot repair it.

It predates this PR, so it does not block. But resolve_property now returns the owner and check_sorting discards it: carrying the scope on SortConfig the way QueryFilter does, and reading it in resolve_field and compare_nodes_by_field, closes the same bug for sorting. Principle: one rule for where a field is read. Verified by reading.

B. 🟢 Nothing tests the save-time identifier check.
📁 packages/core/src/services/node_service/crud.rs:2711-2715, packages/core/src/playbook/selectors.rs:79-96

No test creates a query node with "property": "sta tus" or a sort field a'b and expects the save to be refused, and none checks that a selector reports a malformed name as malformed. Removing the three new lines in validate_query_paths fails no test. One create_node case expecting invalid_update is enough. Verified by searching the tests for the message.

I checked the regression risk of the new call and found none: a query with no target_type decodes as *, the frontend sends '*', and the other rules validate_identifiers applies (a relationship filter with no node_id, a related filter with no filter) already failed at save inside resolve_filters or at every run. The selector reorder only changes which message a malformed name gets.

C. 🟢 The agent still gets 50 rows from an unlimited query with no sign of the cut, and has no ceiling at all.
📁 packages/agent/src/local_agent/tools.rs:4810-4839, packages/core/src/ops/query_ops.rs:680-690

Finding 3's scenario was "how many are ready?" answered 50. That question is asked of the agent, and the agent path is unchanged: 80 ready tasks, run_query returns {"count": 50, …}.

max_rows now means two things, the ceiling and the default for a query with no limit, so the agent cannot have a ceiling without also taking it as the default. With max_rows: None, a stored limit of 5000, or limit: 5000 asked on an unlimited query, puts 5000 summaries in a local model's context.

Recommendation: either split the two (a default_rows beside max_rows), or add a field to the tool result when the page is full, so the model knows to count instead. Parity with search_nodes is a fair reason to leave the default at 50. Verified by reading.

D. 🟢 Each property filter resolves the type's schemas again.
📁 packages/core/src/ops/query_ops.rs:306-313

A plain property filter on a typed target used to cost no schema read. It now calls resolve_field_owners once per filter, which loads every schema in the chain, at save, at each run, and in selects_node for each membership check a play makes. Resolving the owners once per target type per query (the nested filter's far type separately) removes the repeat. Small today; worth doing if selects_node shows up in a profile. Verified by reading.

Wildcard form, performance. No concern worth a change. The correlated subquery only runs for a row whose own bucket has no value (COALESCE stops at the first non-NULL), and it is a primary-key prefix probe on type_ancestry over a chain of a few rows. The wildcard form had no usable index before either.

Nitpicks

  • Nit: a_filter_on_a_subtype_reads_an_inherited_field_where_it_is_stored: the first filter of the last case (relationship … node_id: OPEN, negate) drops PARENT_OF_OPEN by itself, so the test would still pass if the related filter wrongly kept that parent. Removing it makes the related filter carry both halves of the assertion.
  • Nit: a_callers_row_ceiling_bounds_the_stored_limit has no case for Unlimited with max_rows: None, the agent's path, and with 4 rows it could not tell 50 from "all". Not worth 51 rows; a comment saying so is enough.
  • Nit: packages/core/src/services/query_service/mod.rs:1105-1109: the doc on build_related_filter still describes the untyped fallback as the per-row '$.' || node_type || '.<field>' path. It now also reads the ancestors.

Verified by running versus reading

  • Ran: the three tests above; the nested-seed SQL shape in sqlite3.
  • Read: everything else, including the old-code failure analysis, the limit arithmetic in run_saved_query_nodes_excluding, the daemon handler (limit: 0 to None, max_rows: Some(500)), and the callers of resolve_filters.
  • Not run: the full suite (bun run test:changed is reported as passing on this commit).

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

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed (commit 709fb38)

bun run test:changed passes on this commit.

  • B — a malformed filter or sort name is refused at save time, now with a test.
  • C — run_query marks a result that reached its row limit (limit_reached), so a full page is not reported as the total. The agent still has no ceiling of its own, as search_nodes has none.
  • D — resolving a query's names reads each type's fields once, not once per filter.
  • Nits — the subtype test's related filter stands alone; the build_related_filter doc describes the ancestor read.

Not changed: A. A sort on an inherited field of a subtype target still reads the target type's own bucket. It predates this PR and needs a scope on the sort item, a wire struct.

Re-review: not needed. The changes are a test, a per-query cache and a note on the tool result.

@malibio

malibio commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3578 was taken out of the queue — it conflicts with main in: packages/daemon/src/services/node_service.rs, packages/skill/references/cli.md. Merge or rebase origin/main, resolve the conflicts, push, and re-run bun run merge 3578.

@malibio
malibio force-pushed the issue-3554-run-saved-query branch from f117026 to 07afff7 Compare October 5, 2026 07:46
@malibio
malibio merged commit ec1aece into main Oct 5, 2026
@malibio
malibio deleted the issue-3554-run-saved-query branch October 5, 2026 07:46
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.

Run a saved query by id or title, narrow it at run time, negate filters, and filter into link and object values

1 participant