Repository navigation
knowledge.query calculates over ingested datasets with a typed plan and a receipt - #278
Merged
Merged
Conversation
…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]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-query
branch
from
November 5, 2026 19:13
fb7a6b8 to
8bf927b
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
This was referenced Nov 5, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related: #157
Changelog category (leave one):
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.querycalculates 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 throughknowledge.dataset_getor answer from a few retrieved passages, which the issue rules out ("do not answer an aggregate from top-k retrieved rows").Design
server/knowledge/api/models_query.py): up to four datasets of the namespace, eachsource_uri+dataset_idunder analias;wherefilters (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 byday,monthoryear, in UTC);aggregates(countof rows or of a column's values,count_distinct,sum,avg,min,max), orselect(the rows themselves, each with its row ids);order_byresult column names, then the groups' or the rows' own order, so rows that tie come back the same way when a limit cuts them;limit1 to 1,000, withtruncatedwhen more matched. A null meets no comparison butis_null:neandnot_inskip it too.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.0000000004would match 0), a date-time with an offset is read in UTC, and a duration is seconds orH: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 aDecimal128(9)and aFloat64(measured: "There is no supertype for types Decimal(38, 9), Float64").server/knowledge/store/dataset_query.py): oneSELECToverloom.dataset_rowsbuilt from slot names (checked againstSLOT_COLUMNS), result namesc0,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.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'savgof a decimal returns aFloat64and 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.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 answers409 PRECONDITION_FAILEDrather 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.inornot_inlist 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 (valueoninoris_null,valuesoneq) is refused, not dropped. The statement runs inch.caller_shaped(), as the read-only reader user where one is configured (its only grant isSELECTonloom.*), under the caller-shaped ceilings (30 s, 4 GB, 500 million rows read by default) withread_overflow_mode = throw: a plan past them fails with422, never part of an aggregate; the message says how to narrow a query (caller_shapedtakes the hint, so code search keeps its own). A join on a key that repeats is bounded by the time and memory ceilings too.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 areDate32across the 1900-2299 a slot holds (ClickHouse'sDatewraps a date before 1970 or past 2149 to another: 1950-03-15 read as 2129-08-19, measured).completeis false, withincompletegiving 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.knowledge.querygets a bucket of its own sized likeknowledge.search's (20 burst, 3 a second per namespace); by the prefix rule it would have drawn onknowledge.add's write-shaped 10/2, so a handful of queries refused the next write.knowledge.dataset_get's value rendering (datasets._value) is nowjson_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
404), and the leakage suites pass.Compatibility, rollout and rollback
knowledge.query(viewer, read, experimental, not in the default MCP listing). No field of another op changes.select_sequential_consistencyand, with a month or year bucket,enable_extended_results_for_datetime_functions; the shipped reader profile andloom ch-setup's constrain neither (a bucketed query run asloom_readerreturns 1950-03-01). WhereLOOM_CH_READER_USERis set, queries run as that user, whichloom ch-setupalready grantsSELECTonloom.*.Tests
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 outsideSLOT_COLUMNSrefused 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.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,inon numbers,starts_withon text,neon a date-time,not_inandneon a number with a null (a null meets neither), a join, rows with row ids andtruncated), the receipt's snapshots againstknowledge.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 Parquetdecimal(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.test_ch_caller_shaped.py);knowledge.query's own rate-limit bucket (test_ratelimit_read_bucket.py).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 onmainon 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 typecheckandmake test-unitpass (but the four CSV timing cases above); the integration suite passes if server behaviour changed.docs/reference/configuration.mdand thedocs/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).main; no merged migration is edited.hooks/,lib/,bin/,skills/,.mcp.json, the Codexplugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.npm --prefix frontend run build) and its tests pass, iffrontend/changed.docs/describe the system as it now is, and this description names any operator steps and wire changes.tests/unit/test_public_copy.py).git commit -s), as CONTRIBUTING.md asks.🤖 Generated with Claude Code