Skip to content

knowledge.query calculates over ingested datasets with a typed plan and a receipt - #278

Merged
zlareb1 merged 15 commits into
mainfrom
feat/knowledge-query
Nov 5, 2026
Merged

zlareb1 merged 15 commits into
mainfrom
feat/knowledge-query

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Related: #157

Changelog category (leave one):

  • New Feature

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

knowledge.query calculates over the datasets ingested files become: a typed plan of filters, joins, groups and aggregates (or the rows themselves) runs over every row of the live snapshots, and the result carries a receipt naming each snapshot it read.

Why

The issue asks for a structured-query operation over registered datasets: a bounded, typed plan that the server validates against approved schemas and compiles to parameterized read-only SQL, with no model call, typed results, calculation receipts and completeness. Ingest already publishes each table of a CSV, XLSX or Parquet file as a typed snapshot (loom.datasets, loom.dataset_rows); nothing could calculate over one yet, so an agent asked for a total had to page rows through knowledge.dataset_get or answer from a few retrieved passages, which the issue rules out ("do not answer an aggregate from top-k retrieved rows").

Design

  • The plan (server/knowledge/api/models_query.py): up to four datasets of the namespace, each source_uri + dataset_id under an alias; where filters (eq, ne, lt, le, gt, ge, in, not_in, is_null, not_null, contains, starts_with), all of which must hold; one inner equi-join for each dataset past the first, to an earlier one; group_by (a date or date-time by day, month or year, in UTC); aggregates (count of rows or of a column's values, count_distinct, sum, avg, min, max), or select (the rows themselves, each with its row ids); order_by result column names, then the groups' or the rows' own order, so rows that tie come back the same way when a limit cuts them; limit 1 to 1,000, with truncated when more matched. A null meets no comparison but is_null: ne and not_in skip it too.
  • Checked against the schemas (server/knowledge/domain/query.py, pure): every column named is one a schema stores; every filter value is read as its column's type, the same conversion a row's value goes through, except that a number (or a duration) with more than nine decimal places is refused rather than rounded where its column is a decimal (compared rounded, ge 0.0000000004 would match 0), a date-time with an offset is read in UTC, and a duration is seconds or H:MM:SS; every comparison, join, group and aggregate is one its columns' types allow. Join keys must be held in the same kind of slot: ClickHouse has no common type for a Decimal128(9) and a Float64 (measured: "There is no supertype for types Decimal(38, 9), Float64").
  • Compiled (server/knowledge/store/dataset_query.py): one SELECT over loom.dataset_rows built from slot names (checked against SLOT_COLUMNS), result names c0, c1, ... and typed parameters alone; no identifier or value a caller wrote is SQL. Each dataset is a subquery held to its snapshot and the caller's org and namespace, with its own filters, before any join, so a row of another tenant or snapshot is never joined, counted or summed.
  • Decimals: a sum of a decimal column is taken in Decimal256 (Decimal128(9)'s sum stays 38 digits and can overflow); an average is that sum over the count, divided at 18 places and rounded to nine, since ClickHouse's avg of a decimal returns a Float64 and a decimal division truncates to its scale (measured: 2/3 at nine places is 0.666666666). A sum of no values is null. A dataset's number columns past its first 24 number or duration columns are held as doubles, so summed and averaged as doubles.
  • Pinned and revalidated (server/knowledge/app/query.py): each dataset is read at the snapshot its source's live document serves. A dataset whose schema needs an answer (needs_clarification) is refused (422) until a writer approves it, as the issue asks ("uncertain type conversion ... prevents complete numerical serving until resolved"). After the statement, each dataset must still be served by the snapshot read: a publish or a retyping approval serves another and deletes the rows read without waiting, and an erasure serves none, so one replaced or erased while the statement ran answers 409 PRECONDITION_FAILED rather than releasing rows read from it; so does a publish that lands while the query looks the dataset up, rather than a 404. The lookups read only the documents' versions, and the lookups and the scan read the caller's own writes (own_write_reads), so a query right after an ingest or approval finds the snapshot it published and every row of it. A metadata edit moves the document version but keeps the snapshot, so it is not a change.
  • Bounded: a filter's text value is at most 1,024 characters and an in or not_in list of text values 100,000 bytes as the client sends it (a number among them within a few bytes of its sent text) (UTF-8, a backslash before each quote, backslash, backtick, tab or newline, and four bytes of quotes and separator a value; a unit test holds the count to the client's own encoding and escape list), while a list of any other type sends at most about 42 bytes a value, refused as invalid (422) past them: each is one parameter of the statement, which ClickHouse takes up to 128 KiB of, in bytes (measured: 131,073 ASCII characters pass and one more fails with "Field value too long"; 1,000 values of 60 € fail and of 40 pass). The values are strict: a text value is never read as another type (a 1,030-digit string as the integer it spells). A field the op does not take (value on in or is_null, values on eq) is refused, not dropped. The statement runs in ch.caller_shaped(), as the read-only reader user where one is configured (its only grant is SELECT on loom.*), under the caller-shaped ceilings (30 s, 4 GB, 500 million rows read by default) with read_overflow_mode = throw: a plan past them fails with 422, never part of an aggregate; the message says how to narrow a query (caller_shaped takes the hint, so code search keeps its own). A join on a key that repeats is bounded by the time and memory ceilings too.
  • Receipt and completeness: the response names each snapshot read (snapshot_id, revision, row_count, rejected_rows, complete, schema_state), the plan as validated, the statement and its parameters (a decimal in plain digits). A date column is returned as a date, as its type says, and dates and buckets are Date32 across the 1900-2299 a slot holds (ClickHouse's Date wraps a date before 1970 or past 2149 to another: 1950-03-15 read as 2129-08-19, measured). complete is false, with incomplete giving one reason per dataset, when a dataset's extraction left part of its table out or rejected rows. Nothing is stored: the receipt is the response, so no table, migration or erasure step is added.
  • Saved formula values: an XLSX formula column holds the value the workbook last saved, which is what a query sums; nothing recalculates.
  • Rate limit: knowledge.query gets a bucket of its own sized like knowledge.search's (20 burst, 3 a second per namespace); by the prefix rule it would have drawn on knowledge.add's write-shaped 10/2, so a handful of queries refused the next write.
  • knowledge.dataset_get's value rendering (datasets._value) is now json_value, shared with the query result.

Alternatives considered: SQL text from the caller, checked by a parser (a parser's gaps become an injection surface, and the issue rules out model-written SQL); a view per dataset with real column names (a DDL per publish, and names a caller controls inside SQL); running aggregates in Python over paged rows (loads the dataset into the API process, which the issue rules out).

Scope and risk

  • Read-only: no write path, table, migration or setting. New op, new rate-limit bucket.
  • Tenant isolation: the org and namespace come from the request scope the transport authorized and are parameters of every subquery; a dataset id of another org or namespace is not found (404), and the leakage suites pass.
  • Left for later in the issue's plan: plans proposed by a model and answers that combine query results with passages (P8); units, which the dataset schema does not record yet; row or column restrictions inside a namespace, which Loom does not model.

Compatibility, rollout and rollback

  • Wire: adds knowledge.query (viewer, read, experimental, not in the default MCP listing). No field of another op changes.
  • Operator steps: none. A query sends select_sequential_consistency and, with a month or year bucket, enable_extended_results_for_datetime_functions; the shipped reader profile and loom ch-setup's constrain neither (a bucketed query run as loom_reader returns 1950-03-01). Where LOOM_CH_READER_USER is set, queries run as that user, which loom ch-setup already grants SELECT on loom.*.
  • Rollback: reverting removes the op; nothing is stored.

Tests

  • Unit (tests/unit/test_knowledge_query.py, 45): each refusal of a plan its schemas do not allow, with its reason; filter values read as their columns' types; the exact statement for a join, filter, bucketed group, sum and average, with a caller's quote-laden value only a parameter; rows selected with their row ids in source order; a schema naming a slot outside SLOT_COLUMNS refused before compiling; the handler reading the live snapshot under the caller-shaped ceilings, refusing a schema that needs an answer before any read, refusing a snapshot replaced, retyped under the same version or erased while the statement ran, and saying when the result may not cover a dataset and when more rows matched.
  • Integration (tests/integration/test_knowledge_query_live.py, 5, against a real server, ClickHouse and extractor): reference queries over two CSVs (totals, nulls, counts and distinct counts, groups, a time boundary at 23:59:59 on the last day of a month, month buckets, in on numbers, starts_with on text, ne on a date-time, not_in and ne on a number with a null (a null meets neither), a join, rows with row ids and truncated), the receipt's snapshots against knowledge.dataset_get's; the same file under another namespace and another org never reaching a count, and another org's dataset id not found; a dataset that needs clarification refused, then counted once approved with its rejected row reported; a Parquet decimal(38,9) summed and averaged with every digit, and filtered by a boolean and by a decimal zero, and by lists of booleans and of dates, a date column's maximum returned as a date, and dates of 1950 and 2290 grouped by day, month and year and selected; an XLSX formula column summed by its saved values. The ingest suite (11) and the leakage suites (42 passed, 17 skipped) pass.
  • Unit, also: the cap error naming the caller's hint and dropping it with its scope (test_ch_caller_shaped.py); knowledge.query's own rate-limit bucket (test_ratelimit_read_bucket.py).
  • A CSV's 30-digit decimal is read by the CSV reader as a double before it is stored; the query test pins what that gives, and the exact-digit case is Parquet's.
  • Full unit suite on the merged head: 27,461 passed, 19 skipped, 1 xfailed; the four cases of test_the_delimiter_is_sniffed_in_bounded_time (a CSV sniff under a 5 s wall-clock bound, code this PR does not touch) failed under load, as they do on main on the same machine.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. Checked: the generated SQL against a real ClickHouse (decimal sum and average types, join supertypes, buckets, array parameters, the row cap's error), each refusal and the receipt in the tests above, and a review at every push.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass (but the four CSV timing cases above); the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

zlareb1 and others added 13 commits November 5, 2026 19:11
…nd a receipt

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ites, and order ties

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…s snapshot, return dates as dates

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…liases before any read

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…cuments' versions

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…fuse a rounded duration

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…rounding refusal is a decimal's

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…r values strictly

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…se a field the op does not take

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…use values on a null test as no value

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-query branch from fb7a6b8 to 8bf927b Compare November 5, 2026 19:13
@zlareb1
zlareb1 merged commit 4d43403 into main Nov 5, 2026
23 of 24 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-query branch November 5, 2026 20:12
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