From 2b463adde7ab0e041680daa1711bbe05d8ba4387 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 07:18:32 +0000 Subject: [PATCH 01/18] A read's answer records the revision of each item it carried After an item changes, the record of which keys a run was served cannot say which revision the run saw. loom.read_receipts holds one row per item of a receipted read's answer: the memory row's version and stored content hash, or the document's revision, with the request, the run and the reader. It holds identifiers and a hash, never content or query text. The revision is noted by the code that holds the row while the read runs. It is never looked up afterwards and never taken from another row under the same key. The rows queue for one sender per process, which sends one insert each half second, so receipts hold one ClickHouse connection and a fixed insert rate whatever the read rate and never fail or delay a read. A request that runs a mirror leg writes none. Both erasure scopes cover the table with lightweight deletes, and no row is written while a replica without the erasure step serves. A user's census counts the receipts stamped before the erasure was recorded, so a user who keeps reading does not fail their own erasure. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- .github/workflows/ci.yml | 1 + docs/architecture/clickhouse.md | 42 +- docs/architecture/read-receipts.md | 374 +++++ docs/architecture/rolling-upgrades.md | 8 + docs/architecture/storage-layout.md | 1 + docs/features/memory/retention-and-erasure.md | 18 +- docs/features/runs.md | 7 + docs/operations/upgrades.md | 5 + docs/reference/configuration.md | 1 + docs/reference/schema.md | 3 +- loom.example.yaml | 6 + schemas/loom-settings.schema.json | 5 + schemas/migrations/122_read_receipts.sql | 49 + schemas/schema.sql | 33 +- server/cli/hygiene.py | 5 +- server/core/instances.py | 9 + server/erasure/app/saga.py | 2 +- server/erasure/app/saga_steps.py | 10 + server/erasure/store/census.py | 20 +- server/erasure/store/mutations.py | 28 + server/erasure/store/predicates.py | 11 + server/erasure/store/steps_ledgers.py | 33 + server/identity/app/namespace_guide.py | 9 +- server/identity/store/namespace_census.py | 1 + server/knowledge/api/ops_knowledge.py | 7 +- server/knowledge/app/document_reads.py | 6 + server/knowledge/app/gaps.py | 8 +- server/knowledge/app/knowledge_search.py | 3 + server/knowledge/app/read_receipts.py | 17 + server/memory/api/models_brief.py | 8 +- server/memory/api/ops_ask.py | 3 +- server/memory/api/ops_brief.py | 3 +- server/memory/api/ops_bulk.py | 3 +- server/memory/api/ops_context.py | 5 +- server/memory/api/ops_crud.py | 5 +- server/memory/api/ops_for_file.py | 5 +- server/memory/api/ops_lifecycle.py | 5 +- server/memory/api/ops_loom_search.py | 3 +- server/memory/api/ops_procedure.py | 5 +- server/memory/api/ops_search.py | 3 +- server/memory/app/after_write.py | 14 +- server/memory/app/brief.py | 8 +- server/memory/app/context_pack.py | 3 + server/memory/app/for_file.py | 5 +- server/memory/app/handlers.py | 6 + server/memory/app/procedure.py | 2 + server/memory/app/query.py | 4 + server/memory/app/read_receipts.py | 437 ++++++ server/memory/app/retrieval/fact_sql.py | 2 + server/memory/app/retrieval/search.py | 3 + server/memory/app/search/payload.py | 5 + server/memory/app/search/term_leg.py | 15 +- server/memory/app/search/tiers.py | 2 + server/memory/app/served_reads.py | 10 +- server/memory/app/stack.py | 9 +- server/memory/domain/definition_check.py | 4 + server/memory/domain/read_receipts.py | 122 ++ server/memory/store/read_receipts.py | 70 + server/memory/store/shared.py | 8 +- server/settings/catalog.py | 4 + tests/analyzer/shapes.txt | 312 +++-- tests/integration/test_read_receipts.py | 638 +++++++++ tests/unit/degraded_unnoted.txt | 3 + tests/unit/snapshots/live_settings.json | 1 + tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_cell_scan_tables.py | 1 + tests/unit/test_erasure_late_steps.py | 68 + tests/unit/test_erasure_step_order.py | 4 + tests/unit/test_erasure_verify.py | 4 +- tests/unit/test_knowledge_mirrors.py | 2 + tests/unit/test_pg_durable_reads.py | 3 +- tests/unit/test_read_receipts.py | 1224 +++++++++++++++++ tests/unit/test_schema_baseline.py | 2 + tests/unit/test_served_reads.py | 15 +- tests/unit/test_term_leg.py | 32 +- 75 files changed, 3581 insertions(+), 232 deletions(-) create mode 100644 docs/architecture/read-receipts.md create mode 100644 schemas/migrations/122_read_receipts.sql create mode 100644 server/knowledge/app/read_receipts.py create mode 100644 server/memory/app/read_receipts.py create mode 100644 server/memory/domain/read_receipts.py create mode 100644 server/memory/store/read_receipts.py create mode 100644 tests/integration/test_read_receipts.py create mode 100644 tests/unit/test_read_receipts.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf25ce1961d..2f4d65d4025 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1175,6 +1175,7 @@ jobs: tests/integration/test_cross_principal_leakage.py tests/integration/test_memory_get.py tests/integration/test_served_reads.py + tests/integration/test_read_receipts.py tests/integration/test_memory_by_id.py tests/integration/test_memory_bulk.py tests/integration/test_memory_pin.py diff --git a/docs/architecture/clickhouse.md b/docs/architecture/clickhouse.md index 0a94bb67b27..42ed10a909a 100644 --- a/docs/architecture/clickhouse.md +++ b/docs/architecture/clickhouse.md @@ -41,7 +41,7 @@ Retention is in [Partitioning and TTL](#partitioning-and-ttl). | Tracker | `qa_sources`, `qa_item_embeddings`, `qa_link_candidates`, `qa_test_daily`, `qa_rollup_days`, `qa_fail_hours` | `tracker.source.add`, `tracker_embed`, `tracker_links`, `tracker_test_daily` | | Runs, tasks, briefs | `agent_runs`, `agent_turn_usage`, `session_outcomes_by_user`, `procedure_runs`, `tasks`, `task_events`, `task_leases`, `agent_run_claims`, `task_inboxes`, `session_briefs`, `context_blobs` and neighbours | `run.*`, `task.*` / `inbox.*`, `session.brief_*`, `context.offload`, `reflection_distill` | | Namespaces, auth, governance | `namespaces`, `namespace_grants`, `namespace_policies`, `namespace_types`, `namespace_snapshots`, `namespace_calibration_*`, `service_accounts`, `user_state`, `revoked_tokens`, `signing_keys`, `auth_attempts`, `runtime_overrides`, `oauth_state`, `idempotency`, `policy_decisions` and neighbours | `namespace.*`, `grants.*`, sign-up and claim flows, `recalibration`, the idempotency cache | -| Telemetry, audit, cost | `events`, `agent_events`, `agent_cost_rollup_daily`, `audit_log`, `audit_checkpoints`, `search_trace_log`, `memory_exposures`, `memory_usage_events`, `memory_usage_totals`, `memory_served_daily`, `code_search_trace`, `worker_status` and neighbours | The events stream, the op ledger, `observability/audit.py`, `audit_verifier`, the supervisor | +| Telemetry, audit, cost | `events`, `agent_events`, `agent_cost_rollup_daily`, `audit_log`, `audit_checkpoints`, `search_trace_log`, `memory_exposures`, `read_receipts`, `memory_usage_events`, `memory_usage_totals`, `memory_served_daily`, `code_search_trace`, `worker_status` and neighbours | The events stream, the op ledger, `observability/audit.py`, `audit_verifier`, the supervisor | | Service levels | `loom_telemetry.sli_minute` (its own database: telemetry Loom derives from its tables lives outside `loom`) | `sli_minute_refresh`, once a minute over the `agent_events` request rows with an SLO class | | Erasure | `erasure_requests`, `erasure_reversals` | `erasure.request`, `erasure_recovery`, `memory.restore` | | Provider caches | `embedding_cache`, `llm_response_cache` | The embedder and LLM client wrappers | @@ -140,8 +140,11 @@ two groups: `memory_projection_failures`, the graph Undo markers, the `namespace_write_marks` flush, the usage-event flush, the carry-acknowledgement publish and withdraw, every waited entity-graph insert (`memory.set`, `memory.bulk_set`; `graph_insert_settings` - with `wait=True`), and a follow plan's successor inserts (`entity_triple_memories`, - `entity_triple_rows`, `entity_triples`). + with `wait=True`), a follow plan's successor inserts (`entity_triple_memories`, + `entity_triple_rows`, `entity_triples`), and the `read_receipts` sender, which sends + one insert each half second per process and so holds one connection whatever the read + rate + ([read receipts](read-receipts.md#cost)). ClickHouse collects the concurrent inserts into one table in one part per partition and answers each once those parts are written. On return the row is as durable and as @@ -160,9 +163,9 @@ when a buffer fills before the wait ends, at most one per insert when writes are The insert also sends `async_insert_max_query_number = 10000`, so at high rates the window, not ClickHouse's default of 450 statements, decides the flush. -Two windows: the usage-event flusher and shutdown drain and the write-mark flush wait up -to `ch_batched_insert_background_wait_max_ms` (200 ms, ClickHouse's own default), so they -collect more rows per part. Every other batched or waited async insert waits at most +Two windows: the usage-event flusher and shutdown drain, the write-mark flush and the +`read_receipts` sender wait up to `ch_batched_insert_background_wait_max_ms` (200 ms, +ClickHouse's own default), so they collect more rows per part. Every other batched or waited async insert waits at most `ch_batched_insert_wait_max_ms` (50 ms), the `agent_events` timer flush included (`flush_now` waits for a flush in flight), and so does a usage-event flush a request makes because the buffer is full. The two windows are two insert shapes, so they fill @@ -350,17 +353,17 @@ conversations and the graph have no TTL. They leave only by an explicit delete, writer-set expiry (`ttl_seconds`, applied by `memory_expiry_sweep` per the row's `on_expire`) or erasure. Tables with a schema TTL hold telemetry, caches or runner state: -| Window | Tables | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| 60 minutes | `code_search_memo` | -| 3 days | `memory_webhook_outbox`, `memory_webhook_attempts` | -| 7 days | `llm_response_cache`, `code_scip_parts` | -| 30 days | `events`, `embedding_cache`, `memory_drops`, `memory_extraction_queue`, `memory_ask_precedents`, `worker_status`, `code_scip_batches` | -| 90 days | `erasure_requests`, `oauth_state`, `policy_decisions` | -| 180 days | `search_trace_log`, `memory_exposures`, `memory_exposure_breadth_hourly`, `consolidation_runs`, `code_search_trace`, `code_search_outcome` | -| 400 days | `loom_telemetry.sli_minute` | -| 5 years | `erasure_reversals` | -| other | `idempotency` (at `expires_at`), `revoked_tokens` (10 days past token expiry), `context_blobs` (1 day past `expires_at`) | +| Window | Tables | +| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 60 minutes | `code_search_memo` | +| 3 days | `memory_webhook_outbox`, `memory_webhook_attempts` | +| 7 days | `llm_response_cache`, `code_scip_parts` | +| 30 days | `events`, `embedding_cache`, `memory_drops`, `memory_extraction_queue`, `memory_ask_precedents`, `worker_status`, `code_scip_batches` | +| 90 days | `erasure_requests`, `oauth_state`, `policy_decisions` | +| 180 days | `search_trace_log`, `memory_exposures`, `memory_exposure_breadth_hourly`, `read_receipts`, `consolidation_runs`, `code_search_trace`, `code_search_outcome` | +| 400 days | `loom_telemetry.sli_minute` | +| 5 years | `erasure_reversals` | +| other | `idempotency` (at `expires_at`), `revoked_tokens` (10 days past token expiry), `context_blobs` (1 day past `expires_at`) | Operators can add retention to `audit_log`, `agent_events`, `memory`, `memory_embeddings`, `conversations`, `chunks` and `documents` with `LOOM_RETENTION__DAYS`, and tiering @@ -705,8 +708,9 @@ with `purge=true`, stale vector caches, runner state, and the supersession rows remain authoritative; the counters on `memory` are a derived projection. - **Erasure purges** remove rows. On `erasure/store/mutations.py::LIGHTWEIGHT_PURGE_TABLES` (vector, - chunk, summary and evidence tables) a purge uses lightweight `DELETE FROM`, which writes - only the row mask: rows vanish from every read at once and bytes leave at the next merge. + chunk, summary and evidence tables, and read receipts) a purge uses lightweight + `DELETE FROM`, which writes only the row mask: rows vanish from every read at once and + bytes leave at the next merge. Narrow tables keep `ALTER TABLE … DELETE`. The saga polls each mutation by an embedded tag, and a residue census checks the result. - **A refused knowledge write's own chunks**: under the Postgres authority, a write diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md new file mode 100644 index 00000000000..2f40f58e724 --- /dev/null +++ b/docs/architecture/read-receipts.md @@ -0,0 +1,374 @@ +# Read receipts + +A read receipt records which revision of an item a read's answer carried: the memory +row's version and content hash, or the document's revision, with the request, the run and +the reader. It answers "which revision of this did that run see" after the item has +changed, which a record of keys alone cannot: once a second revision of a key is written, +a run that read the first looks the same as one that read the second. + +A receipt holds identifiers and a hash. It never holds content, a prompt or query text. +Every caller of a receipted op leaves one: an agent, an evaluation, a person in the +dashboard. It records that the server built the answer, not that the client received it. + +```mermaid +flowchart LR + R["the read's legs
(hold the rows)"] -->|"note the revision held"| N["notes of the request"] + A["the op's answer"] -->|"its items"| W["the op's wrapper"] + N --> W + W -->|"after the answer"| Q["queue of the process"] + Q -->|"one sender, one insert each half second"| T["loom.read_receipts"] +``` + +## What gets a receipt + +Two things meet when a receipted op returns (`records_receipts` in +`server/memory/app/read_receipts.py`, applied where the op is declared): + +- **A note.** The code that holds a row while the op runs notes the revision it holds + (`note_row`, `note_selected`, `note_memory`, `note_document`). Nothing is read again to + fill a revision in, so a receipt never names a revision written after the read. +- **An item.** The op's answer names the items it carries. A hit the op trimmed, a row + past a section budget and a candidate that did not rank are not items. + +| Op | Items of the answer | Where the revision is noted | +| --------------------------------------------------- | ------------------------------------------ | --------------------------------------------- | +| `memory.search`, `memory.ask` | the hits returned | the fact leg, the term leg, a whole-body read | +| `memory.brief` | the hits its evidence is made from | the same search | +| `search.query` | the memory hits and document hits it keeps | the memory search; the document search | +| `memory.get`, `memory.get_by_id`, `memory.bulk_get` | the rows served | the handler | +| `context.pack` | the stored rows its text prints | its searches, its pinned and recent row reads | +| `memory.stack` | its pinned, recent and procedure entries | its row reads | +| `memory.for_file` | the rows its block prints | its row read | +| `procedure.match` | the procedures matched | its row read | +| `knowledge.search` | the chunks returned | where the search builds its hits | +| `knowledge.get` | the document | the handler, for an ordinary document | + +The op the caller invoked writes the receipts. A handler another op runs (the search +inside `memory.ask`, the stack inside `context.pack`) notes into the outer op's notes and +writes nothing itself, so one answer has one set of receipts. + +An answer that names a row and leaves its value out (`fields` on `memory.get`, +`omit_high_value` on `memory.get_by_id`) still gets the row's receipt: the read held +that revision. + +### Which revision an item takes + +Notes are kept per item and version, because one key can hold a row for each writer and +session, and one op can read a row through more than one table. + +- **An item that carries its version records that version**: a search hit, a served row, + a document hit's revision. The note of that version adds the hash, or a document's + stored version. With no such note the version is recorded alone. +- **An item named without a version takes what the notes of its key agree on**: a row of + a context pack, a stack entry, a matched procedure, a row a file block prints. + - One row noted: that row's version and hash. + - Several versions noted with one content hash: the hash, with version 0. This is one + revision read through the row and through its search document, which sit at + different versions (see [the version and the hash](#the-version-and-the-hash)). + - Anything else, such as two writers' rows under one key: not recorded (version 0, no + hash). + - No note under the key: no receipt. +- **A chunk hit of `memory.search`** is filed under its parent row's key. The read held a + passage, not the row, so its receipt has version 0 and no hash, and it is left out when + the answer also carries the row itself. +- **A hit whose text another stored row gave** records that row's revision: a hit + expanded to its whole body (`bodies`) records the body row read for it, and a governed + definition records the namespace's shared copy that the term leg served, never another + row under the same key. + +### The version and the hash + +The hash identifies the content. Two receipts with the same non-empty hash name one +revision of the content, whichever op and table read it. It is the row's content hash as +stored (`row_content_sha256` in `server/memory/domain/trust.py`), the hash an attestation +binds to. A shared copy stores no hash, so a governed definition's receipt carries the +hash of the copy's stored text, which equals its source row's unless the value is one of +those listed below. + +The version names the stored row the read held. Which table that is depends on the read: + +| The read | `version` is | +| -------------------------------------------------------------------- | --------------------------------- | +| A key lookup, a pinned or recent row, a whole body | the `loom.memory` row's | +| A search hit | the row's search document's | +| A shared-scope hit, a governed definition (`kind` is still `memory`) | the shared copy's (`loom.shared`) | +| An item named without a version | the one row noted, else 0 | + +A search document is written at its row's version. A later write that copies the row and +leaves its content alone (a change of expiry, a verification, tags, extracted entities, a +re-embedding) moves the row and its search document to different versions, and the +version history (`loom.memory_versions`) holds only the row's. So: + +- match two receipts on the hash where both have one; +- use the version to tell reads of one stored row apart, or to fetch the row from the + table the read used; +- match a hash a client holds from `memory.get` by version against that op's receipt. + `memory.get` computes its hash from the decoded value, which differs from the stored + one for a value whose stored form differs from the written one: an object with a null + member or an empty nested object, a float with no fraction, a dotted key, an ISO + timestamp string. + +The hash is left empty, and the version still recorded, for: + +- a high-sensitivity row: the hash of a short secret names it as well as the value does; +- a redacted row: its stored hash is the removed text's; +- a search hit ranked by a leg that reads no hash (the main fact leg and the + `anchor_first` and `recent_first` tiers read it; the other legs record the version + only); +- a hit of a later page of a paged search: the page was kept with each hit's version and + without its hash; +- a row whose stored hash is unset and whose value the read did not hold whole. + +### Documents + +A document receipt names the source URI, the revision and the chunk, with the stored +version of that revision (`doc_version`): two writes that race can number one revision, +and the stored version tells them apart. When one answer holds two stored versions of one +revision, `doc_version` is 0: not recorded. A document receipt has no hash. + +## What gets none + +- **A request that runs a mirror leg**, for any item of its answer, a memory row or an + ordinary document included + ([access follows the source](document-sources.md#the-mirror): a marked request writes + nothing that could depend on what a mirror holds). With auth on, that is every request + of `knowledge.search`, `knowledge.get`, `search.query`, `memory.ask` (which reads + documents unless told not to), and `context.pack` and `memory.stack` with + `include_knowledge`, while a namespace in the request's scope has an active mirrored + source. The notes of code running under private work are dropped + (`public_diagnostics()`), and a row under a mirror's or a code store's name is left + out before the rows are queued. The table refuses such a row too + (`ordinary_namespaces_only`), and with it every row of the insert it arrived in, so + the check before the queue is the one that decides. A source copy served by `knowledge.get` is never noted. +- **Document passages inside `memory.ask`, `context.pack` and `memory.stack` answers.** + The memory rows of the same answer get their receipts; the passages get none. + `knowledge.search`, `knowledge.get` and `search.query` receipt documents. +- **A `memory.get` of a `chunk:` key**, which serves a passage and its neighbours. +- **Reads that list or inspect rather than recall**: `memory.list`, `memory.keys`, + `memory.inspect`, exports, version history, `memory.related`, `memory.recall`, + `memory.timeline`, `facts.*`, `memory.record.query`, `procedure.list`, + `knowledge.synthesize`, `knowledge.query`, and code answers that print memories. +- **A read made while receipts are not written**: `read_receipts_enabled` is off, a + replica older than the table's migration serves (see + [rolling upgrades](#rolling-upgrades)), the process's queue is full, or the insert + failed. + +A missing receipt means "not recorded". It is never an error for the read, and a reader +of the table must not take it to mean the item was not served. + +## The stored row + +`loom.read_receipts` is a plain MergeTree sorted by `(org, namespace, kind, item_key, +ts)`, so an item's reads are one range of the primary key, filtered by revision inside +it. A bloom filter on `run_id` serves "what did this run read". A row is filed under the +namespace that holds the item, so one read over several namespaces writes under each. + +| Column | Meaning | +| ----------------------------------- | ------------------------------------------------------------------------------------------------- | +| `ts` | When the receipt was built, to the second. | +| `org`, `namespace` | The namespace that holds the item. | +| `kind`, `item_key` | `memory` and the memory key, or `document` and the source URI. | +| `version` | Memory: the version of the stored row the read held. Document: its revision. 0: not recorded. | +| `content_sha256` | Memory: the stored content hash. Empty: not recorded. | +| `doc_version`, `chunk_idx` | Document: the stored version of the revision (0: not recorded), and the chunk; `-1` is the whole. | +| `operation`, `request_id`, `run_id` | The op the caller invoked, its request, and the run the request is filed under (`-`: none). | +| `actor`, `token_id` | The token's subject and id. | +| `agent`, `user_id`, `session_id` | The identity the read ran as: the input's, else the token's read scope, else the request's. | + +The reader comes from the request: `actor` and `token_id` from the token, `agent` as the +served-reads log names it (`reader` in `server/memory/app/served_reads.py`). A document +op's input names no agent, user or session, so its receipt takes the ones the request +named to the transport. A read that names no user has `user_id` `-`: the token's subject +is in `actor`, so reads made as an end user stay apart from reads a token of the same +name made. Over MCP, a document read that names no session carries the id of its +connection, which groups one client's reads. + +The run is the one every ledger files the request under (`ledger_run_for` in +`server/observability/run_context.py`): the request's own `run_id` when it carries one, +else the run bound to the request (the `X-Loom-Run-Id` header, or an MCP session's run). +A receipt, the op ledger row and the exposure row of one request therefore name one run. +A read's `run_id` also filters the rows it reads, so a read that filters on another run's +rows is filed under that run. + +**Lifetime.** A receipt is a trace, not memory. Rows expire 180 days after `ts`; whole +monthly parts are dropped, so a row can outlive that by the rest of its month. + +## Reading the table + +No op serves this table; it is read with SQL. Bound every read by time: an item that is +read often has many rows, and a run's rows sit in every namespace it read. + +Which revision of an item a run saw: + +```sql +SELECT ts, operation, version, content_sha256 +FROM loom.read_receipts +WHERE org = {org:String} AND namespace = {namespace:String} + AND kind = 'memory' AND item_key = {key:String} + AND run_id = {run:String} AND ts >= {since:DateTime} +ORDER BY ts +``` + +Which runs were served a revision, by its hash: + +```sql +SELECT run_id, min(ts) AS first_read, uniqExact(request_id) AS requests +FROM loom.read_receipts +WHERE org = {org:String} AND namespace = {namespace:String} + AND kind = 'memory' AND item_key = {key:String} + AND content_sha256 = {sha256:String} AND ts >= {since:DateTime} + AND run_id != '-' +GROUP BY run_id +ORDER BY first_read +``` + +What a run read: + +```sql +SELECT namespace, kind, item_key, version, content_sha256, min(ts) AS first_read +FROM loom.read_receipts +WHERE org = {org:String} AND run_id = {run:String} + AND ts >= {since:DateTime} AND ts < {until:DateTime} +GROUP BY namespace, kind, item_key, version, content_sha256 +ORDER BY first_read +``` + +- **Count revisions, not rows.** `request_id` is the caller's when the caller sends one, + so it is not unique, and a request sent again writes its rows again. Group by + `(run_id, kind, namespace, item_key, version, content_sha256)`. +- **Never ask for `run_id = '-'` alone.** It is every read made outside a run. A read by + run prunes by month and org and then tests the bloom filter on what is left. +- **The query behind a read** is not in a receipt. The exposure row of the same + `request_id` in `loom.memory_exposures` carries the query's digest and the keys + returned. + +## Cost + +- **On the request's path**, a note is a dictionary write, and the main fact leg selects + one more column, `content_sha256`, from the search rows it already reads. No read is + added. While receipts are not written, nothing is noted either. +- **After the answer**, the op queues its rows. One sender per process waits half a + second and sends what has queued in one insert (a waited async insert, + [batched inserts](clickhouse.md#batched-inserts)). Receipts therefore hold one pooled + connection and send at most two inserts a second whatever the read rate; the batch + grows with the rate instead. A receipt can be read about a second after its answer. +- **CPU.** An insert costs the process about two milliseconds whatever it carries, which + is why the answers of half a second share one. Measured in one process against a local + ClickHouse with two items an answer, receipts cost 0.5 ms of process CPU a read at 18 + reads a second and 0.2 ms at 200 reads a second. +- **A slow or failing store loses receipts, not reads.** The queue holds at most 10,000 + rows; past that an answer's rows are dropped. The client sends an insert again once + when its connection drops; an insert that fails after that, or times out, loses its + batch, which is not queued again: a store that is down gets no backlog, and a batch + that landed late is not written twice. Each loss is counted and logged at the first, + the tenth, the hundredth occurrence and so on. +- **Storage** is about 40 to 60 bytes a row after merges with the server's default + compression, up to about 90 where every part is LZ4-compressed. Rows a day are the + receipted reads a day times the items an answer carries: 100 reads a second with 5 + items each write 43 million rows a day and hold about 7.8 billion rows, 310 GB at 40 + bytes a row, over the 180 days. + +| Setting | Default | Effect | +| ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `read_receipts_enabled` | on | Off stops new rows: at once in the process that took the change, within one refresh of the overrides in the others. Stored rows expire by the table's TTL. | + +## Checking that receipts are written + +```sql +SELECT operation, count() AS receipts, max(ts) AS latest +FROM loom.read_receipts +WHERE org = {org:String} AND ts >= now() - INTERVAL 10 MINUTE +GROUP BY operation +``` + +When reads answer and this returns nothing, the server log says why: + +| Log line | Meaning | +| --------------------------------------------------------------- | ------------------------------------------------------------------- | +| `read receipts are not written while a live replica is below …` | An older replica still serves, or no replica heartbeat was read. | +| `read receipts dropped past the queue bound` | The store is slower than the reads; the line carries the rows lost. | +| `read-receipt write failed` | An insert failed; the line carries the count and the error. | + +No line and no rows: `read_receipts_enabled` is off, or the requests run a mirror leg. + +## Erasure + +`loom.read_receipts` has a namespace step and a user step, both `read_receipts.delete`, +and a census row in each scope. + +```mermaid +flowchart LR + A["erasure recorded"] --> B["step: delete every
receipt of the reader"] + B --> C["census: count the reader's receipts
stamped before the erasure was recorded"] + R["the user's later reads"] -.->|"new receipts,
not counted"| C +``` + +- A namespace erasure deletes the receipts filed under the namespace: the receipts of + its items, whoever read them. Receipts of reads its agents made of other namespaces' + items are filed under those namespaces and stay. +- A user erasure deletes the receipts of reads the user made: as the end user the read + ran as (`user_id`), or as the token's subject (`actor`), under any spelling the + directory ties to the user, all compared lower-cased (`RECEIPT_READER` in + `server/erasure/store/predicates.py`). It fails closed when the directory cannot be + read. +- The user step deletes every receipt of the reader it finds. The census counts the + reader's receipts stamped before the second the erasure was recorded in + (`RECEIPT_READER_BEFORE`, `recorded_scope` in `server/erasure/store/mutations.py`). A + user who keeps reading after asking to be erased writes new receipts; those are later + activity, not what the erasure was asked to delete, so they do not fail it. They + expire with the table, or leave with the user's next erasure. +- A receipt of another reader that names a row the user wrote keeps the key, version and + hash until the table's TTL, as the exposure ledger keeps the key. The hash still + matches the erased text, so someone who reads the table and guesses the text can + confirm the guess. The hash of a high-sensitivity row is never stored. +- Both steps delete with a lightweight `DELETE FROM` in every mode + (`LIGHTWEIGHT_PURGE_TABLES` in `server/erasure/store/mutations.py`). A namespace's or a + reader's rows sit in every monthly part, so an `ALTER TABLE … DELETE` would rewrite the + whole table for one erasure. The rows leave every read at once; their bytes leave at + the part's next merge, when the reclaim worker applies the mask, or with the part. + +A receipt is written after the answer. One built by a read that was in flight when an +erasure finished can land after the erasure's census; it holds identifiers and a hash, +and expires with the table. A receipt stamped before a user's erasure was recorded that +lands between the step and the census (its process had not sent it yet, or the store +was slow) is counted: the erasure fails with `loom.read_receipts` in its `residue` and +completes when run again. + +## Rolling upgrades + +An older build's erasure saga has no step for `loom.read_receipts`, so the table gains no +row while such a replica serves: a receipt is written only when every live replica's +schema is at the table's migration or later (`every_live_replica_at` in +`server/core/instances.py`), and none when no heartbeat can be read. The process logs +once that it is not writing. + +Before a rollback to an older build, the operator turns `read_receipts_enabled` off and +runs `TRUNCATE TABLE loom.read_receipts`, and runs it once more after the first older +replica serves, for what this build wrote in between +([upgrades](../operations/upgrades.md#rollback)). + +## Invariants + +- A receipt's revision is one a read of that request held. It is never looked up + afterwards and never inferred from the item's latest value or from another row under + the same key. +- A receipt holds no content, no prompt and no query text. +- A request that runs a mirror leg writes no receipt. +- A receipt never fails the read it describes, and receipts hold one connection of the + process and send at most two inserts a second, so they do not take connections from + reads. + +## Source entry points + +- `server/memory/app/read_receipts.py` (`records_receipts`, the `note_*` helpers, the + per-op item extractors, the sender) +- `server/memory/domain/read_receipts.py` (`Item`, `Noted`, `revision_of`, `receipts`) +- `server/memory/store/read_receipts.py` +- `server/knowledge/app/read_receipts.py` (the document ops' wrapped handlers) + +## Related + +- [Memory architecture: erasure saga](memory-architecture.md#erasure-saga) +- [Rolling upgrades](rolling-upgrades.md) +- [Storage layout](storage-layout.md) +- [Runs](../features/runs.md) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 1a19aa5f188..010e3577030 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1092,6 +1092,14 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline answer cited), and N-1 credits the same keys as N. `tests/unit/test_usage_credit_retraction_sql.py` and `tests/unit/test_usage_fold_sql.py` check N's side, and the mixed-version gate does not check this rule. +73. **Read receipts** (`loom.read_receipts`, migration `122_read_receipts.sql`): N-1's + erasure saga has no step for the table. So while any live replica's schema version is + below 122, or no heartbeat has been read, N writes no receipt, as it records no miss + under rule 48; reads answer as before. Before a rollback, turn + `LOOM_READ_RECEIPTS_ENABLED` off and truncate the table, then truncate it again after + the first N-1 replica serves ([read receipts](read-receipts.md#rolling-upgrades), the + [rollback note](../operations/upgrades.md#rollback)). + `tests/unit/test_read_receipts.py` checks the gate; the mixed-version gate does not. ## What checks them diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md index 2fbc65800b3..a479b5db4df 100644 --- a/docs/architecture/storage-layout.md +++ b/docs/architecture/storage-layout.md @@ -1165,6 +1165,7 @@ it holds no provider identity or credential. | `policy_decisions` | MT `(org, namespace, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | no content | — | policy gate decisions, 90-day TTL; named in `server/identity/store/policy.py` | | `memory_exposures` | MT `(org, namespace, actor, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `memory_exposures.delete`, user scope too | — | which actor was shown which memory, 180-day TTL; named in `server/identity/domain/policy_rules.py`, `server/memory/app/exposure_ledger.py` | | `memory_exposure_breadth_hourly` | AMT `(org, namespace, actor, agent, hour)`, by `toYYYYMM(hour)`, TTL | stays | Derived | no content | — | hourly `uniq` rollup of exposures; named in `server/memory/app/exposure_ledger.py` | +| `read_receipts` | MT `(org, namespace, kind, item_key, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `read_receipts.delete`, user scope too | — | which revision of an item a read's answer carried (version and hash, no content), 180-day TTL; named in `server/memory/store/read_receipts.py`, `server/erasure/store/steps_ledgers.py` | | `memory_usage_events` | MT `(org, namespace, memory_id, ts)`, by `toYYYYMM(ts)` | stays | Log | census, `memory_usage_events.delete`, user `memory_usage_events.scrub` | — | usage events per memory, an agent's label with its run id and principal; wave 4 puts the pair digest on each `acted` event; named in `server/memory/store/usage.py`, `server/memory/store/usage_credit.py` | | `memory_usage_totals` | SMT `(org, namespace, memory_id)` | stays | Derived | no content | — | `SummingMergeTree` totals per memory fed by `memory_usage_totals_mv` from `memory_usage_events`; named in `server/memory/store/reads.py`, `server/memory/workers/usage_fold.py` | | `memory_served_daily` | SMT `(org, namespace, memory_id, agent, day)`, by `toYYYYMM(day)` | stays | Log | no content | — | served counts per memory, agent and day, inserted directly by the agent read ops (`server/memory/app/served_reads.py`) and summed by `SummingMergeTree`; a log on `SummingMergeTree`, which keeps its layout; named in `server/memory/store/served.py`, `server/memory/app/health.py` | diff --git a/docs/features/memory/retention-and-erasure.md b/docs/features/memory/retention-and-erasure.md index 023f21944ad..069e5f21711 100644 --- a/docs/features/memory/retention-and-erasure.md +++ b/docs/features/memory/retention-and-erasure.md @@ -28,7 +28,8 @@ A row leaves the served set only when: - **the owner or operator configured one**: see [configured retention](#configured-retention). Operational tables (telemetry, caches, queues) have fixed TTLs: `loom.search_trace_log`, -`loom.memory_exposures`, `loom.code_search_trace` and `loom.code_search_outcome` 180 days; +`loom.memory_exposures`, `loom.read_receipts`, `loom.code_search_trace` and +`loom.code_search_outcome` 180 days; `loom.erasure_requests` and `loom.policy_decisions` 90 days; `loom.memory_drops`, `loom.memory_extraction_queue`, `loom.events` and `loom.embedding_cache` 30 days; `loom.llm_response_cache` 7 days. The @@ -150,6 +151,21 @@ stamped with no user (`-`) under one of the user's `(namespace, key)` pairs, who memory they belong to: a `-` chunk can hold the user's text, and the write path retires those as the writer's too. Chunks stamped with another user stay. +A `user_id` erasure deletes the read receipts of reads the user made, and a `namespace` +erasure those of the namespace's items +([read receipts](../../architecture/read-receipts.md#erasure)). Three things stay until +the table's 180-day TTL: + +- another reader's receipt of a row the user wrote, with the row's key, version and + content hash (the hash of a high-sensitivity row is never stored); +- a receipt of a read that was in flight when the erasure finished; +- receipts of reads made from an erased namespace of another namespace's items. + +A user who keeps reading after asking to be erased writes new receipts. The erasure +deletes the receipts it finds and checks those stamped before it was recorded, so the +later reads do not fail it; their receipts expire with the table or leave with the +user's next erasure. + A `user_id` erasure also retires the consolidated summaries built from the user's memories, under whatever identity wrote them ([which ones](../../architecture/memory-architecture.md#background-passes)), with what diff --git a/docs/features/runs.md b/docs/features/runs.md index 3b7bdc9424c..4ad6c5ff532 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -26,6 +26,11 @@ A run row lives in `loom.agent_runs`. Most of what `run.get` shows is derived at `recalled` is `-1` when `LOOM_SEARCH_TRACE_LOG_ENABLED` is off and no `recalled_keys` were sent. +Which revision of each memory row and document the run's reads carried is kept apart, in +`loom.read_receipts` under the run's `run_id`, so it can still be told after the item +changes ([read receipts](../architecture/read-receipts.md#reading-the-table)). `run.get` +does not serve it. + ## Budgets `run.begin` takes an optional `budget_usd` (model spend) and `budget_seconds` (how long the run may take). `run.get` @@ -408,3 +413,5 @@ See [configuration: dedup and expiry](../reference/configuration.md#dedup-and-ex a deciding run relied on. - [Memory architecture](../architecture/memory-architecture.md) — the usage-event fold and the tables behind it. +- [Read receipts](../architecture/read-receipts.md) — the revision of each item a run's + reads carried. diff --git a/docs/operations/upgrades.md b/docs/operations/upgrades.md index 117323731b0..9b1cd4f6475 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -422,6 +422,11 @@ fed; request again each one run without `purge` once the newer build serves, as An erasure the previous build runs leaves the user's principal and run on the usage labels, or the namespace's usage events; run it again once the newer build serves, as in step 19 (rule 72). +Before rolling back to a build without read receipts, turn `LOOM_READ_RECEIPTS_ENABLED` +off and run `TRUNCATE TABLE .read_receipts` (`loom.read_receipts` by +default), then run it again once the first replica of the previous build serves, for the +rows written in between: that build's erasure has no step for the table +([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 73). Do not roll back past the build that adds the document bucket while any catalog row names an object in it: an older build answers those downloads `410 BLOB_GONE`, its erasure deletes the rows and cannot reach their objects, and its sweep never walks the diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index c0cd7de8dd9..f8ac3a2e5d8 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1539,6 +1539,7 @@ memory.search: legs, fusion, ranking and gates. | `LOOM_MEMORY_SEARCH_SET_EXPANSION_MIN_SIMILARITY` | `float` | `0.5` | live | Similarity a set-expansion leg's row must exceed to join the pool. | | `LOOM_MEMORY_SEARCH_SET_EXPANSION_MAX_ADDED` | `int` | `5` | live | Most rows the set-expansion legs add to one search. | | `LOOM_MEMORY_EXPOSURE_LEDGER_ENABLED` | `bool` | `True` | live | Read-side exposure ledger in loom.memory_exposures: one row per read (token subject, returned keys, query digest never the text, scope) plus an hourly per-actor roll-up. Carries no user content. | +| `LOOM_READ_RECEIPTS_ENABLED` | `bool` | `True` | live | Read receipts in loom.read_receipts: one row per memory row or document an agent read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL. | | `LOOM_MEMORY_SEARCH_MIN_SIMILARITY` | `float` | `0.22` | | Cosine floor: hits below it are dropped as noise (ANN always returns top_k). The backstop when rerank is bypassed or fails. | | `LOOM_MEMORY_SEARCH_FLOOR_MODE` | `'readmit' \| 'ids_only' \| 'drop'` | `'readmit'` | live | Sub-floor handling when the caller sets top_k: "readmit" (fill k, tag below_floor), "ids_only" (fill k with empty bodies), "drop". A request's floor_mode overrides. | | `LOOM_MEMORY_SEARCH_EMBED_BOUND_S` | `float` | `2.5` | live | Per-attempt bound (seconds) on the query embedding; after the retries the search answers 503 EMBED_TIMEOUT. 0 = unbounded. | diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 43b007abb5d..1e4fe8cc43e 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -142,7 +142,7 @@ the `loom` tables each view reads, and, for each materialized view, its target, -197 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix. +198 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix. #### Tables @@ -317,6 +317,7 @@ the `loom` tables each view reads, and, for each materialized view, its target, | `qa_test_daily` | `ReplacingMergeTree(version)` | `(org, qa_namespace, test_name, day)` | | | | | `query_history_sources` | `ReplacingMergeTree(version)` | `(org, namespace, name)` | | | | | `query_nodes` | `AggregatingMergeTree` | `(org, namespace, query_hash)` | | | | +| `read_receipts` | `MergeTree` | `(org, namespace, kind, item_key, ts)` | `toYYYYMM(ts)` | `ts + toIntervalDay(180)` | 1 skip index (bloom_filter) | | `revoked_tokens` | `ReplacingMergeTree(version)` | `jti` | | `toDateTime(expires_at) + toIntervalDay(10)` | | | `runtime_overrides` | `ReplacingMergeTree(version)` | `(kind, key)` | | | | | `scim_users` | `ReplacingMergeTree(version)` | `id` | | | | diff --git a/loom.example.yaml b/loom.example.yaml index ca51edd9cc3..3deb7c7df0f 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -4695,6 +4695,12 @@ settings: # Carries no user content. [live] # memory_exposure_ledger_enabled: true + # Read receipts in loom.read_receipts: one row per memory row or document an agent + # read's answer carried, with the revision the read held (version and hash, never + # content or query text). Off stops new rows; stored ones expire by the table's TTL. + # [live] + # read_receipts_enabled: true + # Cosine floor: hits below it are dropped as noise (ANN always returns top_k). The # backstop when rerank is bypassed or fails. [restart] # memory_search_min_similarity: 0.22 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 0cee1e39066..2d002062b03 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6590,6 +6590,11 @@ "type": "integer", "description": "Table slots (32 bytes each). Every process of a server must agree; a mismatch falls back to per-process buckets and shows in /v1/health." }, + "read_receipts_enabled": { + "default": true, + "type": "boolean", + "description": "Read receipts in loom.read_receipts: one row per memory row or document an agent read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL." + }, "readiness_check_timeout_s": { "default": 2.0, "exclusiveMinimum": 0, diff --git a/schemas/migrations/122_read_receipts.sql b/schemas/migrations/122_read_receipts.sql new file mode 100644 index 00000000000..fd0fa72f798 --- /dev/null +++ b/schemas/migrations/122_read_receipts.sql @@ -0,0 +1,49 @@ +-- Read receipts (docs/architecture/read-receipts.md). +-- +-- loom.read_receipts: one row per memory row or document chunk an agent read's answer +-- carried, with the revision the read held, written when LOOM_READ_RECEIPTS_ENABLED is +-- on. It holds identifiers and a hash, never content or query text. A row is filed +-- under the namespace that holds the item, so one read over several namespaces writes +-- under each. Sorted by item: an item's reads are one primary-key range, filtered by +-- revision, and the bloom index serves "what was this run served". A trace that expires +-- after 180 days; whole monthly parts drop, so a row can outlive that by the rest of +-- its month. Erased per namespace and per user (user_id or actor). +CREATE TABLE IF NOT EXISTS loom.read_receipts +( + `ts` DateTime DEFAULT now(), + `org` LowCardinality(String), + -- The namespace that holds the item, which is not always the one the read named. + `namespace` LowCardinality(String), + -- 'memory' or 'document'. + `kind` LowCardinality(String), + -- The memory key, or the document's source URI. + `item_key` String, + -- Memory: the row version the read held. Document: its revision. 0: not recorded. + `version` UInt64 DEFAULT 0, + -- Memory: the stored content hash of the row the read held. '': not recorded. + `content_sha256` String DEFAULT '', + -- Document: the stored version of the revision, which tells apart two writes that + -- numbered the same revision. 0 for memory. + `doc_version` UInt64 DEFAULT 0, + -- Document: the chunk served. -1: the whole item. + `chunk_idx` Int32 DEFAULT -1, + -- The op the caller invoked. + `operation` LowCardinality(String), + `request_id` String DEFAULT '', + `run_id` String DEFAULT '-', + -- The reader: the token's subject and id, and the identity tuple it read as. + `actor` String DEFAULT '', + `token_id` String DEFAULT '', + `agent` LowCardinality(String) DEFAULT '', + `user_id` String DEFAULT '-', + `session_id` String DEFAULT '-', + INDEX run_id_bloom_idx run_id TYPE bloom_filter(0.01) GRANULARITY 1, + -- A private mirror's reads are never receipted, and no receipted read serves a code + -- store's rows. + CONSTRAINT ordinary_namespaces_only CHECK NOT match(namespace, '^(acl|crs)-[0-9a-f]{24}$') +) +ENGINE = MergeTree +PARTITION BY toYYYYMM(ts) +ORDER BY (org, namespace, kind, item_key, ts) +TTL ts + INTERVAL 180 DAY +SETTINGS non_replicated_deduplication_window = 1000, ttl_only_drop_parts = 1; diff --git a/schemas/schema.sql b/schemas/schema.sql index 308b2aab92f..8589ad1291c 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -16,13 +16,13 @@ -- Do NOT hand-edit. Edit schemas/migrations/*.sql and re-dump. -- CI verifies this file matches what migrations would produce. -- --- Counts: 197 tables + 5 views + 19 materialized views. +-- Counts: 198 tables + 5 views + 19 materialized views. CREATE DATABASE IF NOT EXISTS `loom`; CREATE DATABASE IF NOT EXISTS `loom_telemetry`; -- ====================================================================== --- Tables (197) +-- Tables (198) -- ====================================================================== -- loom.acl_versions @@ -3944,6 +3944,35 @@ ENGINE = AggregatingMergeTree ORDER BY (org, namespace, query_hash) SETTINGS allow_dimensions_outside_sorting_key = 1, index_granularity = 8192, non_replicated_deduplication_window = 1000; +-- loom.read_receipts +CREATE TABLE IF NOT EXISTS loom.read_receipts +( + `ts` DateTime DEFAULT now(), + `org` LowCardinality(String), + `namespace` LowCardinality(String), + `kind` LowCardinality(String), + `item_key` String, + `version` UInt64 DEFAULT 0, + `content_sha256` String DEFAULT '', + `doc_version` UInt64 DEFAULT 0, + `chunk_idx` Int32 DEFAULT -1, + `operation` LowCardinality(String), + `request_id` String DEFAULT '', + `run_id` String DEFAULT '-', + `actor` String DEFAULT '', + `token_id` String DEFAULT '', + `agent` LowCardinality(String) DEFAULT '', + `user_id` String DEFAULT '-', + `session_id` String DEFAULT '-', + INDEX run_id_bloom_idx run_id TYPE bloom_filter(0.01) GRANULARITY 1, + CONSTRAINT ordinary_namespaces_only CHECK NOT match(namespace, '^(acl|crs)-[0-9a-f]{24}$') +) +ENGINE = MergeTree +PARTITION BY toYYYYMM(ts) +ORDER BY (org, namespace, kind, item_key, ts) +TTL ts + toIntervalDay(180) +SETTINGS non_replicated_deduplication_window = 1000, ttl_only_drop_parts = 1, index_granularity = 8192; + -- loom.revoked_tokens CREATE TABLE IF NOT EXISTS loom.revoked_tokens ( diff --git a/server/cli/hygiene.py b/server/cli/hygiene.py index b7a61dc4304..9999cb09dcc 100644 --- a/server/cli/hygiene.py +++ b/server/cli/hygiene.py @@ -646,7 +646,10 @@ async def _re_verify_run(ch: Any, args: argparse.Namespace) -> int: print(f" {where}: directory unreadable ({error_summary(e)})") rc = 1 continue - with erasure_mutations.purge_scope(purge): + with ( + erasure_mutations.purge_scope(purge), + erasure_mutations.recorded_scope(row["requested_at"]), + ): async with erased_scope(str(row["org"]), scope_type, scope_value, ch=ch) as scope: census, unread = await erasure_census.evidence_census( str(row["org"]), scope_type, scope, ch=ch, spellings=spellings diff --git a/server/core/instances.py b/server/core/instances.py index 4c89fcd1950..6e748356103 100644 --- a/server/core/instances.py +++ b/server/core/instances.py @@ -306,6 +306,15 @@ def live_rows() -> list[dict[str, Any]]: return _live[1] +def every_live_replica_at(migration: int) -> bool: + """Whether every live replica of this deployment runs `migration` or later, as of + the last read. A table that migration adds is written only then: an older replica's + erasure has no step for it, so a row written while one serves could outlive an + erasure it runs. Unknown (no recent heartbeat read) counts as no.""" + live = live_rows() + return bool(live) and all(int(r["schema_version"] or 0) >= migration for r in live) + + def live_hosts() -> int | None: """Distinct hosts with a live serving row in this deployment, as of the last read: a workers-only process (LOOM_SERVES_TRAFFIC=false) shares no diff --git a/server/erasure/app/saga.py b/server/erasure/app/saga.py index cf1453cd2e1..f85d9e2b43c 100644 --- a/server/erasure/app/saga.py +++ b/server/erasure/app/saga.py @@ -398,7 +398,7 @@ async def run_saga( census_purge = applied_purge(input.scope_type, input.scope_value, bool(input.purge)) # The saga id names every mutation this run submits, # so a resumed step finds its own pending mutation instead of adding one. - with erasure_mutations.saga_scope(erasure_id): + with erasure_mutations.saga_scope(erasure_id), erasure_mutations.recorded_scope(requested_at): try: if input.scope_type == "user_id": # A user's erasure purges when asked: the rows leave the parts, not just diff --git a/server/erasure/app/saga_steps.py b/server/erasure/app/saga_steps.py index 00e8e1bbfb6..e01a9b55298 100644 --- a/server/erasure/app/saga_steps.py +++ b/server/erasure/app/saga_steps.py @@ -144,6 +144,14 @@ async def _step_delete_search_misses_by_user(org: str, user_id: str) -> int: return n + await ledger_steps.delete_search_misses_by_user(org, spellings) +async def _step_delete_read_receipts_by_user(org: str, user_id: str) -> int: + """The receipts of the user's reads: as the end user, or as the token's subject under + any spelling the directory ties to the user.""" + return await ledger_steps.delete_read_receipts_by_user( + org, await folded_spellings(org, user_id) + ) + + async def _step_delete_code_links_by_user(org: str, user_id: str) -> int: """The user's code links, erased under the link worker's queue lease, which every cursor write is under: no pass then publishes a cursor it read before the erasure.""" @@ -309,6 +317,7 @@ async def _step_erase_blobs_by_ns(org: str, namespace: _NS) -> int: ("context_blobs.tombstone", ledger_steps.tombstone_context_blobs_by_namespace), ("session_briefs.delete", ledger_steps.delete_session_briefs_by_namespace), ("memory_exposures.delete", ledger_steps.delete_memory_exposures_by_namespace), + ("read_receipts.delete", ledger_steps.delete_read_receipts_by_namespace), ("memory_usage_events.delete", _step_delete_usage_events_by_ns), ("search_trace_log.delete", ledger_steps.delete_search_trace_log_by_namespace), ("code_search_trace.delete", ledger_steps.delete_code_search_trace_by_namespace), @@ -334,6 +343,7 @@ async def _step_erase_blobs_by_ns(org: str, namespace: _NS) -> int: ("context_blobs.tombstone", ledger_steps.tombstone_context_blobs_by_user), ("session_briefs.delete", ledger_steps.delete_session_briefs_by_user), ("memory_exposures.delete", ledger_steps.delete_memory_exposures_by_user), + ("read_receipts.delete", _step_delete_read_receipts_by_user), ("code_search_trace.delete", ledger_steps.delete_code_search_trace_by_user), ("search_misses.delete", _step_delete_search_misses_by_user), ("events.delete", ledger_steps.delete_events_by_user), diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py index 084c163d289..a7a8bd7ac8d 100644 --- a/server/erasure/store/census.py +++ b/server/erasure/store/census.py @@ -19,7 +19,12 @@ from server.core import object_store, pg from server.core.repo_base import _CHClient, _default_client -from server.erasure.store.mutations import namespaces_of, ns_list_predicate, purge_mode +from server.erasure.store.mutations import ( + namespaces_of, + ns_list_predicate, + purge_mode, + recorded_at, +) from server.erasure.store.predicates import ( ANSWER_NS_EQ, LABEL_ACTOR, @@ -28,6 +33,7 @@ NS_EQ, ORPHAN_LEARNINGS, PAYLOAD_UID, + RECEIPT_READER_BEFORE, UID, USER_CHUNKS, USER_COMMUNITY_ROWS, @@ -325,6 +331,16 @@ def owner(self, scope_type: str) -> str | None: "memory_exposures.delete", "memory_exposures.delete", ), + # Which revision of an item a read's answer carried: the namespace's items, and in + # the user scope the reads the user made (as the end user or the token's subject) + # before the erasure was recorded. The user's later calls keep adding rows. + Substrate( + "loom.read_receipts", + "1", + RECEIPT_READER_BEFORE, + "read_receipts.delete", + "read_receipts.delete", + ), # The usage ledger names, on an agent's label, the run and the principal that posted # it: a namespace erasure deletes the namespace's events, a user's scrubs the labels # the user posted (the counts stay, as the totals summed them). @@ -990,6 +1006,8 @@ async def table_residue( # and the principals the user's usage labels carry (`LABEL_ACTOR`). params["spellings"] = list(spellings) params["label_actors"] = label_actors(spellings) + # Where the count of the user's read receipts stops (`RECEIPT_READER_BEFORE`). + params["recorded_at"] = recorded_at() out: dict[str, int] = {} # A purge leaves nothing behind, so its census counts every row, not the # live ones. diff --git a/server/erasure/store/mutations.py b/server/erasure/store/mutations.py index dc97da219df..98d6cec37cd 100644 --- a/server/erasure/store/mutations.py +++ b/server/erasure/store/mutations.py @@ -21,6 +21,7 @@ from typing import Any, cast from server.core.ch_names import split_table +from server.core.datetimes import to_naive_utc_second from server.core.repo_base import _CHClient, _default_client from server.erasure.store.predicates import NS_EQ, NS_IN from server.erasure.store.rows import MutationRow @@ -95,6 +96,30 @@ def step_scope(step: str) -> Iterator[None]: _STEP.reset(token) +# When the erasure being counted was recorded. A user keeps making calls after asking to +# be erased, and a table that takes a row on each of them (`loom.read_receipts`) is counted +# up to this time: later rows are new activity, not what the erasure was asked to delete. +_RECORDED_AT: contextvars.ContextVar[datetime | None] = contextvars.ContextVar( + "loom_erasure_recorded_at", default=None +) + + +@contextlib.contextmanager +def recorded_scope(at: datetime) -> Iterator[None]: + """Inside the block, `recorded_at()` is `at`: when the erasure was recorded.""" + token = _RECORDED_AT.set(to_naive_utc_second(at)) + try: + yield + finally: + _RECORDED_AT.reset(token) + + +def recorded_at() -> datetime: + """When the erasure being counted was recorded, naive UTC to the second (now + outside one).""" + return _RECORDED_AT.get() or _now_naive().replace(microsecond=0) + + def mutation_tag( table: str, mutation: str, where: str, params: dict[str, Any] | None = None ) -> str: @@ -206,8 +231,11 @@ async def run_mutation( # once and the bytes leave at the part's next merge # (`vertical_merge_optimize_lightweight_delete`). The narrow tables keep the # mutation: their rewrite is cheap and their bytes matter less. +# `read_receipts` is narrow but large, and one reader's rows sit in every monthly +# part: the mutation rewrote all of a 24M-row table for 7,000 of its rows. LIGHTWEIGHT_PURGE_TABLES: frozenset[str] = frozenset( { + "loom.read_receipts", "loom.memory_embeddings", "loom.memory_chunks", "loom.code_answers", diff --git a/server/erasure/store/predicates.py b/server/erasure/store/predicates.py index 82ef93e0db8..3f5d59db7d8 100644 --- a/server/erasure/store/predicates.py +++ b/server/erasure/store/predicates.py @@ -191,6 +191,17 @@ MISS_ASKER = ( "(has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id)))" ) +# A receipt of a read the user made: as the end user the read ran as, or as the token's +# subject, under any of the user's spellings (`spellings`, as for `MISS_ASKER`). Both +# columns keep the case the token gave them, so both are lower-cased here. +RECEIPT_READER = ( + "(has({spellings:Array(String)}, lowerUTF8(user_id))" + " OR has({spellings:Array(String)}, lowerUTF8(actor)))" +) +# What a census counts of them: the reads stamped before the second the erasure was +# recorded in (`mutations.recorded_at`). The step deletes every one it finds; a user who +# is still reading writes more behind it, and those are not the erasure's to delete. +RECEIPT_READER_BEFORE = f"({RECEIPT_READER} AND ts < {{recorded_at:DateTime}})" # A usage label the user posted: its principal (`actor`, stamped case-folded) is one of # `label_actors(spellings)`. An exact match, so `actor_bloom_idx` serves it. LABEL_ACTOR = "actor IN {label_actors:Array(String)}" diff --git a/server/erasure/store/steps_ledgers.py b/server/erasure/store/steps_ledgers.py index 81d962527f3..85cffadfee5 100644 --- a/server/erasure/store/steps_ledgers.py +++ b/server/erasure/store/steps_ledgers.py @@ -26,6 +26,7 @@ NS_IN, ORPHAN_LEARNINGS, PAYLOAD_UID, + RECEIPT_READER, SUPPORTED_LEARNINGS, UID, label_actors, @@ -219,6 +220,38 @@ async def delete_memory_exposures_by_user( ) +# Read receipts: which revision of which item a read's answer carried, and who read it. +# A namespace's go with the namespace that holds the items; a user's are the reads the +# user made. Both deletes are lightweight in every mode: a namespace's or a reader's rows +# sit in every monthly part, so a mutation would rewrite the whole table. +async def delete_read_receipts_by_namespace( + org: str, namespace: str | Sequence[str], *, ch: _CHClient | None = None +) -> int: + return await delete_scoped( + "loom.read_receipts", + org=org, + scope_where=NS_EQ, + params={"ns": namespace}, + ch=ch, + lightweight=True, + ) + + +async def delete_read_receipts_by_user( + org: str, spellings: Sequence[str], *, ch: _CHClient | None = None +) -> int: + """The receipts of reads made under any of `spellings`, the user's id and its other + spellings.""" + return await delete_scoped( + "loom.read_receipts", + org=org, + scope_where=RECEIPT_READER, + params={"spellings": list(spellings)}, + ch=ch, + lightweight=True, + ) + + # The usage ledger: counts by memory id and, on an agent's label, the run id and the # principal that posted it. A namespace's events go with it; a user's labels keep their # counts, which the totals already summed, and lose the principal, and the run id when diff --git a/server/identity/app/namespace_guide.py b/server/identity/app/namespace_guide.py index 8c8c834d71d..5db15078da3 100644 --- a/server/identity/app/namespace_guide.py +++ b/server/identity/app/namespace_guide.py @@ -139,12 +139,9 @@ def guide_audit_subject(input: NamespaceGuideSetInput, response: dict[str, Any]) def _every_replica_erases_guides() -> bool: - """Whether every live replica runs a build with loom.namespace_guides: an - older one's namespace erasure has no step for the table, so a guide written - while it serves could outlive an erasure it runs. Unknown (no recent - heartbeat read) counts as no.""" - live = instances.live_rows() - return bool(live) and all(int(r["schema_version"] or 0) >= _GUIDES_MIGRATION for r in live) + """Whether every live replica runs a build with loom.namespace_guides + (`instances.every_live_replica_at`).""" + return instances.every_live_replica_at(_GUIDES_MIGRATION) def _stored_summary(input: NamespaceGuideSetInput, row: dict[str, Any] | None) -> str: diff --git a/server/identity/store/namespace_census.py b/server/identity/store/namespace_census.py index c77a3ef5c47..bdf5e7bf4b0 100644 --- a/server/identity/store/namespace_census.py +++ b/server/identity/store/namespace_census.py @@ -112,6 +112,7 @@ async def unregistered_live( { "loom.events", "loom.memory_exposures", + "loom.read_receipts", "loom.search_trace_log", "loom.code_search_trace", "loom.code_search_outcome", diff --git a/server/knowledge/api/ops_knowledge.py b/server/knowledge/api/ops_knowledge.py index 839a6b263e2..a99bff65483 100644 --- a/server/knowledge/api/ops_knowledge.py +++ b/server/knowledge/api/ops_knowledge.py @@ -56,7 +56,6 @@ ) from server.knowledge.app.dedup import handle_knowledge_dedup_list, handle_knowledge_dedup_resolve from server.knowledge.app.document_reads import ( - handle_knowledge_get, handle_knowledge_list, handle_knowledge_outline, ) @@ -67,9 +66,9 @@ handle_knowledge_ingest_status, ) from server.knowledge.app.inspect import handle_knowledge_inspect -from server.knowledge.app.knowledge_search import handle_knowledge_search from server.knowledge.app.move import handle_knowledge_move from server.knowledge.app.query import handle_knowledge_query +from server.knowledge.app.read_receipts import receipted_knowledge_get, receipted_knowledge_search from server.knowledge.app.reads import handle_knowledge_reads from server.knowledge.app.restore import handle_knowledge_restore from server.knowledge.app.synthesize import handle_knowledge_synthesize @@ -109,7 +108,7 @@ session_content=True, input_model=KnowledgeSearchInput, output_model=KnowledgeSearchOutput, - handler=handle_knowledge_search, + handler=receipted_knowledge_search, idempotent=True, required_role=Role.VIEWER, audit=False, @@ -196,7 +195,7 @@ name="knowledge.get", input_model=KnowledgeGetInput, output_model=KnowledgeGetOutput, - handler=handle_knowledge_get, + handler=receipted_knowledge_get, idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/knowledge/app/document_reads.py b/server/knowledge/app/document_reads.py index f4d0649361c..03f08a1252b 100644 --- a/server/knowledge/app/document_reads.py +++ b/server/knowledge/app/document_reads.py @@ -40,6 +40,7 @@ from server.knowledge.domain.chunk_metadata import read_structure from server.knowledge.domain.chunking import Chunk from server.knowledge.domain.document_access import public_tags +from server.memory.app.read_receipts import note_document from server.operations.read_projection import resolve as _resolve_projection if TYPE_CHECKING: @@ -387,6 +388,11 @@ async def handle_knowledge_get(input: KnowledgeGetInput) -> KnowledgeGetOutput: plan = await source_access.prepare(input.org, [input.namespace]) row = await _ordinary_get_row(input) if row is not None or not plan.marked: + if row is not None: + # An ordinary document's read is receipted; a source copy's never is. + note_document( + input.namespace, input.source_uri, revision=row.revision, doc_version=row.version + ) return _get_output(row, input.source_uri) checked = await source_documents.get(plan, input.namespace, input.source_uri) if checked is not None: diff --git a/server/knowledge/app/gaps.py b/server/knowledge/app/gaps.py index b57663b65c8..76a4be3a715 100644 --- a/server/knowledge/app/gaps.py +++ b/server/knowledge/app/gaps.py @@ -273,13 +273,11 @@ async def _registered_creator(org: str, asker: str) -> str: def every_replica_erases_gaps() -> bool: - """Whether every live replica runs a build whose erasure knows the gap tables: a row - written while an older one serves could outlive an erasure it runs. Unknown (no - recent heartbeat read) counts as no.""" + """Whether every live replica runs a build whose erasure knows the gap tables + (`instances.every_live_replica_at`).""" from server.core import instances - live = instances.live_rows() - return bool(live) and all(int(r["schema_version"] or 0) >= GAPS_MIGRATION for r in live) + return instances.every_live_replica_at(GAPS_MIGRATION) async def handle_knowledge_gaps_list(input: KnowledgeGapsListInput) -> KnowledgeGapsListOutput: diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 37498f67d85..05554698199 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -30,6 +30,7 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.knowledge.domain.chunking import embedding_text from server.memory.app.log_once import LogOnce +from server.memory.app.read_receipts import note_document from server.observability import degradations from server.settings import settings @@ -579,6 +580,8 @@ def _as_search_hits(results_per_ns: list[tuple[str, list[ChunkHit]]]) -> list[_S all_hits: list[_SearchHit] = [] for ns, hits in results_per_ns: for h in hits: + # The revision this search read, for a receipt of a hit the answer keeps. + note_document(ns, h.source_uri, revision=h.revision, doc_version=h.doc_version) hit = _SearchHit( source_uri=h.source_uri, chunk_idx=h.chunk_idx, diff --git a/server/knowledge/app/read_receipts.py b/server/knowledge/app/read_receipts.py new file mode 100644 index 00000000000..52148633022 --- /dev/null +++ b/server/knowledge/app/read_receipts.py @@ -0,0 +1,17 @@ +"""knowledge.search and knowledge.get as the ops serve them: with a read receipt. + +The receipt recorder lives with the memory plane's (`server.memory.app.read_receipts`), +which an op declaration of this plane may not import, so the two handlers are wrapped +here and the ops are declared with these. A handler another op calls directly records +nothing of its own: that op's receipt covers what its answer carries. +""" + +from __future__ import annotations + +from server.knowledge.app.document_reads import handle_knowledge_get +from server.knowledge.app.knowledge_search import handle_knowledge_search +from server.memory.app.read_receipts import knowledge_items, records_receipts + +receipted_knowledge_search = records_receipts(knowledge_items)(handle_knowledge_search) +# A get notes the one document it serves. +receipted_knowledge_get = records_receipts()(handle_knowledge_get) diff --git a/server/memory/api/models_brief.py b/server/memory/api/models_brief.py index e6d1e2555c2..97c09669e10 100644 --- a/server/memory/api/models_brief.py +++ b/server/memory/api/models_brief.py @@ -16,7 +16,9 @@ from __future__ import annotations -from pydantic import BaseModel, Field +from typing import Any + +from pydantic import BaseModel, Field, PrivateAttr from server.memory.api.models_common import _Identity @@ -47,6 +49,10 @@ class MemoryBriefInput(_Identity): class MemoryBriefOutput(BaseModel): + # Not on the wire: the search hits `evidence` was made from, for the read receipts + # (an evidence entry names a key, not the row or its version). + _evidence_hits: list[Any] = PrivateAttr(default_factory=list) + # Echo of the request's query. query: str = "" # The answer `memory.ask` synthesised from the memories; '' when none. diff --git a/server/memory/api/ops_ask.py b/server/memory/api/ops_ask.py index 1ae1a89199a..6c4d28aa21e 100644 --- a/server/memory/api/ops_ask.py +++ b/server/memory/api/ops_ask.py @@ -4,6 +4,7 @@ from server.memory.api.models_ask import MemoryAskInput, MemoryAskOutput from server.memory.app.ask.handler import handle_memory_ask +from server.memory.app.read_receipts import records_receipts, search_items from server.memory.app.served_reads import ask_keys, records_served from server.operations.base import Operation, Role @@ -11,7 +12,7 @@ name="memory.ask", input_model=MemoryAskInput, output_model=MemoryAskOutput, - handler=records_served(ask_keys)(handle_memory_ask), + handler=records_served(ask_keys)(records_receipts(search_items)(handle_memory_ask)), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_brief.py b/server/memory/api/ops_brief.py index 65f77cec38b..1516d312ceb 100644 --- a/server/memory/api/ops_brief.py +++ b/server/memory/api/ops_brief.py @@ -6,13 +6,14 @@ from server.memory.app.brief import ( handle_memory_brief, ) +from server.memory.app.read_receipts import brief_items, records_receipts from server.operations.base import Operation, Role memory_brief = Operation( name="memory.brief", input_model=MemoryBriefInput, output_model=MemoryBriefOutput, - handler=handle_memory_brief, + handler=records_receipts(brief_items)(handle_memory_brief), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_bulk.py b/server/memory/api/ops_bulk.py index 9645901323c..a717fcefeae 100644 --- a/server/memory/api/ops_bulk.py +++ b/server/memory/api/ops_bulk.py @@ -28,6 +28,7 @@ handle_memory_set_from_messages, ) from server.memory.app.query import handle_memory_bulk_get +from server.memory.app.read_receipts import records_receipts from server.operations.base import Operation, Role # ============================================================ @@ -110,7 +111,7 @@ name="memory.bulk_get", input_model=MemoryBulkGetInput, output_model=MemoryBulkGetOutput, - handler=handle_memory_bulk_get, + handler=records_receipts()(handle_memory_bulk_get), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_context.py b/server/memory/api/ops_context.py index 4e1dc9ad756..26b6c3e037a 100644 --- a/server/memory/api/ops_context.py +++ b/server/memory/api/ops_context.py @@ -4,6 +4,7 @@ from server.memory.api.models_context import ContextPackInput, ContextPackOutput from server.memory.app.context_pack import handle_context_pack +from server.memory.app.read_receipts import memory_rows, records_receipts from server.memory.app.served_reads import records_served, rendered_rows from server.operations.base import Operation, Role @@ -12,7 +13,9 @@ session_content=True, input_model=ContextPackInput, output_model=ContextPackOutput, - handler=records_served(rendered_rows)(handle_context_pack), + handler=records_served(rendered_rows)( + records_receipts(memory_rows(rendered_rows))(handle_context_pack) + ), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_crud.py b/server/memory/api/ops_crud.py index 534b447129b..44083d78cbe 100644 --- a/server/memory/api/ops_crud.py +++ b/server/memory/api/ops_crud.py @@ -58,6 +58,7 @@ handle_memory_unpin, ) from server.memory.app.query import handle_memory_keys, handle_memory_list, handle_memory_statuses +from server.memory.app.read_receipts import records_receipts from server.memory.app.restore import handle_memory_restore from server.memory.app.update import handle_memory_update, handle_memory_update_by_id from server.memory.app.verify import handle_memory_verify @@ -72,7 +73,7 @@ name="memory.get", input_model=MemoryGetInput, output_model=MemoryGetOutput, - handler=handle_memory_get, + handler=records_receipts()(handle_memory_get), idempotent=True, required_role=Role.VIEWER, audit=False, @@ -216,7 +217,7 @@ name="memory.get_by_id", input_model=MemoryGetByIdInput, output_model=MemoryGetByIdOutput, - handler=handle_memory_get_by_id, + handler=records_receipts()(handle_memory_get_by_id), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_for_file.py b/server/memory/api/ops_for_file.py index 7d28c1783f8..9e3227b080d 100644 --- a/server/memory/api/ops_for_file.py +++ b/server/memory/api/ops_for_file.py @@ -4,6 +4,7 @@ from server.memory.api.models_for_file import MemoryForFileInput, MemoryForFileOutput from server.memory.app.for_file import handle_memory_for_file +from server.memory.app.read_receipts import memory_rows, records_receipts from server.memory.app.served_reads import printed_rows, records_served from server.operations.base import Operation, Role @@ -12,7 +13,9 @@ session_content=True, input_model=MemoryForFileInput, output_model=MemoryForFileOutput, - handler=records_served(printed_rows)(handle_memory_for_file), + handler=records_served(printed_rows)( + records_receipts(memory_rows(printed_rows))(handle_memory_for_file) + ), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_lifecycle.py b/server/memory/api/ops_lifecycle.py index 7df7eb78f8a..13ca489fd5e 100644 --- a/server/memory/api/ops_lifecycle.py +++ b/server/memory/api/ops_lifecycle.py @@ -27,6 +27,7 @@ from server.memory.app.evidence_reads import handle_memory_evidence, handle_memory_provenance from server.memory.app.ops import handle_memory_reject from server.memory.app.promote import handle_memory_demote, handle_memory_promote +from server.memory.app.read_receipts import memory_rows, records_receipts from server.memory.app.served_reads import records_served, stack_keys from server.memory.app.stack import handle_memory_stack from server.operations.base import Operation, Role @@ -132,7 +133,9 @@ maturity="experimental", input_model=MemoryStackInput, output_model=MemoryStackOutput, - handler=records_served(stack_keys)(handle_memory_stack), + handler=records_served(stack_keys)( + records_receipts(memory_rows(stack_keys))(handle_memory_stack) + ), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_loom_search.py b/server/memory/api/ops_loom_search.py index 1a3cd57740b..5ffd624ef34 100644 --- a/server/memory/api/ops_loom_search.py +++ b/server/memory/api/ops_loom_search.py @@ -4,6 +4,7 @@ from server.memory.api.models_loom_search import SearchInput, SearchOutput from server.memory.app.loom_search.handler import handle_search +from server.memory.app.read_receipts import records_receipts, search_query_items from server.memory.app.served_reads import records_served, search_query_keys from server.operations.base import Operation, Role @@ -13,7 +14,7 @@ mcp_tool="loom_search", input_model=SearchInput, output_model=SearchOutput, - handler=records_served(search_query_keys)(handle_search), + handler=records_served(search_query_keys)(records_receipts(search_query_items)(handle_search)), idempotent=True, required_role=Role.VIEWER, maturity="experimental", diff --git a/server/memory/api/ops_procedure.py b/server/memory/api/ops_procedure.py index 44f6fe6394e..17fa7b5bfc6 100644 --- a/server/memory/api/ops_procedure.py +++ b/server/memory/api/ops_procedure.py @@ -32,6 +32,7 @@ handle_procedure_fork, handle_procedure_revise, ) +from server.memory.app.read_receipts import memory_rows, records_receipts from server.memory.app.served_reads import procedure_keys, records_served from server.operations.base import Operation, Role @@ -49,7 +50,9 @@ name="procedure.match", input_model=ProcedureMatchInput, output_model=ProcedureMatchOutput, - handler=records_served(procedure_keys)(handle_procedure_match), + handler=records_served(procedure_keys)( + records_receipts(memory_rows(procedure_keys))(handle_procedure_match) + ), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/api/ops_search.py b/server/memory/api/ops_search.py index b905bfc0ea2..132ede9369e 100644 --- a/server/memory/api/ops_search.py +++ b/server/memory/api/ops_search.py @@ -13,6 +13,7 @@ SearchTraceLogOutput, ) from server.memory.app.query import handle_memory_aggregate +from server.memory.app.read_receipts import records_receipts, search_items from server.memory.app.search import ( handle_memory_search, handle_memory_search_trace, @@ -30,7 +31,7 @@ session_content=True, input_model=MemorySearchInput, output_model=MemorySearchOutput, - handler=records_served(search_keys)(handle_memory_search), + handler=records_served(search_keys)(records_receipts(search_items)(handle_memory_search)), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/app/after_write.py b/server/memory/app/after_write.py index 38ac2e90942..a5d707632cf 100644 --- a/server/memory/app/after_write.py +++ b/server/memory/app/after_write.py @@ -19,6 +19,7 @@ from __future__ import annotations import asyncio +import contextvars import logging from collections.abc import Coroutine from typing import Any @@ -32,11 +33,17 @@ def schedule( - coro: Coroutine[Any, Any, Any], *, name: str, scope: tuple[str, str] | None = None + coro: Coroutine[Any, Any, Any], + *, + name: str, + scope: tuple[str, str] | None = None, + detached: bool = False, ) -> asyncio.Task[Any] | None: """Run `coro` after the response; None (and the coroutine awaited by nobody is closed) when no loop is running. `scope` is the (org, namespace) - the task writes, for `settle`.""" + the task writes, for `settle`. `detached` runs it with an empty context: a + task that outlives its request and sends other requests' rows carries none + of the request's tag, deadline or identity.""" try: loop = asyncio.get_running_loop() except RuntimeError: @@ -47,7 +54,8 @@ def schedule( for stale in [t for t in _TASKS if t.done() or t.get_loop() is not loop]: _TASKS.discard(stale) _SCOPES.pop(stale, None) - task = register_deferred_task(loop.create_task(coro, name=name)) + context = contextvars.Context() if detached else None + task = register_deferred_task(loop.create_task(coro, name=name, context=context)) _TASKS.add(task) task.add_done_callback(_TASKS.discard) if scope is not None: diff --git a/server/memory/app/brief.py b/server/memory/app/brief.py index de1190f98c1..e1b47cbbc10 100644 --- a/server/memory/app/brief.py +++ b/server/memory/app/brief.py @@ -37,7 +37,7 @@ async def handle_memory_brief(input: MemoryBriefInput) -> MemoryBriefOutput: out = await handle_memory_ask(ask) cited = set(out.memory_keys or []) - hits = [h for h in out.results if h.memory_key in cited] or list(out.results) + hits = ([h for h in out.results if h.memory_key in cited] or list(out.results))[: input.top_k] evidence = [ BriefEvidence( memory_key=h.memory_key, @@ -48,7 +48,7 @@ async def handle_memory_brief(input: MemoryBriefInput) -> MemoryBriefOutput: session_id=getattr(h, "session_id", "") or "", excerpt=(getattr(h, "content_excerpt", "") or "")[:_EXCERPT_CAP], ) - for h in hits[: input.top_k] + for h in hits ] unknowns = [out.abstain_reason] if out.abstain and out.abstain_reason else [] @@ -58,7 +58,7 @@ async def handle_memory_brief(input: MemoryBriefInput) -> MemoryBriefOutput: + [f"search: {u}" for u in unknowns[:3]] ) - return MemoryBriefOutput( + brief = MemoryBriefOutput( query=input.query, answer=out.answer, abstained=bool(out.abstain), @@ -67,3 +67,5 @@ async def handle_memory_brief(input: MemoryBriefInput) -> MemoryBriefOutput: unknowns=unknowns, next_reads=next_reads, ) + brief._evidence_hits = hits + return brief diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index 260bd32c354..030e9d8ae12 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -32,6 +32,7 @@ from server.memory.api.models_search import MemorySearchInput from server.memory.api.models_working_memory import WorkingMemoryRenderInput from server.memory.app.provenance import writer_actor +from server.memory.app.read_receipts import note_row from server.memory.domain import code_change, session_change from server.memory.domain.context_layout import ( _BLOCK_LABELS, @@ -443,6 +444,8 @@ def _vtext(v: Any) -> str: hits = list(by_key.values())[:k] if not hits: return + for h in hits: + note_row(h.row) # the revision this recall read evidence = [ EvidenceItem( diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index 5ab779a2138..3029fd95872 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -22,6 +22,7 @@ _MemoryForFilePrintedRow, ) from server.memory.app.code_link_reads import relocated +from server.memory.app.read_receipts import note_selected from server.memory.domain import code_change, fix_record, session_change from server.memory.domain.decision_schema import ( CONSTRAINT_TAG, @@ -94,7 +95,7 @@ def _select(scope: str, columns: str = "") -> str: tags, confidence, pinned, CAST(status AS String) AS status_text, agent, updated_at, actor, created_at, memory_id, conflict_with, source_resource_id, - verified_by, verified_sha256, content_sha256, + verified_by, verified_sha256, content_sha256, version, redacted_at, if({{include_source_links:UInt8}}, files, []) AS source_files, if({{include_source_links:UInt8}}, user_id, '') AS source_user_id, if({{include_source_links:UInt8}}, session_id, '') AS source_session_id, @@ -696,6 +697,7 @@ async def _rows_for( # of each slice's own top `lim` are the namespace's if ids: found = found + await query_all_sliced(ch, _LINKED_SQL, params | {"linked": ids}, "linked") + note_selected(namespace, found) unique = { ( str(r["memory_id"]), @@ -983,6 +985,7 @@ async def _read_own( "links": held, } ) + note_selected("", rows) # each row carries its namespace return _supersede_order(sorted(rows, key=_order_key)) diff --git a/server/memory/app/handlers.py b/server/memory/app/handlers.py index 2b40f1d32b6..650be43e6c4 100644 --- a/server/memory/app/handlers.py +++ b/server/memory/app/handlers.py @@ -497,6 +497,9 @@ async def _handle_memory_get(input: MemoryGetInput) -> MemoryGetOutput: # content_sha256 isn't stored on loom.memory; compute from canonical # JSON so the wire shape matches the SDK precondition. sha = served_content_sha256(row.value) + from server.memory.app.read_receipts import note_row + + note_row(row) # past the unchanged poll: this answer carries the row recall_by_agent: list[_RecallByAgent] = [] served: dict[str, Any] = {} if input.include_recall_breakdown: @@ -1529,6 +1532,9 @@ async def handle_memory_get_by_id(input: MemoryGetByIdInput) -> MemoryGetByIdOut # high value, so nothing sensitive was read and nothing is audited. omit_value = high and input.omit_high_value sha = served_content_sha256(row.value) + from server.memory.app.read_receipts import note_row + + note_row(row) if high and not omit_value: # Key-only read of a 'high' row: audited. Never raises. from server.observability import audit as _audit diff --git a/server/memory/app/procedure.py b/server/memory/app/procedure.py index cccd34593d4..c9fab3fbf17 100644 --- a/server/memory/app/procedure.py +++ b/server/memory/app/procedure.py @@ -199,6 +199,7 @@ async def _procedure_rows( A 'high' row is never a candidate: the locate leaves it out, so under the wildcard agent the plain row the search matched answers, and no key read is audited.""" import server.memory.store as memory_repo + from server.memory.app.read_receipts import note_row rows: dict[tuple[str, str], Any] = {} for ns, keys in keys_by_ns.items(): @@ -219,6 +220,7 @@ async def _procedure_rows( for row in found: if isinstance(row.value, dict): rows[(ns, row.memory_key)] = row + note_row(row) # the body a match is built from return rows diff --git a/server/memory/app/query.py b/server/memory/app/query.py index 7ddd9fe5fd3..32caa5dda84 100644 --- a/server/memory/app/query.py +++ b/server/memory/app/query.py @@ -900,6 +900,10 @@ async def handle_memory_bulk_get( _record_read_exposure( "memory.bulk_get", input, list(dict.fromkeys(r.memory_key for r in answered.values())) ) + from server.memory.app.read_receipts import note_row + + for r in answered.values(): + note_row(r) missing = [k for k in input.memory_keys if k not in results] return MemoryBulkGetOutput(results=results, missing=missing) diff --git a/server/memory/app/read_receipts.py b/server/memory/app/read_receipts.py new file mode 100644 index 00000000000..13854d74c93 --- /dev/null +++ b/server/memory/app/read_receipts.py @@ -0,0 +1,437 @@ +"""Read receipts: the revision of each item an agent read's answer carried. + +`loom.read_receipts` holds one row per memory row or document chunk an answer carried: +the item, the revision the read held, and who read it in which request and run. It +answers "which revision of this did that run see" after the item has changed, which the +exposure ledger (keys only) cannot. It holds identifiers and a hash, never content or +query text. + +Two halves meet in the op's wrapper (`records_receipts`), applied where the op is +declared: + +- The code that holds a row while the op runs notes its revision (`note_memory`, + `note_document` and the helpers over them). A note is kept only while a receipted op + is running and never under private work, so a private connected source's reads leave + nothing. +- When the handler returns, the wrapper asks the answer which items it carried + (`items_of`) and writes a row for each. An item the op trimmed has no row. A revision + comes from the answer or from a note made while the op ran, never from a later read. + +The write is gated: `read_receipts_enabled`, every live replica on the table's migration +or later (an older one's erasure has no step for it), and a request that read no mirrored +source. The rows queue for one sender per process, which sends them one insert an +interval, so receipts hold one ClickHouse connection and a fixed insert rate whatever the +read rate, and a slow store drops receipts instead of refusing reads. A missing receipt +reads as "not recorded". +""" + +from __future__ import annotations + +import asyncio +import functools +import logging +from collections.abc import Awaitable, Callable, Iterable, Mapping +from contextvars import ContextVar +from typing import Any, Protocol + +from server.core import instances, request_work +from server.core.diagnostics import public_diagnostics +from server.core.naming import is_reserved_name, named +from server.memory.app import after_write +from server.memory.app.log_once import LogOnce +from server.memory.app.served_reads import reader +from server.memory.domain.read_receipts import ( + DOCUMENT, + MEMORY, + Item, + Noted, + Notes, + add_note, + every_noted, + receipts, +) +from server.memory.domain.redaction_lineage import is_content_hash +from server.memory.domain.search_types import hit_row +from server.memory.domain.trust import row_content_sha256 +from server.memory.store import read_receipts as store +from server.settings import settings + +log = logging.getLogger(__name__) + +# The revisions noted while a receipted op runs; None outside one. A note mutates the +# dict and never sets the variable, so every task the handler starts shares it. +_notes: ContextVar[Notes | None] = ContextVar("loom_read_receipt_notes", default=None) + +# The rows waiting for the process's one sender. Past the bound an answer's rows are +# dropped and counted: a slow store must not grow the process, and a dropped receipt +# reads as "not recorded". +_MAX_QUEUED_ROWS = 10_000 # not a setting: a bound on memory held, not a capacity to tune +# The sender waits this long before each insert. An insert costs the process about two +# milliseconds of CPU whatever it carries, so the answers of the interval share one. +_SEND_INTERVAL_S = 0.5 # not a setting: the insert rate the design page states follows from it +_queued: list[dict[str, Any]] = [] +_sender: asyncio.Task[Any] | None = None +_dropped = 0 # rows, ever +_failed = 0 # inserts, ever +_GATE_LOGGED = LogOnce() + +# The sender outlives the request that started it; the tag names its inserts. +SEND_QUERY_TAG = "memory.read_receipts" + +# What an answer's items are, from the op's input and output. +ItemsOf = Callable[[Any, Any], Iterable[Item]] + + +# ------------------------------------------------------------------------- noting + + +def _open_notes() -> Notes | None: + """The running op's notes; None outside a receipted op and under private work.""" + notes = _notes.get() + return notes if notes is not None and public_diagnostics() else None + + +def _never_fails[**P](note: Callable[P, None]) -> Callable[P, None]: + """A note runs inside the read it describes and must not fail it.""" + + @functools.wraps(note) + def safe(*args: P.args, **kwargs: P.kwargs) -> None: + try: + note(*args, **kwargs) + except Exception as e: # noqa: BLE001 — a note must not fail the read + log.warning("read-receipt note failed (non-fatal): %s", e) + + return safe + + +@_never_fails +def note_memory( + namespace: str, + key: str, + *, + version: int, + sha256: str = "", + high: bool = False, + redacted: bool = False, +) -> None: + """Note the revision of a memory row the running op holds. `sha256` is the hash the + read holds; it is left out for a high-sensitivity row (a short secret's hash names it + as well as the value does) and a redacted one (its stored hash is the removed + text's).""" + notes = _open_notes() + if notes is not None and namespace and key: + blank = high or redacted or not is_content_hash(sha256) + add_note(notes, MEMORY, namespace, key, Noted(int(version or 0), "" if blank else sha256)) + + +@_never_fails +def note_row(row: Any) -> None: + """Note a `loom.memory` row a read holds, with its content hash as stored: the hash + an attestation binds to (`row_content_sha256`), the same from every op and table. + `memory.get` serves a hash of the decoded value, which differs for some objects.""" + if _open_notes() is None: + return + note_memory( + str(row.namespace), + str(row.memory_key), + version=int(row.version or 0), + sha256=row_content_sha256(row), + high=str(getattr(row, "sensitivity", "") or "") == "high", + redacted=getattr(row, "redacted_at", None) is not None, + ) + + +@_never_fails +def note_selected(namespace: str, rows: Iterable[Mapping[str, Any]]) -> None: + """Note rows as a statement selected them from `loom.memory` or its search documents: + each row's `memory_key` and `version`, with `content_sha256` when it was selected. + The hash of a redacted row is left out, and of a high-sensitivity one when the + statement selected `sensitivity`; a statement that does not must exclude those rows.""" + notes = _open_notes() + if notes is None: + return + for row in rows: + key = str(row.get("memory_key") or "") + if not key: + continue + sha = row.get("content_sha256") + text = sha.decode("ascii", "replace") if isinstance(sha, bytes) else str(sha or "") + blank = ( + row.get("redacted_at") is not None + or str(row.get("sensitivity") or "") == "high" + or not is_content_hash(text) + ) + add_note( + notes, + MEMORY, + str(row.get("namespace") or namespace), + key, + Noted(int(row.get("version") or 0), "" if blank else text), + ) + + +@_never_fails +def note_document(namespace: str, source_uri: str, *, revision: int, doc_version: int = 0) -> None: + """Note the revision of a document the running op holds.""" + notes = _open_notes() + if notes is not None and namespace and source_uri: + noted = Noted(int(revision or 0), "", int(doc_version or 0)) + add_note(notes, DOCUMENT, namespace, source_uri, noted) + + +# ------------------------------------------------------------------------ the wrapper + + +class _KeepsSignature(Protocol): + """A decorator that returns a handler of the same input and output.""" + + def __call__[I, O]( + self, handler: Callable[[I], Awaitable[O]], / + ) -> Callable[[I], Awaitable[O]]: ... + + +def records_receipts(items_of: ItemsOf | None = None) -> _KeepsSignature: + """Wrap an op's handler so each item of its answer (`items_of`) gets a receipt. With + no `items_of` the answer is every row the handler noted: a key lookup notes exactly + the rows it serves.""" + + def wrap[I, O](handler: Callable[[I], Awaitable[O]]) -> Callable[[I], Awaitable[O]]: + @functools.wraps(handler) + async def handle(input: I) -> O: + # Through `__wrapped__` (the handler, set by functools.wraps), so a test can + # stand in the answer of a registered op and check what the op records. + if _notes.get() is not None or not _recording(): + # Inside a receipted op, that op writes what its own answer carries. + # While nothing is written, nothing is noted either. + return await handle.__wrapped__(input) + notes: Notes = {} + token = _notes.set(notes) + try: + out = await handle.__wrapped__(input) + finally: + _notes.reset(token) + # No await from here to the scheduled write: a note a background task of the + # request makes later is not this answer's. + _record(handler.__name__, input, out, items_of, notes) + return out + + return handle + + return wrap + + +def _recording() -> bool: + """Whether this process writes receipts now: the switch is on and every live replica + can erase them. Read when an op starts.""" + if not settings.read_receipts_enabled: + return False + if instances.every_live_replica_at(store.MIGRATION): + return True + if _GATE_LOGGED.first("replicas"): + log.warning( + "read receipts are not written while a live replica is below migration %d " + "or no replica heartbeat was read", + store.MIGRATION, + ) + return False + + +def _record(name: str, input: Any, out: Any, items_of: ItemsOf | None, notes: Notes) -> None: + """Queue the receipts of one answer. Never raises: a receipt must not fail a read.""" + try: + # An item that carries its version needs no note, so private work is refused here + # as well as at each note. + if request_work.mirror_marked() or not public_diagnostics(): + return + served = every_noted(notes) if items_of is None else receipts(items_of(input, out), notes) + # The table refuses a row under a mirror's or a code store's name, and with it + # every row of its insert. + served = [(item, noted) for item, noted in served if not is_reserved_name(item.namespace)] + if served: + _enqueue(store.build_rows(_reader(input), served)) + except Exception as e: # noqa: BLE001 — a receipt must not fail the read + log.warning("read receipts of %s not recorded (non-fatal): %s", name, e) + + +def _enqueue(rows: list[dict[str, Any]]) -> None: + """Hand one answer's rows to the sender, starting it when it is not running.""" + global _dropped, _sender + if len(_queued) + len(rows) > _MAX_QUEUED_ROWS: + _dropped += len(rows) + if _worth_logging(_dropped, len(rows)): + log.warning("read receipts dropped past the queue bound: %d rows", _dropped) + return + _queued.extend(rows) + # A sender left on a closed loop is never done and never sends. + if _sender is None or _sender.done() or _sender.get_loop().is_closed(): + _sender = after_write.schedule(_send_queued(), name=SEND_QUERY_TAG, detached=True) + if _sender is None: # no running loop: built, not written + _queued.clear() + + +async def _send_queued() -> None: + """Send what has queued, one insert an interval, until nothing is left. The rows that + queue meanwhile go in the next insert, so the batch grows with the read rate and the + inserts and the connections held do not.""" + global _failed + from server.core.ch import set_query_tag + + set_query_tag(SEND_QUERY_TAG) + while _queued: + await asyncio.sleep(_SEND_INTERVAL_S) + rows = _queued.copy() + _queued.clear() + try: + await store.insert(rows) + except Exception as e: # noqa: BLE001 — a receipt must not fail a read + _failed += 1 + if _worth_logging(_failed): + log.warning( + "read-receipt write failed (non-fatal; %d failed, %d rows lost now): %s", + _failed, + len(rows), + e, + ) + + +def _worth_logging(count: int, step: int = 1) -> bool: + """Whether a counter that just rose by `step` to `count` passed a power of ten: the + first is logged, then the 10th, the 100th and so on.""" + return any(count - step < 10**n <= count for n in range(len(str(count)))) + + +def _reset_for_tests() -> None: + """Drop the queued rows and forget the sender and the counters (test seam).""" + global _sender, _dropped, _failed + _queued.clear() + _sender, _dropped, _failed = None, 0, 0 + + +def _reader(input: Any) -> store.Reader: + """Who read, from the request: the token's subject and id, the agent the read counts + as, the user and session it read as, the run and the op the caller invoked. The user + and session are the input's, else the token's read scope, else what the request named + to the transport (a document op's input has neither).""" + from server.auth.context import current_auth + from server.core.logging_config import request_id_var + from server.identity.app.request_scope import request_scope + from server.observability.genai import current_operation, request_identity + from server.observability.run_context import ledger_run_for + + auth = current_auth() + scope = request_scope() + named_to_transport = request_identity() + subject = str(getattr(auth, "subject", "") or "") + # A transport traces a request that names no user under the token's subject. That is + # `actor` here: a read made as no end user says so. + traced_user = named(named_to_transport.get("user_id")) + return store.Reader( + org=str(input.org), + operation=current_operation(), + request_id=request_id_var.get() or "", + # The run the op ledger and the exposure ledger file this request under, so + # the three join on it: the request's own `run_id`, else the run bound to it. + run_id=ledger_run_for(getattr(input, "run_id", None)), + actor=subject, + token_id=str(getattr(auth, "token_id", "") or ""), + agent=reader(input) or named(named_to_transport.get("agent")) or "", + user_id=( + named(getattr(input, "user_id", None)) + or scope.user_id + or (traced_user if traced_user != subject else None) + or "" + ), + session_id=( + named(getattr(input, "session_id", None)) + or scope.session_id + or named(named_to_transport.get("session_id")) + or "" + ), + ) + + +# ------------------------------------------------- what each op's answer carried + +# The search planes whose hit is a stored memory row; a chunk is a passage of one. +_ROW_SOURCES = frozenset({"fact", "anchor"}) +_PASSAGE_SOURCE = "chunk" + + +def _field(hit: Any) -> Callable[[str], Any]: + """A reader of a hit's fields, for a hit object and a wire hit dict alike.""" + return hit.get if isinstance(hit, dict) else lambda name: getattr(hit, name, None) + + +def _hit_item(hit: Any, namespace: str) -> Item | None: + """The stored row a search hit is, at the version the hit carries (none when the hit + carries none); a chunk hit is its parent row at version 0 (the read held the passage, + not the row). None for a hit of another plane (a summary, a record, a computed row): + it is no stored memory row.""" + get = _field(hit) + source = str(get("source") or "fact") + if source == _PASSAGE_SOURCE: + if not get("parent_memory_key"): + return None + return Item(MEMORY, *hit_row(hit, namespace), 0) + if source not in _ROW_SOURCES or not get("memory_key"): + return None + # The private version is the stored row the answer's text came from, when that is + # not the hit's own: a tier row, a governed definition's shared copy, a whole body + # read after the search. + version = int(get("_row_version") or get("version") or 0) + return Item(MEMORY, *hit_row(hit, namespace), version or None) + + +def _hit_items(hits: Iterable[Any], namespace: str) -> list[Item]: + return [item for hit in hits if (item := _hit_item(hit, namespace)) is not None] + + +def _document_items(hits: Iterable[Any], namespace: str) -> list[Item]: + """The document chunk each knowledge hit is, at the revision the hit carries.""" + items: list[Item] = [] + for hit in hits: + get = _field(hit) + uri, idx = get("source_uri"), get("chunk_idx") + if uri: + items.append( + Item( + DOCUMENT, + str(get("namespace") or namespace), + str(uri), + int(get("revision") or 0), + -1 if idx is None else int(idx), + ) + ) + return items + + +def search_items(input: Any, out: Any) -> list[Item]: + """memory.search and memory.ask: the hits the answer returns.""" + return _hit_items(out.results, input.namespace) + + +def brief_items(input: Any, out: Any) -> list[Item]: + """memory.brief: the hits its evidence was made from.""" + return _hit_items(out._evidence_hits, input.namespace) + + +def search_query_items(input: Any, out: Any) -> list[Item]: + """search.query: the hits its memory and knowledge sections kept.""" + memory = [h for h in (out.memory or {}).get("results") or [] if isinstance(h, dict)] + knowledge = [h for h in (out.knowledge or {}).get("results") or [] if isinstance(h, dict)] + return _hit_items(memory, input.namespace) + _document_items(knowledge, input.namespace) + + +def knowledge_items(input: Any, out: Any) -> list[Item]: + """knowledge.search: the chunks the answer returns.""" + return _document_items(out.results, input.namespace) + + +def memory_rows(keys_of: Callable[[Any, Any], Iterable[tuple[str, str]]]) -> ItemsOf: + """The stored rows an answer names without a version, from the extractor that names + them for the served-reads log (`served_reads`).""" + + def items(input: Any, out: Any) -> list[Item]: + return [Item(MEMORY, namespace, key) for namespace, key in keys_of(input, out)] + + return items diff --git a/server/memory/app/retrieval/fact_sql.py b/server/memory/app/retrieval/fact_sql.py index d0d5cd4bdd5..23a77a972a3 100644 --- a/server/memory/app/retrieval/fact_sql.py +++ b/server/memory/app/retrieval/fact_sql.py @@ -97,6 +97,8 @@ async def _fact_leg_sql( e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, + -- The content hash, for the read receipt of a hit this leg ranks. + e.content_sha256 AS content_sha256, -- Multi-vector axis: min(value_dist, key_dist). CH's IF is eager, -- so we can't gate cosineDistance on key-dim; the inner IF falls -- back to the value embedding on dim mismatch, making `least` a diff --git a/server/memory/app/retrieval/search.py b/server/memory/app/retrieval/search.py index 740161d77b9..7b9e2fed72d 100644 --- a/server/memory/app/retrieval/search.py +++ b/server/memory/app/retrieval/search.py @@ -227,6 +227,9 @@ def _fact_rows_to_hits( ) -> list[SearchHit]: """Phase 9 of `vector_search`: the fact rows as typed hits, with the per-hit score decomposition the SQL computed.""" + from server.memory.app.read_receipts import note_selected + + note_selected(q.namespace, rows) # the version and hash this leg read, for a receipt hits = [ SearchHit( memory_key=r["memory_key"], diff --git a/server/memory/app/search/payload.py b/server/memory/app/search/payload.py index 81a6298aecc..cec2471713d 100644 --- a/server/memory/app/search/payload.py +++ b/server/memory/app/search/payload.py @@ -12,6 +12,7 @@ from server.core.ch import get_client from server.core.naming import SENTINEL from server.identity.app.request_scope import request_scope +from server.memory.app.read_receipts import note_row from server.memory.app.search.request import apply_explain_default from server.memory.app.search.tiers import _reader_user_id from server.memory.app.search_tag_filter import read_row_tags as _read_row_tags @@ -444,6 +445,10 @@ def _body_row(h: Any) -> Any: if spent + cost <= budget: h.content_excerpt = text h.body_truncated = False + # The answer now carries this row's text, read after the legs: its receipt + # names this row's revision, not the search document's. + h._row_version = int(getattr(body_row, "version", 0) or 0) + note_row(body_row) spent += cost returned += 1 tokens += cost diff --git a/server/memory/app/search/term_leg.py b/server/memory/app/search/term_leg.py index 9ea02cba107..f36837ded2f 100644 --- a/server/memory/app/search/term_leg.py +++ b/server/memory/app/search/term_leg.py @@ -20,6 +20,7 @@ from server.core.hashing import query_text, valid_unicode from server.memory.api.models_search import MemorySearchInput, TermLegStatus, _MemorySearchHit from server.memory.app.definitions import source_reasons +from server.memory.app.read_receipts import note_memory from server.memory.app.search.context import SearchContext from server.memory.app.search.evidence import EVIDENCE_LIFT_EPS from server.memory.app.sensitivity_level import ON_LOOP_CHARS @@ -34,6 +35,7 @@ ) from server.memory.domain.excerpt import build_excerpt from server.memory.domain.search_types import SHARED_AGENT, hit_row, is_computed_row +from server.memory.domain.trust import live_sha256 from server.memory.store import shared as shared_repo from server.memory.store.embeddings import live_vectors from server.observability import degradations @@ -103,6 +105,7 @@ async def refresh_parked( task = create_deferred_task(_read(org, namespace, query, set(), None, "", whole=True)) current = await outcome(task, settings.memory_term_leg_wait_ms / 1000) values = {h.memory_key: h.content_excerpt for h in current.hits} + versions = {h.memory_key: h._row_version for h in current.hits} refreshed: list[_MemorySearchHit | None] = [] for h in hits: if not h.governed: @@ -121,6 +124,7 @@ async def refresh_parked( continue text = values[h.memory_key] h.content_excerpt = text if whole else build_excerpt(text, memory_key=h.memory_key) + h._row_version = versions[h.memory_key] # the copy this page's check read refreshed.append(h) return refreshed @@ -300,13 +304,14 @@ async def _governed( if d.memory_key not in values: continue await asyncio.sleep(0) - work.charge(len(values[d.memory_key])) - value = json.loads(values[d.memory_key]) + stored, version = values[d.memory_key] + work.charge(len(stored)) + value = json.loads(stored) if isinstance(value, dict) and isinstance(value.get("term"), str): aliases = value.get("aliases") or [] if isinstance(aliases, list) and all(isinstance(a, str) for a in aliases): work.names(value["term"], aliases) - full.append(replace(d, value=value)) + full.append(replace(d, value=value, version=version, sha256=live_sha256(None, stored))) full = [d for d in full if copy_lapse(d, org=org, namespace=namespace) is None] reasons = await source_reasons(org, namespace, full, strong=False, max_value_chars=work.left) return {d.memory_key: d for d in full if reasons[d.memory_key] is None} @@ -340,6 +345,10 @@ def _hit(d: SharedDefinition, namespace: str, *, whole: bool = False) -> _Memory ) hit._row_identity = (SHARED_AGENT, "-", "-") hit._row_scope = "shared" + # The shared copy is the row this hit's text came from, so its receipt names that + # row's revision and no other row's under the key. + hit._row_version = d.version + note_memory(namespace, d.memory_key, version=d.version, sha256=d.sha256) return hit diff --git a/server/memory/app/search/tiers.py b/server/memory/app/search/tiers.py index 0173ec6f1c9..fe34adb323a 100644 --- a/server/memory/app/search/tiers.py +++ b/server/memory/app/search/tiers.py @@ -10,6 +10,7 @@ from server.core.error_summary import error_summary from server.core.tag_sql import TagFilter from server.identity.app.request_scope import request_scope +from server.memory.app.read_receipts import note_row from server.memory.app.search import pg_validation from server.memory.app.search.context import StaleVersions from server.memory.app.search_tag_filter import request_hard_tags as _request_hard_tags @@ -121,6 +122,7 @@ async def _prepend_tier( if None not in who: hit._row_identity = (str(who[0]), str(who[1]), str(who[2])) hit._row_version = int(getattr(r, "version", 0) or 0) + note_row(r) # the row this tier read, for a receipt # `_apply_bodies` reads them: a constraint keeps its excerpt. tier_rows.append(stamp_row_tags(hit, getattr(r, "tags", None))) try: diff --git a/server/memory/app/served_reads.py b/server/memory/app/served_reads.py index b31fd630b64..0020d0b0ef2 100644 --- a/server/memory/app/served_reads.py +++ b/server/memory/app/served_reads.py @@ -68,13 +68,13 @@ async def _write() -> None: class _AgentRead(Protocol): """The input of an agent read op: the org it reads, and the agent from its `agent` - field when it has one (`_reader`).""" + field when it has one (`reader`).""" @property def org(self) -> str: ... -def _reader(input: Any) -> str: +def reader(input: Any) -> str: """Who read: the input's agent when it names one; for a sentinel agent (`*`, `-`: the SDK's and MCP's cross-agent reads, a context pack) or an input with none (memory.for_file), the named consumer behind it. With neither, the sentinel stays and @@ -101,9 +101,9 @@ async def handle(input: I) -> O: try: keys = keys_of(input, out) if keys: - reader = _reader(input) - if reader: - schedule_served(input.org, reader, keys) + agent = reader(input) + if agent: + schedule_served(input.org, agent, keys) except Exception as e: # noqa: BLE001 — a served row must not fail the read log.warning("served keys of %s failed (non-fatal): %s", handler.__name__, e) return out diff --git a/server/memory/app/stack.py b/server/memory/app/stack.py index bc5860a6e24..49accd4e18b 100644 --- a/server/memory/app/stack.py +++ b/server/memory/app/stack.py @@ -16,6 +16,7 @@ from server.knowledge.app.source_access import ReadPlan from server.knowledge.app.source_search_proofs import SearchProofs from server.memory.api.models_lifecycle import MemoryStackInput, MemoryStackOutput, _StackEntry +from server.memory.app.read_receipts import note_selected from server.memory.app.stack_knowledge import StackKnowledge from server.observability import degradations @@ -120,7 +121,8 @@ async def _stack_pinned(ch: Any, input: MemoryStackInput, fill: _StackFill) -> N scope = scope_and(request_scope(), params) pinned_rows = await ch.query_all( f""" - SELECT memory_key, memory_type, value, recall_count, last_recalled_at, actor + SELECT memory_key, memory_type, value, recall_count, last_recalled_at, actor, + version, content_sha256, redacted_at FROM loom.memory FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} @@ -138,6 +140,7 @@ async def _stack_pinned(ch: Any, input: MemoryStackInput, fill: _StackFill) -> N """, params=params, ) + note_selected(input.namespace, pinned_rows) for r in pinned_rows: val = _value_str(r.get("value")) cost = _est_tokens(val) @@ -182,7 +185,8 @@ async def _stack_recent(ch: Any, input: MemoryStackInput, fill: _StackFill) -> s recent_rows = await ch.query_all( f""" SELECT memory_key, memory_type, value, recall_count, - evidence_count, last_recalled_at, actor + evidence_count, last_recalled_at, actor, + version, content_sha256, redacted_at FROM loom.memory FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} @@ -203,6 +207,7 @@ async def _stack_recent(ch: Any, input: MemoryStackInput, fill: _StackFill) -> s """, params=params, ) + note_selected(input.namespace, recent_rows) most_recent_excerpt = "" for r in recent_rows: if r["memory_key"] in pinned_keys: diff --git a/server/memory/domain/definition_check.py b/server/memory/domain/definition_check.py index 0d90b755671..c15204df743 100644 --- a/server/memory/domain/definition_check.py +++ b/server/memory/domain/definition_check.py @@ -39,6 +39,10 @@ class SharedDefinition: promoted_from: tuple[str, ...] promoted_at: datetime promotion_event: str + # The stored row `value` was read from: its version and content hash. Unset on a + # listed definition, whose value holds only its names. + version: int = 0 + sha256: str = "" @dataclass(frozen=True) diff --git a/server/memory/domain/read_receipts.py b/server/memory/domain/read_receipts.py new file mode 100644 index 00000000000..498f05952e8 --- /dev/null +++ b/server/memory/domain/read_receipts.py @@ -0,0 +1,122 @@ +"""Read receipts: which revision of an item an answer carried. + +A receipt joins two things. An op's answer names the items it carried (`Item`). The code +that held a row while the op ran noted the revision it held (`Noted`). `receipts` pairs +them. A revision comes from the answer or from a note made while the op ran, never from +a later read. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import NamedTuple + +MEMORY = "memory" +DOCUMENT = "document" + + +class Item(NamedTuple): + """One item of an answer. `version` is the version the answer carries for it: 0 when + the read that produced it held none (a passage of the row, not the row), None when + the answer names the row without a version.""" + + kind: str + namespace: str + key: str + version: int | None = None + chunk_idx: int = -1 + + +class Noted(NamedTuple): + """The revision a read held: a memory row's version and content hash, or a document's + revision and stored version. An empty hash and a zero version read as not recorded.""" + + version: int = 0 + sha256: str = "" + doc_version: int = 0 + + +# The revisions noted for each (kind, namespace, key), by version: one key can hold a row +# for each writer and session, and one op can read the key more than once. +Notes = dict[tuple[str, str, str], dict[int, Noted]] + +NOT_RECORDED = Noted() + +# Two stored versions were noted for one document revision: which of them a chunk came +# from is not recorded. Kept in the notes so a third note cannot settle it; never stored. +_SEVERAL = -1 + + +def add_note(notes: Notes, kind: str, namespace: str, key: str, noted: Noted) -> None: + """Keep `noted` for the item. A second note of the same version adds what the first + lacked: one leg reads a row's hash and another only its version.""" + held = notes.setdefault((kind, namespace, key), {}) + earlier = held.get(noted.version) + if earlier is None: + held[noted.version] = noted + else: + held[noted.version] = Noted( + noted.version, + earlier.sha256 or noted.sha256, + _agreed(earlier.doc_version, noted.doc_version), + ) + + +def _agreed(earlier: int, later: int) -> int: + """The stored version two notes of one revision agree on.""" + if not later or later == earlier: + return earlier + return later if not earlier else _SEVERAL + + +def _stored(noted: Noted) -> Noted: + """`noted` as a receipt stores it: a stored version the notes disagree on is 0.""" + return noted if noted.doc_version >= 0 else noted._replace(doc_version=0) + + +def revision_of(item: Item, notes: Notes) -> Noted | None: + """The revision of `item`, or None when the answer names a row nobody noted. + + An answer that carries the item's version records that version, with what a note of + it adds: the hash, or a document's stored version. An answer that names the row alone + takes what the notes of its key agree on. One table's version of a row is not + another's (a search document is rewritten at its own version), so the notes agree + when they all carry one hash; the version is recorded when only one was noted. Notes + that do not agree leave the revision not recorded.""" + held = notes.get((item.kind, item.namespace, item.key), {}) + if item.version is not None: + return _stored(held.get(item.version) or Noted(item.version)) + rows = [noted for version, noted in held.items() if version] + if not rows: + return NOT_RECORDED if held else None + if len(rows) == 1: + return rows[0] + hashes = {noted.sha256 for noted in rows} + return Noted(0, hashes.pop()) if len(hashes) == 1 else NOT_RECORDED + + +def every_noted(notes: Notes) -> list[tuple[Item, Noted]]: + """Every noted revision as an item of the answer: a key lookup notes exactly the rows + it serves.""" + return [ + (Item(kind, namespace, key, noted.version), _stored(noted)) + for (kind, namespace, key), held in notes.items() + for noted in held.values() + ] + + +def receipts(items: Iterable[Item], notes: Notes) -> list[tuple[Item, Noted]]: + """Each item of the answer with its revision, once per revision. An item whose + revision is not recorded is left out when the answer also carries a recorded revision + of it: a passage of a row beside the row itself.""" + paired: dict[tuple[str, str, str, int, Noted], Item] = {} + for item in items: + noted = revision_of(item, notes) + if noted is not None: + paired.setdefault((item.kind, item.namespace, item.key, item.chunk_idx, noted), item) + recorded = {place[:4] for place in paired if place[4] != NOT_RECORDED} + return [ + (item, place[4]) + for place, item in paired.items() + if place[4] != NOT_RECORDED or place[:4] not in recorded + ] diff --git a/server/memory/store/read_receipts.py b/server/memory/store/read_receipts.py new file mode 100644 index 00000000000..5bb690d1541 --- /dev/null +++ b/server/memory/store/read_receipts.py @@ -0,0 +1,70 @@ +"""loom.read_receipts: one row per item an agent read's answer carried, with the +revision the read held. Identifiers and a hash only: no content and no query text.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +from server.core.ch_writes import async_insert_settings +from server.core.datetimes import naive_utc_now +from server.core.repo_base import _CHClient +from server.memory.domain.read_receipts import Item, Noted + +TABLE = "loom.read_receipts" + +# The migration that adds the table; an older replica's erasure has no step for it. +MIGRATION = 122 # tests/unit/test_read_receipts.py ties it to the file + +_SENTINEL = "-" + + +@dataclass(frozen=True) +class Reader: + """Who read, and in which request and run: the same on every row of one answer.""" + + org: str + operation: str + request_id: str = "" + run_id: str = "" + actor: str = "" + token_id: str = "" + agent: str = "" + user_id: str = "" + session_id: str = "" + + +def build_rows(reader: Reader, served: Sequence[tuple[Item, Noted]]) -> list[dict[str, Any]]: + """The rows of one answer: each item under the namespace that holds it.""" + now = naive_utc_now().replace(microsecond=0) + return [ + { + "ts": now, + "org": reader.org, + "namespace": item.namespace, + "kind": item.kind, + "item_key": item.key, + "version": int(noted.version), + "content_sha256": noted.sha256, + "doc_version": int(noted.doc_version), + "chunk_idx": int(item.chunk_idx), + "operation": reader.operation, + "request_id": reader.request_id, + "run_id": reader.run_id or _SENTINEL, + "actor": reader.actor, + "token_id": reader.token_id, + "agent": reader.agent, + "user_id": reader.user_id or _SENTINEL, + "session_id": reader.session_id or _SENTINEL, + } + for item, noted in served + ] + + +async def insert(rows: list[dict[str, Any]], *, ch: _CHClient | None = None) -> None: + from server.core.repo_base import _default_client + + await (ch or _default_client()).insert( + TABLE, rows, settings=async_insert_settings(background=True) + ) diff --git a/server/memory/store/shared.py b/server/memory/store/shared.py index d70c4bcdf24..3c55e9973cf 100644 --- a/server/memory/store/shared.py +++ b/server/memory/store/shared.py @@ -395,17 +395,17 @@ async def shared_definitions( async def definition_values( org: str, namespace: str, keys: list[str], *, ch: _CHClient | None = None -) -> dict[str, str]: - """The stored `value` of each live shared definition under `keys`.""" +) -> dict[str, tuple[str, int]]: + """The stored `value` and the version of each live shared definition under `keys`.""" if not keys: return {} ch = ch or _default_client() rows = await ch.query_all( """ - SELECT memory_key, value FROM loom.shared FINAL + SELECT memory_key, value, version FROM loom.shared FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tombstoned_at IS NULL """, params={"org": org, "ns": namespace, "keys": keys}, ) - return {r["memory_key"]: r["value"] for r in rows} + return {r["memory_key"]: (r["value"], int(r["version"])) for r in rows} diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 876d5bdec19..066a50e4ac4 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -3957,6 +3957,10 @@ class MemorySearchSettings(BaseModel): # (token subject, returned keys, query digest never the text, scope) plus # an hourly per-actor roll-up. Carries no user content. memory_exposure_ledger_enabled: Annotated[bool, LIVE] = True + # Read receipts in loom.read_receipts: one row per memory row or document an agent + # read's answer carried, with the revision the read held (version and hash, never + # content or query text). Off stops new rows; stored ones expire by the table's TTL. + read_receipts_enabled: Annotated[bool, LIVE] = True # Cosine floor: hits below it are dropped as noise (ANN always returns # top_k). The backstop when rerank is bypassed or fails. memory_search_min_similarity: float = 0.22 diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index f7b729b0e54..e93b4ea8566 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -4,27 +4,29 @@ # and review the diff: a new line is a new statement shape. 001eb6c5587e SELECT DISTINCT canonical_text FROM loom.entity_canonical_map FINAL WHERE org = {org:String} AND namespace IN {namespaces:Array(String)} AND mention_text IN {mentions:Array(String)} AND tombstoned_at 0028ff84bbed SELECT agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND has(tags, {tag:String}) ORDER BY updated_at DESC -004f2544bc01 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 005d9c786103 SELECT scope_type, scope_path, summary, pagerank, in_degree, out_degree, key_symbols FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:St 00e65c7c9771 SELECT DISTINCT toString(namespace) AS ns, agent, user_id, session_id, memory_key, toString(memory_id) AS id FROM (SELECT namespace, agent, user_id, session_id, memory_key, memory_id, tags FROM loom.m 01287768034f SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND record_id IN {ids:Array(UUID)} -017897c60dc2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +0179df41ed4e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 01a34c93d39f SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, toString(valid_at) AS said_on, substring(JSONExtractString(value), ?, ?) AS text FROM loom.memory FINAL WHERE org = {org: 01ae59cc61a2 WITH (SELECT toFloat64(count()) FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL) AS n_keys, (SELECT mapFromArrays(groupArray(s), groupA 01ba4cf216b1 ALTER TABLE loom.memory_doc_stats DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 01c116b13550 ALTER TABLE loom.conversations UPDATE is_saved = false, saved_at = NULL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:S 01fc37594989 WITH ( SELECT ( arrayFlatten(groupArrayIf(pair, own AND live AND verified)), arrayFlatten(groupArray(arrayConcat( if(own AND NOT (live AND verified), pair, []), if(own, [], released_aliases) ))) ) FRO +02119fb598ba SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 022062ef2123 SELECT namespace, source_uri, public_namespace, public_uri FROM (SELECT namespace, source_uri, indexOf({bindings:Array(Tuple(String, String))}, (namespace, right(source_uri, ?))) AS binding, arrayElem 0223e520348c SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key FROM loom.memory_embeddings PREWHERE embedding_dim = ? WHERE tombstoned_at IS NULL AND embed_failed_at IS NULL AND 022615b444ba SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 022dab339693 SELECT count() AS n FROM loom.consolidation_runs WHERE org = {org:String} AND namespace IN {ns:Array(String)} 02309b9227fc ALTER TABLE loom.chunk_term_freq DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +02653d40256c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 02882e91b704 ALTER TABLE loom.query_history_sources DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync 028cbc46b63f ALTER TABLE loom.memory_evidence DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +02b89044d357 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 02ba759cbc26 SELECT count() AS n FROM loom.dataset_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 02d00423f108 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 02e87ce1c9ea SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a -030e592bade2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +0313cfe27052 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 031cbd122ba7 ALTER TABLE loom.memory_ask_precedents DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 0326955f9efe SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 03637287975f SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -34,6 +36,7 @@ 039c3e0374f5 SELECT sa_subject, created_by, lineage FROM loom.service_accounts FINAL WHERE org = {org:String} AND name = {name:String} 03aba5278638 SELECT toUInt64(count()) AS n, toFloat64(avgOrDefault(token_count)) AS avgdl FROM loom.code_doc_stats FINAL WHERE org = {org:String} AND namespace = {ns:String} 03bf49ef6922 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value_len > ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, va +03e1542a5c25 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 03e1950e2a26 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread 03fb62bd1de3 ALTER TABLE loom.conversations UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {eras 04230db7e13e SELECT DISTINCT toInt64(units) AS units, ? AS erasure_type, ? AS erasure_value FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?) AND scope_value={ns:String} AND user_id={uid:Str @@ -44,47 +47,46 @@ 0473bb3df951 SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND namespace = {ns:String} 04777ef63345 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 048542c0e8b1 SELECT count() AS n FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL -04a330796db7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +04b952ad3fc2 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND namespace IN {ns:Array(String)} 04c23321e14b SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} 04ce236a9d90 SELECT org, namespace, source_uri, doc_id, title, content, tags, metadata, version, superseded_at, ingested_at, content_sha256, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, 04fe814e14a0 SELECT count() AS n FROM loom.tasks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND is_deleted = ? 050364b1b9a3 SELECT chunk_id, path, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} A -050e16b57409 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 053746111345 SELECT namespace, kind, owner_email, description, tags, active, conversation_logging_enabled, capture_generation_io, coverage_sweep, consolidation_enabled, daily_cost_cap_usd, daily_user_cost_cap_usd, 0538feb2d18d SELECT state_value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key = {key:String} LIMIT ? 054e6dab8b81 SELECT chunk_id, path, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} A 05510df8e69d ALTER TABLE loom.memory_projection_failures UPDATE status = ?, resolved_at = {at:DateTime} WHERE org IN {orgs:Array(String)} AND toString(failure_id) IN {failure_ids:Array(String)} AND status = ? AND 05b23580975b SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND namespace = {ns:String} -05bd530eef44 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 05cbd10620a9 SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} 05d1e8a8b89c SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc 05d68e77b952 SELECT m.memory_id, m.memory_key, m.value, m.pinned, m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, cosineDistance(e.embedding, {emb:Array(Float32)}) AS dist FROM loom.memory m FINAL JOIN loo 05eb1769fceb SELECT * FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model != {model:String} AND tombstoned_at IS NULL -061e30d3b4be SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 06360b1e4608 SELECT neighbor, sum(w) AS weight, argMax(seed, w) AS via_seed FROM ( SELECT entity_b AS neighbor, co_occur AS w, entity_a AS seed FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns_ +065d1ae244d0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 0663f6f57816 SELECT ? AS kind, value, total AS count FROM ( SELECT arrayJoin(tags) AS value, count() AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL A 067f506e1886 SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND user_id = {uid:String} AND memory_id NOT IN (SELECT memory_id FROM loom.memory FINAL WHERE org = {org:String} AND memory_i +06839885846a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 069733204bd0 SELECT count() AS n FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND if(session_id = +069935ea2b36 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +06ad1b41aedd SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 06b297a2e8a7 SELECT src_path, test_path FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND method = {method:String} AND tombstoned_at IS NULL -06f5eeb27d54 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 06ff2b38df31 SELECT count() AS n FROM loom.agent_runs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND grade != ? AND started_at >= now() - INTERVAL {win:UInt32} SECOND 07417011df11 SELECT category_id, count() AS item_count FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL GROUP BY category_id 0775de50682c SELECT max(updated_at) AS updated_at FROM loom.blacklist_version 079b92892a64 ALTER TABLE loom.documents DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 07f0130e01ef SELECT count() AS n FROM ( SELECT evidence_id, tombstoned_at FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND se -07fb8f365a46 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0816a510f9d6 ALTER TABLE loom.knowledge_ingest_cancels DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 081ae5bd0da9 ALTER TABLE loom.conversations UPDATE tombstoned_at = {now:DateTime} WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND tombstoned_at IS N 0864a7a96605 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU 0871bd510695 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom 0874603d8218 SELECT duplicate_of AS canonical_id, count() AS dup_count, groupArray(?)((memory_id, memory_key, agent, created_at)) AS dups FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} -087592d82096 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 087a1ee7374c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 089042275ad2 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 08a7cc3679db SELECT DISTINCT units, toString(digest) AS anchor FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?,?) AND scope_value={ns:String} AND user_id={uid:String}) OR (scope_kind=? AND 08bde665b126 SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} 08f67c0b9944 SELECT number, is_pr, state, state_reason, author, title, labels, opened_at, closed_at, merged_at, updated_at, head_sha, base_sha, files FROM loom.code_gh_items FINAL WHERE org = {org:String} AND name 091a5b6e28bb SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} +092355e7be59 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 092b4e7347ba ALTER TABLE loom.query_nodes DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 092fea064f1d SELECT org, namespace, source_uri, doc_id, title, description, content, tags, metadata, version, superseded_at, ingested_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, ori 0934ab49d07b SELECT toString(memory_id) AS id, uniqExact(version) AS versions FROM loom.memory_versions WHERE org = {org:String} AND namespace = {ns:String} AND memory_id IN {ids:Array(UUID)} GROUP BY memory_id @@ -99,28 +101,23 @@ 0a1c979e7c7c SELECT pr_number, groupUniqArray(author) AS reviewers FROM loom.code_pr_reviews FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number IN {nums:Array(UInt32)} AND is_bot = false AND 0a2e9f72aa7a SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND namespace IN {ns:Array(String)} 0a8192fba06f ALTER TABLE loom.memory_categories UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_ -0a96e5fd0ce8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0af74f951e80 ALTER TABLE loom.search_misses DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 0b0c34b379f4 SELECT count() AS n FROM loom.documents WHERE org = {org:String} AND user_id != {uid:String} AND superseded_at IS NULL AND cityHash64(namespace, source_uri) IN {docs:Array(UInt64)} 0b2232f64806 SELECT memory_key, memory_type, content_excerpt, ? - cosineDistance(embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(temporal_anchor, toDateTime(?))) AS temporal_anchor, temporal_confi -0b2d5876bfed SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0b4f7cc315ea SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 0b5058ee7142 SELECT event_type, count() AS cnt, min(ts) AS first_ts, max(ts) AS last_ts FROM loom.audit_log WHERE ts >= toDateTime64(now() - INTERVAL {since:UInt32} SECOND, ?, ?) AND NOT match(namespace, ?) GROUP 0b9b692a0146 SELECT version, pinned, lock_mode, lock_until, sensitivity, tags FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND user_id = {uid:String} AND agent = ? AND session_id = ? 0bc3c370840a SELECT count() AS n FROM ( SELECT pr_number FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number = {pr:UInt32} AND tombstoned_at IS NULL AND merged_at > ( 0bc94430cb61 SELECT user_id AS name, count() AS n, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) AND user_id NO 0bd7fa669a1d SELECT org, namespace, agent, user_id, session_id, run_id, goal, user_request, expected_outcome, environment, model, consumer, status, started_at, completed_at, duration_ms, final_response, confidence -0bf23a0ea1ed SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -0c01fd5b408f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0c17515461b3 SELECT identity_agent, user_id, session_id, record_json, created_at FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace = {ns:String} AND schema_name = {schema:String} AND status = ? 0c21fda60b05 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont -0c30860cea7b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0c4c81666597 SELECT head, samples FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace = {ns:String} AND gap_id = {gap:String} AND build = (SELECT max(build) FROM loom.knowledge_gaps WHERE org = {org:St 0c5526d83da4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist +0c64438b4ac8 DELETE FROM loom.read_receipts WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 0c999f060efc SELECT proposal_policy FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 0cfc88297bf0 SELECT count() AS n FROM loom.knowledge_ingestions WHERE org = {org:String} AND namespace = {ns:String} 0d0074d068cf SELECT queue_id, agent, user_id, session_id, status, attempts, message_count, content_chars, written, last_error, enqueued_at, updated_at FROM loom.memory_extraction_queue FINAL PREWHERE org = {org:St -0d722791e395 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 0db9931937d8 SELECT count() AS n FROM loom.memory WHERE org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String)) 0df388be7e18 SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND (JSONExtractString(payload, ?) = {uid:String} OR arrayExists(e -> JSONExtractString(e, ?) = {uid:String}, JSONExtr 0df8d59119a4 SELECT org, namespace, policy_id, effect, description, actions, condition, enabled, mode, created_by, created_at, updated_at, tombstoned_at FROM loom.namespace_policies FINAL WHERE org = {org:String} @@ -139,18 +136,17 @@ 0fd1cbc1eecb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 0fdc18bb9750 SELECT memory_key, argMax(tombstoned_at IS NOT NULL, version) AS deleted, argMax(status, version) AS head_status, argMax(content_sha256, version) AS head_sha256, argMax(sensitivity, version) AS head_s 0ff9c942958d SELECT * FROM loom.code_chunks FINAL WHERE (org, namespace, embedding_model, path, chunk_id) IN {keys:Array(Tuple(String, String, String, String, String))} AND tombstoned_at IS NULL +101a174f99e3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 1030febb1e77 ALTER TABLE loom.chunks UPDATE doc_superseded_at = {now:DateTime} WHERE (org = {org:String} AND user_id = {uid:String} AND doc_superseded_at IS NULL) AND ({erasure_mutation_tag:String} = {erasure_muta 1032019497c6 SELECT value, memory_type, confidence, promoted_from, promotion_event, promoted_from_candidate_id, promoted_by, rationale, promoted_at, reversible_until, tombstoned_at, version FROM loom.shared FINAL 1036d9982eb4 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at 1069a110039a SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 107be5b763da SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 109db307d85f SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND user_id = {uid:String} AND doc_superseded_at IS NULL -10ff90cbf7b6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 11073f58b15c SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND agent != {id:String} AND user_ 1116bf60755b SELECT {literals:Array(String)}[held] AS literal, chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( i -> m 1150f6c7a8f5 SELECT * FROM loom.memory_embeddings FINAL PREWHERE (org, namespace, agent, user_id, session_id, memory_key) IN arrayZip( {o:Array(String)}, {n:Array(String)}, {a:Array(String)}, {u:Array(String)}, {s 1151127d54f9 SELECT ? AS present FROM loom.code_summaries WHERE org = {org:String} AND namespace = {ns:String} AND scope_type = ? AND pagerank > ? AND tombstoned_at IS NULL LIMIT ? -118b55a24b40 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 11c20f09352b SELECT org, namespace, agent, user_id, session_id, queue_id, payload, message_count, content_chars, status, attempts, lease_until, last_error, written, enqueued_at, updated_at, version, enqueued_by FR 11c411e29cb8 SELECT memory_key, argMax(tombstoned_at IS NOT NULL, version) AS deleted, argMax(status, version) AS head_status, argMax(content_sha256, version) AS head_sha256, argMax(sensitivity, version) AS head_s 11cedbaa6be7 SELECT memory_key, if(rn <= {ceiling:UInt32}, value, ?) AS value, promoted_from, promoted_at, promotion_event, total FROM ( SELECT memory_key, value, promoted_from, promoted_at, promotion_event, row_n @@ -165,52 +161,44 @@ 1293be9506e5 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 1295024350b9 ALTER TABLE loom.memory_record_fields UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasu 12fd2ac43350 SELECT count() AS n FROM loom.session_outcomes_by_user WHERE org = {org:String} AND namespace = {ns:String} -1331e86914d6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 13890ea9a3f4 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { 13d52fc9398f SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 13e2c549c1f2 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {o -13e45981aae2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 13eb341253e0 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR +14062fc1c31b SELECT memory_key, memory_type, if({full_values:UInt8}, value, substring(value, ?, if((memory_type = ? OR hasAny(tags, [?, ?])), {whole_bytes:UInt32}, ?))) AS value, tags, confidence, pinned, CAST(sta 1425256025b1 SELECT src, dst, relation, direction, pair_co_occur, provenance FROM ( -- The aggregate alias must NOT be `co_occur`: shadowing the source -- column makes ClickHouse resolve the HAVING reference into -145aca79b883 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 14697ca6bfd3 ALTER TABLE loom.dataset_rows DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 147a8c9b17f2 SELECT sum(upstream_cost_usd) AS spent, sumIf(upstream_cost_usd, operation = {op:String}) AS own, sumIf(upstream_cost_usd, user_id = {uid:String}) AS user_spent, sumIf(upstream_cost_usd, user_id = {ui 14c924c1ec78 SELECT agent, user_id, session_id, memory_key, arrayReverseSort(groupArray((version, deleted, target))) AS versions FROM ( SELECT agent, user_id, session_id, memory_key, version, tombstoned_at IS NOT -15107eb3cae0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -15305ed67ee3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 1531893b0f7d SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 154aea8f41f9 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 1552f717160b SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, -155bb556af22 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 156c81c0e9bc SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns 15c48e67a57a SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 15ee0c6d12dd SELECT count() AS n FROM loom.procedure_runs WHERE org = {org:String} AND namespace IN {ns:Array(String)} 15fc912a653c SELECT org, namespace, source_uri, doc_id, title, tags, version, revision, access_json, superseded_at, ingested_at, content_sha256, format, parser, coverage, ingestion_id, artifact_sha256, blob_path, -1602737f595c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 161726b6fb23 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to 167fa87844b1 ALTER TABLE loom.entity_summaries DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1683de848d27 SELECT count() AS n FROM loom.entity_edges WHERE org = {org:String} AND namespace = {ns:String} AND ? 16856971c616 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND cityHash64(namespace, subject, relation, object) IN {owned:Array(UInt64)} 168996bf0400 SELECT DISTINCT subject FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} -- both sides lowered by ClickHouse, as the grant map lowers them AND has(arrayMap(s -> lo -16a2b5def24b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 16cf9f836a3a SELECT count() AS n FROM loom.entity_vectors WHERE org = {org:String} AND namespace IN {ns:Array(String)} -16df003ef8b4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 16f21c116c6f SELECT session_id, chunk_index, groupUniqArray(memory_key) AS memory_keys FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND namespace = {ns:String} AND session_id IN {sessions:Array(St 172b5834ddd7 ALTER TABLE loom.session_outcomes_by_user DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1735014353cb SELECT agent, count() AS rows, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL GROUP BY agent ORDER BY rows DESC, agent L 173cb2ae58ea SELECT pr_number, title, author, labels, merged_at, files, assignees, body_excerpt, linked_issues, additions, deletions, -- mirrors code/domain/index/pr_signals.is_revert_pr (match(title, ?) OR positi 175d3d8b3854 SELECT src_path, test_path, confidence, evidence FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND src_path IN {paths:Array(String)} AND method = ? AND tombstoned_ 17612729b3e2 SELECT * FROM loom.learnings_queue FINAL WHERE org = {org:String} AND candidate_id IN {cids:Array(UUID)} -1799e5db040e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +17728127ac3b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 17d1d3c496e4 SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND (cityHash64(namespace, entity) IN {entities:Array(UInt64)} OR cityHash64(namespace, label) IN {entities:Array(UInt64)}) -17dac6a35956 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -17e1defc0d07 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +17d4638f8bb5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 181170548081 SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns 181f7665f4ab SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, dateDiff(?, updated_at, now()) AS age_days, length(conflict_with) AS peers FROM loom.memory FINAL WHERE org = {org:String 182b2004f117 SELECT active, toString(contact_email) AS contact_email, password_hash = ? AS sso FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 1874492b7e5b SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace = {ns:String} 1891df92bb07 SELECT DISTINCT org FROM ( SELECT org FROM loom.namespaces FINAL WHERE owner_email = {s:String} AND active = ? UNION ALL SELECT org FROM loom.namespace_grants FINAL WHERE lower(subject) = lower({s:Str 18beffc43c3d SELECT memory_key_a, memory_key_b, allowed_at, allowed_by, reason FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY allowed_at +18e170c06a0c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 1904c89aac43 SELECT uniqExact(path) AS n FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND startsWith(path, {prefix 1906e06d78a5 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, memory_key, version, ? AS value_json, toJSONString(content_exc 190702c74f85 SELECT ts, actor, subject FROM loom.audit_log WHERE org = ? AND namespace = ? AND event_type = {event:String} AND ({name:String} = ? OR JSONExtractString(subject, ?) = {name:String}) ORDER BY ts DESC @@ -221,7 +209,6 @@ 19acdb7285ea SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} 19b86ccb59a0 SELECT * FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL 19bf5552e29f ALTER TABLE loom.memory_belief_sources UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} -19d1d90ea590 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 19dbe94c1af5 SELECT DISTINCT content_excerpt AS t FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND session_id = {s:String} 19ec71ce3c42 SELECT org, namespace, source_uri, chunk_idx, content, context, tags, doc_metadata, chunk_metadata, ingested_at, doc_superseded_at, embedding_model, embedding_dim FROM loom.chunks WHERE org = {org:Str 19f1db04c7f7 ALTER TABLE loom.entity_triples DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -232,10 +219,12 @@ 1a6a02f4cb48 SELECT pr_number, title, merged_at FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at >= {since:DateTime} AND (hasAny(files, { 1a99a12c31c7 SELECT count() AS n, if(n = ?, NULL, max(updated_at)) AS latest FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = ? AND tombstoned_at IS NULL 1ab144ee2ae9 SELECT toString(m.memory_id) AS mid, m.org AS org, m.namespace AS namespace, m.agent AS agent, m.user_id AS user_id, m.memory_key AS memory_key, m.reinforcement_count AS reinforcement_count, coalesce( +1ab98577390b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 1adf35203901 SELECT record_id, parent_memory_key, session_id, schema_name, record_json, field_text, lexical_score, least( ?, ? * lexical_score + ? + ? ) AS rank_score, -- NB: alias the stringified date as *_iso, N 1aef76e6d083 SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} +1afa6c36738c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +1b590eff20c7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 1b6020dc7d2f SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, embedding_model, embedding, version, content_sha256, status FROM loom.memory_embeddings FINAL WHERE (org, namespace, agent, -1b99a5d0c69c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 1b9df594185a SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND user_id = {uid:String} AND ? 1bc7a4e72aad SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND namespace IN {ns:Array(String)} 1bea4af4ad7c SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} @@ -246,6 +235,7 @@ 1ca42e357807 ALTER TABLE loom.entity_triple_rows DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1ca47c4c11f3 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 1cb430ccdf4d SELECT ? FROM (SELECT * FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND msg_id IN {ids:Array(Str +1ccbc41cb8ff SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 1cfc6f95dc0f SELECT uniqExact(pr_number) AS fixes, count() AS branch_rows, max(computed_at) AS last_computed, min(computed_at) AS first_computed FROM loom.code_backport_gaps FINAL WHERE org = {org:String} AND code 1d111f0f3599 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND user_id = {uid:String} 1d56611f4e39 ALTER TABLE loom.blob_uploads DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -257,7 +247,6 @@ 1db80df6143e SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace = {ns:String} AND ? 1dc228ffa971 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 1dd58eb93569 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -1deb753bdce4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 1e0e9634872a SELECT mention_text, canonical_text, confidence, evidence_count, created_at FROM loom.entity_canonical_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL LIMIT {l 1e223219a756 ALTER TABLE loom.memory_doc_stats DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 1e6bdc6d3711 SELECT ? AS present FROM loom.knowledge_sources WHERE (source_kind = ? OR kind = ? OR credential_mode = ?) LIMIT ? @@ -266,11 +255,8 @@ 1ea0c8768c0e SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 1ef2654703f8 SELECT DISTINCT source_uri FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(u -> startsWith(source_uri, concat(u, ?)), {uris:Array(String)}) ORDER BY sour 1f46432bb4a5 SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, degree FROM ( SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, row_number() OVER (PARTITION BY src -1f7f08f173b3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 1f90ede3098e SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 1fd1361296a7 SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () AS total FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(pa -202a8461a799 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -203271a48bf1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2048d3599a42 SELECT DISTINCT namespace, memory_key FROM loom.shared FINAL WHERE org = {org:String} AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(promoted_from, {sources:Array( 2056fb3f58af SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} 208cd8ce06ff SELECT session_id FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND tombstoned_at IS NULL AND session_id @@ -283,10 +269,8 @@ 21662d2b21ba SELECT coalesce( nullIf(toString(value_json.x), ?), JSONExtractString(value, ?)) AS x_g, count() AS metric FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agen 216ad9ee2d07 SELECT count() AS n FROM loom.delete_version_checks WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 21dde6a63f09 SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FROM ( SELECT namespace, thread_id, ts, msg_id, row_bytes, sum(row_bytes) OVER (ORDER BY namespace, thread_id, ts, msg_id ROWS BETWEEN -21f75f729515 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 21fe5bec912f SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND agent = {agent:String} 220a9f3ad17c SELECT DISTINCT name, qualified_name FROM loom.code_symbol_names FINAL WHERE org = {org:String} AND namespace = {ns:String} AND name IN {bares:Array(String)} AND tombstoned_at IS NULL LIMIT ? -220cd62bab8c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2213d888d1fc ALTER TABLE loom.chunk_term_freq DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 223891b31b82 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 22508f757954 SELECT thread_id, title, metadata, run_id, user_id, created_at, updated_at, agent FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} @@ -295,6 +279,8 @@ 22612cf3a394 SELECT namespace, source_uri, public_namespace, public_uri FROM (SELECT namespace, source_uri, indexOf({bindings:Array(Tuple(String, String))}, (namespace, right(source_uri, ?))) AS binding, arrayElem 2261d5bd6945 SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND content_sha256 IN {hashes:Array(String)} AND source_uri != {ex:String} AND doc_superseded_at IS NULL AND ( 226e4e3d52e6 SELECT pr_number, title, merged_at FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at >= {since:DateTime} AND (arrayExists(f - +22bb5ae78bee SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +22d5f4746f1f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 22e0a45e948a SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, toString(chunk_index), ?, content_sha256) AS memory_ 22e4b395ef49 ALTER TABLE loom.conversation_threads UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} 22eb12673f82 SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND user_id = {uid:String} @@ -305,6 +291,7 @@ 232204b29bcb ALTER TABLE loom.document_blobs DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 2347071a201b SELECT chunk_id, path, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} A 235fd0c4725c SELECT path, content_hash, context_text, embedding FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND path IN {paths:Array(String +236f4e2a3800 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 23c7e58243f2 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} 241610b30143 SELECT count() AS n FROM loom.session_briefs WHERE org = {org:String} AND namespace = {ns:String} 24168bc01a22 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user @@ -328,8 +315,6 @@ 25de1e18cb52 SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:String} AND user_id = {uid:String} 25ec5ad61cad SELECT count() AS n FROM loom.memory_term_freq WHERE org = {org:String} AND namespace = {ns:String} 25f13428bdaf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist -25f6c93d15d9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -25fbab541f36 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2602243148c9 SELECT count() AS n FROM loom.memory_doc_stats WHERE org = {org:String} AND namespace IN {ns:Array(String)} 26074fce7af4 SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace = {ns:String} 2616ad6a7aa2 SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -339,6 +324,7 @@ 263e0e516f53 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND namespace = {ns:String} 265e1e1ea76e SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance(embedding, {q:Array(Float32)}) AS distance, ? AS lexical, [] AS matched FROM loom.c 267ecd9bc043 SELECT count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +268fe39744ca SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 26a0805d2f62 SELECT f AS path, argMin(pr_number, merged_at) AS first_pr, min(merged_at) AS first_merged_at FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} 26ab94c3ceb1 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU 26c7bcb3fa76 SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND hasAny(window_keys, arrayConcat((SELECT groupUniqArray(memory_key) FROM loom.memory WHERE org = {org:String} AND user_id = @@ -357,6 +343,7 @@ 2869ad9e327d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 286bea24dbf7 SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} 287f753fd62a SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND namespace = {ns:String} +2896992dca58 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 28ac67fce8dc SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, 28d50d57494f SELECT * FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND tombstoned_at IS NULL 28f66520523f SELECT count() AS n FROM loom.blob_uploads WHERE org = {org:String} AND namespace = {ns:String} @@ -365,20 +352,22 @@ 294597853414 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 294c529534b2 SELECT from_key AS memory_key, relation, toString(created_at) AS created_at FROM loom.operator_edges FINAL WHERE org = {o:String} AND namespace = {n:String} AND to_key = {k:String} AND tombstoned_at I 296456fcd1e6 SELECT countIf(kind = ? AND consumer NOT IN {inspectors:Array(String)} AND operation != ?) AS attempts, countIf(kind = ? AND consumer NOT IN {inspectors:Array(String)} AND operation != ? AND success) +297eb05014d4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 29a0a6e6456c SELECT (SELECT min(merged_at) FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL) AS pr_from, (SELECT max(merged_at) FROM loom.code_pr_histo 29b51c035ace SELECT block_key, content, char_limit, version, updated_at FROM loom.working_memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND 29c3e6ecef0f SELECT DISTINCT namespace FROM loom.learnings_queue FINAL WHERE org = {org:String} AND source_kind IN {private_kinds:Array(String)} 29d8a27b9a71 SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, verified_by, verified_at, dateDiff(?, verified_at, now()) AS attested_days_ago FROM loom.memory FINAL WHERE org = {org:St +29dd3462bc99 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2a07cf2c351d SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND status != ? AND status != ? AND status != ? AND agent = {a 2a21b625bbc3 SELECT toString(memory_id) AS memory_id, org, namespace, agent, user_id, session_id, memory_key, toString(value) AS value, pinned, valid_at, created_at, updated_at, version, redacted_at, toString(cont -2a44383c565f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -2a4c344dc346 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2a5db1d4ffaa SELECT name, category_id FROM loom.categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND name IN {names:Array(String)} AND tombstoned_at IS NULL 2a8380b2d95e SELECT toUInt32(countDistinct(seq)) AS n FROM loom.code_scip_parts WHERE org = {org:String} AND namespace = {ns:String} AND batch_id = {bid:UUID} +2a90bda9fe59 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2ac2ff622b95 SELECT op, returned_ids, returned_paths, abstain, route, args_json FROM loom.code_search_trace WHERE org = {org:String} AND namespace = {ns:String} AND trace_run_id = {rid:String} AND ts > now() - INT 2ac704bcfa82 SELECT namespace, max(last_write) AS last_write FROM loom.namespace_write_marks WHERE (org = {org:String} AND namespace IN {nss:Array(String)}) OR (org = ? AND namespace = ?) GROUP BY namespace 2acea788fdac SELECT count() AS n FROM loom.agent_runs WHERE org = {org:String} AND namespace = {ns:String} AND ? 2af0d1f09e9c SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +2b17f08d1a09 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2b19dd7cec5e SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR 2b2fcb364a16 SELECT org, namespace, facet_kind, name, path, ordinal, line, confidence, indexed_commit, tombstoned_at, created_at, version FROM loom.code_test_facets FINAL WHERE org = {org:String} AND namespace = { 2b3b54e956dd SELECT count() AS scanned, countIf(symbol_id NOT IN ( SELECT to_symbol_id FROM loom.code_edges WHERE org = {org:String} AND namespace = {ns:String} AND edge_kind = ? AND tombstoned_at IS NULL)) AS unc @@ -388,6 +377,7 @@ 2bc18b5b99bf SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND ((namespace, memory_key) IN (SELECT namespace, memory_key FROM loom.memory WHERE org = {org:String} AND user_id = {uid 2bc760875b65 DELETE FROM loom.code_answers WHERE (org = {org:String} AND (namespace = {ns:String} OR memory_namespace = {ns:String})) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS li 2c04b7b2650d SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} +2c2ad0d73583 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2c5e3c3099fc SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 2cad8bf84992 SELECT org, qa_namespace, issue_number, pr_number, rank, score, bm25_title, bm25_body, bm25_norm, window_hours, component_match, frames_symbols, frames_files, frames_total, closes_mention, terms, pr_t 2cbb59e64f4a SELECT path FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL @@ -408,12 +398,13 @@ 2e5cc0f7531e SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a 2e63bd24d8df SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 2e661191cba4 SELECT count() AS n FROM system.mutations WHERE database = {db:String} AND table = {name:String} AND NOT is_done AND match(command, ?) -2e755b234427 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2e91f70c748e DELETE FROM loom.memory_chunks WHERE (org = {org:String} AND (user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN {keys:Array(Tuple(String, String))}))) AND ({erasure_mutation 2ed709d1c719 SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 2eeae7d3e832 SELECT path, scope, kind, start_line, end_line, content FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL AND 2f03e5440755 SELECT pr_number, title, labels, merged_at, merge_commit_sha FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at >= {since:Date +2f476975ad71 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2f87519d6c67 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL +2fa5c1f4e23c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 2fab97e447f4 SELECT count() AS n FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 2fc0cc735773 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 2fd8ca033214 DELETE FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND if(session_id = {ss:String}, @@ -429,23 +420,20 @@ 31448ef63205 SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, valid_to, dateDiff(?, valid_to, now()) AS days_past FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:S 31611f39fb5c SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { 31716a5618f9 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? -31a3c7ed1429 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 31b4d2370bfc SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a 32003fb01e5d SELECT holder, acquired_at, ttl_s, (renewed_at + toIntervalSecond(ttl_s)) < now64(?) AS stale FROM loom._migration_lock WHERE name = {name:String} 321ac4055c75 SELECT count() AS n FROM loom.tasks WHERE org = {org:String} AND namespace = {ns:String} 321fcca0963a ALTER TABLE loom.memory_records UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mut +324135a22d05 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 324ff895a2e7 SELECT j.*, ifNull(d.doc_live, ?) AS has_document, j.open_jobs = ? AND ifNull(d.doc_written_at, toDateTime(?)) > toDateTime(j.latest_updated_at) AS replaced FROM ( SELECT source_uri, count() AS jobs, 326c31c72256 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 3287616dab35 SELECT count() AS n FROM loom.documents WHERE org = {org:String} AND user_id = {uid:String} 328c58ef9dbc SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 32931cd0870a SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -3296d59f88ce SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -3298846483ff SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 32a0622ffdb7 DELETE FROM loom.memory_chunks WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 32aeaaa9dcea SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 32b8fda40451 SELECT greatest(toUInt64(toUnixTimestamp64Nano(now64(?))), max(version) + ?) AS v FROM loom.code_index_state WHERE org = {k0:String} AND namespace = {k1:String} AND state_key = {k2:String} 32cc48140047 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { -32f125aa8b0c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 330223892c54 ALTER TABLE loom.oauth_signin_state DELETE WHERE claim_key = {k:String} AND value = {v:String} SETTINGS keeper_map_strict_mode = ?, max_execution_time = ? 332512811b3a SELECT chunk_id, path, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} A 33259268a673 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist @@ -457,11 +445,12 @@ 33bb6d3ee095 SELECT DISTINCT subject FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} -- both sides lowered by ClickHouse, as the grant map lowers them AND has(arrayMap(s -> lo 33bdfb31c03a SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND user_id = {uid:String} 33c8db3a36dd SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND ((namespace, entity) IN (SELECT namespace, entity FROM (SELECT namespace, entity_a AS entity, memory_key FROM loom.entity_ +33cdac13416a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 33ce237afae6 SELECT source AS consumer_key, count() AS outcome_rows, countIf(action IN (?, ?)) AS outcome_positive, countIf(action IN (?, ?)) AS outcome_negative, countIf(action IN (?, ?)) AS shunt_rows, sum(token +33d179d9b1ff SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor))) 33db1f0050ff SELECT path, uniqExact(facet_kind, name) AS matched, groupArray((facet_kind, name, ordinal, line, confidence)) AS hits, ? AS co_occurs FROM loom.code_test_facets FINAL WHERE org = {org:String} AND nam 3403e1e98ed1 SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, status, proposed_at, decided_at, decided_b 341b6eb8dac2 ALTER TABLE loom.operator_edges UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {era -341c19706973 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 342653bd9d76 SELECT to_symbol_id AS symbol_id, max(to_q) AS qualified_name, count() AS fan_in_calls, countIf(NOT match(path, {noise:String})) AS fan_in_nontest, uniqExact(path) AS caller_files FROM ( SELECT to_sym 342f026b3008 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND namespace = {ns:String} AND ? 343b7c396165 SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -478,7 +467,6 @@ 3556360a339b SELECT m.org, m.namespace, m.agent, m.user_id, m.session_id, m.memory_key, m.memory_type, m.value AS content_excerpt, m.run_id, m.entities, m.tags, m.files, m.concepts, m.valid_at, m.valid_to, m.expir 35aac92ad0a8 SELECT toString(memory_id) AS memory_id, agent, user_id, session_id, memory_key, memory_type, value, toString(value_json) AS value_json, confidence, source_trace, version, tombstoned_at, created_at, e 35b95e4edd22 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL -35c8e97591f4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 35d1bf602130 SELECT role FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND lower(subject) IN {subs:Array(String)} AND revoked_at IS NULL AND status = ? ORDER BY multiIf(role 35dc32428e96 SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND (prior_record_id IN {ids:Array(UUID)} OR incoming_record_id IN {ids:Array(UUID)}) 35e32b8b4bb0 SELECT owner_email, contact_email FROM loom.namespaces FINAL WHERE org = {org:String} AND ifNull(active, true) = true AND contact_email != ? AND (password_hash = ? OR (org, namespace, contact_email) I @@ -486,6 +474,7 @@ 3601acc0a3e4 SELECT jti, issued_before, revoked_by, revoked_at, expires_at FROM loom.revoked_tokens FINAL WHERE jti IN {keys:Array(String)} AND expires_at > now() 360f8238361a SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} 362f57a395d3 SELECT org, namespace FROM loom.code_symbol_stats WHERE org IN {orgs:Array(String)} AND namespace IN {namespaces:Array(String)} GROUP BY org, namespace +366444f4cbb7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 3696ba20e278 SELECT leftPad(lower(hex(groupBitXor(sipHash64(memory_id, content_sha256, confidence, coalesce(valid_at, updated_at))))), ?, ?) AS digest, count() AS n FROM loom.memory FINAL WHERE org = {org:String} 36c56add9f31 SELECT issue_number, max(computed_at) AS latest FROM loom.qa_link_candidates FINAL WHERE org = {org:String} AND qa_namespace = {ns:String} AND issue_number IN {nums:Array(UInt32)} GROUP BY issue_numbe 37222534b76c SELECT count() AS n FROM loom.knowledge_source_listings WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -493,6 +482,7 @@ 37740a4c5dba SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND user_id = {uid:String} 378589d81d6f SELECT count() AS n FROM loom.operator_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 379cd09b4b77 ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +37ad205d92c2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 37d3add2a1a2 SELECT count() AS n FROM loom.knowledge_source_push WHERE org = {org:String} AND namespace = {ns:String} 37e82d44def8 SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND namespace = {ns:String} 380b4d047f79 SELECT m.org AS org, m.namespace AS namespace, m.user_id AS user_id, count() AS n FROM loom.memory AS m FINAL INNER JOIN loom.namespaces AS n FINAL ON m.org = n.org AND m.namespace = n.namespace WHERE @@ -523,9 +513,10 @@ 3aee32f6c95a WITH docs AS ( SELECT thread_id, msg_id, any(role) AS msg_role, argMax(content, ts) AS body, max(ts) AS saved_at, arrayFilter(t -> length(t) >= ?, splitByNonAlpha(lowerUTF8(body))) AS words FROM loom. 3b05a28d96f2 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3b1ae278b7f6 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { -3b4b4580cc9a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +3b47eb3efe68 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 3ba235828531 ALTER TABLE loom.documents UPDATE superseded_at = {now:DateTime} WHERE (org = {org:String} AND user_id != {uid:String} AND superseded_at IS NULL AND cityHash64(namespace, source_uri) IN {docs:Array(UI 3bab9ca71efb SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND ((user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN (SELECT namespace, memory_key FROM loom.me +3bc65895959f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 3bcf2270da8d SELECT count() AS n FROM loom.query_nodes WHERE org = {org:String} AND namespace = {ns:String} 3bf5cab894ce SELECT {literals:Array(String)}[held] AS literal, chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( i -> m 3c31742569aa SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns @@ -538,20 +529,19 @@ 3d1528d28966 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 3d5f2761d6fe SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3d5ff23ff854 ALTER TABLE loom.memory_code_links DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -3d6ba2ce3958 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 3d8049f7a5b0 SELECT thread_id, count() AS msg_count, min(ts) AS first_seen, max(ts) AS last_seen FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND ts > now() - toIntervalDay({wd:UInt 3d84a6e7023a SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(content, ?, {listed:UInt32}), ts) AS content, max(c.saved_at) AS saved_at FROM loom.conversations AS c WHERE org = {org:String} AND na 3d86e656f60d SELECT DISTINCT units, toString(digest) AS anchor FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?) AND scope_value={ns:String} AND user_id={uid:String}) OR (scope_kind=? AND sc 3db4fecd9fa4 ALTER TABLE loom.memory_exposures DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 3dbe507e1cfb SELECT src AS src_path, tst AS test_path, count() AS n FROM ( SELECT pr_number, arrayJoin(arrayFilter(f -> NOT startsWith(f, ?), files)) AS src, arrayJoin(arrayFilter(f -> startsWith(f, ?), files)) AS 3dd0aee92803 SELECT count() AS turns, countIf(NOT priced) AS unpriced, sum(cost_usd) AS cost FROM loom.agent_turn_usage FINAL WHERE org = {org:String} AND namespace = {ns:String} AND session_id = {sid:String} AND +3dddb32f4ac8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 3de627934fdd SELECT pi, path, count() AS chunks, min(start_line) AS first_line FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( i -> position(content, {pats:Array(String)}[i]) > ?, arrayEnumerate({pats:Array(St 3debdbf01b64 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 3e00482285b2 SELECT count() AS n FROM loom.entity_vectors WHERE org = {org:String} AND namespace = {ns:String} 3e18758b5b32 ALTER TABLE loom.session_outcomes_by_user DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s 3e2075d7a93f SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 3e2b5291eea1 SELECT ? AS in_use FROM ((SELECT ? FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND revoked_at IS NULL AND status = ? LIMIT ?) UNION ALL (SELECT ? FROM loom.me -3e48779bb136 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 3e750c517754 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 3ea44fb37980 ALTER TABLE loom.session_briefs DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 3eb6ce41ac13 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { @@ -570,12 +560,14 @@ 4014f350fe0d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 40196660a417 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace IN {nss:Array(String)} A 4031751e6622 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND user_id = {uid:String} +40380c354127 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 40572eb4f789 SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace = {ns:String} 4091a6de6c4d SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL 4094b2b5ad1d SELECT countIf(startsWith(name, ?)) AS patch_parts FROM system.parts WHERE database = {db:String} AND table = {t:String} AND active 40d51d7bb87a ALTER TABLE loom.memory_evidence DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 40d90ca12f13 SELECT number FROM loom.code_gh_items FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND is_pr AND state = ? ORDER BY updated_at DESC, number DESC LIMIT {limit:UI 40dfbf0248ef SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, content, context, tags, chunk_metadata, ingested_at, agent, session_id, toString(source_class) AS +40e24f5cf835 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 4113c01ac87f SELECT memory_key, count() AS matches FROM (SELECT tm.memory_key FROM loom.entity_triple_memories AS tm INNER JOIN loom.entity_triples AS t ON t.org = tm.org AND t.namespace = tm.namespace AND t.subje 413b4ddac97c SELECT pr_number, merge_sha, payload, sections, built_at, indexed_commit, tokens, build_ms FROM loom.code_review_briefs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS 415f2e580ed9 SELECT * FROM loom.service_accounts FINAL WHERE org = {org:String} AND (created_by = {by:String} OR has(lineage, {by:String})) AND NOT hasAll(lineage, {above:Array(String)}) AND (expires_at IS NULL OR @@ -612,7 +604,6 @@ 44a0f92f53ee SELECT pr_number, title, author, files, merged_at, linked_issues, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {tokens:Array(String)}, {idfs:Array 44b352c793fc SELECT DISTINCT start_line, end_line, content, kind, scope, symbol_ids, toString(indexed_commit) AS indexed_commit FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND 44be9faca8dd SELECT pr_number, title, author, merged_at, files, linked_issues, (match(title, {revert_re:String}) OR positionCaseInsensitive(body_excerpt, ?) > ? ) AS is_revert FROM loom.code_pr_history FINAL WHERE -44c4e646c377 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 44fe95e059ce ALTER TABLE loom.blob_uploads DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 450e3ad5b8bd ALTER TABLE loom.agent_runs DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4513efbe8bcb SELECT count() AS n FROM loom.blob_uploads WHERE org = {org:String} AND user_id = {uid:String} AND ? @@ -629,7 +620,6 @@ 45b2ddeb9077 SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND namespace = {ns:String} AND ? 460bf05872eb SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a 460e68ed6d10 SELECT row_hash FROM loom.audit_log WHERE org IN {orgs:Array(String)} AND namespace IN {nss:Array(String)} AND event_type = ? AND ts BETWEEN {first:DateTime64(?)} AND {last:DateTime64(?)} AND row_hash -460fbc2150ef SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 4623d58159c3 WITH m AS ( SELECT org, namespace, agent, user_id, session_id, memory_key, argMax(status, version) AS ms, max(version) AS mv, argMax(tuple(invalid_at), version).? AS invalid_at FROM loom.memory WHERE 4646e37d7905 SELECT org, namespace, agent, user_id, session_id, memory_key FROM ( SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND (arrayExist 465fe8dcbff7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist @@ -638,15 +628,20 @@ 46abdab5dec6 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 46c16fbf6c99 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 46e9280c500c ALTER TABLE loom.conversations UPDATE tombstoned_at = {now:DateTime} WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id IN {ids:Arr +46eeeed79d97 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 46fb9af13bbe SELECT DISTINCT msg_id FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND msg_id IN {mids:Array(String)} AND is_saved AND tombstoned_at IS NU 47183f9a2d9e SELECT chunk_id, path, scope, kind, start_line, end_line, embedding_dim, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings( concat(?, lexemes, ?), concat(?, tok, ?) ), {tokens:Array(String)}, {i +472c19b0284e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 472e38ad8c05 SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND namespace IN {ns:Array(String)} +473a9aaa708b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +475aef0da95a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 476e1eb1f2e5 ALTER TABLE loom.knowledge_uploads DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 477c2ea34273 SELECT category_id, name, description, substring(summary, ?, ?) AS summary_excerpt, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.categories FINAL WHERE org = {org:String} AND na -47cb339c8f67 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +478c120499f7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 47cc75ceb8fa SELECT count() AS n FROM ( SELECT evidence_id, tombstoned_at FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND se 47d6216caf2e SELECT number, state, author, title, labels, opened_at, closed_at, updated_at, files, title_hits, file_hit FROM ( SELECT number, state, author, title, labels, opened_at, closed_at, updated_at, files, 47db1deeabfd SELECT DISTINCT namespace FROM ( SELECT namespace FROM loom.memory WHERE org = {org:String} AND (namespace, agent, user_id, session_id, memory_key) IN ( SELECT namespace, agent, user_id, session_id, m +47df66ec3a80 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 47e13d18aa4f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 47ea41c2e2e8 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create 482347c34a21 SELECT memory_key, groupUniqArray(?)(ent) AS shared FROM ( SELECT other.memory_key AS memory_key, other.entity_a AS ent FROM loom.entity_edge_memories AS other WHERE other.org = {o:String} AND other.n @@ -657,6 +652,7 @@ 49041bd47683 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 492df45ef39b INSERT INTO loom.conversation_embeddings SELECT e.* EXCEPT (embedded, known) REPLACE (if(p.matched = ? AND e.known = ?, p.holder.?, e.agent) AS agent, if(p.matched = ? AND e.known = ?, p.holder.?, e.r 4967ddddb4bf ALTER TABLE loom.learnings_supporters DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync +4977a88315ca SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 49b4574ab213 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at 49bd450f5650 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id != {id:String}) GROUP 49c788209c09 SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND user_id = {uid:String} AND (superseded_at IS NULL OR (blob_path != ? AND blob_erased_at IS NULL)) @@ -670,20 +666,19 @@ 4aeabb5d4edf SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 4b25bd59f082 SELECT DISTINCT org, namespace, name, source_id, source_kind, owner_subject, connection_id FROM loom.knowledge_sources WHERE credential_mode = ? AND NOT (source_kind = ? OR kind = ? OR credential_mode 4b65a7bc66f1 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} +4ba366a556c0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 4baa66e24a1e SELECT pr_number, title, author, labels, merged_at, merge_commit_sha, linked_issues, body_excerpt FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND has(files, {p 4bcc327f9556 ALTER TABLE loom.knowledge_gaps DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4bfcae48a0ba ALTER TABLE loom.query_history_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4c0a0c4d2640 SELECT namespace, parent FROM loom.collections FINAL WHERE org = {org:String} AND NOT deleted 4c0ae4c5f102 SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND namespace IN {ns:Array(String)} 4c23e6d132bf SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND (user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN {keys:Array(Tuple -4c3d134f21ec SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 4c3f4eec49d0 SELECT count() AS n FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND session_id = {s:String} AND memory_key = {k:Str 4c5b7e5731dc SELECT e.agent AS agent, e.user_id AS user_id, e.session_id AS session_id, e.memory_key AS memory_key, max(e.version) AS version, argMax(e.tags, e.version) AS tags FROM loom.memory_embeddings AS e FIN 4c671d3f1cbc SELECT record_id, parent_memory_key, session_id, schema_name, record_json, field_text, lexical_score, least( ?, ? * lexical_score + ? + ? ) AS rank_score, -- NB: alias the stringified date as *_iso, N 4c7dd09282aa SELECT merge_commit_sha FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number = {pr:UInt32} AND tombstoned_at IS NULL AND merge_commit_sha != ? AND merged_ 4c809ae216d7 SELECT s.memory_key, s.value, cosineDistance(e.embedding, {emb:Array(Float32)}) AS dist FROM loom.shared s FINAL JOIN loom.memory_embeddings e FINAL ON e.org = s.org AND e.namespace = s.namespace AND 4cb8080c7ceb SELECT count() AS n FROM loom.scim_users FINAL WHERE deleted = ? AND has(addresses, {a:String}) -4cbab38c8950 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 4cffb3ebff8e ALTER TABLE loom.conversations UPDATE is_saved = true, user_id = {uid:String}, saved_at = coalesce(saved_at, {at:DateTime64(?, ?)}) WHERE org = {org:String} AND namespace = {ns:String} AND agent = {ag 4d19c2282f56 ALTER TABLE loom.session_brief_revisions DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sy 4d76718ea54e ALTER TABLE loom.memory DELETE WHERE (org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String))})) A @@ -692,12 +687,12 @@ 4e6e72b7fe21 SELECT mirror, namespace FROM loom.knowledge_mirrors FINAL WHERE org = {org:String} AND namespace IN {namespaces:Array(String)} AND NOT deleted ORDER BY mirror 4e7c07737d13 SELECT session_id, toString(coalesce(valid_at, created_at)) AS d FROM loom.session_summaries FINAL WHERE org = {o:String} AND namespace = {n:String} AND tombstoned_at IS NULL AND has(derived_from, {k: 4e88cc211a2e SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc -4ea86416312c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 4f01d06d9c9a SELECT record_id, parent_memory_key, session_id, schema_name, record_json, field_text, lexical_score, least( ?, ? * lexical_score + ? + if(valid_at IS NOT NULL AND abs(dateDiff(?, valid_at, parseDateT 4f15bec9d213 SELECT toString(memory_id) AS id, version, value_preview, value_len > ? AS cut FROM loom.memory WHERE org = {org:String} AND namespace = {ns:String} AND (memory_id, version) IN {pairs:Array(Tuple(UUID 4f59cd517107 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 4f71b021bf53 ALTER TABLE loom.knowledge_source_push DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4fd22a03732e SELECT count() AS n FROM loom.dataset_rows WHERE org = {org:String} AND namespace = {ns:String} +4ff808acccee SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 5000543b86ce SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 502b6dac17fa ALTER TABLE loom.search_trace_log DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 502f95a7cabd SELECT org, namespace, agent, user_id, thread_id, title, metadata, run_id, created_at, updated_at, tombstoned_at FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace = {scope:St @@ -711,6 +706,8 @@ 5163c1fd8d3c SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND namespace = {ns:String} 516db52eddcc SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace = {ns:String} AND ? 51af520b7286 SELECT DISTINCT tier, qualified_name, symbol_id FROM loom.code_symbol_names WHERE org = {org:String} AND namespace = {ns:String} AND name IN {names:Array(String)} AND (qualified_name = {full:String} O +51bac3caaf99 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND namespace = {ns:String} AND ? +51f1b6e27428 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 51f662fe04fe SELECT count() AS n FROM loom.learnings_queue WHERE org = {org:String} AND candidate_id IN {cids:Array(UUID)} AND status = ? 52083af6b301 SELECT count() AS n FROM system.mutations WHERE database = {db:String} AND table = {t:String} AND NOT is_done 52448e9cfd6b ALTER TABLE loom.memory_record_conflicts UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {er @@ -720,6 +717,7 @@ 528a44452aa5 SELECT namespace, agent, user_id, session_id, memory_key, toString(status) AS row_status, duplicate_of AS canonical_id FROM loom.memory FINAL WHERE org = {org:String} AND (namespace, agent, user_id, s 52c2e4a12bb9 SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 52d32818a393 SELECT namespace, toString(memory_id) AS canonical_id, memory_key, memory_type, value, tags, version, agent, session_id, user_id, source_class, sensitivity, toString(created_at) AS created_at, toStrin +52e56eaa0e76 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 52ef9d28c739 SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, embedding_model, embedding, version, content_sha256, status FROM loom.memory_embeddings FINAL WHERE (org, namespace, agent, 52f36dc110b9 SELECT memory_id, memory_key, agent, value, created_at FROM loom.memory FINAL WHERE org = {org:String} AND memory_id = {mid:UUID} AND tombstoned_at IS NULL LIMIT ? 531386d56860 SELECT count() AS n FROM loom.memory_drops WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -734,6 +732,7 @@ 54082f4a0bda SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 541a4c06fca2 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, created_at, valid_at, version, status FROM ( SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, t 544bda275e23 ALTER TABLE loom.memory_code_link_queue DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +54688d6f363c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 548ad40962ec SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model 548b3de5bbd4 SELECT memory_key, toString(memory_id) AS mid, content_sha256, agent, memory_type, -- a high value is readable by key only if(sensitivity = ?, ?, substring(value, ?, ?)) AS preview, sensitivity, tags, 549dd1314271 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL @@ -742,9 +741,9 @@ 54cd7b5dbc85 SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND namespace IN {ns:Array(String)} 54d5d57497e5 ALTER TABLE loom.knowledge_ingestions DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 54e9937abaf0 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} -54ff7b59c788 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 555ee79d4eb0 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 55833cd394e4 SELECT text, tokens_in, tokens_out FROM loom.llm_response_cache WHERE model = {model:String} AND key = {key:String} ORDER BY created_at DESC LIMIT ? +558b42c365a7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 558f85fadb18 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 559a2b5dca2e SELECT agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(source_trace, {trace:String}) AND (ag 55b4e25fe476 ALTER TABLE loom.memory DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -762,16 +761,17 @@ 566af30aabf5 SELECT count() AS n FROM (SELECT ? FROM loom.memory LIMIT ?) SETTINGS select_sequential_consistency = ? 569c9b218f83 ALTER TABLE loom.conflict_allowlist DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = 56a045b3692e SELECT kind, number, source_id, component, is_open, created_at, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.qa_item_embeddings FINAL WHERE org = {org:String} AND namespace = {n +56a19fa9673d SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND namespace = {ns:String} 56ab4d25e910 DELETE FROM loom.memory_embeddings WHERE org={org:String} AND namespace={namespace:String} AND agent={agent:String} AND user_id={user_id:String} AND session_id={session_id:String} AND scope={scope:Str +56cf1226e81d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 56f6ba832916 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 56f6eca8bb7f SELECT count() AS n FROM loom.session_briefs WHERE org = {org:String} AND user_id = {uid:String} 56f8615a03d2 SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(promoted_from, {source 570524ca0968 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND has(arrayConcat(window_keys, cited_keys), {key:String}) 571c3ee1dd0f SELECT source_uri, doc_id, title, ingested_at FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND content_sha256 = {sha:String} AND content_sha256 != ? AND source_uri != -571c46e835c7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 5733adacaa36 SELECT g.namespace AS namespace, g.role AS role, ifNull(toString(g.status), ?) AS status, g.pending_role AS pending_role, g.pending_since AS pending_since, g.granted_at AS joined_at, toString(ifNull(n +57857910868c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 578dc73df15f ALTER TABLE loom.agent_events_private UPDATE user_id = ?, memory_key = if(memory_key = ?, ?, ?), args = mapApply((k, v) -> (k, if(k IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), ?, v)), args), subjec -57973bb10799 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 57994fa865de SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 57b88b7f8883 SELECT thread_id, uniqExact(msg_id, cityHash64(content)) AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id IN {tids:Array(String)} AND tombstoned_at IS NU 57b9aebb5d45 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_muta @@ -801,7 +801,6 @@ 596ef23d53ca SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns 5985b4690741 ALTER TABLE loom.memory UPDATE value = ?, value_json = ?, evidence = ?, entities = [], concepts = [], redacted_at = {ts:DateTime}, redaction_reason = {rb:String} WHERE org = {org:String} AND ((namespa 599611be357f SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL -599725704d75 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 59b3f6e281d9 SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 59b463c0ef4b SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, queue_id) AS memory_key, version, ? AS value_json, p 59bc4767d952 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ @@ -816,6 +815,7 @@ 5aa78267733c SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 5aa9a77dc0c1 SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND namespace = {ns:String} 5ab4520a4503 SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND namespace = {ns:String} +5abfc08546ac SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 5ad558ab68b9 ALTER TABLE loom.memory_reinforcement DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync 5b18ec31d5f5 DELETE FROM loom.chunks WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 5b39f4c73106 SELECT memory_key, record_json, created_at, (memory_key, identity_agent, user_id, session_id) IN ( SELECT memory_key, agent, user_id, session_id FROM loom.memory FINAL WHERE org = {org:String} AND nam @@ -826,6 +826,7 @@ 5bcdfad6f454 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 5c174b8803f6 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 5c2243636c81 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ +5c36203308a9 DELETE FROM loom.read_receipts WHERE (org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor)))) AND ({erasure_mutation_tag:String 5c5bd0cdac42 SELECT count() AS n, if(n = ?, NULL, max(ingested_at)) AS latest FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND superseded_at IS NULL 5c7221c42763 SELECT to_key AS memory_key, relation, toString(created_at) AS created_at FROM loom.operator_edges FINAL WHERE org = {o:String} AND namespace = {n:String} AND from_key = {k:String} AND tombstoned_at I 5caa1782814d SELECT ts, org, namespace, agent, operation, latency_ms, success, error_code, request_id, trace_id FROM (SELECT raw.ts AS ts, raw.org AS org, raw.namespace AS namespace, raw.agent AS agent, raw.user_i @@ -836,13 +837,13 @@ 5d4167a48c16 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 5d8fbc4e4072 SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND namespace IN {ns:Array(String)} 5da02e185da3 SELECT ? AS present FROM loom.code_files WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL LIMIT ? +5dce9d644112 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 5df15c3b47a5 SELECT toString(tier) AS tier, count() AS edges, max(created_at) AS last_at FROM loom.code_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL GROUP BY tier 5e685e7d200a ALTER TABLE loom.search_misses DELETE WHERE (org = {org:String} AND (has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id)))) AND ({erasure_mutation_tag:String} = 5e8b03fa60c0 SELECT session_id FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND tombstoned_at IS NULL AND session_id 5e902d2cb6ad SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 5e9d05fdddf9 SELECT * FROM loom.code_scip_batches FINAL WHERE org = {org:String} AND namespace = {ns:String} AND batch_id = {bid:UUID} 5ec21e0b6ff9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist -5eff22c5d922 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 5f07507d00b9 INSERT INTO loom.chunk_supersessions (org, namespace, embedding_model, source_uri, doc_version, superseded_at) SELECT DISTINCT org, namespace, embedding_model, source_uri, doc_version, {when:DateTime} 5f0aadd21dd2 ALTER TABLE loom.memory_belief_sources UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND 5f3660ea1130 SELECT agent, user_id, session_id, memory_key, version_now, tombstoned_now, version_at FROM ( SELECT agent, user_id, session_id, memory_key, version AS version_now, toUInt8(tombstoned_at IS NOT NULL) @@ -858,7 +859,6 @@ 5fb487a531c5 SELECT org, namespace, agent, user_id, session_id, queue_id, payload, message_count, content_chars, status, attempts, lease_until, last_error, written, enqueued_at, updated_at, version, enqueued_by FR 5fbf0c799d3d SELECT sumIf(toUInt64OrZero(args[?]), mirror_marked = ?) AS cache_hits, sumIf(toFloat64OrZero(args[?]), mirror_marked = ?) AS cache_saved_usd FROM (SELECT ts, org, namespace, agent, user_id, session_i 6030dc0ec106 SELECT * FROM loom.memory_versions FINAL WHERE org = {org:String} AND namespace = {ns:String} AND (memory_key, version) IN {pairs:Array(Tuple(String, UInt64))} -6031b8079171 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 603e4cee0b25 SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND namespace = {ns:String} 605f40b3712a SELECT entity, substring(summary_text, ?, ?) AS content_excerpt, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- alias must NOT be `valid_from`: it would shadow the base column - 6093d8c2fa9d SELECT scope_path AS path, summary, pagerank, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embeddin @@ -875,19 +875,19 @@ 61ba62d47959 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND namespace = {ns:String} AND ? 61c44c22fa4a SELECT * FROM ( SELECT agent, user_id, session_id, memory_key, cosineDistance(embedding, {emb:Array(Float32)}) AS dist FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:St 61c5aba9d271 SELECT count() AS n FROM loom.agent_events_private WHERE org = {org:String} AND (user_id = {uid:String} OR subject = {p:String}) -61ecc04f5fbf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +61d479f67bb8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 62027e9bfdc3 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 622295445cf6 SELECT if(length(path) >= ?, path[?], ?) AS src, if(length(path) >= ?, path[?], ?) AS dst, note, agent, ts FROM loom.procedure_runs WHERE org = {org:String} AND namespace = {ns:String} AND memory_key -622a78531dec SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 622d8f1d5bfd ALTER TABLE loom.conflict_allowlist UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = 626e478d6985 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 627e872383d3 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom 6285f383b808 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 62958ba7ae8e SELECT uniqExact(path) AS n FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND lower(content) LIKE {sc_ 62b8af846501 SELECT count() AS n FROM loom.consolidation_runs WHERE org = {org:String} AND namespace = {ns:String} +62bbe484caba SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 6337dbb0bbab SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont -634c9f0bfb3a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 63a839f81adb SELECT namespace, source_uri, title, description, tags, ingested_at, superseded_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, original_filename, content_preview FROM loom +63a93557a802 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 63af7db92642 SELECT label, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN labels AS label WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} 63c18bd2b0f9 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND user_id = {uid:String} 63cdeebcb8df SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to @@ -895,6 +895,7 @@ 641af70c0e23 ALTER TABLE loom.task_events DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 64280912c4ea SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR 642df47c9bb7 SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND namespace IN {ns:Array(String)} +645188574bbc SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 6453a8df6771 DELETE FROM loom.session_summaries WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 6473287ef380 SELECT count() AS n FROM loom.knowledge_sources WHERE org = {org:String} AND namespace = {ns:String} AND owner_subject = {owner:String} AND credential_mode = ? AND source_kind = {kind:String} AND NOT 648a6cfb4d1d SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue_count, residue, verified_at, census FROM loom @@ -914,6 +915,7 @@ 663c96bc8c2e SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 666fcf41eb4a SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 6673f6bc29c7 SELECT DISTINCT pr_number FROM loom.code_pr_history WHERE org = {org:String} AND namespace = {ns:String} AND toDate(merged_at, ?) = {day:Date} +669ef8c5a0c6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 66a80f4706a4 ALTER TABLE loom.operator_edges DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 66b1526f73ec SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 6703a82deeda SELECT operation, count() AS calls, countIf(success) AS succeeded, min(ts) AS first_at, max(ts) AS last_at FROM (SELECT raw.ts AS ts, raw.org AS org, raw.namespace AS namespace, raw.agent AS agent, ra @@ -923,27 +925,25 @@ 6765755688ca SELECT kind, name, status, description, cardinality, created_by, updated_at FROM loom.namespace_ontology FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = {status:String} ORDER B 679aaca08b74 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows 67b04af64852 SELECT DISTINCT namespace FROM loom.documents WHERE org = {org:String} AND user_id = {uid:String} ORDER BY namespace -67e29bf73ff4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +67dfbb3578cb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 680c3774ab86 SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance(embedding, {q:Array(Float32)}) AS distance, ? AS lexical, arrayIntersect(keys, {key 680d46eea97c SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND record_id IN {ids:Array(UUID)} 682186e8e166 SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 687082296f51 SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND user_id = {uid:String} AND doc_superseded_at IS NULL AND (org, namespace, embedding_model, source_uri, doc_version) NOT IN (SELECT org 687db7744a91 WITH agent = {agent:String} AND tombstoned_at IS NULL AS live SELECT countIf(live AND embedding_model = {model:String} AND embedding_dim > ?) AS current, countIf(live AND (NOT is_saved OR user_id != { -6890d08c6806 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 68f55ebf081d SELECT pr_number, title, author, labels, merged_at, files, assignees, body_excerpt, linked_issues, additions, deletions, -- mirrors code/domain/index/pr_signals.is_revert_pr (match(title, ?) OR positi 68f8108c8eb8 SELECT symbol_id, qualified_name, path, fan_in_calls, fan_in_nontest, fan_in_name, caller_files, defined_files, is_test FROM loom.code_symbol_stats FINAL WHERE org = {org:String} AND namespace = {ns:S 69721a6b8e46 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 6983b4c8b3a8 SELECT start_line, end_line, content, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND tombstoned_at IS NULL ORDER BY s 69a567e4df7d SELECT if(has({pool:Array(UInt32)}, revision), {head:UInt32}, revision) AS rev, count() AS samples, quantileExact(?)(steps_taken) AS p50_steps, quantileExact(?)(duration_ms) AS p50_duration_ms, quanti 69ad2d1a3b4a SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND user_id = {uid:String} AND event_type != ? +69be5177a7ee SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 69c8766f7bf2 ALTER TABLE loom.entity_edge_rows DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 69dd5319d904 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND namespace IN {ns:Array(String)} 69df89f26d2c SELECT count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND actor IN {label_actors:Array(String)} AND ? -6a1bf0f50b24 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 6a3370791075 SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} 6a5190d3f6a4 SELECT count() AS n FROM loom.memory_versions WHERE org = {org:String} AND namespace IN {ns:Array(String)} 6a53a350be30 SELECT candidate_id, memory_key, memory_type, proposed_value, status, supporters, rationale, source_kind, source_resource_id, version, seeded_from_thread_id, seeded_from_msg_id, supporter_count, confi -6a6d2a924f0f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 6a941a6c5e43 WITH ( SELECT max(computed_at) FROM loom.entity_communities WHERE org = {org:String} AND namespace = {ns:String} AND level = ? ) AS latest SELECT community_id, any(size) AS size, latest AS computed_at 6abb543e4d1a SELECT symbol_id, uniqExact(path) AS defined_files, min(match(path, {noise:String})) AS is_test, argMin(path, (match(path, {noise:String}), path)) AS def_path FROM ( SELECT symbol_id, argMax(path, ver 6ad106d09e67 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: @@ -956,7 +956,6 @@ 6b6d53e64bd0 ALTER TABLE loom.entity_edges DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 6b920c15b813 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 6bca66927292 SELECT min(ts) AS first_ts, count() AS n FROM loom.audit_log -6befffe2772b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 6c17c9f6e702 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace IN {nss:Array(String)} A 6c1cb0579e58 SELECT entity, community_id FROM loom.entity_communities FINAL WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND level = ? AND entity IN {ents:Array(String)} AND (namespace, computed_a 6c2e2e39e107 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, queue_id) AS memory_key, version, ? AS value_json, p @@ -979,6 +978,7 @@ 6e5e297bbb30 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND status != ? AND agent = {agent:String} AND user_id = {uid: 6e894706d089 SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 6e90fc205193 SELECT org, namespace, agent, user_id, session_id, memory_key FROM ( SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND (arrayExist +6ea5f96beea9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 6eac9c7cf08e DELETE FROM loom.session_summaries WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync 6f025f927273 SELECT count() AS n FROM loom.knowledge_ingestions WHERE org = {org:String} AND user_id = {uid:String} 6f11f5e87057 SELECT DISTINCT path FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND symbol_id IN {ids:Array(String)} AND tombstoned_at IS NULL @@ -987,6 +987,7 @@ 6f5de71aa3ff ALTER TABLE loom.datasets DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 6f5e97facae7 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND user_id = {uid:String} 6f7989d65b42 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND user_id = {uid:String} AND ? +6f838d32dab9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 6f838e71a9a0 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont 6fd3e3093469 SELECT DISTINCT path FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND startsWith(path, {prefix:String}) AND tombstoned_at IS NU 701267d73992 SELECT org, namespace, agent, user_id, session_id, argMaxIf(actor, version, actor != ? AND NOT has({pipeline:Array(String)}, actor) AND NOT startsWith(actor, {cli:String})) AS writer FROM loom.memory @@ -997,6 +998,8 @@ 7060375c96df SELECT agent, user_id, session_id, memory_key, memory_type, value FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND (agent, user_id, session_id, memory_key) IN {rows:Arra 706860c52e9b SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR 70b8fc823f33 SELECT count() AS n FROM loom.knowledge_group_members WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +70cff3518bda SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +70d6cc6d3188 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 70e79f9a81f4 SELECT count() AS n FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 711d1334a264 SELECT from_symbol_id, path, argMax(guards, version) AS guards, argMax(guard_kinds, version) AS guard_kinds, argMax(sites, version) AS sites, argMax(site_callees, version) AS site_callees, argMax(site 71315c743233 SELECT m.org AS org, m.namespace AS namespace, m.memory_key AS memory_key FROM (SELECT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE tombstoned_at IS NULL AND sen @@ -1012,6 +1015,7 @@ 7241de7a778c ALTER TABLE loom.context_blobs UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {eras 72570c0878fd SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 72a96f3573e5 SELECT memory_key, toString(memory_id) AS mid, content_sha256, agent, memory_type, -- a high value is readable by key only if(sensitivity = ?, ?, substring(value, ?, ?)) AS preview, sensitivity, tags, +72b942d5fcfb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 72ba39630853 SELECT memory_key, memory_type, value, confidence, source_trace, memory_id, entities, tags, valid_at, char_limit, pinned, tombstoned_at, version, status, superseded_by FROM loom.memory FINAL WHERE org 72e4548118f7 SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND namespace IN {ns:Array(String)} 72f06cf9707b SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -1031,7 +1035,7 @@ 7473dd492492 SELECT label, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN labels AS label WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} 74749bb79292 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 747deda3bb6f SELECT namespace, countIf(status=?) AS pending, countIf(status=?) AS promoted, countIf(status=?) AS rejected, if(countIf(status IN (?,?)) > ?, countIf(status=?) / countIf(status IN (?,?)), ?) AS appro -74d0f50cae51 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +74ec17e309d1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 75436536fca7 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 75472d68157f ALTER TABLE loom.entity_communities DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 75554c47d6b1 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pa @@ -1044,7 +1048,6 @@ 75f3fd72118d ALTER TABLE loom.memory_term_freq DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 7615ac826d0c SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, toString(evidence_id)) AS memory_key, toUInt64(toUni 764e065d440e SELECT count() AS n FROM loom.knowledge_ingest_cancels WHERE org = {org:String} AND user_id = {uid:String} AND ? -764e0e259701 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 765404bd5d8d SELECT toDate(coalesce(temporal_anchor, valid_at)) AS event_date, cosineDistance(embedding, {q:Array(Float32)}) AS distance, substring(content_excerpt, ?, ?) AS excerpt, memory_key, temporal_anchor IS 7662b4971175 SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN 76ed76b066ae SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ @@ -1057,11 +1060,10 @@ 77be1ad28338 SELECT DISTINCT agent FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY agent 77cd7f76783c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 7843812c63f3 SELECT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory AS m WHERE m.memory_type IN (?, ?, ?) AND org = {org_filter:String} AND namespace = {ns_filter:String} AND m.created_at > -78687844bf40 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 78ba94b892b2 SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(content, ?, {listed:UInt32}), ts) AS content, max(c.saved_at) AS saved_at FROM loom.conversations AS c WHERE org = {org:String} AND na -78c6fa82ee03 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 78caa320ee42 SELECT * FROM loom.memory_embeddings FINAL PREWHERE org = {org:String} AND namespace = {ns:String} AND scope = ? AND memory_key = {k:String} WHERE tombstoned_at IS NULL SETTINGS select_sequential_cons 78cfc350f4ab SELECT countIf(location != ?) AS stored, countIf(location != ? AND NOT (startsWith(location, {root:String}) AND length(splitByChar(?, substring(location, length({root:String}) + ?))) = ?)) AS elsewher +78e907792edf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 78ea1be7fe36 ALTER TABLE loom.memory_webhook_outbox DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 78fc48ead015 SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND user_id = {uid:String} AND superseded_at IS NULL 790996cc57e5 ALTER TABLE loom.memory_record_fields DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1075,7 +1077,6 @@ 797930d09a5b SELECT toString(failure_id) AS failure_id, org, namespace, agent, projection, source_operation, source_resource_id, memory_keys, error_type, error_message, payload, status, created_at, resolved_at FRO 79af77cb3b0b ALTER TABLE loom.derived_facts DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 79b7b807206a SELECT count() AS n, max(computed_at) AS newest_at FROM loom.code_unit_risk FINAL WHERE org = {org:String} AND namespace = {ns:String} -79de60794e30 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 79ec8e98cd5d SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 7a102674981e SELECT count() AS n FROM loom.query_history_sources WHERE org = {org:String} AND namespace IN {ns:Array(String)} 7a4159a961af SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue_count, residue, verified_at, census FROM loom @@ -1085,9 +1086,9 @@ 7a87bbd25387 SELECT org, namespace, agent, user_id, thread_id, title, metadata, run_id, created_at, updated_at, tombstoned_at FROM loom.conversation_threads FINAL WHERE org = {org:String} AND user_id = {scope:Stri 7aab1cf5e970 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, session_id) AS memory_key, version, ? AS value_json, 7aad3247f4a7 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL +7ad0b1c2f4ef SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 7ad2d6cd3530 SELECT brief_key, revision, agent, user_id, session_id, head_sha, trigger, author, sections, rendered, events_total, source_chars, brief_chars, actor, updated_at, tombstoned_at, version FROM loom.sess 7ada090d2235 ALTER TABLE loom.shared UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_ta -7ae5fa2ffa15 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 7b00f0e38432 SELECT namespace, source_id, `group`, members, read_at, deleted FROM loom.knowledge_group_members FINAL WHERE org = {org:String} AND (namespace, source_id, `group`) IN {groups:Array(Tuple(String, Stri 7b11cdb24e8b SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 7b16ed6ec37d SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidence, version) AS confidence, argMax(tombstoned_at IS NULL, vers @@ -1105,6 +1106,7 @@ 7bb9d891b190 SELECT thread_id, msg_id, role, content_excerpt AS embedded_text, ts, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND nam 7bcba9ce8741 SELECT state_value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key = ? LIMIT ? 7c06e9fdda88 ALTER TABLE loom.knowledge_uploads DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +7c25c9e1bda5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 7c313a3b4c8e SELECT term, toUInt64(uniqExactMerge(df_state)) AS df FROM loom.code_term_freq WHERE org = {org:String} AND namespace = {ns:String} AND term IN {tokens:Array(String)} GROUP BY term 7c3b3812fec8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 7c3c296ceaa7 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a @@ -1115,7 +1117,6 @@ 7c8c91c6764e SELECT state_value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key = {key:String} 7ca3298a5f77 SELECT count() AS n FROM loom.learnings_queue WHERE org = {org:String} AND namespace = {ns:String} 7ca425af7836 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND agent != {id:String}) GROUP BY -7ca4cd496272 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 7cb115afec15 SELECT count() AS n FROM loom.datasets WHERE org = {org:String} AND user_id = {uid:String} 7cd33526cc9c ALTER TABLE loom.memory_records DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 7ce46ce955fb SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -1141,6 +1142,7 @@ 7f189382759c SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont 7f3000230a53 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { 7f3109c4ef67 SELECT max(mirror_marked) AS marked FROM loom.erasure_requests WHERE org = {org:String} AND id = {id:UUID} AND requested_at > now() - INTERVAL ? DAY +7f5965a4a5e8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 7f69aecf50a8 SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns 7f811f5fc105 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU 7f8322a3673c SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -1158,11 +1160,13 @@ 803b5fead6fb ALTER TABLE loom.code_search_outcome DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 803d105bdcc0 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL 80615d70d925 SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND namespace = {ns:String} AND ? +808fac34a07e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 809ffd3a9a82 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL) GROUP BY tag HAVING rows >= {min: 80ac0a0e1397 SELECT toYYYYMM(ts) AS partition, ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE ts >= toDateTime64(now() - INTERVAL {lb:UInt32} SECOND, ?, ?) AND (ts, 80cfa2f097df SELECT org, namespace, agent, user_id, session_id, embedding_model, version, summary_text, key_facts, derived_from, at FROM (SELECT org, namespace, agent, user_id, session_id, embedding_model, version 8107af48e1df SELECT count() AS n FROM ( SELECT evidence_id, tombstoned_at FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND user_id = {uid:String} AND session_id = {sid:String} AND 81147eeb107a SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND namespace = {ns:String} +812b9a4b253f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 812c33d11f88 ALTER TABLE loom.memory_projection_failures DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations 813e255fc5b3 ALTER TABLE loom.task_events DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 81a685cdbf1f SELECT count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -1173,6 +1177,7 @@ 8211772db3ff SELECT count() AS n FROM loom.memory_versions WHERE org = {org:String} AND namespace = {ns:String} 821b8680cff7 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND (user_id = {uid:String} OR has(tags, ?) AND hasAny(arrayMap(t -> (toString(namespace), t), tags), (SELECT groupUniqArray((toStri 821c5fd66314 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont +823744cea1f9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 824960aa6a71 SELECT DISTINCT path, kind, scope, start_line, end_line FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL ORD 82554a8768f6 SELECT DISTINCT toString(record_id) AS id FROM (SELECT record_id FROM loom.memory_records WHERE org = {org:String} AND user_id = {uid:String}) 82ab558f7ff1 SELECT * FROM loom.scim_users FINAL WHERE lowerUTF8(user_name) = lowerUTF8({n:String}) AND deleted = ? LIMIT ? @@ -1180,9 +1185,9 @@ 82fff045a9ab SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 8304a44da344 ALTER TABLE loom.entity_canonical_map UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasu 831a9cfc9db8 SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} +833203e48b68 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 833e61e70cec ALTER TABLE loom.code_search_trace DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 834a21e3a869 SELECT namespace, JSONExtractString(payload, ?) AS operation, toUInt64(sum(? + JSONExtractUInt(payload, ?))) AS violations, max(JSONExtractFloat(payload, ?)) AS max_overage_ratio, round(avg(JSONExtrac -83662fd4e4a4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 839c4113555f SELECT count() AS n FROM loom.code_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 83ae9068116e SELECT count() AS n FROM ( SELECT evidence_id, tombstoned_at FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND role = {role:String} AND obse 83d781f2d931 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to @@ -1196,6 +1201,7 @@ 8452df8453eb DELETE FROM loom.memory_embeddings WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? 847f10f435b6 SELECT memory_id, memory_key, memory_type, version, pinned, created_at, conflict_with, sensitivity FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status = ? AND tombst 8483426b1032 SELECT hit.? - ? AS qidx, m.memory_id, m.memory_key, m.value, m.pinned, m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, hit.? AS dist FROM loom.memory m FINAL JOIN loom.memory_embeddings e FIN +848a614eefe2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 84bdbba6f76c ALTER TABLE loom.knowledge_gaps DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 84c7b32e7dac ALTER TABLE loom.agent_events UPDATE user_id = ?, memory_key = if(memory_key = ?, ?, ?), args = mapApply((k, v) -> (k, if(k IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), ?, v)), args), subject = if(s 84cf65787e43 SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:String} AND user_id = {uid:String} AND memory_id NOT IN (SELECT memory_id FROM loom.memory FINAL WHERE org = {org:String} AND memory_id @@ -1228,6 +1234,7 @@ 8821bc6c7261 SELECT count() AS n FROM loom.session_briefs WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 884c1941f3ed SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, status, proposed_at, decided_at, decided_b 8863d1cc780b SELECT author, uniqExact(pr_number) AS prs FROM loom.code_pr_reviews FINAL WHERE org = {org:String} AND namespace = {ns:String} AND comment_created_at >= now() - INTERVAL {days:UInt32} DAY AND is_bot +8879f43a2306 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 888ce735eb8f SELECT DISTINCT source_uri, toString(doc_id) AS id FROM loom.documents WHERE org = {org:String} AND namespace = {ns:String} AND source_uri >= {uri:String} AND (source_uri, id) > ({uri:String}, {id:Str 888f7269df70 ALTER TABLE loom.memory_exposures DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 88c56985a4c0 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows @@ -1237,6 +1244,7 @@ 8934b9b24243 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 89676ac16aab SELECT toString(memory_id) AS memory_id, org, namespace, agent, user_id, session_id, memory_key, value, actor, version, redacted_at, toString(coalesce(valid_at, updated_at)) AS since FROM loom.memory 8968185eda3b SELECT source_uri, title, version, revision, ingestion_id, ingested_at, if(format != ?, toString(format), if(JSONExtractString(metadata, ?) != ?, JSONExtractString(metadata, ?), if(blob_content_type ! +8982d84c6083 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 8982fae06fdb SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} 898db6ed880f ALTER TABLE loom.memory_drops DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 89b5cc709cb7 ALTER TABLE loom.memory_records DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1248,7 +1256,6 @@ 8a5fb93b3273 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create 8a6b5d3e9731 SELECT p.pr_number AS pr_number, p.merge_commit_sha AS merge_commit_sha, p.pack_tokens AS pack_tokens, p.created_at AS created_at, ifNull(h.title, ?) AS title, ifNull(h.author, ?) AS author, h.merged_ 8a725f267f59 SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND namespace = {ns:String} AND ? -8a8b47f8466b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 8a8bd6cc9556 SELECT toString(memory_id) AS memory_id, org, namespace, agent, user_id, session_id, memory_key, value, actor, version, redacted_at, toString(coalesce(valid_at, updated_at)) AS since FROM loom.memory 8ab804cb3281 SELECT queue_id, agent, user_id, session_id, status, version, enqueued_at < now64(?) - toIntervalDay(?) AS past_last_day FROM loom.memory_extraction_queue FINAL PREWHERE org = {org:String} AND namespa 8ad29b28f61b SELECT concat(?, session_id, ?, toString(chunk_index)) AS memory_key, ? AS memory_type, content AS content_excerpt, toString(created_at) AS created_at, toString(created_at) AS valid_at FROM loom.memor @@ -1257,6 +1264,7 @@ 8aee13cb4e2b SELECT block_key, content, char_limit, version, created_at, updated_at FROM loom.working_memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid 8b04eea55270 SELECT ? AS ok FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:String} AND (tombstoned_at IS NULL 8b2280a5ef89 ALTER TABLE loom.knowledge_group_members DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sy +8ba478644b6c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 8bae83aca4ab SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, version, value, toString(value_json) AS object_text FROM loom.memory FINAL WHERE tombstoned_at IS NULL AND sensitivity = ? AND 8c0933e7e8b9 DELETE FROM loom.learnings_queue WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} AND version <= {v:UInt64} SETTINGS lightweight_deletes_sync = ? 8c0d632fd7b7 SELECT org, inbox, owner_agent, owner_namespace, description, posters, accept_disclosure, default_lease_seconds, max_attempts, max_defers, triage_escalate_after_seconds, webhook_url, webhook_secret_re @@ -1279,6 +1287,7 @@ 8e071b3fbd04 ALTER TABLE loom.entity_communities DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = 8e07b58eaf79 SELECT arrayFirst( u -> startsWith(source_resource_id, concat({prefix:String}, u, ?)), {uris:Array(String)} ) AS source_uri, toUInt8(has(tags, {proposed_tag:String})) AS proposed, count() AS total, co 8e1b7f890fb2 SELECT org, namespace, agent, user_id, session_id, name, source_id, host, port, secure, user, password_enc, cluster, databases, actor, source_class, created_at, tombstoned_at, version FROM loom.query_ +8e3f49a06055 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 8e580377c32a SELECT count() AS n FROM loom.search_trace_log WHERE org = {org:String} AND namespace = {ns:String} 8e674bf368f7 SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance(embedding, {q:Array(Float32)}) AS distance, ? AS lexical, arrayIntersect(keys, {key 8e7711e9fddb SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user @@ -1293,8 +1302,9 @@ 8fc17be4beac ALTER TABLE loom.entity_triple_rows DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 8fc9bad334c6 SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () AS total FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND match(path, { 8fd7023b0ac4 SELECT community_id, any(label) AS label, max(size) AS size, toString(max(computed_at)) AS last_computed FROM loom.entity_communities WHERE org = {o:String} AND namespace = {n:String} AND level = ? AN -8fe855565856 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 8ffdf2a7f5d9 SELECT DISTINCT toString(memory_id) AS id FROM loom.entity_triple_rows WHERE org = {org:String} AND user_id = {uid:String} AND memory_id NOT IN (SELECT memory_id FROM loom.memory FINAL WHERE org = {or +900116326f67 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +90170bd124c1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 9017f74f4c3d SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 90332816a040 SELECT toString(memory_id) AS memory_id, version, value, tags, valid_at, pinned, lock_mode, lock_until, sensitivity FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND user 9034f734be88 SELECT toString(memory_id) AS memory_id, memory_key, agent, user_id, session_id, duplicate_of FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND @@ -1307,6 +1317,7 @@ 91d49a7a3197 SELECT toString(memory_id) AS memory_id, org, namespace, agent, user_id, session_id, memory_key, value, actor, version, redacted_at, toString(coalesce(valid_at, updated_at)) AS since FROM loom.memory 91d550909ae3 ALTER TABLE loom.operator_edges UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mut 920f55498792 SELECT path FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(path, ?) AND extract(path, ?) IN {nums:Array(String)} ORDER BY path +92189b286c5b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 924227e8fe2f SELECT {literals:Array(String)}[held] AS literal, chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( i -> m 92511fc23cad SELECT count() AS n FROM loom.subject_last_seen WHERE org = {org:String} AND subject = {p:String} 925c1511f1c1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ @@ -1314,10 +1325,10 @@ 92bb5bdc48ce SELECT count() AS n FROM loom.memory_versions WHERE org = {org:String} AND (user_id = {uid:String} OR has(tags, ?) AND hasAny(arrayMap(t -> (toString(namespace), t), tags), (SELECT groupUniqArray((toS 92cd7a1258cd SELECT count() AS n FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 92e6b8baf91e SELECT m.org AS org, m.namespace AS namespace, count() AS live_rows, max(m.created_at) AS last_write FROM loom.memory AS m FINAL LEFT ANTI JOIN (SELECT org, namespace FROM loom.namespaces) AS n ON m.o -9320702d5e1e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9339ac2a7139 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 9353e65f71a0 SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 935ffe795d8b ALTER TABLE loom.entity_edges DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +93640db868d1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 936b90406cce SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 936f42f73802 SELECT symbol_id, qualified_name, name, signature, path, start_line, end_line, tier, kind FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(Str 9385536d2dcd ALTER TABLE loom.session_outcomes_by_user DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1342,7 +1353,6 @@ 9568a0ca0e47 ALTER TABLE loom.conversation_threads DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 95a1f85e91e0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 95c5ed847a4d SELECT path, uniqExact(transform(to_symbol_id, {ids:Array(String)}, {names:Array(String)}, to_symbol_id)) AS callees FROM ( SELECT tier, to_symbol_id, from_symbol_id, path, line, argMax(tombstoned_at -95f859dcea00 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9610f3c84686 SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key FROM loom.memory_embeddings WHERE (org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key) 96291ba85a09 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, 9648988c847c SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} @@ -1350,12 +1360,15 @@ 96cd9708162d SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND user_id = {uid:String} 96e6221f7f9f SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create 96ecb876ec8c SELECT * FROM loom.scim_users FINAL WHERE id = {id:String} +9716594e45a7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 971a9c534152 SELECT entity, substring(summary_text, ?, ?) AS content_excerpt, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- alias must NOT be `valid_from`: it would shadow the base column - 9761b739c189 SELECT m.org AS org, m.namespace AS namespace, m.user_id AS user_id, count() AS n FROM loom.memory AS m FINAL INNER JOIN loom.namespaces AS n FINAL ON m.org = n.org AND m.namespace = n.namespace WHERE 976a3206306b SELECT toUInt64(toUnixTimestamp64Milli(now64(?))) AS ms +977dbe0650c7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 979ee17b2127 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR 97b465efed16 SELECT source_uri, count() AS live, countIf(embedding_model = {model:String} AND embedding_dim > ?) AS searchable, countIf(embedding_dim = ?) AS unembedded, countIf(embedding_model != {model:String}) 97f2b91effdf SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue FROM loom.erasure_requests FINAL WHERE status +9818aee4334d SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND ((has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor))) AND ts < {recorded_at 982795414e49 SELECT agent, user_id, session_id, memory_key, cosineDistance(embedding, {emb:Array(Float32)}) AS dist FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory 9848ee046655 ALTER TABLE loom.memory_belief_sources DELETE WHERE (org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:S 98649b515546 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user @@ -1373,7 +1386,6 @@ 99b2b4b77f2a SELECT memory_key, memory_type, content_excerpt, ? - cosineDistance(embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(temporal_anchor, toDateTime(?))) AS temporal_anchor, temporal_confi 99b329fe464e SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 99bb0fb8f03c ALTER TABLE loom.session_summaries UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_m -99d86c8fa8ea SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 99e205d8de95 SELECT slo_class, sum(requests) AS requests, sum(server_errors) AS server_errors FROM loom_telemetry.sli_minute WHERE slo_class != ? AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UIn 99ebc0e5d139 SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 99ebe72c9d4f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist @@ -1387,31 +1399,28 @@ 9adfa8216cee ALTER TABLE loom.memory_code_link_queue DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 9ae3708317b3 SELECT if(consumer = ?, args[?], consumer) AS consumer_key, count() AS calls, countIf(NOT success) AS errors, countIf(NOT success AND error_code = ?) AS server_errors, round(errors / calls, ?) AS erro 9b1e4cc93d63 ALTER TABLE loom.memory_exposures DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +9b372860078f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 9b3d6ec905f6 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -9b5464e2b15d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -9b6b77417df3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -9babe2e9da64 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9bad70421959 SELECT toString(memory_id) AS memory_id, memory_key, agent, user_id, session_id, duplicate_of FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND -9bd2cea8e042 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9bd30fe1f711 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 9bdea6b87eff SELECT actor AS name, count() AS n, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) AND actor != ? G 9c400d8b7c0c ALTER TABLE loom.oauth_signin_state UPDATE value = {v:String}, expires_at = {e:UInt32} WHERE claim_key = {k:String} AND value = {old:String} SETTINGS keeper_map_strict_mode = ?, max_execution_time = ? 9c438a0de758 SELECT thread_id, argMax((agent, toString(role), substringUTF8(content, ?, {listed:UInt32})), (ts, msg_id)) AS last_turn FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AN 9c4f1355a57a SELECT countIf(status = ?) AS conflicted, countIf(status = ?) AS proposed FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status IN (?, ?) AND tombstoned_at IS NULL -9c5dd41a6bc3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9c748a412c4b SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to 9c9c041df913 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} 9ca253f1c5a0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 9ca34d18548d SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND (JSONExtractString(payload, ?) = {uid:String} OR arrayExists(e -> JSONExtractString(e, ?) = {uid:String}, JSONExtr 9ca9ff655201 SELECT uniqExact(user_id, session_id, memory_key) AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND tombstoned_at IS NULL AND ( 9caee3d742e8 SELECT agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status != ? ORDER BY agent, user_id, session_id, -9cccefb4c425 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9cdbcb7e4976 SELECT org, qa_namespace AS namespace FROM loom.qa_link_candidates WHERE org IN {orgs:Array(String)} AND qa_namespace IN {namespaces:Array(String)} GROUP BY org, namespace 9cdc49aba925 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL 9cea5db2333b SELECT m.org, m.namespace, m.agent, m.user_id, m.session_id, m.memory_key FROM loom.memory AS m FINAL LEFT ANTI JOIN ( SELECT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory_em 9d336f6da7c7 SELECT uniqExact(embedding_model, chunk_idx) AS chunk_count FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri = {uri:String} AND JSONExtractUInt(chunk_metadata, ?) = +9d3e14685096 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 9d4138cd6c9a SELECT src_path, max(confidence) AS best_confidence FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND test_path IN {paths:Array(String)} AND tombstoned_at IS NULL 9daeeb2ab9a4 SELECT org, namespace, memory_key, status, tombstoned_at FROM loom.memory FINAL WHERE tombstoned_at IS NOT NULL AND status != ? +9daf10dfec2f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 9dafb689b559 SELECT DISTINCT cityHash64(namespace, source_uri) AS h FROM loom.documents FINAL WHERE org = {org:String} AND user_id = {uid:String} 9de706c43448 SELECT count() AS n FROM loom.query_nodes WHERE org = {org:String} AND namespace IN {ns:Array(String)} 9df5ef365bc8 SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL @@ -1419,8 +1428,6 @@ 9dffe07ed651 SELECT operation, count() AS calls, countIf(success) AS succeeded, min(ts) AS first_at, max(ts) AS last_at FROM (SELECT raw.ts AS ts, raw.org AS org, raw.namespace AS namespace, raw.agent AS agent, ra 9e0bc0ef26b0 SELECT toYYYYMM(ts) AS partition, ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE ts >= toDateTime64(now() - INTERVAL {lb:UInt32} SECOND, ?, ?) ORDER BY 9e328bb12721 SELECT count() AS n FROM loom.learnings_queue WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? -9e49c20a4fc8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -9e7b47b91e9c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 9e9adc05a7ef SELECT namespace, kind, owner_email, description, tags, active, conversation_logging_enabled, capture_generation_io, coverage_sweep, consolidation_enabled, daily_cost_cap_usd, daily_user_cost_cap_usd, 9eafee0b23b4 SELECT count() AS n FROM loom.memory_extraction_queue WHERE org = {org:String} AND user_id = {uid:String} AND ? 9ed5e750e8c9 DELETE FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND (source_uri, doc_version) IN {rows:Array(Tuple(String, UInt64))} SETTINGS lightweight_deletes_sync = ? @@ -1430,16 +1437,17 @@ 9f28894e137d SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER 9f30f09f17f1 SELECT memory_key, count() AS matches FROM (SELECT tm.memory_key FROM loom.entity_triple_memories AS tm INNER JOIN loom.entity_triples AS t ON t.org = tm.org AND t.namespace = tm.namespace AND t.subje 9f3688435054 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL +9f87e710ff0a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 9f8b92dfe437 SELECT kind, number, source_id, component, is_open, created_at, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.qa_item_embeddings FINAL WHERE org = {org:String} AND namespace = {n 9f8cce397797 ALTER TABLE loom.memory_chunk_sources UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND 9fad0b356a81 SELECT namespace, countIf(status=?) AS pending, countIf(status=?) AS promoted, countIf(status=?) AS rejected, if(countIf(status IN (?,?)) > ?, countIf(status=?) / countIf(status IN (?,?)), ?) AS appro 9ff4c37ed354 WITH spend AS ( SELECT org, namespace, sum(upstream_cost_usd) AS spent, sumIf(upstream_cost_usd, operation = {op:String}) AS own FROM (SELECT ts, org, namespace, agent, user_id, session_id, run_id, op 9fff0b609d85 SELECT toUInt32(quantileExact(?)(failing_tests)) AS median_tests, count() AS hours FROM loom.qa_fail_hours FINAL WHERE org = {org:String} AND qa_namespace = {ns:String} AND hour >= {h0:DateTime} AND h a010bc956c57 SELECT org, namespace, agent, user_id, session_id, memory_key, checked, tombstone, checked_state_sha256, done FROM loom.delete_version_checks FINAL WHERE org = {org:String} AND namespace = {ns:String} +a01acebe8956 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a055584d8e91 SELECT toString(f.failure_id) AS failure_id, org, namespace, agent, projection, source_operation, source_resource_id, memory_keys, error_type, error_message, payload, status, created_at, resolved_at F a0585852a421 SELECT memory_id, memory_key, value, pinned, agent, user_id, session_id, run_id, valid_at FROM loom.memory FINAL PREWHERE org = {org:String} AND namespace = {ns:String} AND (agent, user_id, session_id a0706937823b SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { -a08014de0c22 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g a09ec2d88823 SELECT pr_number, title, author, labels, files, merged_at, opened_at, linked_issues, lexemes FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS N a0b4dab9a372 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, session_id) AS memory_key, version, ? AS value_json, a0be1210dc79 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -1451,7 +1459,6 @@ a1498841d4b7 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c. a14fb4b432ac SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist a15f5abcdc5f SELECT sum(evidence_count) AS evidence_count FROM loom.memory_usage_totals WHERE org = {org:String} AND namespace = {ns:String} AND memory_id = {mid:String} a175ce2b58cf ALTER TABLE loom.memory_extraction_queue DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -a1915011bebf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g a19f3b0331fd SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom a1a9bf524c5c SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () AS total FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(sp a1bbc2e5bf93 SELECT count() AS n FROM loom.tasks FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND is_deleted = ? @@ -1464,16 +1471,17 @@ a219f248e90c SELECT org, namespace, agent, user_id, session_id, memory_id, memor a247e662ca98 SELECT src, dst, relation, direction, pair_co_occur, provenance, degree FROM ( SELECT p.src AS src, p.dst AS dst, p.relation AS relation, p.direction AS direction, p.pair_co_occur AS pair_co_occur, p. a270b5e25de9 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user a28f385fb356 SELECT agent AS name, count() AS n, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) AND agent != ? G +a2a1279db771 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a2e086bfc0e6 SELECT org, namespace, agent, user_id, thread_id, msg_id, role, content, reasoning, metadata, tokens, run_id, ts, is_saved, saved_at, tombstoned_at, length(content) + length(reasoning) + length(metada a2f33ec966a9 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {scope_uid:String}) a2facce0f48a SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND namespace = {ns:String} AND ? a2fd7cdaba22 SELECT countIf(n > ?) / greatest(count(), ?) AS reused_share FROM ( SELECT memory_key, count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstone a30c520d6647 ALTER TABLE loom.entity_edges DELETE WHERE (org = {org:String} AND cityHash64(namespace, entity_a, entity_b) IN {owned:Array(UInt64)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String a30e0be090a8 SELECT count() AS n FROM loom.agent_runs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND session_id = {sid:String} AND (positionCaseInsensitiveUTF8(goal, {q:S -a30fe8e84093 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g a339b1bc6929 ALTER TABLE loom.memory_chunks UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {eras a33eb1d76cb3 SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL a350e145841a ALTER TABLE loom.memory_chunk_sources DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync +a363748d9281 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a3afc43cd42d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ a3b7af18a429 SELECT ? FROM (SELECT * FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND (embedding_model, msg_id a3cd47767201 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND (user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN {keys:Array(Tuple(String, String))})) @@ -1491,7 +1499,6 @@ a5152b5d9889 ALTER TABLE loom.conversation_embeddings UPDATE tombstoned_at = {no a54183869dec SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace IN {ns:Array(String)} a543652b324c SELECT org, namespace, agent, user_id, session_id, run_id, goal, user_request, expected_outcome, environment, model, consumer, status, started_at, completed_at, duration_ms, final_response, confidence a55966ee4380 SELECT f.lang AS lang, toString(s.tier) AS tier, count() AS symbols, max(s.created_at) AS last_at FROM ( SELECT path, tier, created_at FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespa -a5598bacc84d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g a563ab145bc6 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace IN {nss:Array(String)} A a56fae89e202 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, toString(evidence_id)) AS memory_key, toUInt64(toUni a57247237093 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to @@ -1510,8 +1517,10 @@ a67dc6a1b98a SELECT path, start_line, end_line, content_hash FROM loom.code_chun a68b12d4c3b3 SELECT memory_type, count() AS c FROM loom.memory FINAL WHERE org = {o:String} AND namespace = {n:String} AND tombstoned_at IS NULL AND status = ? AND memory_key NOT LIKE ? GROUP BY memory_type a6ae128a7aef SELECT callee_name, path, line, from_symbol_id, argMax(from_qualified_name, version) AS from_qualified_name, argMax(call_text, version) AS call_text, argMax(disposition, version) AS disposition, argMa a6bf30adfd30 SELECT memory_key, memory_type, content_excerpt, ? - cosineDistance(embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(temporal_anchor, toDateTime(?))) AS temporal_anchor, temporal_confi +a6cc8f0940d5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a6cda72cdc5a SELECT record_id, parent_memory_key, session_id, schema_name, record_json, field_text, lexical_score, least( ?, ? * lexical_score + ? + ? ) AS rank_score, -- NB: alias the stringified date as *_iso, N a6d7b1389c15 SELECT f.lang AS lang, count() AS chunks, countIf(c.embedding_dim > ?) AS embedded, countIf(c.context_source = ?) AS described, max(c.created_at) AS last_at FROM ( SELECT path, embedding_dim, context_ +a6d9b3ff7668 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a6e14fdbe6b8 SELECT namespace FROM loom.namespaces FINAL WHERE org = {org:String} AND classification = ? a701cdc94407 SELECT count() AS n FROM loom.memory_term_freq WHERE org = {org:String} AND namespace IN {ns:Array(String)} a70c5f10eab4 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows @@ -1529,6 +1538,7 @@ a883073e33de SELECT count() AS n, if(n = ?, NULL, max(created_at)) AS latest FRO a8b303321d91 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER a8c0ec6a4b16 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model a8c6e74f4e8d SELECT event_type, count() AS cnt, min(ts) AS first_ts, max(ts) AS last_ts FROM loom.audit_log WHERE ts >= toDateTime64(now() - INTERVAL {since:UInt32} SECOND, ?, ?) AND NOT match(namespace, ?) AND or +a8e6a6c23de5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this a8ef32fbad8c SELECT content_sha256, count() AS chunk_count, uniqExact(source_uri) AS uri_count, groupArray(?)((source_uri, chunk_idx)) AS samples FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:Strin a8f2636209f6 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE org = {org:String} AND (NOT startsWith(namespace, {col_prefix:String}) OR namespace IN {col_readab a90054f8b1c7 SELECT DISTINCT b.? AS qid FROM system.mutations ARRAY JOIN {versions:Array(Tuple(String, UInt64))} AS b WHERE database = {db:String} AND table = {t:String} AND is_done = ? AND position(command, {pat: @@ -1536,7 +1546,6 @@ a92198f269fa SELECT day, runs, fails, prs, groups, steps, flips, same_commit_fli a937609f7c0d SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows a940d1ebe53d SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:String} AND namespace = {ns:String} a94901681d41 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {id:String} AND user -a9575695a5f4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g a98d68a7b8da SELECT DISTINCT namespace, memory_key FROM (SELECT namespace, memory_key FROM loom.memory WHERE org = {org:String} AND user_id = {uid:String}) a98f2f0e55ec SELECT count() AS n FROM loom.code_search_trace WHERE org = {org:String} AND user_id = {uid:String} AND ? a9ace0ac3910 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { @@ -1550,16 +1559,14 @@ aa7e2654b8fc ALTER TABLE loom.memory_code_link_queue DELETE WHERE (org = {org:St aa907e4bc418 SELECT callee_name, path, line, from_symbol_id, argMax(from_qualified_name, version) AS from_qualified_name, argMax(call_text, version) AS call_text, argMax(disposition, version) AS disposition, argMa aa9ea59255fa SELECT ts, event_type, org, namespace, actor, subject, request_id FROM loom.audit_log WHERE org = {org:String} AND position(subject, {needle:String}) > ? AND namespace NOT IN {shown_hidden:Array(Strin aab29a09f09a SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at -aabfd8358c49 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g aad9d329e92c SELECT org, namespace, source_uri, doc_id, title, description, content, tags, metadata, version, superseded_at, ingested_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, ori aada449038f9 SELECT path, chunk_id FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} GROUP BY path, chunk_id HAVING argMax(embedding_dim, version) = ? aaf76b8f180c ALTER TABLE loom.documents DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -ab03466b06f2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ab17dd911c04 SELECT DISTINCT toString(memory_id) AS mid FROM loom.memory FINAL WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND memory_id IN {ids:Array(UUID)} AND tombstoned_at IS NULL AND user_id +ab25cf36ab2c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ab6563a97507 ALTER TABLE loom.entity_triples DELETE WHERE (org = {org:String} AND cityHash64(namespace, subject, relation, object) IN {owned:Array(UInt64)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_t ab694fe8e1a0 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { ab7b1d37942f SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND namespace = {ns:String} AND ? -abaca5d7137b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g abc727fc102d SELECT test_name, sum(runs) AS runs_in_window, sum(fails) AS fails_in_window, count() OVER () AS matches FROM loom.qa_test_daily FINAL WHERE org = {org:String} AND qa_namespace = {ns:String} AND day > abcf251b1c48 ALTER TABLE loom.learnings_queue UPDATE proposed_value = ?, rationale = ?, decision_reason = ? WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} AND source_kind IN {ki abfe0a1ce868 SELECT DISTINCT toString(candidate_id) AS id FROM (SELECT candidate_id FROM loom.learnings_supporters WHERE org = {org:String}) WHERE candidate_id IN {cids:Array(UUID)} @@ -1573,7 +1580,6 @@ acdb1556ad03 SELECT brief_key, revision, agent, user_id, session_id, head_sha, t acdf77ff85a4 SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL acf8ca67ed68 SELECT count() AS n FROM loom.knowledge_sources WHERE credential_mode = ? OR (source_kind = ? OR kind = ? OR credential_mode = ?) acfa8ad8dceb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist -ad229cd4a4cf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ad2a1b0821de DELETE FROM loom.memory_embeddings WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync ad2be7d3232a SELECT toString(memory_id) AS id, argMax(memory_key, version) AS key, source_class FROM loom.memory_versions PREWHERE org = {org:String} AND namespace = {ns:String} WHERE memory_id IN {ids:Array(UUID) ad2f3798c352 SELECT ? FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?) AND scope_value={ns:String} AND user_id={uid:String}) OR (scope_kind=? AND scope_value={ns:String}) OR (scope_kind=? A @@ -1583,12 +1589,13 @@ ad5724799b14 SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUI ad575f71f510 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, ? AS session_id, ? AS actor, concat(?, entity) AS memory_key, version, ? AS value_json ad69a81ba9d2 SELECT queue_id, agent, user_id, session_id, status, attempts, message_count, content_chars, written, last_error, enqueued_at, updated_at FROM loom.memory_extraction_queue FINAL WHERE org = {org:Strin ad717da278a8 SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:String} AND (user_id = {uid:String} OR (namespace, memory_id) IN (SELECT toString(namespace), memory_id FROM (SELECT namespace, agent, u +ad73105546fb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ad7df829f50e SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model ad8e16687ea3 SELECT count() AS n FROM loom.query_history_sources WHERE org = {org:String} AND namespace = {ns:String} ad9ab785eb2e SELECT number, state, author, title, labels, head_sha, base_sha, files, updated_at FROM loom.code_gh_items FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND is_p ada9a712953c SELECT count() AS n, if(n = ?, NULL, max(updated_at)) AS latest FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status IN (?, ?) adc43eb8c1dd SELECT toString(record_id) AS rid, field_name, value_state FROM loom.memory_record_fields WHERE org = {org:String} AND namespace = {ns:String} AND record_id IN {ids:Array(UUID)} AND tombstoned_at IS N -adf11bff947e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +ade54f89df99 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ae454dd59278 WITH cand AS ( SELECT path FROM loom.code_test_facets FINAL WHERE org = {org:String} AND namespace = {ns:String} AND (facet_kind, name) IN {pairs:Array(Tuple(String, String))} AND tombstoned_at IS NUL ae4e819b95ea SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} ae5b8ffb587a SELECT l.memory_key AS memory_key, toString(l.memory_id) AS memory_id, l.code_namespace AS code_namespace, l.path AS path, l.qualified_name AS qualified_name, l.state AS state, l.changed_since AS chan @@ -1607,7 +1614,9 @@ b0fbecd9222a SELECT memory_id, org, namespace, agent, user_id, session_id, memor b10bb326c320 SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(promoted_from, {sources:Array(String)})) b12468f0e092 SELECT ? FROM loom.memory WHERE tombstoned_at IS NULL AND expires_at IS NOT NULL AND expires_at <= now() AND (org, namespace) NOT IN (SELECT org, namespace FROM loom.namespaces FINAL WHERE retention_d b12d34885e03 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mut +b1418741fbe6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b14f5bc32c83 SELECT memory_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_id IN {ids:Array(UUID)} AND tombstoned_at IS NULL +b1512ea6675d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b1605e1b3322 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ b1686849396a ALTER TABLE loom.memory_record_conflicts UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (prior_record_id IN {ids:Array(UUID)} OR incoming_record_id IN {i b16d9d5df37e SELECT ? AS x FROM loom.scim_users FINAL WHERE id IN {ids:Array(String)} AND active = ? LIMIT ? @@ -1615,23 +1624,21 @@ b17835f57d67 ALTER TABLE loom.working_memory DELETE WHERE (org = {org:String} AN b18bb1fa8a4f SELECT namespace, kind, owner_email, description, tags, active, conversation_logging_enabled, capture_generation_io, coverage_sweep, consolidation_enabled, daily_cost_cap_usd, daily_user_cost_cap_usd, b1931bf6e5a4 SELECT DISTINCT owner_email, org FROM loom.namespaces FINAL WHERE contact_email = {email:String} AND active = ? AND owner_email != ? AND (password_hash = ? OR (org, namespace) IN ( SELECT org, namespa b19a91de5abc SELECT scope_path AS path, summary, pagerank, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embeddin +b1ad3749748d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b21e9b73a809 SELECT count() AS n FROM loom.entity_degree WHERE org = {org:String} AND namespace IN {ns:Array(String)} b2233addfc9d ALTER TABLE loom.memory_belief_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b23268ea2de0 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { b236b7dad790 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ -b23d21a95e52 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g b28c41921399 ALTER TABLE loom.conversation_embeddings UPDATE is_saved = false, saved_at = NULL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_i b28ee52aa7fa SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND namespace = {ns:String} AND event_type != ? b29763aacc63 SELECT record_id, parent_memory_key, session_id, schema_name, record_json, field_text, lexical_score, least( ?, ? * lexical_score + ? + ? ) AS rank_score, -- NB: alias the stringified date as *_iso, N b29c27122f9b SELECT count() AS n FROM loom.knowledge_source_push WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? b2a8d13a93f2 SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? -b2b8650dca93 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g b2d5a25cd043 SELECT count() AS n FROM loom.agent_runs WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? b2eda427e5b8 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a b3008a1630c8 SELECT n.org AS org, n.namespace AS namespace, n.owner_email AS owner_email, live.live_rows AS live_rows, greatest(ifNull(w.last_write, toDateTime64(?, ?)), toDateTime64(live.last_created, ?)) AS last b30fdbb7b57a SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, degree FROM ( SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, row_number() OVER (PARTITION BY src b32239abb324 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread -b33bc129de89 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g b342b80cc105 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? b39112fc83b4 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? b3bd7a2bbf21 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL @@ -1649,10 +1656,13 @@ b4bd124a4089 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. b4eaaee7f731 SELECT org, namespace, agent, user_id, session_id, name, source_id, host, port, secure, user, password_enc, cluster, databases, actor, source_class, created_at, tombstoned_at, version FROM loom.query_ b4fcede7dd0d SELECT * EXCEPT (embedding) FROM loom.code_summaries FINAL WHERE (org, namespace, embedding_model, scope_type, scope_path) IN {keys:Array(Tuple(String, String, String, String, String))} AND embedding_ b50bb3c82af0 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU +b50d606a3284 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou b517057ddbb9 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), {keys:Array(String)}) +b5372e83b5f1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b546d3bd8553 SELECT count() AS n FROM loom.entity_edge_memories WHERE org = {org:String} AND namespace = {ns:String} AND ? b556883f0824 ALTER TABLE loom.entity_triple_memories DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b57226087b36 ALTER TABLE loom.memory DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +b5983d19891b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b599a544d8e9 SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND superseded_at IS NULL b5c1f249d43b ALTER TABLE loom.delete_version_checks DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b5cfdd2b8732 DELETE FROM loom.memory_embeddings WHERE (org = {org:String} AND scope = ? AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND ({erasure_mutation_tag:String} = {erasure_mutation_ta @@ -1662,12 +1672,12 @@ b6559a8e5adb SELECT number, state, author, title, labels, opened_at, closed_at, b66012743fd9 SELECT DISTINCT path FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND lower(content) LIKE {gp_0:String} AND position(content, {pat b66541ee51e6 SELECT memory_key, content_excerpt, event_date, distance FROM ( SELECT memory_key, content_excerpt, toDate(coalesce(temporal_anchor, valid_at)) AS event_date, cosineDistance(embedding, {q:Array(Float3 b672950c0262 SELECT org, code_namespace, branch_namespace, pr_number, branch, verdict, epistemic, basis, reason, cherry_pick_pr, cherry_pick_sha, backport_pr, label_wanted, wanted_branch, wanted_source, settled, p +b67517a275d1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b6863354aea9 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR b68ceac3dfb4 DELETE FROM loom.memory_embeddings WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? b696b34d3213 ALTER TABLE loom.events DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b6a13cb61dc5 SELECT memory_key, memory_type, content_excerpt, valid_at, created_at, namespace, count() OVER () AS total_matching FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:Strin b6af5d3577c9 ALTER TABLE loom.conversations UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutat -b6bcb78ce0e7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g b6e3262356f1 ALTER TABLE loom.entity_summaries DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b6e450fe3122 ALTER TABLE loom.idempotency DELETE WHERE (org = {org:String} AND ?) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b6efdfdd16e7 ALTER TABLE loom.entity_edge_memories DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1678,6 +1688,7 @@ b71b52607a5e SELECT path, lang, size_bytes, loc, indexed_commit, count() OVER () b72f652f8cd3 SELECT org, qa_namespace, issue_number, pr_number, rank, score, bm25_title, bm25_body, bm25_norm, window_hours, component_match, frames_symbols, frames_files, frames_total, closes_mention, terms, pr_t b754383d88e8 SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} b75c692879fc SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FROM ( SELECT namespace, thread_id, ts, msg_id, row_bytes, sum(row_bytes) OVER (ORDER BY namespace, thread_id, ts, msg_id ROWS BETWEEN +b7611790f428 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b76599c7ef8e SELECT pr_number, title, author, labels, body_excerpt, files, merge_commit_sha, merged_at, target_branch FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_num b7673cb46abc SELECT concat(?, session_id, ?, toString(chunk_index)) AS memory_key, ? AS memory_type, content AS content_excerpt, toString(created_at) AS created_at, toString(created_at) AS valid_at FROM loom.memor b76b606d5ec4 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -1703,13 +1714,10 @@ b9f6cfd45b7f SELECT count() AS n FROM loom.conversations WHERE org = {org:String ba2554cad547 SELECT source_uri, count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri IN {uris:Array(String)} AND doc_superseded_at IS NULL AND (org, namespace, embeddin ba2843155ed7 SELECT queue_id, agent, user_id, session_id, status, version, enqueued_at < now64(?) - toIntervalDay(?) AS past_last_day FROM loom.memory_extraction_queue FINAL PREWHERE org = {org:String} AND namespa ba28d3f48cd1 SELECT ts, org, namespace, agent, user_id, session_id, operation, request_id, mode, decision, enforced, determining_rules, errors, detail, latency_ms FROM loom.policy_decisions WHERE org = {org:String -ba3aa58d4a58 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ba505cefcdfd SELECT subject, namespace, role, granted_at, pending_role, is_owner FROM ( SELECT subject, namespace, toString(role) AS role, granted_at, pending_role, ? AS is_owner FROM loom.namespace_grants FINAL W ba7611490c4d ALTER TABLE loom.search_misses DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? bb02b0e3dee7 SELECT symbol_id, qualified_name, name, signature, path, start_line, end_line, tier, kind FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND -bb04945353ff SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g bb4566fa0eb8 SELECT namespace, toString(owner_email) AS owner, active, tags, password_hash = ? AS sso FROM loom.namespaces FINAL WHERE org = {org:String} AND contact_email = {ident:String} -bb4f8de6abf4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g bb995e847c01 SELECT thread_id, uniqExact(msg_id, cityHash64(content)) AS n, argMax((agent, toString(role), substringUTF8(content, ?, {listed:UInt32})), (ts, msg_id)) AS last_turn FROM loom.conversations WHERE org bba54143f24b ALTER TABLE loom.learnings_queue DELETE WHERE (org = {org:String} AND candidate_id IN {cids:Array(UUID)} AND status = ?) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mu bba7b08570b0 ALTER TABLE loom.conflict_allowlist UPDATE tombstoned_at = {ts:DateTime}, reason = concat(reason, ?, {note:String}) WHERE org = {org:String} AND namespace = {ns:String} AND memory_key_a = {a:String} A @@ -1721,8 +1729,7 @@ bbe8f503595e WITH (SELECT (toFloat64(count()), sumMap(arrayFilter(s -> has({stem bc00b5272311 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} bc1c9ad1efe8 ALTER TABLE loom.entity_triple_memories DELETE WHERE (org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag: bc2fa2b83f5e SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN -bc5126e6ac2f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -bc80814b4c3b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +bc5b1bfc8719 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this bc8de31fd6e5 DELETE FROM loom.memory_evidence WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? bcbd26618fa1 SELECT ? AS seen FROM (SELECT raw.ts AS ts, raw.org AS org, raw.namespace AS namespace, raw.agent AS agent, raw.user_id AS user_id, raw.session_id AS session_id, raw.run_id AS run_id, raw.operation AS bccb3b408622 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND scope = ? AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} @@ -1732,6 +1739,7 @@ bd095b55bf5d SELECT count() AS n FROM loom.memory_embeddings WHERE org = {org:St bd4266cbfe15 SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} bd96c18aed1a SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l bda43b1f632f WITH arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc)) AS words SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance +bdcbc97a1057 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this bdde77a5c044 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, toString(evidence_id)) AS memory_key, toUInt64(toUni bde7c432bca1 ALTER TABLE loom.entity_communities DELETE WHERE (org = {org:String} AND (cityHash64(namespace, entity) IN {entities:Array(UInt64)} OR cityHash64(namespace, label) IN {entities:Array(UInt64)})) AND ({ bde98d358a2b SELECT path, uniqExact(facet_kind, name) AS matched, groupArray((facet_kind, name, ordinal, line, confidence)) AS hits, length(arrayIntersect(groupUniqArrayIf(ordinal, facet_kind = {k0:String} AND nam @@ -1748,11 +1756,9 @@ bf09992e73fc SELECT memory_key, toString(memory_id) AS id, version, memory_type, bf0c10f9a95a SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision FROM loom.chunks WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND embedding_model bf193ac927b4 SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND namespace = {ns:String} bf1ce8fef88c SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias -bf4ffadd242a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g bfbdb1dc9399 SELECT namespace, count() AS turns, uniqExact(session_id) AS sessions, sum(toUInt64(input_tokens)) AS input_tokens, sum(toUInt64(cache_read_tokens)) AS cache_read_tokens, sum(toUInt64(cache_creation_5 bfc004b68fb9 DELETE FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND session_id = {s:String} AND memory_key = {k:String} AND (((c bfd5743c4304 SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} -bfd60b03e477 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g bfea84126fad SELECT toString(visibility) AS visibility, active, requires_approval, ifNull(kind, ?) AS kind, toString(join_policy) AS join_policy, toString(classification) AS classification FROM loom.namespaces FIN c06061acf9ae SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL c08820c92bcf SELECT symbol_id, qualified_name, path, fan_in_calls, fan_in_nontest, fan_in_name, caller_files, defined_files, is_test FROM loom.code_symbol_stats FINAL WHERE org = {org:String} AND namespace = {ns:S @@ -1761,19 +1767,19 @@ c089ec35a685 SELECT org, namespace, source_uri, version, revision, title, descri c08d6d75fc0e SELECT max(toUInt32OrZero(extract(path, ?))) AS n FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND startsWith(path, ?) c095360ca752 ALTER TABLE loom.memory_projection_failures DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = c0ce0f6f148d SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER -c120bd746afc SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c14310076fa0 SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread c1434f6b0ebe SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:String} AND namespace = {ns:String} AND ? +c1513845a8b8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c15f8b68d7f7 SELECT agent AS key, sum(upstream_cost_usd) AS total_cost_usd, count() AS total_calls, uniqExact(operation) AS ops_distinct , uniqExact(namespace) AS namespaces_distinct FROM (SELECT raw.ts AS ts, raw c16434c88b3c SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {scope_uid:String}) c165eb8bf32a SELECT worker, argMax(failures, finished) AS consecutive_failures, argMax(error_class, finished) AS error_class, max(finished) AS last_finished FROM ( SELECT worker, instance_label, argMax(consecutive c169a496882f SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND namespace = {ns:String} c16e06ab36a7 SELECT chunk_id, path, scope, kind, start_line, end_line, embedding_dim, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings( concat(?, lexemes, ?), concat(?, tok, ?) ), {tokens:Array(String)}, {i c1aa2dbb7a43 SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND hasAny(window_keys, {keys:Array(String)}) -c1ad00d9e230 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c1dd61e21ceb SELECT window_start, window_end, row_count, toString(rows_digest) AS rows_digest, toString(prev_checkpoint_hash) AS prev_checkpoint_hash, toString(checkpoint_hash) AS checkpoint_hash FROM loom.audit_c c1f9002b82f4 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to c1fc173ac609 SELECT pr_number, title, author, merged_at, files, linked_issues, (match(title, {revert_re:String}) OR positionCaseInsensitive(body_excerpt, ?) > ? ) AS is_revert FROM loom.code_pr_history FINAL WHERE +c228994bcf35 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c23ce268d788 SELECT DISTINCT start_line, end_line, content, kind, scope, symbol_ids, toString(indexed_commit) AS indexed_commit FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND c23f3a6975c8 ALTER TABLE loom.memory_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND scope = ? AND (namespace, memory_key) IN {keys:Array(Tuple(String, Stri c266319cd4ad SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL @@ -1802,9 +1808,10 @@ c4cee4797736 SELECT count() AS sources, countIf(j.has_document = ? AND NOT j.rep c4d11f8d928a SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} c4d8e27d9015 SELECT tier, qualified_name, symbol_id, name, path, start_line, end_line FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND (tier, qualified_name, symbol_id) IN ( SE c4e9948e3b0a SELECT count() AS n FROM loom.events WHERE org = {org:String} AND user_id = {uid:String} AND ? +c4ebebde6b03 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? c4f78bf506c2 ALTER TABLE loom.chunks UPDATE doc_superseded_at = {now:DateTime} WHERE (org = {org:String} AND namespace IN {ns:Array(String)} AND doc_superseded_at IS NULL) AND ({erasure_mutation_tag:String} = {era c4fb2b7ac3e8 ALTER TABLE loom.tasks DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -c505e5d9fbf9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +c529ba815261 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c53355b3cf3a SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER c562da6b7b7f SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND namespace IN {ns:Array(String)} c5f2a81cdd02 SELECT count() AS n FROM loom.consolidation_runs WHERE org = {org:String} AND user_id = {uid:String} @@ -1812,30 +1819,31 @@ c6056fca9bec ALTER TABLE loom.conflict_allowlist UPDATE tombstoned_at = {now:Dat c6278079e133 SELECT namespace, agent, user_id, session_id, memory_key, toString(memory_id) AS mid, value, tags, files, toString(content_sha256) AS sha, version FROM loom.memory FINAL WHERE org = {org:String} AND n c6381f8d82cd SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND user_id = {uid:String} c65537c736d4 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, -c66359775d68 SELECT memory_key, memory_type, if({full_values:UInt8}, value, substring(value, ?, if((memory_type = ? OR hasAny(tags, [?, ?])), {whole_bytes:UInt32}, ?))) AS value, tags, confidence, pinned, CAST(sta c6a6b15089e3 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND namespace = {ns:String} c6a8c61641b8 ALTER TABLE loom.entity_summaries UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {e c6c0326e2dd5 SELECT DISTINCT embedding_model, msg_id FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND ((agent c6c8bd9f5afd SELECT operation, sumMerge(cost_usd_state) AS cost_usd, sumMerge(tokens_state) AS tokens, sumMerge(embed_tokens_state) AS embed_tokens, countMerge(ops_state) AS ops, sumMerge(errors_state) AS errors, c6cde2e02fad ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -c6d2cd622bdf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c6e9dc907dc7 SELECT value FROM loom.oauth_signin_state WHERE claim_key = {k:String} +c70604a9efed SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c71b88136b17 SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND user_id = {uid:String} AND ? c72e7e6dceb9 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} +c76fd586918f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c77ef954081d SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to c7a141e14400 SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc c7ae15b6a560 SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns c7bb2467449a SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model c7c8b7f2f21c ALTER TABLE loom.memory_record_conflicts DELETE WHERE (org = {org:String} AND (prior_record_id IN {ids:Array(UUID)} OR incoming_record_id IN {ids:Array(UUID)})) AND ({erasure_mutation_tag:String} = {e +c7d2f923fd60 DELETE FROM loom.read_receipts WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? c7ec8090e470 SELECT memory_key, memory_type, content_excerpt, ? - cosineDistance(embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(temporal_anchor, toDateTime(?))) AS temporal_anchor, temporal_confi c8167139ec34 DELETE FROM loom.memory_embeddings WHERE (org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String))} c8342f918649 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user c8424367f9c9 SELECT namespace, source_uri, count() AS chunk_count FROM loom.chunks WHERE org = {org:String} AND (namespace, source_uri) IN {keys:Array(Tuple(String, String))} AND doc_superseded_at IS NULL AND (org -c850ef07bf65 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c853d7bbd170 SELECT org, agent, count() AS calls, countIf(if(consumer = ?, args[?], consumer) NOT IN {untagged:Array(String)}) AS tagged, calls - tagged AS untagged, round(tagged / calls, ?) AS tagged_ratio, anyIf c85b7e038508 SELECT namespace, kind FROM loom.namespaces FINAL WHERE org = {org:String} c873c5cd3338 SELECT retention_days, dedup_threshold, hot_quota, conflict_policy FROM loom.namespace_types FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_type = {mt:String} LIMIT ? c87677674058 SELECT DISTINCT namespace FROM loom.search_misses WHERE org = {org:String} AND (has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id))) +c884110db3ce SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c8870c302e09 SELECT min(t.bumped) AS first_unfolded FROM ( SELECT org, namespace, memory_id, sum(recall_count) AS recall_total, sum(evidence_count) AS evidence_total, max(last_recalled_at) AS last_recalled, max(bu c892414a0cf3 SELECT role, granted_by, status, pending_role, pending_since FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND subject = {sub:String} AND revoked_at IS NULL AND c8ce735d214f SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} @@ -1845,6 +1853,7 @@ c91d7e14d509 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} c924a3001167 SELECT memory_id, version, confidence, source_trace, pinned, created_at, updated_at, expires_at, tombstoned_at, redacted_at, redaction_reason, actor, source_class, agent, status, conflict_with, tags, c92bf0b39a95 SELECT chunk_index, content, embedding_dim FROM loom.memory_chunks FINAL WHERE org = {org:String} AND namespace = {namespace:String} AND session_id = {session_id:String} AND chunk_index BETWEEN {first c95045c50e46 SELECT count() AS n FROM loom.code_answers WHERE org = {org:String} AND (namespace = {ns:String} OR memory_namespace = {ns:String}) +c95637249d50 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this c97078eb79f8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist c97976fc373a SELECT ts, event_type, org, namespace, actor, subject, request_id FROM loom.audit_log WHERE org = {org:String} AND namespace = {ns:String} AND namespace NOT IN {shown_hidden:Array(String)} AND NOT mat c99a26ec4116 SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND (prior_record_id IN (SELECT record_id FROM loom.memory_records WHERE org = {org:String} AND user_id = {uid:Stri @@ -1853,8 +1862,8 @@ c9e1e8c68869 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {o c9f9d7dec4e6 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} c9fa8afaae00 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { c9fe098e7b96 ALTER TABLE loom.memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mut +c9fff1bc7d69 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ca0b395ea906 SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL -ca0ee9f43efa SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ca154b025d9d ALTER TABLE loom.memory_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = { ca1912ebd5ef SELECT count() AS n FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ca1dc69efef1 ALTER TABLE loom.entity_triples DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1862,9 +1871,8 @@ ca2544d6bcf6 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org ca351aa27df2 ALTER TABLE loom.memory_code_links UPDATE suggestion = ?, judged_hash = ? WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND session_id = {s:Strin ca3ca2bdf380 SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND namespace = {ns:String} ca4f97381722 SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} -ca5008422344 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ca58f3affe58 ALTER TABLE loom.conversation_threads UPDATE tombstoned_at = {now:DateTime} WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND tombstoned_ -ca924a95865f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +ca59aaf74d77 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ca9ec9e5facb SELECT count() AS c FROM ( SELECT evidence_id, argMax(tombstoned_at, created_at) AS tomb_latest FROM loom.memory_belief_sources WHERE org = {o:String} AND namespace = {n:String} AND memory_key = {k:St caa73a929cde SELECT toUnixTimestamp64Milli(now64(?)) AS ms cabd0fc4905d ALTER TABLE loom.consolidation_runs DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1896,6 +1904,7 @@ cd90d22d20ca ALTER TABLE loom.agent_runs DELETE WHERE (org = {org:String} AND us cd9e93d56539 SELECT name, tier, qualified_name, symbol_id, argMax(kind, version) AS kind, argMax(tombstoned_at IS NULL, version) AS is_live FROM loom.code_symbol_names WHERE org = {org:String} AND namespace = {ns: cda426d483f7 SELECT count() AS n FROM loom.code_answers WHERE org = {org:String} AND (namespace = {ns:String} OR memory_namespace = {ns:String}) AND (answer != ? OR citations != ? OR question != ?) AND ? cda6ebc4e0e5 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, +cdb7fc08cc9c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ce0fd8b93ea7 SELECT f AS path, argMin(pr_number, merged_at) AS first_pr, min(merged_at) AS first_merged_at FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} ce17fa3463a5 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status != ? AND tombstoned_at IS NULL AND user_id = {uid:String} AND session_id = {sid:String} AND m ce2f9959b87c SELECT count() AS n FROM loom.operator_edges FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL @@ -1908,7 +1917,6 @@ cea581143d39 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_ cec032d1cb17 SELECT user_id FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:String} AND is_sav cec3f5ad060e SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN cee7e1df6fac SELECT jti, revoked_at, expires_at, reason, revoked_by, issued_before, version FROM loom.revoked_tokens FINAL WHERE jti = {j:String} AND expires_at > now() -cf06ff759823 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g cf0cc9e2222f SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns:String} cf104f8e96d5 SELECT ? FROM loom.memory_extraction_queue FINAL WHERE org={org:String} AND namespace={namespace:String} AND agent={agent:String} AND user_id={user_id:String} AND session_id={session_id:String} AND qu cf1e114983a0 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), @@ -1922,18 +1930,16 @@ cfc0533b440e SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {o cfdc9de83162 SELECT from_symbol_id, path, argMax(guards, version) AS guards, argMax(guard_kinds, version) AS guard_kinds, argMax(sites, version) AS sites, argMax(site_callees, version) AS site_callees, argMax(site cfee4638bfe0 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL) WHERE lower(tag) IN {names:Array( cff998bacc10 ALTER TABLE loom.dataset_rows DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +d011453cdd96 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d043dcfa2c2b SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} d04bc22409e3 SELECT uniqExact(msg_id) AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NOT NULL AND (agent = {agen d05cbcbbe13f SELECT path, target.? AS symbol_id, target.? AS definition, min(start_line) AS start FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( key -> key.? = path AND has(symbol_ids, key.?) AND start_line < d06419919bf2 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL d06c9096df61 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER -d0802f441bc2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -d089a672528c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g d0a888305d0b SELECT org, code_namespace, branch_namespace, pr_number, branch, verdict, epistemic, basis, reason, cherry_pick_pr, cherry_pick_sha, backport_pr, label_wanted, wanted_branch, wanted_source, settled, p d0be57c846ee SELECT if(consumer = ?, args[?], consumer) AS consumer_key, count() AS calls, countIf(NOT success) AS errors, countIf(NOT success AND error_code = ?) AS server_errors, round(errors / calls, ?) AS erro d0c38ecb1040 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model d0c98dde6333 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -d10a174bff69 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g d11e82174d2d SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user d143302e86ef SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows d19be6e39b44 SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key, created_at, version FROM loom.memory_embeddings FINAL PREWHERE (org, namespace, agent, user_id, session_id, memor @@ -1948,6 +1954,7 @@ d2c01d2cb202 SELECT count() AS n FROM loom.entity_canonical_map FINAL WHERE org d2c964f328e6 SELECT path FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND arrayExists(s -> endsWith(path, s), {suffixes:Array(String)}) ORDER BY path LI d2f86e5a0e3b SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND namespace = {ns:String} AND ? d2fd4c13d8ce DELETE FROM loom.knowledge_sources WHERE org = {org:String} AND namespace = {ns:String} AND owner_subject = {owner:String} AND credential_mode = ? AND source_kind = {kind:String} AND NOT (source_kind +d30026efd74b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d304379eee88 SELECT DISTINCT toInt64(units) AS units, ? AS erasure_type, ? AS erasure_value FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?,?) AND scope_value={ns:String} AND user_id={uid:S d33262f73e11 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER d33dae31077e SELECT toString(schema_id) AS schema_id, name, description, status FROM loom.memory_schemas FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status = ? ORDER BY @@ -1969,6 +1976,7 @@ d4b213b382a9 SELECT ? AS hit FROM loom.memory_usage_events WHERE org = {org:Stri d4dce40507f9 SELECT state_key, state_value, version FROM loom.code_index_state FINAL WHERE org = ? AND namespace = {ns:String} AND state_key IN {keys:Array(String)} d4ef142bf4bd ALTER TABLE loom.conversation_embeddings UPDATE is_saved = false, saved_at = NULL, tombstoned_at = {when:DateTime} WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND t d4fee96dc8f4 SELECT symbol_id, qualified_name, name, signature, path, start_line, end_line, tier, kind, toString(indexed_commit) AS extent_commit FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace +d5470e8ddca2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d557e6a3b134 SELECT memory_key, memory_type, confidence, version, created_at, expires_at, valid_at, pinned, status, evidence_count, recall_count, last_recalled_at, tags, entities, source_trace, sensitivity, verifi d56922333058 SELECT splitByChar(?, memory_key)[?] AS prefix, count() AS rows FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND position(memory_key, ?) > ? GR d5b4ec5018be SELECT name, qualified_name, path FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tier = ? AND (qualified_name, symbol_id) IN ( SELECT qualified_name, symbol_id F @@ -1976,6 +1984,7 @@ d5ec04e0cf87 ALTER TABLE loom.session_briefs DELETE WHERE (org = {org:String} AN d5ec7f2e8ae9 SELECT memory_key, toString(memory_id) AS id, version, sensitivity, value_len, redacted_at IS NOT NULL AS redacted, agent, user_id, session_id, memory_type, source_class, updated_at FROM loom.memory F d5ef8fb29c15 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND session_id != {id:String} AND d5fe39952bc8 SELECT pr_number, comment_id, path, line, author, body, comment_created_at FROM loom.code_pr_reviews FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND to +d6662b746f94 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d694356aa10c WITH expk AS ( SELECT org, namespace, run_id, k AS memory_key, min(ts) AS first_seen FROM loom.memory_exposures ARRAY JOIN returned_keys AS k WHERE ts > {since_exp:DateTime} AND run_id NOT IN (?, ?) G d6a2045b3ae5 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, version FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns: d6a93eee9053 SELECT source_uri, count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri IN {uris:Array(String)} AND doc_superseded_at IS NULL AND (org, namespace, embeddin @@ -1987,9 +1996,9 @@ d6f4dbbe11c2 SELECT count() AS n FROM loom.code_search_trace WHERE org = {org:St d6f86512c787 ALTER TABLE loom.memory_record_fields UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} d703c37f097b SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} d72c59703717 ALTER TABLE loom.context_blobs DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +d72fe5d38968 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d734505c48d8 SELECT embedding, embedding_dim, embedding_model FROM loom.qa_item_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND kind = {kind:String} AND number = {n:UInt64} AND tombstoned d749ae65d41a SELECT toString(memory_id) AS id, argMax(status, version) AS status, argMax(superseded_by, version) AS superseded_by, -- argMax skips NULLs: take it over the flag, or a restored row reads deleted. arg -d76186bb002a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g d77696150f16 SELECT id, org, scope_type, scope_value, requester, actor, urgency, purge, mirror_marked, attempts, steps_completed, requested_at, failure_reason, residue_count, residue, verified_at, census FROM loom d7794951d874 SELECT count() AS n FROM loom.code_search_trace WHERE org = {org:String} AND namespace = {ns:String} d782528717e8 ALTER TABLE loom.memory_extraction_queue UPDATE status=?, last_error=?, lease_until=toDateTime64(?,?) WHERE org={org:String} AND namespace={namespace:String} AND agent={agent:String} AND user_id={user @@ -2002,11 +2011,11 @@ d7cfaad88c70 SELECT toString(memory_id) AS memory_id, version, value, tags, vali d7d96dfa1058 SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? d7dc30a09645 SELECT block_key, content, char_limit, version, updated_at FROM loom.working_memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND d7de17d5a712 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a -d808cd422fe1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g d82b17493a28 SELECT if(s.user_id != ?, s.user_id, p.user_id) AS who, s.digest AS digest, if(h.user_id != ?, h.version, p.version) AS profile_version FROM ( SELECT user_id, leftPad(lower(hex(groupBitXor(sipHash64(m d839b7f9932b SELECT pr_number, title, author, merged_at, files, additions, deletions FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at < { d83b2c2ce2d0 SELECT count() AS n FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND pr_number = {pr:UInt32} AND pr_number NOT IN ( SELECT pr_numbe d868e6812142 SELECT daily_cost_cap_usd, daily_user_cost_cap_usd, budget_alert_inbox FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? +d87db4dc5a99 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this d8994cf87248 ALTER TABLE loom.documents UPDATE superseded_at = {now:DateTime} WHERE (org = {org:String} AND namespace = {ns:String} AND superseded_at IS NULL) AND ({erasure_mutation_tag:String} = {erasure_mutation d8a5b7c95b66 SELECT src_path, test_path, method, max(confidence) AS confidence, anyLast(evidence) AS evidence FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND src_path IN {pat d8ae3db37924 ALTER TABLE loom.conversation_threads DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -2014,8 +2023,6 @@ d8bfa06e05a1 SELECT number, head_sha, base_sha, files FROM loom.code_gh_items FI d933bd904df8 SELECT count() AS n FROM loom.document_blobs WHERE org = {org:String} AND namespace = {ns:String} d93d46e4c7b2 SELECT if(s.user_id != ?, s.user_id, p.user_id) AS who, s.digest AS digest, if(h.user_id != ?, h.version, p.version) AS profile_version FROM ( SELECT user_id, leftPad(lower(hex(groupBitXor(sipHash64(m d946250457c8 SELECT *, checked_at < toDateTime(fromUnixTimestamp64Nano(toInt64({before:UInt64}))) - INTERVAL {days:UInt32} DAY AS expired, hex(sipHash128(path, qualified_name, namespace, memory_id)) AS scan_digest -d94876cb7709 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -d99357c88d12 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g d9a9b49ab646 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model d9b16651542c ALTER TABLE loom.entity_edge_memories DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync da16c635942f SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} @@ -2026,6 +2033,7 @@ daa9953aad14 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index) dabe37717488 SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} ORDER BY state_key dae0d2378112 SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL dae4a1968b69 ALTER TABLE loom.context_blobs UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutat +dae7125bf66f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this db13fde1fa1b SELECT count() AS n FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL db1aefddf28d ALTER TABLE loom.document_blobs DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? db20b0dcab76 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, created_at, valid_at, version, status FROM ( SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, t @@ -2047,7 +2055,7 @@ dc003d9f3eb2 SELECT toString(failure_id) AS failure_id, org, namespace, agent, p dc06a0e4e9ec SELECT count() AS n FROM loom.code_search_outcome WHERE org = {org:String} AND namespace IN {ns:Array(String)} dc0b35f711b3 INSERT INTO loom._migration_lock (name, holder, acquired_at, renewed_at, ttl_s, build_commit) SETTINGS keeper_map_strict_mode = ?, async_insert = ? VALUES ({name:String}, {me:String}, now64(?), now64( dc258476c8e1 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL -dc8f7f26ff35 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +dc8d24176f6d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this dcaad5caba4b SELECT agent, user_id, memory_key, argMax(reinforcement_count, version) AS reinforcement_count, argMax(last_reinforced_at, version) AS last_reinforced_at FROM loom.memory_reinforcement WHERE org = {or dcacca961d46 WITH arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc)) AS words SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance dcb2464f4c49 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND user_id = {uid:String} AND ? @@ -2067,8 +2075,6 @@ dda464c89047 SELECT neighbor, role, sum(co_occur) AS co_occur FROM ( SELECT obje ddb1a5ea55c9 SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL ddc00b268be8 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, queue_id) AS memory_key, version, ? AS value_json, t dde8208a93a2 SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? -ddfb30beb525 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -de25c2cb1919 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g de2873bc124f SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc de6e3a798fff DELETE FROM loom.entity_vectors WHERE (org = {org:String} AND (user_id = {uid:String} OR (namespace, memory_key) IN {keys:Array(Tuple(String, String))})) AND ({erasure_mutation_tag:String} = {erasure_ de7bbe4a4ec2 ALTER TABLE loom.memory_categories UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = { @@ -2077,8 +2083,10 @@ de88ab6d445d SELECT queue_id, agent, user_id, session_id, status, attempts, mess de897aab140e ALTER TABLE loom.memory_projection_failures DELETE WHERE (org = {org:String} AND (JSONExtractString(payload, ?) = {uid:String} OR arrayExists(e -> JSONExtractString(e, ?) = {uid:String}, JSONExtractAr deafbec33253 SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND namespace = {ns:String} deb47fbf6e50 SELECT neighbor, role, sum(co_occur) AS co_occur FROM ( SELECT object AS neighbor, ? AS role, sum(co_occur) AS co_occur FROM loom.entity_triples WHERE org = {org:String} AND namespace = {ns:String} AN +deb654b145c4 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ded4dbaaf6b9 SELECT toString(schema_id) AS schema_id, name, description, status FROM loom.memory_schemas FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY name LIMIT {li dedc23bcedfb SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FROM ( SELECT namespace, thread_id, ts, msg_id, row_bytes, sum(row_bytes) OVER (ORDER BY namespace, thread_id, ts, msg_id ROWS BETWEEN +df046ee37fdc SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this df065418883d DELETE FROM loom.chunks WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? df0e1be64e2f SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, confidence, agent FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL A df31f9f54e16 SELECT from_key, to_key, relation FROM loom.operator_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND from_key IN {keys:Array(String)} AND relation IN {rels:Array(String)} AND tomb @@ -2116,7 +2124,6 @@ e1ad22795fae SELECT count() AS n FROM loom.knowledge_ingest_cancels WHERE org = e1bbf72c5367 SELECT org, namespace, name, source_id, provider, generation, fingerprint, provider_id, status, secret_enc, agent, user_id, session_id, actor FROM loom.knowledge_source_push FINAL WHERE provider = ? A e1d3cfd2dea5 ALTER TABLE loom.entity_canonical_map DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? e1def4eb2c85 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, version, value, toString(value_json) AS object_text FROM loom.memory FINAL WHERE tombstoned_at IS NULL AND sensitivity = ? AND -e1e575757b4d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g e1eb0c7b7e97 SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} e226762a2e02 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to e25d8681d2ed SELECT sumForEach(arrayMap((hit, pre) -> toUInt32(hit > ? AND startsWith(path, pre)), multiSearchAllPositions(content, {pats:Array(String)}), {prefixes:Array(String)})) AS hits, count() AS chunks FROM @@ -2127,21 +2134,22 @@ e2ac0ebae738 SELECT ? FROM loom.conflict_allowlist FINAL WHERE org = {org:String e2b0bf26bd07 SELECT count() AS n FROM loom.knowledge_ingestions WHERE org = {org:String} AND namespace IN {ns:Array(String)} e2b366085ee8 SELECT toString(candidate_id) AS candidate_id, proposed_value FROM loom.learnings_queue FINAL WHERE org = {org:String} AND namespace = {ns:String} AND source_kind IN {kinds:Array(String)} AND proposed e2b5eb67509b SELECT count() AS n FROM loom.scim_users FINAL WHERE deleted = ? -e2c7ea266e58 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g e2d6458239f7 SELECT number, is_pr, state, state_reason, author, title, opened_at, closed_at, merged_at, updated_at FROM loom.code_gh_items FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_ -e2dfec65926a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g e30e0afa7cd0 ALTER TABLE loom.memory_record_versions DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? e31386435853 SELECT count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND namespace IN {ns:Array(String)} e33eba4d561f SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns e37d6af3680a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist +e39d8f5737df SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e3a91311885a SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user e3ac6b4d5b37 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace IN {ns:Array(String)} e3b4b40993e4 SELECT DISTINCT org, code_namespace FROM loom.memory_code_links WHERE tombstoned_at IS NULL ORDER BY org, code_namespace +e42328436802 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e437129a1eed SELECT path, lang, index_error, indexed_commit, created_at FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND index_error != ? ORDER BY creat e43d0c378314 SELECT org, namespace, consumer, query AS pattern, path_prefix, count() AS calls FROM loom.code_search_trace WHERE ts > now() - INTERVAL {hours:UInt32} HOUR AND op = ? AND abstain = ? AND route IN (?, e47e74abe77a SELECT ts, org, namespace, agent, user_id, session_id, operation, request_id, trace_id, latency_ms, input_tokens, output_tokens, embedding_tokens, upstream_cost_usd, bytes_written, success, error_code e4e22f2c7784 SELECT count() OVER () AS total, a.memory_key AS memory_key, toString(a.memory_id) AS memory_id, dateDiff(?, a.created_at, now()) AS age_seconds FROM (SELECT org, namespace, agent, user_id, session_id e4e978084474 SELECT namespace, kind, toString(visibility) AS visibility, title, description FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} +e4f3e7424c6a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e5024546eff6 SELECT count() AS n FROM loom.knowledge_group_members WHERE org = {org:String} AND namespace = {ns:String} e51463feccae SELECT namespace, sum(upstream_cost_usd) AS cost_usd, sum(toUInt64(input_tokens) + toUInt64(output_tokens)) AS tokens, sum(toUInt64(embedding_tokens)) AS embed_tokens, count() AS ops, countIf(mirror_m e528e5544515 SELECT count() AS n FROM loom.document_blobs WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -2154,29 +2162,30 @@ e5bac6e4a74e SELECT memory_id, version, agent, user_id, session_id, memory_key, e5ca09ca8882 SELECT ? FROM loom.revoked_tokens FINAL WHERE jti IN {keys:Array(String)} AND expires_at > now() AND issued_before IS NULL UNION ALL SELECT ? FROM loom.oauth_state FINAL WHERE record_type = ? AND id = e5d3479fff14 SELECT agent, user_id, session_id, memory_key, cosineDistance(embedding, {emb:Array(Float32)}) AS dist FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND user_i e5df581175ec SELECT count() AS n FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace IN {ns:Array(String)} -e5e482e9d615 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g e60347067264 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, e62faca61816 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create e67a89c4f6c6 SELECT group_id, members FROM loom.principal_groups FINAL WHERE org = {org:String} AND NOT deleted e68412b65969 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, memory_key, version, toString(value_json) AS value_json, value e6990fcc8c82 SELECT thread_id, msg_id, role, content_excerpt AS embedded_text, ts, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND nam +e6e57a9d517a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e6f6f6bc74e2 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} +e6fedcc9761c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e7331ee31d1b SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user e747c3134919 ALTER TABLE loom.memory_record_fields UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND record_id IN {ids:Array(UUID)}) AND ({erasure_mutation_tag:String} = e75f4a024984 SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns:String} AND ? e77afbb3fb28 SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND doc_superseded_at IS NULL AND (org, namespace, embedding_model, source_uri, doc_version) NOT IN (S e77b590b9f54 SELECT org, namespace, name, source_id, provider, generation, fingerprint, provider_id, status, secret_enc, agent, user_id, session_id, actor FROM loom.knowledge_source_push FINAL WHERE org = {org:Str e77c1e05f3c4 SELECT count() AS n FROM loom.blob_uploads WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +e7b42de1321e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e7d4c583cc0e ALTER TABLE loom.procedure_runs DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? e7ef19d41a90 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create e7f1d693d5b1 SELECT count() AS n FROM loom.entity_vectors WHERE org = {org:String} AND (user_id = {uid:String} OR (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) e8009bd53bc4 SELECT number, head_sha FROM loom.code_gh_items FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND is_pr AND state = ? AND head_sha != ? ORDER BY updated_at DESC, -e82345a88eca SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +e88287c17ca3 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this e8aec6fb1cfa SELECT if(format != ?, toString(format), if(JSONExtractString(metadata, ?) != ?, JSONExtractString(metadata, ?), if(blob_content_type != ?, toString(blob_content_type), if(lower(extract(if(original_fi e8dbbea8dde5 SELECT org, code_namespace, path, qualified_name, namespace, memory_id FROM loom.memory_code_links ORDER BY org, code_namespace, path, qualified_name, namespace, memory_id LIMIT {lim:UInt32} e8ee753a0792 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, e926f4d894f5 SELECT toUInt64(count()) AS n, sumForEach( arrayMap(t -> toUInt64(position(concat(?, lexemes, ?), concat(?, t, ?)) > ?), {tokens:Array(String)}) ) AS dfs FROM loom.code_pr_history FINAL WHERE org = {o -e95e0aaed16c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g e9b0e6383969 ALTER TABLE loom.knowledge_source_listings DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_ e9bc797f59c7 SELECT org, namespace, agent, user_id, session_id, memory_key, argMax(status, version) AS status, argMax(duplicate_of, version) AS duplicate_of, argMax(tombstoned_at IS NULL, version) AS live, argMax( e9dddc21ebf5 SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -2197,6 +2206,7 @@ eb430aeb667b SELECT org, namespace, agent, user_id, thread_id, msg_id, role, con eb49c309cbd8 SELECT org, namespace, agent, user_id, thread_id, title, metadata, run_id, created_at, updated_at, tombstoned_at FROM loom.conversation_threads FINAL WHERE org = {org:String} AND user_id = {scope:Stri eb6d8b657224 ALTER TABLE loom.entity_degree DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? ebda0f2e731d SELECT number, title FROM loom.code_gh_items FINAL WHERE org = {org:String} AND namespace = {ns:String} AND number IN {nums:Array(UInt32)} AND tombstoned_at IS NULL +ebf7c54189b7 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ebf804c151c9 SELECT * FROM loom.scim_users FINAL WHERE deleted = ? AND has(work_addresses, {a:String}) ORDER BY user_name LIMIT {count:UInt32} OFFSET {skip:UInt32} ebfbbf224b6e SELECT agent, user_id, session_id, memory_key, version_now, tombstoned_now, version_at FROM ( SELECT agent, user_id, session_id, memory_key, version AS version_now, toUInt8(tombstoned_at IS NOT NULL) ec411682b641 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user @@ -2209,12 +2219,12 @@ ed3dcc0014f8 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index) ed4fa5b45c9d WITH (SELECT (toFloat64(count()), sumMap(arrayFilter(s -> has({stems:Array(String)}, s), arrayDistinct(arrayMap( t -> stem(t, ?), splitByChar(?, translate(lower(memory_key), ?, ?))))) AS ks, arrayResi ed5e89f5c5cf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist ed7542958aa8 SELECT count() AS n FROM loom.entity_edge_memories WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +ed7a87402544 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ed95fca11907 SELECT subject, relation, object, sum(co_occur) AS co_occur, max(last_seen) AS last_seen, -- The strongest tier behind the aggregated triple. -- Not `AS provenance`: with the provenance filter in WHER +ed9b8189958e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this eda44de2c24a SELECT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory AS m WHERE m.memory_type IN (?, ?, ?) GROUP BY org, namespace, agent, user_id, session_id, memory_key HAVING argMax(empty edbfaec0aa75 SELECT count() AS n FROM loom.search_trace_log WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? edcbb0de7f6b SELECT pr_number, title, merged_at FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at >= {since:DateTime} AND (hasAny(files, { -eddb21bfb8d6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g -ede6acdb02ce SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g ee0278bae64b SELECT name, kind, path FROM ( SELECT tier, qualified_name, symbol_id, name, kind, path, argMax(tombstoned_at IS NULL, version) AS is_live FROM loom.code_symbols WHERE org = {org:String} AND namespace ee252893a251 SELECT sum(upstream_cost_usd) AS spent, countDistinct(namespace) AS ns_count FROM (SELECT ts, org, namespace, agent, user_id, session_id, run_id, operation, request_id, trace_id, memory_key, impersona ee76dd7690f3 SELECT toUnixTimestamp(max(merged_at)) AS landed FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merge_commit_sha IN {shas:Array(Stri @@ -2223,6 +2233,7 @@ ee9d24ac863c SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(c ee9f6e3f6646 SELECT hit.? - ? AS qidx, m.memory_id, m.memory_key, m.value, m.pinned, m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, hit.? AS dist FROM loom.memory m FINAL JOIN loom.memory_embeddings e FIN eecd42f63a03 SELECT path, content_hash FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL eee2fae9882f SELECT org, namespace, agent, thread_id, msg_id, role, content, reasoning, user_id, run_id, metadata, tokens, ts FROM loom.conversations WHERE org = {org:String} AND namespace IN {nss:Array(String)} A +ef155fcabf1b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ef6ff1fccbfa SELECT count() AS n FROM loom.memory_evidence FINAL WHERE org = {org:String} AND user_id = {uid:String} ef8cb8bc2b6e SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ef96a51ef6af SELECT jti, issued_before, version FROM loom.revoked_tokens FINAL WHERE expires_at > now() UNION ALL SELECT id AS jti, NULL AS issued_before, toUInt64(?) AS version FROM loom.oauth_state FINAL WHERE r @@ -2240,11 +2251,9 @@ f08249ee1acf SELECT kind, name, status, description, cardinality, created_by, up f0c46bd2964b SELECT org, toString(memory_id) AS memory_id, namespace, agent, user_id, session_id, memory_key, version, content_sha256, tags FROM ( SELECT org, memory_id, namespace, agent, user_id, session_id, memo f0d1a655888a SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER f0e13f039554 ALTER TABLE loom.knowledge_source_listings DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -f0f965973223 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f106a32ca75c SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user f14fa202dddc SELECT count() AS n FROM loom.code_chunks WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? f1a48bd7f91b ALTER TABLE loom.datasets DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? -f1ad3ef2004c SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f1d3bac694f9 SELECT greatest(toUInt64(toUnixTimestamp64Nano(now64(?))), max(version) + ?) AS v FROM loom.service_accounts WHERE org = {k0:String} AND name = {k1:String} f1ec97a6faeb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist f1ed5a57d65b SELECT count() AS n FROM loom.dataset_rows WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -2253,6 +2262,7 @@ f20625bfa023 SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = { f240e2237c44 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND agent = {id:String}) GROUP BY f27f3153bdd4 ALTER TABLE loom.shared UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (arrayExists(x -> splitByChar(?, x)[?] = {uid:String}, promoted_from) OR hasAny(pr f29b14854479 SELECT count() AS n FROM loom.consolidation_runs WHERE org = {org:String} AND namespace = {ns:String} AND ? +f2a872c44d8e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f2b1aae097d8 SELECT count() AS n FROM loom.memory_webhook_outbox WHERE org = {org:String} AND user_id = {uid:String} f2c8777c135d SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU f2cc30719090 SELECT * FROM loom.scim_users FINAL WHERE deleted = ? AND has(addresses, {a:String}) ORDER BY user_name LIMIT {count:UInt32} OFFSET {skip:UInt32} @@ -2262,8 +2272,8 @@ f343363836cf SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = f348283abeae SELECT * EXCEPT (embedding) FROM loom.code_chunks FINAL WHERE (org, namespace, embedding_model, path, chunk_id) IN {keys:Array(Tuple(String, String, String, String, UUID))} AND embedding_dim = ? AND t f36a74131100 SELECT uniqExact(embedding_model, chunk_idx) AS chunk_count FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri = {uri:String} AND JSONExtractUInt(chunk_metadata, ?) = f38dc7d9c2fc SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER +f395f4ff7759 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f39c3befadc3 WITH (SELECT (toFloat64(count()), sumMap(arrayFilter(s -> has({stems:Array(String)}, s), arrayDistinct(arrayMap( t -> stem(t, ?), splitByChar(?, translate(lower(memory_key), ?, ?))))) AS ks, arrayResi -f3a3885da999 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f3bd7999e18e SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND session_id = {id:String} AND u f3c14bb38069 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} f3c37b490eb7 SELECT count() AS n FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -2273,6 +2283,7 @@ f418c75a4197 SELECT kind, number, text_sha256, embedding_model FROM loom.qa_item f4249afc51bd SELECT toString(memory_id) AS memory_id, org, namespace, agent, user_id, session_id, memory_key, version, redacted_at, toString(content_sha256) AS content_sha256, if(sensitivity = ?, [], entities) AS f426fd45f2ab SELECT subject FROM loom.audit_log WHERE org = ? AND namespace = ? AND event_type = {et:String} AND ts >= toDateTime64(now() - INTERVAL {s:UInt32} SECOND, ?, ?) f44dcb1cb8df ALTER TABLE loom.documents UPDATE superseded_at = {now:DateTime} WHERE (org = {org:String} AND namespace IN {ns:Array(String)} AND superseded_at IS NULL) AND ({erasure_mutation_tag:String} = {erasure_ +f45b170d4f58 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f4a4dc94c981 SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND namespace = {ns:String} f4a7b1b62a06 ALTER TABLE loom.conversation_threads DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync f4cf9d7c7d76 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR @@ -2280,11 +2291,12 @@ f4e0b9f1ec2c SELECT path, count() AS chunks, min(start_line) AS first_line, coun f4e0e618ad7d SELECT count() AS n FROM loom.memory_extraction_queue FINAL WHERE org = {org:String} AND namespace = {ns:String} AND status IN {waiting:Array(String)} AND agent = {agent:String} AND user_id = {uid:Str f4e148ccd272 SELECT memory_id, version, confidence, source_trace, pinned, created_at, updated_at, expires_at, tombstoned_at, redacted_at, redaction_reason, actor, source_class, agent, status, conflict_with, tags, f4f15984ba26 SELECT brief_key, revision, agent, user_id, session_id, head_sha, trigger, author, sections, rendered, events_total, source_chars, brief_chars, actor, updated_at, tombstoned_at, version FROM loom.sess +f4fbd5666c4e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f516a9cc81d3 SELECT * FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tombstoned_at IS NULL f51d6af32512 SELECT e.org AS org, e.namespace AS namespace, e.agent AS agent, e.user_id AS user_id, e.session_id AS session_id, e.memory_key AS memory_key FROM (SELECT org, namespace, agent, user_id, session_id, m f51e0ce42dcd SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, expires_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND (emp -f52e30d82733 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f5ddaf977ab5 SELECT state_key, state_value AS value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key IN {keys:Array(String)} +f5ffc57e48b2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f60a04215196 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user f617d9867707 SELECT count() AS n FROM loom.memory_code_links WHERE org = {org:String} AND namespace IN {ns:Array(String)} f62c0f3f47ea DELETE FROM loom.code_answers WHERE (org = {org:String} AND (namespace IN {ns:Array(String)} OR memory_namespace IN {ns:Array(String)})) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:Stri @@ -2311,12 +2323,12 @@ f7ba11c1dbcc SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org f7bfa7426c75 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} f7c04f2fe996 SELECT count() AS n FROM loom.document_blobs WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? f8081de4841b SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -f833c025305d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f83401bb2bae SELECT * FROM loom.service_accounts FINAL WHERE org = {org:String} AND name = {name:String} AND (created_by IN {subs:Array(String)} OR hasAny(lineage, {subs:Array(String)})) AND revoked_at IS NULL AND f83f4bc3fef2 SELECT org, namespace, agent, user_id, session_id, memory_key, actor, toString(memory_id) AS mid, value, tags, files, toString(content_sha256) AS sha, CAST(status AS String) AS status, tombstoned_at, f8544e732b91 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user f86ba4e3e00f SELECT conflict_threshold, duplicate_threshold, default_conflict_policy FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? f86df7b89de1 SELECT chunk_id, path, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} A +f912aea621b6 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this f9300e54119b SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} f94222b8e538 SELECT * FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? f9818bc5e82a SELECT count() AS n FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -2324,20 +2336,18 @@ f98a98f483aa SELECT cityHash64(namespace, subject, relation, object) AS h FROM l f98c1c151442 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist f9aff1abcf47 SELECT count() AS n FROM loom.memory_evidence FINAL WHERE org = {org:String} AND namespace = {ns:String} f9c70055e9f9 SELECT DISTINCT tier, qualified_name, symbol_id FROM loom.code_symbol_ids WHERE org = {org:String} AND namespace = {ns:String} AND symbol_id IN {ids:Array(String)} -f9dcf0e208ec SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f9e4163b2950 SELECT ts, event_type, org, namespace, actor, subject, request_id FROM loom.audit_log WHERE org = {org:String} AND position(subject, {needle:String}) > ? AND namespace NOT IN {shown_hidden:Array(Strin f9f4a4284762 ALTER TABLE loom.memory_chunks UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) fa179e95b5f8 SELECT mutation_id, is_done, parts_to_do, latest_fail_reason FROM system.mutations WHERE database = {db:String} AND table = {t:String} AND is_done = ? AND command LIKE {pat:String} ORDER BY create_tim fa2389f66698 SELECT org, namespace, scope_type, scope_path, version FROM loom.code_summaries WHERE (org, namespace) IN {repos:Array(Tuple(String, String))} AND embedding_model = {model:String} AND embedding_dim = -fa2feed872ed SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g fa42f3c303c9 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist faa46c762ea5 SELECT org, namespace, edges FROM ( SELECT g.org AS org, g.namespace AS namespace, g.edges AS edges FROM ( SELECT org, namespace, count() AS edges FROM loom.entity_edges GROUP BY org, namespace ) AS g fac0f07fb670 SELECT pr_number, title, merge_commit_sha, files, merged_at FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merge_commit_sha != ? AND fadae2c61913 DELETE FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:String} AND tombstoned_at IS NULL AND is_s faf71d48ebd2 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +fb4658b7ad8e SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this fb620293a3f5 SELECT version, pinned, lock_mode, lock_until, sensitivity, tags FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND user_id = {uid:String} AND agent = ? AND session_id = ? fb7fc150938f SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FROM ( SELECT namespace, thread_id, ts, msg_id, row_bytes, sum(row_bytes) OVER (ORDER BY namespace, thread_id, ts, msg_id ROWS BETWEEN -fb8a291d93a5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g fbbbcced58d9 SELECT path, splitByChar(?, arrayElement(splitByChar(?, path), ?))[?] AS stem FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND splitByChar( fbd02f260158 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE request_id = {rid:String} ORDER BY ts ASC LIMIT {limit:UInt32} fbd1ef24012c SELECT count() AS n FROM loom.tasks WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -2369,12 +2379,12 @@ fe404d0b76ee SELECT toString(record_id) AS rid, memory_key, toString(memory_id) fe4fdc7e30f7 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a fe7a96c7e2d2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ fe9b04fb1f69 SELECT count() AS n FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns:Array(String)} -fe9df4ed378d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g fec00ca7180d SELECT namespace, source_id, started_at, crawl_generation FROM loom.knowledge_source_listings FINAL WHERE org = {org:String} AND (namespace, source_id) IN {pairs:Array(Tuple(String, String))} LIMIT {l fed00127661d SELECT org, namespace, agent, user_id, thread_id, msg_id, role, content, reasoning, metadata, tokens, run_id, ts, is_saved, saved_at, tombstoned_at, length(content) + length(reasoning) + length(metada fef350e42e77 ALTER TABLE loom.learnings_queue DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? ff00b5b19dc0 SELECT count() AS n, max(tombstoned_at) AS gone FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:S ff0506048e83 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont +ff156a627ef2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this ff23e7932268 ALTER TABLE loom.working_memory DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? ff438b330e4f SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status != ? AND session_id = {sid:String} AND startsWith(memory_key, {p:St ffa5c94364aa SELECT DISTINCT namespace FROM ( SELECT namespace FROM loom.memory WHERE org = {org:String} AND (namespace, agent, user_id, session_id, memory_key) IN ( SELECT namespace, agent, user_id, session_id, m diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py new file mode 100644 index 00000000000..84d71664a61 --- /dev/null +++ b/tests/integration/test_read_receipts.py @@ -0,0 +1,638 @@ +"""Read receipts: a read's answer leaves a row naming the revision of each item it carried. + +A run that read one revision of a memory still names that revision after the next is +written, and a replaced document's earlier read names the revision it served. The hash +is the stored one from every op and from either table a row is read through, a governed +definition names the shared copy it served, two writers' rows under one key each keep +their own revision, a revision the read could not name safely reads as not recorded, no +row holds content or query text, namespace and user erasure remove the rows, and with +receipts off a read still answers. +""" + +from __future__ import annotations + +import asyncio +import os +import sys +import uuid +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +import httpx +import pytest +import pytest_asyncio + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "sdk" / "python")) + +from tests.integration._eventually import eventually, overrides_adopted # noqa: E402 +from tests.integration._resources import unique_org # noqa: E402 + +pytestmark = pytest.mark.asyncio + +ORG = unique_org("read-receipts") +FIRST = "the nightly backup of the orders cluster runs at 02:00 UTC" +SECOND = "the nightly backup of the orders cluster runs at 04:30 UTC" +QUERY = "when does the nightly backup of the orders cluster run" + +_COLUMNS = ( + "kind, namespace, item_key, version, content_sha256, doc_version, chunk_idx, operation," + " request_id, run_id, actor, token_id, agent, user_id, session_id" +) + + +def _ns(label: str) -> str: + return f"rr-{label}-{uuid.uuid4().hex[:6]}" + + +def _run_id(label: str) -> str: + return f"rr-{label}-{uuid.uuid4().hex[:8]}" + + +def _receipts(ch: Any, namespace: str, org: str = ORG, **equals: Any) -> list[dict[str, Any]]: + """The namespace's receipts, oldest first, narrowed by column equality.""" + where = "".join(f" AND {column} = {{{column}:String}}" for column in equals) + return list( + ch.query( + f"SELECT {_COLUMNS} FROM loom.read_receipts" + f" WHERE org = {{org:String}} AND namespace = {{ns:String}}{where}" + " ORDER BY ts, item_key, chunk_idx", + parameters={"org": org, "ns": namespace, **equals}, + ).named_results() + ) + + +async def _landed(ch: Any, namespace: str, org: str = ORG, **equals: Any) -> list[dict[str, Any]]: + """The receipts once at least one matches: a receipt is written after the answer.""" + + async def rows() -> list[dict[str, Any]]: + return _receipts(ch, namespace, org, **equals) + + return await eventually(rows, description=f"a receipt of {equals or namespace} lands") + + +async def _read( + caller: Any, op: str, run: str = "", *, request_id: str = "", **body: Any +) -> dict[str, Any]: + """One op as `caller` (the body may name another namespace or agent), in `run` when + it names one, under `request_id` when given.""" + payload = {"org": caller.org, "namespace": caller.namespace, "agent": caller.agent, **body} + headers = {"X-Loom-Run-Id": run} if run else None + result = await caller.transport.post_with_meta( + f"/v1/{op}", payload, extra_headers=headers, request_id=request_id or None + ) + return result.data + + +def _request_id(label: str) -> str: + return f"rr-{label}-{uuid.uuid4().hex[:12]}" + + +async def _stored( + ch: Any, namespace: str, key: str, agent: str = "w", table: str = "loom.memory" +) -> tuple[int, str]: + """The version and content hash of the live row under `key`, once ClickHouse holds + it. A shared copy stores no hash.""" + sha = "''" if table == "loom.shared" else "toString(content_sha256)" + whose = "" if table == "loom.shared" else " AND agent = {agent:String}" + + async def row() -> list[tuple[int, str]]: + return list( + ch.query( + f"SELECT version, {sha} FROM {table} FINAL" + " WHERE org = {org:String} AND namespace = {ns:String}" + f" AND memory_key = {{key:String}}{whose} AND tombstoned_at IS NULL", + parameters={"org": ORG, "ns": namespace, "key": key, "agent": agent}, + ).result_rows + ) + + [(version, sha256)] = await eventually(row, description=f"{table} holds {key}") + return int(version), str(sha256) + + +async def _stored_hash(ch: Any, namespace: str, key: str) -> str: + return (await _stored(ch, namespace, key))[1] + + +async def test_a_run_that_read_one_revision_still_names_it_after_the_next( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns, before, after = _ns("rev"), _run_id("before"), _run_id("after") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + first = await _read(a, "memory.get", before, memory_key="backup_window") + await a.memory.set("backup_window", SECOND, memory_type="semantic") + second = await _read(a, "memory.get", after, memory_key="backup_window") + assert second["version"] > first["version"] + assert second["content_sha256"] != first["content_sha256"] + + [later] = await _landed(ch_client, ns, run_id=after) + assert (later["version"], later["content_sha256"]) == ( + second["version"], + second["content_sha256"], + ) + # the earlier run's receipt is the revision it read, not the key's latest + [earlier] = await _landed(ch_client, ns, run_id=before) + assert (earlier["version"], earlier["content_sha256"]) == ( + first["version"], + first["content_sha256"], + ) + assert (earlier["kind"], earlier["item_key"], earlier["chunk_idx"]) == ( + "memory", + "backup_window", + -1, + ) + assert (earlier["operation"], earlier["agent"]) == ("memory.get", "w") + assert earlier["request_id"] + + +async def test_every_op_records_the_stored_hash_of_a_row( + control_plane_url: str, ch_client: Any +) -> None: + """A search hit and a key lookup of one revision carry one hash, the stored one. The + hash memory.get serves is of the decoded value, and differs for an object with a null + field: a receipt still records the stored hash.""" + from loom import Agent + + ns, run = _ns("hash"), _run_id("one") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + await a.memory.set("retention", {"days": 30, "legal_hold": None}, memory_type="semantic") + + async def found() -> bool: + hits = await _read(a, "memory.search", run, query=QUERY, top_k=5) + return any(h["memory_key"] == "backup_window" for h in hits["results"]) + + await eventually(found, description="the search returns the fact") + await _read(a, "memory.get", run, memory_key="backup_window") + await _read(a, "memory.get", run, memory_key="retention") + await _read(a, "memory.bulk_get", run, memory_keys=["retention"]) + + stored = await _stored_hash(ch_client, ns, "backup_window") + + async def both_ops() -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns, item_key="backup_window", run_id=run) + return rows if {"memory.search", "memory.get"} <= {r["operation"] for r in rows} else [] + + rows = await eventually(both_ops, description="the search's and the lookup's receipts land") + hashes = {r["operation"]: r["content_sha256"] for r in rows} + assert hashes["memory.search"] == hashes["memory.get"] == stored + + async def both_lookups() -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns, item_key="retention", run_id=run) + return rows if {"memory.get", "memory.bulk_get"} <= {r["operation"] for r in rows} else [] + + lookups = await eventually(both_lookups, description="both lookups' receipts land") + assert {r["content_sha256"] for r in lookups} == { + await _stored_hash(ch_client, ns, "retention") + } + assert len({r["version"] for r in lookups}) == 1 + + +async def test_a_row_read_through_both_tables_records_its_stored_hash( + control_plane_url: str, ch_client: Any +) -> None: + """A change of expiry moves the row and its search document to different versions of + one content. A context pack names its rows without a version and reads them through + either table, so the version its receipt holds is either table's or none: the hash + is the content's all the same.""" + from loom import Agent + + ns = _ns("touch") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + await _read(a, "memory.touch", memory_key="backup_window", ttl_seconds=86_400) + + async def packed() -> str: + rid = _request_id("pack") + out = await _read(a, "context.pack", request_id=rid, query=QUERY) + return rid if "02:00 UTC" in str(out) else "" + + rid = await eventually(packed, description="the pack prints the fact") + + stored = await _stored_hash(ch_client, ns, "backup_window") + [row] = await _landed(ch_client, ns, request_id=rid, item_key="backup_window") + assert row["content_sha256"] == stored + + +async def test_two_writers_rows_under_one_key_each_keep_their_own_revision( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("two") + async with ( + Agent(org=ORG, namespace=ns, agent="planner", base_url=control_plane_url) as planner, + Agent(org=ORG, namespace=ns, agent="builder", base_url=control_plane_url) as builder, + ): + await planner.memory.set("backup_window", FIRST, memory_type="semantic") + await builder.memory.set("backup_window", SECOND, memory_type="semantic") + + async def both() -> str: + rid = _request_id("two") + out = await _read(planner, "memory.search", request_id=rid, agent="*", query=QUERY) + hits = [h for h in out["results"] if h["memory_key"] == "backup_window"] + return rid if len(hits) == 2 else "" + + rid = await eventually(both, description="the search returns both writers' rows") + + rows = await _landed(ch_client, ns, request_id=rid, item_key="backup_window") + assert {(r["version"], r["content_sha256"]) for r in rows} == { + await _stored(ch_client, ns, "backup_window", "planner"), + await _stored(ch_client, ns, "backup_window", "builder"), + } + assert len(rows) == 2 + + +ARR = { + "term": "ARR", + "aliases": ["annual recurring revenue"], + "body": "Yearly subscription revenue.", +} +ARR_CORRECTED = {**ARR, "body": "Yearly subscription revenue, net of churn and discounts."} +ARR_KEY, ARR_QUERY = "definition/arr", "what is our ARR this year" + + +async def _promote(admin: Any, namespace: str, value: dict[str, Any]) -> None: + """Write `namespace`'s definition and promote the revision just written.""" + row = {"namespace": namespace, "agent": "-", "memory_key": ARR_KEY} + await _read(admin, "memory.set", **row, value=value, memory_type="definition") + got = await _read(admin, "memory.get", **row) + await _read(admin, "memory.promote", **row, approved_sha256=got["content_sha256"]) + + +async def test_a_governed_definition_names_the_shared_copy_it_served( + control_plane_url: str, ch_client: Any, admin: Any +) -> None: + """A query that names a governed term is served the namespace's shared copy. Its + receipt names that copy before and after a correction, and never the reader's own + row under the same key, which the answer does not carry.""" + from loom import Agent + + ns = _ns("term") + + async def governed_read(bot: Any, body: str) -> str: + """A search by `bot` that was served the definition with `body`: its request id.""" + + async def served() -> str: + rid = _request_id("term") + out = await _read(bot, "memory.search", request_id=rid, query=ARR_QUERY, top_k=5) + texts = [str(h["content_excerpt"]) for h in out["results"] if h.get("governed")] + return rid if any(body in text for text in texts) else "" + + return await eventually(served, description=f"the search serves {body!r}") + + async with Agent(org=ORG, namespace=ns, agent="bot", base_url=control_plane_url) as bot: + await bot.memory.set(ARR_KEY, "my own note: ARR is what a pirate says") + await _promote(admin, ns, ARR) + before = await governed_read(bot, ARR["body"]) + first = await _stored(ch_client, ns, ARR_KEY, table="loom.shared") + first_hash = (await _stored(ch_client, ns, ARR_KEY, "-"))[1] + + await _promote(admin, ns, ARR_CORRECTED) + after = await governed_read(bot, "net of churn") + second = await _stored(ch_client, ns, ARR_KEY, table="loom.shared") + second_hash = (await _stored(ch_client, ns, ARR_KEY, "-"))[1] + + own = await _stored(ch_client, ns, ARR_KEY, "bot") + assert second[0] > first[0] and len({first_hash, second_hash, own[1]}) == 3 + [earlier] = await _landed(ch_client, ns, request_id=before, item_key=ARR_KEY) + [later] = await _landed(ch_client, ns, request_id=after, item_key=ARR_KEY) + assert (earlier["version"], earlier["content_sha256"]) == (first[0], first_hash) + assert (later["version"], later["content_sha256"]) == (second[0], second_hash) + + +async def test_a_receipt_names_the_run_its_requests_exposure_row_names( + control_plane_url: str, ch_client: Any +) -> None: + """A read that names a run in its body is filed under that run, and one that names + none under the run bound to the request: the exposure ledger's rule, so a receipt + and the exposure row of one request join on the run.""" + from loom import Agent + + ns, bound, named = _ns("run"), _run_id("bound"), _run_id("named") + by_body, by_header = _request_id("body"), _request_id("header") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await _read( + a, + "memory.set", + memory_key="backup_window", + value=FIRST, + memory_type="semantic", + run_id=named, + ) + + async def found() -> bool: + hits = await _read(a, "memory.search", query=QUERY, top_k=5) + return bool(hits["results"]) + + await eventually(found, description="the search returns the fact") + await _read(a, "memory.search", bound, request_id=by_body, query=QUERY, run_id=named) + await _read(a, "memory.search", bound, request_id=by_header, query=QUERY) + + def exposure_run(request_id: str) -> Any: + async def run() -> list[str]: + return [ + str(r[0]) + for r in ch_client.query( + "SELECT run_id FROM loom.memory_exposures WHERE org = {org:String}" + " AND namespace = {ns:String} AND request_id = {rid:String}", + parameters={"org": ORG, "ns": ns, "rid": request_id}, + ).result_rows + ] + + return run + + for request_id, run in ((by_body, named), (by_header, bound)): + [row] = await _landed(ch_client, ns, request_id=request_id) + assert row["run_id"] == run + exposed = await eventually(exposure_run(request_id), description="the exposure row lands") + assert exposed == [run] + + +async def test_a_document_read_names_the_agent_user_and_session_that_read( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("who") + uri = f"doc://runbooks/backup-{uuid.uuid4().hex[:6]}" + user, session = f"carol-{uuid.uuid4().hex[:6]}", f"sess-{uuid.uuid4().hex[:6]}" + async with Agent(org=ORG, namespace=ns, agent="planner", base_url=control_plane_url) as a: + await a.knowledge.add(FIRST, source_uri=uri, tags=["runbook"]) + got = await _read(a, "knowledge.get", source_uri=uri, user_id=user, session_id=session) + [row] = await _landed(ch_client, ns, item_key=uri) + assert (row["kind"], row["version"]) == ("document", got["revision"]) + assert (row["agent"], row["user_id"], row["session_id"]) == ("planner", user, session) + + +async def test_a_hash_that_would_name_a_secret_reads_as_not_recorded( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("high") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await _read( + a, + "memory.set", + memory_key="door_code", + value="4417", + memory_type="semantic", + sensitivity="high", + ) + got = await _read(a, "memory.get", memory_key="door_code") + assert got["found"] is True + [row] = await _landed(ch_client, ns, item_key="door_code") + # the version is recorded; the hash of a short secret would name it + assert (row["version"], row["content_sha256"]) == (got["version"], "") + + +async def test_a_replaced_documents_earlier_read_names_the_revision_it_served( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns, before, after = _ns("doc"), _run_id("before"), _run_id("after") + uri = f"doc://runbooks/backup-{uuid.uuid4().hex[:6]}" + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.knowledge.add(FIRST, source_uri=uri, tags=["runbook"]) + + async def searched() -> dict[str, Any]: + out = await _read(a, "knowledge.search", before, query=QUERY, namespace_scope="this") + return out if any(h["source_uri"] == uri for h in out["results"]) else {} + + hits = await eventually(searched, description="the search returns the document") + [hit] = [h for h in hits["results"] if h["source_uri"] == uri] + first = await _read(a, "knowledge.get", before, source_uri=uri) + + await a.knowledge.add(SECOND, source_uri=uri, tags=["runbook"]) + + async def replaced() -> dict[str, Any]: + got = await _read(a, "knowledge.get", after, source_uri=uri) + return got if got["revision"] != first["revision"] else {} + + second = await eventually(replaced, description="the replacement is served") + assert second["revision"] > first["revision"] == hit["revision"] + + async def served_before() -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns, run_id=before) + ops = {r["operation"] for r in rows} + return rows if {"knowledge.search", "knowledge.get"} <= ops else [] + + earlier = await eventually(served_before, description="the first run's receipts land") + assert {(r["kind"], r["item_key"], r["version"]) for r in earlier} == { + ("document", uri, first["revision"]) + } + # a document receipt has no hash; its chunk is the one the hit named, -1 for the whole + assert {r["content_sha256"] for r in earlier} == {""} + by_op = {r["operation"]: r for r in earlier} + assert by_op["knowledge.search"]["chunk_idx"] == hit["chunk_idx"] + assert by_op["knowledge.get"]["chunk_idx"] == -1 + assert all(r["doc_version"] > 0 for r in earlier) + + later = await _landed(ch_client, ns, run_id=after) + assert {r["version"] for r in later} >= {second["revision"]} + # the stored versions tell the two revisions apart too + assert {r["doc_version"] for r in later}.isdisjoint({r["doc_version"] for r in earlier}) + + +async def test_no_receipt_holds_content_or_query_text( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("text") + uri = f"doc://runbooks/backup-{uuid.uuid4().hex[:6]}" + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + await a.knowledge.add(SECOND, source_uri=uri, tags=["runbook"]) + + async def read_all() -> bool: + hits = await _read(a, "memory.search", query=QUERY, top_k=5) + docs = await _read(a, "knowledge.search", query=QUERY, namespace_scope="this") + return bool(hits["results"]) and bool(docs["results"]) + + await eventually(read_all, description="both searches return something") + await _read(a, "memory.get", memory_key="backup_window") + await _read(a, "context.pack", query=QUERY) + + async def both_kinds() -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns) + return rows if {"memory", "document"} <= {r["kind"] for r in rows} else [] + + rows = await eventually(both_kinds, description="memory and document receipts land") + text = " ".join(str(value) for row in rows for value in row.values()) + for private in ("02:00", "04:30", "nightly backup", "orders cluster", "when does"): + assert private not in text, private + + +@pytest.fixture +async def admin(control_plane_url: str, mint_test_token: Any) -> Any: + """The org's admin, who runs erasures (a saga's synchronous mutations outlast the + SDK's default timeout).""" + from loom import Agent + + token = mint_test_token(org=ORG, namespaces=["*"], roles=["org_admin", "admin", "writer"]) + async with Agent( + org=ORG, + namespace=_ns("adm"), + agent="platform-admin", + base_url=control_plane_url, + timeout_s=60.0, + api_key=token, + ) as a: + yield a + + +@pytest.mark.slow +async def test_a_namespace_erasure_removes_the_namespaces_receipts( + control_plane_url: str, ch_client: Any, admin: Any +) -> None: + from loom import Agent + + erased, kept = _ns("gone"), _ns("kept") + for ns in (erased, kept): + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + await a.knowledge.add(SECOND, source_uri=f"doc://{ns}", tags=["runbook"]) + await _read(a, "memory.get", memory_key="backup_window") + await _read(a, "knowledge.get", source_uri=f"doc://{ns}") + + for ns in (erased, kept): + + async def both_kinds(ns: str = ns) -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns) + return rows if {"memory", "document"} <= {r["kind"] for r in rows} else [] + + await eventually(both_kinds, description=f"{ns}'s receipts land") + + result = await admin.erasure.request_namespace(erased, requester="ops@example.com") + assert result["status"] == "completed" + steps = {s["step"]: s for s in result["steps"]} + assert steps["read_receipts.delete"]["rows_affected"] >= 2 + assert _receipts(ch_client, erased) == [] + assert {r["kind"] for r in _receipts(ch_client, kept)} == {"memory", "document"} + + +@pytest.mark.slow +async def test_a_user_erasure_removes_the_reads_the_user_made( + control_plane_url: str, ch_client: Any, admin: Any +) -> None: + from loom import Agent + + ns = _ns("user") + uri = f"doc://runbooks/backup-{uuid.uuid4().hex[:6]}" + erased, kept = f"alice-{uuid.uuid4().hex[:6]}", f"bob-{uuid.uuid4().hex[:6]}" + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.knowledge.add(SECOND, source_uri=uri, tags=["runbook"]) + for user in (erased, kept): + await a.memory.set(f"editor_{user}", f"{user} edits in a terminal", user_id=user) + got = await _read(a, "memory.get", memory_key=f"editor_{user}", user_id=user) + assert got["found"] is True + # a document's input names no user: the receipt takes the request's + await _read(a, "knowledge.get", source_uri=uri, user_id=user) + + for user in (erased, kept): + + async def both_kinds(user: str = user) -> list[dict[str, Any]]: + rows = _receipts(ch_client, ns, user_id=user) + return rows if {"memory", "document"} <= {r["kind"] for r in rows} else [] + + await eventually(both_kinds, description=f"{user}'s receipts land") + + result = await admin.erasure.request_user_id(erased, requester="ops@example.com") + assert result["status"] == "completed" + steps = {s["step"]: s for s in result["steps"]} + assert steps["read_receipts.delete"]["rows_affected"] >= 2 + assert _receipts(ch_client, ns, user_id=erased) == [] + assert sorted(r["item_key"] for r in _receipts(ch_client, ns, user_id=kept)) == sorted( + [f"editor_{kept}", uri] + ) + + +@pytest.mark.slow +async def test_a_user_who_keeps_reading_is_still_erased( + control_plane_url: str, ch_client: Any, admin: Any +) -> None: + """Each read the user makes while the saga runs writes a receipt behind its step. The + census counts the reads from before the erasure was recorded, so the erasure completes + and the later receipts stay.""" + from loom import Agent + + ns = _ns("busy") + uri = f"doc://runbooks/backup-{uuid.uuid4().hex[:6]}" + user = f"carol-{uuid.uuid4().hex[:6]}" + before, after = _request_id("before"), _request_id("after") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.knowledge.add(SECOND, source_uri=uri, tags=["runbook"]) + await _read(a, "knowledge.get", request_id=before, source_uri=uri, user_id=user) + await _landed(ch_client, ns, request_id=before) + erased = asyncio.Event() + + async def keep_reading() -> int: + reads = 0 + while not erased.is_set(): + await _read(a, "knowledge.get", source_uri=uri, user_id=user) + reads += 1 + await asyncio.sleep(0.05) + return reads + + reader = asyncio.create_task(keep_reading()) + try: + result = await admin.erasure.request_user_id(user, requester="ops@example.com") + finally: + erased.set() + reads = await reader + await _read(a, "knowledge.get", request_id=after, source_uri=uri, user_id=user) + + assert reads > 0 + assert (result["status"], result["residue_count"]) == ("completed", 0) + steps = {s["step"]: s for s in result["steps"]} + assert steps["read_receipts.delete"]["rows_affected"] >= 1 + # the read made before the erasure is gone; one made after it is the user's new activity + [kept] = await _landed(ch_client, ns, request_id=after) + assert kept["user_id"] == user + assert _receipts(ch_client, ns, request_id=before) == [] + + +@pytest_asyncio.fixture +async def receipts_switch(control_plane_url: str) -> AsyncIterator[httpx.AsyncClient]: + """An admin client for the live setting; the override is cleared afterwards.""" + token = os.environ.get("LOOM_API_KEY") + headers = {"Authorization": f"Bearer {token}"} if token else {} + async with httpx.AsyncClient(base_url=control_plane_url, timeout=10.0, headers=headers) as c: + try: + yield c + finally: + clear = {"name": "read_receipts_enabled", "clear": True} + await c.post("/v1/admin/settings.set", json=clear) + + +async def test_with_receipts_off_a_read_still_answers_and_writes_none( + control_plane_url: str, ch_client: Any, receipts_switch: httpx.AsyncClient +) -> None: + from loom import Agent + + ns = _ns("off") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("while_off", FIRST, memory_type="semantic") + await a.memory.set("while_on", SECOND, memory_type="semantic") + + off = {"name": "read_receipts_enabled", "value": False} + assert (await receipts_switch.post("/v1/admin/settings.set", json=off)).status_code == 200 + await overrides_adopted() + got = await _read(a, "memory.get", memory_key="while_off") + assert got["found"] is True and got["value"] == FIRST + + on = {"name": "read_receipts_enabled", "clear": True} + assert (await receipts_switch.post("/v1/admin/settings.set", json=on)).status_code == 200 + await overrides_adopted() + await _read(a, "memory.get", memory_key="while_on") + + # the later read's receipt has landed, so the earlier one would have by now + await _landed(ch_client, ns, item_key="while_on") + assert _receipts(ch_client, ns, item_key="while_off") == [] diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 10408318e3a..d881a080356 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -380,6 +380,9 @@ server/memory/app/promote.py::handle_memory_promote::1 server/memory/app/proposals.py::_surface_conflicts::1 write server/memory/app/proposals.py::policy_for::1 settings server/memory/app/query.py::_record_read_exposure::1 telemetry +server/memory/app/read_receipts.py::_never_fails.safe::1 telemetry +server/memory/app/read_receipts.py::_record::1 telemetry +server/memory/app/read_receipts.py::_send_queued::1 telemetry server/memory/app/recall_credit.py::consumer_closed_loop::1 telemetry server/memory/app/reextract.py::replay.one::1 logged_only_nonanswer server/memory/app/rerank.py::_host_of::1 telemetry diff --git a/tests/unit/snapshots/live_settings.json b/tests/unit/snapshots/live_settings.json index 1911ac0c794..0093a50bed6 100644 --- a/tests/unit/snapshots/live_settings.json +++ b/tests/unit/snapshots/live_settings.json @@ -364,6 +364,7 @@ "pg_payload_restore_horizon_minutes", "pg_publish_interval_ms", "provider_check_timeout_s", + "read_receipts_enabled", "readiness_check_timeout_s", "schema_status_ttl_s", "search_trace_log_enabled", diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 6a9bed59121..3584d7bf411 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -1153,6 +1153,7 @@ "ratelimit_shared": "auto", "ratelimit_shared_path": "", "ratelimit_shared_slots": 16384, + "read_receipts_enabled": true, "readiness_check_timeout_s": 2.0, "reads_llm_free": false, "ready_requires_mirrors": false, diff --git a/tests/unit/test_cell_scan_tables.py b/tests/unit/test_cell_scan_tables.py index 0305405d415..e4cb5cee0e7 100644 --- a/tests/unit/test_cell_scan_tables.py +++ b/tests/unit/test_cell_scan_tables.py @@ -160,6 +160,7 @@ "loom.qa_test_daily", "loom.query_nodes", "loom.query_history_sources", + "loom.read_receipts", "loom.search_misses", "loom.search_trace_log", "loom.service_accounts", diff --git a/tests/unit/test_erasure_late_steps.py b/tests/unit/test_erasure_late_steps.py index 07da0cdecf2..8cd40d1ec6b 100644 --- a/tests/unit/test_erasure_late_steps.py +++ b/tests/unit/test_erasure_late_steps.py @@ -7,6 +7,7 @@ from __future__ import annotations import asyncio +from datetime import UTC, datetime from typing import Any import pytest @@ -14,6 +15,7 @@ from server.erasure.app import saga_steps from server.erasure.store import census as erasure_census from server.erasure.store import mutations as erasure_mutations +from server.erasure.store import predicates from server.erasure.store import steps_ledgers as ledger_steps from tests.unit.definition_queue_fake import install @@ -167,6 +169,72 @@ def test_user_scope_delete_steps_skip_the_tables_without_a_user_axis() -> None: assert len(ch.commands) == 1 and "user_id = {uid:String}" in ch.commands[0][0] +def test_a_users_read_receipts_are_the_reads_they_made_under_any_spelling() -> None: + """As the end user the read ran as, or as the token's subject. The step deletes every + one it finds; the census counts the same readers.""" + ch = _StubCH(count=2) + spellings = ["alice", "alice@example.com"] + n = asyncio.run(ledger_steps.delete_read_receipts_by_user("o", spellings, ch=ch)) + assert n == 2 + [(sql, params)] = ch.commands + assert sql.lstrip().startswith("DELETE FROM loom.read_receipts") + assert predicates.RECEIPT_READER in sql and "recorded_at" not in sql + assert "lowerUTF8(user_id)" in sql and "lowerUTF8(actor)" in sql + assert (params["org"], params["spellings"]) == ("o", spellings) + [row] = [s for s in erasure_census._CENSUS if s.table == "loom.read_receipts"] + assert row.user_pred == predicates.RECEIPT_READER_BEFORE + assert predicates.RECEIPT_READER in predicates.RECEIPT_READER_BEFORE + assert (row.ns_step, row.user_step) == ("read_receipts.delete", "read_receipts.delete") + + +def test_a_users_census_counts_the_receipts_from_before_the_erasure_was_recorded( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A user who asked to be erased keeps reading, and each read writes a receipt: the + census stops at the second the erasure was recorded in, so those are not residue.""" + + async def no_copies(*args: Any, **kwargs: Any) -> dict[str, int]: + return {} + + monkeypatch.setattr(erasure_census, "copy_residue", no_copies) + recorded = datetime(2026, 3, 4, 5, 6, 7, 890000, tzinfo=UTC) + + def receipts_count() -> tuple[str, dict[str, Any]]: + ch = _StubCH(count=0) + asyncio.run( + erasure_census.table_residue("o", "user_id", "alice", ch=ch, spellings=["alice"]) + ) + [(sql, params)] = [c for c in ch.counts if "loom.read_receipts" in c[0]] + return sql, params + + with erasure_mutations.recorded_scope(recorded): + sql, params = receipts_count() + assert "ts < {recorded_at:DateTime}" in sql and predicates.RECEIPT_READER in sql + # Naive UTC to the second, as the column holds `ts`. + assert params["recorded_at"] == datetime(2026, 3, 4, 5, 6, 7) + # Outside an erasure the count runs up to now. + monkeypatch.setattr(erasure_mutations, "_now_naive", lambda: datetime(2026, 3, 9, 1, 2, 3, 9)) + assert receipts_count()[1]["recorded_at"] == datetime(2026, 3, 9, 1, 2, 3) + # A namespace's census counts every receipt under it, whenever it was written. + ch = _StubCH(count=0) + asyncio.run(erasure_census.table_residue("o", "namespace", "n", ch=ch)) + [(sql, params)] = [c for c in ch.counts if "loom.read_receipts" in c[0]] + assert "recorded_at" not in sql and "recorded_at" not in params + + +def test_a_namespaces_read_receipts_leave_by_a_lightweight_delete_in_every_mode() -> None: + """A namespace's receipts sit in every monthly part, so a mutation would rewrite the + whole table: the step masks the rows instead, with or without a purge.""" + ch = _StubCH(count=3) + assert asyncio.run(ledger_steps.delete_read_receipts_by_namespace("o", ["a", "b"], ch=ch)) == 3 + [(sql, params)] = ch.commands + assert sql.lstrip().startswith("DELETE FROM loom.read_receipts") + assert "(org = {org:String} AND namespace IN {ns:Array(String)})" in sql + assert (params["org"], params["ns"]) == ("o", ["a", "b"]) + assert all(" FINAL" not in count for count, _ in ch.counts) # a plain MergeTree + assert "loom.read_receipts" in erasure_mutations.LIGHTWEIGHT_PURGE_TABLES + + def test_a_purge_turns_the_conversation_tombstones_into_deletes() -> None: ch = _StubCH() with erasure_mutations.purge_scope(True): diff --git a/tests/unit/test_erasure_step_order.py b/tests/unit/test_erasure_step_order.py index 5180399dadd..fc74824d93f 100644 --- a/tests/unit/test_erasure_step_order.py +++ b/tests/unit/test_erasure_step_order.py @@ -168,6 +168,7 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("context_blobs.tombstone", ((U, "loom.context_blobs"),)), ("session_briefs.delete", ((D, "loom.session_briefs"), (D, "loom.session_brief_revisions"))), ("memory_exposures.delete", ((D, "loom.memory_exposures"),)), + ("read_receipts.delete", ((L, "loom.read_receipts"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"),)), ("search_misses.delete", ((D, "loom.knowledge_gaps"), (D, "loom.search_misses"))), ("events.delete", ((D, "loom.events"),)), @@ -265,6 +266,7 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("context_blobs.tombstone", ((U, "loom.context_blobs"),)), ("session_briefs.delete", ((D, "loom.session_briefs"), (D, "loom.session_brief_revisions"))), ("memory_exposures.delete", ((D, "loom.memory_exposures"),)), + ("read_receipts.delete", ((L, "loom.read_receipts"),)), _usage_events("memory_usage_events.delete", (D, "loom.memory_usage_events")), ("search_trace_log.delete", ((D, "loom.search_trace_log"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"), (D, "loom.code_search_outcome"))), @@ -391,6 +393,7 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("context_blobs.tombstone", ((D, "loom.context_blobs"),)), ("session_briefs.delete", ((D, "loom.session_briefs"), (D, "loom.session_brief_revisions"))), ("memory_exposures.delete", ((D, "loom.memory_exposures"),)), + ("read_receipts.delete", ((L, "loom.read_receipts"),)), _usage_events("memory_usage_events.delete", (D, "loom.memory_usage_events")), ("search_trace_log.delete", ((D, "loom.search_trace_log"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"), (D, "loom.code_search_outcome"))), @@ -588,6 +591,7 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ), ), ("memory_exposures.delete", ((D, "loom.memory_exposures"),)), + ("read_receipts.delete", ((L, "loom.read_receipts"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"),)), ("search_misses.delete", ((D, "loom.knowledge_gaps"), (D, "loom.search_misses"))), ("events.delete", ((D, "loom.events"),)), diff --git a/tests/unit/test_erasure_verify.py b/tests/unit/test_erasure_verify.py index 08a56b2e564..bfc6f6129e7 100644 --- a/tests/unit/test_erasure_verify.py +++ b/tests/unit/test_erasure_verify.py @@ -137,7 +137,7 @@ def test_census_covers_every_substrate_and_uses_final_on_soft_deleted_tables() - out = asyncio.run(erasure_census.residue_census("o", "namespace", "ns", ch=ch)) assert set(out) == set(erasure_census.census_tables("namespace")) # every namespace-scoped substrate, entity, cache, chunk-link and code table - assert len(out) == 75 and sum(out.values()) == 0 + assert len(out) == 76 and sum(out.values()) == 0 by_table = {sql.split("FROM ")[1].split()[0]: sql for sql, _ in ch.query_one_calls} assert ( " FINAL" in by_table["loom.memory"] and "tombstoned_at IS NULL" in by_table["loom.memory"] @@ -218,7 +218,7 @@ def test_census_user_scope_skips_namespace_only_tables() -> None: "loom.task_events", } <= set(out) assert "loom.memory_answers" not in out - assert len(out) == 56 + assert len(out) == 57 assert "loom.blob_uploads" in out # who uploaded what: the user's go # the user's supporter rows, and any bot-rule candidate left with no supporter assert {"loom.learnings_queue", "loom.learnings_supporters"} <= set(out) diff --git a/tests/unit/test_knowledge_mirrors.py b/tests/unit/test_knowledge_mirrors.py index 4e207fe6c8a..10ea9defd37 100644 --- a/tests/unit/test_knowledge_mirrors.py +++ b/tests/unit/test_knowledge_mirrors.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +from datetime import datetime from pathlib import Path from typing import Any @@ -325,6 +326,7 @@ def test_erasure_re_verify_reports_what_a_mirror_still_holds( row = { "id": "e1", "org": ORG, "scope_type": "namespace", "scope_value": "team", "purge": False, "attempts": 1, "steps_completed": [], "failure_reason": "x", + "requested_at": datetime(2026, 3, 4, 5, 6, 7), } # fmt: skip async def _failed(**_: Any) -> list[dict[str, Any]]: diff --git a/tests/unit/test_pg_durable_reads.py b/tests/unit/test_pg_durable_reads.py index 2a7c7a6c705..24b03462ecc 100644 --- a/tests/unit/test_pg_durable_reads.py +++ b/tests/unit/test_pg_durable_reads.py @@ -108,7 +108,8 @@ "server/memory/store/lifecycle.py": "decides a delete, which commits", "server/memory/store/pg_batch.py": "a newer head copy is read again durably", "server/memory/store/pg_publish.py": "live decision writers are read durably", - "server/memory/store/reads.py": "point reads to the caller; send nothing", + "server/memory/store/reads.py": "point reads to the caller; a read receipt sends the " + "served version and hash, never content, and may name a revision a failover loses", "server/memory/store/records.py": "a retirement reads its writers durably; " "`live_writer_record` filters a request's read, which commits through `memory.set`", "server/memory/store/redaction.py": "decides a redaction, which commits", diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py new file mode 100644 index 00000000000..438597c9f23 --- /dev/null +++ b/tests/unit/test_read_receipts.py @@ -0,0 +1,1224 @@ +"""Read receipts: which revision of an item an agent read's answer carried.""" + +from __future__ import annotations + +import asyncio +import re +from collections.abc import Callable, Iterator +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.core import instances, request_work +from server.core.diagnostics import private_work +from server.memory.app import after_write, served_reads +from server.memory.app import read_receipts as rr +from server.memory.app.log_once import LogOnce +from server.memory.domain.read_receipts import ( + DOCUMENT, + MEMORY, + NOT_RECORDED, + Item, + Noted, + Notes, + add_note, + every_noted, + receipts, + revision_of, +) +from server.memory.store import read_receipts as store +from server.settings import settings + +ROOT = Path(__file__).resolve().parents[2] +SHA = "a" * 64 +OTHER_SHA = "b" * 64 +MIRROR = "acl-" + "0" * 24 +STORE = "crs-" + "0" * 24 + +# Every op whose answer is receipted. +RECEIPTED = { + "memory.search", + "memory.ask", + "memory.brief", + "search.query", + "memory.get", + "memory.get_by_id", + "memory.bulk_get", + "context.pack", + "memory.stack", + "memory.for_file", + "procedure.match", + "knowledge.search", + "knowledge.get", +} + + +def _notes(*noted: tuple[str, str, str, Noted]) -> Notes: + notes: Notes = {} + for kind, namespace, key, revision in noted: + add_note(notes, kind, namespace, key, revision) + return notes + + +# ------------------------------------------------------------------- pairing rules + + +def test_an_item_with_a_version_records_that_version() -> None: + notes = _notes((MEMORY, "n", "k", Noted(3, SHA)), (MEMORY, "n", "k", Noted(5, OTHER_SHA))) + assert revision_of(Item(MEMORY, "n", "k", 5), notes) == Noted(5, OTHER_SHA) + # a version no read noted is still the answer's own: recorded without a hash, and + # never the nearest note's + assert revision_of(Item(MEMORY, "n", "k", 4), notes) == Noted(4) + assert revision_of(Item(MEMORY, "n", "other", 5), notes) == Noted(5) + assert revision_of(Item(MEMORY, "m", "k", 5), notes) == Noted(5) + + +def test_an_item_without_a_version_takes_what_the_notes_of_its_key_agree_on() -> None: + one = _notes((MEMORY, "n", "k", Noted(3, SHA)), (MEMORY, "n", "k", Noted(0))) + assert revision_of(Item(MEMORY, "n", "k"), one) == Noted(3, SHA) + # one row read through two tables: its search document is at another version + same = _notes((MEMORY, "n", "k", Noted(3, SHA)), (MEMORY, "n", "k", Noted(8, SHA))) + assert revision_of(Item(MEMORY, "n", "k"), same) == Noted(0, SHA) + # two writers' rows under one key: the answer does not say which one it printed + two = _notes((MEMORY, "n", "k", Noted(3, SHA)), (MEMORY, "n", "k", Noted(8, OTHER_SHA))) + assert revision_of(Item(MEMORY, "n", "k"), two) == NOT_RECORDED + # a hash one note lacks is not assumed equal + unknown = _notes((MEMORY, "n", "k", Noted(3, SHA)), (MEMORY, "n", "k", Noted(8))) + assert revision_of(Item(MEMORY, "n", "k"), unknown) == NOT_RECORDED + # the read held a passage of the row only + passage = _notes((MEMORY, "n", "k", Noted(0))) + assert revision_of(Item(MEMORY, "n", "k"), passage) == NOT_RECORDED + # no read of the op held a row of this key + assert revision_of(Item(MEMORY, "n", "other"), one) is None + + +def test_a_second_note_of_a_version_adds_what_the_first_lacked() -> None: + notes: Notes = {} + add_note(notes, MEMORY, "n", "k", Noted(3)) + add_note(notes, MEMORY, "n", "k", Noted(3, SHA)) + add_note(notes, MEMORY, "n", "k", Noted(3, OTHER_SHA)) # the first hash stays + assert notes == {(MEMORY, "n", "k"): {3: Noted(3, SHA)}} + + +def test_two_stored_versions_of_one_document_revision_are_not_recorded() -> None: + notes: Notes = {} + chunk = Item(DOCUMENT, "n", "doc", 2, 0) + add_note(notes, DOCUMENT, "n", "doc", Noted(2)) + add_note(notes, DOCUMENT, "n", "doc", Noted(2, "", 11)) + add_note(notes, DOCUMENT, "n", "doc", Noted(2, "", 11)) + assert revision_of(chunk, notes) == Noted(2, "", 11) + # a write that numbered the same revision again: which one a chunk came from is unknown + add_note(notes, DOCUMENT, "n", "doc", Noted(2, "", 12)) + add_note(notes, DOCUMENT, "n", "doc", Noted(2, "", 11)) # a later note settles nothing + assert revision_of(chunk, notes) == Noted(2) + assert every_noted(notes) == [(Item(DOCUMENT, "n", "doc", 2), Noted(2))] + + +def test_the_receipts_are_of_the_answers_items_not_of_every_note() -> None: + notes = _notes((MEMORY, "n", "kept", Noted(1, SHA)), (MEMORY, "n", "trimmed", Noted(2, SHA))) + kept, carried = Item(MEMORY, "n", "kept", 1), Item(MEMORY, "n", "carried", 4) + named = Item(MEMORY, "n", "named") # no version in the answer and no note: no receipt + assert receipts([kept, carried, named], notes) == [(kept, Noted(1, SHA)), (carried, Noted(4))] + + +def test_a_passage_of_a_row_is_left_out_beside_the_row() -> None: + notes = _notes((MEMORY, "n", "fact", Noted(6, SHA))) + passage, row = Item(MEMORY, "n", "fact", 0), Item(MEMORY, "n", "fact", 6) + assert receipts([passage, row], notes) == [(row, Noted(6, SHA))] + # alone, the passage is a receipt with no revision, whether its row was noted or not + assert receipts([passage], notes) == [(passage, NOT_RECORDED)] + assert receipts([passage], {}) == [(passage, NOT_RECORDED)] + + +def test_one_receipt_for_each_revision_and_chunk() -> None: + notes = _notes((MEMORY, "n", "k", Noted(1, SHA)), (DOCUMENT, "n", "doc", Noted(2, "", 9))) + row = Item(MEMORY, "n", "k", 1) + first, third = Item(DOCUMENT, "n", "doc", 2, 0), Item(DOCUMENT, "n", "doc", 2, 3) + assert receipts([row, row, first, third, third], notes) == [ + (row, Noted(1, SHA)), + (first, Noted(2, "", 9)), + (third, Noted(2, "", 9)), + ] + + +def test_a_key_lookups_answer_is_every_noted_revision() -> None: + notes = _notes( + (MEMORY, "n", "k", Noted(1, SHA)), + (MEMORY, "n", "k", Noted(4)), + (DOCUMENT, "m", "doc", Noted(2, "", 9)), + ) + assert every_noted(notes) == [ + (Item(MEMORY, "n", "k", 1), Noted(1, SHA)), + (Item(MEMORY, "n", "k", 4), Noted(4)), + (Item(DOCUMENT, "m", "doc", 2), Noted(2, "", 9)), + ] + + +# ------------------------------------------------------------------------ the row + + +def _table_columns() -> set[str]: + ddl = (ROOT / "schemas" / "migrations" / f"{store.MIGRATION}_read_receipts.sql").read_text() + return set(re.findall(r"^\s+`(\w+)` ", ddl, flags=re.M)) + + +def test_the_migration_constant_names_the_file_that_creates_the_table() -> None: + [path] = (ROOT / "schemas" / "migrations").glob("*_read_receipts.sql") + assert int(path.name.split("_")[0]) == store.MIGRATION + assert f"CREATE TABLE IF NOT EXISTS {store.TABLE}" in path.read_text() + + +def test_the_table_refuses_the_names_the_check_before_the_queue_leaves_out() -> None: + from server.core import naming + + ddl = (ROOT / "schemas" / "migrations" / f"{store.MIGRATION}_read_receipts.sql").read_text() + assert f"CHECK {naming.not_reserved_sql()}\n" in ddl + + +def test_a_row_holds_the_tables_columns_and_no_content() -> None: + reader = store.Reader(org="o", operation="memory.search", request_id="r", agent="codex") + memory, document = store.build_rows( + reader, + [ + (Item(MEMORY, "n", "k", 3), Noted(3, SHA)), + (Item(DOCUMENT, "m", "doc://a", 2, 5), Noted(2, "", 11)), + ], + ) + assert set(memory) == set(document) == _table_columns() + assert not {"value", "content", "content_excerpt", "query", "prompt"} & set(memory) + assert memory["ts"].microsecond == 0 and memory["ts"].tzinfo is None + assert {k: v for k, v in memory.items() if k != "ts"} == { + "org": "o", + "namespace": "n", + "kind": MEMORY, + "item_key": "k", + "version": 3, + "content_sha256": SHA, + "doc_version": 0, + "chunk_idx": -1, + "operation": "memory.search", + "request_id": "r", + "run_id": "-", + "actor": "", + "token_id": "", + "agent": "codex", + "user_id": "-", + "session_id": "-", + } + # a document is filed under the namespace that holds it, by revision and chunk + assert [document[c] for c in ("namespace", "item_key", "version", "doc_version")] == [ + "m", + "doc://a", + 2, + 11, + ] + assert (document["chunk_idx"], document["content_sha256"]) == (5, "") + + +def test_the_insert_is_a_background_async_insert() -> None: + calls: list[tuple[str, list[dict[str, Any]], dict[str, Any]]] = [] + + class _Ch: + async def insert(self, table: str, rows: list[dict[str, Any]], *, settings: Any) -> None: + calls.append((table, rows, settings)) + + rows = [{"org": "o"}] + asyncio.run(store.insert(rows, ch=_Ch())) + [(table, sent, sent_settings)] = calls + assert (table, sent) == ("loom.read_receipts", rows) + assert sent_settings["async_insert"] == 1 + assert sent_settings["async_insert_busy_timeout_max_ms"] == int( + settings.ch_batched_insert_background_wait_max_ms + ) + + +# ------------------------------------------------------------------- the wrapper + +_INPUT = SimpleNamespace(org="o", namespace="n", agent="codex") + + +@pytest.fixture +def written(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[list[dict[str, Any]]]]: + """Receipts on and every live replica able to erase them: the rows of each insert.""" + batches: list[list[dict[str, Any]]] = [] + + async def _insert(rows: list[dict[str, Any]], **_kw: Any) -> None: + batches.append(rows) + + monkeypatch.setattr(store, "insert", _insert) + monkeypatch.setattr(instances, "live_rows", lambda: [{"schema_version": store.MIGRATION}]) + monkeypatch.setattr(settings, "read_receipts_enabled", True) + monkeypatch.setattr(rr, "_GATE_LOGGED", LogOnce()) + monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0) # the sender sends at its next turn + rr._reset_for_tests() + yield batches + rr._reset_for_tests() + + +def _run(handler: Any, input: Any = _INPUT) -> Any: + async def _go() -> Any: + out = await handler(input) + await after_write.drain() + return out + + return asyncio.run(_go()) + + +def _op(note: Callable[[], None], out: Any = None, items_of: Any = None) -> Any: + """A receipted op whose handler makes `note`'s notes and answers `out`.""" + + async def handler(_input: Any) -> Any: + note() + return out + + return rr.records_receipts(items_of)(handler) + + +def _note_k() -> None: + rr.note_memory("n", "k", version=3, sha256=SHA) + + +def _receipt( + kind: str, + namespace: str, + key: str, + version: int, + sha256: str = "", + doc_version: int = 0, + chunk_idx: int = -1, +) -> tuple[Any, ...]: + return (kind, namespace, key, version, sha256, doc_version, chunk_idx) + + +def _receipts(written: list[list[dict[str, Any]]]) -> list[tuple[Any, ...]]: + return [ + _receipt( + r["kind"], + r["namespace"], + r["item_key"], + r["version"], + r["content_sha256"], + r["doc_version"], + r["chunk_idx"], + ) + for rows in written + for r in rows + ] + + +def test_an_op_writes_a_row_for_each_noted_item_of_its_answer( + written: list[list[dict[str, Any]]], +) -> None: + def note() -> None: + rr.note_memory("n", "kept", version=3, sha256=SHA) + rr.note_memory("n", "trimmed", version=9, sha256=OTHER_SHA) + + out = SimpleNamespace(rows=[("n", "kept"), ("n", "not_noted")]) + assert _run(_op(note, out, rr.memory_rows(lambda _i, o: o.rows))) is out + assert _receipts(written) == [_receipt(MEMORY, "n", "kept", 3, SHA)] + + +def test_a_key_lookup_writes_every_row_it_noted(written: list[list[dict[str, Any]]]) -> None: + def note() -> None: + rr.note_memory("n", "a", version=1, sha256=SHA) + rr.note_document("n", "doc://a", revision=2, doc_version=11) + + _run(_op(note)) + assert _receipts(written) == [ + _receipt(MEMORY, "n", "a", 1, SHA), + _receipt(DOCUMENT, "n", "doc://a", 2, "", 11), + ] + + +def test_the_reader_comes_from_the_request( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + from server.auth import context as auth_context + from server.core.logging_config import request_id_var + from server.identity.app import request_scope as scope_mod + from server.identity.domain.read_scope import ReadFilters + from server.observability import genai, run_context + + token = SimpleNamespace(subject="Alice@Example.com", token_id="tok-1") + monkeypatch.setattr(auth_context, "current_auth", lambda: token) + own = ReadFilters(scope="own_user", user_id="u1", session_id=None) + monkeypatch.setattr(scope_mod, "request_scope", lambda: own) + monkeypatch.setattr(genai, "current_operation", lambda: "memory.get") + # the body names a session and no user: the user is the token's read scope + input = SimpleNamespace(org="o", namespace="n", agent="codex", user_id="-", session_id="s9") + + async def _go() -> None: + request_id_var.set("req-1") + run_context.set_ledger_run("run-1") + await _op(_note_k)(input) + await after_write.drain() + + asyncio.run(_go()) + [[row]] = written + reader = ("operation", "request_id", "run_id", "actor", "token_id", "agent") + assert [row[c] for c in reader] == [ + "memory.get", + "req-1", + "run-1", + "Alice@Example.com", + "tok-1", + "codex", + ] + assert (row["org"], row["user_id"], row["session_id"]) == ("o", "u1", "s9") + + +def test_the_run_is_the_one_every_ledger_files_the_request_under( + written: list[list[dict[str, Any]]], +) -> None: + """The request's own `run_id` when it carries one, else the run bound to it: the rule + of the op ledger and the exposure ledger, so a receipt joins both on the run.""" + from server.observability import run_context + + def reads(run_id: str | None) -> SimpleNamespace: + return SimpleNamespace(org="o", namespace="n", agent="codex", run_id=run_id) + + async def _go(bound: str, input: Any) -> None: + run_context.set_ledger_run(bound) + await _op(_note_k)(input) + await after_write.drain() + assert written[-1][0]["run_id"] == (run_context.ledger_run_for(input.run_id) or "-") + + asyncio.run(_go("run-bound", reads("run-named"))) + asyncio.run(_go("run-bound", reads(None))) + asyncio.run(_go("", reads("run-named"))) + asyncio.run(_go("", reads(None))) + assert [rows[0]["run_id"] for rows in written] == ["run-named", "run-bound", "run-named", "-"] + + +def test_a_document_read_names_the_reader_the_request_named( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + from server.observability import genai + + named = {"agent": "planner", "user_id": "carol", "session_id": "s1"} + monkeypatch.setattr(genai, "request_identity", lambda: named) + input = SimpleNamespace(org="o", namespace="n") # a document op's input names no reader + _run(_op(lambda: rr.note_document("n", "doc://a", revision=1)), input) + [[row]] = written + assert (row["agent"], row["user_id"], row["session_id"]) == ("planner", "carol", "s1") + + +def test_a_read_that_names_no_user_is_not_filed_under_the_tokens_subject( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + """A transport traces an unnamed user as the token's subject; a receipt keeps the + subject in `actor` and the user unset, so reads made as an end user stay apart from + reads a token of that name made.""" + from server.auth import context as auth_context + from server.observability import genai + + token = SimpleNamespace(subject="svc-reader", token_id="tok-1") + monkeypatch.setattr(auth_context, "current_auth", lambda: token) + traced = {"agent": "planner", "user_id": "svc-reader"} + monkeypatch.setattr(genai, "request_identity", lambda: traced) + input = SimpleNamespace(org="o", namespace="n") + _run(_op(lambda: rr.note_document("n", "doc://a", revision=1)), input) + [[row]] = written + assert (row["actor"], row["user_id"], row["session_id"]) == ("svc-reader", "-", "-") + + +def test_an_op_run_inside_another_writes_nothing_itself( + written: list[list[dict[str, Any]]], +) -> None: + def note() -> None: + rr.note_memory("n", "a", version=1, sha256=SHA) + rr.note_memory("n", "b", version=2, sha256=SHA) + + inner = _op(note) + + async def outer_handler(input: Any) -> Any: + await inner(input) + return SimpleNamespace(rows=[("n", "a")]) + + outer = rr.records_receipts(rr.memory_rows(lambda _i, o: o.rows))(outer_handler) + _run(outer) + # one write, of the outer answer's items, with the revisions the inner read held + assert [_receipts([rows]) for rows in written] == [[_receipt(MEMORY, "n", "a", 1, SHA)]] + + +def test_a_note_made_after_the_answer_is_not_the_answers( + written: list[list[dict[str, Any]]], +) -> None: + late: list[asyncio.Task[None]] = [] + + async def _later() -> None: + await asyncio.sleep(0) + rr.note_memory("n", "late", version=2, sha256=SHA) + + async def handler(_input: Any) -> None: + _note_k() + late.append(asyncio.get_running_loop().create_task(_later())) + + op = rr.records_receipts()(handler) + + async def _go() -> None: + await op(_INPUT) + await asyncio.gather(*late) + await after_write.drain() + + asyncio.run(_go()) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +def test_a_task_the_handler_awaits_notes_into_its_answer( + written: list[list[dict[str, Any]]], +) -> None: + async def leg() -> None: + rr.note_memory("n", "leg", version=2, sha256=SHA) + + async def handler(_input: Any) -> None: + await asyncio.get_running_loop().create_task(leg()) + + _run(rr.records_receipts()(handler)) + assert _receipts(written) == [_receipt(MEMORY, "n", "leg", 2, SHA)] + + +def test_two_ops_at_once_keep_their_own_notes(written: list[list[dict[str, Any]]]) -> None: + async def handler(input: Any) -> None: + rr.note_memory("n", input.key, version=1, sha256=SHA) + await asyncio.sleep(0) # the other op notes its row meanwhile + + op = rr.records_receipts()(handler) + + async def _go() -> None: + first = SimpleNamespace(org="o", namespace="n", agent="a", key="x") + second = SimpleNamespace(org="o", namespace="n", agent="b", key="y") + await asyncio.gather(op(first), op(second)) + await after_write.drain() + + asyncio.run(_go()) + rows = sorted((r["agent"], r["item_key"]) for batch in written for r in batch) + assert rows == [("a", "x"), ("b", "y")] + + +def test_a_note_outside_a_receipted_op_is_kept_nowhere() -> None: + _note_k() + rr.note_document("n", "doc://a", revision=1) + assert rr._notes.get() is None + + +# ------------------------------------------------------------------------ the gates + + +def test_no_receipt_while_the_setting_is_off( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + monkeypatch.setattr(settings, "read_receipts_enabled", False) + noted: list[Any] = [] + + async def handler(_input: Any) -> None: + _note_k() + noted.append(rr._notes.get()) + + _run(rr.records_receipts()(handler)) + # off costs a read nothing: no note is kept, no row is built + assert written == [] and noted == [None] + + +@pytest.mark.parametrize( + "live", + [ + [], # no heartbeat read: unknown counts as no + [{"schema_version": store.MIGRATION - 1}], + [{"schema_version": store.MIGRATION}, {"schema_version": store.MIGRATION - 1}], + [{"schema_version": None}], + ], +) +def test_no_receipt_while_a_live_replica_cannot_erase_it( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]], live: list[Any] +) -> None: + monkeypatch.setattr(instances, "live_rows", lambda: live) + assert not instances.every_live_replica_at(store.MIGRATION) + _run(_op(_note_k)) + assert written == [] + + +def test_a_closed_replica_gate_is_logged_once( + monkeypatch: pytest.MonkeyPatch, + written: list[list[dict[str, Any]]], + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr(instances, "live_rows", lambda: []) + with caplog.at_level("WARNING", logger=rr.__name__): + _run(_op(_note_k)) + _run(_op(_note_k)) + said = [r for r in caplog.records if "read receipts are not written" in r.getMessage()] + assert len(said) == 1 and written == [] + + +def test_receipts_are_written_once_every_live_replica_is_at_the_migration( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + live = [{"schema_version": store.MIGRATION}, {"schema_version": store.MIGRATION + 3}] + monkeypatch.setattr(instances, "live_rows", lambda: live) + _run(_op(_note_k)) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +def test_a_request_that_read_a_mirrored_source_writes_nothing( + written: list[list[dict[str, Any]]], +) -> None: + async def handler(_input: Any) -> None: + _note_k() + assert request_work.mark_mirrored() + + op = rr.records_receipts()(handler) + + async def _go() -> None: + request_work.begin() + await op(_INPUT) + await after_write.drain() + + asyncio.run(_go()) + assert written == [] + + +def test_a_note_made_under_private_work_is_dropped(written: list[list[dict[str, Any]]]) -> None: + def note() -> None: + rr.note_memory("n", "public", version=1, sha256=SHA) + with private_work(): + rr.note_memory("n", "private", version=2, sha256=SHA) + rr.note_document("n", "doc://private", revision=1) + rr.note_selected("n", [{"memory_key": "selected", "version": 4}]) + + _run(_op(note)) + assert _receipts(written) == [_receipt(MEMORY, "n", "public", 1, SHA)] + + +def test_an_answer_made_under_private_work_writes_nothing( + written: list[list[dict[str, Any]]], +) -> None: + """A hit carries its own version, so the answer is refused as well as each note.""" + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + + async def handler(_input: Any) -> Any: + return MemorySearchOutput(results=[_hit("k", version=7)], embedding_model="e") + + op = rr.records_receipts(rr.search_items)(handler) + + async def _go() -> None: + with private_work(): + await op(MemorySearchInput(org="o", namespace="n", query="q")) + await after_write.drain() + + asyncio.run(_go()) + assert written == [] + + +def test_an_item_of_a_mirror_or_a_code_store_gets_no_row( + written: list[list[dict[str, Any]]], +) -> None: + def note() -> None: + rr.note_memory(MIRROR, "k", version=1, sha256=SHA) + rr.note_document(MIRROR, "doc://a", revision=1) + rr.note_memory(STORE, "k", version=1, sha256=SHA) + _note_k() + + _run(_op(note)) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +# ------------------------------------------------ a receipt never fails the read + + +def test_a_failing_handler_raises_as_before_and_writes_nothing( + written: list[list[dict[str, Any]]], +) -> None: + async def handler(_input: Any) -> None: + _note_k() + raise ValueError("no such row") + + op = rr.records_receipts()(handler) + + async def _go() -> None: + with pytest.raises(ValueError, match="no such row"): + await op(_INPUT) + assert rr._notes.get() is None # the next op of this context starts clean + await after_write.drain() + + asyncio.run(_go()) + assert written == [] + + +def test_a_cancelled_handler_writes_nothing(written: list[list[dict[str, Any]]]) -> None: + started = asyncio.Event() + + async def handler(_input: Any) -> None: + _note_k() + started.set() + await asyncio.Event().wait() # the caller goes away while the op waits + + op = rr.records_receipts()(handler) + + async def _go() -> None: + task = asyncio.ensure_future(op(_INPUT)) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await after_write.drain() + + asyncio.run(_go()) + assert written == [] and rr._queued == [] + + +def test_a_failing_item_read_never_fails_the_answer(written: list[list[dict[str, Any]]]) -> None: + def broken(_input: Any, _out: Any) -> list[Item]: + raise RuntimeError("boom") + + out = object() + assert _run(_op(_note_k, out, broken)) is out + assert written == [] + + +def test_a_note_that_cannot_read_its_row_never_fails_the_read( + written: list[list[dict[str, Any]]], +) -> None: + def note() -> None: + rr.note_row(object()) # no namespace, key or version + rr.note_selected("n", [None]) # type: ignore[list-item] + _note_k() + + out = object() + assert _run(_op(note, out)) is out + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +def test_a_failing_insert_leaves_the_read_answered( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + async def _down(_rows: list[dict[str, Any]], **_kw: Any) -> None: + raise RuntimeError("store down") + + monkeypatch.setattr(store, "insert", _down) + out = object() + assert _run(_op(_note_k, out)) is out + # the rows are lost, not sent again: a store that is down gets no backlog + assert (rr._failed, rr._queued) == (1, []) + monkeypatch.setattr(store, "insert", _collect(written)) + _run(_op(_note_k)) # the next answer starts a new sender + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +def _collect(batches: list[list[dict[str, Any]]]) -> Any: + async def _insert(rows: list[dict[str, Any]], **_kw: Any) -> None: + batches.append(rows) + + return _insert + + +def test_past_the_queue_bound_an_answers_rows_are_dropped_and_counted( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + monkeypatch.setattr(rr, "_MAX_QUEUED_ROWS", 1) + + def two() -> None: + rr.note_memory("n", "a", version=1, sha256=SHA) + rr.note_memory("n", "b", version=2, sha256=SHA) + + out = object() + assert _run(_op(two, out)) is out + assert written == [] and rr._dropped == 2 + _run(_op(_note_k)) # an answer that fits is written + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, SHA)] + + +def test_one_sender_carries_the_rows_that_queue_during_its_insert( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + """Receipts hold one connection: the reads answered while an insert is out go in + the next one.""" + release = asyncio.Event() + out_at_once: list[int] = [] + sent: list[int] = [] + + async def _slow(rows: list[dict[str, Any]], **_kw: Any) -> None: + out_at_once.append(1) + assert len(out_at_once) == 1 + await release.wait() + sent.append(len(rows)) + out_at_once.pop() + + monkeypatch.setattr(store, "insert", _slow) + op = _op(_note_k) + + async def _go() -> None: + await op(_INPUT) + await _sender_turns() # the sender takes the first answer's row to the store + for _ in range(5): + await op(_INPUT) + release.set() + await after_write.drain() + + asyncio.run(_go()) + assert sent == [1, 5] + + +async def _sender_turns() -> None: + """Let the sender wait out its interval (none in these tests) and start its insert.""" + for _ in range(2): + await asyncio.sleep(0) + + +def test_the_answers_of_one_interval_share_an_insert( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + """An insert costs the same whatever it carries, so the sender waits an interval + before each: reads that arrive one after another do not each pay for one.""" + monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0.05) + op = _op(_note_k) + + async def _go() -> None: + for _ in range(4): + await op(_INPUT) + await asyncio.sleep(0.001) + await after_write.drain() + + asyncio.run(_go()) + assert [len(rows) for rows in written] == [4] + + +def test_a_sender_left_on_a_closed_loop_is_replaced( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + """A loop that closes with the sender mid-insert leaves a task that is never done: + the next answer starts a sender on its own loop, which sends what had queued too.""" + + async def _hang(_rows: list[dict[str, Any]], **_kw: Any) -> None: + await asyncio.Event().wait() + + monkeypatch.setattr(store, "insert", _hang) + op = _op(_note_k) + + async def _first() -> None: + await op(_INPUT) + await _sender_turns() # the sender takes the row to a store that never answers + await op(_INPUT) # queued behind it + + loop = asyncio.new_event_loop() + loop.run_until_complete(_first()) + loop.close() + assert rr._sender is not None and not rr._sender.done() + monkeypatch.setattr(store, "insert", _collect(written)) + _run(op) + # the row the first sender took is lost with it; the queued one and the new one land + assert [len(rows) for rows in written] == [2] + + +def test_the_sender_carries_nothing_of_the_request_that_started_it( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + from server.core.ch import current_query_tag + from server.core.logging_config import request_id_var + + seen: list[tuple[str | None, str]] = [] + + async def _insert(_rows: list[dict[str, Any]], **_kw: Any) -> None: + seen.append((request_id_var.get(), current_query_tag())) + + monkeypatch.setattr(store, "insert", _insert) + + async def _go() -> None: + request_id_var.set("req-1") + await _op(_note_k)(_INPUT) + await after_write.drain() + + asyncio.run(_go()) + assert seen == [(None, rr.SEND_QUERY_TAG)] + + +def test_a_repeating_failure_is_logged_at_each_power_of_ten() -> None: + assert [n for n in range(1, 1200) if rr._worth_logging(n)] == [1, 10, 100, 1000] + # a counter that rises by an answer's rows is logged when it passes one + assert rr._worth_logging(5, 5) and rr._worth_logging(12, 5) and not rr._worth_logging(17, 5) + + +# ------------------------------------------------------------------------- the hash + + +@pytest.mark.parametrize( + ("note", "sha256"), + [ + ({"sha256": SHA}, SHA), + ({"sha256": SHA, "high": True}, ""), # a short secret's hash names it + ({"sha256": SHA, "redacted": True}, ""), # the stored hash is the removed text's + ({"sha256": ""}, ""), + ({"sha256": "A" * 64}, ""), # not a stored content hash + ({"sha256": "abc"}, ""), + ], +) +def test_the_hash_is_recorded_only_when_it_names_content_safely( + written: list[list[dict[str, Any]]], note: dict[str, Any], sha256: str +) -> None: + _run(_op(lambda: rr.note_memory("n", "k", version=3, **note))) + # the version is recorded either way + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 3, sha256)] + + +def _row(**fields: Any) -> SimpleNamespace: + row = { + "namespace": "n", + "memory_key": "k", + "version": 4, + "content_sha256": SHA, + "value": {"a": None}, + "value_truncated": False, + "sensitivity": "normal", + "redacted_at": None, + } + return SimpleNamespace(**{**row, **fields}) + + +def test_a_row_is_noted_with_its_stored_hash(written: list[list[dict[str, Any]]]) -> None: + from server.memory.domain.redaction_lineage import is_content_hash + from server.memory.domain.trust import row_content_sha256 + + unset = _row(memory_key="unset", content_sha256="") + + def note() -> None: + rr.note_row(_row()) + rr.note_row(unset) # hashed from the value, as an attestation would + rr.note_row(_row(memory_key="cut", content_sha256="", value_truncated=True)) + rr.note_row(_row(memory_key="secret", sensitivity="high")) + rr.note_row(_row(memory_key="redacted", redacted_at=object())) + + _run(_op(note)) + from_value = row_content_sha256(unset) + assert is_content_hash(from_value) and from_value != SHA + assert _receipts(written) == [ + _receipt(MEMORY, "n", "k", 4, SHA), + _receipt(MEMORY, "n", "unset", 4, from_value), + _receipt(MEMORY, "n", "cut", 4), + _receipt(MEMORY, "n", "secret", 4), + _receipt(MEMORY, "n", "redacted", 4), + ] + + +def test_selected_rows_are_noted_as_the_statement_read_them( + written: list[list[dict[str, Any]]], +) -> None: + rows = [ + {"memory_key": "a", "version": 2, "content_sha256": SHA.encode()}, + {"memory_key": "b", "version": 3, "content_sha256": SHA, "redacted_at": object()}, + {"memory_key": "c", "version": 5, "namespace": "m"}, # no hash selected + {"memory_key": "d", "version": 6, "content_sha256": SHA, "sensitivity": "high"}, + {"memory_key": "", "version": 1}, + ] + _run(_op(lambda: rr.note_selected("n", rows))) + assert _receipts(written) == [ + _receipt(MEMORY, "n", "a", 2, SHA), + _receipt(MEMORY, "n", "b", 3), + _receipt(MEMORY, "m", "c", 5), + _receipt(MEMORY, "n", "d", 6), + ] + + +# -------------------------------------------------- what each op's answer carried + + +def _hit(key: str, **fields: Any) -> Any: + from server.memory.api.models_search import _MemorySearchHit + + row_version = fields.pop("row_version", 0) + hit = _MemorySearchHit( + memory_key=key, + memory_type="semantic", + content_excerpt="x", + distance=0.1, + similarity=0.9, + **fields, + ) + hit._row_version = row_version + return hit + + +def _document_hit(**fields: Any) -> Any: + from server.knowledge.api.models_knowledge import _SearchHit + + hit = { + "source_uri": "doc://a", + "chunk_idx": 2, + "content": "c", + "tags": [], + "distance": 0.1, + "similarity": 0.9, + "revision": 3, + } + return _SearchHit(**{**hit, **fields}) + + +def test_a_search_receipts_the_rows_and_passages_its_answer_returns( + written: list[list[dict[str, Any]]], +) -> None: + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + + hits = [ + _hit("fact", version=7), + # a tier row: the wire's version is 0, the stored one is private + _hit("tier", row_version=4, source="anchor"), + _hit("chunk:s1:3", parent_memory_key="long", source="chunk"), + _hit("both", version=2), + _hit("chunk:s1:4", parent_memory_key="both", source="chunk"), + _hit("summary", version=1, source="summary"), # no stored memory row + _hit("far", version=5, namespace="m"), + # a whole body read after the search: the answer carries that row's text + _hit("body", version=8, row_version=9), + ] + + def note() -> None: + rr.note_memory("n", "fact", version=7, sha256=SHA) # the fact leg read its hash + rr.note_memory("n", "trimmed", version=6, sha256=SHA) # a candidate that did not rank + rr.note_memory("n", "body", version=8, sha256=SHA) # the search document + rr.note_memory("n", "body", version=9, sha256=OTHER_SHA) # the row the body came from + + out = MemorySearchOutput(results=hits, embedding_model="e") + _run(_op(note, out, rr.search_items), MemorySearchInput(org="o", namespace="n", query="q")) + assert _receipts(written) == [ + _receipt(MEMORY, "n", "fact", 7, SHA), + _receipt(MEMORY, "n", "tier", 4), + _receipt(MEMORY, "n", "long", 0), # a passage: the read held no row version + _receipt(MEMORY, "n", "both", 2), # the row, not its passage beside it + _receipt(MEMORY, "m", "far", 5), + _receipt(MEMORY, "n", "body", 9, OTHER_SHA), + ] + + +def test_a_governed_definition_is_receipted_at_the_shared_copy_it_served( + written: list[list[dict[str, Any]]], +) -> None: + from server.memory.api.models_loom_search import SearchInput, SearchOutput + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + + key = "definition/arr" + + def note() -> None: + rr.note_memory("n", key, version=12, sha256=SHA) # the term leg: the shared copy + rr.note_memory("n", key, version=30, sha256=OTHER_SHA) # the fact leg: its source row + + out = MemorySearchOutput( + results=[_hit(key, governed=True, row_version=12)], embedding_model="e" + ) + ident = {"org": "o", "namespace": "n"} + _run(_op(note, out, rr.search_items), MemorySearchInput(**ident, query="q")) + # the source row was edited after the promotion: the answer carried the copy's text + assert _receipts(written) == [_receipt(MEMORY, "n", key, 12, SHA)] + # an answer that carries the hit without its stored version cannot say which row it is + wire = SearchOutput.model_validate({"memory": out.model_dump(mode="json")}) + _run(_op(note, wire, rr.search_query_items), SearchInput(**ident, query="q")) + assert _receipts(written)[1:] == [_receipt(MEMORY, "n", key, 0)] + + +def test_a_document_search_receipts_each_chunk_at_its_revision( + written: list[list[dict[str, Any]]], +) -> None: + from server.knowledge.api.models_knowledge import KnowledgeSearchInput, KnowledgeSearchOutput + + hits = [ + _document_hit(), + _document_hit(chunk_idx=4), + _document_hit(source_uri="doc://b", revision=1, namespace="m"), + _document_hit(source_uri="doc://unnumbered", revision=0), + ] + + def note() -> None: + rr.note_document("n", "doc://a", revision=3, doc_version=11) + rr.note_document("m", "doc://b", revision=1, doc_version=5) + rr.note_document("n", "doc://unnumbered", revision=0, doc_version=8) + rr.note_document("n", "doc://trimmed", revision=2, doc_version=6) + + out = KnowledgeSearchOutput(results=hits, embedding_model="e") + input = KnowledgeSearchInput(org="o", namespace="n", query="q") + _run(_op(note, out, rr.knowledge_items), input) + assert _receipts(written) == [ + _receipt(DOCUMENT, "n", "doc://a", 3, "", 11, 2), + _receipt(DOCUMENT, "n", "doc://a", 3, "", 11, 4), + _receipt(DOCUMENT, "m", "doc://b", 1, "", 5, 2), + _receipt(DOCUMENT, "n", "doc://unnumbered", 0, "", 8, 2), + ] + + +def test_a_versionless_answer_records_the_hash_of_a_row_read_through_two_tables( + written: list[list[dict[str, Any]]], +) -> None: + """A context pack names a row by key. Its search noted the row's search document, at + that document's version, and its own read noted the memory row.""" + from server.memory.api.models_context import ContextPackInput, ContextPackOutput + + def note() -> None: + rr.note_selected("n", [{"memory_key": "k", "version": 8, "content_sha256": SHA}]) + rr.note_row(_row(version=3)) + + pack = ContextPackOutput(rendered="", sections={}, section_count=0, token_budget=1) + pack._served_rows = [("n", "k")] + items = rr.memory_rows(served_reads.rendered_rows) + _run(_op(note, pack, items), ContextPackInput(org="o", namespace="n", agent="a", query="q")) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 0, SHA)] + + +def _answers() -> dict[str, tuple[Any, Any, Callable[[], None], list[tuple[Any, ...]]]]: + """Per receipted op: a real input, a real answer that carries memory `k` (and, where + the op serves documents, a chunk of `doc://a`), the notes its read makes, and the + receipts it must write.""" + from server.knowledge.api.models_knowledge import KnowledgeSearchInput, KnowledgeSearchOutput + from server.memory.api.models_ask import MemoryAskInput, MemoryAskOutput + from server.memory.api.models_brief import MemoryBriefInput, MemoryBriefOutput + from server.memory.api.models_context import ContextPackInput, ContextPackOutput + from server.memory.api.models_for_file import MemoryForFileInput, MemoryForFileOutput + from server.memory.api.models_lifecycle import MemoryStackInput, MemoryStackOutput + from server.memory.api.models_loom_search import SearchInput, SearchOutput + from server.memory.api.models_procedure import ProcedureMatchInput, ProcedureMatchOutput + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + + def note_row() -> None: + rr.note_memory("n", "k", version=7, sha256=SHA) + + def note_document() -> None: + rr.note_document("n", "doc://a", revision=3, doc_version=11) + + def note_both() -> None: + note_row() + note_document() + + row = [_receipt(MEMORY, "n", "k", 7, SHA)] + chunk = [_receipt(DOCUMENT, "n", "doc://a", 3, "", 11, 2)] + document = [_receipt(DOCUMENT, "n", "doc://a", 3, "", 11)] + + ident = {"org": "o", "namespace": "n", "agent": "codex"} + lookup = SimpleNamespace(**ident) + search = MemorySearchOutput(results=[_hit("k", version=7)], embedding_model="e") + documents = KnowledgeSearchOutput(results=[_document_hit()], embedding_model="e") + brief = MemoryBriefOutput() + brief._evidence_hits = [_hit("k", version=7)] + pack = ContextPackOutput(rendered="", sections={}, section_count=0, token_budget=1) + pack._served_rows = [("n", "k")] + for_file = MemoryForFileOutput( + path="a.py", + total=1, + hits=[], + printed=[{"namespace": "n", "memory_key": "k", "line": "- k: v"}], + ) + stack = MemoryStackOutput.model_validate( + { + "entries": [{"section": "pinned", "memory_key": "k", "tokens": 1}], + "tokens_used": 1, + "tokens_budget": 10, + "truncated": False, + "section_counts": {}, + } + ) + match = ProcedureMatchOutput.model_validate( + { + "matches": [ + { + "name": "p", + "situation": "s", + "steps": [], + "similarity": 0.9, + "memory_key": "k", + "namespace": "n", + } + ] + } + ) + both = SearchOutput.model_validate( + { + "memory": search.model_dump(mode="json"), + "knowledge": documents.model_dump(mode="json"), + } + ) + return { + "memory.search": (MemorySearchInput(**ident, query="q"), search, note_row, row), + "memory.ask": ( + MemoryAskInput(**ident, query="q"), + MemoryAskOutput(answer="", results=[_hit("k", version=7)]), + note_row, + row, + ), + "memory.brief": (MemoryBriefInput(**ident, query="q"), brief, note_row, row), + "search.query": (SearchInput(**ident, query="q"), both, note_both, row + chunk), + "memory.get": (lookup, object(), note_row, row), + "memory.get_by_id": (lookup, object(), note_row, row), + "memory.bulk_get": (lookup, object(), note_row, row), + "context.pack": (ContextPackInput(**ident, query="q"), pack, note_row, row), + "memory.stack": (MemoryStackInput(**ident), stack, note_row, row), + "memory.for_file": ( + MemoryForFileInput(org="o", namespace="n", path="a.py"), + for_file, + note_row, + row, + ), + "procedure.match": (ProcedureMatchInput(**ident, situation="s"), match, note_row, row), + "knowledge.search": ( + KnowledgeSearchInput(org="o", namespace="n", query="q"), + documents, + note_document, + chunk, + ), + "knowledge.get": (lookup, object(), note_document, document), + } + + +def _receipts_wrapper(handler: Any) -> Any: + """The `records_receipts` wrapper among a handler's wrappers, or None (a wrapper + keeps the handler's name, so it is told by the file its code is in).""" + while handler is not None: + code = getattr(handler, "__code__", None) + if code is not None and code.co_filename == rr.__file__: + return handler + handler = getattr(handler, "__wrapped__", None) + return None + + +def test_exactly_the_recall_ops_are_receipted() -> None: + """A read that lists or inspects (memory.list, memory.keys, an export) and a search + an op runs for its own use carry no wrapper; neither does a write.""" + from server.operations.registry import OPERATIONS_BY_NAME + + receipted = { + name for name, op in OPERATIONS_BY_NAME.items() if _receipts_wrapper(op.handler) is not None + } + assert receipted == RECEIPTED == set(_answers()) + + +@pytest.mark.parametrize("name", sorted(RECEIPTED)) +def test_each_receipted_op_writes_what_its_answer_carried( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]], name: str +) -> None: + """Through the registered op's own handler, its read stood in: the op pairs the + answer's real wire model with the notes and writes the revision the read held. A + renamed field would make an extractor find nothing, with every stand-in test green.""" + from server.memory.store import served + from server.operations.registry import OPERATIONS_BY_NAME + + input, answer, note, expected = _answers()[name] + + async def _no_served_rows(*_a: Any, **_kw: Any) -> int: + return 0 + + async def _read(_input: Any) -> Any: + note() + # a row the answer does not carry: a candidate that did not rank + if name not in {"memory.get", "memory.get_by_id", "memory.bulk_get", "knowledge.get"}: + rr.note_memory("n", "not_served", version=2, sha256=OTHER_SHA) + return answer + + monkeypatch.setattr(served, "record_served", _no_served_rows) + handler = OPERATIONS_BY_NAME[name].handler + monkeypatch.setattr(_receipts_wrapper(handler), "__wrapped__", _read) + assert _run(handler, input) is answer + assert _receipts(written) == expected + + +def test_the_served_reads_log_and_the_receipts_name_the_same_rows() -> None: + """An answer that names its rows without a version is read by the served-reads + extractor, so the two records cannot disagree on what an answer carried.""" + out = SimpleNamespace(matches=[SimpleNamespace(memory_key="p", namespace="")]) + input = SimpleNamespace(namespace="n") + assert rr.memory_rows(served_reads.procedure_keys)(input, out) == [Item(MEMORY, "n", "p")] diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index 446346871c4..64a7fa1090e 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -25,6 +25,7 @@ "search_misses": "the searches that found nothing, kept to group into knowledge gaps", "knowledge_gaps": "the gaps grouped from the misses, rebuilt daily", "memory_exposures": "an access log of which rows a read served", + "read_receipts": "which revision of an item a read served: identifiers and a hash", "code_search_trace": "a per-search trace of code search", "code_search_outcome": "the outcome of each traced code search", "context_blobs": "offloaded context whose writer sets expires_at", @@ -176,6 +177,7 @@ def test_the_journal_files() -> None: "119_workspace_crawl.sql", "120_usage_label_provenance.sql", "121_code_repo_base_namespace.sql", + "122_read_receipts.sql", ] diff --git a/tests/unit/test_served_reads.py b/tests/unit/test_served_reads.py index 365cd798536..8f404de6e00 100644 --- a/tests/unit/test_served_reads.py +++ b/tests/unit/test_served_reads.py @@ -248,11 +248,22 @@ async def _answer(_input: Any) -> Any: assert [w["ns_keys"] for w in written] == [{"n": ["k"]}] +def _records_served(handler: Any) -> bool: + """True when `records_served` is among the handler's wrappers (a wrapper keeps the + handler's name, so it is told by the file its code is in).""" + while handler is not None: + if handler.__code__.co_filename == served_reads.__file__: + return True + handler = getattr(handler, "__wrapped__", None) + return False + + def test_key_lookups_and_own_use_searches_record_nothing() -> None: """A key lookup is the agent naming a key it knows; decision.precedents and - memory.apply search for their own use: their handlers are not wrapped.""" + memory.apply search for their own use: `records_served` wraps none of them.""" from server.operations.registry import OPERATIONS_BY_NAME + assert _records_served(OPERATIONS_BY_NAME["memory.search"].handler) for name in ( "memory.get", "memory.bulk_get", @@ -260,7 +271,7 @@ def test_key_lookups_and_own_use_searches_record_nothing() -> None: "decision.precedents", "memory.apply", ): - assert not hasattr(OPERATIONS_BY_NAME[name].handler, "__wrapped__"), name + assert not _records_served(OPERATIONS_BY_NAME[name].handler), name def test_an_evaluation_ask_records_nothing() -> None: diff --git a/tests/unit/test_term_leg.py b/tests/unit/test_term_leg.py index ebcaff00fd9..265636fe372 100644 --- a/tests/unit/test_term_leg.py +++ b/tests/unit/test_term_leg.py @@ -45,9 +45,15 @@ async def shared_definitions( assert strong is False return [names(r) for r in state.get("listed", state["rows"])[:limit]] - async def definition_values(org: str, namespace: str, keys: list[str]) -> dict[str, str]: + async def definition_values( + org: str, namespace: str, keys: list[str] + ) -> dict[str, tuple[str, int]]: state["values_read"].append(sorted(keys)) - return {r["memory_key"]: r["value"] for r in state["rows"] if r["memory_key"] in keys} + return { + r["memory_key"]: (r["value"], int(r.get("version", 1))) + for r in state["rows"] + if r["memory_key"] in keys + } async def source_reasons( org: str, namespace: str, defs: list[Any], *, strong: bool, max_value_chars: int @@ -67,6 +73,28 @@ async def _keys(query: str, excluded: frozenset[str] = frozenset()) -> tuple[str return leg.status, [h.memory_key for h in leg.hits] +async def test_a_governed_hit_carries_and_notes_the_shared_copy_it_serves( + store: dict[str, Any], +) -> None: + """The receipt of a governed hit names the shared copy, not another row of the key.""" + from server.memory.app import read_receipts + from server.memory.domain.read_receipts import MEMORY, Noted, Notes + from server.memory.domain.trust import live_sha256 + + row = {**_row("definition/arr", "ARR"), "version": 41} + store["rows"] = [row] + notes: Notes = {} + token = read_receipts._notes.set(notes) + try: + leg = await term_leg._read("o", "n", "what is ARR", set(), None, "m") + finally: + read_receipts._notes.reset(token) + [hit] = leg.hits + assert (hit.version, hit._row_version) == (0, 41) + stored = Noted(41, live_sha256(None, row["value"])) + assert notes == {(MEMORY, "n", "definition/arr"): {41: stored}} + + async def test_a_query_naming_no_term_reads_no_source(store: dict[str, Any]) -> None: store["rows"] = [_row("definition/arr", "ARR")] assert await _keys("what did we ship") == ("complete", []) From b0bf4e8cf67918d90aa7416b5212ef83bc59f20b Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 10:21:16 +0000 Subject: [PATCH 02/18] The analyzer's shape list holds one shape for the schema dump The rebase left the shape of main's dump beside the shape of this branch's. The list is regenerated with python -m tests.analyzer.corpus --write. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- tests/analyzer/shapes.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index e93b4ea8566..28153e2f224 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -118,6 +118,7 @@ 0c999f060efc SELECT proposal_policy FROM loom.namespaces FINAL WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 0cfc88297bf0 SELECT count() AS n FROM loom.knowledge_ingestions WHERE org = {org:String} AND namespace = {ns:String} 0d0074d068cf SELECT queue_id, agent, user_id, session_id, status, attempts, message_count, content_chars, written, last_error, enqueued_at, updated_at FROM loom.memory_extraction_queue FINAL PREWHERE org = {org:St +0d61f55e9bf0 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 0db9931937d8 SELECT count() AS n FROM loom.memory WHERE org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String)) 0df388be7e18 SELECT count() AS n FROM loom.memory_projection_failures WHERE org = {org:String} AND (JSONExtractString(payload, ?) = {uid:String} OR arrayExists(e -> JSONExtractString(e, ?) = {uid:String}, JSONExtr 0df8d59119a4 SELECT org, namespace, policy_id, effect, description, actions, condition, enabled, mode, created_by, created_at, updated_at, tombstoned_at FROM loom.namespace_policies FINAL WHERE org = {org:String} @@ -503,7 +504,6 @@ 39f9fbc2c519 SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND user_id = {uid:String} 3a315e2ef1be ALTER TABLE loom.entity_canonical_map UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} 3a6169b72b54 SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND user_id = {uid:String} -3a662f80aca3 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 3a8471ec9ffe SELECT pr_number, any(title) AS title, any(author) AS author, min(merged_at) AS merged_at, max(opened_at) AS opened_at, any(files) AS files, any(linked_issues) AS linked_issues FROM loom.code_pr_histo 3a88608e1703 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 3a892047e93b SELECT scope_type, scope_path, summary, pagerank, in_degree, out_degree, key_symbols FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:St @@ -1656,7 +1656,6 @@ b4bd124a4089 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. b4eaaee7f731 SELECT org, namespace, agent, user_id, session_id, name, source_id, host, port, secure, user, password_enc, cluster, databases, actor, source_class, created_at, tombstoned_at, version FROM loom.query_ b4fcede7dd0d SELECT * EXCEPT (embedding) FROM loom.code_summaries FINAL WHERE (org, namespace, embedding_model, scope_type, scope_path) IN {keys:Array(Tuple(String, String, String, String, String))} AND embedding_ b50bb3c82af0 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU -b50d606a3284 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou b517057ddbb9 SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), {keys:Array(String)}) b5372e83b5f1 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this b546d3bd8553 SELECT count() AS n FROM loom.entity_edge_memories WHERE org = {org:String} AND namespace = {ns:String} AND ? From 659b3bcef3609bfa28d56713e2134458fba5c3ea Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 13:24:07 +0000 Subject: [PATCH 03/18] Read receipts name the rows an answer printed, log each loss with its cause and total, and live 190 days A context pack's receipts are the rows its rendered text prints, at the version of the search hit each was printed from; an abstaining search's rows are receipted and not counted as served. search.query receipts its memory hits from the search's own models, which keep the private row version. Each kind of loss (closed replica gate, queue bound, failed insert) is logged at most once a minute with its total since the process started. The closed-gate line names its cause and counts only answers that had rows to record, so the gate is asked when an answer's rows are queued. Reader strings pass through as_valid_unicode (server/core/hashing.py, shared with memory.for_file), so a lone surrogate costs no insert. An unnamed agent is stored as '-'. A user's erasure counts the receipts stamped up to the second it was recorded in, and its whole-org counts and delete run under the DDL deadline. The table keeps a row 190 days, so every row outlives six calendar months, and its agent column defaults to '-'. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/clickhouse.md | 23 +- docs/architecture/read-receipts.md | 285 ++++++++++++------ docs/architecture/rolling-upgrades.md | 5 +- docs/architecture/storage-layout.md | 2 +- docs/features/memory/retention-and-erasure.md | 19 +- docs/features/runs.md | 12 +- docs/operations/upgrades.md | 17 +- schemas/migrations/122_read_receipts.sql | 9 +- server/core/hashing.py | 11 +- server/erasure/store/census.py | 33 +- server/erasure/store/mutations.py | 2 +- server/erasure/store/predicates.py | 10 +- server/erasure/store/steps_ledgers.py | 23 +- server/memory/api/models_context.py | 3 + server/memory/api/models_loom_search.py | 6 + server/memory/api/ops_context.py | 6 +- server/memory/app/context_pack.py | 28 +- server/memory/app/for_file.py | 10 +- server/memory/app/loom_search/fanout.py | 7 + server/memory/app/loom_search/handler.py | 7 +- server/memory/app/read_receipts.py | 127 +++++--- server/memory/domain/context_layout.py | 17 +- server/memory/domain/evidence_pack.py | 12 +- server/memory/store/read_receipts.py | 15 +- server/settings/catalog.py | 6 +- tests/integration/test_read_receipts.py | 4 +- tests/unit/test_context_pack_served_rows.py | 73 ++++- tests/unit/test_erasure_census_tail.py | 19 +- tests/unit/test_erasure_late_steps.py | 62 +++- tests/unit/test_memory_search_kinds.py | 5 + tests/unit/test_pg_durable_reads.py | 4 +- tests/unit/test_read_receipts.py | 245 +++++++++++++-- 32 files changed, 839 insertions(+), 268 deletions(-) diff --git a/docs/architecture/clickhouse.md b/docs/architecture/clickhouse.md index 42ed10a909a..c2ce3a2eb70 100644 --- a/docs/architecture/clickhouse.md +++ b/docs/architecture/clickhouse.md @@ -353,17 +353,18 @@ conversations and the graph have no TTL. They leave only by an explicit delete, writer-set expiry (`ttl_seconds`, applied by `memory_expiry_sweep` per the row's `on_expire`) or erasure. Tables with a schema TTL hold telemetry, caches or runner state: -| Window | Tables | -| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 60 minutes | `code_search_memo` | -| 3 days | `memory_webhook_outbox`, `memory_webhook_attempts` | -| 7 days | `llm_response_cache`, `code_scip_parts` | -| 30 days | `events`, `embedding_cache`, `memory_drops`, `memory_extraction_queue`, `memory_ask_precedents`, `worker_status`, `code_scip_batches` | -| 90 days | `erasure_requests`, `oauth_state`, `policy_decisions` | -| 180 days | `search_trace_log`, `memory_exposures`, `memory_exposure_breadth_hourly`, `read_receipts`, `consolidation_runs`, `code_search_trace`, `code_search_outcome` | -| 400 days | `loom_telemetry.sli_minute` | -| 5 years | `erasure_reversals` | -| other | `idempotency` (at `expires_at`), `revoked_tokens` (10 days past token expiry), `context_blobs` (1 day past `expires_at`) | +| Window | Tables | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| 60 minutes | `code_search_memo` | +| 3 days | `memory_webhook_outbox`, `memory_webhook_attempts` | +| 7 days | `llm_response_cache`, `code_scip_parts` | +| 30 days | `events`, `embedding_cache`, `memory_drops`, `memory_extraction_queue`, `memory_ask_precedents`, `worker_status`, `code_scip_batches` | +| 90 days | `erasure_requests`, `oauth_state`, `policy_decisions` | +| 180 days | `search_trace_log`, `memory_exposures`, `memory_exposure_breadth_hourly`, `consolidation_runs`, `code_search_trace`, `code_search_outcome` | +| 190 days | `read_receipts` | +| 400 days | `loom_telemetry.sli_minute` | +| 5 years | `erasure_reversals` | +| other | `idempotency` (at `expires_at`), `revoked_tokens` (10 days past token expiry), `context_blobs` (1 day past `expires_at`) | Operators can add retention to `audit_log`, `agent_events`, `memory`, `memory_embeddings`, `conversations`, `chunks` and `documents` with `LOOM_RETENTION_
_DAYS`, and tiering diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 2f40f58e724..8166023fea6 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -10,6 +10,11 @@ A receipt holds identifiers and a hash. It never holds content, a prompt or quer Every caller of a receipted op leaves one: an agent, an evaluation, a person in the dashboard. It records that the server built the answer, not that the client received it. +Two other receipts describe a read and are not rows of this table: the read receipt the +[outbound MCP source client](mcp-source-client.md) attaches to the evidence of one source +read, which is kept in memory, and the `receipt` field of a `knowledge.query` answer, +which names the snapshots the query read. + ```mermaid flowchart LR R["the read's legs
(hold the rows)"] -->|"note the revision held"| N["notes of the request"] @@ -28,7 +33,9 @@ Two things meet when a receipted op returns (`records_receipts` in (`note_row`, `note_selected`, `note_memory`, `note_document`). Nothing is read again to fill a revision in, so a receipt never names a revision written after the read. - **An item.** The op's answer names the items it carries. A hit the op trimmed, a row - past a section budget and a candidate that did not rank are not items. + past a section budget and a candidate that did not rank are not items. The rows of a + search that abstains are items: `memory.search` returns them and a context pack prints + them, so each has its receipt, although the pack does not count them as served. | Op | Items of the answer | Where the revision is noted | | --------------------------------------------------- | ------------------------------------------ | --------------------------------------------- | @@ -57,10 +64,14 @@ Notes are kept per item and version, because one key can hold a row for each wri session, and one op can read a row through more than one table. - **An item that carries its version records that version**: a search hit, a served row, - a document hit's revision. The note of that version adds the hash, or a document's - stored version. With no such note the version is recorded alone. -- **An item named without a version takes what the notes of its key agree on**: a row of - a context pack, a stack entry, a matched procedure, a row a file block prints. + a document hit's revision, a line a context pack prints from a search hit. The note of + that version adds the hash, or a document's stored version. With no such note the + version is recorded alone. `search.query` serves its memory hits dumped and a context + pack prints text, so both build their items from the search's own hits: where two rows + share a key, the receipt names the one whose text the answer carries. +- **An item named without a version takes what the notes of its key agree on**: a stack + entry (in `memory.stack` and in a context pack), a pack's startup recall, a matched + procedure, a row a file block prints. - One row noted: that row's version and hash. - Several versions noted with one content hash: the hash, with version 0. This is one revision read through the row and through its search document, which sit at @@ -68,7 +79,7 @@ session, and one op can read a row through more than one table. - Anything else, such as two writers' rows under one key: not recorded (version 0, no hash). - No note under the key: no receipt. -- **A chunk hit of `memory.search`** is filed under its parent row's key. The read held a +- **A chunk hit** is filed under its parent row's key. The read held a passage, not the row, so its receipt has version 0 and no hash, and it is left out when the answer also carries the row itself. - **A hit whose text another stored row gave** records that row's revision: a hit @@ -119,6 +130,13 @@ The hash is left empty, and the version still recorded, for: without its hash; - a row whose stored hash is unset and whose value the read did not hold whole. +Under the Postgres authority a key lookup, a whole body, a matched procedure and +`knowledge.get` serve the head Postgres holds, and the receipt names that head without +reading it again durably. ClickHouse holds a row at that version once its delivery +lands. A head a failover loses +([only durable revisions are published](storage-authority.md#only-durable-revisions-are-published)) +leaves a receipt that names a revision no store holds. + ### Documents A document receipt names the source URI, the revision and the chunk, with the stored @@ -133,70 +151,94 @@ revision, `doc_version` is 0: not recorded. A document receipt has no hash. ([access follows the source](document-sources.md#the-mirror): a marked request writes nothing that could depend on what a mirror holds). With auth on, that is every request of `knowledge.search`, `knowledge.get`, `search.query`, `memory.ask` (which reads - documents unless told not to), and `context.pack` and `memory.stack` with - `include_knowledge`, while a namespace in the request's scope has an active mirrored - source. The notes of code running under private work are dropped - (`public_diagnostics()`), and a row under a mirror's or a code store's name is left - out before the rows are queued. The table refuses such a row too + documents unless told not to), `memory.brief` (which runs `memory.ask`), and + `context.pack` and `memory.stack` with `include_knowledge`, while a namespace in the + request's scope has an active mirrored source. The notes of code running under private + work are dropped (`public_diagnostics()`), and a row under a mirror's or a code + store's name is left out before the rows are queued. The table refuses such a row too (`ordinary_namespaces_only`), and with it every row of the insert it arrived in, so - the check before the queue is the one that decides. A source copy served by `knowledge.get` is never noted. -- **Document passages inside `memory.ask`, `context.pack` and `memory.stack` answers.** - The memory rows of the same answer get their receipts; the passages get none. - `knowledge.search`, `knowledge.get` and `search.query` receipt documents. + the check before the queue is the one that decides. A source copy served by + `knowledge.get` is never noted. +- **Document passages inside `memory.ask`, `memory.brief`, `context.pack` and + `memory.stack` answers.** The document search notes each passage's revision, but these + answers carry no passage with its revision and chunk: `memory.ask` returns their + count, `memory.brief` nothing of them, a context pack cites namespace, URI and + section, and a stack entry names the URI. The memory rows of the same answer get their + receipts. `knowledge.search`, `knowledge.get` and `search.query` receipt documents. - **A `memory.get` of a `chunk:` key**, which serves a passage and its neighbours. - **Reads that list or inspect rather than recall**: `memory.list`, `memory.keys`, `memory.inspect`, exports, version history, `memory.related`, `memory.recall`, `memory.timeline`, `facts.*`, `memory.record.query`, `procedure.list`, `knowledge.synthesize`, `knowledge.query`, and code answers that print memories. - **A read made while receipts are not written**: `read_receipts_enabled` is off, a - replica older than the table's migration serves (see - [rolling upgrades](#rolling-upgrades)), the process's queue is full, or the insert - failed. + live replica is older than the table's migration or the process has no recent read of + the replica list (see [rolling upgrades](#rolling-upgrades)), the process's queue is + full, or the insert failed. -A missing receipt means "not recorded". It is never an error for the read, and a reader -of the table must not take it to mean the item was not served. +A missing receipt means "not recorded". It is never an error for the read, and someone +who reads the table must not take it to mean the item was not served. -## The stored row +## The receipt row `loom.read_receipts` is a plain MergeTree sorted by `(org, namespace, kind, item_key, ts)`, so an item's reads are one range of the primary key, filtered by revision inside it. A bloom filter on `run_id` serves "what did this run read". A row is filed under the namespace that holds the item, so one read over several namespaces writes under each. -| Column | Meaning | -| ----------------------------------- | ------------------------------------------------------------------------------------------------- | -| `ts` | When the receipt was built, to the second. | -| `org`, `namespace` | The namespace that holds the item. | -| `kind`, `item_key` | `memory` and the memory key, or `document` and the source URI. | -| `version` | Memory: the version of the stored row the read held. Document: its revision. 0: not recorded. | -| `content_sha256` | Memory: the stored content hash. Empty: not recorded. | -| `doc_version`, `chunk_idx` | Document: the stored version of the revision (0: not recorded), and the chunk; `-1` is the whole. | -| `operation`, `request_id`, `run_id` | The op the caller invoked, its request, and the run the request is filed under (`-`: none). | -| `actor`, `token_id` | The token's subject and id. | -| `agent`, `user_id`, `session_id` | The identity the read ran as: the input's, else the token's read scope, else the request's. | +| Column | Meaning | +| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ts` | When the receipt was built, to the second. | +| `org`, `namespace` | The namespace that holds the item. | +| `kind`, `item_key` | `memory` and the memory key, or `document` and the source URI. | +| `version` | Memory: the version of the stored row the read held. Document: its revision, `revision` in `loom.documents`, not that table's `version`. 0: not recorded. | +| `content_sha256` | Memory: the stored content hash. Empty: not recorded. | +| `doc_version`, `chunk_idx` | Document: the version of the stored document the read held, which its chunks carry as `doc_version` in `loom.chunks` (0: not recorded), and the chunk; `-1` is the whole. | +| `operation`, `request_id`, `run_id` | The op the caller invoked, its request, and the run the request is filed under (`-`: none). | +| `actor`, `token_id` | The token's subject and id. | +| `agent`, `user_id`, `session_id` | The identity the read ran as: the input's, else the token's read scope, else the request's. | The reader comes from the request: `actor` and `token_id` from the token, `agent` as the -served-reads log names it (`reader` in `server/memory/app/served_reads.py`). A document -op's input names no agent, user or session, so its receipt takes the ones the request -named to the transport. A read that names no user has `user_id` `-`: the token's subject -is in `actor`, so reads made as an end user stay apart from reads a token of the same -name made. Over MCP, a document read that names no session carries the id of its -connection, which groups one client's reads. +served-reads log names it (`reader` in `server/memory/app/served_reads.py`). A read that +names no agent has `agent` `-`. + +Five ops have no user or session field in their input, and all but `search.query` no +agent field: `knowledge.search`, `knowledge.get`, `search.query`, `memory.get_by_id` and +`memory.for_file`. A read through one of them is filed by its transport: + +- Over HTTP, under the agent, user and session the request's body named. +- Over MCP, under the token's read scope when the token is pinned to a user, else under + no user and the connection's id, whatever the call's arguments name. + +A read that names no user has `user_id` `-`: the token's subject is in `actor`, so reads +made as an end user stay apart from reads a token of the same name made. A request that +names the token's subject itself as the user, through one of the five ops, is filed +under `-` too: the transport traces an unnamed user as the subject, and the two are one +string when the receipt is built. To find one person's reads, match `user_id` or +`actor`. + +Over MCP, a read that names no session carries the id of its connection, which groups +one client's reads; the exposure row of the same request has `-`. The run is the one every ledger files the request under (`ledger_run_for` in `server/observability/run_context.py`): the request's own `run_id` when it carries one, -else the run bound to the request (the `X-Loom-Run-Id` header, or an MCP session's run). +else the run bound to the request: the `X-Loom-Run-Id` header, or over MCP the session's +run, for the ops that run labels ([reading the table](#reading-the-table) names them). A receipt, the op ledger row and the exposure row of one request therefore name one run. A read's `run_id` also filters the rows it reads, so a read that filters on another run's rows is filed under that run. -**Lifetime.** A receipt is a trace, not memory. Rows expire 180 days after `ts`; whole -monthly parts are dropped, so a row can outlive that by the rest of its month. +A reader string that UTF-8 cannot hold (a `run_id`, `agent`, `user_id` or `session_id` +the caller named with a lone surrogate) is stored with `?` in place of the surrogate. + +**Lifetime.** A receipt is a trace, not memory. Rows expire 190 days after `ts`: six +calendar months are at most 184 days, so every receipt is kept for at least six months. +Whole monthly parts are dropped, so a row can outlive the 190 days by the rest of its +month. ## Reading the table -No op serves this table; it is read with SQL. Bound every read by time: an item that is -read often has many rows, and a run's rows sit in every namespace it read. +No op serves this table; it is read with SQL. Bound every statement by time: an item +that is read often has many rows, and a run's rows sit in every namespace it read. Which revision of an item a run saw: @@ -209,6 +251,9 @@ WHERE org = {org:String} AND namespace = {namespace:String} ORDER BY ts ``` +For a document, filter `kind = 'document'` with the source URI as `item_key`, and select +`version AS revision, doc_version, chunk_idx`. + Which runs were served a revision, by its hash: ```sql @@ -216,37 +261,61 @@ SELECT run_id, min(ts) AS first_read, uniqExact(request_id) AS requests FROM loom.read_receipts WHERE org = {org:String} AND namespace = {namespace:String} AND kind = 'memory' AND item_key = {key:String} - AND content_sha256 = {sha256:String} AND ts >= {since:DateTime} + AND (content_sha256 = {sha256:String} + OR (content_sha256 = '' AND version IN {versions:Array(UInt64)})) + AND ts >= {since:DateTime} AND run_id != '-' GROUP BY run_id ORDER BY first_read ``` +The hash finds only the receipts that carry it. A read of the same stored row whose +receipt has no hash (see [the version and the hash](#the-version-and-the-hash)) is found +by its version: pass the versions, other than 0, that the item's receipts with this hash +name. A row labelled high-sensitivity at every read has no hash in any receipt, so keep +only the version branch for it (an empty `sha256` would match every receipt without a +hash). A redacted row keeps its version, so a receipt without a hash stamped after the +redaction names the row with its text removed. The answer is a lower bound: a read that +left no receipt is not in it. + What a run read: ```sql -SELECT namespace, kind, item_key, version, content_sha256, min(ts) AS first_read +SELECT namespace, kind, item_key, content_sha256, + arraySort(groupUniqArray(version)) AS versions, min(ts) AS first_read FROM loom.read_receipts WHERE org = {org:String} AND run_id = {run:String} AND ts >= {since:DateTime} AND ts < {until:DateTime} -GROUP BY namespace, kind, item_key, version, content_sha256 +GROUP BY namespace, kind, item_key, content_sha256, + if(content_sha256 = '', version, 0) ORDER BY first_read ``` - **Count revisions, not rows.** `request_id` is the caller's when the caller sends one, - so it is not unique, and a request sent again writes its rows again. Group by - `(run_id, kind, namespace, item_key, version, content_sha256)`. -- **Never ask for `run_id = '-'` alone.** It is every read made outside a run. A read by - run prunes by month and org and then tests the bloom filter on what is left. + so it is not unique, and a request sent again writes its rows again. One content can + be recorded under several versions (the row's, its search document's, 0), so group on + the hash where there is one and on the version where there is none, as the statement + above does. +- **Never ask for `run_id = '-'` alone.** It is every read made outside a run. A + statement that filters on a run prunes by month and org and then tests the bloom + filter on what is left. +- **Over MCP, not every read has the session's run.** The session's run labels an op + whose input has a `run_id` field, and `search.query`. A `knowledge.search`, `knowledge.get`, + `memory.get_by_id`, `memory.for_file` or `procedure.match` of the same session is + filed under `-`, as its op ledger row is; find it by `session_id` + ([the receipt row](#the-receipt-row)). - **The query behind a read** is not in a receipt. The exposure row of the same `request_id` in `loom.memory_exposures` carries the query's digest and the keys returned. ## Cost -- **On the request's path**, a note is a dictionary write, and the main fact leg selects - one more column, `content_sha256`, from the search rows it already reads. No read is - added. While receipts are not written, nothing is noted either. +- **On the request's path**, a note is a dictionary write, and the reads that note a + revision select its columns from the rows they already read: `content_sha256` in the + main fact leg; `version`, `content_sha256` and `redacted_at` in the stack's pinned and + recent reads; `version` and `redacted_at` in the file read; `version` in the + governed-definition read. No read is added. While `read_receipts_enabled` is off, + nothing is noted either. - **After the answer**, the op queues its rows. One sender per process waits half a second and sends what has queued in one insert (a waited async insert, [batched inserts](clickhouse.md#batched-inserts)). Receipts therefore hold one pooled @@ -260,13 +329,16 @@ ORDER BY first_read rows; past that an answer's rows are dropped. The client sends an insert again once when its connection drops; an insert that fails after that, or times out, loses its batch, which is not queued again: a store that is down gets no backlog, and a batch - that landed late is not written twice. Each loss is counted and logged at the first, - the tenth, the hundredth occurrence and so on. + that landed late is not written twice. Dropped rows and failed inserts are counted + apart, and each is logged at most once a minute with its total since the process + started ([checking that receipts are written](#checking-that-receipts-are-written)). - **Storage** is about 40 to 60 bytes a row after merges with the server's default compression, up to about 90 where every part is LZ4-compressed. Rows a day are the receipted reads a day times the items an answer carries: 100 reads a second with 5 - items each write 43 million rows a day and hold about 7.8 billion rows, 310 GB at 40 - bytes a row, over the 180 days. + items each write 43 million rows a day and hold about 8.2 billion rows, 330 to 490 GB + at 40 to 60 bytes a row, over the 190 days. Whole monthly parts drop, so the table + peaks a sixth higher, at about 221 days of rows (9.5 billion rows, 380 to 570 GB), + just before a month's parts drop. | Setting | Default | Effect | | ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -283,24 +355,39 @@ GROUP BY operation When reads answer and this returns nothing, the server log says why: -| Log line | Meaning | -| --------------------------------------------------------------- | ------------------------------------------------------------------- | -| `read receipts are not written while a live replica is below …` | An older replica still serves, or no replica heartbeat was read. | -| `read receipts dropped past the queue bound` | The store is slower than the reads; the line carries the rows lost. | -| `read-receipt write failed` | An insert failed; the line carries the count and the error. | - -No line and no rows: `read_receipts_enabled` is off, or the requests run a mirror leg. +| Log line | Meaning | +| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| `read receipts not written: a live replica is older than migration …` | A replica of an older build still serves. The line carries the answers not recorded since the process started. | +| `read receipts not written: no recent read of the replica list` | The process's heartbeat has no recent read of the list of live replicas. The line carries the answers not recorded since the process started. | +| `read receipts dropped past the queue bound` | The store is slower than the reads. The line carries the rows dropped since the process started. | +| `read-receipt write failed` | An insert failed. The line carries the inserts failed since the process started, the rows this insert lost and the error. | +| `read-receipt note failed` | A note raised. The read answered, and that revision was not noted. | +| `read receipts of not recorded` | Building or queueing one answer's receipts raised; the line names the op's handler function. The read answered, and that answer has none. | + +While its cause lasts, each of these is written at most once a minute: a `not written` +line (the two share the minute), the queue-bound line and the failed-insert line. The +last two lines of the table are written each time. No line says that receipts are +written again: rows from the statement above are the sign. + +A heartbeat that read load refuses a connection-pool slot stops receipts while reads +still answer: the heartbeat reads the list of live replicas and waits for a slot as a +read does. When the `no recent read` line repeats and the store answers, the process is +short of pool slots for its read load (`LOOM_CH_POOL_MAXSIZE`, +[statement deadlines](clickhouse.md#statement-classes-deadlines-and-traffic-classes)). + +No line in the last few minutes and no rows: `read_receipts_enabled` is off, or the +requests run a mirror leg. ## Erasure `loom.read_receipts` has a namespace step and a user step, both `read_receipts.delete`, -and a census row in each scope. +and a census row in each scope. A user erasure: ```mermaid flowchart LR A["erasure recorded"] --> B["step: delete every
receipt of the reader"] - B --> C["census: count the reader's receipts
stamped before the erasure was recorded"] - R["the user's later reads"] -.->|"new receipts,
not counted"| C + B --> C["census: count the reader's receipts stamped up to
the second the erasure was recorded in"] + R["the user's reads
after that second"] -.->|"new receipts,
not counted"| C ``` - A namespace erasure deletes the receipts filed under the namespace: the receipts of @@ -312,39 +399,65 @@ flowchart LR `server/erasure/store/predicates.py`). It fails closed when the directory cannot be read. - The user step deletes every receipt of the reader it finds. The census counts the - reader's receipts stamped before the second the erasure was recorded in - (`RECEIPT_READER_BEFORE`, `recorded_scope` in `server/erasure/store/mutations.py`). A - user who keeps reading after asking to be erased writes new receipts; those are later - activity, not what the erasure was asked to delete, so they do not fail it. They - expire with the table, or leave with the user's next erasure. + reader's receipts stamped up to the second the erasure was recorded in + (`RECEIPT_READER_UP_TO`, `recorded_scope` in `server/erasure/store/mutations.py`). A + user who keeps reading after asking to be erased writes new receipts; those stamped + after that second are later activity, not what the erasure was asked to delete, so + they do not fail it. They expire with the table, or leave with the user's next + erasure. A read the user makes later in that second is counted only when its receipt + lands after the step; the erasure then fails once and completes when run again. - A receipt of another reader that names a row the user wrote keeps the key, version and hash until the table's TTL, as the exposure ledger keeps the key. The hash still matches the erased text, so someone who reads the table and guesses the text can - confirm the guess. The hash of a high-sensitivity row is never stored. + confirm the guess. No hash is stored for a row that was labelled high-sensitivity when + it was read. A row labelled after a read keeps that read's hash until the TTL. - Both steps delete with a lightweight `DELETE FROM` in every mode (`LIGHTWEIGHT_PURGE_TABLES` in `server/erasure/store/mutations.py`). A namespace's or a reader's rows sit in every monthly part, so an `ALTER TABLE … DELETE` would rewrite the whole table for one erasure. The rows leave every read at once; their bytes leave at the part's next merge, when the reclaim worker applies the mask, or with the part. - -A receipt is written after the answer. One built by a read that was in flight when an -erasure finished can land after the erasure's census; it holds identifiers and a hash, -and expires with the table. A receipt stamped before a user's erasure was recorded that -lands between the step and the census (its process had not sent it yet, or the store -was slow) is counted: the erasure fails with `loom.read_receipts` in its `residue` and -completes when run again. +- A user erasure reads `user_id` and `actor` of every receipt of the org, which no key + or index narrows to one reader: for the step's count, for its delete when the count is + not zero, and for the census count. The step's count and a user census's counts run + under the DDL deadline + ([statement deadlines](clickhouse.md#statement-classes-deadlines-and-traffic-classes)): + `LOOM_CH_TIMEOUT_DDL_S`, 300 s by default, and the read deadline when that is 0. The + two counts of this table cost about one to three core-minutes per billion receipts of + the org; the delete waits up to `LOOM_ERASURE_MUTATION_WAIT_S`. When a user erasure + fails with `BACKEND_TIMEOUT` at `read_receipts.delete` or at `verify.residue`, raise + that deadline (a restart) and resume the erasure + ([abandoned sagas](../features/memory/retention-and-erasure.md#abandoned-sagas)). + +A receipt is written half a second after its answer at the earliest, and later when its +process stalls or the store is slow. One stamped up to the second a user's erasure was +recorded in that lands between the step and the census is counted: the erasure fails +with `loom.read_receipts` in its `residue` and completes when run again. One that lands +after an erasure's census is neither deleted nor counted, in either scope and whenever +its read answered. The erasure reports `completed` with no residue, and +`loom erasure-re-verify` does not count it. That row holds identifiers and a hash, and +stays until the table's TTL or the next erasure of the same scope. ## Rolling upgrades An older build's erasure saga has no step for `loom.read_receipts`, so the table gains no row while such a replica serves: a receipt is written only when every live replica's schema is at the table's migration or later (`every_live_replica_at` in -`server/core/instances.py`), and none when no heartbeat can be read. The process logs -once that it is not writing. - -Before a rollback to an older build, the operator turns `read_receipts_enabled` off and -runs `TRUNCATE TABLE loom.read_receipts`, and runs it once more after the first older -replica serves, for what this build wrote in between +`server/core/instances.py`). The gate also closes while the process has no recent read +of the list of live replicas: with none, it cannot tell that no older replica serves. +The process's heartbeat reads the list and waits for a connection-pool slot as a read +does, so read load that fills the pool closes the gate while reads still answer. Answers +in that time get no receipt. The process logs which of the two causes closed the gate, +at most once a minute, with the answers not recorded since it started. That line and its +total are the sign +([checking that receipts are written](#checking-that-receipts-are-written)). + +Before a rollback to an older build, the operator turns `read_receipts_enabled` off for +the deployment (`loom settings set read_receipts_enabled false`) and runs +`TRUNCATE TABLE loom.read_receipts SETTINGS max_table_size_to_drop = 0`, and runs it +once more after the first older replica serves, for what this build wrote in between. +Without the setting, ClickHouse refuses to truncate a table above its +`max_table_size_to_drop`, 50 GB by default. Once this build serves alone again, +`loom settings reset read_receipts_enabled` turns receipts back on ([upgrades](../operations/upgrades.md#rollback)). ## Invariants diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 010e3577030..486409b76b8 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1096,8 +1096,9 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline erasure saga has no step for the table. So while any live replica's schema version is below 122, or no heartbeat has been read, N writes no receipt, as it records no miss under rule 48; reads answer as before. Before a rollback, turn - `LOOM_READ_RECEIPTS_ENABLED` off and truncate the table, then truncate it again after - the first N-1 replica serves ([read receipts](read-receipts.md#rolling-upgrades), the + `read_receipts_enabled` off with `loom settings set` and truncate the table, then + truncate it again after the first N-1 replica serves + ([read receipts](read-receipts.md#rolling-upgrades), the [rollback note](../operations/upgrades.md#rollback)). `tests/unit/test_read_receipts.py` checks the gate; the mixed-version gate does not. diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md index a479b5db4df..bbbccbed42c 100644 --- a/docs/architecture/storage-layout.md +++ b/docs/architecture/storage-layout.md @@ -1165,7 +1165,7 @@ it holds no provider identity or credential. | `policy_decisions` | MT `(org, namespace, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | no content | — | policy gate decisions, 90-day TTL; named in `server/identity/store/policy.py` | | `memory_exposures` | MT `(org, namespace, actor, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `memory_exposures.delete`, user scope too | — | which actor was shown which memory, 180-day TTL; named in `server/identity/domain/policy_rules.py`, `server/memory/app/exposure_ledger.py` | | `memory_exposure_breadth_hourly` | AMT `(org, namespace, actor, agent, hour)`, by `toYYYYMM(hour)`, TTL | stays | Derived | no content | — | hourly `uniq` rollup of exposures; named in `server/memory/app/exposure_ledger.py` | -| `read_receipts` | MT `(org, namespace, kind, item_key, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `read_receipts.delete`, user scope too | — | which revision of an item a read's answer carried (version and hash, no content), 180-day TTL; named in `server/memory/store/read_receipts.py`, `server/erasure/store/steps_ledgers.py` | +| `read_receipts` | MT `(org, namespace, kind, item_key, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `read_receipts.delete`, user scope too | — | which revision of an item a read's answer carried (version and hash, no content), 190-day TTL; named in `server/memory/store/read_receipts.py`, `server/erasure/store/steps_ledgers.py` | | `memory_usage_events` | MT `(org, namespace, memory_id, ts)`, by `toYYYYMM(ts)` | stays | Log | census, `memory_usage_events.delete`, user `memory_usage_events.scrub` | — | usage events per memory, an agent's label with its run id and principal; wave 4 puts the pair digest on each `acted` event; named in `server/memory/store/usage.py`, `server/memory/store/usage_credit.py` | | `memory_usage_totals` | SMT `(org, namespace, memory_id)` | stays | Derived | no content | — | `SummingMergeTree` totals per memory fed by `memory_usage_totals_mv` from `memory_usage_events`; named in `server/memory/store/reads.py`, `server/memory/workers/usage_fold.py` | | `memory_served_daily` | SMT `(org, namespace, memory_id, agent, day)`, by `toYYYYMM(day)` | stays | Log | no content | — | served counts per memory, agent and day, inserted directly by the agent read ops (`server/memory/app/served_reads.py`) and summed by `SummingMergeTree`; a log on `SummingMergeTree`, which keeps its layout; named in `server/memory/store/served.py`, `server/memory/app/health.py` | diff --git a/docs/features/memory/retention-and-erasure.md b/docs/features/memory/retention-and-erasure.md index 069e5f21711..f786a5d088a 100644 --- a/docs/features/memory/retention-and-erasure.md +++ b/docs/features/memory/retention-and-erasure.md @@ -154,17 +154,22 @@ those as the writer's too. Chunks stamped with another user stay. A `user_id` erasure deletes the read receipts of reads the user made, and a `namespace` erasure those of the namespace's items ([read receipts](../../architecture/read-receipts.md#erasure)). Three things stay until -the table's 180-day TTL: +the table's 190-day TTL: - another reader's receipt of a row the user wrote, with the row's key, version and - content hash (the hash of a high-sensitivity row is never stored); -- a receipt of a read that was in flight when the erasure finished; -- receipts of reads made from an erased namespace of another namespace's items. + content hash (no hash is stored for a row that was labelled high-sensitivity when it + was read); +- a receipt that lands after the erasure's census: one is written half a second after + its answer at the earliest, and later when its process stalls or the store is slow. + The erasure reports `completed`, and the next erasure of the same scope deletes the + receipt; +- after a `namespace` erasure, receipts of reads its agents made of other namespaces' + items: a receipt is filed under the namespace that holds the item. A user who keeps reading after asking to be erased writes new receipts. The erasure -deletes the receipts it finds and checks those stamped before it was recorded, so the -later reads do not fail it; their receipts expire with the table or leave with the -user's next erasure. +deletes the receipts it finds, and its census counts those stamped up to the second the +erasure was requested in, so reads after that second do not fail it; their receipts +expire with the table or leave with the user's next erasure. A `user_id` erasure also retires the consolidated summaries built from the user's memories, under whatever identity wrote them diff --git a/docs/features/runs.md b/docs/features/runs.md index 4ad6c5ff532..067cdac0a29 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -26,10 +26,12 @@ A run row lives in `loom.agent_runs`. Most of what `run.get` shows is derived at `recalled` is `-1` when `LOOM_SEARCH_TRACE_LOG_ENABLED` is off and no `recalled_keys` were sent. -Which revision of each memory row and document the run's reads carried is kept apart, in +Which revision of a memory row or document a read of the run carried is kept apart, in `loom.read_receipts` under the run's `run_id`, so it can still be told after the item -changes ([read receipts](../architecture/read-receipts.md#reading-the-table)). `run.get` -does not serve it. +changes. Not every read writes a receipt +([what gets none](../architecture/read-receipts.md#what-gets-none)): a missing one means +"not recorded", not "not served". No op serves the table; it is read with SQL +([reading the table](../architecture/read-receipts.md#reading-the-table)). ## Budgets @@ -413,5 +415,5 @@ See [configuration: dedup and expiry](../reference/configuration.md#dedup-and-ex a deciding run relied on. - [Memory architecture](../architecture/memory-architecture.md) — the usage-event fold and the tables behind it. -- [Read receipts](../architecture/read-receipts.md) — the revision of each item a run's - reads carried. +- [Read receipts](../architecture/read-receipts.md) — the revision of an item a run's + read carried. diff --git a/docs/operations/upgrades.md b/docs/operations/upgrades.md index 9b1cd4f6475..8745778472d 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -422,11 +422,18 @@ fed; request again each one run without `purge` once the newer build serves, as An erasure the previous build runs leaves the user's principal and run on the usage labels, or the namespace's usage events; run it again once the newer build serves, as in step 19 (rule 72). -Before rolling back to a build without read receipts, turn `LOOM_READ_RECEIPTS_ENABLED` -off and run `TRUNCATE TABLE .read_receipts` (`loom.read_receipts` by -default), then run it again once the first replica of the previous build serves, for the -rows written in between: that build's erasure has no step for the table -([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 73). +Before rolling back to a build without read receipts, turn `read_receipts_enabled` off +for the deployment (`loom settings set read_receipts_enabled false`, which every replica +applies within `LOOM_RUNTIME_OVERRIDES_REFRESH_SECONDS` and which wins over a replica's +environment) and run +`TRUNCATE TABLE .read_receipts SETTINGS max_table_size_to_drop = 0` +(`loom.read_receipts` by default; without the setting ClickHouse refuses to truncate a +table above its `max_table_size_to_drop`, 50 GB by default), then run it again once the +first replica of the previous build serves, for the rows written in between: that +build's erasure has no step for the table +([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 73). Once the +newer build serves alone again, `loom settings reset read_receipts_enabled` turns +receipts back on. Do not roll back past the build that adds the document bucket while any catalog row names an object in it: an older build answers those downloads `410 BLOB_GONE`, its erasure deletes the rows and cannot reach their objects, and its sweep never walks the diff --git a/schemas/migrations/122_read_receipts.sql b/schemas/migrations/122_read_receipts.sql index fd0fa72f798..62baaf26562 100644 --- a/schemas/migrations/122_read_receipts.sql +++ b/schemas/migrations/122_read_receipts.sql @@ -6,8 +6,9 @@ -- under the namespace that holds the item, so one read over several namespaces writes -- under each. Sorted by item: an item's reads are one primary-key range, filtered by -- revision, and the bloom index serves "what was this run served". A trace that expires --- after 180 days; whole monthly parts drop, so a row can outlive that by the rest of --- its month. Erased per namespace and per user (user_id or actor). +-- after 190 days, so every row is kept at least six calendar months (184 days at +-- most); whole monthly parts drop, so a row can outlive that by the rest of its +-- month. Erased per namespace and per user (user_id or actor). CREATE TABLE IF NOT EXISTS loom.read_receipts ( `ts` DateTime DEFAULT now(), @@ -34,7 +35,7 @@ CREATE TABLE IF NOT EXISTS loom.read_receipts -- The reader: the token's subject and id, and the identity tuple it read as. `actor` String DEFAULT '', `token_id` String DEFAULT '', - `agent` LowCardinality(String) DEFAULT '', + `agent` LowCardinality(String) DEFAULT '-', `user_id` String DEFAULT '-', `session_id` String DEFAULT '-', INDEX run_id_bloom_idx run_id TYPE bloom_filter(0.01) GRANULARITY 1, @@ -45,5 +46,5 @@ CREATE TABLE IF NOT EXISTS loom.read_receipts ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (org, namespace, kind, item_key, ts) -TTL ts + INTERVAL 180 DAY +TTL ts + INTERVAL 190 DAY SETTINGS non_replicated_deduplication_window = 1000, ttl_only_drop_parts = 1; diff --git a/server/core/hashing.py b/server/core/hashing.py index 019d9165d5c..ad8d91e94cb 100644 --- a/server/core/hashing.py +++ b/server/core/hashing.py @@ -11,8 +11,9 @@ caller can drift. The text forms those hashes and comparisons read live here too: `canonical_document_text` -for documents and chunks, and `query_text` and `valid_unicode` for a query, which the -knowledge-gap grouping and the term leg read alike. +for documents and chunks, `query_text` and `valid_unicode` for a query, which the +knowledge-gap grouping and the term leg read alike, and `as_valid_unicode` for text a +store or a printed line must be able to encode. """ from __future__ import annotations @@ -113,6 +114,12 @@ def valid_unicode(text: str) -> bool: return True +def as_valid_unicode(text: str) -> str: + """`text` with each lone surrogate (JSON can hold one; UTF-8 cannot) as `?`, so + `valid_unicode` holds of it.""" + return text.encode("utf-8", "replace").decode("utf-8") + + def sha256_document_text(text: str) -> str: """The `content_sha256` of a loom.documents / loom.chunks row: hex SHA-256 of the canonicalized text. Empty in → empty out (callers short-circuit diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py index a7a8bd7ac8d..9fa754c5f11 100644 --- a/server/erasure/store/census.py +++ b/server/erasure/store/census.py @@ -11,6 +11,7 @@ from __future__ import annotations +import contextlib import json import logging from collections.abc import Mapping, Sequence @@ -18,6 +19,7 @@ from typing import Any from server.core import object_store, pg +from server.core.ch import class_timeout_s, statement_timeout from server.core.repo_base import _CHClient, _default_client from server.erasure.store.mutations import ( namespaces_of, @@ -33,7 +35,7 @@ NS_EQ, ORPHAN_LEARNINGS, PAYLOAD_UID, - RECEIPT_READER_BEFORE, + RECEIPT_READER_UP_TO, UID, USER_CHUNKS, USER_COMMUNITY_ROWS, @@ -333,11 +335,11 @@ def owner(self, scope_type: str) -> str | None: ), # Which revision of an item a read's answer carried: the namespace's items, and in # the user scope the reads the user made (as the end user or the token's subject) - # before the erasure was recorded. The user's later calls keep adding rows. + # up to the second the erasure was recorded in. The user's later calls keep adding rows. Substrate( "loom.read_receipts", "1", - RECEIPT_READER_BEFORE, + RECEIPT_READER_UP_TO, "read_receipts.delete", "read_receipts.delete", ), @@ -1006,7 +1008,7 @@ async def table_residue( # and the principals the user's usage labels carry (`LABEL_ACTOR`). params["spellings"] = list(spellings) params["label_actors"] = label_actors(spellings) - # Where the count of the user's read receipts stops (`RECEIPT_READER_BEFORE`). + # Where the count of the user's read receipts stops (`RECEIPT_READER_UP_TO`). params["recorded_at"] = recorded_at() out: dict[str, int] = {} # A purge leaves nothing behind, so its census counts every row, not the @@ -1025,16 +1027,29 @@ async def table_residue( if purge: live = "1" final = " FINAL" if live != "1" and sub.final else "" - row = await ch.query_one( - f"SELECT count() AS n FROM {table}{final} " - f"WHERE org = {{org:String}} AND {pred} AND {live}", - params=params, - ) + with _count_deadline(scope_type): + row = await ch.query_one( + f"SELECT count() AS n FROM {table}{final} " + f"WHERE org = {{org:String}} AND {pred} AND {live}", + params=params, + ) out[table] = int((row or {}).get("n") or 0) out.update(await copy_residue(org, scope_type, scope_value, ch=ch)) return out +def _count_deadline(scope_type: str) -> contextlib.AbstractContextManager[None]: + """The deadline one table's count runs under. Few sort keys order a user's rows, so a + user-scope count can read every row the org has in a table, and `loom.read_receipts` + has one for each item a read served: it takes the DDL class's deadline, as a step's + delete does, where the read deadline would fail the census of a large org. With + `ch_timeout_ddl_s` 0 the scope sets nothing and the read deadline stands. A + namespace's count keeps the read deadline.""" + if scope_type == "namespace": + return contextlib.nullcontext() + return statement_timeout(class_timeout_s("ddl")) + + async def evidence_census( org: str, scope_type: str, diff --git a/server/erasure/store/mutations.py b/server/erasure/store/mutations.py index 98d6cec37cd..b0a923551ba 100644 --- a/server/erasure/store/mutations.py +++ b/server/erasure/store/mutations.py @@ -232,7 +232,7 @@ async def run_mutation( # (`vertical_merge_optimize_lightweight_delete`). The narrow tables keep the # mutation: their rewrite is cheap and their bytes matter less. # `read_receipts` is narrow but large, and one reader's rows sit in every monthly -# part: the mutation rewrote all of a 24M-row table for 7,000 of its rows. +# part, so a mutation rewrites the whole table for one erasure. LIGHTWEIGHT_PURGE_TABLES: frozenset[str] = frozenset( { "loom.read_receipts", diff --git a/server/erasure/store/predicates.py b/server/erasure/store/predicates.py index 3f5d59db7d8..7590523b814 100644 --- a/server/erasure/store/predicates.py +++ b/server/erasure/store/predicates.py @@ -198,10 +198,12 @@ "(has({spellings:Array(String)}, lowerUTF8(user_id))" " OR has({spellings:Array(String)}, lowerUTF8(actor)))" ) -# What a census counts of them: the reads stamped before the second the erasure was -# recorded in (`mutations.recorded_at`). The step deletes every one it finds; a user who -# is still reading writes more behind it, and those are not the erasure's to delete. -RECEIPT_READER_BEFORE = f"({RECEIPT_READER} AND ts < {{recorded_at:DateTime}})" +# What a census counts of them: the reads stamped up to the second the erasure was +# recorded in (`mutations.recorded_at`). That second counts: `ts` holds whole seconds, and +# a read answered earlier in it came before the erasure. The step deletes every one it +# finds; a user who is still reading writes more behind it, and those are not the +# erasure's to delete. +RECEIPT_READER_UP_TO = f"({RECEIPT_READER} AND ts <= {{recorded_at:DateTime}})" # A usage label the user posted: its principal (`actor`, stamped case-folded) is one of # `label_actors(spellings)`. An exact match, so `actor_bloom_idx` serves it. LABEL_ACTOR = "actor IN {label_actors:Array(String)}" diff --git a/server/erasure/store/steps_ledgers.py b/server/erasure/store/steps_ledgers.py index 85cffadfee5..0674dfbe5cb 100644 --- a/server/erasure/store/steps_ledgers.py +++ b/server/erasure/store/steps_ledgers.py @@ -11,7 +11,7 @@ from typing import Any from server.core import lease_writes, leases, rmt_carry -from server.core.ch import sequential_reads +from server.core.ch import class_timeout_s, sequential_reads, statement_timeout from server.core.ch_params import chunks from server.core.errors import BackendUnavailableError from server.core.lease_writes import fenced @@ -242,14 +242,19 @@ async def delete_read_receipts_by_user( ) -> int: """The receipts of reads made under any of `spellings`, the user's id and its other spellings.""" - return await delete_scoped( - "loom.read_receipts", - org=org, - scope_where=RECEIPT_READER, - params={"spellings": list(spellings)}, - ch=ch, - lightweight=True, - ) + # The sort key does not order a reader's rows, so the step's count reads every receipt + # of the org: it takes the DDL class's deadline, as the delete after it does, where + # the read deadline would fail the step on a large org. With `ch_timeout_ddl_s` 0 the + # scope sets nothing and the read deadline stands. + with statement_timeout(class_timeout_s("ddl")): + return await delete_scoped( + "loom.read_receipts", + org=org, + scope_where=RECEIPT_READER, + params={"spellings": list(spellings)}, + ch=ch, + lightweight=True, + ) # The usage ledger: counts by memory id and, on an agent's label, the run id and the diff --git a/server/memory/api/models_context.py b/server/memory/api/models_context.py index 5f26b58c8a4..f2d433b8ed5 100644 --- a/server/memory/api/models_context.py +++ b/server/memory/api/models_context.py @@ -127,6 +127,9 @@ class ContextPackOutput(BaseModel): # The (namespace, memory_key) of each stored row whose item line `rendered` still # holds, which the op records as served to the agent. Private, never on the wire. _served_rows: list[tuple[str, str]] = PrivateAttr(default_factory=list) + # The same rows as a read receipt records them (`read_receipts.Item`): a row printed + # from a search hit at that hit's version. Private, never on the wire. + _served_items: list[Any] = PrivateAttr(default_factory=list) # The pack as one text: each non-empty section in a `` tag, in block order, # cut to `token_budget`. diff --git a/server/memory/api/models_loom_search.py b/server/memory/api/models_loom_search.py index 479e20334e3..a34edeaad86 100644 --- a/server/memory/api/models_loom_search.py +++ b/server/memory/api/models_loom_search.py @@ -15,6 +15,7 @@ BaseModel, ConfigDict, Field, + PrivateAttr, SerializerFunctionWrapHandler, StrictBool, model_serializer, @@ -93,6 +94,11 @@ class SearchOutput(BaseModel): defect report; `withheld` counts what the answer-first rules held back and why.""" + # The search models of `memory.results`, in their order. A dumped row has lost the + # stored version its text came from, which the read receipt records. Private, never + # on the wire. + _memory_hits: list[Any] = PrivateAttr(default_factory=list) + @model_serializer(mode="wrap") def _drop_absent_sections(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: data: dict[str, Any] = handler(self) diff --git a/server/memory/api/ops_context.py b/server/memory/api/ops_context.py index 26b6c3e037a..d1fdd6ae96f 100644 --- a/server/memory/api/ops_context.py +++ b/server/memory/api/ops_context.py @@ -4,7 +4,7 @@ from server.memory.api.models_context import ContextPackInput, ContextPackOutput from server.memory.app.context_pack import handle_context_pack -from server.memory.app.read_receipts import memory_rows, records_receipts +from server.memory.app.read_receipts import pack_items, records_receipts from server.memory.app.served_reads import records_served, rendered_rows from server.operations.base import Operation, Role @@ -13,9 +13,7 @@ session_content=True, input_model=ContextPackInput, output_model=ContextPackOutput, - handler=records_served(rendered_rows)( - records_receipts(memory_rows(rendered_rows))(handle_context_pack) - ), + handler=records_served(rendered_rows)(records_receipts(pack_items)(handle_context_pack)), idempotent=True, required_role=Role.VIEWER, audit=False, diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index 030e9d8ae12..23629bde257 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -32,7 +32,7 @@ from server.memory.api.models_search import MemorySearchInput from server.memory.api.models_working_memory import WorkingMemoryRenderInput from server.memory.app.provenance import writer_actor -from server.memory.app.read_receipts import note_row +from server.memory.app.read_receipts import hit_item, note_row from server.memory.domain import code_change, session_change from server.memory.domain.context_layout import ( _BLOCK_LABELS, @@ -58,6 +58,7 @@ from server.memory.domain.decision_statement import states_reason from server.memory.domain.evidence_pack import EvidenceItem, pack_evidence from server.memory.domain.memory_types import excluded_from_unfiltered_search +from server.memory.domain.read_receipts import MEMORY, Item from server.memory.domain.search_types import SHARED_AGENT, hit_row, hit_row_key, names_row from server.observability import degradations @@ -223,6 +224,9 @@ class _PackState: # order; None for an item that is no stored row. The rows whose line the rendered pack # still holds are what the op records as served (`served_rows`). item_rows: dict[str, list[tuple[str, str] | None]] = field(default_factory=dict) + # Beside `item_rows`, what a read receipt records for each item line: the row by its + # key, or at the version of the search hit the line was printed from. + item_receipts: dict[str, list[Item | None]] = field(default_factory=dict) # The sections the request's `deadline_ms` stopped (`ContextPackOutput.partial`). cut: list[str] = field(default_factory=list) @@ -235,12 +239,20 @@ def put( source_count: int = 0, extra_meta: dict[str, Any] | None = None, rows: list[tuple[str, str] | None] | None = None, + receipts: list[Item | None] | None = None, ) -> None: + """`receipts` names each of `rows` at the version its line was printed from; a + section that passes none names its rows by key, for the notes of its read.""" input = self.input default_section_tokens = self.default_section_tokens if not body: return self.item_rows[name] = list(rows or []) + self.item_receipts[name] = ( + [Item(MEMORY, *row) if row else None for row in self.item_rows[name]] + if receipts is None + else list(receipts) + ) if name in RECALLED_SECTIONS: body = escape_data(body) trimmed, was_truncated = _trim( @@ -720,8 +732,10 @@ async def _pack_decisions_from_hits( "\n".join(lines), citations=citations, # An abstaining search's rows are no answer: the answer marks them so, and a - # client drops them (the prompt-recall hook does), so none counts as served. + # client drops them (the prompt-recall hook does), so none counts as served. The + # text still prints them, so each has its receipt. rows=None if abstained else [hit_row(h, input.namespace) for h in decision_hits], + receipts=[hit_item(h, input.namespace) for h in decision_hits], source_count=len(decision_hits), ) @@ -845,12 +859,17 @@ async def _pack_memories(st: _PackState) -> None: # Keep relevance (rank) order in the packed block; the event # date rides each line as a label, not as a sort key. ) + # Two rows of one key share a citation and one is printed: the receipt names that + # one, at its own version. + hit_behind = {id(item): h for item, h in zip(evidence, hits, strict=True)} + printed = [hit_item(hit_behind[id(item)], input.namespace) for item in packed.kept] st.put( "memories", packed.rendered, citations=packed.citations, # see _pack_decisions_from_hits: an abstaining search shows no answer rows=None if out.abstain else [row_of[c] for c in packed.citations], + receipts=printed, source_count=packed.source_count, extra_meta={ "evidence_groups": packed.groups, @@ -1181,6 +1200,7 @@ def _clone_pack(prefix: _PackState) -> _PackState: shown_procedures=list(prefix.shown_procedures), withheld_procedures=list(prefix.withheld_procedures), item_rows={name: list(rows) for name, rows in prefix.item_rows.items()}, + item_receipts={name: list(items) for name, items in prefix.item_receipts.items()}, cut=list(prefix.cut), ) @@ -1252,7 +1272,9 @@ def _render_checked_pack( f"deadline {input.deadline_ms} ms: {', '.join(st.cut)} not finished" if st.cut else "" ), ) - out._served_rows = served_rows(rendered, [name for name, _ in present], st.item_rows) + shown = [name for name, _ in present] + out._served_rows = served_rows(rendered, shown, st.item_rows) + out._served_items = served_rows(rendered, shown, st.item_receipts) return out diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index 3029fd95872..6d63afa2300 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -14,6 +14,7 @@ from server.code.domain.anchor import local_name, names_symbol from server.core.ch import get_client, statement_timeout from server.core.datetimes import naive_utc_now +from server.core.hashing import as_valid_unicode from server.core.repo_base import query_all_sliced from server.memory.api.models_for_file import ( MemoryForFileInput, @@ -145,7 +146,7 @@ def value_text(hit: dict[str, Any]) -> str: value = json.loads(raw) except ValueError: return raw # memory.set always stores JSON; any other text prints as stored - return _encodable( + return as_valid_unicode( value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) ) if not raw.startswith('"'): @@ -159,15 +160,10 @@ def value_text(hit: dict[str, Any]) -> str: # A cut between the two escapes of a surrogate pair leaves half of one. text = text[:-1] if text and "\ud800" <= text[-1] <= "\udbff" else text # Escaped text decodes to far fewer characters than the line holds: mark the cut. - return _encodable(text.rstrip()) + "…" + return as_valid_unicode(text.rstrip()) + "…" return raw -def _encodable(text: str) -> str: - """`text` with any lone surrogate (JSON can hold one; UTF-8 cannot) as `?`.""" - return text.encode("utf-8", "replace").decode("utf-8") - - def _one_line(text: str, limit: int) -> str: flat = " ".join(str(text).split()) return flat if len(flat) <= limit else flat[: limit - 1].rstrip() + "…" diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index fc78dcc896e..0cb97b8fd66 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -509,9 +509,16 @@ async def search_sections( settled.query, label_namespace=label, ) + payload[SERVED_MEMORY_HITS] = _served_models(payload, models) return payload +# The key `search_sections` returns the search models of the served memory rows under. +# It is no section of the answer: the op's handler takes it off the payload and keeps the +# models on the output (`SearchOutput._memory_hits`). +SERVED_MEMORY_HITS = "_memory_hits" + + def _clear_governed_hints_and_dump(result: MemorySearchOutput) -> dict[str, Any]: """Empty, on `result`'s own models, the `next` of each governed definition cut to the body budget, then dump `result`. That `next` names memory.search with the same diff --git a/server/memory/app/loom_search/handler.py b/server/memory/app/loom_search/handler.py index 674b2787bfa..570d11e6589 100644 --- a/server/memory/app/loom_search/handler.py +++ b/server/memory/app/loom_search/handler.py @@ -18,7 +18,7 @@ SearchInput, SearchOutput, ) -from server.memory.app.loom_search.fanout import search_sections +from server.memory.app.loom_search.fanout import SERVED_MEMORY_HITS, search_sections from server.memory.app.loom_search.tracker_leg import prepare_tracker_search from server.observability import degradations @@ -101,7 +101,10 @@ async def handle_search(input: SearchInput) -> SearchOutput: ] ) _record_gap_miss(input, payload, repo_namespace or "") - return SearchOutput.model_validate(payload) + served = payload.pop(SERVED_MEMORY_HITS, []) + out = SearchOutput.model_validate(payload) + out._memory_hits = served + return out finally: if live_task is not None and not live_task.done(): live_task.cancel() diff --git a/server/memory/app/read_receipts.py b/server/memory/app/read_receipts.py index 13854d74c93..f3f9068928d 100644 --- a/server/memory/app/read_receipts.py +++ b/server/memory/app/read_receipts.py @@ -30,15 +30,16 @@ import asyncio import functools import logging +import time from collections.abc import Awaitable, Callable, Iterable, Mapping from contextvars import ContextVar from typing import Any, Protocol from server.core import instances, request_work from server.core.diagnostics import public_diagnostics +from server.core.hashing import as_valid_unicode from server.core.naming import is_reserved_name, named from server.memory.app import after_write -from server.memory.app.log_once import LogOnce from server.memory.app.served_reads import reader from server.memory.domain.read_receipts import ( DOCUMENT, @@ -71,9 +72,15 @@ _SEND_INTERVAL_S = 0.5 # not a setting: the insert rate the design page states follows from it _queued: list[dict[str, Any]] = [] _sender: asyncio.Task[Any] | None = None -_dropped = 0 # rows, ever -_failed = 0 # inserts, ever -_GATE_LOGGED = LogOnce() +# What the process did not record since it started. Only its log lines report these, so +# each line carries its total and two lines subtract to the loss between them. +_unrecorded = 0 # answers, while the replica gate was closed +_dropped = 0 # rows, past the queue bound +_failed = 0 # inserts +# Each kind of loss (closed gate, queue bound, failed insert) is logged at most this +# often, so an incident shows whenever it starts and a long one does not fill the log. +_LOG_EVERY_S = 60.0 # not a setting: how often a log line repeats, not what is recorded +_logged_at: dict[str, float] = {} # The sender outlives the request that started it; the tag names its inserts. SEND_QUERY_TAG = "memory.read_receipts" @@ -200,9 +207,9 @@ def wrap[I, O](handler: Callable[[I], Awaitable[O]]) -> Callable[[I], Awaitable[ async def handle(input: I) -> O: # Through `__wrapped__` (the handler, set by functools.wraps), so a test can # stand in the answer of a registered op and check what the op records. - if _notes.get() is not None or not _recording(): + if _notes.get() is not None or not settings.read_receipts_enabled: # Inside a receipted op, that op writes what its own answer carries. - # While nothing is written, nothing is noted either. + # While the setting is off, nothing is noted either. return await handle.__wrapped__(input) notes: Notes = {} token = _notes.set(notes) @@ -220,22 +227,42 @@ async def handle(input: I) -> O: return wrap -def _recording() -> bool: - """Whether this process writes receipts now: the switch is on and every live replica - can erase them. Read when an op starts.""" - if not settings.read_receipts_enabled: - return False +def _replicas_can_erase() -> bool: + """Whether every live replica can erase a receipt, so an answer's rows may be written. + Asked for an answer that has rows: one refused is counted, and logged with its cause.""" + global _unrecorded if instances.every_live_replica_at(store.MIGRATION): return True - if _GATE_LOGGED.first("replicas"): + _unrecorded += 1 + if not _log_due("gate"): + return False + if instances.live_rows(): log.warning( - "read receipts are not written while a live replica is below migration %d " - "or no replica heartbeat was read", + "read receipts not written: a live replica is older than migration %d " + "(answers not recorded since the process started: %d)", store.MIGRATION, + _unrecorded, + ) + else: + # The process's own heartbeat reads the list, and waits for a pool slot as a + # read does: a read load can close the gate while the store answers. + log.warning( + "read receipts not written: no recent read of the replica list " + "(answers not recorded since the process started: %d)", + _unrecorded, ) return False +def _log_due(kind: str) -> bool: + """Whether a loss of `kind` is logged now: at most one line a minute for each kind.""" + now = time.monotonic() + if now - _logged_at.get(kind, float("-inf")) < _LOG_EVERY_S: + return False + _logged_at[kind] = now + return True + + def _record(name: str, input: Any, out: Any, items_of: ItemsOf | None, notes: Notes) -> None: """Queue the receipts of one answer. Never raises: a receipt must not fail a read.""" try: @@ -247,8 +274,8 @@ def _record(name: str, input: Any, out: Any, items_of: ItemsOf | None, notes: No # The table refuses a row under a mirror's or a code store's name, and with it # every row of its insert. served = [(item, noted) for item, noted in served if not is_reserved_name(item.namespace)] - if served: - _enqueue(store.build_rows(_reader(input), served)) + if served and _replicas_can_erase(): + _enqueue(store.build_rows(_request_reader(input), served)) except Exception as e: # noqa: BLE001 — a receipt must not fail the read log.warning("read receipts of %s not recorded (non-fatal): %s", name, e) @@ -258,15 +285,17 @@ def _enqueue(rows: list[dict[str, Any]]) -> None: global _dropped, _sender if len(_queued) + len(rows) > _MAX_QUEUED_ROWS: _dropped += len(rows) - if _worth_logging(_dropped, len(rows)): - log.warning("read receipts dropped past the queue bound: %d rows", _dropped) + if _log_due("queue"): + log.warning( + "read receipts dropped past the queue bound " + "(rows dropped since the process started: %d)", + _dropped, + ) return _queued.extend(rows) # A sender left on a closed loop is never done and never sends. if _sender is None or _sender.done() or _sender.get_loop().is_closed(): _sender = after_write.schedule(_send_queued(), name=SEND_QUERY_TAG, detached=True) - if _sender is None: # no running loop: built, not written - _queued.clear() async def _send_queued() -> None: @@ -285,33 +314,30 @@ async def _send_queued() -> None: await store.insert(rows) except Exception as e: # noqa: BLE001 — a receipt must not fail a read _failed += 1 - if _worth_logging(_failed): + if _log_due("insert"): log.warning( - "read-receipt write failed (non-fatal; %d failed, %d rows lost now): %s", + "read-receipt write failed (non-fatal; inserts failed since the " + "process started: %d, rows lost now: %d): %s", _failed, len(rows), e, ) -def _worth_logging(count: int, step: int = 1) -> bool: - """Whether a counter that just rose by `step` to `count` passed a power of ten: the - first is logged, then the 10th, the 100th and so on.""" - return any(count - step < 10**n <= count for n in range(len(str(count)))) - - def _reset_for_tests() -> None: - """Drop the queued rows and forget the sender and the counters (test seam).""" - global _sender, _dropped, _failed + """Drop the queued rows and forget the sender, the counters and when each kind of + loss was logged (test seam).""" + global _sender, _unrecorded, _dropped, _failed _queued.clear() - _sender, _dropped, _failed = None, 0, 0 + _logged_at.clear() + _sender, _unrecorded, _dropped, _failed = None, 0, 0, 0 -def _reader(input: Any) -> store.Reader: +def _request_reader(input: Any) -> store.Reader: """Who read, from the request: the token's subject and id, the agent the read counts as, the user and session it read as, the run and the op the caller invoked. The user and session are the input's, else the token's read scope, else what the request named - to the transport (a document op's input has neither).""" + to the transport (not every op's input has them: a document op's has neither).""" from server.auth.context import current_auth from server.core.logging_config import request_id_var from server.identity.app.request_scope import request_scope @@ -323,25 +349,29 @@ def _reader(input: Any) -> store.Reader: named_to_transport = request_identity() subject = str(getattr(auth, "subject", "") or "") # A transport traces a request that names no user under the token's subject. That is - # `actor` here: a read made as no end user says so. + # `actor` here: a read made as no end user says so. A request that names the token's + # own subject as its user, on an op whose input has no `user_id`, is filed under `-` + # too: the two are one string when the receipt is built. traced_user = named(named_to_transport.get("user_id")) + # The caller names the run, agent, user and session, and JSON can carry a lone + # surrogate: an insert cannot encode one, and fails with every row it carries. return store.Reader( org=str(input.org), operation=current_operation(), request_id=request_id_var.get() or "", # The run the op ledger and the exposure ledger file this request under, so # the three join on it: the request's own `run_id`, else the run bound to it. - run_id=ledger_run_for(getattr(input, "run_id", None)), + run_id=as_valid_unicode(ledger_run_for(getattr(input, "run_id", None))), actor=subject, token_id=str(getattr(auth, "token_id", "") or ""), - agent=reader(input) or named(named_to_transport.get("agent")) or "", - user_id=( + agent=as_valid_unicode(reader(input) or named(named_to_transport.get("agent")) or ""), + user_id=as_valid_unicode( named(getattr(input, "user_id", None)) or scope.user_id or (traced_user if traced_user != subject else None) or "" ), - session_id=( + session_id=as_valid_unicode( named(getattr(input, "session_id", None)) or scope.session_id or named(named_to_transport.get("session_id")) @@ -362,11 +392,12 @@ def _field(hit: Any) -> Callable[[str], Any]: return hit.get if isinstance(hit, dict) else lambda name: getattr(hit, name, None) -def _hit_item(hit: Any, namespace: str) -> Item | None: +def hit_item(hit: Any, namespace: str) -> Item | None: """The stored row a search hit is, at the version the hit carries (none when the hit carries none); a chunk hit is its parent row at version 0 (the read held the passage, not the row). None for a hit of another plane (a summary, a record, a computed row): - it is no stored memory row.""" + it is no stored memory row. `hit` is the search's own model: a dumped hit has lost + the private version.""" get = _field(hit) source = str(get("source") or "fact") if source == _PASSAGE_SOURCE: @@ -383,7 +414,7 @@ def _hit_item(hit: Any, namespace: str) -> Item | None: def _hit_items(hits: Iterable[Any], namespace: str) -> list[Item]: - return [item for hit in hits if (item := _hit_item(hit, namespace)) is not None] + return [item for hit in hits if (item := hit_item(hit, namespace)) is not None] def _document_items(hits: Iterable[Any], namespace: str) -> list[Item]: @@ -416,10 +447,18 @@ def brief_items(input: Any, out: Any) -> list[Item]: def search_query_items(input: Any, out: Any) -> list[Item]: - """search.query: the hits its memory and knowledge sections kept.""" - memory = [h for h in (out.memory or {}).get("results") or [] if isinstance(h, dict)] + """search.query: the hits its memory and knowledge sections kept. The memory hits are + the search's models (`_memory_hits`), not the section's dumped rows.""" knowledge = [h for h in (out.knowledge or {}).get("results") or [] if isinstance(h, dict)] - return _hit_items(memory, input.namespace) + _document_items(knowledge, input.namespace) + return _hit_items(out._memory_hits, input.namespace) + _document_items( + knowledge, input.namespace + ) + + +def pack_items(input: Any, out: Any) -> list[Item]: + """context.pack: the rows its `rendered` answer prints (`_served_items`): one a search + hit was printed from at that hit's version, any other by its key.""" + return list(out._served_items) def knowledge_items(input: Any, out: Any) -> list[Item]: diff --git a/server/memory/domain/context_layout.py b/server/memory/domain/context_layout.py index 58919083db6..45e1573981b 100644 --- a/server/memory/domain/context_layout.py +++ b/server/memory/domain/context_layout.py @@ -274,20 +274,21 @@ def _own_bookmark(block: Any, mine: str) -> bool: STACK_ROW_LAYERS = frozenset({"pinned", "recent_recall", "procedure"}) -def served_rows( +def served_rows[Row]( rendered: str, section_names: list[str], - item_rows: dict[str, list[tuple[str, str] | None]], -) -> list[tuple[str, str]]: - """The stored rows the rendered pack shows. `rendered` is the answer every caller + item_rows: dict[str, list[Row | None]], +) -> list[Row]: + """The stored rows the rendered pack shows, as `item_rows` names each: its (namespace, + key), or the item a read receipt records for it. `rendered` is the answer every caller gets (MCP's lean pack carries it alone); `sections` and `blocks` keep lines the pack's own budget cut, so a row counts only where `rendered` holds it. What a client then - discards is its own; a section the answer marks as no answer records no rows (see - `_pack_memories`). Each section's item lines start with `- ` (`one_item` indents a + discards is its own; a section the answer marks as no answer names no served row and + still names its receipts (see `_pack_memories`). Each section's item lines start with `- ` (`one_item` indents a continuation), in the order of its `item_rows`; a trim keeps a prefix, so the first n rows of a section whose n item lines `rendered` still holds were shown, a cut one included. `section_names` are the present sections in pack order.""" - shown: list[tuple[str, str]] = [] + shown: list[Row] = [] cursor = 0 for name in section_names: start = rendered.find(f"<{name}>\n", cursor) @@ -297,6 +298,6 @@ def served_rows( end = rendered.find(f"\n", start) end = len(rendered) if end < 0 else end lines = sum(1 for line in rendered[start:end].split("\n") if line.startswith("- ")) - shown += [row for row in item_rows.get(name, [])[:lines] if row] + shown += [row for row in item_rows.get(name, [])[:lines] if row is not None] cursor = end return shown diff --git a/server/memory/domain/evidence_pack.py b/server/memory/domain/evidence_pack.py index effd672e3b5..393844a4a39 100644 --- a/server/memory/domain/evidence_pack.py +++ b/server/memory/domain/evidence_pack.py @@ -60,6 +60,9 @@ class PackedEvidence: source_count: int truncated: bool groups: list[str] = field(default_factory=list) + # The item printed for each of `citations`, in their order: of the items that share a + # citation one is printed. + kept: list[EvidenceItem] = field(default_factory=list) def _trim(text: str, char_budget: int) -> tuple[str, bool]: @@ -154,7 +157,7 @@ def pack_evidence( ordered = primary + overflow lines: list[str] = [] - citations: list[str] = [] + kept: list[EvidenceItem] = [] groups: list[str] = [] truncated = False served: list[str] = [] @@ -170,7 +173,7 @@ def pack_evidence( lines.append(line) served.append(_state(item)) changed = changed or bool(item.changed_in) - citations.append(item.citation) + kept.append(item) if group not in groups: groups.append(group) lines[:0] = _opening(served, changed) @@ -178,8 +181,9 @@ def pack_evidence( rendered, trim_truncated = _trim("\n".join(lines), char_budget) return PackedEvidence( rendered=rendered, - citations=citations, - source_count=len(citations), + citations=[item.citation for item in kept], + source_count=len(kept), truncated=truncated or trim_truncated, groups=groups, + kept=kept, ) diff --git a/server/memory/store/read_receipts.py b/server/memory/store/read_receipts.py index 5bb690d1541..f66c2268e64 100644 --- a/server/memory/store/read_receipts.py +++ b/server/memory/store/read_receipts.py @@ -8,7 +8,8 @@ from typing import Any from server.core.ch_writes import async_insert_settings -from server.core.datetimes import naive_utc_now +from server.core.datetimes import naive_utc_now_seconds +from server.core.naming import SENTINEL, named from server.core.repo_base import _CHClient from server.memory.domain.read_receipts import Item, Noted @@ -17,8 +18,6 @@ # The migration that adds the table; an older replica's erasure has no step for it. MIGRATION = 122 # tests/unit/test_read_receipts.py ties it to the file -_SENTINEL = "-" - @dataclass(frozen=True) class Reader: @@ -37,7 +36,7 @@ class Reader: def build_rows(reader: Reader, served: Sequence[tuple[Item, Noted]]) -> list[dict[str, Any]]: """The rows of one answer: each item under the namespace that holds it.""" - now = naive_utc_now().replace(microsecond=0) + now = naive_utc_now_seconds() return [ { "ts": now, @@ -51,12 +50,12 @@ def build_rows(reader: Reader, served: Sequence[tuple[Item, Noted]]) -> list[dic "chunk_idx": int(item.chunk_idx), "operation": reader.operation, "request_id": reader.request_id, - "run_id": reader.run_id or _SENTINEL, + "run_id": reader.run_id or SENTINEL, "actor": reader.actor, "token_id": reader.token_id, - "agent": reader.agent, - "user_id": reader.user_id or _SENTINEL, - "session_id": reader.session_id or _SENTINEL, + "agent": named(reader.agent, wildcard=True) or SENTINEL, + "user_id": reader.user_id or SENTINEL, + "session_id": reader.session_id or SENTINEL, } for item, noted in served ] diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 066a50e4ac4..97480a9efb8 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -3957,9 +3957,9 @@ class MemorySearchSettings(BaseModel): # (token subject, returned keys, query digest never the text, scope) plus # an hourly per-actor roll-up. Carries no user content. memory_exposure_ledger_enabled: Annotated[bool, LIVE] = True - # Read receipts in loom.read_receipts: one row per memory row or document an agent - # read's answer carried, with the revision the read held (version and hash, never - # content or query text). Off stops new rows; stored ones expire by the table's TTL. + # Read receipts in loom.read_receipts: one row per memory row or document chunk a read's + # answer carried, with the revision the read held (version and hash, never content or + # query text). Off stops new rows; stored ones expire by the table's TTL. read_receipts_enabled: Annotated[bool, LIVE] = True # Cosine floor: hits below it are dropped as noise (ANN always returns # top_k). The backstop when rerank is bypassed or fails. diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 84d71664a61..bfb84261942 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -559,8 +559,8 @@ async def test_a_user_who_keeps_reading_is_still_erased( control_plane_url: str, ch_client: Any, admin: Any ) -> None: """Each read the user makes while the saga runs writes a receipt behind its step. The - census counts the reads from before the erasure was recorded, so the erasure completes - and the later receipts stay.""" + census counts the reads stamped up to the second the erasure was recorded in, so the + erasure completes and the later receipts stay.""" from loom import Agent ns = _ns("busy") diff --git a/tests/unit/test_context_pack_served_rows.py b/tests/unit/test_context_pack_served_rows.py index 2bfce54df53..1c0e6de7fd8 100644 --- a/tests/unit/test_context_pack_served_rows.py +++ b/tests/unit/test_context_pack_served_rows.py @@ -14,6 +14,7 @@ from server.memory.api.models_context import ContextPackInput from server.memory.app.context_pack import handle_context_pack from server.memory.domain.context_layout import served_rows +from server.memory.domain.read_receipts import MEMORY, Item from tests.unit.checked_pack_fakes import install_pack_stack, install_pack_target @@ -124,6 +125,65 @@ async def _search(*a: Any, **k: Any) -> Any: ) assert "a part of a long value" in out.sections["memories"] assert out._served_rows == [("ns", "long_fact")] + # the read held the passage, not the row: its receipt carries no row version + assert out._served_items == [Item(MEMORY, "ns", "long_fact", 0)] + + +def _fact(key: str, text: str, score: float, **fields: Any) -> NS: + hit = { + "namespace": "ns", + "memory_key": key, + "parent_memory_key": "", + "content_excerpt": text, + "source": "fact", + "source_resource_id": "", + "rank_score": score, + "temporal_anchor": "", + "valid_at": "", + "memory_type": "semantic", + } + return NS(**{**hit, **fields}) + + +def test_a_receipt_names_the_row_a_line_was_printed_from_at_its_version( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A key holds a row for each session that wrote it, and the two share a citation: + the pack prints the better one, and its receipt names that row's version, whichever + row another leg of the search read. A whole body read after the search is the row + the text came from, not the search document the hit was.""" + _stub_all_but_the_stack(monkeypatch, [_entry("pinned", "pin", 20)]) + + async def _search(*a: Any, **k: Any) -> Any: + return NS( + results=[ + _fact("shared", "the other session's row", 0.4, version=5), + _fact("shared", "the row printed", 0.9, version=7), + _fact("body", "a whole body", 0.8, version=8, _row_version=9), + _fact("summary", "no stored row", 0.7, version=1, source="summary"), + ], + abstain=False, + abstain_reason="", + retrieval_confidence=0.9, + retrieval_risk="low", + route_agreement=1.0, + ) + + monkeypatch.setattr("server.memory.app.search.handle_memory_search", _search) + out = asyncio.run( + handle_context_pack( + ContextPackInput(org="o", namespace="ns", agent="a", query="q", token_budget=2000) + ) + ) + assert "the row printed" in out.rendered and "the other session's row" not in out.rendered + assert out._served_items == [ + Item(MEMORY, "ns", "pin"), # a stack entry: by its key, for the notes of its read + Item(MEMORY, "ns", "shared", 7), + Item(MEMORY, "ns", "body", 9), + ] + assert [row for row in out._served_rows if row[1] != "summary"] == [ + (item.namespace, item.key) for item in out._served_items + ] def test_a_key_holding_a_hash_is_recorded_whole(monkeypatch: pytest.MonkeyPatch) -> None: @@ -205,12 +265,13 @@ async def _search(*a: Any, **k: Any) -> Any: assert len(kept) < 8 -def test_a_pack_whose_search_abstained_records_none_of_its_hits( +def test_a_pack_whose_search_abstained_serves_none_of_its_hits_and_receipts_each( monkeypatch: pytest.MonkeyPatch, ) -> None: """The answer marks an abstaining memories section as no answer, and a client drops - it (the prompt-recall hook does), so its rows, and the decisions among them, are not - recorded; the stack beside it still is.""" + it (the prompt-recall hook does), so its rows, and the decisions among them, do not + count as served; the stack beside it still does. The text prints them all the same, + so each has its receipt, as `memory.search` gives an abstaining answer's rows.""" _stub_all_but_the_stack(monkeypatch, [_entry("pinned", "pin", 20)]) async def _search(*a: Any, **k: Any) -> Any: @@ -248,6 +309,12 @@ def hit(key: str, kind: str) -> NS: ) assert "weak match weak" in out.rendered assert out._served_rows == [("ns", "pin")] + assert "weak match dec" in out.rendered + assert out._served_items == [ + Item(MEMORY, "ns", "pin"), + Item(MEMORY, "ns", "weak"), + Item(MEMORY, "ns", "dec"), + ] async def _no_records(*a: Any, **k: Any) -> dict[str, Any]: diff --git a/tests/unit/test_erasure_census_tail.py b/tests/unit/test_erasure_census_tail.py index ad976785f35..ffe077f375e 100644 --- a/tests/unit/test_erasure_census_tail.py +++ b/tests/unit/test_erasure_census_tail.py @@ -242,6 +242,7 @@ async def _boom() -> int: async def fake_census(org, st, sv, *, ch=None, spellings=()): calls.append(f"{st}:{sv}:{erasure_mutations.purge_mode()}") + counted_to.append(erasure_mutations.recorded_at()) return {"loom.memory": 0} async def noop(**kw): @@ -250,6 +251,10 @@ async def noop(**kw): async def spellings(org, user_id): return [user_id] + counted_to: list[Any] = [] + # Not now: outside the saga's scope `recorded_at()` is the present second. + recorded = h.datetime(2026, 3, 4, 5, 6, 7) + monkeypatch.setattr(h, "_saga_user_id", fake_user_saga) monkeypatch.setattr(h, "checkpoint", noop) monkeypatch.setattr("server.erasure.app.saga_steps.folded_spellings", spellings) @@ -261,10 +266,12 @@ async def spellings(org, user_id): input=inp, row={"actor": "human:t"}, erasure_id="e2", - requested_at=_now(), + requested_at=recorded, previously_completed=set(), ) assert out.status == "failed" and calls == ["user_id:alice:False"] + # The census counts a user's read receipts up to when the erasure was recorded. + assert counted_to == [recorded] # --------------------------------------------------------------------------- @@ -756,14 +763,17 @@ async def test_re_verify_run_lists_censuses_and_resumes_from_the_checkpoint(monk from server.cli import hygiene calls: list[Any] = [] - row = _ledger_row(attempts=5) + # Not now: outside the scope `recorded_at()` is the present second. + recorded = h.datetime(2026, 3, 4, 5, 6, 7) + row = _ledger_row(attempts=5, requested_at=recorded) async def fake_list(*, org=None, ch=None): calls.append(("list", org)) return [row] async def fake_census(org, st, sv, *, ch=None, spellings=()): - calls.append(("census", st, sv, erasure_mutations.purge_mode())) + mode = (erasure_mutations.purge_mode(), erasure_mutations.recorded_at()) + calls.append(("census", st, sv, *mode)) return {"loom.entity_edges": 3, "loom.memory": 0} async def fake_counts(*, ch=None): @@ -803,7 +813,8 @@ async def fake_run_saga( completed_since=None, ) assert await hygiene._re_verify_run(object(), args) == 1 # residue found, nothing resumed - assert calls == [("list", "o"), ("census", "namespace", ["lme-1"], True)] + # as the saga counted: purging, and up to when the erasure was recorded + assert calls == [("list", "o"), ("census", "namespace", ["lme-1"], True, recorded)] calls.clear() args.resume = True diff --git a/tests/unit/test_erasure_late_steps.py b/tests/unit/test_erasure_late_steps.py index 8cd40d1ec6b..104d781ad74 100644 --- a/tests/unit/test_erasure_late_steps.py +++ b/tests/unit/test_erasure_late_steps.py @@ -182,16 +182,17 @@ def test_a_users_read_receipts_are_the_reads_they_made_under_any_spelling() -> N assert "lowerUTF8(user_id)" in sql and "lowerUTF8(actor)" in sql assert (params["org"], params["spellings"]) == ("o", spellings) [row] = [s for s in erasure_census._CENSUS if s.table == "loom.read_receipts"] - assert row.user_pred == predicates.RECEIPT_READER_BEFORE - assert predicates.RECEIPT_READER in predicates.RECEIPT_READER_BEFORE + assert row.user_pred == predicates.RECEIPT_READER_UP_TO + assert predicates.RECEIPT_READER in predicates.RECEIPT_READER_UP_TO assert (row.ns_step, row.user_step) == ("read_receipts.delete", "read_receipts.delete") -def test_a_users_census_counts_the_receipts_from_before_the_erasure_was_recorded( +def test_a_users_census_counts_the_receipts_up_to_the_second_the_erasure_was_recorded_in( monkeypatch: pytest.MonkeyPatch, ) -> None: """A user who asked to be erased keeps reading, and each read writes a receipt: the - census stops at the second the erasure was recorded in, so those are not residue.""" + census counts up to the second the erasure was recorded in, so those are not residue. + That second counts: a read answered earlier in it came before the erasure.""" async def no_copies(*args: Any, **kwargs: Any) -> dict[str, int]: return {} @@ -209,7 +210,7 @@ def receipts_count() -> tuple[str, dict[str, Any]]: with erasure_mutations.recorded_scope(recorded): sql, params = receipts_count() - assert "ts < {recorded_at:DateTime}" in sql and predicates.RECEIPT_READER in sql + assert "ts <= {recorded_at:DateTime}" in sql and predicates.RECEIPT_READER in sql # Naive UTC to the second, as the column holds `ts`. assert params["recorded_at"] == datetime(2026, 3, 4, 5, 6, 7) # Outside an erasure the count runs up to now. @@ -222,6 +223,57 @@ def receipts_count() -> tuple[str, dict[str, Any]]: assert "recorded_at" not in sql and "recorded_at" not in params +class _DeadlineCH(_StubCH): + """A stub that finds no row and keeps the deadline each table's count was sent under.""" + + def __init__(self) -> None: + super().__init__(count=0) + self.deadlines: dict[str, float] = {} + + async def query_one(self, sql, params=None): + from server.core.ch import class_timeout_s + + self.deadlines[sql.split("FROM ")[1].split()[0]] = class_timeout_s("read") + return await super().query_one(sql, params) + + +def test_a_users_receipt_counts_run_under_the_ddl_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The sort key does not order a reader's rows, so the user step's count and the user + census's read every receipt of the org: they take the DDL class's deadline, where the + read deadline would fail the erasure of a large org.""" + from server.settings import settings + + async def no_copies(*args: Any, **kwargs: Any) -> dict[str, int]: + return {} + + def deadlines(run: Any, *args: Any, **kwargs: Any) -> dict[str, float]: + ch = _DeadlineCH() + asyncio.run(run(*args, ch=ch, **kwargs)) + return ch.deadlines + + def by_user() -> tuple[float, set[float]]: + step = deadlines(ledger_steps.delete_read_receipts_by_user, "o", ["alice"]) + census = deadlines( + erasure_census.table_residue, "o", "user_id", "alice", spellings=["alice"] + ) + assert set(step) == {"loom.read_receipts"} and "loom.read_receipts" in census + return step["loom.read_receipts"], set(census.values()) + + monkeypatch.setattr(erasure_census, "copy_residue", no_copies) + monkeypatch.setattr(settings, "ch_timeout_read_s", 30.0) + monkeypatch.setattr(settings, "ch_timeout_ddl_s", 300.0) + assert by_user() == (300.0, {300.0}) + # A namespace's counts are keyed by the namespace and keep the read deadline. + step = deadlines(ledger_steps.delete_read_receipts_by_namespace, "o", "n") + census = deadlines(erasure_census.table_residue, "o", "namespace", "n") + assert step == {"loom.read_receipts": 30.0} and set(census.values()) == {30.0} + # With the DDL deadline off the scope sets nothing, and the read deadline stands. + monkeypatch.setattr(settings, "ch_timeout_ddl_s", 0.0) + assert by_user() == (30.0, {30.0}) + + def test_a_namespaces_read_receipts_leave_by_a_lightweight_delete_in_every_mode() -> None: """A namespace's receipts sit in every monthly part, so a mutation would rewrite the whole table: the step masks the rows instead, with or without a purge.""" diff --git a/tests/unit/test_memory_search_kinds.py b/tests/unit/test_memory_search_kinds.py index cb9b986dd54..fecba26d08e 100644 --- a/tests/unit/test_memory_search_kinds.py +++ b/tests/unit/test_memory_search_kinds.py @@ -608,6 +608,8 @@ async def memory_leg(inp: MemorySearchInput, *, repo_namespace: str) -> MemorySe monkeypatch.setattr(fanout, "memory_with_repo_decisions", memory_leg) payload = _sections(["false_positive"]) assert _keys(payload["memory"]["results"]) == ["review/false_positive/ttl", "other/fact"] + # beside the dumped rows, their search models in served order, for the read receipt + assert [id(m) for m in payload[fanout.SERVED_MEMORY_HITS]] == [id(lesson), id(foreign)] assert "withheld" not in payload assert len(payload["conversations"]["results"]) == 1 # the memory search ran in rank order; loom_search ordered its kept rows @@ -640,6 +642,9 @@ async def nothing(*a: Any, **k: Any) -> Any: ) out = asyncio.run(handler.handle_search(query)) assert _keys(out.memory["results"]) == ["fp", "other/fact"] + # the answer keeps the served rows' models for its receipt and serves none of them + assert [id(m) for m in out._memory_hits] == [id(rows[1]), id(rows[0])] + assert set(out.model_dump()) >= {"memory"} and "_memory_hits" not in out.model_dump() def test_loom_search_leaves_a_lesson_moved_for_stale_code_where_it_is(monkeypatch): diff --git a/tests/unit/test_pg_durable_reads.py b/tests/unit/test_pg_durable_reads.py index 24b03462ecc..ef0d14799dc 100644 --- a/tests/unit/test_pg_durable_reads.py +++ b/tests/unit/test_pg_durable_reads.py @@ -77,7 +77,9 @@ "server/knowledge/store/datasets.py": "catalog rows to the caller; a write it decides " "(a carry, an approval) projects only its own commit", "server/knowledge/store/documents.py": "reads beside the writer's own commit; " - "the worker's sends are its durable claims", + "the worker's sends are its durable claims; a read receipt of `knowledge.get` sends " + "the served revision and version, never content, and may name a revision a failover " + "loses", "server/memory/app/blacklist_guard.py": "captures a value guard; each resulting write " "commits with its policy generations rechecked", "server/memory/app/blacklist_sweep.py": "tombstones through its own commit", diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py index 438597c9f23..252e13dadc7 100644 --- a/tests/unit/test_read_receipts.py +++ b/tests/unit/test_read_receipts.py @@ -11,11 +11,10 @@ import pytest -from server.core import instances, request_work +from server.core import background, instances, request_work from server.core.diagnostics import private_work from server.memory.app import after_write, served_reads from server.memory.app import read_receipts as rr -from server.memory.app.log_once import LogOnce from server.memory.domain.read_receipts import ( DOCUMENT, MEMORY, @@ -30,6 +29,7 @@ ) from server.memory.store import read_receipts as store from server.settings import settings +from tests.unit.clock_fake import ManualClock, idle_time ROOT = Path(__file__).resolve().parents[2] SHA = "a" * 64 @@ -217,6 +217,17 @@ def test_a_row_holds_the_tables_columns_and_no_content() -> None: assert (document["chunk_idx"], document["content_sha256"]) == (5, "") +@pytest.mark.parametrize( + ("agent", "stored"), [("codex", "codex"), ("", "-"), ("-", "-"), ("*", "-")] +) +def test_a_read_that_names_no_agent_stores_the_sentinel(agent: str, stored: str) -> None: + """An agent left out, and the `*` of a read across agents, name nobody: the column + holds `-`, as the user, session and run columns do.""" + reader = store.Reader(org="o", operation="memory.search", agent=agent) + [row] = store.build_rows(reader, [(Item(MEMORY, "n", "k", 3), Noted(3, SHA))]) + assert row["agent"] == stored + + def test_the_insert_is_a_background_async_insert() -> None: calls: list[tuple[str, list[dict[str, Any]], dict[str, Any]]] = [] @@ -250,7 +261,6 @@ async def _insert(rows: list[dict[str, Any]], **_kw: Any) -> None: monkeypatch.setattr(store, "insert", _insert) monkeypatch.setattr(instances, "live_rows", lambda: [{"schema_version": store.MIGRATION}]) monkeypatch.setattr(settings, "read_receipts_enabled", True) - monkeypatch.setattr(rr, "_GATE_LOGGED", LogOnce()) monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0) # the sender sends at its next turn rr._reset_for_tests() yield batches @@ -410,7 +420,9 @@ def test_a_read_that_names_no_user_is_not_filed_under_the_tokens_subject( ) -> None: """A transport traces an unnamed user as the token's subject; a receipt keeps the subject in `actor` and the user unset, so reads made as an end user stay apart from - reads a token of that name made.""" + reads a token of that name made. The traced identity is the same when the request + names the token's own subject as its user, on an op whose input has no `user_id`: + that read is filed under `-` too.""" from server.auth import context as auth_context from server.observability import genai @@ -424,6 +436,57 @@ def test_a_read_that_names_no_user_is_not_filed_under_the_tokens_subject( assert (row["actor"], row["user_id"], row["session_id"]) == ("svc-reader", "-", "-") +def test_a_reader_string_utf8_cannot_hold_costs_no_answer_its_receipt( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + """A request's JSON can carry a lone surrogate in the run, agent, user and session it + names, and an insert cannot encode one. Each is stored with `?` in its place: the + answer keeps its row, and so do the answers that share its insert.""" + from server.observability import genai + + async def _encoding(rows: list[dict[str, Any]], **_kw: Any) -> None: + for row in rows: + for value in row.values(): + if isinstance(value, str): + value.encode("utf-8") # the client encodes every string it sends + written.append(rows) + + monkeypatch.setattr(store, "insert", _encoding) + monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0.5) + to_transport: dict[str, str] = {} + monkeypatch.setattr(genai, "request_identity", lambda: to_transport) + lone = "\ud800" + in_body = SimpleNamespace( + org="o", + namespace="n", + agent=f"a-{lone}", + user_id=f"u-{lone}", + session_id=f"s-{lone}", + run_id=f"r-{lone}", + ) + op = _op(_note_k) + + async def _go() -> None: + await op(_INPUT) + await op(in_body) + # an op whose input names no reader takes the transport's + to_transport.update(agent=f"ta-{lone}", user_id=f"tu-{lone}", session_id=f"ts-{lone}") + await op(SimpleNamespace(org="o", namespace="n")) + await after_write.drain() + + # On a manual clock the three answers are inside one interval, so they share an insert. + with asyncio.Runner() as runner, idle_time(runner.get_loop(), ManualClock()): + runner.run(_go()) + [rows] = written + assert rr._failed == 0 + reader = ("agent", "user_id", "session_id", "run_id") + assert [[row[c] for c in reader] for row in rows] == [ + ["codex", "-", "-", "-"], + ["a-?", "u-?", "s-?", "r-?"], + ["ta-?", "tu-?", "ts-?", "-"], + ] + + def test_an_op_run_inside_another_writes_nothing_itself( written: list[list[dict[str, Any]]], ) -> None: @@ -537,20 +600,48 @@ def test_no_receipt_while_a_live_replica_cannot_erase_it( monkeypatch.setattr(instances, "live_rows", lambda: live) assert not instances.every_live_replica_at(store.MIGRATION) _run(_op(_note_k)) - assert written == [] + # the answer had a row to write: it is counted, and nothing is built or queued + assert written == [] and (rr._unrecorded, rr._queued) == (1, []) + +def _said(caplog: pytest.LogCaptureFixture, what: str) -> list[str]: + return [line for r in caplog.records if what in (line := r.getMessage())] -def test_a_closed_replica_gate_is_logged_once( + +def test_a_closed_replica_gate_is_counted_and_logged_at_most_once_a_minute( monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]], caplog: pytest.LogCaptureFixture, ) -> None: - monkeypatch.setattr(instances, "live_rows", lambda: []) + """Only the log reports a closed gate. Its line names what closed it and carries how + many answers were not recorded since the process started, and it is written again + when the gate is found closed a minute later, however long ago the process first + logged it.""" + clock = ManualClock(t=1000.0) + monkeypatch.setattr(rr.time, "monotonic", clock.monotonic) + live: list[dict[str, Any]] = [] + monkeypatch.setattr(instances, "live_rows", lambda: live) + not_written = "read receipts not written" with caplog.at_level("WARNING", logger=rr.__name__): + _run(_op(_note_k)) # the process read no replica list + clock.advance(59) + _run(_op(_note_k)) # inside the minute: counted, not logged + _run(_op(lambda: None)) # an answer with nothing to record is no loss + assert len(_said(caplog, not_written)) == 1 + live.append({"schema_version": store.MIGRATION}) # the gate opens + clock.advance(1) _run(_op(_note_k)) + assert len(_said(caplog, not_written)) == 1 and len(written) == 1 + # an older replica joins, a minute after the line: closed for the other cause + live.append({"schema_version": store.MIGRATION - 1}) _run(_op(_note_k)) - said = [r for r in caplog.records if "read receipts are not written" in r.getMessage()] - assert len(said) == 1 and written == [] + assert _said(caplog, not_written) == [ + "read receipts not written: no recent read of the replica list " + "(answers not recorded since the process started: 1)", + f"read receipts not written: a live replica is older than migration {store.MIGRATION} " + "(answers not recorded since the process started: 3)", + ] + assert rr._unrecorded == 3 and len(written) == 1 def test_receipts_are_written_once_every_live_replica_is_at_the_migration( @@ -772,19 +863,40 @@ def test_the_answers_of_one_interval_share_an_insert( ) -> None: """An insert costs the same whatever it carries, so the sender waits an interval before each: reads that arrive one after another do not each pay for one.""" - monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0.05) + monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0.5) op = _op(_note_k) async def _go() -> None: for _ in range(4): await op(_INPUT) - await asyncio.sleep(0.001) + await asyncio.sleep(0.1) await after_write.drain() - asyncio.run(_go()) + # The loop runs on a manual clock, which moves only while every task waits: four + # answers a tenth of a second apart are inside one interval however slow the host. + with asyncio.Runner() as runner, idle_time(runner.get_loop(), ManualClock()): + runner.run(_go()) assert [len(rows) for rows in written] == [4] +def test_an_answer_after_the_interval_goes_in_the_next_insert( + monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] +) -> None: + monkeypatch.setattr(rr, "_SEND_INTERVAL_S", 0.5) + op = _op(_note_k) + + async def _go() -> None: + for _ in range(3): + await op(_INPUT) + await asyncio.sleep(0.2) # the third answer queues at 0.4, the sender sends at 0.5 + await op(_INPUT) # at 0.6: the sender is done, so this one starts another + await after_write.drain() + + with asyncio.Runner() as runner, idle_time(runner.get_loop(), ManualClock()): + runner.run(_go()) + assert [len(rows) for rows in written] == [3, 1] + + def test_a_sender_left_on_a_closed_loop_is_replaced( monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]] ) -> None: @@ -794,6 +906,9 @@ def test_a_sender_left_on_a_closed_loop_is_replaced( async def _hang(_rows: list[dict[str, Any]], **_kw: Any) -> None: await asyncio.Event().wait() + # The first sender is never done, so the process's registry of deferred tasks would + # keep it and every later drain would report work on another loop. + monkeypatch.setattr(background, "_registered_tasks", set()) monkeypatch.setattr(store, "insert", _hang) op = _op(_note_k) @@ -806,6 +921,8 @@ async def _first() -> None: loop.run_until_complete(_first()) loop.close() assert rr._sender is not None and not rr._sender.done() + # asyncio logs a pending task when it is collected, which would be inside a later test. + rr._sender._log_destroy_pending = False monkeypatch.setattr(store, "insert", _collect(written)) _run(op) # the row the first sender took is lost with it; the queued one and the new one land @@ -834,10 +951,49 @@ async def _go() -> None: assert seen == [(None, rr.SEND_QUERY_TAG)] -def test_a_repeating_failure_is_logged_at_each_power_of_ten() -> None: - assert [n for n in range(1, 1200) if rr._worth_logging(n)] == [1, 10, 100, 1000] - # a counter that rises by an answer's rows is logged when it passes one - assert rr._worth_logging(5, 5) and rr._worth_logging(12, 5) and not rr._worth_logging(17, 5) +def test_each_kind_of_loss_is_logged_at_most_once_a_minute_with_its_total( + monkeypatch: pytest.MonkeyPatch, + written: list[list[dict[str, Any]]], + caplog: pytest.LogCaptureFixture, +) -> None: + """Only the log reports a loss. An incident is logged when it starts, whatever the + process lost before it, and a long one does not fill the log. Each line carries the + total since the process started, so two lines subtract to the loss between them.""" + clock = ManualClock(t=1000.0) + monkeypatch.setattr(rr.time, "monotonic", clock.monotonic) + + async def _down(_rows: list[dict[str, Any]], **_kw: Any) -> None: + raise RuntimeError("store down") + + def two() -> None: + rr.note_memory("n", "a", version=1, sha256=SHA) + rr.note_memory("n", "b", version=2, sha256=SHA) + + monkeypatch.setattr(store, "insert", _down) + monkeypatch.setattr(rr, "_MAX_QUEUED_ROWS", 1) + fits, too_many = _op(_note_k), _op(two) + + def lose() -> None: + _run(fits) # its insert fails + _run(too_many) # its rows are past the queue bound + + with caplog.at_level("WARNING", logger=rr.__name__): + lose() # each kind is logged + clock.advance(59) + lose() # inside the minute: counted, not logged + clock.advance(1) + lose() # a minute after the first line: logged again, with the total + assert _said(caplog, "write failed") == [ + "read-receipt write failed (non-fatal; inserts failed since the process started: 1, " + "rows lost now: 1): store down", + "read-receipt write failed (non-fatal; inserts failed since the process started: 3, " + "rows lost now: 1): store down", + ] + assert _said(caplog, "queue bound") == [ + "read receipts dropped past the queue bound (rows dropped since the process started: 2)", + "read receipts dropped past the queue bound (rows dropped since the process started: 6)", + ] + assert written == [] # ------------------------------------------------------------------------- the hash @@ -1009,10 +1165,33 @@ def note() -> None: _run(_op(note, out, rr.search_items), MemorySearchInput(**ident, query="q")) # the source row was edited after the promotion: the answer carried the copy's text assert _receipts(written) == [_receipt(MEMORY, "n", key, 12, SHA)] - # an answer that carries the hit without its stored version cannot say which row it is + # search.query serves the hit dumped, without its stored version, and keeps the model wire = SearchOutput.model_validate({"memory": out.model_dump(mode="json")}) + wire._memory_hits = out.results _run(_op(note, wire, rr.search_query_items), SearchInput(**ident, query="q")) - assert _receipts(written)[1:] == [_receipt(MEMORY, "n", key, 0)] + assert _receipts(written)[1:] == [_receipt(MEMORY, "n", key, 12, SHA)] + + +def test_search_query_receipts_the_row_a_whole_body_came_from( + written: list[list[dict[str, Any]]], +) -> None: + """The dumped hit carries the search document's version. The receipt is built from + the search's model, which holds the row the body was read from.""" + from server.memory.api.models_loom_search import SearchInput, SearchOutput + from server.memory.api.models_search import MemorySearchOutput + + def note() -> None: + rr.note_memory("n", "body", version=8, sha256=SHA) # the search document + rr.note_memory("n", "body", version=9, sha256=OTHER_SHA) # the row the body came from + + hits = [_hit("body", version=8, row_version=9)] + dumped = MemorySearchOutput(results=hits, embedding_model="e").model_dump(mode="json") + assert dumped["results"][0]["version"] == 8 and "_row_version" not in dumped["results"][0] + out = SearchOutput.model_validate({"memory": dumped}) + out._memory_hits = hits + _run(_op(note, out, rr.search_query_items), SearchInput(org="o", namespace="n", query="q")) + assert _receipts(written) == [_receipt(MEMORY, "n", "body", 9, OTHER_SHA)] + assert "_memory_hits" not in out.model_dump() def test_a_document_search_receipts_each_chunk_at_its_revision( @@ -1047,8 +1226,8 @@ def note() -> None: def test_a_versionless_answer_records_the_hash_of_a_row_read_through_two_tables( written: list[list[dict[str, Any]]], ) -> None: - """A context pack names a row by key. Its search noted the row's search document, at - that document's version, and its own read noted the memory row.""" + """A context pack names a row of its memory stack by key. One read noted the row's + search document, at that document's version, and another the memory row.""" from server.memory.api.models_context import ContextPackInput, ContextPackOutput def note() -> None: @@ -1056,9 +1235,9 @@ def note() -> None: rr.note_row(_row(version=3)) pack = ContextPackOutput(rendered="", sections={}, section_count=0, token_budget=1) - pack._served_rows = [("n", "k")] - items = rr.memory_rows(served_reads.rendered_rows) - _run(_op(note, pack, items), ContextPackInput(org="o", namespace="n", agent="a", query="q")) + pack._served_items = [Item(MEMORY, "n", "k")] + input = ContextPackInput(org="o", namespace="n", agent="a", query="q") + _run(_op(note, pack, rr.pack_items), input) assert _receipts(written) == [_receipt(MEMORY, "n", "k", 0, SHA)] @@ -1097,7 +1276,7 @@ def note_both() -> None: brief = MemoryBriefOutput() brief._evidence_hits = [_hit("k", version=7)] pack = ContextPackOutput(rendered="", sections={}, section_count=0, token_budget=1) - pack._served_rows = [("n", "k")] + pack._served_items = [Item(MEMORY, "n", "k", 7)] for_file = MemoryForFileOutput( path="a.py", total=1, @@ -1133,6 +1312,7 @@ def note_both() -> None: "knowledge": documents.model_dump(mode="json"), } ) + both._memory_hits = search.results return { "memory.search": (MemorySearchInput(**ident, query="q"), search, note_row, row), "memory.ask": ( @@ -1187,6 +1367,23 @@ def test_exactly_the_recall_ops_are_receipted() -> None: assert receipted == RECEIPTED == set(_answers()) +def test_an_mcp_sessions_run_labels_the_receipted_ops_that_take_a_run() -> None: + """Over MCP the session's run is bound for an op whose input has `run_id`, and for + `search.query`. A receipt of any other receipted op is filed under no run there, as + its op ledger row is: the design page names these ops.""" + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport.mcp_runs import takes_run + + unlabelled = {name for name in RECEIPTED if not takes_run(OPERATIONS_BY_NAME[name])} + assert unlabelled == { + "memory.get_by_id", + "memory.for_file", + "procedure.match", + "knowledge.search", + "knowledge.get", + } + + @pytest.mark.parametrize("name", sorted(RECEIPTED)) def test_each_receipted_op_writes_what_its_answer_carried( monkeypatch: pytest.MonkeyPatch, written: list[list[dict[str, Any]]], name: str From 4d88eda129b03c9de4d7edea9c55c2350c1ec5a5 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 13:39:22 +0000 Subject: [PATCH 04/18] The generated schema, settings pages and rule numbers match the read-receipts table schemas/schema.sql and docs/reference/schema.md carry the 190-day TTL and the agent column's default. The settings reference, schema and example carry the setting's comment. The read-receipts rolling-upgrade rule is rule 74, after the rule main numbers 73, and the rollback note names it. The design page's log table names the handler in the per-answer line and lists knowledge.search among the MCP reads filed under no run. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 6 +++--- docs/architecture/rolling-upgrades.md | 19 ++++++++++--------- docs/operations/upgrades.md | 2 +- docs/reference/configuration.md | 2 +- docs/reference/schema.md | 2 +- loom.example.yaml | 2 +- schemas/loom-settings.schema.json | 2 +- schemas/schema.sql | 4 ++-- server/memory/domain/context_layout.py | 9 +++++---- 9 files changed, 25 insertions(+), 23 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 8166023fea6..0eb064050e3 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -355,14 +355,14 @@ GROUP BY operation When reads answer and this returns nothing, the server log says why: -| Log line | Meaning | -| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| Log line | Meaning | +| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `read receipts not written: a live replica is older than migration …` | A replica of an older build still serves. The line carries the answers not recorded since the process started. | | `read receipts not written: no recent read of the replica list` | The process's heartbeat has no recent read of the list of live replicas. The line carries the answers not recorded since the process started. | | `read receipts dropped past the queue bound` | The store is slower than the reads. The line carries the rows dropped since the process started. | | `read-receipt write failed` | An insert failed. The line carries the inserts failed since the process started, the rows this insert lost and the error. | | `read-receipt note failed` | A note raised. The read answered, and that revision was not noted. | -| `read receipts of not recorded` | Building or queueing one answer's receipts raised; the line names the op's handler function. The read answered, and that answer has none. | +| `read receipts of not recorded` | Building or queueing one answer's receipts raised; the line names the op's handler function. The read answered, and that answer has none. | While its cause lasts, each of these is written at most once a minute: a `not written` line (the two share the minute), the queue-bound line and the failed-insert line. The diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 11c5be2a370..2929ab485dd 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1092,15 +1092,6 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline answer cited), and N-1 credits the same keys as N. `tests/unit/test_usage_credit_retraction_sql.py` and `tests/unit/test_usage_fold_sql.py` check N's side, and the mixed-version gate does not check this rule. -73. **Read receipts** (`loom.read_receipts`, migration `122_read_receipts.sql`): N-1's - erasure saga has no step for the table. So while any live replica's schema version is - below 122, or no heartbeat has been read, N writes no receipt, as it records no miss - under rule 48; reads answer as before. Before a rollback, turn - `read_receipts_enabled` off with `loom settings set` and truncate the table, then - truncate it again after the first N-1 replica serves - ([read receipts](read-receipts.md#rolling-upgrades), the - [rollback note](../operations/upgrades.md#rollback)). - `tests/unit/test_read_receipts.py` checks the gate; the mixed-version gate does not. 73. **Owner erasure covers worker sources** (`connected_accounts._erase_worker_owners`): N's SCIM user delete erases the user's worker source rows, which N-1 only preserves. @@ -1116,6 +1107,16 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline serves. No gate holds the rollout, and the mixed-version gate does not check this rule. +74. **Read receipts** (`loom.read_receipts`, migration `122_read_receipts.sql`): N-1's + erasure saga has no step for the table. So while any live replica's schema version is + below 122, or no heartbeat has been read, N writes no receipt, as it records no miss + under rule 48; reads answer as before. Before a rollback, turn + `read_receipts_enabled` off with `loom settings set` and truncate the table, then + truncate it again after the first N-1 replica serves + ([read receipts](read-receipts.md#rolling-upgrades), the + [rollback note](../operations/upgrades.md#rollback)). + `tests/unit/test_read_receipts.py` checks the gate; the mixed-version gate does not. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/operations/upgrades.md b/docs/operations/upgrades.md index 32137824a84..2a93168ccbc 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -449,7 +449,7 @@ environment) and run table above its `max_table_size_to_drop`, 50 GB by default), then run it again once the first replica of the previous build serves, for the rows written in between: that build's erasure has no step for the table -([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 73). Once the +([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 74). Once the newer build serves alone again, `loom settings reset read_receipts_enabled` turns receipts back on. Do not roll back past the build that adds the document bucket while any catalog row diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f8ac3a2e5d8..06fe40596f4 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1539,7 +1539,7 @@ memory.search: legs, fusion, ranking and gates. | `LOOM_MEMORY_SEARCH_SET_EXPANSION_MIN_SIMILARITY` | `float` | `0.5` | live | Similarity a set-expansion leg's row must exceed to join the pool. | | `LOOM_MEMORY_SEARCH_SET_EXPANSION_MAX_ADDED` | `int` | `5` | live | Most rows the set-expansion legs add to one search. | | `LOOM_MEMORY_EXPOSURE_LEDGER_ENABLED` | `bool` | `True` | live | Read-side exposure ledger in loom.memory_exposures: one row per read (token subject, returned keys, query digest never the text, scope) plus an hourly per-actor roll-up. Carries no user content. | -| `LOOM_READ_RECEIPTS_ENABLED` | `bool` | `True` | live | Read receipts in loom.read_receipts: one row per memory row or document an agent read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL. | +| `LOOM_READ_RECEIPTS_ENABLED` | `bool` | `True` | live | Read receipts in loom.read_receipts: one row per memory row or document chunk a read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL. | | `LOOM_MEMORY_SEARCH_MIN_SIMILARITY` | `float` | `0.22` | | Cosine floor: hits below it are dropped as noise (ANN always returns top_k). The backstop when rerank is bypassed or fails. | | `LOOM_MEMORY_SEARCH_FLOOR_MODE` | `'readmit' \| 'ids_only' \| 'drop'` | `'readmit'` | live | Sub-floor handling when the caller sets top_k: "readmit" (fill k, tag below_floor), "ids_only" (fill k with empty bodies), "drop". A request's floor_mode overrides. | | `LOOM_MEMORY_SEARCH_EMBED_BOUND_S` | `float` | `2.5` | live | Per-attempt bound (seconds) on the query embedding; after the retries the search answers 503 EMBED_TIMEOUT. 0 = unbounded. | diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 1e4fe8cc43e..60356c1f341 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -317,7 +317,7 @@ the `loom` tables each view reads, and, for each materialized view, its target, | `qa_test_daily` | `ReplacingMergeTree(version)` | `(org, qa_namespace, test_name, day)` | | | | | `query_history_sources` | `ReplacingMergeTree(version)` | `(org, namespace, name)` | | | | | `query_nodes` | `AggregatingMergeTree` | `(org, namespace, query_hash)` | | | | -| `read_receipts` | `MergeTree` | `(org, namespace, kind, item_key, ts)` | `toYYYYMM(ts)` | `ts + toIntervalDay(180)` | 1 skip index (bloom_filter) | +| `read_receipts` | `MergeTree` | `(org, namespace, kind, item_key, ts)` | `toYYYYMM(ts)` | `ts + toIntervalDay(190)` | 1 skip index (bloom_filter) | | `revoked_tokens` | `ReplacingMergeTree(version)` | `jti` | | `toDateTime(expires_at) + toIntervalDay(10)` | | | `runtime_overrides` | `ReplacingMergeTree(version)` | `(kind, key)` | | | | | `scim_users` | `ReplacingMergeTree(version)` | `id` | | | | diff --git a/loom.example.yaml b/loom.example.yaml index 3deb7c7df0f..cd534ae66ed 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -4695,7 +4695,7 @@ settings: # Carries no user content. [live] # memory_exposure_ledger_enabled: true - # Read receipts in loom.read_receipts: one row per memory row or document an agent + # Read receipts in loom.read_receipts: one row per memory row or document chunk a # read's answer carried, with the revision the read held (version and hash, never # content or query text). Off stops new rows; stored ones expire by the table's TTL. # [live] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 2d002062b03..8c8eb4a176d 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6593,7 +6593,7 @@ "read_receipts_enabled": { "default": true, "type": "boolean", - "description": "Read receipts in loom.read_receipts: one row per memory row or document an agent read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL." + "description": "Read receipts in loom.read_receipts: one row per memory row or document chunk a read's answer carried, with the revision the read held (version and hash, never content or query text). Off stops new rows; stored ones expire by the table's TTL." }, "readiness_check_timeout_s": { "default": 2.0, diff --git a/schemas/schema.sql b/schemas/schema.sql index 8589ad1291c..312e196b7fa 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -3961,7 +3961,7 @@ CREATE TABLE IF NOT EXISTS loom.read_receipts `run_id` String DEFAULT '-', `actor` String DEFAULT '', `token_id` String DEFAULT '', - `agent` LowCardinality(String) DEFAULT '', + `agent` LowCardinality(String) DEFAULT '-', `user_id` String DEFAULT '-', `session_id` String DEFAULT '-', INDEX run_id_bloom_idx run_id TYPE bloom_filter(0.01) GRANULARITY 1, @@ -3970,7 +3970,7 @@ CREATE TABLE IF NOT EXISTS loom.read_receipts ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (org, namespace, kind, item_key, ts) -TTL ts + toIntervalDay(180) +TTL ts + toIntervalDay(190) SETTINGS non_replicated_deduplication_window = 1000, ttl_only_drop_parts = 1, index_granularity = 8192; -- loom.revoked_tokens diff --git a/server/memory/domain/context_layout.py b/server/memory/domain/context_layout.py index 45e1573981b..54ba1e85705 100644 --- a/server/memory/domain/context_layout.py +++ b/server/memory/domain/context_layout.py @@ -284,10 +284,11 @@ def served_rows[Row]( gets (MCP's lean pack carries it alone); `sections` and `blocks` keep lines the pack's own budget cut, so a row counts only where `rendered` holds it. What a client then discards is its own; a section the answer marks as no answer names no served row and - still names its receipts (see `_pack_memories`). Each section's item lines start with `- ` (`one_item` indents a - continuation), in the order of its `item_rows`; a trim keeps a prefix, so the first n - rows of a section whose n item lines `rendered` still holds were shown, a cut one - included. `section_names` are the present sections in pack order.""" + still names its receipts (see `_pack_memories`). Each section's item lines start with + `- ` (`one_item` indents a continuation), in the order of its `item_rows`; a trim keeps + a prefix, so the first n rows of a section whose n item lines `rendered` still holds + were shown, a cut one included. `section_names` are the present sections in pack + order.""" shown: list[Row] = [] cursor = 0 for name in section_names: From 7dff08b9a3eab8ee3a0563a1854ba2309a7b1163 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 14:49:12 +0000 Subject: [PATCH 05/18] An erasure's recorded time has one source, memory.for_file notes its answer once, and each read path's note has a test The time an erasure was recorded is bound once by the saga and by the restore replay (recorded_scope). The census reads it to the second and the code-index purge reads it directly, where it read the ledger row on every step. memory.for_file notes the rows of its answer in the handler, where the rows of the request's namespaces and of the caller's other namespaces meet, so one call covers both reads. search_sections builds the thread-history section in a helper, which keeps it inside the function-length limit. Tests: an integration case reads a row by its id, for a file and as a pinned row of the stack and compares each receipt with the stored revision; unit cases cover the stack's pinned and recalled rows and the body a procedure match is built from. Each fails when its note call is removed. Docs: loom.read_receipts is listed with its own 190 days, and the erasure section names the deadline to raise, LOOM_CH_TIMEOUT_DDL_S. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 5 +- docs/features/memory/retention-and-erasure.md | 4 +- server/code/app/index/erasing.py | 11 ++--- server/erasure/app/replay.py | 6 ++- server/erasure/app/saga_steps.py | 13 +---- server/erasure/store/mutations.py | 29 ++++++----- server/memory/app/for_file.py | 3 +- server/memory/app/loom_search/fanout.py | 27 +++++----- tests/integration/test_read_receipts.py | 48 ++++++++++++++++++ tests/unit/test_code_erasure_skip_busy.py | 41 ++++++++-------- tests/unit/test_knowledge_mirrors.py | 3 +- tests/unit/test_loom_search_fanout_kinds.py | 15 +++++- tests/unit/test_read_receipts.py | 49 +++++++++++++++++++ tests/unit/test_restore_reconcile.py | 4 ++ 14 files changed, 184 insertions(+), 74 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 0eb064050e3..06bcead892e 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -45,7 +45,7 @@ Two things meet when a receipted op returns (`records_receipts` in | `memory.get`, `memory.get_by_id`, `memory.bulk_get` | the rows served | the handler | | `context.pack` | the stored rows its text prints | its searches, its pinned and recent row reads | | `memory.stack` | its pinned, recent and procedure entries | its row reads | -| `memory.for_file` | the rows its block prints | its row read | +| `memory.for_file` | the rows its block prints | the handler, over the rows its reads return | | `procedure.match` | the procedures matched | its row read | | `knowledge.search` | the chunks returned | where the search builds its hits | | `knowledge.get` | the document | the handler, for an ordinary document | @@ -425,7 +425,8 @@ flowchart LR two counts of this table cost about one to three core-minutes per billion receipts of the org; the delete waits up to `LOOM_ERASURE_MUTATION_WAIT_S`. When a user erasure fails with `BACKEND_TIMEOUT` at `read_receipts.delete` or at `verify.residue`, raise - that deadline (a restart) and resume the erasure + `LOOM_CH_TIMEOUT_DDL_S` (a restart; a deployment that set it to 0 sets a positive + value, since the counts otherwise stop at the 30 s read deadline) and resume the erasure ([abandoned sagas](../features/memory/retention-and-erasure.md#abandoned-sagas)). A receipt is written half a second after its answer at the earliest, and later when its diff --git a/docs/features/memory/retention-and-erasure.md b/docs/features/memory/retention-and-erasure.md index f786a5d088a..b7abfd312b4 100644 --- a/docs/features/memory/retention-and-erasure.md +++ b/docs/features/memory/retention-and-erasure.md @@ -27,8 +27,8 @@ A row leaves the served set only when: `memory.touch`, `run.complete(retain="expire")`, a reflection's `expires_in_days`; - **the owner or operator configured one**: see [configured retention](#configured-retention). -Operational tables (telemetry, caches, queues) have fixed TTLs: `loom.search_trace_log`, -`loom.memory_exposures`, `loom.read_receipts`, `loom.code_search_trace` and +Operational tables (telemetry, caches, queues) have fixed TTLs: `loom.read_receipts` 190 +days; `loom.search_trace_log`, `loom.memory_exposures`, `loom.code_search_trace` and `loom.code_search_outcome` 180 days; `loom.erasure_requests` and `loom.policy_decisions` 90 days; `loom.memory_drops`, `loom.memory_extraction_queue`, diff --git a/server/code/app/index/erasing.py b/server/code/app/index/erasing.py index ca0f00db4e9..88fdc5ec218 100644 --- a/server/code/app/index/erasing.py +++ b/server/code/app/index/erasing.py @@ -6,13 +6,12 @@ import logging import time -from collections.abc import Awaitable, Callable, Sequence +from collections.abc import Sequence from datetime import UTC, datetime, timedelta from server.core import leases from server.core.errors import OverloadedError -_At = Callable[[], Awaitable[datetime]] log = logging.getLogger(__name__) # Their passes hold the entry lock, which names the namespace they are on. _ENTRY_LOCKED = frozenset({"code_scip_full", "code_scip_delta"}) @@ -70,7 +69,7 @@ async def _pass_begun_before(recorded: datetime) -> str: return "" -async def _holder(org: str, namespaces: Sequence[str], recorded: _At) -> str: +async def _holder(org: str, namespaces: Sequence[str], recorded: datetime) -> str: """What may still write an indexed one of `namespaces`, '' when nothing is known to.""" from server.code.app.index.entry_lock import entry_lease_name from server.code.app.ingest import refresh_lease_name @@ -86,13 +85,13 @@ async def _holder(org: str, namespaces: Sequence[str], recorded: _At) -> str: return f"a compiler-tier pass holds the entry lock of {ns!r}" if await leases.has_live_holder(refresh_lease_name(org, ns)): return f"a code.refresh pass is indexing {ns!r}" - if rows and (worker := await _pass_begun_before(await recorded())): + if rows and (worker := await _pass_begun_before(recorded)): return f"a {worker} pass that began before the erasure may still be writing" return "" -async def refuse_while_in_use(org: str, namespaces: Sequence[str], recorded: _At) -> None: - """OVERLOADED while work begun before the erasure was `recorded()` may still write.""" +async def refuse_while_in_use(org: str, namespaces: Sequence[str], recorded: datetime) -> None: + """OVERLOADED while work begun before the erasure was `recorded` may still write.""" if held := await _holder(org, namespaces, recorded): raise OverloadedError( f"{held}; the code index is purged once that ends: the recovery worker retries " diff --git a/server/erasure/app/replay.py b/server/erasure/app/replay.py index 35133b8fdf3..37b15622e08 100644 --- a/server/erasure/app/replay.py +++ b/server/erasure/app/replay.py @@ -215,7 +215,11 @@ async def _run_steps( scope = parse_namespace_list(input.scope_value) if input.scope_type == "user_id": await marks.bump(input.org, marks.ORG_WIDE, "erasure") - with erasure_mutations.saga_scope(erasure_id), erasure_mutations.purge_scope(purge): + with ( + erasure_mutations.saga_scope(erasure_id), + erasure_mutations.purge_scope(purge), + erasure_mutations.recorded_scope(row["requested_at"]), + ): for name, step in steps: with erasure_mutations.step_scope(name): try: diff --git a/server/erasure/app/saga_steps.py b/server/erasure/app/saga_steps.py index e01a9b55298..f3a17aed5d0 100644 --- a/server/erasure/app/saga_steps.py +++ b/server/erasure/app/saga_steps.py @@ -17,20 +17,18 @@ from server.code.app.index.retire import code_tables_keyed_by_namespace, refresh_code_views from server.core import grant_cache from server.core.ch import sequential_reads -from server.core.datetimes import as_aware_utc from server.core.errors import caller_text from server.core.naming import is_mirror_name from server.core.principals import personal_name from server.core.repo_base import _CHClient from server.erasure.store import census as erasure_census -from server.erasure.store import ledger from server.erasure.store import refusals as refusal_steps from server.erasure.store import steps_graph as graph_steps from server.erasure.store import steps_ledgers as ledger_steps from server.erasure.store import steps_memory as memory_steps from server.erasure.store import steps_pg as pg_steps from server.erasure.store import steps_principals as principal_steps -from server.erasure.store.mutations import current_saga, namespaces_of, purge_scope +from server.erasure.store.mutations import current_saga, namespaces_of, purge_scope, recorded from server.knowledge.app import mirrors as knowledge_mirrors from server.knowledge.app.sources import retire_sources_of from server.memory.app import run_feedback @@ -91,18 +89,11 @@ async def _step_verify_residue( return 0 -async def _recorded_at() -> datetime: - """When the running saga's erasure was recorded (now outside a saga).""" - erasure_id, _ = current_saga() - row = await ledger.fetch_request_status(erasure_id) if erasure_id else None - return as_aware_utc(row["requested_at"] if row else None) or datetime.now(UTC) - - async def _step_purge_code_index_by_ns(org: str, namespace: _NS) -> int: """A code namespace's repository index — every loom.code_* table keyed by (org, namespace) — leaves with the namespace, once no work begun before the erasure was recorded may still write it.""" - await erasing.refuse_while_in_use(org, namespaces_of(namespace), _recorded_at) + await erasing.refuse_while_in_use(org, namespaces_of(namespace), recorded()) return await memory_steps.purge_code_index_by_namespace( org, namespace, diff --git a/server/erasure/store/mutations.py b/server/erasure/store/mutations.py index b0a923551ba..30a99ddfd41 100644 --- a/server/erasure/store/mutations.py +++ b/server/erasure/store/mutations.py @@ -21,7 +21,7 @@ from typing import Any, cast from server.core.ch_names import split_table -from server.core.datetimes import to_naive_utc_second +from server.core.datetimes import as_aware_utc, to_naive_utc_second from server.core.repo_base import _CHClient, _default_client from server.erasure.store.predicates import NS_EQ, NS_IN from server.erasure.store.rows import MutationRow @@ -96,28 +96,33 @@ def step_scope(step: str) -> Iterator[None]: _STEP.reset(token) -# When the erasure being counted was recorded. A user keeps making calls after asking to -# be erased, and a table that takes a row on each of them (`loom.read_receipts`) is counted -# up to this time: later rows are new activity, not what the erasure was asked to delete. -_RECORDED_AT: contextvars.ContextVar[datetime | None] = contextvars.ContextVar( - "loom_erasure_recorded_at", default=None +# When the erasure being run or counted was recorded. Work that began before it may still +# write what the erasure deletes, and work after it is not the erasure's to delete: a user +# keeps making calls after asking to be erased, so a table that takes a row on each of +# them (`loom.read_receipts`) is counted up to this time. +_RECORDED: contextvars.ContextVar[datetime | None] = contextvars.ContextVar( + "loom_erasure_recorded", default=None ) @contextlib.contextmanager def recorded_scope(at: datetime) -> Iterator[None]: - """Inside the block, `recorded_at()` is `at`: when the erasure was recorded.""" - token = _RECORDED_AT.set(to_naive_utc_second(at)) + """Inside the block, `recorded()` is `at`: when the erasure was recorded.""" + token = _RECORDED.set(as_aware_utc(at)) try: yield finally: - _RECORDED_AT.reset(token) + _RECORDED.reset(token) + + +def recorded() -> datetime: + """When the erasure being run or counted was recorded (now outside one).""" + return _RECORDED.get() or _now_naive().replace(tzinfo=UTC) def recorded_at() -> datetime: - """When the erasure being counted was recorded, naive UTC to the second (now - outside one).""" - return _RECORDED_AT.get() or _now_naive().replace(microsecond=0) + """`recorded()` as naive UTC to the second, as a `DateTime` column compares.""" + return to_naive_utc_second(recorded()) def mutation_tag( diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index 6d63afa2300..e8793c2f1ac 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -693,7 +693,6 @@ async def _rows_for( # of each slice's own top `lim` are the namespace's if ids: found = found + await query_all_sliced(ch, _LINKED_SQL, params | {"linked": ids}, "linked") - note_selected(namespace, found) unique = { ( str(r["memory_id"]), @@ -981,7 +980,6 @@ async def _read_own( "links": held, } ) - note_selected("", rows) # each row carries its namespace return _supersede_order(sorted(rows, key=_order_key)) @@ -1083,6 +1081,7 @@ async def handle_memory_for_file(input: MemoryForFileInput) -> MemoryForFileOutp if others is not None: note_budget_shape("own_namespaces") rows = rows + others[: max(int(input.top_k) - len(rows), 0)] + note_selected(input.namespace, rows) # each row carries its namespace hits: list[_MemoryForFileHit] = [] to_render: list[dict[str, Any]] = [] diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 0cb97b8fd66..c51160f0705 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -344,6 +344,18 @@ async def _published_knowledge( return section +def _conversations_section(conv_result: Any) -> dict[str, Any]: + """The thread-history section, bundled so "have we discussed X" lands in the same + call: the search's dump with its hits under `results` alone, or the leg's error.""" + if isinstance(conv_result, Exception): + return {"error": _leg_error("conversations", conv_result), "results": []} + conv_dump = conv_result.model_dump() + conv_hits = conv_dump.get("results") or conv_dump.get("hits") or [] + # One list, not the same hits twice under `hits` and `results`. + conv_dump.pop("hits", None) + return {**conv_dump, "results": conv_hits} + + async def search_sections( *, org: str, @@ -479,20 +491,7 @@ async def search_sections( else {"results": list(profile_rows)} ) - # Conversations: thread-history search, bundled so "have we discussed X" - # lands in the same call. - conv_hits: list[dict[str, Any]] = [] - if isinstance(conv_result, Exception): - payload["conversations"] = { - "error": _leg_error("conversations", conv_result), - "results": [], - } - else: - conv_dump = conv_result.model_dump() - conv_hits = conv_dump.get("results") or conv_dump.get("hits") or [] - # One list, not the same hits twice under `hits` and `results`. - conv_dump.pop("hits", None) - payload["conversations"] = {**conv_dump, "results": conv_hits} + payload["conversations"] = _conversations_section(conv_result) lead = answer_first(payload, namespace, explain=explain, moved=moved) read_in = _served_models(payload, models) # memory.ask's order, not `kinds_first`'s diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index bfb84261942..88c2e561ff3 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -192,6 +192,54 @@ async def both_lookups() -> list[dict[str, Any]]: assert len({r["version"] for r in lookups}) == 1 +async def test_a_row_read_by_id_for_a_file_or_in_the_stack_is_recorded( + control_plane_url: str, ch_client: Any +) -> None: + """The reads that reach a row without a search (by its id, by a file it is about, as a + pinned row of the stack) name it in their answer without a revision: the receipt + holds the stored revision the read selected.""" + from loom import Agent + + ns, run = _ns("ops"), _run_id("ops") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + fact = await _read( + a, "memory.set", memory_key="backup_window", value=FIRST, files=["ops/backup.py"] + ) + await a.memory.pin("pager", "the on-call pager follows rotation 7", "semantic") + + by_id = await _read(a, "memory.get_by_id", run, memory_id=fact["memory_id"]) + assert by_id["found"] is True + + async def served(op: str, names: str, key: str, **body: Any) -> bool: + out = await _read(a, op, run, **body) + return any(row["memory_key"] == key for row in out[names]) + + async def pinned() -> bool: + return await served("memory.stack", "entries", "pager") + + async def about_the_file() -> bool: + return await served("memory.for_file", "printed", "backup_window", path="ops/backup.py") + + await eventually(pinned, description="the stack carries the pinned row") + await eventually(about_the_file, description="the file's block prints the row") + + read = { + "memory.get_by_id": "backup_window", + "memory.for_file": "backup_window", + "memory.stack": "pager", + } + + async def every_op() -> dict[str, dict[str, Any]]: + rows = _receipts(ch_client, ns, run_id=run) + newest = {r["operation"]: r for r in rows if r["item_key"] == read.get(r["operation"])} + return newest if set(newest) == set(read) else {} + + receipts = await eventually(every_op, description="each read's receipt lands") + for op, key in read.items(): + recorded = (receipts[op]["version"], receipts[op]["content_sha256"]) + assert recorded == await _stored(ch_client, ns, key), op + + async def test_a_row_read_through_both_tables_records_its_stored_hash( control_plane_url: str, ch_client: Any ) -> None: diff --git a/tests/unit/test_code_erasure_skip_busy.py b/tests/unit/test_code_erasure_skip_busy.py index 2a10e170fdc..8cf3578f4d5 100644 --- a/tests/unit/test_code_erasure_skip_busy.py +++ b/tests/unit/test_code_erasure_skip_busy.py @@ -4,7 +4,7 @@ write the namespace, and succeeds once it has ended; a pass that starts after the record skips the namespace; a refusal on a worker's pass ends at that pass's deadline even when the worker never reports again. CH-free: the ledger, the leases and the worker-status -rows are fakes.""" +rows are fakes, and the purge runs in the scopes its saga binds.""" from __future__ import annotations @@ -20,7 +20,6 @@ from server.core import ch, leases from server.core.errors import OverloadedError from server.erasure.app import ledger_reads, saga_steps -from server.erasure.store import ledger from server.erasure.store import mutations as erasure_mutations from server.erasure.store import steps_memory as memory_steps from server.workers import registry, status_store @@ -80,9 +79,6 @@ async def latest_rows(**kw: Any) -> list[dict[str, Any]]: def enabled_workers() -> list[Any]: return [SimpleNamespace(name=n, deadline_seconds=lambda: 900.0) for n in world.enabled] - async def request(erasure_id: str, **_: Any) -> dict[str, Any]: - return {"requested_at": world.recorded.replace(tzinfo=None)} - async def purge(org: str, namespace: Any, **_: Any) -> int: world.purged.append(namespace) return 7 @@ -90,13 +86,16 @@ async def purge(org: str, namespace: Any, **_: Any) -> int: monkeypatch.setattr(leases, "has_live_holder", has_live_holder) monkeypatch.setattr(status_store, "latest_rows", latest_rows) monkeypatch.setattr(registry, "enabled_workers", enabled_workers) - monkeypatch.setattr(ledger, "fetch_request_status", request) monkeypatch.setattr(memory_steps, "purge_code_index_by_namespace", purge) return world -async def _purge(namespaces: Any = ("code-a",)) -> int: - with erasure_mutations.saga_scope("00000000-0000-0000-0000-000000000001"): +async def _purge(world: _World, namespaces: Any = ("code-a",)) -> int: + with ( + erasure_mutations.saga_scope("00000000-0000-0000-0000-000000000001"), + # The ledger's `requested_at`: naive UTC, as a resumed saga reads it back. + erasure_mutations.recorded_scope(world.recorded.replace(tzinfo=None)), + ): return await saga_steps._step_purge_code_index_by_ns("o", list(namespaces)) @@ -105,12 +104,12 @@ async def test_a_pass_in_flight_refuses_the_purge_until_it_ends(world: _World) - # (its worker's newest row finished more than an interval before the record). world.ingest_row(world.recorded - timedelta(seconds=200)) with pytest.raises(OverloadedError) as refused: - await _purge() + await _purge(world) assert "code_ingest pass that began before the erasure" in refused.value.message assert "repeat it" in refused.value.message assert world.purged == [] world.ingest_row(world.recorded + timedelta(seconds=20)) # that pass has ended - assert await _purge() == 7 + assert await _purge(world) == 7 assert world.purged == [["code-a"]] @@ -124,30 +123,30 @@ async def test_a_lease_on_the_namespace_refuses_the_purge( world.ingest_row(world.recorded + timedelta(seconds=20)) # no pass in flight world.held.add(lease) with pytest.raises(OverloadedError, match=says): - await _purge(["code-b", "code-a"]) + await _purge(world, ["code-b", "code-a"]) world.held.clear() - assert await _purge(["code-b", "code-a"]) == 7 + assert await _purge(world, ["code-b", "code-a"]) == 7 async def test_a_worker_idle_at_the_record_or_a_memory_namespace_does_not_hold_it( world: _World, ) -> None: world.ingest_row(world.recorded - timedelta(seconds=60)) # next pass after the record - assert await _purge() == 7 + assert await _purge(world) == 7 world.rows.clear() world.ingest_row(world.recorded - timedelta(seconds=200)) world.indexed = [] # no code index: a memory namespace - assert await _purge() == 7 + assert await _purge(world) == 7 async def test_an_unreadable_status_store_refuses_the_purge_retryably(world: _World) -> None: world.ingest_row(world.recorded + timedelta(seconds=20)) world.unreadable = True with pytest.raises(OverloadedError, match="worker state unknown") as refused: - await _purge() + await _purge(world) assert refused.value.extra["retry_after_s"] == 60 and world.purged == [] world.unreadable = False - assert await _purge() == 7 + assert await _purge(world) == 7 async def test_an_enabled_worker_with_no_finished_row_holds_the_purge_to_its_deadline( @@ -156,15 +155,15 @@ async def test_an_enabled_worker_with_no_finished_row_holds_the_purge_to_its_dea world.enabled = ["code_ingest", "code_summary"] # its first pass: no row yet world.ingest_row(world.recorded + timedelta(seconds=20)) with pytest.raises(OverloadedError, match="code_summary pass that began before"): - await _purge() + await _purge(world) world.recorded = datetime.now(UTC) - timedelta(seconds=920) # its deadline is past - assert await _purge() == 7 + assert await _purge(world) == 7 async def test_no_supervised_row_holds_no_enabled_worker(world: _World) -> None: # No supervisor runs (a CLI-only install, a test job): no worker can be in a first pass. world.enabled = ["code_ingest", "code_summary"] - assert await _purge() == 7 + assert await _purge(world) == 7 async def test_the_refusal_ends_at_the_pass_deadline(world: _World) -> None: @@ -172,9 +171,9 @@ async def test_the_refusal_ends_at_the_pass_deadline(world: _World) -> None: world.recorded = datetime.now(UTC) - timedelta(seconds=880) world.ingest_row(world.recorded - timedelta(seconds=200)) with pytest.raises(OverloadedError): - await _purge() + await _purge(world) world.recorded = datetime.now(UTC) - timedelta(seconds=920) - assert await _purge() == 7 + assert await _purge(world) == 7 async def test_a_pass_that_starts_after_the_record_skips_the_namespace( diff --git a/tests/unit/test_knowledge_mirrors.py b/tests/unit/test_knowledge_mirrors.py index 10ea9defd37..c999241bae7 100644 --- a/tests/unit/test_knowledge_mirrors.py +++ b/tests/unit/test_knowledge_mirrors.py @@ -207,7 +207,8 @@ async def promote(row: Any) -> None: marked.append(True) monkeypatch.setattr(replay, "_promote_mark", promote) - asyncio.run(replay._run_steps(body, "e1", [("memory.tombstone", step)], {})) + row: Any = {"requested_at": datetime(2026, 3, 4, 5, 6, 7)} + asyncio.run(replay._run_steps(body, "e1", [("memory.tombstone", step)], row)) assert marked == [True] assert seen == [(["team", MIRROR], True)] diff --git a/tests/unit/test_loom_search_fanout_kinds.py b/tests/unit/test_loom_search_fanout_kinds.py index 4619f50c497..9d4b3931b1d 100644 --- a/tests/unit/test_loom_search_fanout_kinds.py +++ b/tests/unit/test_loom_search_fanout_kinds.py @@ -8,6 +8,7 @@ import asyncio import inspect import re +from types import SimpleNamespace import pytest @@ -228,8 +229,18 @@ def test_lean_drops_the_per_hit_bookkeeping() -> None: def test_conversations_section_carries_one_list() -> None: - src = inspect.getsource(loom_search_fanout.search_sections) - assert 'conv_dump.pop("hits", None)' in src + """The thread hits ride under `results` alone, whichever name the search's dump gives + them, and a failed leg answers its error with no hits.""" + hit = {"conversation_id": "c", "content": "x"} + for name in ("results", "hits"): + dump = {name: [hit], "total": 1} + search = SimpleNamespace(model_dump=lambda dump=dump: dict(dump)) + assert loom_search_fanout._conversations_section(search) == { + "results": [hit], + "total": 1, + } + failed = loom_search_fanout._conversations_section(RuntimeError("down")) + assert failed["results"] == [] and failed["error"] def test_a_fail_closed_kind_read_refuses_without_a_connection( diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py index 252e13dadc7..3feb4400561 100644 --- a/tests/unit/test_read_receipts.py +++ b/tests/unit/test_read_receipts.py @@ -1241,6 +1241,55 @@ def note() -> None: assert _receipts(written) == [_receipt(MEMORY, "n", "k", 0, SHA)] +@pytest.mark.parametrize("section", ["_stack_pinned", "_stack_recent"]) +def test_a_stack_records_the_stored_revision_of_the_rows_it_selects( + written: list[list[dict[str, Any]]], section: str +) -> None: + """A stack's entries carry no revision: the statement that selects a pinned or a + recalled row notes the revision it read.""" + from server.memory.api.models_lifecycle import MemoryStackInput + from server.memory.app import stack + from server.memory.app.served_reads import stack_keys + + class _Selected: + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: + return [{"memory_key": "k", "value": "v", "version": 6, "content_sha256": SHA}] + + async def handler(input: MemoryStackInput) -> Any: + fill = stack._StackFill(budget=100) + await getattr(stack, section)(_Selected(), input, fill) + return SimpleNamespace(entries=fill.entries) + + input = MemoryStackInput(org="o", namespace="n", agent="a") + _run(rr.records_receipts(rr.memory_rows(stack_keys))(handler), input) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 6, SHA)] + + +def test_a_matched_procedure_records_the_stored_revision_of_its_body( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +) -> None: + """A match names its procedure by key: the read of the body it is built from notes + the revision.""" + import server.memory.store as memory_repo + from server.memory.api.models_procedure import ProcedureMatchInput + from server.memory.app import procedure + from server.memory.app.served_reads import procedure_keys + + async def bodies(identity: Any, keys: list[str], **_kw: Any) -> list[Any]: + return [_row(memory_key=key, value={"steps": ["a"]}, version=9) for key in keys] + + monkeypatch.setattr(memory_repo, "get_many_by_keys", bodies) + + async def handler(input: ProcedureMatchInput) -> Any: + rows = await procedure._procedure_rows(input, {"n": ["procedure_p"]}) + matches = [SimpleNamespace(namespace=ns, memory_key=key) for ns, key in rows] + return SimpleNamespace(matches=matches) + + input = ProcedureMatchInput(org="o", namespace="n", agent="a", situation="s") + _run(rr.records_receipts(rr.memory_rows(procedure_keys))(handler), input) + assert _receipts(written) == [_receipt(MEMORY, "n", "procedure_p", 9, SHA)] + + def _answers() -> dict[str, tuple[Any, Any, Callable[[], None], list[tuple[Any, ...]]]]: """Per receipted op: a real input, a real answer that carries memory `k` (and, where the op serves documents, a chunk of `doc://a`), the notes its read makes, and the diff --git a/tests/unit/test_restore_reconcile.py b/tests/unit/test_restore_reconcile.py index 1b46e8de865..9e7c3ecf33f 100644 --- a/tests/unit/test_restore_reconcile.py +++ b/tests/unit/test_restore_reconcile.py @@ -613,10 +613,12 @@ def test_the_replay_runs_each_step_over_the_scope_its_saga_did( from server.erasure.store import mutations seen: list[tuple[Any, bool, str]] = [] + recorded: set[datetime] = set() def step(name: str) -> Any: async def run(org: str, s: Any) -> int: seen.append((s, mutations.purge_mode(), name)) + recorded.add(mutations.recorded()) return 0 return run @@ -646,6 +648,8 @@ async def bump(*a: Any) -> None: entry = _completed(scope_type=scope_type, scope_value=scope_value, purge=purge) asyncio.run(replay.replay(entry, "clickhouse", _now())) assert seen and all(s == scope and p == purged for s, p, _ in seen) + # And at the time its saga did: the code-index purge refuses on work begun before it. + assert recorded == {entry["requested_at"].replace(tzinfo=UTC)} @pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") From 70f507aa183148db2e8a83c1054f8d9fd7855fd2 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 15:28:55 +0000 Subject: [PATCH 06/18] An erasure's first run and its resume read one recorded second, and two more read paths' notes have a test recorded() answers the second the erasure was recorded in, as the ledger row holds it, so a first run and a resume bind the same value. The code-index purge holds for a code worker whose next pass was due anywhere in that second, on every run. Tests: an integration case reads a file's block that prints a row the caller wrote in another namespace and compares its receipt, filed under that namespace, with the stored revision. The stack's unit case answers only the columns its statements select. A purge case binds the time as a first run and as a resume do. Each fails when its behaviour is removed. Docs: the erasure section names the read deadline's setting. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 3 +- server/code/app/index/erasing.py | 15 +++--- server/erasure/store/mutations.py | 8 ++-- tests/integration/test_read_receipts.py | 58 +++++++++++++++++++++++ tests/unit/test_code_erasure_skip_busy.py | 15 ++++++ tests/unit/test_read_receipts.py | 7 ++- 6 files changed, 94 insertions(+), 12 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 06bcead892e..65eac2dc405 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -426,7 +426,8 @@ flowchart LR the org; the delete waits up to `LOOM_ERASURE_MUTATION_WAIT_S`. When a user erasure fails with `BACKEND_TIMEOUT` at `read_receipts.delete` or at `verify.residue`, raise `LOOM_CH_TIMEOUT_DDL_S` (a restart; a deployment that set it to 0 sets a positive - value, since the counts otherwise stop at the 30 s read deadline) and resume the erasure + value, since the counts otherwise stop at the read deadline, `LOOM_CH_TIMEOUT_READ_S`) + and resume the erasure ([abandoned sagas](../features/memory/retention-and-erasure.md#abandoned-sagas)). A receipt is written half a second after its answer at the earliest, and later when its diff --git a/server/code/app/index/erasing.py b/server/code/app/index/erasing.py index 88fdc5ec218..24eecef9e98 100644 --- a/server/code/app/index/erasing.py +++ b/server/code/app/index/erasing.py @@ -35,10 +35,11 @@ async def being_erased(org: str, namespace: str) -> bool: async def _pass_begun_before(recorded: datetime) -> str: """A code worker whose newest pass row finished an interval (none after a failure) before - `recorded`, so its next pass may have begun by then, and whose deadline is not past. An - enabled one with no finished row (its first pass, while a supervisor reports) counts the same - way from `recorded`; a - status store that cannot be read refuses, retryably, since nothing is then known.""" + the erasure, so its next pass may have begun by then, and whose deadline is not past. An + enabled one with no finished row (its first pass, while a supervisor reports) counts the + same way. `recorded` is the second the erasure was recorded in, so a pass due anywhere in + that second counts as begun before it. A status store that cannot be read refuses, + retryably, since nothing is then known.""" from server.workers import registry, status_store try: @@ -51,20 +52,20 @@ async def _pass_begun_before(recorded: datetime) -> str: ) from e rows = [r for r in all_rows if r.get("trigger") != "manual"] newest = {r["worker"]: r for r in sorted(rows, key=lambda r: r.get("pass_finished") or "")} - now = datetime.now(UTC) + now, by = datetime.now(UTC), recorded + timedelta(seconds=1) # recorded before `by` for name, row in sorted(newest.items()): if not name.startswith("code_") or name in _ENTRY_LOCKED or not row["pass_finished"]: continue rest = row.get("interval_s") if row.get("status") in ("ok", "idle", "partial") else 0 began_by = datetime.fromisoformat(row["pass_finished"]) + timedelta(seconds=rest or 0) - if began_by <= recorded and now < recorded + timedelta(seconds=row["deadline_s"] or 0): + if began_by < by and now < by + timedelta(seconds=row["deadline_s"] or 0): return str(name) if not rows: # no supervisor reports here, so no worker can be in its first pass return "" finished = {n for n, r in newest.items() if r.get("pass_finished")} for spec in registry.enabled_workers(): if spec.name.startswith("code_") and spec.name not in _ENTRY_LOCKED | finished: - if now < recorded + timedelta(seconds=spec.deadline_seconds()): + if now < by + timedelta(seconds=spec.deadline_seconds()): return spec.name return "" diff --git a/server/erasure/store/mutations.py b/server/erasure/store/mutations.py index 30a99ddfd41..5dbcd8a4597 100644 --- a/server/erasure/store/mutations.py +++ b/server/erasure/store/mutations.py @@ -107,7 +107,7 @@ def step_scope(step: str) -> Iterator[None]: @contextlib.contextmanager def recorded_scope(at: datetime) -> Iterator[None]: - """Inside the block, `recorded()` is `at`: when the erasure was recorded.""" + """Inside the block, `recorded()` is the second of `at`: when the erasure was recorded.""" token = _RECORDED.set(as_aware_utc(at)) try: yield @@ -116,8 +116,10 @@ def recorded_scope(at: datetime) -> Iterator[None]: def recorded() -> datetime: - """When the erasure being run or counted was recorded (now outside one).""" - return _RECORDED.get() or _now_naive().replace(tzinfo=UTC) + """The second the erasure being run or counted was recorded in, as its ledger row + holds it, so its first run and a resume read one value (the current second outside + one).""" + return (_RECORDED.get() or _now_naive().replace(tzinfo=UTC)).replace(microsecond=0) def recorded_at() -> datetime: diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 88c2e561ff3..7a0fa0e1e94 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -240,6 +240,64 @@ async def every_op() -> dict[str, dict[str, Any]]: assert recorded == await _stored(ch_client, ns, key), op +async def test_a_file_lookup_records_the_callers_row_of_another_namespace( + control_plane_url: str, ch_client: Any, mint_test_token: Any +) -> None: + """Where the deployment's default scope is `all_mine`, a file's block also prints the + rows the caller wrote in their other namespaces: such a row's receipt is filed under + the namespace that holds it, with the revision stored there.""" + from loom import Agent + + home, records, run = _ns("home"), _ns("records"), _run_id("own") + repo, path = f"repo:{uuid.uuid4().hex[:10]}", f"ops/{uuid.uuid4().hex[:6]}/backup.py" + owner = mint_test_token(org=ORG, namespaces=[home, records], roles=["writer"], subject="w") + operator = mint_test_token(org="*", roles=["platform_admin"], subject="rr-operator") + + async def default_scope(**body: Any) -> None: + """Set or clear the scope a read with no named scope takes (deployment-wide).""" + async with httpx.AsyncClient(timeout=30.0) as http: + r = await http.post( + f"{control_plane_url}/v1/admin/settings.set", + json={"name": "memory_search_default_namespace_scope", **body}, + headers={"Authorization": f"Bearer {operator}"}, + ) + assert r.status_code == 200, r.text + + async def printed(a: Any) -> bool: + out = await _read(a, "memory.for_file", run, path=path, tags=[repo]) + return [hit["namespace"] for hit in out["hits"]] == [records] + + async with Agent( + org=ORG, namespace=home, agent="w", base_url=control_plane_url, api_key=owner + ) as a: + await _read( + a, + "memory.set", + namespace=records, + memory_key="backup_window", + value=FIRST, + files=[path], + tags=[repo], + ) + await default_scope(value="all_mine") + try: + await eventually( + lambda: printed(a), + max_wait=30.0, + description="the file's block prints the caller's row of another namespace", + ) + finally: + await default_scope(clear=True) + await overrides_adopted() + + stored = await _stored(ch_client, records, "backup_window") + rows = await _landed(ch_client, records, run_id=run) + assert {(r["operation"], r["item_key"], r["version"], r["content_sha256"]) for r in rows} == { + ("memory.for_file", "backup_window", *stored) + } + assert _receipts(ch_client, home, run_id=run) == [] # filed where the row is, only there + + async def test_a_row_read_through_both_tables_records_its_stored_hash( control_plane_url: str, ch_client: Any ) -> None: diff --git a/tests/unit/test_code_erasure_skip_busy.py b/tests/unit/test_code_erasure_skip_busy.py index 8cf3578f4d5..4731b6d4f18 100644 --- a/tests/unit/test_code_erasure_skip_busy.py +++ b/tests/unit/test_code_erasure_skip_busy.py @@ -113,6 +113,21 @@ async def test_a_pass_in_flight_refuses_the_purge_until_it_ends(world: _World) - assert world.purged == [["code-a"]] +@pytest.mark.parametrize("resumed", [False, True]) +async def test_a_first_run_and_a_resume_hold_the_same_passes(world: _World, resumed: bool) -> None: + """The first run binds the time the erasure was recorded at and a resume the ledger's, + which holds it to the second. Both read that second: a pass due within it holds the + purge and one due after it does not.""" + second = world.recorded.replace(microsecond=0) + world.recorded = second if resumed else second.replace(microsecond=900_000) + world.ingest_row(second + timedelta(seconds=0.5 - 120)) # its next pass: in the second + with pytest.raises(OverloadedError, match="code_ingest pass that began before"): + await _purge(world) + world.rows.clear() + world.ingest_row(second + timedelta(seconds=1.5 - 120)) # its next pass: after it + assert await _purge(world) == 7 + + @pytest.mark.parametrize( ("lease", "says"), [("scip_entry:o/code-a", "entry lock"), ("code_refresh:o/code-a", "code.refresh")], diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py index 3feb4400561..abbcb014f2c 100644 --- a/tests/unit/test_read_receipts.py +++ b/tests/unit/test_read_receipts.py @@ -1251,9 +1251,14 @@ def test_a_stack_records_the_stored_revision_of_the_rows_it_selects( from server.memory.app import stack from server.memory.app.served_reads import stack_keys + stored = {"memory_key": "k", "value": "v", "version": 6, "content_sha256": SHA} + class _Selected: + """Answers the columns the statement selects, as ClickHouse does.""" + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: - return [{"memory_key": "k", "value": "v", "version": 6, "content_sha256": SHA}] + selected = set(re.findall(r"\w+", sql.split("FROM")[0])) + return [{name: value for name, value in stored.items() if name in selected}] async def handler(input: MemoryStackInput) -> Any: fill = stack._StackFill(budget=100) From c00a3590591e411e9086249fd748c8973c38f26e Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 16:46:04 +0000 Subject: [PATCH 07/18] A redacted row's receipt has a test on each read that selects it, and the purge's hold is tested at its deadline The stack's two row reads and the file read select `redacted_at` so a redacted row's receipt carries no hash; no test failed when a statement stopped selecting it. Each now has a case whose store answers only the selected columns, for a live row and a redacted one. The code-index purge waits a deadline past the end of the second the erasure was recorded in. A clock seam lets a test check the hold half a second before that end and at it, for a worker's newest row and for a first pass. The pages said a receipt is written half a second after its answer at the earliest; a row queued while the sender waits goes out sooner. They now say within about half a second, and state that the user census compares the reading replica's clock with the recording replica's with no margin. The description of `ch_batched_insert_background_wait_max_ms` names the receipt sender, which waits under it. The integration file's two settings cleanups check the server's answer and wait for what it serves. `recorded_at()` no longer floors a value `recorded()` floored, and the `after_write` docstring covers a detached task. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 8 ++- docs/features/memory/retention-and-erasure.md | 4 +- docs/reference/configuration.md | 2 +- loom.example.yaml | 6 +- schemas/loom-settings.schema.json | 2 +- server/code/app/index/erasing.py | 7 ++- server/erasure/store/mutations.py | 6 +- server/memory/app/after_write.py | 5 +- server/settings/catalog.py | 6 +- tests/integration/test_read_receipts.py | 31 ++++++--- tests/unit/test_code_erasure_skip_busy.py | 20 ++++++ tests/unit/test_read_receipts.py | 63 +++++++++++++++---- 12 files changed, 125 insertions(+), 35 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 65eac2dc405..c1708e36e6f 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -406,6 +406,12 @@ flowchart LR they do not fail it. They expire with the table, or leave with the user's next erasure. A read the user makes later in that second is counted only when its receipt lands after the step; the erasure then fails once and completes when run again. +- A receipt's stamp is the clock of the replica that answered the read, and the recorded + second is the clock of the replica that recorded the erasure; the census compares the + two with no margin. A read answered before the erasure by a replica whose clock runs + ahead of the recorder's can be stamped after that second, and is then treated as later + activity: the step deletes its receipt when it has landed, and the census does not + count one that lands after the step. - A receipt of another reader that names a row the user wrote keeps the key, version and hash until the table's TTL, as the exposure ledger keeps the key. The hash still matches the erased text, so someone who reads the table and guesses the text can @@ -430,7 +436,7 @@ flowchart LR and resume the erasure ([abandoned sagas](../features/memory/retention-and-erasure.md#abandoned-sagas)). -A receipt is written half a second after its answer at the earliest, and later when its +A receipt is written within about half a second of its answer, and later when its process stalls or the store is slow. One stamped up to the second a user's erasure was recorded in that lands between the step and the census is counted: the erasure fails with `loom.read_receipts` in its `residue` and completes when run again. One that lands diff --git a/docs/features/memory/retention-and-erasure.md b/docs/features/memory/retention-and-erasure.md index b7abfd312b4..b7e9237b8eb 100644 --- a/docs/features/memory/retention-and-erasure.md +++ b/docs/features/memory/retention-and-erasure.md @@ -159,8 +159,8 @@ the table's 190-day TTL: - another reader's receipt of a row the user wrote, with the row's key, version and content hash (no hash is stored for a row that was labelled high-sensitivity when it was read); -- a receipt that lands after the erasure's census: one is written half a second after - its answer at the earliest, and later when its process stalls or the store is slow. +- a receipt that lands after the erasure's census: one is written within about half a + second of its answer, and later when its process stalls or the store is slow. The erasure reports `completed`, and the next erasure of the same scope deletes the receipt; - after a `namespace` erasure, receipts of reads its agents made of other namespaces' diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 06fe40596f4..f7e2777a98e 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -186,7 +186,7 @@ ClickHouse connection, query shaping and vector storage. | `LOOM_CH_BATCHED_INSERTS` | `bool` | `True` | live | Batch the inserts written on every request into shared parts; false commits them, and the waited async inserts keep their bounds (docs/architecture/clickhouse.md#batched-inserts). | | `LOOM_CH_BATCHED_INSERT_WAIT_MIN_MS` | `int` | `10` | live | Shortest wait, ms, of a batched or waited async insert: what a lone insert waits when writes are sparse; capped at ch_batched_insert_wait_max_ms (or the background bound). | | `LOOM_CH_BATCHED_INSERT_WAIT_MAX_MS` | `int` | `50` | live | Longest wait, ms, of a batched or waited async insert a request waits on; it holds a pooled connection meanwhile. | -| `LOOM_CH_BATCHED_INSERT_BACKGROUND_WAIT_MAX_MS` | `int` | `200` | live | Longest wait, ms, of the usage-event flusher's ticks and shutdown drain and the write-mark timer's flush, which no request waits on, except run.retract_credit while a tick is already sending. | +| `LOOM_CH_BATCHED_INSERT_BACKGROUND_WAIT_MAX_MS` | `int` | `200` | live | Longest wait, ms, of the usage-event flusher's ticks and shutdown drain, the write-mark timer's flush and the read-receipt sender's inserts, which no request waits on, except run.retract_credit while a tick is already sending. | | `LOOM_CH_POOL_WAIT_MS` | `int` | `500` | | Max wait, ms, for a pool slot before failing fast with 503 OVERLOADED. 0 = no slot gate. | | `LOOM_CH_REPLICA_BOUND_RETRIES` | `int` | `2` | | Fresh connections a statement tries after a replica-bound error (a replica that lost its Keeper session, a replica's read-only table). Behind a load balancer one reconnect can land on the replica that just failed, so a single retry is not enough. | diff --git a/loom.example.yaml b/loom.example.yaml index cd534ae66ed..886e9f63edb 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -126,9 +126,9 @@ settings: # pooled connection meanwhile. [live] # ch_batched_insert_wait_max_ms: 50 - # Longest wait, ms, of the usage-event flusher's ticks and shutdown drain and the - # write-mark timer's flush, which no request waits on, except run.retract_credit while - # a tick is already sending. [live] + # Longest wait, ms, of the usage-event flusher's ticks and shutdown drain, the + # write-mark timer's flush and the read-receipt sender's inserts, which no request + # waits on, except run.retract_credit while a tick is already sending. [live] # ch_batched_insert_background_wait_max_ms: 200 # Max wait, ms, for a pool slot before failing fast with 503 OVERLOADED. 0 = no slot diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 8c8eb4a176d..883f41aa321 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -441,7 +441,7 @@ "exclusiveMinimum": 0, "maximum": 5000, "type": "integer", - "description": "Longest wait, ms, of the usage-event flusher's ticks and shutdown drain and the write-mark timer's flush, which no request waits on, except run.retract_credit while a tick is already sending." + "description": "Longest wait, ms, of the usage-event flusher's ticks and shutdown drain, the write-mark timer's flush and the read-receipt sender's inserts, which no request waits on, except run.retract_credit while a tick is already sending." }, "ch_batched_insert_wait_max_ms": { "default": 50, diff --git a/server/code/app/index/erasing.py b/server/code/app/index/erasing.py index 24eecef9e98..04cf3ac7239 100644 --- a/server/code/app/index/erasing.py +++ b/server/code/app/index/erasing.py @@ -17,6 +17,11 @@ _ENTRY_LOCKED = frozenset({"code_scip_full", "code_scip_delta"}) +def _now() -> datetime: + """The current time (a seam: a test sets the instant a deadline is compared at).""" + return datetime.now(UTC) + + async def being_erased(org: str, namespace: str) -> bool: """True too when the ledger cannot be read: no work starts that the purge may miss.""" from server.erasure.app import ledger_reads @@ -52,7 +57,7 @@ async def _pass_begun_before(recorded: datetime) -> str: ) from e rows = [r for r in all_rows if r.get("trigger") != "manual"] newest = {r["worker"]: r for r in sorted(rows, key=lambda r: r.get("pass_finished") or "")} - now, by = datetime.now(UTC), recorded + timedelta(seconds=1) # recorded before `by` + now, by = _now(), recorded + timedelta(seconds=1) # recorded before `by` for name, row in sorted(newest.items()): if not name.startswith("code_") or name in _ENTRY_LOCKED or not row["pass_finished"]: continue diff --git a/server/erasure/store/mutations.py b/server/erasure/store/mutations.py index 5dbcd8a4597..d1108764041 100644 --- a/server/erasure/store/mutations.py +++ b/server/erasure/store/mutations.py @@ -21,7 +21,7 @@ from typing import Any, cast from server.core.ch_names import split_table -from server.core.datetimes import as_aware_utc, to_naive_utc_second +from server.core.datetimes import as_aware_utc, to_naive_utc from server.core.repo_base import _CHClient, _default_client from server.erasure.store.predicates import NS_EQ, NS_IN from server.erasure.store.rows import MutationRow @@ -123,8 +123,8 @@ def recorded() -> datetime: def recorded_at() -> datetime: - """`recorded()` as naive UTC to the second, as a `DateTime` column compares.""" - return to_naive_utc_second(recorded()) + """`recorded()` as naive UTC, as a `DateTime` column compares.""" + return to_naive_utc(recorded()) def mutation_tag( diff --git a/server/memory/app/after_write.py b/server/memory/app/after_write.py index a5d707632cf..38d4b847b92 100644 --- a/server/memory/app/after_write.py +++ b/server/memory/app/after_write.py @@ -8,8 +8,9 @@ more inserts, seconds of them when the service's inserts are slow. `schedule` runs such a coroutine as a task of the request (it keeps the -request's context, so its statements carry the request's `log_comment`); the -set holds the live tasks of the running loop, and `drain()` at shutdown lets +request's context, so its statements carry the request's `log_comment`, unless +it is `detached`: a task that outlives the request starts with an empty one); +the set holds the live tasks of the running loop, and `drain()` at shutdown lets them land before the ClickHouse client goes away. A task scheduled with a `scope` (org, namespace) can be waited on by a read of that namespace in the same process (`settle`); the other processes see a graph projection in flight diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 59f7d57145b..8eae41f9308 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -733,9 +733,9 @@ class ClickHouseSettings(BaseModel): # Longest wait, ms, of a batched or waited async insert a request waits on; it holds a # pooled connection meanwhile. ch_batched_insert_wait_max_ms: Annotated[int, LIVE] = Field(default=50, gt=0, le=1000) - # Longest wait, ms, of the usage-event flusher's ticks and shutdown drain and the - # write-mark timer's flush, which no request waits on, except run.retract_credit while - # a tick is already sending. + # Longest wait, ms, of the usage-event flusher's ticks and shutdown drain, the + # write-mark timer's flush and the read-receipt sender's inserts, which no request + # waits on, except run.retract_credit while a tick is already sending. ch_batched_insert_background_wait_max_ms: Annotated[int, LIVE] = Field( default=200, gt=0, le=5000 ) diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 7a0fa0e1e94..3a03122ab4c 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -34,6 +34,8 @@ ORG = unique_org("read-receipts") FIRST = "the nightly backup of the orders cluster runs at 02:00 UTC" SECOND = "the nightly backup of the orders cluster runs at 04:30 UTC" +# Each web process answers some of a run of calls; this many reach every one. +_WEB_PROCESS_LOOKUPS = 6 QUERY = "when does the nightly backup of the orders cluster run" _COLUMNS = ( @@ -253,20 +255,28 @@ async def test_a_file_lookup_records_the_callers_row_of_another_namespace( owner = mint_test_token(org=ORG, namespaces=[home, records], roles=["writer"], subject="w") operator = mint_test_token(org="*", roles=["platform_admin"], subject="rr-operator") - async def default_scope(**body: Any) -> None: - """Set or clear the scope a read with no named scope takes (deployment-wide).""" + async def default_scope(**body: Any) -> bool: + """Set or clear the scope a read with no named scope takes (deployment-wide); + whether the server took it.""" async with httpx.AsyncClient(timeout=30.0) as http: r = await http.post( f"{control_plane_url}/v1/admin/settings.set", json={"name": "memory_search_default_namespace_scope", **body}, headers={"Authorization": f"Bearer {operator}"}, ) - assert r.status_code == 200, r.text + return r.status_code == 200 async def printed(a: Any) -> bool: out = await _read(a, "memory.for_file", run, path=path, tags=[repo]) return [hit["namespace"] for hit in out["hits"]] == [records] + async def shipped(a: Any) -> bool: + """Clear the override, again when a clear was refused, and say whether no lookup + prints the row any more: each web process answers some of them.""" + if not await default_scope(clear=True): + return False + return not any([await printed(a) for _ in range(_WEB_PROCESS_LOOKUPS)]) + async with Agent( org=ORG, namespace=home, agent="w", base_url=control_plane_url, api_key=owner ) as a: @@ -279,7 +289,7 @@ async def printed(a: Any) -> bool: files=[path], tags=[repo], ) - await default_scope(value="all_mine") + assert await default_scope(value="all_mine") try: await eventually( lambda: printed(a), @@ -287,8 +297,12 @@ async def printed(a: Any) -> bool: description="the file's block prints the caller's row of another namespace", ) finally: - await default_scope(clear=True) - await overrides_adopted() + await eventually( + lambda: shipped(a), + max_wait=30.0, + interval=0.5, + description="every server process serves the shipped scope again", + ) stored = await _stored(ch_client, records, "backup_window") rows = await _landed(ch_client, records, run_id=run) @@ -715,7 +729,10 @@ async def receipts_switch(control_plane_url: str) -> AsyncIterator[httpx.AsyncCl yield c finally: clear = {"name": "read_receipts_enabled", "clear": True} - await c.post("/v1/admin/settings.set", json=clear) + cleared = await c.post("/v1/admin/settings.set", json=clear) + if "no override to reset" not in cleared.text: # the test left one set + assert cleared.status_code == 200, cleared.text + await overrides_adopted() # every process writes receipts for the next test async def test_with_receipts_off_a_read_still_answers_and_writes_none( diff --git a/tests/unit/test_code_erasure_skip_busy.py b/tests/unit/test_code_erasure_skip_busy.py index 4731b6d4f18..8c097616eaf 100644 --- a/tests/unit/test_code_erasure_skip_busy.py +++ b/tests/unit/test_code_erasure_skip_busy.py @@ -128,6 +128,26 @@ async def test_a_first_run_and_a_resume_hold_the_same_passes(world: _World, resu assert await _purge(world) == 7 +@pytest.mark.parametrize("first_pass", [False, True]) +async def test_a_hold_lasts_a_deadline_past_the_recorded_second( + world: _World, monkeypatch: pytest.MonkeyPatch, first_pass: bool +) -> None: + """A pass that began late in the recorded second may write for its whole deadline, so + the purge waits that long past the second's end: for a worker's newest row and for an + enabled worker in its first pass alike.""" + second = world.recorded = world.recorded.replace(microsecond=0) + if first_pass: + world.enabled = ["code_ingest", "code_summary"] # code_summary has no row yet + world.ingest_row(second + timedelta(seconds=20)) # a supervisor reports + else: + world.ingest_row(second - timedelta(seconds=200)) # its pass began before + monkeypatch.setattr(erasing, "_now", lambda: second + timedelta(seconds=900.5)) + with pytest.raises(OverloadedError, match="pass that began before"): + await _purge(world) + monkeypatch.setattr(erasing, "_now", lambda: second + timedelta(seconds=901)) + assert await _purge(world) == 7 + + @pytest.mark.parametrize( ("lease", "says"), [("scip_entry:o/code-a", "entry lock"), ("code_refresh:o/code-a", "code.refresh")], diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py index abbcb014f2c..e29b0fa8404 100644 --- a/tests/unit/test_read_receipts.py +++ b/tests/unit/test_read_receipts.py @@ -5,6 +5,7 @@ import asyncio import re from collections.abc import Callable, Iterator +from datetime import UTC, datetime from pathlib import Path from types import SimpleNamespace from typing import Any @@ -36,6 +37,8 @@ OTHER_SHA = "b" * 64 MIRROR = "acl-" + "0" * 24 STORE = "crs-" + "0" * 24 +# When a redacted row was redacted: any time, since a note reads only that it is set. +_REDACTED_AT = datetime(2026, 1, 1, tzinfo=UTC) # Every op whose answer is receipted. RECEIPTED = { @@ -1241,33 +1244,71 @@ def note() -> None: assert _receipts(written) == [_receipt(MEMORY, "n", "k", 0, SHA)] +class _Selected: + """Answers the columns a statement selects of one stored row, as ClickHouse does.""" + + def __init__(self, stored: dict[str, Any]) -> None: + self.stored = stored + + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: + selected = set(re.findall(r"\w+", sql.split("FROM")[0])) + return [{name: value for name, value in self.stored.items() if name in selected}] + + +@pytest.mark.parametrize("redacted", [False, True]) @pytest.mark.parametrize("section", ["_stack_pinned", "_stack_recent"]) def test_a_stack_records_the_stored_revision_of_the_rows_it_selects( - written: list[list[dict[str, Any]]], section: str + written: list[list[dict[str, Any]]], section: str, redacted: bool ) -> None: """A stack's entries carry no revision: the statement that selects a pinned or a - recalled row notes the revision it read.""" + recalled row notes the revision it read, and no hash of a redacted row.""" from server.memory.api.models_lifecycle import MemoryStackInput from server.memory.app import stack from server.memory.app.served_reads import stack_keys stored = {"memory_key": "k", "value": "v", "version": 6, "content_sha256": SHA} - - class _Selected: - """Answers the columns the statement selects, as ClickHouse does.""" - - async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: - selected = set(re.findall(r"\w+", sql.split("FROM")[0])) - return [{name: value for name, value in stored.items() if name in selected}] + stored["redacted_at"] = _REDACTED_AT if redacted else None async def handler(input: MemoryStackInput) -> Any: fill = stack._StackFill(budget=100) - await getattr(stack, section)(_Selected(), input, fill) + await getattr(stack, section)(_Selected(stored), input, fill) return SimpleNamespace(entries=fill.entries) input = MemoryStackInput(org="o", namespace="n", agent="a") _run(rr.records_receipts(rr.memory_rows(stack_keys))(handler), input) - assert _receipts(written) == [_receipt(MEMORY, "n", "k", 6, SHA)] + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 6, "" if redacted else SHA)] + + +@pytest.mark.parametrize("redacted", [False, True]) +def test_a_file_lookup_records_the_stored_revision_of_the_rows_it_selects( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch, redacted: bool +) -> None: + """A lookup's hits carry no revision: the statement that selects the rows of a file + notes the revision it read, and no hash of a redacted row.""" + from server.memory.api.models_for_file import MemoryForFileInput + from server.memory.app import for_file + from server.memory.app.served_reads import printed_rows + + stored = { + "memory_id": "id-k", + "memory_key": "k", + "memory_type": "semantic", + "value": '"v"', + "tags": [], + "confidence": 1.0, + "pinned": 0, + "status_text": "active", + "agent": "a", + "matched_files": ["src/a.py"], + "version": 6, + "content_sha256": SHA, + "redacted_at": _REDACTED_AT if redacted else None, + } + monkeypatch.setattr(for_file, "get_client", lambda: _Selected(stored)) + input = MemoryForFileInput(org="o", namespace="n", path="src/a.py") + handler = rr.records_receipts(rr.memory_rows(printed_rows))(for_file.handle_memory_for_file) + _run(handler, input) + assert _receipts(written) == [_receipt(MEMORY, "n", "k", 6, "" if redacted else SHA)] def test_a_matched_procedure_records_the_stored_revision_of_its_body( From b5b3b69f90aad58bc90ee95a6a9c77cea72fd051 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 18:27:00 +0000 Subject: [PATCH 08/18] run.reliance lists what a run read, at which revisions, and what its client reported relying on A run's read receipts are the record of what Loom served it, and memories_used is the client's own statement of what it relied on. run.reliance joins the two in one viewer read: one entry per item, with the revisions the run was served and one of four states (returned, reported, reported_and_served, not_recorded). One function derives the state (server/tasks/domain/reliance.py) and every surface reads it through the op. No state means a mismatch: a read can leave no receipt, so a report with no record reads not_recorded. The answer names a revision by its stored versions, as decimal text, and carries no content hash and no reader: a receipt keeps the hash of a row that is redacted or labelled high-sensitivity after the read. The receipt statement returns one row per item, sorts the reported keys first and sorts an item's (hash, version) pairs before it cuts them. A cut answer (500 recorded items, 32 versions of each, truncated: true) therefore keeps every reported item and the highest versions. It has no time bound: a read can carry the run's id before the run's row is written and after the run closes. A failed receipt read fails the op, and a token narrowed below the namespace is refused, as for run.get. Surfaces: the wire op, the generated call in the five SDKs and agent.run.reliance in Python, loom call, loom_op by name, and the section "What this run read" in the dashboard's run detail. versionTime has its own module, so the shell's chunk does not carry it. Tests: unit cases for the function's truth table, the handler, the store statement's parameters and caps, and the op's contract; integration cases for each state against a server, for HTTP, the SDK, the CLI and MCP answering alike, for one run id in two namespaces and for a cut answer; the cross-principal walk probes the op with a seeded read; dashboard cases for the section and the run detail. Docs: the runs page has a section on what a run read, the read-receipts page a subsection on the op that reads a run. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- docs/architecture/read-receipts.md | 42 +- docs/features/dashboard.md | 2 +- docs/features/runs.md | 107 +- docs/guides/without-the-dashboard.md | 2 +- docs/reference/operations.md | 3 +- docs/reference/operations/run.md | 18 + docs/reference/status.md | 4 +- frontend/e2e/fixtures.ts | 46 + frontend/src/api/runs.test.ts | 17 +- frontend/src/api/runs.ts | 26 + frontend/src/flows/RunReliance.test.tsx | 314 +++++ frontend/src/flows/RunReliance.tsx | 223 ++++ frontend/src/lib/versionTime.test.ts | 23 + frontend/src/lib/versionTime.ts | 10 + frontend/src/views/Runs.detail.test.tsx | 65 +- frontend/src/views/Runs.fields.test.tsx | 1 + frontend/src/views/Runs.paging.test.tsx | 1 + frontend/src/views/Runs.rows.test.tsx | 1 + frontend/src/views/Runs.table.test.tsx | 1 + frontend/src/views/Runs.tsx | 9 +- sdk/go/client.gen.go | 26 + sdk/go/wire/models.gen.go | 34 +- sdk/python/loom/client.py | 8 + sdk/python/loom/ops.py | 48 + sdk/python/loom/run.py | 9 + sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 10 +- sdk/rust/src/blocking_operations.rs | 17 + sdk/rust/src/operations.rs | 18 + sdk/rust/src/wire_models.rs | 1084 +++++++++-------- sdk/rust/tests/registry_contracts.rs | 22 + sdk/typescript/src/generated/ops.ts | 29 +- server/operations/reach_manifest.py | 4 + server/settings/catalog.py | 2 + server/tasks/api/models_run.py | 52 +- server/tasks/api/ops_run.py | 15 + server/tasks/app/run.py | 41 +- server/tasks/domain/reliance.py | 110 ++ server/tasks/store/runs.py | 57 +- tests/analyzer/cases/planes.py | 5 +- tests/analyzer/shapes.txt | 1 + .../test_cross_principal_leakage.py | 27 + tests/integration/test_run_reliance.py | 266 ++++ tests/unit/session_content_senders.json | 6 +- tests/unit/snapshots/sdk_public_api.json | 7 + tests/unit/test_run_reliance.py | 386 ++++++ tests/unit/test_sdk_run_reliance.py | 28 + 46 files changed, 2705 insertions(+), 522 deletions(-) create mode 100644 frontend/src/flows/RunReliance.test.tsx create mode 100644 frontend/src/flows/RunReliance.tsx create mode 100644 frontend/src/lib/versionTime.test.ts create mode 100644 frontend/src/lib/versionTime.ts create mode 100644 server/tasks/domain/reliance.py create mode 100644 tests/integration/test_run_reliance.py create mode 100644 tests/unit/test_run_reliance.py create mode 100644 tests/unit/test_sdk_run_reliance.py diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 65eac2dc405..43aed464cee 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -237,8 +237,10 @@ month. ## Reading the table -No op serves this table; it is read with SQL. Bound every statement by time: an item -that is read often has many rows, and a run's rows sit in every namespace it read. +`run.reliance` serves one run's items in one namespace +([the op that reads a run](#the-op-that-reads-a-run)); every other question is answered +with SQL. Bound every statement by time: an item that is read often has many rows, and a +run's rows sit in every namespace it read. Which revision of an item a run saw: @@ -308,6 +310,40 @@ ORDER BY first_read `request_id` in `loom.memory_exposures` carries the query's digest and the keys returned. +### The op that reads a run + +`run.reliance` reads the receipts of one run in the namespace its caller names, after +the run's row in `loom.agent_runs`: a namespace that holds no run with the id answers +`found: false` and reads no receipt. [What a run read](../features/runs.md#what-a-run-read) +gives the answer's states and limits. + +- **One row an item.** The statement groups by `kind` and `item_key` and collects the + item's distinct `(content_sha256, version)` pairs, so its bound counts items and never + cuts inside one. The revisions are then grouped as the rule above says: on the hash + where there is one, on the version where there is none. +- **The reported keys sort first**, then the items served most recently. A report holds + at most 500 keys and the answer 500 recorded items, so a cut answer still holds every + reported item's receipts: a report reads as not recorded only when the run has no + receipt of the item. +- **The pairs are sorted before they are cut.** An item keeps its 32 highest pairs by + version. An aggregate that stops at the first pairs it meets can keep a different set + from one run of the statement to the next, and can drop the newest revision. +- **No time bound**, although a statement written by hand should carry one. A run's + labels can be older than its row: a header names any id, and `run.begin` can take that + id later. A lower bound from the run's start would answer "not recorded" for a record + that exists, and an upper bound at its close would drop the reads a resumed session + labels after the close. The read takes the `(org, namespace)` prefix of the key and + then tests the bloom filter on every granule of the namespace, so its cost grows with + the receipts the namespace keeps, not with the deployment's. +- **No hash in the answer.** A receipt written before a row was redacted or labelled + high-sensitivity keeps that read's hash for the receipt's lifetime, and the hash of a + short secret names it as well as the value does. The op groups and matches on the hash + and answers a revision by its versions; a revision the record holds by hash alone is + answered with no version. +- **No reader in the answer.** The statement selects no reader column. +- **A failed read fails the op.** A partial list would print "not recorded" for a + receipt that was not read. + ## Cost - **On the request's path**, a note is a dictionary write, and the reads that note a @@ -480,6 +516,8 @@ Without the setting, ClickHouse refuses to truncate a table above its - `server/memory/domain/read_receipts.py` (`Item`, `Noted`, `revision_of`, `receipts`) - `server/memory/store/read_receipts.py` - `server/knowledge/app/read_receipts.py` (the document ops' wrapped handlers) +- `server/tasks/store/runs.py` (`receipted_items`, the statement `run.reliance` runs) +- `server/tasks/domain/reliance.py` (`revisions_of`, `reliance`: the states) ## Related diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index b3465e2c7e8..1728f49835e 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -102,7 +102,7 @@ The account menu names the organization. Every page has a shareable URL. | **Recall** (tab of Memories) | `/recall` | "Why did this rank here": the rows the Memories list shows for a query with no filters set, in its order (keyword matches newest first, then `memory.search` hits with their ranking terms), and read past searches with every key and score they returned (`memory.search_trace_log`). | | **Library** | `/library` | Knowledge documents: add (a file, which is uploaded for the server's extractor, badged beforehand with the format `knowledge.formats` says it is read as, and whose ingest is followed to the revision it publishes, with **Stop ingestion** while it runs, `knowledge.ingest_cancel`; several files at once, picked or dropped, each its own document followed in a list with **Retry failed** and **Stop** ([many files](knowledge.md#many-files-from-the-dashboard)); a folder, which becomes a collection with its folders nested inside it (on My files or a namespace, the person picks a top-level collection or files kept with their folder paths) ([a folder](knowledge.md#a-folder-from-the-dashboard)); or pasted text), preview, download, edit metadata, move (**Move to…** on a row or a selection, `knowledge.move`, to a collection the person adds to, My files or the namespace at the top: [moving documents](knowledge.md#moving-documents); beside the tree, a row dragged onto a place, with the selection when it is in one, opens **Move to…** set to that place, and only the places **Move to…** lists take the drop), delete (the notice it raises carries **Undo**, `knowledge.restore`, which restores the document's last deleted revision, whichever delete retired it; a bulk delete's notice has none), review the typed tables a document's file became from its preview's **Tables** and approve their column types (`knowledge.dataset_get`, `knowledge.dataset_approve`), and find a passage inside the documents (**Find a passage**, `knowledge.search`; each hit is cited by its revision and place, in lines, a key, pages or slides, or rows, and opens its document). Where the page is at least 1036 px wide (from a 1280 px window with the sidebar open; **Ask AI** beside the page narrows it), a tree beside the documents lists where they can be: **All documents**, the namespace picked at the top, **My files**, the person's [collections](../architecture/sharing.md) nested as they sit (a button before each one that holds others shows or hides them, which the browser remembers per person and org; the one shown and its parents open by themselves), and **Shared with you** (`collection.list`); **New collection** at its foot turns into a title field that says where the collection goes: inside the collection shown when it is pressed, if the person writes there, else at the top level. Narrower, a select above the list shows **All documents**, the namespace or one of the collections, as a tree with each one's title and description (its `col-…` address in **About this place**; a title shown twice carries its address); `?collection=` names it (`?place=all` names All documents). At every width the browser tab names the place shown. **All documents** is one list of the documents of every place the person reads in the Library (the namespace at the top, **My files** and the collections, in the tree's order), read in one `knowledge.list` call that names them in `namespaces`, up to the 101 places one call takes; the rest are said to be left out. Each row says where it lives, as a link to that place, and takes its writes from that place's role: a row of a collection the person only reads has no checkbox and its writes say why, and **Move to…** takes a selection from one place at a time. What the read left out is said above the rows, never as part of the whole: when the read is refused, each place is read alone to name the ones refused (and any whose own read then failed, with **Read again**), and the rest are listed; a place refused is left out of later reads, still named, until the collections answer again (they are read again the first time a place is refused, and a grant that had not reached the reading replica yet is then read); any other failure is the list's error, with **Retry**. The figures line counts the places read ("4 of 5 places"), or only those read ("3 places read") while the collections could not be loaded or their list stops early. From a server a release behind that reads one place per call, the page says only the first is shown, and a **Load more** that server cannot continue reads the list again from the top. Its **Add document** adds to the namespace at the top, else to **My files**. Elsewhere, while something is searched, a choice under the search bar keeps the search in **This collection** (**This namespace** on a namespace) or takes it **Everywhere**, which reads every place, for the list and for **Find a passage** (the places the list read, saying how many it leaves out; the panel stays open and asks again when the scope changes), each row saying where it lives; All documents always searches everywhere. A collection's path from the top runs on one line above the list (beside the tree, it ends with the collection's title): the place above, the ones above the parent folded into a dots button, and the parent, each a link (a parent the person cannot read shows as a dots button, which gives its address when tapped). From 640 px wide the collections inside the one shown sit as a row of folder chips above its documents (on a phone the select lists them), and, where the tree is not shown, on **My files** and on a namespace, below the documents **Collections** lists the person's own top-level ones (and their own whose parent they cannot read), with **Shared with you** below them: the collections the person reads or writes but does not administer (one inside another shared with them shows inside it), each list naming the parents of a collection inside another, in words for a parent missing from the list (`collection.list` names no owner, so one shared as admin sits with the person's own, and the role is the token's: a token capped below admin lists the person's own here too). Each list of places in the tree shows its first fifty (the way to the place shown always among them), the chips and each list below the documents their first six, and each Show more adds fifty; on a phone the path is one back button beside the select, and the select, a tree, lists the collections inside. On a code or tracker namespace, or none, the select lists only collections; with no namespace at the top, the Library opens **My files** (a token that is not a person's has no files of its own: it stays on the top level, which lists the collections). Under the path, a collection's header says who can see it, in words: the grants on it and on the parents it inherits from, as far as the person can read them (`grants.list`, [inheritance](../architecture/sharing.md#the-model)); **My files** say they are the person's alone. **Share**, beside **Add document** (its icon alone on a phone), opens its members in place for its admins (`grants.*`), with who else can see it through each parent listed beneath them, read-only and linked to the parent; anyone else gets **See who**, the same dialog with its controls unavailable. Its menu holds **Budget…**; its admins move it under another collection or to the top (`collection.move`; beside the tree, dragging it onto a collection it may go inside, or onto **Drop here for the top level**, opens that move set to it) and delete it, which erases what it holds (`collection.delete`); **New collection** creates one from a title, inside the one shown when the person writes there; the server derives its address, and a title already used inside the same collection (at the top level, one of the person's own) opens that one (with **Choose the address myself**, the title is kept as given) ([names and titles](../architecture/sharing.md)). The header's **New** adds to the header's namespace, so while the Library shows a collection, or a namespace that holds no documents, it offers no **Document**: the Library's own **Add document** adds where the Library shows. The select finds a collection by its title, address or description as you type. See [knowledge](knowledge.md). **Sources**, in the header's actions and counting them (its icon alone on a phone), opens the document sources of the shared namespace or collection in view below the header, with their last sync; the [sources table](knowledge.md#document-sources) says who changes them. | | **Conversations** | `/conversations` | Stored conversation threads, replayed turn by turn (a writer renames a thread, an admin deletes one), and the saved session briefs, which a writer forgets. See [conversations and sessions](conversations-and-sessions.md). | -| **Runs** | `/runs` | The run ledger: goal, how it ended, what it relied on and wrote, and in the replay what it recalled, observed and cost; a writer grades a closed run by whether it held up. See [runs](runs.md). | +| **Runs** | `/runs` | The run ledger: goal, how it ended, what it relied on and wrote, and in the replay what it recalled, observed and cost, and what it read: the revision of each item and what the agent reported relying on; a writer grades a closed run by whether it held up. See [runs](runs.md). | | **Tasks** | `/tasks` | The task inbox board. Tiles count what needs a person (triage, blocked on a person, failed, leases about to end); rows group as Triage, To do, In progress, Waiting, Closed, as a list or a board, with Accept / Won't do inline; the panel's buttons or a drag onto another group move a task. See [tasks and decisions](tasks-and-decisions.md). | | **Repositories** | `/repositories` | Indexed code repositories, each with Health, Explore, PR packs and Access tabs, and the org's trackers; a branch's admin re-indexes it after one of its commits. An opened repository lists its documents and their sources, each with its last sync; a source's name opens its settings, sync state and the documents it wrote (`knowledge.source.inspect`), and a caller with the role the [sources table](knowledge.md#document-sources) names adds, checks, edits, syncs, rotates and retires a source there. See [code index](code-index/overview.md) and [tracker](tracker/overview.md). | | **Settings** | `/settings` | **Tokens** (one form for every token: what it reads, where it saves, its expiry; the setup for each MCP client or a script; the list, with what each token reads); **Memory** (`?tab=memory`: patterns never to save, each with a sweep of the memories it already matches, seeding memory from a document, and the webhooks that receive its memory changes and their deliveries); **Structure** (`?tab=structure`, on a memory namespace: the record schemas, each one's records and disagreements with the record each disagreement superseded, the profile schema, the graph ontology and the categories; an admin registers and approves schemas, sets or clears the profile schema and accepts and adds ontology terms, a writer adds categories); and **Models & keys** for a platform admin. | diff --git a/docs/features/runs.md b/docs/features/runs.md index 067cdac0a29..e0380a41ecd 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -30,7 +30,9 @@ Which revision of a memory row or document a read of the run carried is kept apa `loom.read_receipts` under the run's `run_id`, so it can still be told after the item changes. Not every read writes a receipt ([what gets none](../architecture/read-receipts.md#what-gets-none)): a missing one means -"not recorded", not "not served". No op serves the table; it is read with SQL +"not recorded", not "not served". `run.reliance` lists a run's receipts beside what its +client reported ([what a run read](#what-a-run-read)); any other question of the table +is answered with SQL ([reading the table](../architecture/read-receipts.md#reading-the-table)). ## Budgets @@ -112,6 +114,92 @@ empty, `ok` from the outcome); an agent that calls `procedure.record_run` itself leave that key out of `memories_used` so the run is not counted twice. See [procedures and learnings](memory/procedures-and-learnings.md). +## What a run read + +`run.reliance` lists the items one run read, the revisions it was served, and what its +client reported relying on. The answer joins two sources and keeps them apart: + +- An item is **served** when an answer of Loom carried it. The run's + [read receipts](../architecture/read-receipts.md) are the record of that. +- The **report** is `memories_used`: the client's own statement, as the run's last + `run.complete` kept it. A close keeps a key only when it names a live memory of the + run's namespace. A key of another namespace, a key with no live row and a passage id + are in no report. A later `run.complete` that names no memory, or a `run.begin` sent + again, leaves the run with no report. + +Each item has one state, true as of the read: + +| State | The dashboard's label | Shows | Does not show | +| --------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `returned` | Recalled | Loom served the item under the run. | That the agent read or used it. | +| `reported` | Reported as relied on | The client named the item, and the record holds it at the revisions listed. | Which of those revisions the agent relied on. | +| `reported_and_served` | Recalled, and reported as relied on | The report names a revision the record holds. `memories_used` names keys and no revision, so no report reaches this state. | That the item changed the agent's answer. | +| `not_recorded` | Reported as relied on, recall not recorded | The client named the item, and the run has no record of it. | That the item was not served. It is never a mismatch: [what is not listed](#what-is-not-listed) gives the reasons a record can be missing. | + +An item's `revisions` are what the record holds, highest version first, and each one's +`versions` are the stored versions under which the run was served one content. For a +memory they are the `version` of `memory.history`, as decimal text, and the dashboard +shows the time that version was written. For a document they are its revision number. A +`not_recorded` item has no revision: the answer never fills in the item's latest. + +`run.get` answers a different question from other sources: its `recalled` and +`recalled_keys` come from the search trace log and the keys a client sent at the close, +this list from the receipts, so the two can differ. + +The answer holds at most 500 recorded items and the 32 highest recorded versions of +each. Past either bound `truncated` is true; every reported item is kept, then the items +served most recently. + +```bash +loom call run.reliance run_id= --namespace +``` + +```python +answer = await agent.run.reliance(run_id) +for item in answer["items"]: + print(item["state"], item["kind"], item["key"]) +``` + +### What is listed + +A read is listed when its receipt names the run. Which reads carry the run depends on the +caller: + +| Caller | Its reads are listed when | +| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Any HTTP client | The request's body names the run (`run_id`), or the request carries the `X-Loom-Run-Id` header. On a recall read a body `run_id` also filters to the run's own rows, so label such a read with the header. | +| The Python SDK | The read is made in a run scope, which sends the header on `memory.search`, `memory.search_trace`, `memory.ask` and `memory.list`, and on no document read. | +| The Rust SDK | The client is bound to a run: it sends the header on every call. | +| The TypeScript, Go and Ruby SDKs | The call's input names the run. These SDKs send no run header. | +| An MCP session | The read is one the session's run labels ([reading the table](../architecture/read-receipts.md#reading-the-table) names them). No answer gives an agent the id of its session's run, so over MCP an agent calls `run.reliance` through `loom_op` for a run id it holds: one it opened with `run.begin`, or one a person gave it. | + +A document read with the header: + +```bash +curl -sX POST "$LOOM_BASE_URL/v1/knowledge.search" -H "Authorization: Bearer $LOOM_API_KEY" \ + -H 'Content-Type: application/json' -H 'X-Loom-Run-Id: ' \ + -d '{"org":"acme","namespace":"support","query":"refund policy for annual plans"}' +``` + +### What is not listed + +- **A read that wrote no receipt**: a request that runs a mirror leg and the other cases + of [what gets none](../architecture/read-receipts.md#what-gets-none). +- **An item of another namespace.** A receipt is filed under the namespace that holds + the item, and a report keeps only keys of the run's namespace. +- **A read older than the receipts' lifetime** + ([the receipt row](../architecture/read-receipts.md#the-receipt-row)). +- **Which passage of a document was served.** A document is listed once, with its + revisions. +- **Who read.** A run id on a read is client input: any caller that can read the + namespace can label a read with a run's id, so the list can hold another caller's + reads of the namespace's items, and it never names a reader. +- **The agent's own reads over MCP, for a run a plugin's hook opens.** The hook's run + lists the items of the context packs the hooks requested. The reads the agent makes + over MCP are filed under the session's run, a second row of the Runs list, which the + list shows with "Show runs with no memory activity" while that run saved and reported + nothing. + ## Taking back a run's credit `run.retract_credit` cancels the `used`, `evidence` and `harm` events that a run's @@ -312,14 +400,15 @@ so no run dated before the erasure comes back. ## Operations -| Operation | Role | Does | -| -------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `run.begin` | writer | Open a run: `goal` (required), `user_request`, `expected_outcome`, `run_id` (empty or `-`: minted), `session_id`, `role`, `model`, `metadata`. Re-sending the same `run_id` replaces the row; an id of the MCP transport's shape (`mcp-` and 40 hex digits) gets an id of its own. | -| `run.complete` | writer | Close it once: `status`, `memories_used`, `memories_delivered`, `recalled_keys`, `outcome`, `reflection`, `retain`. Not idempotent: completing twice appends usage events twice. | -| `run.get` | viewer | One run with its live derivations. | -| `run.list` | viewer | One page of runs, filtered by `agent`, `session_id`, `status`, `grade`, `q` and `memory_activity` (`with` keeps runs that relied on or wrote a memory, `without` the hollow ones; filters apply before `limit`). | -| `run.grade` | writer | Grade a closed run or a session's runs `pass` / `fail`. | -| `run.retract_credit` | writer | Cancel the `used`, `evidence` and `harm` events of a run's labels, or of the caller's labels in a window (`since`, `until`), with compensating events; `dry_run` reports only. Idempotent. | +| Operation | Role | Does | +| ------------------------------------------------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `run.begin` | writer | Open a run: `goal` (required), `user_request`, `expected_outcome`, `run_id` (empty or `-`: minted), `session_id`, `role`, `model`, `metadata`. Re-sending the same `run_id` replaces the row; an id of the MCP transport's shape (`mcp-` and 40 hex digits) gets an id of its own. | +| `run.complete` | writer | Close it once: `status`, `memories_used`, `memories_delivered`, `recalled_keys`, `outcome`, `reflection`, `retain`. Not idempotent: completing twice appends usage events twice. | +| `run.get` | viewer | One run with its live derivations. | +| `run.list` | viewer | One page of runs, filtered by `agent`, `session_id`, `status`, `grade`, `q` and `memory_activity` (`with` keeps runs that relied on or wrote a memory, `without` the hollow ones; filters apply before `limit`). | +| [`run.reliance`](../reference/operations/run.md#runreliance) | viewer | What a run was served, at which revisions, and what its client reported relying on, with one state per item ([what a run read](#what-a-run-read)). | +| `run.grade` | writer | Grade a closed run or a session's runs `pass` / `fail`. | +| `run.retract_credit` | writer | Cancel the `used`, `evidence` and `harm` events of a run's labels, or of the caller's labels in a window (`since`, `until`), with compensating events; `dry_run` reports only. Idempotent. | `run.list` pages with `order_by` (start time, duration or memories relied on, each ascending or descending; `started_desc`, newest first, by default) and `offset` (at most diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index d950ac1fe25..a0fa98f9ab1 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -81,7 +81,7 @@ are on `agent.account` and `agent.deployment`. | Review queue (conflicts) | `conflicts.list`, `conflicts.resolve`, `learnings.review` | `agent.conflicts.list()`, `.resolve(...)` | | Activity, audit log | `profile.activity`, `audit.list`, `agents.connected`, `mentor.brief`, `memory.exposure_summary`, `memory.owner_report` | `agent.audit.list(...)`, `agent.profile.*` | | Cost and budgets | `cost.summary`, `cost.budget_status` | `agent.cost.summary(...)` | -| Runs | `run.list`, `run.get` | `agent.run.*` | +| Runs | `run.list`, `run.get`, `run.reliance` | `agent.run.*` | | Code index | `code.index_status`, `code.repo.add`, … | `agent.code.*` | | Erasure, forgetting | `erasure.request`, `erasure.status`, `erasure.list`, `erasure.export`, `memory.clear` | `agent.erasure.*` | | Tasks and inbox | `task.create`, `task.pull`, `task.updates`, `inbox.*` | `agent.tasks.*` | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 5e390acc2fd..bcf53332329 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -124,7 +124,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -385 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +386 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row. @@ -709,6 +709,7 @@ Fields for every `run` op: [operations/run.md](operations/run.md). | [`run.get`](operations/run.md#runget) | Replay one run: goal, status, final response, the memories it relied on, the memory_keys it wrote, how many memories it recalled and observed, and what its model turns cost. | viewer | read | yes | | | [`run.grade`](operations/run.md#rungrade) | A verdict on a CLOSED run, usually days after it — a maintainer confirmed the finding, CI passed, a reviewer rejected it. | writer | idempotent | no | yes | | [`run.list`](operations/run.md#runlist) | A page of a namespace's agent runs and their match count (`total`), filtered and sorted. | viewer | read | no | | +| [`run.reliance`](operations/run.md#runreliance) | What one run was served, at which revisions, and what its client reported relying on. | viewer | read | no | | | [`run.retract_credit`](operations/run.md#runretract_credit) | Cancel the usage credit of one run, or of the caller's labels over at most 30 days. | writer | idempotent | no | yes | ### search diff --git a/docs/reference/operations/run.md b/docs/reference/operations/run.md index d5c91c11cc5..536c4b00ecb 100644 --- a/docs/reference/operations/run.md +++ b/docs/reference/operations/run.md @@ -163,6 +163,24 @@ A page of a namespace's agent runs and their match count (`total`), filtered and | `runs` | `list[RunRow]` | Matching runs in `order_by` order (newest `started_at` first by default), projected to `fields` when given. | | `total` | `int \| None` | How many runs match the filters; null on a full page after the first. | +## `run.reliance` + +What one run was served, at which revisions, and what its client reported relying on. + +`POST /v1/run.reliance` · MCP `loom_run_reliance` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The tenant (first element of the identity tuple). | +| `namespace` | `str` | required | The namespace the op reads or writes. | +| `run_id` | `str` | required | The run whose reads and report are listed. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `found` | `bool` | False when the namespace holds no run with this id; `items` is then empty. | +| `items` | `list[RunRelianceItem]` | One entry per item: `returned` (served, not reported), `reported` (the client's claim, for an item the record holds), `reported_and_served` (the claim names a served revision), `not_recorded` (reported, no record: not a mismatch). | +| `truncated` | `bool` | True when the answer is cut: it keeps every reported item, then the items served most recently, 500 recorded items in all, and the 32 highest recorded versions of each. | + ## `run.retract_credit` Cancel the usage credit of one run, or of the caller's labels over at most 30 days. diff --git a/docs/reference/status.md b/docs/reference/status.md index 6ba1f20fe13..37781966fa1 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -385 operations, 271 of them experimental. +386 operations, 272 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -64,7 +64,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `procedure` | 2 | [`procedure.evolve`](operations/procedure.md#procedureevolve), [`procedure.fork`](operations/procedure.md#procedurefork), [`procedure.list`](operations/procedure.md#procedurelist), [`procedure.locate`](operations/procedure.md#procedurelocate), [`procedure.record_run`](operations/procedure.md#procedurerecord_run), [`procedure.revise`](operations/procedure.md#procedurerevise) | | `profile` | 2 | [`profile.append`](operations/profile.md#profileappend), [`profile.replace`](operations/profile.md#profilereplace), [`profile.set`](operations/profile.md#profileset), [`profile.structured`](operations/profile.md#profilestructured) | | `profile_schema` | 0 | [`profile_schema.clear`](operations/profile_schema.md#profile_schemaclear), [`profile_schema.get`](operations/profile_schema.md#profile_schemaget), [`profile_schema.set`](operations/profile_schema.md#profile_schemaset) | -| `run` | 4 | [`run.grade`](operations/run.md#rungrade), [`run.retract_credit`](operations/run.md#runretract_credit) | +| `run` | 4 | [`run.grade`](operations/run.md#rungrade), [`run.reliance`](operations/run.md#runreliance), [`run.retract_credit`](operations/run.md#runretract_credit) | | `search` | 0 | [`search.query`](operations/search.md#searchquery) | | `session` | 0 | [`session.brief_delete`](operations/session.md#sessionbrief_delete), [`session.brief_get`](operations/session.md#sessionbrief_get), [`session.brief_list`](operations/session.md#sessionbrief_list), [`session.brief_save`](operations/session.md#sessionbrief_save) | | `task` | 0 | [`task.accept`](operations/task.md#taskaccept), [`task.block`](operations/task.md#taskblock), [`task.cancel`](operations/task.md#taskcancel), [`task.claim`](operations/task.md#taskclaim), [`task.complete`](operations/task.md#taskcomplete), [`task.counts`](operations/task.md#taskcounts), [`task.create`](operations/task.md#taskcreate), [`task.defer`](operations/task.md#taskdefer), [`task.fail`](operations/task.md#taskfail), [`task.get`](operations/task.md#taskget), [`task.heartbeat`](operations/task.md#taskheartbeat), [`task.history`](operations/task.md#taskhistory), [`task.list`](operations/task.md#tasklist), [`task.progress`](operations/task.md#taskprogress), [`task.pull`](operations/task.md#taskpull), [`task.reassign`](operations/task.md#taskreassign), [`task.reopen`](operations/task.md#taskreopen), [`task.resume`](operations/task.md#taskresume), [`task.unblock`](operations/task.md#taskunblock), [`task.update`](operations/task.md#taskupdate), [`task.updates`](operations/task.md#taskupdates), [`task.wont_do`](operations/task.md#taskwont_do) | diff --git a/frontend/e2e/fixtures.ts b/frontend/e2e/fixtures.ts index 1f93a101335..f6d87de1efe 100644 --- a/frontend/e2e/fixtures.ts +++ b/frontend/e2e/fixtures.ts @@ -1190,6 +1190,8 @@ export async function installApi(page: Page, options: InstallOptions = {}): Prom return json({ hits: conversationHitsFixture(options.threadRows, Number(body.top_k ?? 50)) }); case "/v1/run.get": return json(runGetFixture(runRowsFixture(options.runRows ?? 0, ns), String(body.run_id ?? ""))); + case "/v1/run.reliance": + return json(RUN_RELIANCE_FIXTURE); case "/v1/tracker.source.list": calls.trackerSources++; if (trackerSources === null) { @@ -1449,6 +1451,50 @@ function runRowsFixture(n: number, namespace: string): Record[] /** `run.get` for one of `runs` (RunGetOutput in server/tasks/api/models_run.py): the * row and what the server derives live — the keys recalled and written, the session's * turns and cost, the budgets passed. An unknown id answers `found: false`. */ +/** What a run read, one row of each state: a memory recalled and reported, a document only + * recalled, a memory reported at a revision the run was served, and a report with no record. */ +const RUN_RELIANCE_FIXTURE = { + found: true, + truncated: false, + items: [ + { + kind: "memory", + key: "runbooks/ingest-lag", + state: "reported", + revisions: [{ versions: ["1789891200000000000", "1789891260000000000"] }, { versions: [] }], + last_served_at: "2026-09-20T08:01:00.000Z", + }, + { + kind: "memory", + key: "oncall/escalation-policy", + state: "reported_and_served", + revisions: [{ versions: ["1789804800000000000"] }], + last_served_at: "2026-09-20T08:00:30.000Z", + }, + { + kind: "memory", + key: "alerts/known-noisy", + state: "not_recorded", + revisions: [], + last_served_at: "", + }, + { + kind: "document", + key: "https://docs.example.com/runbooks/ingest-lag.md", + state: "returned", + revisions: [{ versions: ["3"] }], + last_served_at: "2026-09-20T08:00:10.000Z", + }, + { + kind: "memory", + key: "services/ingest-owner", + state: "returned", + revisions: [], + last_served_at: "2026-09-20T08:00:05.000Z", + }, + ], +}; + function runGetFixture(runs: Record[], runId: string): Record { const run = runs.find((r) => r.run_id === runId); if (!run) { diff --git a/frontend/src/api/runs.test.ts b/frontend/src/api/runs.test.ts index ef0fa4d4dcc..6d7b71209dd 100644 --- a/frontend/src/api/runs.test.ts +++ b/frontend/src/api/runs.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { listRunsPage, RUN_LIST_MAX_Q } from "./runs"; +import { getRunReliance, listRunsPage, RUN_LIST_MAX_Q } from "./runs"; // run.list takes a search of at most RUN_LIST_MAX_Q characters: a longer one (a pasted // goal) is cut to it, so the page shows results rather than a 422. @@ -44,3 +44,18 @@ describe("listRunsPage", () => { expect(await listRunsPage(id, {})).toMatchObject({ total: 0, paged: true }); }); }); + +describe("getRunReliance", () => { + it("asks for the run in the namespace the page reads", async () => { + const answer = { found: true, items: [], truncated: false }; + const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => Response.json(answer)); + vi.stubGlobal("fetch", fetchMock); + expect(await getRunReliance({ org: "dev", namespace: "team" }, "r-1")).toEqual(answer); + expect(String(fetchMock.mock.calls[0][0])).toMatch(/\/v1\/run\.reliance$/); + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ + org: "dev", + namespace: "team", + run_id: "r-1", + }); + }); +}); diff --git a/frontend/src/api/runs.ts b/frontend/src/api/runs.ts index ba8f894c62f..207bb9b3632 100644 --- a/frontend/src/api/runs.ts +++ b/frontend/src/api/runs.ts @@ -130,6 +130,32 @@ export async function getRun(id: { org: string; namespace: string }, runId: stri return post("/v1/run.get", { org: id.org, namespace: id.namespace, run_id: runId }); } +/** One item a run was served or its agent reported. `state` is a string the server derives: + * the section's label map is the only place the dashboard spells one. */ +export interface RunRelianceItem { + kind: string; // "memory" or "document" + key: string; + state: string; + // Highest version first; a revision held by its hash alone has no version. Versions are + // decimal text: a memory's is above 2^53. + revisions: { versions: string[] }[]; + last_served_at: string; // "" for a report with no record +} + +export interface RunRelianceResponse { + found: boolean; + items: RunRelianceItem[]; + truncated: boolean; +} + +/** What a run was served, at which revisions, and what its agent reported relying on. */ +export async function getRunReliance( + id: { org: string; namespace: string }, + runId: string, +): Promise { + return post("/v1/run.reliance", { org: id.org, namespace: id.namespace, run_id: runId }); +} + /** A proposal an owner's auto policy accepted or rejected on a grade. */ export interface RunGradeProposal { memory_key: string; diff --git a/frontend/src/flows/RunReliance.test.tsx b/frontend/src/flows/RunReliance.test.tsx new file mode 100644 index 00000000000..b476641557e --- /dev/null +++ b/frontend/src/flows/RunReliance.test.tsx @@ -0,0 +1,314 @@ +import { cleanup, fireEvent, render, screen, waitFor, within } from "../test/rtl"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiError, type RunRelianceItem, type RunRelianceResponse } from "../api"; +import { useStore } from "../lib/state"; +import { must } from "../test/must"; +import { opNames } from "../test/opNames"; +import { RunReliance } from "./RunReliance"; + +// What a run read: one row per item with the revisions the run was served and one label +// that joins the recall on record with the agent's report. The server derives the state; +// the section words it and never infers one. + +const getRunReliance = vi.fn(); +vi.mock("../api", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getRunReliance: (...args: Parameters) => getRunReliance(...args) }; +}); + +const identity = { org: "dev", namespace: "team" }; +// 2026-12-03 14:32:09 UTC and one second later, as epoch nanoseconds. +const V1 = "1796308329123456789"; +const V2 = "1796308330123456789"; + +const item = (over: Partial = {}): RunRelianceItem => ({ + kind: "memory", + key: "deploy_window", + state: "returned", + revisions: [{ versions: [V1] }], + last_served_at: "2026-12-03T15:00:00.000Z", + ...over, +}); +const answer = (items: RunRelianceItem[], over: Partial = {}): RunRelianceResponse => ({ + found: true, + items, + truncated: false, + ...over, +}); + +const STANDING = + "Lists the reads Loom recorded under this run for items of this namespace. A read that is not listed may still have happened: its record can expire, fail to be written, be filed under another run, or name an item of another namespace."; +const REPORT_NOTE = + "A report names no revision, so for a reported memory the revisions shown are what this run was served, not which one the agent relied on."; +const CUT_NOTE = + "This list is cut: it keeps every reported item, the items read most recently, and the newest revisions of each."; +const EMPTY = + "No read is on record for this run, and the agent reported no memory it relied on. A read is listed when its request names this run, as the coding-agent plugins and the SDK's run scope do."; + +async function table(): Promise { + return screen.findByRole("table", { name: "What this run read" }); +} +/** The table row that holds `key`'s chip. */ +async function rowOf(key: string): Promise { + const cell = within(await table()).getByText(key); + return must(cell.closest("tr"), `row of ${key}`); +} + +describe("RunReliance", () => { + beforeEach(() => { + vi.clearAllMocks(); + useStore.setState({ authed: true, identity: { ...identity, agent: "loom-ui" }, view: "runs" }); + }); + afterEach(() => { + cleanup(); + useStore.setState({ identity: null, inspectedMemoryKey: null, pendingDocSourceUri: null }); + }); + + it("reads the run once, in the namespace the page reads", async () => { + getRunReliance.mockResolvedValue(answer([item()])); + render(); + await table(); + expect(getRunReliance).toHaveBeenCalledTimes(1); + expect(getRunReliance).toHaveBeenCalledWith(identity, "r1"); + expect(screen.getByRole("heading", { name: "What this run read" })).toBeInTheDocument(); + for (const header of ["Item", "Revision", "Recall and report", "Last read"]) { + expect(screen.getByRole("columnheader", { name: header })).toBeInTheDocument(); + } + }); + + it("words each state in full", async () => { + getRunReliance.mockResolvedValue( + answer([ + item({ key: "k_returned", state: "returned" }), + item({ key: "k_both", state: "reported_and_served" }), + item({ key: "k_reported", state: "reported" }), + item({ key: "k_missing", state: "not_recorded", revisions: [], last_served_at: "" }), + ]), + ); + render(); + const label = async (key: string) => within(await rowOf(key)).getByText(/Recalled|Reported/).textContent; + expect(await label("k_returned")).toBe("Recalled"); + expect(await label("k_both")).toBe("Recalled, and reported as relied on"); + expect(await label("k_reported")).toBe("Reported as relied on"); + expect(await label("k_missing")).toBe("Reported as relied on, recall not recorded"); + }); + + it("names a memory revision by the time its lowest version was written", async () => { + getRunReliance.mockResolvedValue(answer([item({ revisions: [{ versions: [V1, V2] }] })])); + render(); + const row = await rowOf("deploy_window"); + expect(within(row).getByText("Dec 3, 2026, 14:32 UTC").closest("time")).toHaveAttribute( + "datetime", + "2026-12-03T14:32:09.123Z", + ); + expect(row).toHaveTextContent("Written Dec 3, 2026, 14:32 UTC"); + expect(row).not.toHaveTextContent(V1); + }); + + it("shows the digits of a memory version that is no write time", async () => { + getRunReliance.mockResolvedValue(answer([item({ revisions: [{ versions: ["42"] }] })])); + render(); + expect(await rowOf("deploy_window")).toHaveTextContent("Version 42"); + }); + + it("names a document revision by its number", async () => { + getRunReliance.mockResolvedValue( + answer([item({ kind: "document", key: "docs://runbook", revisions: [{ versions: ["7"] }] })]), + ); + render(); + expect(await rowOf("docs://runbook")).toHaveTextContent("Revision 7"); + }); + + it("says a revision held with no version, and an item held with no revision", async () => { + getRunReliance.mockResolvedValue( + answer([ + item({ key: "by_hash", revisions: [{ versions: [] }] }), + item({ key: "no_revision", revisions: [] }), + item({ key: "no_record", state: "not_recorded", revisions: [], last_served_at: "" }), + ]), + ); + render(); + expect(within(await rowOf("by_hash")).getByText("Version not recorded")).toBeInTheDocument(); + expect(within(await rowOf("no_revision")).getByText("Revision not recorded")).toBeInTheDocument(); + // A report with no record shows no revision, never the item's latest, and no time. + const missing = await rowOf("no_record"); + // Click UI's table repeats the column's header in each cell, for its phone layout. + expect(missing.querySelectorAll("td")[1]).toHaveTextContent(/^Revision$/); + expect(missing.querySelector("time")).toBeNull(); + }); + + it("shows five revisions of an item and counts the rest", async () => { + const revisions = Array.from({ length: 7 }, (_, i) => ({ versions: [String(7 - i)] })); + getRunReliance.mockResolvedValue( + answer([ + item({ kind: "document", key: "docs://long", revisions }), + item({ kind: "document", key: "docs://six", revisions: revisions.slice(0, 6) }), + ]), + ); + render(); + const row = await rowOf("docs://long"); + for (const n of [7, 6, 5, 4, 3]) expect(within(row).getByText(String(n))).toBeInTheDocument(); + expect(within(row).queryByText("2")).toBeNull(); + expect(within(row).getByText("and 2 earlier revisions")).toBeInTheDocument(); + expect(within(await rowOf("docs://six")).getByText("and 1 earlier revision")).toBeInTheDocument(); + }); + + it("a memory opens in the inspector and a document in the Library", async () => { + getRunReliance.mockResolvedValue( + answer([item(), item({ kind: "document", key: "docs://runbook", revisions: [{ versions: ["7"] }] })]), + ); + render(); + fireEvent.click(within(await table()).getByRole("button", { name: "deploy_window" })); + expect(useStore.getState().inspectedMemoryKey).toBe("deploy_window"); + fireEvent.click(within(await table()).getByRole("button", { name: "docs://runbook" })); + expect(useStore.getState().pendingDocSourceUri).toBe("docs://runbook"); + expect(useStore.getState().view).toBe("knowledge"); + }); + + it("an item of a kind it does not know opens nothing and shows its kind", async () => { + getRunReliance.mockResolvedValue(answer([item({ kind: "ticket", key: "T-1", revisions: [] })])); + render(); + const row = await rowOf("T-1"); + expect(within(row).queryByRole("button")).toBeNull(); + expect(within(row).getByText("ticket")).toBeInTheDocument(); + }); + + it("a state it has no label for draws no badge", async () => { + getRunReliance.mockResolvedValue(answer([item({ state: "superseded" })])); + render(); + const row = await rowOf("deploy_window"); + expect(row).not.toHaveTextContent(/superseded|Recalled|Reported/); + }); + + it("says what the list covers under the table, in view", async () => { + getRunReliance.mockResolvedValue(answer([item()])); + render(); + const tableEl = await table(); + const line = screen.getByText(STANDING); + expect(tableEl.compareDocumentPosition(line) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(screen.queryByRole("tooltip")).toBeNull(); + expect(screen.queryByText(REPORT_NOTE)).toBeNull(); + expect(screen.queryByText(CUT_NOTE)).toBeNull(); + }); + + it("explains a reported row's revisions only when a row is reported, and a cut list only when cut", async () => { + getRunReliance.mockResolvedValue(answer([item({ state: "reported" })], { truncated: true })); + render(); + await table(); + expect(screen.getByText(REPORT_NOTE)).toBeInTheDocument(); + expect(screen.getByText(CUT_NOTE)).toBeInTheDocument(); + expect(screen.getByText(STANDING)).toBeInTheDocument(); + }); + + it("a run with nothing read or reported says what would fill the list", async () => { + getRunReliance.mockResolvedValue(answer([])); + render(); + expect(await screen.findByText(EMPTY)).toBeInTheDocument(); + expect(screen.getByText(STANDING)).toBeInTheDocument(); + expect(screen.queryByRole("table")).toBeNull(); + }); + + it("a run the namespace does not hold says so", async () => { + getRunReliance.mockResolvedValue(answer([], { found: false })); + render(); + expect(await screen.findByText("This run was not found in this namespace.")).toBeInTheDocument(); + expect(screen.queryByText(EMPTY)).toBeNull(); + expect(screen.queryByRole("table")).toBeNull(); + }); + + it("a failed read is an alert that says why, never the empty text or a label", async () => { + getRunReliance.mockRejectedValue( + new ApiError({ + status: 503, + code: "BACKEND_UNAVAILABLE", + message: "the store did not answer", + requestId: "req-9", + }), + ); + render(); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent(/^Couldn't load what this run read: .*the store did not answer/); + expect(alert).toHaveTextContent("req-9"); + expect(screen.getByRole("heading", { name: "What this run read" })).toBeInTheDocument(); + expect(screen.queryByText(EMPTY)).toBeNull(); + expect(screen.queryByText(/Recalled|Reported/)).toBeNull(); + }); + + it.each([ + ["404", new ApiError({ status: 404 })], + ["405", new ApiError({ status: 405 })], + ["an unknown-operation code", new ApiError({ status: 400, code: "UNKNOWN_OP" })], + ])("a server that does not serve the read (%s) draws no section", async (_name, error) => { + getRunReliance.mockRejectedValue(error); + const { container } = render(); + await waitFor(() => expect(getRunReliance).toHaveBeenCalled()); + await waitFor(() => expect(container).toBeEmptyDOMElement()); + expect(screen.queryByRole("heading")).toBeNull(); + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("draws ten of twelve items, then the rest on Show more", async () => { + const items = Array.from({ length: 12 }, (_, i) => item({ key: `key_${String(i).padStart(2, "0")}` })); + getRunReliance.mockResolvedValue(answer(items)); + render(); + const tableEl = await table(); + expect(within(tableEl).getAllByRole("button")).toHaveLength(10); + expect(within(tableEl).queryByText("key_10")).toBeNull(); + expect(screen.getByText("Showing 10 of 12")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Show 2 more" })); + expect(await within(tableEl).findByText("key_11")).toBeInTheDocument(); + expect(within(tableEl).getAllByRole("button")).toHaveLength(12); + expect(screen.queryByRole("button", { name: /^Show / })).toBeNull(); + expect(screen.queryByText(/^Showing /)).toBeNull(); + // The press removed its button: the focus lands on the first row it added. + await waitFor(() => expect(within(tableEl).getByRole("button", { name: "key_10" })).toHaveFocus()); + }); + + it("ten items draw no Show more", async () => { + getRunReliance.mockResolvedValue(answer(Array.from({ length: 10 }, (_, i) => item({ key: `key_${i}` })))); + render(); + expect(within(await table()).getAllByRole("button")).toHaveLength(10); + expect(screen.queryByRole("button", { name: /^Show / })).toBeNull(); + expect(screen.queryByText(/^Showing /)).toBeNull(); + }); + + it("run Y never shows run X's items when X's answer lands last", async () => { + let answerX: (v: RunRelianceResponse) => void = () => {}; + getRunReliance + .mockImplementationOnce(() => new Promise((r) => (answerX = r))) + .mockResolvedValueOnce(answer([item({ key: "key_from_y" })])); + const { rerender } = render(); + rerender(); + expect(await within(await table()).findByText("key_from_y")).toBeInTheDocument(); + answerX(answer([item({ key: "key_from_x" })])); + await new Promise((r) => setTimeout(r, 0)); + expect(screen.queryByText("key_from_x")).toBeNull(); + expect(screen.getByText("key_from_y")).toBeInTheDocument(); + }); + + it("no rendered text names a state or an operation", async () => { + getRunReliance.mockResolvedValue( + answer( + [ + item({ key: "k1", state: "returned" }), + item({ key: "k2", state: "reported_and_served" }), + item({ key: "k3", state: "reported" }), + item({ key: "k4", state: "not_recorded", revisions: [], last_served_at: "" }), + item({ key: "k5", state: "superseded", revisions: [{ versions: [] }] }), + ], + { truncated: true }, + ), + ); + const { container } = render(); + await table(); + const text = container.textContent ?? ""; + for (const state of ["reported_and_served", "not_recorded", "returned", "superseded"]) { + expect(text).not.toContain(state); + } + // "reported" is also a plain word of the labels: only the bare state is ruled out. + expect(text).not.toMatch(/\breported\b(?! as relied on| item| memory| no memory)/); + const { names } = await opNames(); + expect(names.has("run.get")).toBe(true); + for (const op of names) expect(text).not.toContain(op); + }); +}); diff --git a/frontend/src/flows/RunReliance.tsx b/frontend/src/flows/RunReliance.tsx new file mode 100644 index 00000000000..a95858ab426 --- /dev/null +++ b/frontend/src/flows/RunReliance.tsx @@ -0,0 +1,223 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { Badge } from "@clickhouse/click-ui/Badge"; +import { Button } from "@clickhouse/click-ui/Button"; +import { Table, type TableRowType } from "@clickhouse/click-ui/Table"; +import { getRunReliance, type Identity, type RunRelianceItem, type RunRelianceResponse } from "../api"; +import { Chip, ListTime, Loading, Panel, SectionHeading } from "../components/ui"; +import { errorLine } from "../lib/errorWords"; +import { fmtInt, listTimeTitle } from "../lib/format"; +import { useStore } from "../lib/state"; +import { isOpAbsent } from "../lib/trackerSources"; +import { type ShowMoreRows, useShowMore } from "../lib/useShowMore"; +import { versionTime } from "../lib/versionTime"; + +const TITLE = "What this run read"; +/** Rows drawn before the first Show more. */ +const FIRST_SHOWN = 10; +/** Revisions of one item drawn; the rest are counted. */ +const REVISIONS_SHOWN = 5; + +// What each state the server derives reads as: the recall on record, the agent's report, or +// both. The only place the dashboard spells a state; one it has no label for draws no badge. +const LABELS = new Map([ + ["returned", "Recalled"], + ["reported_and_served", "Recalled, and reported as relied on"], + ["reported", "Reported as relied on"], + ["not_recorded", "Reported as relied on, recall not recorded"], +]); + +const HEADERS = [{ label: "Item" }, { label: "Revision" }, { label: "Recall and report" }, { label: "Last read" }]; + +const itemId = (item: RunRelianceItem) => `${item.kind}:${item.key}`; + +type Load = + | { at: "loading" } + | { at: "absent" } + | { at: "failed"; line: string } + | { at: "ready"; answer: RunRelianceResponse }; + +/** What a run read: each item with the revisions the run was served and what the agent + * reported relying on. It owns its panel, since a server that does not serve the read + * gets no section at all. Mount it with the run id as `key`: a late answer for another + * run then lands on an unmounted section. */ +export function RunReliance({ identity, runId }: { identity: Pick; runId: string }) { + const [load, setLoad] = useState({ at: "loading" }); + const { org, namespace } = identity; + useEffect(() => { + let live = true; + setLoad({ at: "loading" }); + getRunReliance({ org, namespace }, runId) + .then((answer) => { + if (live) setLoad({ at: "ready", answer }); + }) + .catch((e: unknown) => { + if (!live) return; + setLoad(isOpAbsent(e) ? { at: "absent" } : { at: "failed", line: errorLine(e, { read: true }) }); + }); + return () => { + live = false; + }; + }, [org, namespace, runId]); + + // A server a release behind: the rest of the run's detail stays as it is. + if (load.at === "absent") return null; + return ( + }> + {load.at === "loading" && } + {load.at === "failed" && ( +
+ Couldn't load what this run read: {load.line} +
+ )} + {load.at === "ready" && } +
+ ); +} + +function Answer({ answer }: { answer: RunRelianceResponse }) { + if (!answer.found) return

This run was not found in this namespace.

; + if (answer.items.length === 0) { + return ( +
+

+ No read is on record for this run, and the agent reported no memory it relied on. A read is listed when its + request names this run, as the coding-agent plugins and the SDK's run scope do. +

+ +
+ ); + } + return ; +} + +/** What the list covers, in view under it: a read that is not listed is not a read that did + * not happen. */ +function Covers() { + return ( +

+ Lists the reads Loom recorded under this run for items of this namespace. A read that is not listed may still have + happened: its record can expire, fail to be written, be filed under another run, or name an item of another + namespace. +

+ ); +} + +function Items({ items, cut }: { items: RunRelianceItem[]; cut: boolean }) { + const table = useRef(null); + const how: ShowMoreRows = { + key: itemId, + // The rows are the table's, not a list's: each drawn item with the chip that opens it. + rows: () => + [...(table.current?.querySelectorAll("[data-reliance-item]") ?? [])].flatMap( + (cell): Array<[string, HTMLElement]> => { + const button = cell.querySelector("button"); + return button ? [[cell.dataset.relianceItem ?? "", button]] : []; + }, + ), + }; + const more = useShowMore(items, FIRST_SHOWN, how); + const drawn = more.shown.length; + // Click UI's Badge measures its text on every render: the rows change only with the items drawn. + const rows = useMemo(() => items.slice(0, drawn).map(itemRow), [items, drawn]); + return ( +
+
+ {more.moreLabel && ( +
+ + {`Showing ${fmtInt(drawn)} of ${fmtInt(items.length)}`} +
+ )} + + {items.some((item) => item.state === "reported") && ( +

+ A report names no revision, so for a reported memory the revisions shown are what this run was served, not + which one the agent relied on. +

+ )} + {cut && ( +

+ This list is cut: it keeps every reported item, the items read most recently, and the newest revisions of + each. +

+ )} + + ); +} + +function itemRow(item: RunRelianceItem): TableRowType { + const label = LABELS.get(item.state); + return { + id: itemId(item), + items: [ + { label: }, + { label: }, + { label: label ? : null }, + { label: }, + ], + }; +} + +/** The item as the chip that opens it: a memory in the inspector, a document in the Library. + * A kind this build does not know opens nothing and is named beside its key. */ +function ItemChip({ item }: { item: RunRelianceItem }) { + const inspect = useStore((s) => s.inspect); + const openDocument = useStore((s) => s.openDocument); + return ( +
+ {item.kind === "memory" ? ( + inspect(item.key, { agent: "*" })} /> + ) : item.kind === "document" ? ( + openDocument(item.key)} /> + ) : ( + <> + + {item.kind} + + )} +
+ ); +} + +/** The revisions the run was served, highest first. A report with no record shows none: + * never the item's latest. */ +function Revisions({ item }: { item: RunRelianceItem }) { + if (item.revisions.length === 0) { + return item.last_served_at ? Revision not recorded : null; + } + const rest = item.revisions.length - REVISIONS_SHOWN; + return ( +
+ {item.revisions.slice(0, REVISIONS_SHOWN).map((revision, i) => ( + // The list never reorders: a revision has no id of its own on the wire. +
+ +
+ ))} + {rest > 0 &&
{`and ${rest} earlier revision${rest === 1 ? "" : "s"}`}
} +
+ ); +} + +/** One revision by what a person can read: a memory's by the time its stored row was + * written (an absolute time, so two written within a day read differently), a document's by + * its number. `versions` are ascending; the lowest is the content's first write. */ +function RevisionName({ kind, versions }: { kind: string; versions: string[] }) { + const lowest = versions[0]; + if (lowest === undefined) return Version not recorded; + const written = kind === "memory" ? versionTime(lowest) : null; + if (written) { + return ( + <> + Written + + ); + } + return ( + <> + {kind === "memory" ? "Version" : "Revision"} {lowest} + + ); +} diff --git a/frontend/src/lib/versionTime.test.ts b/frontend/src/lib/versionTime.test.ts new file mode 100644 index 00000000000..b10159b00e7 --- /dev/null +++ b/frontend/src/lib/versionTime.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { versionTime } from "./versionTime"; + +describe("versionTime", () => { + it("reads a memory version as the time its stored row was written", () => { + // Nanoseconds above 2^53: read as a BigInt, so the milliseconds are exact. + expect(versionTime("1796308329123456789")).toBe("2026-12-03T14:32:09.123Z"); + }); + + it("is null for a number outside the range a write time falls in", () => { + expect(versionTime("3")).toBeNull(); + expect(versionTime("999999999999999999")).toBeNull(); + expect(versionTime("4000000000000000000")).toBeNull(); + expect(versionTime("1000000000000000000")).toBe("2001-09-09T01:46:40.000Z"); + }); + + it("is null for text that is not digits", () => { + expect(versionTime("")).toBeNull(); + expect(versionTime("v2")).toBeNull(); + expect(versionTime("-1796308329123456789")).toBeNull(); + expect(versionTime("1.7e18")).toBeNull(); + }); +}); diff --git a/frontend/src/lib/versionTime.ts b/frontend/src/lib/versionTime.ts new file mode 100644 index 00000000000..203c945e2f7 --- /dev/null +++ b/frontend/src/lib/versionTime.ts @@ -0,0 +1,10 @@ +/** The ISO time a memory version was written: a version is its stored row's write time in + * epoch nanoseconds, decimal text above 2^53. Null for text that is not digits or a number + * outside the range a write time falls in (the server's own bounds, 2001 to 2096). Its own + * module: only the run detail reads it, so the shell's chunk does not carry it. */ +export function versionTime(version: string): string | null { + if (!/^\d{1,20}$/.test(version)) return null; + const ns = BigInt(version); + if (ns < 10n ** 18n || ns >= 4n * 10n ** 18n) return null; + return new Date(Number(ns / 1_000_000n)).toISOString(); +} diff --git a/frontend/src/views/Runs.detail.test.tsx b/frontend/src/views/Runs.detail.test.tsx index 2e85d38cc90..dedad8ae5d4 100644 --- a/frontend/src/views/Runs.detail.test.tsx +++ b/frontend/src/views/Runs.detail.test.tsx @@ -1,7 +1,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "../test/rtl"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { RunGetResponse, RunRow } from "../api"; +import { ApiError, type RunGetResponse, type RunRelianceResponse, type RunRow } from "../api"; import { useStore } from "../lib/state"; import { must } from "../test/must"; import { EMPTY_WHY, RUNS_FIELDS, Runs, hasNoMemoryActivity } from "./Runs"; @@ -12,6 +12,7 @@ import { EMPTY_WHY, RUNS_FIELDS, Runs, hasNoMemoryActivity } from "./Runs"; const listRuns = vi.fn(); const getRun = vi.fn(); +const getRunReliance = vi.fn<(...args: unknown[]) => Promise>(); vi.mock("../api", async (importOriginal) => { const actual = await importOriginal(); return { @@ -22,6 +23,7 @@ vi.mock("../api", async (importOriginal) => { return { runs, total: runs.length, paged: true }; }, getRun: (...args: unknown[]) => getRun(...args), + getRunReliance: (...args: unknown[]) => getRunReliance(...args), listMine: vi.fn(async () => []), isAuthDisabled: () => false, }; @@ -79,6 +81,15 @@ const full = row({ goal: "fix the thing", }); +// One memory the run was served and its agent reported, as the run's read answers it. +const served = { + kind: "memory", + key: "fact_a", + state: "reported", + revisions: [{ versions: ["1796308329123456789"] }], + last_served_at: "2026-09-21T17:00:01.000Z", +}; + const detail = (over: Partial = {}): RunGetResponse => ({ found: true, run: null, @@ -107,6 +118,7 @@ describe("Runs page", () => { beforeEach(() => { vi.clearAllMocks(); getRun.mockResolvedValue(detail()); + getRunReliance.mockResolvedValue({ found: true, items: [], truncated: false }); useStore.setState({ authed: true, identity: { org: "dev", namespace: "ns", agent: "loom-ui" }, @@ -375,6 +387,57 @@ describe("Runs page", () => { expect(within(dialog).getByText("key_from_y")).toBeInTheDocument(); }); + it("opens with what the run read, and keeps the memories the agent relied on", async () => { + listRuns.mockResolvedValue([full]); + getRunReliance.mockResolvedValue({ found: true, items: [served], truncated: false }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "fix the thing" })); + const dialog = await screen.findByRole("dialog"); + expect(await within(dialog).findByRole("table", { name: "What this run read" })).toBeInTheDocument(); + expect(getRunReliance).toHaveBeenCalledWith({ org: "dev", namespace: "ns" }, "r-full"); + const headings = within(dialog) + .getAllByRole("heading", { level: 3 }) + .map((h) => h.textContent); + expect(headings[0]).toBe("What this run read"); + expect(headings).toContain("Memories the agent relied on"); + // The reported key is still a chip of its own section, beside the item's row above. + expect(within(dialog).getAllByRole("button", { name: "fact_a" })).toHaveLength(2); + }); + + it("an inferred run with reads on record is not said to have recalled nothing", async () => { + listRuns.mockResolvedValue([row({ metadata: { implicit: true } })]); + getRunReliance.mockResolvedValue({ found: true, items: [served], truncated: false }); + render(); + fireEvent.click(await screen.findByText("Show runs with no memory activity")); + fireEvent.click(await screen.findByRole("button", { name: "ISSUE_TRIAGE issue_114194" })); + const dialog = await screen.findByRole("dialog"); + expect(await within(dialog).findByRole("table", { name: "What this run read" })).toBeInTheDocument(); + const alert = within(dialog).getByText(/inferred from a connection/); + expect(alert).toHaveTextContent("the agent named nothing it relied on and wrote nothing under it"); + expect(dialog).not.toHaveTextContent(/recalled and wrote nothing|did no memory work/); + }); + + it("the Recalled help says what the figure counts, and that what the run read can differ", async () => { + for (const text of [EMPTY_WHY.recalledOff, EMPTY_WHY.recalledZero]) { + expect(text).toContain("What this run read is recorded separately and can differ."); + expect(text).not.toMatch(/does not record searches|no search was recorded/); + } + expect(EMPTY_WHY.recalledOff).toContain("recall history, which this deployment does not keep"); + }); + + it("a server that does not serve the read draws no section and keeps the reported chips", async () => { + listRuns.mockResolvedValue([full]); + getRunReliance.mockRejectedValue(new ApiError({ status: 404 })); + render(); + fireEvent.click(await screen.findByRole("button", { name: "fix the thing" })); + const dialog = await screen.findByRole("dialog"); + await waitFor(() => expect(getRunReliance).toHaveBeenCalledTimes(1)); + expect(await stat(dialog, "Recalled")).toHaveTextContent("0"); + expect(within(dialog).queryByRole("heading", { name: "What this run read" })).toBeNull(); + expect(within(dialog).queryByRole("alert")).toBeNull(); + expect(within(dialog).getByRole("button", { name: "fact_a" })).toBeInTheDocument(); + }); + it("recalled n/a when the trace log is off, with no link to a history that cannot exist", async () => { listRuns.mockResolvedValue([full]); getRun.mockResolvedValue(detail({ recalled: -1 })); diff --git a/frontend/src/views/Runs.fields.test.tsx b/frontend/src/views/Runs.fields.test.tsx index 7194b8a112f..9cf4032d428 100644 --- a/frontend/src/views/Runs.fields.test.tsx +++ b/frontend/src/views/Runs.fields.test.tsx @@ -25,6 +25,7 @@ vi.mock("../api", async (importOriginal) => { return { runs, total: runs.length, paged: true }; }, getRun: vi.fn(async () => ({ found: false, run: null })), + getRunReliance: vi.fn(async () => ({ found: true, items: [], truncated: false })), gradeRun: vi.fn(), listMine: vi.fn(async () => []), isAuthDisabled: () => false, diff --git a/frontend/src/views/Runs.paging.test.tsx b/frontend/src/views/Runs.paging.test.tsx index 62ce9b7cd2e..17205dc0e07 100644 --- a/frontend/src/views/Runs.paging.test.tsx +++ b/frontend/src/views/Runs.paging.test.tsx @@ -23,6 +23,7 @@ vi.mock("../api", async (importOriginal) => { ...actual, listRunsPage: (id: unknown, opts?: RunListOptions) => listRunsPage(id, opts), getRun: vi.fn(async () => ({ found: false, run: null })), + getRunReliance: vi.fn(async () => ({ found: true, items: [], truncated: false })), listMine: vi.fn(async () => []), isAuthDisabled: () => false, }; diff --git a/frontend/src/views/Runs.rows.test.tsx b/frontend/src/views/Runs.rows.test.tsx index ce191ae71ae..a2873d18456 100644 --- a/frontend/src/views/Runs.rows.test.tsx +++ b/frontend/src/views/Runs.rows.test.tsx @@ -26,6 +26,7 @@ vi.mock("../api", async (importOriginal) => { ...actual, listRunsPage: (id: unknown, opts?: RunListOptions) => listRunsPage(id, opts), getRun: () => getRun(), + getRunReliance: vi.fn(async () => ({ found: true, items: [], truncated: false })), listMine: vi.fn(async () => []), isAuthDisabled: () => false, }; diff --git a/frontend/src/views/Runs.table.test.tsx b/frontend/src/views/Runs.table.test.tsx index 8cb429693ac..1d250e6c060 100644 --- a/frontend/src/views/Runs.table.test.tsx +++ b/frontend/src/views/Runs.table.test.tsx @@ -19,6 +19,7 @@ vi.mock("../api", async (importOriginal) => { return { runs, total: runs.length, paged: true }; }, getRun: vi.fn(async () => ({ found: false, run: null })), + getRunReliance: vi.fn(async () => ({ found: true, items: [], truncated: false })), listMine: vi.fn(async () => []), isAuthDisabled: () => false, }; diff --git a/frontend/src/views/Runs.tsx b/frontend/src/views/Runs.tsx index b59bc679372..d84e8555354 100644 --- a/frontend/src/views/Runs.tsx +++ b/frontend/src/views/Runs.tsx @@ -48,6 +48,7 @@ import { ListToolbar, ListToolbarSearch } from "../components/ui/ListToolbar"; import { DraftSearch } from "../components/ui/DraftSearch"; import { PHONE_QUERY, useMedia } from "../lib/useMedia"; import { RunGrade } from "../flows/RunGrade"; +import { RunReliance } from "../flows/RunReliance"; import { canWrite, useNamespaceRoleRead } from "../lib/namespaceRole"; import { callReason } from "../lib/callReason"; import { focusViewHeading } from "../lib/place"; @@ -186,9 +187,10 @@ export function hasNoMemoryActivity(r: RunRow): boolean { export const EMPTY_WHY = { used: "none reported — only the agent can say which memories it relied on; it lists them when it completes the run", written: "none — a memory write counts here when the agent tags it with the run", - recalledOff: "n/a — this deployment does not record searches; an operator can turn that on", + recalledOff: + "n/a — this figure counts the searches in the recall history, which this deployment does not keep (an operator can turn that on), and the keys the agent lists when it completes the run. What this run read is recorded separately and can differ.", recalledZero: - "no search was recorded under this run: a search counts here when the agent tags it with the run, as the coding-agent plugins and the SDK's run scope do, or lists what it recalled when it completes the run", + "no search is in the recall history under this run: a search counts here when the agent tags it with the run, as the coding-agent plugins and the SDK's run scope do, or lists what it recalled when it completes the run. What this run read is recorded separately and can differ.", observations: "observations tagged with this run (the coding-agent plugins tag what they capture)", noSession: "the run was started without a session (a session given only in the run's metadata is not read), so model turns and cost cannot be matched to it", @@ -1066,7 +1068,7 @@ export function Runs() { state="neutral" size="small" text={ - 'This run was inferred from a connection that did no memory work — it recalled and wrote nothing, and closed on idle rather than being completed by the agent. Its "completed" status is not a reported outcome.' + 'This run was inferred from a connection: the agent named nothing it relied on and wrote nothing under it, and it closed on idle rather than being completed by the agent. Its "completed" status is not a reported outcome.' } /> )} @@ -1079,6 +1081,7 @@ export function Runs() { }, naming nothing it relied on, and no write was tagged with this run. The fields below say what each one would have needed.`} /> )} + {open && } {replayed?.user_request && (
{replayed.user_request}
diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index 5c46170a9b0..a08e3da84e7 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -2807,6 +2807,18 @@ type RunListOutput = wire.RunListOutput // RunReflection is a model used by Loom operations. type RunReflection = wire.RunReflection +// RunRelianceInput is the request to run.reliance. +type RunRelianceInput = wire.RunRelianceInput + +// RunRelianceItem is a model used by Loom operations. +type RunRelianceItem = wire.RunRelianceItem + +// RunRelianceOutput is the response from run.reliance. +type RunRelianceOutput = wire.RunRelianceOutput + +// RunRelianceRevision is a model used by Loom operations. +type RunRelianceRevision = wire.RunRelianceRevision + // RunRetractCreditInput is the request to run.retract_credit. type RunRetractCreditInput = wire.RunRetractCreditInput @@ -8107,6 +8119,20 @@ func (s RunService) List(ctx context.Context, opts ...Option[RunListInput]) (*Ru return callOperation[RunListOutput](s.client, ctx, "run.list", in) } +// Reliance calls run.reliance. +// Use WithInput to supply additional request fields. +func (s RunService) Reliance(ctx context.Context, runID string, opts ...Option[RunRelianceInput]) (*RunRelianceOutput, error) { + in := applyOptions(opts) + in.RunID = runID + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[RunRelianceOutput](s.client, ctx, "run.reliance", in) +} + // RetractCredit calls run.retract_credit. // Use WithInput to supply additional request fields. func (s RunService) RetractCredit(ctx context.Context, opts ...Option[RunRetractCreditInput]) (*RunRetractCreditOutput, error) { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 5ecb29c347f..405d7b03bf9 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: f1defcff2d03cec9926a81611839e5bc533954e758b82fbf0feb058b10041eea +// Registry model schema SHA-256: b9b823ead18dc9b7169d4c5f37fa4c9f6f051a75cf7bb920eeeeb19dc5b6271d // Package wire contains the Go requests and responses for Loom operations. package wire @@ -11553,6 +11553,38 @@ type RunReflection struct { ExpiresInDays *int64 `json:"expires_in_days,omitempty"` } +// RunRelianceInput is the request to run.reliance. +type RunRelianceInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + RunID string `json:"run_id"` +} + +// RunRelianceItem is a model used by Loom operations. +type RunRelianceItem struct { + Kind string `json:"kind"` + Key string `json:"key"` + State string `json:"state"` + Revisions *[]RunRelianceRevision `json:"revisions,omitempty"` + LastServedAt *string `json:"last_served_at,omitempty"` +} + +// RunRelianceOutput is the response from run.reliance. +type RunRelianceOutput struct { + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + Found bool `json:"found"` + Items *[]RunRelianceItem `json:"items,omitempty"` + Truncated *bool `json:"truncated,omitempty"` +} + +// RunRelianceRevision is a model used by Loom operations. +type RunRelianceRevision struct { + Versions *[]string `json:"versions,omitempty"` +} + // RunRetractCreditInput is the request to run.retract_credit. type RunRetractCreditInput struct { Org string `json:"org"` diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index 88f4684a1bb..f5565063da7 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -3115,6 +3115,14 @@ async def list( """`run.list`.""" return cast("_ops.RunListOutput", await self._agent.call("run.list", body, **options)) + async def reliance( + self, body: _ops.RunRelianceBody | None = None, /, **options: Any + ) -> _ops.RunRelianceOutput: + """`run.reliance`.""" + return cast( + "_ops.RunRelianceOutput", await self._agent.call("run.reliance", body, **options) + ) + async def retract_credit( self, body: _ops.RunRetractCreditBody | None = None, /, **options: Any ) -> _ops.RunRetractCreditOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 7ffb0e89d83..fddedfeafe0 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -367,6 +367,7 @@ class OpSpec: "run.get", "run.grade", "run.list", + "run.reliance", "run.retract_credit", "search.query", "session.brief_delete", @@ -755,6 +756,7 @@ class OpSpec: "run.get", "run.grade", "run.list", + "run.reliance", "run.retract_credit", "search.query", "session.brief_delete", @@ -4751,6 +4753,18 @@ class OpSpec: False, True, ), + "run.reliance": OpSpec( + "run.reliance", + "RunRelianceInput", + "RunRelianceBody", + "RunRelianceOutput", + True, + "viewer", + "experimental", + 300, + False, + True, + ), "run.retract_credit": OpSpec( "run.retract_credit", "RunRetractCreditInput", @@ -19845,6 +19859,40 @@ class RunListOutput(TypedDict, total=False): total: NotRequired[Optional[int]] +class RunRelianceInput(TypedDict, total=False): + "What one run was served, at which revisions, and what its client reported relying on." + + org: Required[str] + namespace: Required[str] + run_id: Required[str] + + +class RunRelianceBody(TypedDict, total=False): + "What one run was served, at which revisions, and what its client reported relying on." + + org: NotRequired[str] + namespace: NotRequired[str] + run_id: NotRequired[str] + + +class RunRelianceOutput(TypedDict, total=False): + found: Required[bool] + items: NotRequired[list["RunRelianceItem"]] + truncated: NotRequired[bool] + + +class RunRelianceItem(TypedDict, total=False): + kind: Required[str] + key: Required[str] + state: Required[Literal["returned", "reported", "reported_and_served", "not_recorded"]] + revisions: NotRequired[list["RunRelianceRevision"]] + last_served_at: NotRequired[str] + + +class RunRelianceRevision(TypedDict, total=False): + versions: NotRequired[list[str]] + + class RunRetractCreditInput(TypedDict, total=False): "Cancel the usage credit of one run, or of the caller's labels over at most 30 days." diff --git a/sdk/python/loom/run.py b/sdk/python/loom/run.py index 2e1d9fb38ae..e1d938cc619 100644 --- a/sdk/python/loom/run.py +++ b/sdk/python/loom/run.py @@ -362,6 +362,15 @@ async def get(self, run_id: str) -> dict[str, Any]: {"org": self._agent.org, "namespace": self._agent.namespace, "run_id": run_id}, ) + async def reliance(self, run_id: str) -> dict[str, Any]: + """What the run was served, at which revisions, and what its client + reported relying on: `found`, `items` (each with `kind`, `key`, `state`, + `revisions` and `last_served_at`) and `truncated`.""" + return await self._agent.transport.post( + "/v1/run.reliance", + {"org": self._agent.org, "namespace": self._agent.namespace, "run_id": run_id}, + ) + async def list( self, *, diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 580401db417..5272872a6db 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -8,7 +8,7 @@ module Loom # Every served operation: its spec in OPS, and one method per op on the class # of its group (`client.memory.set(...)` is `memory.set`). module Generated - OP_COUNT = 385 + OP_COUNT = 386 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -340,6 +340,7 @@ module Generated "run.get" => OpSpec.new("run.get", "run", "get", true, true, "viewer", "stable", %w[org namespace run_id].freeze, %w[org namespace run_id].freeze), "run.grade" => OpSpec.new("run.grade", "run", "grade", true, false, "writer", "experimental", %w[org namespace run_id session_id grade source reason ref].freeze, %w[org namespace grade].freeze), "run.list" => OpSpec.new("run.list", "run", "list", true, true, "viewer", "stable", %w[org namespace agent session_id status limit offset order_by q memory_activity grade fields].freeze, %w[org namespace].freeze), + "run.reliance" => OpSpec.new("run.reliance", "run", "reliance", true, true, "viewer", "experimental", %w[org namespace run_id].freeze, %w[org namespace run_id].freeze), "run.retract_credit" => OpSpec.new("run.retract_credit", "run", "retract_credit", true, false, "writer", "experimental", %w[org namespace run_id since until dry_run].freeze, %w[org namespace].freeze), "search.query" => OpSpec.new("search.query", "search", "query", true, true, "viewer", "experimental", %w[org namespace agent query top_k tags kinds_first namespace_scope recipe bodies explain live page].freeze, %w[org namespace query].freeze), "session.brief_delete" => OpSpec.new("session.brief_delete", "session", "brief_delete", true, false, "writer", "experimental", %w[org namespace agent user_id session_id run_id brief_key].freeze, %w[org namespace agent brief_key].freeze), @@ -2629,6 +2630,13 @@ def list(body = nil, request_options: nil, **fields) call_op("run.list", body, fields, request_options) end + # `run.reliance` (viewer, read-only, experimental). + # What one run was served, at which revisions, and what its client reported relying on. + # Required: org, namespace, run_id. + def reliance(body = nil, request_options: nil, **fields) + call_op("run.reliance", body, fields, request_options) + end + # `run.retract_credit` (writer, writes, Idempotency-Key, experimental). # Cancel the usage credit of one run, or of the caller's labels over at most 30 days. # Required: org, namespace. diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index 9b7b783bed6..72086192796 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -4696,6 +4696,23 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("run.get", &request, options) } + /// Call `run.reliance`. + pub fn run_reliance( + &self, + request: crate::RunRelianceInput, + ) -> Result { + self.run_reliance_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `run.reliance` with per-request options and metadata. + pub fn run_reliance_with_options( + &self, + request: crate::RunRelianceInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("run.reliance", &request, options) + } /// Call `run.list`. pub fn run_list( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index 35b2b73059a..a6eb42a00d7 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -5023,6 +5023,24 @@ impl crate::Client { ) -> Result, crate::CallFailure> { self.call("run.get", &request, options).await } + /// Call `run.reliance`. + pub async fn run_reliance( + &self, + request: crate::RunRelianceInput, + ) -> Result { + self.run_reliance_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `run.reliance` with per-request options and metadata. + pub async fn run_reliance_with_options( + &self, + request: crate::RunRelianceInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("run.reliance", &request, options).await + } /// Call `run.list`. pub async fn run_list( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 6edd8d1c3c8..1e1ec9ad32d 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -1420,6 +1420,7 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ ), ("run.complete", false, false, &["namespace", "org"], &[]), ("run.get", true, true, &["namespace", "org"], &[]), + ("run.reliance", true, true, &["namespace", "org"], &[]), ("run.list", true, true, &["namespace", "org"], &[]), ("run.grade", true, false, &["namespace", "org"], &[]), ( @@ -54813,22 +54814,106 @@ impl RunListInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum RunRelianceItemState { + #[serde(rename = "returned")] + Returned, + #[serde(rename = "reported")] + Reported, + #[serde(rename = "reported_and_served")] + ReportedAndServed, + #[serde(rename = "not_recorded")] + NotRecorded, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] -pub struct RunRetractCreditOutput { +pub struct RunRelianceRevision { #[serde(default = "default_2352")] - pub run_id: String, + pub versions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RunRelianceItem { + pub kind: String, + pub key: String, + pub state: RunRelianceItemState, #[serde(default = "default_2353")] - pub used_retracted: Integer, + pub revisions: Vec, #[serde(default = "default_2354")] - pub evidence_retracted: Integer, + pub last_served_at: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RunRelianceOutput { + pub found: bool, #[serde(default = "default_2355")] - pub harm_retracted: Integer, + pub items: Vec, #[serde(default = "default_2356")] - pub events_written: Integer, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RunRelianceInput { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub org: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub namespace: Option, + pub run_id: String, +} +impl RunRelianceInput { + pub fn new(run_id: impl Into) -> Self { + Self { + org: None, + namespace: None, + run_id: run_id.into(), + } + } + pub fn org(mut self, org: impl Into) -> Self { + self.org = Some(org.into()); + self + } + pub fn namespace(mut self, namespace: impl Into) -> Self { + self.namespace = Some(namespace.into()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("run.reliance", &self, options).await + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RunRetractCreditOutput { #[serde(default = "default_2357")] - pub more: bool, + pub run_id: String, #[serde(default = "default_2358")] + pub used_retracted: Integer, + #[serde(default = "default_2359")] + pub evidence_retracted: Integer, + #[serde(default = "default_2360")] + pub harm_retracted: Integer, + #[serde(default = "default_2361")] + pub events_written: Integer, + #[serde(default = "default_2362")] + pub more: bool, + #[serde(default = "default_2363")] pub dry_run: bool, } @@ -54985,39 +55070,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2361")] + #[serde(default = "default_2366")] pub content: String, - #[serde(default = "default_2362")] + #[serde(default = "default_2367")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2360")] + #[serde(default = "default_2365")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2363")] + #[serde(default = "default_2368")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2359")] - pub tracker: Option>, #[serde(default = "default_2364")] + pub tracker: Option>, + #[serde(default = "default_2369")] pub live: Option, - #[serde(default = "default_2365")] + #[serde(default = "default_2370")] pub memory: std::collections::HashMap, - #[serde(default = "default_2366")] + #[serde(default = "default_2371")] pub knowledge: std::collections::HashMap, - #[serde(default = "default_2367")] + #[serde(default = "default_2372")] pub profile: std::collections::HashMap, - #[serde(default = "default_2368")] + #[serde(default = "default_2373")] pub conversations: std::collections::HashMap, - #[serde(default = "default_2369")] + #[serde(default = "default_2374")] pub withheld: Option>, - #[serde(default = "default_2370")] + #[serde(default = "default_2375")] pub namespaces_skipped: Vec, } @@ -55221,7 +55306,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2371")] + #[serde(default = "default_2376")] pub revision: Integer, } @@ -55314,67 +55399,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2380")] + #[serde(default = "default_2385")] pub what: String, - #[serde(default = "default_2381")] + #[serde(default = "default_2386")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2383")] + #[serde(default = "default_2388")] pub tried: String, - #[serde(default = "default_2384")] + #[serde(default = "default_2389")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2386")] + #[serde(default = "default_2391")] pub what: String, - #[serde(rename = "ref", default = "default_2387")] + #[serde(rename = "ref", default = "default_2392")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2391")] + #[serde(default = "default_2396")] pub path: String, - #[serde(default = "default_2392")] + #[serde(default = "default_2397")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2377")] + #[serde(default = "default_2382")] pub goal: String, - #[serde(default = "default_2378")] + #[serde(default = "default_2383")] pub status: String, - #[serde(default = "default_2379")] + #[serde(default = "default_2384")] pub verification: String, - #[serde(default = "default_2382")] + #[serde(default = "default_2387")] pub decisions: Vec, - #[serde(default = "default_2385")] + #[serde(default = "default_2390")] pub dead_ends: Vec, - #[serde(default = "default_2388")] + #[serde(default = "default_2393")] pub done: Vec, - #[serde(default = "default_2389")] + #[serde(default = "default_2394")] pub open_questions: Vec, - #[serde(default = "default_2390")] + #[serde(default = "default_2395")] pub next_steps: Vec, - #[serde(default = "default_2393")] + #[serde(default = "default_2398")] pub files: Vec, - #[serde(default = "default_2394")] + #[serde(default = "default_2399")] pub constraints: Vec, - #[serde(default = "default_2395")] + #[serde(default = "default_2400")] pub pointers: Vec, - #[serde(default = "default_2396")] + #[serde(default = "default_2401")] pub client_summary: String, - #[serde(default = "default_2397")] + #[serde(default = "default_2402")] pub client_summary_at: String, } @@ -55382,45 +55467,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2372")] + #[serde(default = "default_2377")] pub brief_key: String, - #[serde(default = "default_2373")] + #[serde(default = "default_2378")] pub revision: Integer, - #[serde(default = "default_2374")] + #[serde(default = "default_2379")] pub snapshot_id: String, - #[serde(default = "default_2375")] + #[serde(default = "default_2380")] pub snapshot_key: String, - #[serde(default = "default_2376")] + #[serde(default = "default_2381")] pub rendered: String, - #[serde(default = "default_2398")] + #[serde(default = "default_2403")] pub sections: Option, - #[serde(default = "default_2399")] + #[serde(default = "default_2404")] pub project: String, - #[serde(default = "default_2400")] + #[serde(default = "default_2405")] pub branch: String, - #[serde(default = "default_2401")] + #[serde(default = "default_2406")] pub head_sha: String, - #[serde(default = "default_2402")] + #[serde(default = "default_2407")] pub author: String, - #[serde(default = "default_2403")] + #[serde(default = "default_2408")] pub trigger: String, - #[serde(default = "default_2404")] + #[serde(default = "default_2409")] pub actor: String, - #[serde(default = "default_2405")] + #[serde(default = "default_2410")] pub source_sessions: Vec, - #[serde(default = "default_2406")] + #[serde(default = "default_2411")] pub updated_at: Option, - #[serde(default = "default_2407")] + #[serde(default = "default_2412")] pub age_seconds: Integer, - #[serde(default = "default_2408")] + #[serde(default = "default_2413")] pub revisions: Integer, - #[serde(default = "default_2409")] + #[serde(default = "default_2414")] pub events_total: Integer, - #[serde(default = "default_2410")] + #[serde(default = "default_2415")] pub source_chars: Integer, - #[serde(default = "default_2411")] + #[serde(default = "default_2416")] pub brief_chars: Integer, - #[serde(default = "default_2412")] + #[serde(default = "default_2417")] pub deleted: bool, } @@ -55595,34 +55680,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2413")] + #[serde(default = "default_2418")] pub project: String, - #[serde(default = "default_2414")] + #[serde(default = "default_2419")] pub branch: String, - #[serde(default = "default_2415")] + #[serde(default = "default_2420")] pub agent: String, - #[serde(default = "default_2416")] + #[serde(default = "default_2421")] pub goal: String, - #[serde(default = "default_2417")] + #[serde(default = "default_2422")] pub status: String, - #[serde(default = "default_2418")] + #[serde(default = "default_2423")] pub author: String, - #[serde(default = "default_2419")] + #[serde(default = "default_2424")] pub actor: String, - #[serde(default = "default_2420")] + #[serde(default = "default_2425")] pub updated_at: Option, - #[serde(default = "default_2421")] + #[serde(default = "default_2426")] pub age_seconds: Integer, - #[serde(default = "default_2422")] + #[serde(default = "default_2427")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2423")] + #[serde(default = "default_2428")] pub briefs: Vec, - #[serde(default = "default_2424")] + #[serde(default = "default_2429")] pub rendered: String, } @@ -55762,25 +55847,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2428")] + #[serde(default = "default_2433")] pub events_in: Integer, - #[serde(default = "default_2429")] + #[serde(default = "default_2434")] pub windows: Integer, - #[serde(default = "default_2430")] + #[serde(default = "default_2435")] pub events_total: Integer, - #[serde(default = "default_2431")] + #[serde(default = "default_2436")] pub source_chars: Integer, - #[serde(default = "default_2432")] + #[serde(default = "default_2437")] pub brief_chars: Integer, - #[serde(default = "default_2433")] + #[serde(default = "default_2438")] pub compression_ratio: f64, - #[serde(default = "default_2434")] + #[serde(default = "default_2439")] pub dropped_ungrounded: Integer, - #[serde(default = "default_2435")] + #[serde(default = "default_2440")] pub tokens_in: Integer, - #[serde(default = "default_2436")] + #[serde(default = "default_2441")] pub tokens_out: Integer, - #[serde(default = "default_2437")] + #[serde(default = "default_2442")] pub llm_model: String, } @@ -55790,13 +55875,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2425")] + #[serde(default = "default_2430")] pub author: String, - #[serde(default = "default_2426")] + #[serde(default = "default_2431")] pub reason: String, - #[serde(default = "default_2427")] + #[serde(default = "default_2432")] pub rendered: String, - #[serde(default = "default_2438")] + #[serde(default = "default_2443")] pub stats: SessionBriefStats, } @@ -56541,39 +56626,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2439")] + #[serde(default = "default_2444")] pub reason: String, - #[serde(default = "default_2440")] + #[serde(default = "default_2445")] pub blocked_on: String, - #[serde(default = "default_2441")] + #[serde(default = "default_2446")] pub not_before: Option, - #[serde(default = "default_2442")] + #[serde(default = "default_2447")] pub resume_at: Option, - #[serde(default = "default_2443")] + #[serde(default = "default_2448")] pub deadline: Option, - #[serde(default = "default_2444")] + #[serde(default = "default_2449")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2445")] + #[serde(default = "default_2450")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2446")] + #[serde(default = "default_2451")] pub from_subject: String, - #[serde(default = "default_2447")] + #[serde(default = "default_2452")] pub origin: String, - #[serde(default = "default_2448")] + #[serde(default = "default_2453")] pub parent_task_id: Option, - #[serde(default = "default_2449")] + #[serde(default = "default_2454")] pub owner: String, - #[serde(default = "default_2450")] + #[serde(default = "default_2455")] pub attempt: Integer, - #[serde(default = "default_2451")] + #[serde(default = "default_2456")] pub fence: Integer, - #[serde(default = "default_2452")] + #[serde(default = "default_2457")] pub lease_until: Option, - #[serde(default = "default_2453")] + #[serde(default = "default_2458")] pub outcome: std::collections::HashMap, - #[serde(default = "default_2454")] + #[serde(default = "default_2459")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -56584,7 +56669,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2455")] + #[serde(default = "default_2460")] pub seq: Integer, } @@ -56985,10 +57070,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2456")] + #[serde(default = "default_2461")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2457")] + #[serde(default = "default_2462")] pub oldest: Option, } @@ -57075,7 +57160,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2458")] + #[serde(default = "default_2463")] pub next: String, } @@ -57414,7 +57499,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2459")] + #[serde(default = "default_2464")] pub task: Option, } @@ -57548,23 +57633,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2460")] + #[serde(default = "default_2465")] pub from_status: String, - #[serde(default = "default_2461")] + #[serde(default = "default_2466")] pub to_status: String, - #[serde(default = "default_2462")] + #[serde(default = "default_2467")] pub actor: String, - #[serde(default = "default_2463")] + #[serde(default = "default_2468")] pub agent: String, - #[serde(default = "default_2464")] + #[serde(default = "default_2469")] pub fence: Integer, - #[serde(default = "default_2465")] + #[serde(default = "default_2470")] pub version: Integer, - #[serde(default = "default_2466")] + #[serde(default = "default_2471")] pub reason: String, - #[serde(default = "default_2467")] + #[serde(default = "default_2472")] pub patch: std::collections::HashMap, - #[serde(default = "default_2468")] + #[serde(default = "default_2473")] pub note: String, pub ts: String, } @@ -57904,7 +57989,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2469")] + #[serde(default = "default_2474")] pub note: String, } @@ -58300,7 +58385,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2470")] + #[serde(default = "default_2475")] pub conflict: bool, } @@ -58663,19 +58748,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2471")] + #[serde(default = "default_2476")] pub intent: String, - #[serde(default = "default_2472")] + #[serde(default = "default_2477")] pub anchors: std::collections::HashMap, - #[serde(default = "default_2473")] + #[serde(default = "default_2478")] pub sections: Vec>, - #[serde(default = "default_2474")] + #[serde(default = "default_2479")] pub searched: Vec, - #[serde(default = "default_2475")] + #[serde(default = "default_2480")] pub lines: Vec, - #[serde(default = "default_2476")] + #[serde(default = "default_2481")] pub restricted: bool, - #[serde(default = "default_2477")] + #[serde(default = "default_2482")] pub verdict: String, } @@ -58771,17 +58856,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2478")] + #[serde(default = "default_2483")] pub tracker_namespace: String, - #[serde(default = "default_2479")] + #[serde(default = "default_2484")] pub tracker_namespaces: Vec, - #[serde(default = "default_2480")] + #[serde(default = "default_2485")] pub restricted: bool, - #[serde(default = "default_2481")] + #[serde(default = "default_2486")] pub kind: String, - #[serde(default = "default_2482")] + #[serde(default = "default_2487")] pub authorized: bool, - #[serde(default = "default_2483")] + #[serde(default = "default_2488")] pub templates: Vec, } @@ -58834,13 +58919,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2484")] + #[serde(default = "default_2489")] pub risk: std::collections::HashMap, - #[serde(default = "default_2485")] + #[serde(default = "default_2490")] pub open_issues: Vec>, - #[serde(default = "default_2486")] + #[serde(default = "default_2491")] pub known: bool, - #[serde(default = "default_2487")] + #[serde(default = "default_2492")] pub tracker_unavailable: bool, } @@ -58901,9 +58986,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2488")] + #[serde(default = "default_2493")] pub tables: Vec>, - #[serde(default = "default_2489")] + #[serde(default = "default_2494")] pub templates: std::collections::HashMap, } @@ -58956,66 +59041,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2500")] + #[serde(default = "default_2505")] pub status: String, - #[serde(default = "default_2501")] + #[serde(default = "default_2506")] pub reason: String, - #[serde(default = "default_2502")] + #[serde(default = "default_2507")] pub message: String, - #[serde(default = "default_2503")] + #[serde(default = "default_2508")] pub retried: bool, - #[serde(default = "default_2504")] + #[serde(default = "default_2509")] pub ms: Integer, - #[serde(default = "default_2505")] + #[serde(default = "default_2510")] pub cause: String, - #[serde(default = "default_2506")] + #[serde(default = "default_2511")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2490")] + #[serde(default = "default_2495")] pub verdict: String, - #[serde(default = "default_2491")] + #[serde(default = "default_2496")] pub items: Vec>, - #[serde(default = "default_2492")] + #[serde(default = "default_2497")] pub undecided: bool, - #[serde(default = "default_2493")] + #[serde(default = "default_2498")] pub epistemic: String, - #[serde(default = "default_2494")] + #[serde(default = "default_2499")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2495")] + #[serde(default = "default_2500")] pub judge: std::collections::HashMap, - #[serde(default = "default_2496")] + #[serde(default = "default_2501")] pub fit_at: String, - #[serde(default = "default_2497")] + #[serde(default = "default_2502")] pub fit: std::collections::HashMap, - #[serde(default = "default_2498")] + #[serde(default = "default_2503")] pub query: std::collections::HashMap, - #[serde(default = "default_2499")] + #[serde(default = "default_2504")] pub legs: std::collections::HashMap, - #[serde(default = "default_2507")] + #[serde(default = "default_2512")] pub leg_status: Vec, - #[serde(default = "default_2508")] + #[serde(default = "default_2513")] pub tracker_unavailable: bool, - #[serde(default = "default_2509")] + #[serde(default = "default_2514")] pub namespaces: Vec, - #[serde(default = "default_2510")] + #[serde(default = "default_2515")] pub by_namespace: std::collections::HashMap>, - #[serde(default = "default_2511")] + #[serde(default = "default_2516")] pub closest: Vec>, - #[serde(default = "default_2512")] + #[serde(default = "default_2517")] pub needs: Vec>, - #[serde(default = "default_2513")] + #[serde(default = "default_2518")] pub closest_note: String, - #[serde(default = "default_2514")] + #[serde(default = "default_2519")] pub nearest: Vec>, - #[serde(default = "default_2515")] + #[serde(default = "default_2520")] pub rerank: std::collections::HashMap, - #[serde(default = "default_2516")] + #[serde(default = "default_2521")] pub answer: String, - #[serde(default = "default_2517")] + #[serde(default = "default_2522")] pub related_prs: Vec>, } @@ -59222,17 +59307,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2518")] + #[serde(default = "default_2523")] pub known_flaky: bool, - #[serde(default = "default_2519")] + #[serde(default = "default_2524")] pub open_issues: Integer, - #[serde(default = "default_2520")] + #[serde(default = "default_2525")] pub issues: Vec>, - #[serde(default = "default_2521")] + #[serde(default = "default_2526")] pub verdict: String, - #[serde(default = "default_2522")] + #[serde(default = "default_2527")] pub tracker_unavailable: bool, - #[serde(default = "default_2523")] + #[serde(default = "default_2528")] pub signal: Option>, } @@ -59315,9 +59400,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2524")] + #[serde(default = "default_2529")] pub unknown: Vec, - #[serde(default = "default_2525")] + #[serde(default = "default_2530")] pub tracker_unavailable: bool, } @@ -59366,19 +59451,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2526")] + #[serde(default = "default_2531")] pub subject: std::collections::HashMap, - #[serde(default = "default_2527")] + #[serde(default = "default_2532")] pub verdict: String, - #[serde(default = "default_2528")] + #[serde(default = "default_2533")] pub items: Vec>, - #[serde(default = "default_2529")] + #[serde(default = "default_2534")] pub epistemic: String, - #[serde(default = "default_2530")] + #[serde(default = "default_2535")] pub record: std::collections::HashMap, - #[serde(default = "default_2531")] + #[serde(default = "default_2536")] pub computed_at: String, - #[serde(default = "default_2532")] + #[serde(default = "default_2537")] pub tracker_unavailable: bool, } @@ -59476,11 +59561,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2533")] + #[serde(default = "default_2538")] pub active_blockers: Integer, - #[serde(default = "default_2534")] + #[serde(default = "default_2539")] pub health: std::collections::HashMap, - #[serde(default = "default_2535")] + #[serde(default = "default_2540")] pub tracker_unavailable: bool, } @@ -59529,17 +59614,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2536")] + #[serde(default = "default_2541")] pub items: Vec>, - #[serde(default = "default_2537")] + #[serde(default = "default_2542")] pub query: std::collections::HashMap, - #[serde(default = "default_2538")] + #[serde(default = "default_2543")] pub legs: std::collections::HashMap, - #[serde(default = "default_2539")] + #[serde(default = "default_2544")] pub epistemic: String, - #[serde(default = "default_2540")] + #[serde(default = "default_2545")] pub tracker_unavailable: bool, - #[serde(default = "default_2541")] + #[serde(default = "default_2546")] pub namespaces: Vec, } @@ -59660,19 +59745,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2542")] + #[serde(default = "default_2547")] pub namespaces: Vec>, - #[serde(default = "default_2543")] + #[serde(default = "default_2548")] pub contract: std::collections::HashMap, - #[serde(default = "default_2544")] + #[serde(default = "default_2549")] pub roles: Vec, - #[serde(default = "default_2545")] + #[serde(default = "default_2550")] pub my_role: String, - #[serde(default = "default_2546")] + #[serde(default = "default_2551")] pub dry_run: bool, - #[serde(default = "default_2547")] + #[serde(default = "default_2552")] pub written: bool, - #[serde(default = "default_2548")] + #[serde(default = "default_2553")] pub view_templates: std::collections::HashMap, } @@ -59835,13 +59920,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2549")] + #[serde(default = "default_2554")] pub database: String, - #[serde(default = "default_2550")] + #[serde(default = "default_2555")] pub reachable: bool, - #[serde(default = "default_2551")] + #[serde(default = "default_2556")] pub contract: std::collections::HashMap, - #[serde(default = "default_2552")] + #[serde(default = "default_2557")] pub view_templates: std::collections::HashMap, } @@ -59881,11 +59966,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2553")] + #[serde(default = "default_2558")] pub tables: Vec>, - #[serde(default = "default_2554")] + #[serde(default = "default_2559")] pub roles: Vec, - #[serde(default = "default_2555")] + #[serde(default = "default_2560")] pub proposal: std::collections::HashMap, } @@ -60014,9 +60099,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2556")] + #[serde(default = "default_2561")] pub sources: Vec>, - #[serde(default = "default_2557")] + #[serde(default = "default_2562")] pub self_service: bool, } @@ -60069,9 +60154,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2558")] + #[serde(default = "default_2563")] pub deactivated: bool, - #[serde(default = "default_2559")] + #[serde(default = "default_2564")] pub namespaces_retired: Vec, } @@ -60112,9 +60197,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2560")] + #[serde(default = "default_2565")] pub contract: std::collections::HashMap, - #[serde(default = "default_2561")] + #[serde(default = "default_2566")] pub rotated_at: String, } @@ -60161,11 +60246,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2562")] + #[serde(default = "default_2567")] pub contract: std::collections::HashMap, - #[serde(default = "default_2563")] + #[serde(default = "default_2568")] pub dry_run: bool, - #[serde(default = "default_2564")] + #[serde(default = "default_2569")] pub written: bool, } @@ -60232,45 +60317,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2565")] + #[serde(default = "default_2570")] pub verdict: String, - #[serde(default = "default_2566")] + #[serde(default = "default_2571")] pub why: Vec, - #[serde(default = "default_2567")] + #[serde(default = "default_2572")] pub lower_bound: f64, - #[serde(default = "default_2568")] + #[serde(default = "default_2573")] pub window_days: Integer, - #[serde(default = "default_2569")] + #[serde(default = "default_2574")] pub since: String, - #[serde(default = "default_2570")] + #[serde(default = "default_2575")] pub features: std::collections::HashMap, - #[serde(default = "default_2571")] + #[serde(default = "default_2576")] pub infra: std::collections::HashMap, - #[serde(default = "default_2572")] + #[serde(default = "default_2577")] pub churn: std::collections::HashMap, - #[serde(default = "default_2573")] + #[serde(default = "default_2578")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2574")] + #[serde(default = "default_2579")] pub source: String, - #[serde(default = "default_2575")] + #[serde(default = "default_2580")] pub timings_ms: std::collections::HashMap, - #[serde(default = "default_2576")] + #[serde(default = "default_2581")] pub tracker_unavailable: bool, - #[serde(default = "default_2577")] + #[serde(default = "default_2582")] pub rollup: std::collections::HashMap, - #[serde(default = "default_2578")] + #[serde(default = "default_2583")] pub streak: std::collections::HashMap, - #[serde(default = "default_2579")] + #[serde(default = "default_2584")] pub smells: std::collections::HashMap, - #[serde(default = "default_2580")] + #[serde(default = "default_2585")] pub prior: std::collections::HashMap, - #[serde(default = "default_2581")] + #[serde(default = "default_2586")] pub unavailable_reason: String, - #[serde(default = "default_2582")] + #[serde(default = "default_2587")] pub candidates: Vec>, - #[serde(default = "default_2583")] + #[serde(default = "default_2588")] pub candidate_matches: Integer, - #[serde(default = "default_2584")] + #[serde(default = "default_2589")] pub resolved_from: String, } @@ -60374,9 +60459,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2585")] + #[serde(default = "default_2590")] pub recorded: bool, - #[serde(default = "default_2586")] + #[serde(default = "default_2591")] pub route: String, } @@ -60560,7 +60645,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2587")] + #[serde(default = "default_2592")] pub deliveries: Vec, } @@ -60682,14 +60767,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2588")] + #[serde(default = "default_2593")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2589")] + #[serde(default = "default_2594")] pub webhooks: Vec, } @@ -60871,7 +60956,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2590")] + #[serde(default = "default_2595")] pub fill_ratio: f64, } @@ -61095,15 +61180,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2591")] + #[serde(default = "default_2596")] pub content: String, - #[serde(default = "default_2592")] + #[serde(default = "default_2597")] pub char_limit: Integer, - #[serde(default = "default_2593")] + #[serde(default = "default_2598")] pub version: Integer, - #[serde(default = "default_2594")] + #[serde(default = "default_2599")] pub updated_at: Option, - #[serde(default = "default_2595")] + #[serde(default = "default_2600")] pub fill_ratio: f64, } @@ -61214,7 +61299,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2596")] + #[serde(default = "default_2601")] pub updated_at: Option, } @@ -61222,7 +61307,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2597")] + #[serde(default = "default_2602")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -68661,741 +68746,756 @@ fn default_2350() -> Vec { fn default_2351() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2352() -> String { +fn default_2352() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2353() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2354() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2355() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2356() -> bool { + serde_json::from_str("false").expect("schema default") +} +fn default_2357() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2353() -> Integer { +fn default_2358() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2354() -> Integer { +fn default_2359() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2355() -> Integer { +fn default_2360() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2356() -> Integer { +fn default_2361() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2357() -> bool { +fn default_2362() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2358() -> bool { +fn default_2363() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2359() -> Option> { +fn default_2364() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2360() -> LiveSearchResultsLive { +fn default_2365() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2361() -> String { +fn default_2366() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2362() -> LiveSearchHitLive { +fn default_2367() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2363() -> Vec { +fn default_2368() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2364() -> Option { +fn default_2369() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2365() -> std::collections::HashMap { +fn default_2370() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2366() -> std::collections::HashMap { +fn default_2371() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2367() -> std::collections::HashMap { +fn default_2372() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2368() -> std::collections::HashMap { +fn default_2373() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2369() -> Option> { +fn default_2374() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2370() -> Vec { +fn default_2375() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2371() -> Integer { +fn default_2376() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2372() -> String { +fn default_2377() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2373() -> Integer { +fn default_2378() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2374() -> String { +fn default_2379() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2375() -> String { +fn default_2380() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2376() -> String { +fn default_2381() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2377() -> String { +fn default_2382() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2378() -> String { +fn default_2383() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2379() -> String { +fn default_2384() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2380() -> String { +fn default_2385() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2381() -> String { +fn default_2386() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2382() -> Vec { +fn default_2387() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2383() -> String { +fn default_2388() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2384() -> String { +fn default_2389() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2385() -> Vec { +fn default_2390() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2386() -> String { +fn default_2391() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2387() -> String { +fn default_2392() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2388() -> Vec { +fn default_2393() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2389() -> Vec { +fn default_2394() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2390() -> Vec { +fn default_2395() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2391() -> String { +fn default_2396() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2392() -> String { +fn default_2397() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2393() -> Vec { +fn default_2398() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2394() -> Vec { +fn default_2399() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2395() -> Vec { +fn default_2400() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2396() -> String { +fn default_2401() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2397() -> String { +fn default_2402() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2398() -> Option { +fn default_2403() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2399() -> String { +fn default_2404() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2400() -> String { +fn default_2405() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2401() -> String { +fn default_2406() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2402() -> String { +fn default_2407() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2403() -> String { +fn default_2408() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2404() -> String { +fn default_2409() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2405() -> Vec { +fn default_2410() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2406() -> Option { +fn default_2411() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2407() -> Integer { +fn default_2412() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2408() -> Integer { +fn default_2413() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2409() -> Integer { +fn default_2414() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2410() -> Integer { +fn default_2415() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2411() -> Integer { +fn default_2416() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2412() -> bool { +fn default_2417() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2413() -> String { +fn default_2418() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2414() -> String { +fn default_2419() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2415() -> String { +fn default_2420() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2416() -> String { +fn default_2421() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2417() -> String { +fn default_2422() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2418() -> String { +fn default_2423() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2419() -> String { +fn default_2424() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2420() -> Option { +fn default_2425() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2421() -> Integer { +fn default_2426() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2422() -> Integer { +fn default_2427() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2423() -> Vec { +fn default_2428() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2424() -> String { +fn default_2429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2425() -> String { +fn default_2430() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2426() -> String { +fn default_2431() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2427() -> String { +fn default_2432() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2428() -> Integer { +fn default_2433() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2429() -> Integer { +fn default_2434() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2430() -> Integer { +fn default_2435() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2431() -> Integer { +fn default_2436() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2432() -> Integer { +fn default_2437() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2433() -> f64 { +fn default_2438() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2434() -> Integer { +fn default_2439() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2435() -> Integer { +fn default_2440() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2436() -> Integer { +fn default_2441() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2437() -> String { +fn default_2442() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2438() -> SessionBriefStats { +fn default_2443() -> SessionBriefStats { serde_json::from_str("{\"events_in\":0,\"windows\":0,\"events_total\":0,\"source_chars\":0,\"brief_chars\":0,\"compression_ratio\":0.0,\"dropped_ungrounded\":0,\"tokens_in\":0,\"tokens_out\":0,\"llm_model\":\"\"}").expect("schema default") } -fn default_2439() -> String { +fn default_2444() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2440() -> String { +fn default_2445() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2441() -> Option { +fn default_2446() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2442() -> Option { +fn default_2447() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2443() -> Option { +fn default_2448() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2444() -> Integer { +fn default_2449() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2445() -> std::collections::HashMap { +fn default_2450() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2446() -> String { +fn default_2451() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2447() -> String { +fn default_2452() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2448() -> Option { +fn default_2453() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2449() -> String { +fn default_2454() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2450() -> Integer { +fn default_2455() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2451() -> Integer { +fn default_2456() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2452() -> Option { +fn default_2457() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2453() -> std::collections::HashMap { +fn default_2458() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2454() -> String { +fn default_2459() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2455() -> Integer { +fn default_2460() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2456() -> String { +fn default_2461() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2457() -> Option { +fn default_2462() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2458() -> String { +fn default_2463() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2459() -> Option { +fn default_2464() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2460() -> String { +fn default_2465() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2461() -> String { +fn default_2466() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2462() -> String { +fn default_2467() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2463() -> String { +fn default_2468() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2464() -> Integer { +fn default_2469() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2465() -> Integer { +fn default_2470() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2466() -> String { +fn default_2471() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2467() -> std::collections::HashMap { +fn default_2472() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2468() -> String { +fn default_2473() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2469() -> String { +fn default_2474() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2470() -> bool { +fn default_2475() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2471() -> String { +fn default_2476() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2472() -> std::collections::HashMap { +fn default_2477() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2473() -> Vec> { +fn default_2478() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2474() -> Vec { +fn default_2479() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2475() -> Vec { +fn default_2480() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2476() -> bool { +fn default_2481() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2477() -> String { +fn default_2482() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2478() -> String { +fn default_2483() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2479() -> Vec { +fn default_2484() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2480() -> bool { +fn default_2485() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2481() -> String { +fn default_2486() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2482() -> bool { +fn default_2487() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2483() -> Vec { +fn default_2488() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2484() -> std::collections::HashMap { +fn default_2489() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2485() -> Vec> { +fn default_2490() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2486() -> bool { +fn default_2491() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2487() -> bool { +fn default_2492() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2488() -> Vec> { +fn default_2493() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2489() -> std::collections::HashMap { +fn default_2494() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2490() -> String { +fn default_2495() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2491() -> Vec> { +fn default_2496() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2492() -> bool { +fn default_2497() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2493() -> String { +fn default_2498() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2494() -> std::collections::HashMap { +fn default_2499() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2495() -> std::collections::HashMap { +fn default_2500() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2496() -> String { +fn default_2501() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2497() -> std::collections::HashMap { +fn default_2502() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2498() -> std::collections::HashMap { +fn default_2503() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2499() -> std::collections::HashMap { +fn default_2504() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2500() -> String { +fn default_2505() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2501() -> String { +fn default_2506() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2502() -> String { +fn default_2507() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2503() -> bool { +fn default_2508() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2504() -> Integer { +fn default_2509() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2505() -> String { +fn default_2510() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2506() -> String { +fn default_2511() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2507() -> Vec { +fn default_2512() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2508() -> bool { +fn default_2513() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2509() -> Vec { +fn default_2514() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2510() -> std::collections::HashMap> { +fn default_2515() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2511() -> Vec> { +fn default_2516() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2512() -> Vec> { +fn default_2517() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2513() -> String { +fn default_2518() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2514() -> Vec> { +fn default_2519() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2515() -> std::collections::HashMap { +fn default_2520() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2516() -> String { +fn default_2521() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2517() -> Vec> { +fn default_2522() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2518() -> bool { +fn default_2523() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2519() -> Integer { +fn default_2524() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2520() -> Vec> { +fn default_2525() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2521() -> String { +fn default_2526() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2522() -> bool { +fn default_2527() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2523() -> Option> { +fn default_2528() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2524() -> Vec { +fn default_2529() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2525() -> bool { +fn default_2530() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2526() -> std::collections::HashMap { +fn default_2531() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2527() -> String { +fn default_2532() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2528() -> Vec> { +fn default_2533() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2529() -> String { +fn default_2534() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2530() -> std::collections::HashMap { +fn default_2535() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2531() -> String { +fn default_2536() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2532() -> bool { +fn default_2537() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2533() -> Integer { +fn default_2538() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2534() -> std::collections::HashMap { +fn default_2539() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2535() -> bool { +fn default_2540() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2536() -> Vec> { +fn default_2541() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2537() -> std::collections::HashMap { +fn default_2542() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2538() -> std::collections::HashMap { +fn default_2543() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2539() -> String { +fn default_2544() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2540() -> bool { +fn default_2545() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2541() -> Vec { +fn default_2546() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2542() -> Vec> { +fn default_2547() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2543() -> std::collections::HashMap { +fn default_2548() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2544() -> Vec { +fn default_2549() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2545() -> String { +fn default_2550() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2546() -> bool { +fn default_2551() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2547() -> bool { +fn default_2552() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2548() -> std::collections::HashMap { +fn default_2553() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2549() -> String { +fn default_2554() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2550() -> bool { +fn default_2555() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2551() -> std::collections::HashMap { +fn default_2556() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2552() -> std::collections::HashMap { +fn default_2557() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2553() -> Vec> { +fn default_2558() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2554() -> Vec { +fn default_2559() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2555() -> std::collections::HashMap { +fn default_2560() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2556() -> Vec> { +fn default_2561() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2557() -> bool { +fn default_2562() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2558() -> bool { +fn default_2563() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2559() -> Vec { +fn default_2564() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2560() -> std::collections::HashMap { +fn default_2565() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2561() -> String { +fn default_2566() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2562() -> std::collections::HashMap { +fn default_2567() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2563() -> bool { +fn default_2568() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2564() -> bool { +fn default_2569() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2565() -> String { +fn default_2570() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2566() -> Vec { +fn default_2571() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2567() -> f64 { +fn default_2572() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2568() -> Integer { +fn default_2573() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2569() -> String { +fn default_2574() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2570() -> std::collections::HashMap { +fn default_2575() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2571() -> std::collections::HashMap { +fn default_2576() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2572() -> std::collections::HashMap { +fn default_2577() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2573() -> std::collections::HashMap { +fn default_2578() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2574() -> String { +fn default_2579() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2575() -> std::collections::HashMap { +fn default_2580() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2576() -> bool { +fn default_2581() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2577() -> std::collections::HashMap { +fn default_2582() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2578() -> std::collections::HashMap { +fn default_2583() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2579() -> std::collections::HashMap { +fn default_2584() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2580() -> std::collections::HashMap { +fn default_2585() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2581() -> String { +fn default_2586() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2582() -> Vec> { +fn default_2587() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2583() -> Integer { +fn default_2588() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2584() -> String { +fn default_2589() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2585() -> bool { +fn default_2590() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2586() -> String { +fn default_2591() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2587() -> Vec { +fn default_2592() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2588() -> bool { +fn default_2593() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2589() -> Vec { +fn default_2594() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2590() -> f64 { +fn default_2595() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2591() -> String { +fn default_2596() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2592() -> Integer { +fn default_2597() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2593() -> Integer { +fn default_2598() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2594() -> Option { +fn default_2599() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2595() -> f64 { +fn default_2600() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2596() -> Option { +fn default_2601() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2597() -> Vec { +fn default_2602() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index f895b436e8e..9315c0b187a 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -8434,6 +8434,28 @@ fn run_get() { ); } #[test] +fn run_reliance() { + let value: clickhouse_loom::RunRelianceInput = + serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\",\"run_id\":\"sample\"}") + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::RunRelianceOutput = + serde_json::from_str("{\"found\":false}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["items"], + serde_json::from_str::("[]").unwrap(), + "run.reliance:items" + ); + assert_eq!( + encoded["truncated"], + serde_json::from_str::("false").unwrap(), + "run.reliance:truncated" + ); +} +#[test] fn run_list() { let value: clickhouse_loom::RunListInput = serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap(); diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index c70328d10a1..acb0290fe90 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -9810,6 +9810,30 @@ export interface RunListOutput { total?: number | null; } +export interface RunRelianceInput { + org: string; + namespace: string; + run_id: string; +} + +export interface RunRelianceItem { + kind: string; + key: string; + state: "returned" | "reported" | "reported_and_served" | "not_recorded"; + revisions?: RunRelianceRevision[]; + last_served_at?: string; +} + +export interface RunRelianceRevision { + versions?: string[]; +} + +export interface RunRelianceOutput { + found: boolean; + items?: RunRelianceItem[]; + truncated?: boolean; +} + export interface RunRetractCreditInput { org: string; namespace: string; @@ -11292,6 +11316,7 @@ export type OpName = | "run.get" | "run.grade" | "run.list" + | "run.reliance" | "run.retract_credit" | "search.query" | "session.brief_delete" @@ -11680,6 +11705,7 @@ export interface OpMap { "run.get": { input: RunGetInput; output: RunGetOutput }; "run.grade": { input: RunGradeInput; output: RunGradeOutput }; "run.list": { input: RunListInput; output: RunListOutput }; + "run.reliance": { input: RunRelianceInput; output: RunRelianceOutput }; "run.retract_credit": { input: RunRetractCreditInput; output: RunRetractCreditOutput }; "search.query": { input: SearchQueryInput; output: SearchQueryOutput }; "session.brief_delete": { input: SessionBriefDeleteInput; output: SessionBriefDeleteOutput }; @@ -12068,6 +12094,7 @@ export const OPS: readonly OpSpec[] = [ { name: "run.get", group: "run", method: "get", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 300, audit: false, readOnly: true }, { name: "run.grade", group: "run", method: "grade", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 800, audit: true, readOnly: false }, { name: "run.list", group: "run", method: "list", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 200, audit: false, readOnly: true }, + { name: "run.reliance", group: "run", method: "reliance", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: true }, { name: "run.retract_credit", group: "run", method: "retractCredit", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 800, audit: true, readOnly: false }, { name: "search.query", group: "search", method: "query", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 3500, audit: false, readOnly: true }, { name: "session.brief_delete", group: "session", method: "briefDelete", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 200, audit: true, readOnly: false }, @@ -12131,4 +12158,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 385; +export const GENERATED_OP_COUNT = 386; diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index 0b70840abac..3cddf995ed0 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -1071,6 +1071,10 @@ "sdk_method", "dashboard", ), + "run.reliance": ( + "sdk_method", + "dashboard", + ), "run.retract_credit": ("sdk_method",), "search.query": ("sdk_method",), "session.brief_delete": ( diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 59f7d57145b..1ca5bfa3aea 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -6897,6 +6897,8 @@ class TrackerSettings(BaseModel): "run.get": 300, "run.grade": 800, "run.list": 200, + # One point read and one grouped read of the namespace's receipts by the run_id index. + "run.reliance": 300, # Reads before the claim, a drain that can wait for an in-flight flush, then under the # claim one grouped read (a run's by the run_id index, a window's by the credited_at # and actor indexes) and one fenced insert. diff --git a/server/tasks/api/models_run.py b/server/tasks/api/models_run.py index aa3aacf6d16..8ed756e27de 100644 --- a/server/tasks/api/models_run.py +++ b/server/tasks/api/models_run.py @@ -7,7 +7,8 @@ terminal status, the memories the agent RELIED on (`memories_used` → a `used` usage event, distinct from `recall` = returned) and an outcome that feeds the evidence counters. `run.get` / `run.list` render the story: goal → recalled → -used → written → cost → outcome. `run.retract_credit` cancels a run's labels with +used → written → cost → outcome. `run.reliance` lists what a run was served beside +what its client reported. `run.retract_credit` cancels a run's labels with compensating events. """ @@ -22,6 +23,7 @@ from server.operations.base import MCP_HIDDEN from server.operations.read_projection import ProjectedRow from server.tasks.domain.budgets import BudgetKind +from server.tasks.domain.reliance import RelianceState from server.tasks.domain.states import RunStatus @@ -404,6 +406,54 @@ class RunGetOutput(BaseModel): over_budget: list[BudgetKind] = Field(default_factory=list) +class RunRelianceInput(BaseModel): + """What one run was served, at which revisions, and what its client reported relying on. + + Each item has one state.""" + + org: str + namespace: str + # The run whose reads and report are listed. + run_id: str = Field(min_length=1, max_length=128) + + +class RunRelianceRevision(BaseModel): + # The stored versions under which the run was served one content, ascending, as + # decimal text: a memory version is the write time of its stored row in nanoseconds, + # above 2^53. A document's revision number. Empty: the record holds the content by + # its hash alone. + versions: list[str] = Field(default_factory=list) + + +class RunRelianceItem(BaseModel): + # `memory` or `document`. A plain string: a reader of a stored value takes one it + # does not know. + kind: str + # The memory key, or the document's source URI. + key: str + # One of the four states; `items` says what each means. + state: RelianceState + # The revisions the run's receipts hold for the item, highest version first. Empty: + # the record names no revision (always so for `not_recorded`). + revisions: list[RunRelianceRevision] = Field(default_factory=list) + # The newest receipt of the item, ISO UTC; empty for `not_recorded`. + last_served_at: str = "" + + +class RunRelianceOutput(BaseModel): + # False when the namespace holds no run with this id; `items` is then empty. + found: bool + # One entry per item: `returned` (served, not reported), `reported` (the client's + # claim, for an item the record holds), `reported_and_served` (the claim names a + # served revision), `not_recorded` (reported, no record: not a mismatch). Reported + # items first, in the order reported; then the others, last served first. + items: list[RunRelianceItem] = Field(default_factory=list) + # True when the answer is cut: it keeps every reported item, then the items served + # most recently, 500 recorded items in all, and the 32 highest recorded versions of + # each. + truncated: bool = False + + class RunListInput(BaseModel): org: str namespace: str diff --git a/server/tasks/api/ops_run.py b/server/tasks/api/ops_run.py index 79cb180639a..b8144ee02ff 100644 --- a/server/tasks/api/ops_run.py +++ b/server/tasks/api/ops_run.py @@ -14,6 +14,8 @@ RunGradeOutput, RunListInput, RunListOutput, + RunRelianceInput, + RunRelianceOutput, RunRetractCreditInput, RunRetractCreditOutput, ) @@ -23,6 +25,7 @@ handle_run_get, handle_run_grade, handle_run_list, + handle_run_reliance, handle_run_retract_credit, ) @@ -60,6 +63,17 @@ audit=False, ) +run_reliance = Operation( + name="run.reliance", + maturity="experimental", + input_model=RunRelianceInput, + output_model=RunRelianceOutput, + handler=handle_run_reliance, + idempotent=True, + required_role=Role.VIEWER, + audit=False, +) + run_list = Operation( name="run.list", input_model=RunListInput, @@ -98,6 +112,7 @@ run_begin, run_complete, run_get, + run_reliance, run_list, run_grade, run_retract_credit, diff --git a/server/tasks/app/run.py b/server/tasks/app/run.py index e8bb41e62b9..718af7b0e28 100644 --- a/server/tasks/app/run.py +++ b/server/tasks/app/run.py @@ -1,5 +1,5 @@ -"""Run ledger handlers (`run.begin`, `run.complete`, `run.get`, `run.list`, -`run.grade`, `run.retract_credit`). +"""Run ledger handlers (`run.begin`, `run.complete`, `run.get`, `run.reliance`, +`run.list`, `run.grade`, `run.retract_credit`). One row per agent execution in `loom.agent_runs` (ReplacingMergeTree on org/namespace/run_id). begin inserts it active; complete re-inserts the same @@ -51,11 +51,16 @@ RunGradeProposal, RunListInput, RunListOutput, + RunRelianceInput, + RunRelianceItem, + RunRelianceOutput, + RunRelianceRevision, RunRetractCreditInput, RunRetractCreditOutput, RunRow, ) from server.tasks.domain.budgets import budgets_exceeded +from server.tasks.domain.reliance import Reported, reliance from server.tasks.domain.session_runs import is_session_run_id from server.tasks.store import runs as runs_store from server.tasks.store.rows import RunLedgerRow @@ -1175,6 +1180,38 @@ def _run_window(row: RunLedgerRow) -> tuple[datetime, datetime]: return row["started_at"], row.get("completed_at") or _now() +async def handle_run_reliance(input: RunRelianceInput) -> RunRelianceOutput: + """What the run was served under its own id in the namespace, beside what its last + `run.complete` kept as relied on. A failed receipt read fails the op: a partial answer + would print a report as having no record.""" + ch = get_client() + existing = await runs_store.fetch_run(ch, input.org, input.namespace, input.run_id) + if existing is None: + return RunRelianceOutput(found=False) + reported = [str(k) for k in (existing.get("memories_used") or [])] + # Refused to narrowed tokens, as run.get: a run's receipts name rows other users wrote. + served, truncated = await runs_store.receipted_items( + ch, input.org, input.namespace, str(existing["run_id"]), reported + ) + return RunRelianceOutput( + found=True, + items=[ + RunRelianceItem( + kind=item.kind, + key=item.key, + state=item.state, + revisions=[ + RunRelianceRevision(versions=[str(v) for v in revision.versions]) + for revision in item.revisions + ], + last_served_at=_iso(item.last_served), + ) + for item in reliance(served, [Reported(key) for key in reported]) + ], + truncated=truncated, + ) + + async def handle_run_list(input: RunListInput) -> RunListOutput: """A page of a namespace's agent runs and their match count (`total`), filtered and sorted.""" diff --git a/server/tasks/domain/reliance.py b/server/tasks/domain/reliance.py new file mode 100644 index 00000000000..d87c90cf7fb --- /dev/null +++ b/server/tasks/domain/reliance.py @@ -0,0 +1,110 @@ +"""Reliance: one state for each item a run was served or its client reported. + +The record is the run's read receipts: the items Loom's answers carried under the run, +with the revision each read held. The report is the run row's `memories_used`: the +memory keys the client named as relied on, as the run's last `run.complete` kept them. +The record is best effort and expires, so a reported item without one is `not_recorded`. +No state means a mismatch. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from datetime import datetime +from typing import Literal, NamedTuple + +from server.memory.domain.read_receipts import MEMORY + +RelianceState = Literal["returned", "reported", "reported_and_served", "not_recorded"] + + +class Served(NamedTuple): + """One item of the run's receipts, with the (content hash, version) pairs as stored: + an empty hash and a zero version are not recorded.""" + + kind: str + key: str + seen: Sequence[tuple[str, int]] + last_served: datetime + + +class Reported(NamedTuple): + """One entry of the report: a memory key, with the revision relied on where the + client named one.""" + + key: str + version: int = 0 + sha256: str = "" + + +class Revision(NamedTuple): + """One content the run was served. `versions` are the stored versions it was read + under, ascending; empty when the record holds it by its hash alone.""" + + sha256: str + versions: tuple[int, ...] + + +class Reliance(NamedTuple): + kind: str + key: str + state: RelianceState + revisions: tuple[Revision, ...] + last_served: datetime | None + + +def revisions_of(seen: Iterable[tuple[str, int]]) -> tuple[Revision, ...]: + """The revisions `seen` names, highest version first and one held by hash alone last. + + One content is one revision under every stored version it was read at (a row and its + search document are written at different versions), so pairs group on the hash. A + pair with no hash is the read of a stored row: it joins the revision that lists its + version, and is a revision of its own when none does.""" + by_hash: dict[str, set[int]] = {} + hashless: set[int] = set() + for sha256, version in seen: + if sha256: + by_hash.setdefault(sha256, set()).update({version} - {0}) + elif version: + hashless.add(version) + hashed: set[int] = set().union(*by_hash.values()) + revisions = [Revision(sha256, tuple(sorted(versions))) for sha256, versions in by_hash.items()] + revisions += [Revision("", (version,)) for version in hashless - hashed] + return tuple(sorted(revisions, key=lambda r: (-max(r.versions, default=0), r.sha256))) + + +def _names(report: Reported, revisions: Iterable[Revision]) -> bool: + """Whether the report names a revision the record holds. A zero version or an empty + hash names none.""" + return any( + (report.version and report.version in revision.versions) + or (report.sha256 and report.sha256 == revision.sha256) + for revision in revisions + ) + + +def reliance(served: Iterable[Served], reported: Iterable[Reported]) -> list[Reliance]: + """One item per reported key in the order reported, then the served items no report + names in the order given. A report is of memory keys, so it matches a memory item + only; a key reported twice counts as its first entry.""" + record = list(served) + memories = {item.key: item for item in record if item.kind == MEMORY} + out: dict[str, Reliance] = {} + for report in reported: + if report.key in out: + continue + item = memories.get(report.key) + if item is None: + out[report.key] = Reliance(MEMORY, report.key, "not_recorded", (), None) + continue + revisions = revisions_of(item.seen) + state: RelianceState = "reported_and_served" if _names(report, revisions) else "reported" + out[report.key] = Reliance(MEMORY, item.key, state, revisions, item.last_served) + return [ + *out.values(), + *( + Reliance(item.kind, item.key, "returned", revisions_of(item.seen), item.last_served) + for item in record + if item.kind != MEMORY or item.key not in out + ), + ] diff --git a/server/tasks/store/runs.py b/server/tasks/store/runs.py index b95c10cd5d5..52ae853e6b0 100644 --- a/server/tasks/store/runs.py +++ b/server/tasks/store/runs.py @@ -1,6 +1,6 @@ """SQL for the run ledger: `loom.agent_runs` and the reads a run derives from the planes that carry its `run_id` / `session_id` (`loom.memory`, -`loom.search_trace_log`, `loom.agent_turn_usage`). +`loom.search_trace_log`, `loom.agent_turn_usage`, `loom.read_receipts`). `loom.agent_runs` is a ReplacingMergeTree on (org, namespace, run_id): every write is a whole version row (`run_row` fills the columns a partial row @@ -19,14 +19,18 @@ from server.core.ch import sequential_reads from server.core.leases import key_exists from server.identity.domain.read_scope import ReadFilters, scope_and +from server.memory.domain.read_receipts import MEMORY from server.observability import degradations from server.observability.store.event_reads import MASKED_EVENTS +from server.tasks.domain.reliance import Served from server.tasks.store.rows import RunLedgerRow log = logging.getLogger(__name__) # Cap on the keys a derived read returns. DERIVED_LIMIT = 500 +# The recorded (hash, version) pairs of one item an answer keeps. +RECEIPT_PAIRS = 32 RUN_COLUMNS = ( "org", @@ -456,6 +460,55 @@ async def traced_recall_keys(ch: Any, org: str, ns: str, run_id: str) -> list[st return [str(r["memory_key"]) for r in rows if r.get("memory_key")] +async def receipted_items( + ch: Any, org: str, ns: str, run_id: str, reported: list[str] +) -> tuple[list[Served], bool]: + """The items the run's receipts name in the namespace, the reported ones first, then + last served first, each with its highest recorded (hash, version) pairs; and whether + the answer is cut (more than DERIVED_LIMIT items, or more than RECEIPT_PAIRS pairs of + one).""" + # One row an item, so the cap never splits one, and a report holds fewer keys than + # the cap: a cut answer keeps every reported item's receipts. The pairs are sorted + # before they are cut, or which of them survive would differ between two calls. + # No time bound: a read can carry the run's id before its row is written and after + # it closes. + rows = await ch.query_all( + """ + SELECT kind, item_key, max(ts) AS last_served, + arraySlice( + arrayReverseSort(p -> (p.2, p.1), groupUniqArray((content_sha256, version))), + 1, {pairs:UInt32} + ) AS seen + FROM loom.read_receipts + WHERE org = {org:String} AND namespace = {ns:String} AND run_id = {rid:String} + GROUP BY kind, item_key + ORDER BY (kind = {memory:String} AND has({reported:Array(String)}, item_key)) DESC, + last_served DESC, kind, item_key + LIMIT {lim:UInt32} + """, + params={ + "org": org, + "ns": ns, + "rid": run_id, + "reported": reported, + "memory": MEMORY, + "pairs": RECEIPT_PAIRS + 1, + "lim": DERIVED_LIMIT + 1, + }, + ) + cut = len(rows) > DERIVED_LIMIT or any(len(r["seen"]) > RECEIPT_PAIRS for r in rows) + served = [ + Served( + str(r["kind"]), + str(r["item_key"]), + [(str(sha256), int(version)) for sha256, version in r["seen"][:RECEIPT_PAIRS]], + r["last_served"], + ) + for r in rows[:DERIVED_LIMIT] + ] + return served, cut + + async def run_cost( ch: Any, org: str, ns: str, session_id: str, since: datetime, until: datetime ) -> tuple[int, int, float]: @@ -505,6 +558,7 @@ async def live_memories_by_key( __all__ = [ "DERIVED_LIMIT", "LIST_ORDERS", + "RECEIPT_PAIRS", "RUN_COLUMNS", "RUN_TEXT_MATCH", "count_runs", @@ -513,6 +567,7 @@ async def live_memories_by_key( "list_runs", "live_memories_by_key", "observation_count", + "receipted_items", "run_cost", "run_row", "runs_to_grade", diff --git a/tests/analyzer/cases/planes.py b/tests/analyzer/cases/planes.py index a635475a06b..e9299e185d9 100644 --- a/tests/analyzer/cases/planes.py +++ b/tests/analyzer/cases/planes.py @@ -886,13 +886,16 @@ async def _budget_warning_events(ch: RecordingCH, _v: dict[str, Any]) -> None: async def _session_runs(ch: RecordingCH, c: dict[str, Any]) -> None: """The session-run ledger reads: the run under an id, the idle sweep, a - run's spend over its window, and the time a re-sent turn is recorded with.""" + run's spend over its window, the items its receipts name, and the time a re-sent + turn is recorded with.""" from server.insights.store import cost from server.tasks.store import runs await runs.active_runs_by_id(ch, ORG, "mcp-" + "0" * 40) await runs.idle_session_runs(ch, idle_seconds=1800, limit=500) await runs.run_cost(ch, ORG, NS, "s1", _DT, _DT) + # run.reliance's handler stops at a missing run row, so its read is driven here. + await runs.receipted_items(ch, ORG, NS, "r1", ["k1"]) await cost.recorded_turn_times(ORG, NS, "s1", ["m1"], ch=ch) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 2b17f29e6b7..fdc1617239a 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -801,6 +801,7 @@ 5909da4606be SELECT DISTINCT org, owner_subject FROM loom.knowledge_sources WHERE (source_kind = ? OR kind = ? OR credential_mode = ?) AND org = {org:String} AND owner_subject != ? ORDER BY org, owner_subject LIMI 5923bd3d36dc SELECT thread_id, count() AS n, argMax((agent, toString(role), substringUTF8(content, ?, {listed:UInt32})), (ts, msg_id)) AS last_turn FROM loom.conversations WHERE org = {org:String} AND namespace = 593e0e151193 SELECT toString(memory_id) AS memory_id FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND memory_key = {key:String} +5958c75c9b0c SELECT kind, item_key, max(ts) AS last_served, arraySlice( arrayReverseSort(p -> (p.?, p.?), groupUniqArray((content_sha256, version))), ?, {pairs:UInt32} ) AS seen FROM loom.read_receipts WHERE org = 596490bd9ba5 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 596642e90401 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 596ef23d53ca SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 88171542caf..78210253d3c 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -247,6 +247,7 @@ "conversation.threads", "run.get", "run.list", + "run.reliance", "working_memory.get", "working_memory.render", "learnings.list", @@ -305,6 +306,8 @@ def __init__(self, org: str, ns_a: str, ns_b: str) -> None: # Canaries in the conversation, run, working-memory and policy planes. self.thread_id = "" self.run_id = "" + # The memory the canary run read: its key holds a nonce. + self.read_key = "" self.policy_id = "" # A session brief canary. self.brief_key = "" @@ -737,6 +740,20 @@ def seed(control_plane_url: str, mint_test_token) -> _Seed: ) assert r.status_code == 200, r.text s.run_id = str(r.json().get("run_id") or "") + # One read under the run, left open, so run.reliance lists an item that holds a nonce. + n_read = _canary() + s.nonces.append(n_read) + s.read_key = f"canary_read_{n_read}" + body = {"org": org, "namespace": s.ns_a, "agent": "a", "memory_key": s.read_key} + r = _post(control_plane_url, tok_a, "memory.set", {**body, "value": "read by the canary run"}) + assert r.status_code == 200, r.text + r = httpx.post( + f"{control_plane_url}/v1/memory.get", + json=body, + headers={"Authorization": f"Bearer {tok_a}", "X-Loom-Run-Id": s.run_id}, + timeout=30.0, + ) + assert r.status_code == 200 and r.json().get("found") is True, r.text n_wm = _canary() s.nonces.append(n_wm) r = _post( @@ -1468,6 +1485,16 @@ def test_positive_control_tenant_a_reads_its_canaries_in_the_tenant_text_planes( assert r.status_code == 200 and r.json().get("found") is True and seed.leaked(r.text), r.text[ :300 ] + # A receipt is written after its answer: the run's list holds the key once it lands. + reliance = {"org": seed.org, "namespace": seed.ns_a, "run_id": seed.run_id} + wait_until( + lambda: ( + seed.read_key + in _post(control_plane_url, tokens["a_writer"], "run.reliance", reliance).text + ), + max_wait=15, + description="the canary run's read is listed", + ) r = _post( control_plane_url, tokens["a_writer"], diff --git a/tests/integration/test_run_reliance.py b/tests/integration/test_run_reliance.py new file mode 100644 index 00000000000..969f109d300 --- /dev/null +++ b/tests/integration/test_run_reliance.py @@ -0,0 +1,266 @@ +"""run.reliance: what one run was served beside what its client reported relying on. + +A read under a run lists the item at the version the read held; a report of a key +reads beside the versions served and never names one of them; a report with no read +on record says the recall is not recorded, also for a read made with receipts off. The +op answers alike over HTTP, the Python SDK, the CLI and MCP by name, a run id two +namespaces share lists each namespace's own items, and a cut answer keeps the +reported item and each item's highest versions. +""" + +from __future__ import annotations + +import asyncio +import json +import sys +import uuid +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "sdk" / "python")) + +from tests.integration._eventually import eventually, overrides_adopted # noqa: E402 +from tests.integration.test_extraction_status_mine import _loom_op, _mint # noqa: E402 +from tests.integration.test_read_receipts import ( # noqa: E402 + ORG, + _landed, + _read, + receipts_switch, # noqa: F401 — the fixture, used by name +) + +pytestmark = pytest.mark.asyncio + +FIRST = "the orders cluster keeps seven daily snapshots" +SECOND = "the orders cluster keeps fourteen daily snapshots" +THIRD = "the billing cluster keeps thirty daily snapshots" + + +def _ns(label: str) -> str: + return f"rel-{label}-{uuid.uuid4().hex[:6]}" + + +async def _begin(agent: Any, run_id: str = "") -> str: + return str((await agent.run.begin(goal="answer a retention question", run_id=run_id))["run_id"]) + + +async def _listed(agent: Any, run: str, revisions: int) -> list[dict[str, Any]]: + """The run's items once the record holds `revisions` revisions: a receipt is written + after its answer.""" + + async def items() -> list[dict[str, Any]]: + answer = await agent.run.reliance(run) + held = sum(len(item["revisions"]) for item in answer["items"]) + return answer["items"] if held >= revisions else [] + + return await eventually(items, description=f"{revisions} revisions of {run} are listed") + + +async def test_an_unreported_read_is_returned_at_its_version( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("returned") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("snapshots", FIRST, memory_type="semantic") + run = await _begin(a) + got = await _read(a, "memory.get", run, memory_key="snapshots") + await _landed(ch_client, ns, run_id=run) + answer = await a.run.reliance(run) + + assert (answer["found"], answer["truncated"]) == (True, False) + [item] = answer["items"] + assert (item["kind"], item["key"], item["state"]) == ("memory", "snapshots", "returned") + # a memory version is past 2^53: the wire carries its digits + assert item["revisions"] == [{"versions": [str(got["version"])]}] + assert datetime.fromisoformat(item["last_served_at"]).tzinfo is not None + + +async def test_a_key_only_report_reads_reported_beside_the_versions_served( + control_plane_url: str, +) -> None: + from loom import Agent + + ns = _ns("reported") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + run = await _begin(a) + await a.memory.set("snapshots", FIRST, memory_type="semantic") + first = await _read(a, "memory.get", run, memory_key="snapshots") + await a.memory.set("snapshots", SECOND, memory_type="semantic") + second = await _read(a, "memory.get", run, memory_key="snapshots") + closed = await a.run.complete(run, memories_used=["snapshots"]) + assert closed["used_applied"] == 1, closed + [item] = await _listed(a, run, revisions=2) + + assert second["version"] > first["version"] + # the report names a key and no revision: it never reads as a revision served + assert item["state"] == "reported" + assert item["revisions"] == [ + {"versions": [str(second["version"])]}, + {"versions": [str(first["version"])]}, + ] + + +async def test_a_report_without_a_record_is_not_recorded_also_with_receipts_off( + control_plane_url: str, + ch_client: Any, + receipts_switch: httpx.AsyncClient, # noqa: F811 +) -> None: + from loom import Agent + + ns = _ns("unrecorded") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("never_read", FIRST, memory_type="semantic") + await a.memory.set("read_while_off", SECOND, memory_type="semantic") + # a third content: a write that repeats another key's content stores no row + await a.memory.set("read_while_on", THIRD, memory_type="semantic") + run = await _begin(a) + + off = {"name": "read_receipts_enabled", "value": False} + assert (await receipts_switch.post("/v1/admin/settings.set", json=off)).status_code == 200 + await overrides_adopted() + await _read(a, "memory.get", run, memory_key="read_while_off") + + on = {"name": "read_receipts_enabled", "clear": True} + assert (await receipts_switch.post("/v1/admin/settings.set", json=on)).status_code == 200 + await overrides_adopted() + await _read(a, "memory.get", run, memory_key="read_while_on") + # the later read's receipt has landed, so the earlier one would have by now + await _landed(ch_client, ns, item_key="read_while_on") + + await a.run.complete(run, memories_used=["never_read", "read_while_off"]) + answer = await a.run.reliance(run) + + states = {item["key"]: item for item in answer["items"]} + assert [item["key"] for item in answer["items"]] == [ + "never_read", + "read_while_off", + "read_while_on", + ] + for key in ("never_read", "read_while_off"): + assert (states[key]["state"], states[key]["revisions"], states[key]["last_served_at"]) == ( + "not_recorded", + [], + "", + ) + assert states["read_while_on"]["state"] == "returned" + + +async def test_http_the_sdk_the_cli_and_mcp_by_name_answer_alike( + control_plane_url: str, ch_client: Any, capsys: pytest.CaptureFixture[str] +) -> None: + from loom import Agent, cli + + ns = _ns("alike") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("snapshots", FIRST, memory_type="semantic") + run = await _begin(a) + await _read(a, "memory.get", run, memory_key="snapshots") + await _landed(ch_client, ns, run_id=run) + await a.run.complete(run, memories_used=["snapshots"]) + + body = {"org": ORG, "namespace": ns, "run_id": run} + over_http = (await a.transport.post_with_meta("/v1/run.reliance", body)).data + from_sdk = await a.run.reliance(run) + + capsys.readouterr() + # the CLI runs its own event loop + argv = ["call", "run.reliance", f"run_id={run}", "--org", ORG, "--namespace", ns] + assert await asyncio.to_thread(cli.main, [*argv, "--server", control_plane_url]) == 0 + from_cli = json.loads(capsys.readouterr().out) + + token = _mint(ORG, [ns], f"sa:reliance-{uuid.uuid4().hex[:6]}") + over_mcp = _loom_op(control_plane_url, token, "run.reliance", {"namespace": ns, "run_id": run}) + assert not over_mcp.get("isError"), over_mcp + + [item] = over_http["items"] + assert (item["key"], item["state"]) == ("snapshots", "reported") + for answer in (from_sdk, from_cli, over_mcp["structuredContent"]): + assert {k: answer[k] for k in ("found", "items", "truncated")} == { + "found": True, + "items": over_http["items"], + "truncated": False, + } + + +async def test_the_same_run_id_in_another_namespace_lists_that_namespace_only( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + here, there, nowhere = _ns("here"), _ns("there"), _ns("nowhere") + run = f"rel-shared-{uuid.uuid4().hex[:8]}" + answers: dict[str, dict[str, Any]] = {} + for ns, key in ((here, "kept_here"), (there, "kept_there")): + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set(key, FIRST, memory_type="semantic") + assert await _begin(a, run) == run + await _read(a, "memory.get", run, memory_key=key) + await _landed(ch_client, ns, run_id=run) + for ns in (here, there, nowhere): + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + answers[ns] = await a.run.reliance(run) + + assert [item["key"] for item in answers[here]["items"]] == ["kept_here"] + assert [item["key"] for item in answers[there]["items"]] == ["kept_there"] + # a namespace that holds no such run reads no receipt + assert answers[nowhere] == {"found": False, "items": [], "truncated": False} + + +async def test_a_cut_answer_keeps_the_reported_item_and_the_highest_versions( + control_plane_url: str, ch_client: Any +) -> None: + from loom import Agent + + ns = _ns("cut") + now = datetime.now(UTC).replace(microsecond=0) + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("reported_first", FIRST, memory_type="semantic") + run = await _begin(a) + + def receipt(key: str, version: int, sha256: str, age: timedelta) -> list[Any]: + return [now - age, ORG, ns, "memory", key, version, sha256, "memory.get", run] + + # 502 items: the reported one is the oldest read, `many` the newest with 34 + # revisions, and 500 between them. + rows = [receipt("reported_first", 7, "a" * 64, timedelta(hours=2))] + rows += [ + receipt("many", version, f"{version:064x}", timedelta(seconds=40 - version)) + for version in range(1, 35) + ] + rows += [ + receipt(f"item-{i:03d}", 1, f"{1000 + i:064x}", timedelta(minutes=1, seconds=i)) + for i in range(500) + ] + ch_client.insert( + "loom.read_receipts", + rows, + column_names=[ + "ts", + "org", + "namespace", + "kind", + "item_key", + "version", + "content_sha256", + "operation", + "run_id", + ], + ) + await a.run.complete(run, memories_used=["reported_first"]) + answer = await a.run.reliance(run) + + assert answer["truncated"] is True + items = answer["items"] + assert len(items) == 500 + assert (items[0]["key"], items[0]["state"]) == ("reported_first", "reported") + assert items[0]["revisions"] == [{"versions": ["7"]}] + assert items[1]["key"] == "many" + assert items[1]["revisions"] == [{"versions": [str(v)]} for v in range(34, 2, -1)] + # the item read longest ago among the unreported is the one the cut drops + assert "item-499" not in {item["key"] for item in items} diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 8df74dd9087..0dd7ab306b2 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -277,6 +277,10 @@ "category": "explicit", "reason": "Implements an explicit run read, list or grading request; ambient begin and complete sends are classified separately." }, + "sdk/python/loom/run.py:run.reliance:cc289a2c227dd793307a:1": { + "category": "explicit", + "reason": "Implements an explicit run read, list or grading request; ambient begin and complete sends are classified separately." + }, "sdk/python/loom/run.py:run.retract_credit:a4b92b19e519d190b022:1": { "category": "explicit", "reason": "Implements an explicit credit retraction request: a run id or a window and a dry-run flag, no session content." @@ -427,7 +431,7 @@ "sdk/python/loom/integrations/llamaindex.py": "06eaa071115cad752d27bdc9bf7c4d5b6f5d7d39d9896267fcd459a4e06bf661", "sdk/python/loom/integrations/openai_agents.py": "143fe1df060b96550a33f77fa44416e291c2154552e433f8309275f61c8fca2a", "sdk/python/loom/memory.py": "0c9f8c1e9bcab157d817ce7f097068817f8a6261225d415ccd7cdf6111b390e0", - "sdk/python/loom/run.py": "e8a226167889f9657f93ffa9b00b46cdda70de49ce236c07da1124a2f23b3832", + "sdk/python/loom/run.py": "f9241e7bcdddc5f6d91323e5b50a2bc76cbf87e46a91b6503becb338893bc7e7", "sdk/python/loom/session.py": "5f0fd61fcfdbf9d60888b111887fca8f32e24eb51ca9ff04a256901657c3202b", "sdk/typescript/src/integrations/claude-memory.ts": "c846f0011d7cf1ba4b30e99fbfd8adb6b29abff56856d0dbe14fba620007f6bc", "sdk/typescript/src/integrations/google-adk.ts": "26035863d6a81630e1a10c2045128b4483151ad9e4d13e9202d9c90054cf62d6", diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index 1c75d43ae49..8acd9989924 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -1724,6 +1724,10 @@ "body", "options" ], + "reliance": [ + "body", + "options" + ], "retract_credit": [ "body", "options" @@ -3616,6 +3620,9 @@ "order_by", "q" ], + "reliance": [ + "run_id" + ], "retract_credit": [ "run_id", "since", diff --git a/tests/unit/test_run_reliance.py b/tests/unit/test_run_reliance.py new file mode 100644 index 00000000000..a1ae4b78c0c --- /dev/null +++ b/tests/unit/test_run_reliance.py @@ -0,0 +1,386 @@ +"""run.reliance: what a run was served, at which revisions, and what its client +reported relying on. + +One pure function derives an item's state from the run's read receipts (the record) +and the run row's `memories_used` (the report). The handler reads both under the +addressed `(org, namespace)` and prints versions, never a content hash or a reader. +""" + +from __future__ import annotations + +import ast +import asyncio +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest + +from server.memory.domain.read_receipts import DOCUMENT, MEMORY +from server.tasks.api.models_run import RunRelianceInput, RunRelianceOutput +from server.tasks.domain.reliance import ( + Reported, + Revision, + Served, + reliance, + revisions_of, +) +from server.tasks.store import runs as runs_store +from tests.unit.test_run_ledger import T0, _FakeCH, _run_row + +ROOT = Path(__file__).resolve().parents[2] + +V1 = 1_780_000_000_000_000_001 +V2 = 1_780_000_000_000_000_002 +V3 = 1_780_000_000_000_000_003 +H1 = "a" * 64 +H2 = "b" * 64 +T1 = T0 + timedelta(seconds=30) + + +def _served(key: str, seen: list[tuple[str, int]], kind: str = MEMORY, at: datetime = T0) -> Served: + return Served(kind, key, seen, at) + + +# ------------------------------------------------------------------ the function + + +def test_each_state_follows_the_record_and_the_report() -> None: + served = [ + _served("served-only", [(H1, V1)]), + _served("by-version", [(H1, V1)]), + _served("by-hash", [(H2, V2)]), + _served("other-revision", [(H1, V1)]), + _served("docs://guide", [("", 3)], kind=DOCUMENT, at=T1), + ] + reported = [ + Reported("by-version", version=V1), + Reported("by-hash", sha256=H2), + Reported("other-revision", version=V3, sha256=H2), + Reported("no-record", version=V1, sha256=H1), + ] + + out = {(i.kind, i.key): i for i in reliance(served, reported)} + + # A run that retrieves an item and does not report it. + assert out[(MEMORY, "served-only")].state == "returned" + assert out[(MEMORY, "served-only")].revisions == (Revision(H1, (V1,)),) + # A report whose version or hash is in the run's record. + assert out[(MEMORY, "by-version")].state == "reported_and_served" + assert out[(MEMORY, "by-hash")].state == "reported_and_served" + # A report of a revision the record does not hold keeps the revisions served. + assert out[(MEMORY, "other-revision")].state == "reported" + assert out[(MEMORY, "other-revision")].revisions == (Revision(H1, (V1,)),) + # A report with no record: no revision, never the item's latest, and no time. + missing = out[(MEMORY, "no-record")] + assert missing.state == "not_recorded" + assert missing.revisions == () and missing.last_served is None + # A document is recorded by its revision number. + doc = out[(DOCUMENT, "docs://guide")] + assert doc.state == "returned" and doc.last_served == T1 + assert doc.revisions == (Revision("", (3,)),) + assert len(out) == 6 + + +def test_a_key_only_report_of_a_served_item_reads_reported_beside_its_revisions() -> None: + [item] = reliance([_served("k", [(H1, V1), (H2, V2)], at=T1)], [Reported("k")]) + + assert item.state == "reported" + assert item.revisions == (Revision(H2, (V2,)), Revision(H1, (V1,))) + assert item.last_served == T1 + + +def test_a_zero_version_or_an_empty_hash_never_matches_a_report() -> None: + # The record holds the item with no revision; the report names none either. + [unrevised] = reliance([_served("k", [("", 0)])], [Reported("k", version=0, sha256="")]) + assert unrevised.state == "reported" + # A hash recorded with no version is not matched by a zero version. + [hashed] = reliance([_served("k", [(H1, 0)])], [Reported("k", version=0)]) + assert hashed.state == "reported" + # A version recorded with no hash is not matched by an empty hash. + [versioned] = reliance([_served("k", [("", V1)])], [Reported("k", sha256="")]) + assert versioned.state == "reported" + + +def test_versions_under_one_hash_are_one_revision() -> None: + # One content read as the row, as its search document and by hash alone. + assert revisions_of([(H1, V2), (H1, V1), (H1, 0), (H1, V2)]) == (Revision(H1, (V1, V2)),) + + +def test_a_hashless_receipt_joins_the_revision_that_lists_its_version() -> None: + # A leg that reads no hash held the stored row another read hashed. + assert revisions_of([(H1, V1), ("", V1)]) == (Revision(H1, (V1,)),) + # A version no hashed revision lists is a revision of its own, highest version first. + assert revisions_of([(H1, V1), ("", V2)]) == (Revision("", (V2,)), Revision(H1, (V1,))) + + +def test_a_hash_with_no_version_is_a_revision_with_no_versions() -> None: + # Two contents served by hash alone are two revisions, listed after a versioned one. + assert revisions_of([(H2, 0), (H1, 0), ("", V1)]) == ( + Revision("", (V1,)), + Revision(H1, ()), + Revision(H2, ()), + ) + + +def test_a_served_item_with_no_version_or_hash_lists_no_revision_and_keeps_its_time() -> None: + assert revisions_of([("", 0)]) == () + [item] = reliance([_served("k", [("", 0)], at=T1)], []) + assert item.state == "returned" and item.revisions == () and item.last_served == T1 + + +def test_every_reported_key_is_an_item_and_reported_items_lead() -> None: + served = [_served("s1", [(H1, V1)]), _served("r2", [(H1, V1)]), _served("s2", [(H1, V1)])] + reported = [Reported("r1"), Reported("r2"), Reported("r1", version=V1)] + + out = reliance(served, reported) + + # One item per reported key in the order reported, then the rest in the order given. + assert [(i.key, i.state) for i in out] == [ + ("r1", "not_recorded"), + ("r2", "reported"), + ("s1", "returned"), + ("s2", "returned"), + ] + + +def test_a_report_matches_a_memory_item_only() -> None: + out = reliance([_served("docs://guide", [("", 3)], kind=DOCUMENT)], [Reported("docs://guide")]) + + assert [(i.kind, i.key, i.state) for i in out] == [ + (MEMORY, "docs://guide", "not_recorded"), + (DOCUMENT, "docs://guide", "returned"), + ] + + +# ------------------------------------------------------- the handler and the read + + +@pytest.fixture +def env(): + from server.tasks.app import run as h + + fake = _FakeCH() + with patch.object(h, "get_client", return_value=fake): + yield fake, h + + +def _receipts(key: str, seen: list[tuple[str, int]], kind: str = MEMORY, at: datetime = T0) -> dict: + return {"kind": kind, "item_key": key, "last_served": at, "seen": seen} + + +def _reliance( + h: Any, run_id: str = "r1", org: str = "o", namespace: str = "n" +) -> RunRelianceOutput: + return asyncio.run( + h.handle_run_reliance(RunRelianceInput(org=org, namespace=namespace, run_id=run_id)) + ) + + +@pytest.mark.parametrize("run_id", ["zz", "-"]) +def test_an_unknown_run_reads_no_receipt(env, run_id: str) -> None: + fake, h = env + + out = _reliance(h, run_id) + + assert out.found is False and out.items == [] and out.truncated is False + assert [kind for kind, _, _ in fake.calls] == ["one"] + + +def test_the_receipt_read_binds_the_addressed_org_and_namespace_and_the_run_rows_id(env) -> None: + fake, h = env + fake.one.append(_run_row(org="o", namespace="n", run_id="r1", memories_used=["k1", "k2"])) + + out = _reliance(h, "r1", org="o", namespace="n") + + assert out.found is True and [i.state for i in out.items] == ["not_recorded", "not_recorded"] + (_, run_sql, run_params), (kind, sql, params) = fake.calls + assert "FROM loom.agent_runs FINAL" in run_sql + assert run_params == {"org": "o", "ns": "n", "rid": "r1"} + assert kind == "all" and "FROM loom.read_receipts" in sql and "FINAL" not in sql + assert "org = {org:String} AND namespace = {ns:String} AND run_id = {rid:String}" in sql + assert params == { + "org": "o", + "ns": "n", + "rid": "r1", + "reported": ["k1", "k2"], + "memory": MEMORY, + "pairs": runs_store.RECEIPT_PAIRS + 1, + "lim": runs_store.DERIVED_LIMIT + 1, + } + + +def test_the_statement_selects_no_reader_column_and_the_answer_has_no_hash_or_reader_field( + env, +) -> None: + fake, h = env + fake.one.append(_run_row(memories_used=["k1"])) + fake.all.append([_receipts("k1", [(H1, V1)]), _receipts("k2", [(H2, 0)])]) + + out = _reliance(h) + + sql = fake.calls[-1][1] + for column in ("actor", "token_id", "agent", "user_id", "session_id", "request_id"): + assert column not in sql, column + assert "operation" not in sql + text = out.model_dump_json() + assert H1 not in text and H2 not in text + readers = {"actor", "token_id", "agent", "user_id", "session_id", "request_id", "operation"} + hashes = {"sha256", "content_sha256", "hash"} + for model in (RunRelianceOutput, *_nested_models(RunRelianceOutput)): + assert not (set(model.model_fields) & (readers | hashes)), model.__name__ + # The hash still tells two contents apart: each is one revision. + assert [len(i.revisions) for i in out.items] == [1, 1] + assert out.items[1].revisions[0].versions == [] + + +def _nested_models(model: Any) -> list[Any]: + from pydantic import BaseModel + + found: list[Any] = [] + for info in model.model_fields.values(): + for arg in getattr(info.annotation, "__args__", ()): + if isinstance(arg, type) and issubclass(arg, BaseModel): + found += [arg, *_nested_models(arg)] + return found + + +def test_a_cut_answer_says_so_and_keeps_every_reported_item(env) -> None: + fake, h = env + # The statement orders a reported item first and asks for one row more than it keeps. + rows = [_receipts("reported", [(H1, V1)])] + [ + _receipts(f"k{i:03d}", [(H1, V1)]) for i in range(runs_store.DERIVED_LIMIT) + ] + fake.one.append(_run_row(memories_used=["reported", "unrecorded"])) + fake.all.append(rows) + + out = _reliance(h) + + assert out.truncated is True + assert [(i.key, i.state) for i in out.items[:2]] == [ + ("reported", "reported"), + ("unrecorded", "not_recorded"), + ] + recorded = [i for i in out.items if i.state != "not_recorded"] + assert len(recorded) == runs_store.DERIVED_LIMIT + assert rows[-1]["item_key"] not in {i.key for i in out.items} + + +def test_a_cut_answer_keeps_the_first_pairs_of_an_item(env) -> None: + fake, h = env + # Highest version first, as the statement sorts them; one pair more than is kept. + pairs = [("", V1 + n) for n in range(runs_store.RECEIPT_PAIRS, -1, -1)] + fake.one.append(_run_row()) + fake.all.append([_receipts("k", pairs), _receipts("other", [(H1, V1)])]) + + out = _reliance(h) + + assert out.truncated is True + listed = [int(r.versions[0]) for r in out.items[0].revisions] + assert listed == [V1 + n for n in range(runs_store.RECEIPT_PAIRS, 0, -1)] + + +def test_an_answer_within_both_caps_is_not_cut(env) -> None: + fake, h = env + pairs = [("", V1 + n) for n in range(runs_store.RECEIPT_PAIRS)] + fake.one.append(_run_row()) + fake.all.append([_receipts(f"k{i:03d}", pairs) for i in range(runs_store.DERIVED_LIMIT)]) + + out = _reliance(h) + + assert out.truncated is False and len(out.items) == runs_store.DERIVED_LIMIT + + +def test_versions_are_decimal_strings(env) -> None: + fake, h = env + fake.one.append(_run_row()) + fake.all.append( + [ + _receipts("k", [(H1, V2), (H1, V1)], at=datetime(2026, 9, 11, 12, 0, 5)), + _receipts("docs://guide", [("", 3)], kind=DOCUMENT), + ] + ) + + out = _reliance(h) + + memory, document = out.items + # A memory version is above 2^53: a JSON number would lose its last digits. + assert V1 > 2**53 + assert memory.revisions[0].versions == [str(V1), str(V2)] + assert memory.last_served_at == "2026-09-11T12:00:05.000Z" + assert (document.kind, document.key) == (DOCUMENT, "docs://guide") + assert document.revisions[0].versions == ["3"] + + +def test_a_failed_receipt_read_fails_the_op(env) -> None: + fake, h = env + fake.one.append(_run_row(memories_used=["k1"])) + + async def failing(sql, params=None): + raise RuntimeError("read deadline") + + fake.query_all = failing + + # No partial answer: a failed read never prints a report as having no record. + with pytest.raises(RuntimeError, match="read deadline"): + _reliance(h) + + +def test_a_run_closed_again_with_no_report_lists_no_reported_item(env) -> None: + fake, h = env + # The run's last close named no memory, so the row holds no report. + fake.one.append(_run_row(status="completed", memories_used=[])) + fake.all.append([_receipts("k1", [(H1, V1)])]) + + out = _reliance(h) + + assert [(i.key, i.state) for i in out.items] == [("k1", "returned")] + assert fake.calls[-1][2]["reported"] == [] + + +# ------------------------------------------------------------------ the contract + +_STATES = ("returned", "reported", "reported_and_served", "not_recorded") +_DOMAIN = "server/tasks/domain/reliance.py" + + +def test_only_the_domain_module_spells_a_state() -> None: + """Every surface takes a state from the function: no other module of the server or + of the Python SDK's run client compares against one or builds one.""" + from typing import get_args + + from server.tasks.domain.reliance import RelianceState + + assert get_args(RelianceState) == _STATES + # The two names no other code has a reason to write as a whole string. + marks = {"reported_and_served", "not_recorded"} + spelled: set[str] = set() + for path in [*sorted((ROOT / "server").rglob("*.py")), ROOT / "sdk/python/loom/run.py"]: + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if isinstance(node, ast.Constant) and node.value in marks: + spelled.add(path.relative_to(ROOT).as_posix()) + assert spelled == {_DOMAIN} + + +def test_the_op_is_viewer_read_only_experimental_and_unlisted() -> None: + from server.identity.domain.read_scope import NARROW_SAFE_OPS, SCOPED_OPS + from server.operations.base import Role + from server.operations.registry import OPERATIONS_BY_NAME + from server.operations.toolsets import _MCP_HIDDEN_OPS, listed_under_all + + op = OPERATIONS_BY_NAME["run.reliance"] + assert op.required_role == Role.VIEWER and op.read_only and op.idempotent and not op.audit + assert op.maturity == "experimental" + # Callable by name through `loom_op`, in no listing. + assert not listed_under_all(op) and op.name not in _MCP_HIDDEN_OPS + # A run's receipts name rows other users wrote: a narrowed token is refused. + assert op.name not in SCOPED_OPS and op.name not in NARROW_SAFE_OPS + + +def test_the_reference_row_of_items_names_each_state() -> None: + page = (ROOT / "docs/reference/operations/run.md").read_text(encoding="utf-8") + section = page.split("## `run.reliance`", 1)[1].split("\n## ", 1)[0] + [row] = [ln for ln in section.splitlines() if ln.startswith("| `items` |")] + for state in _STATES: + assert f"`{state}`" in row, state diff --git a/tests/unit/test_sdk_run_reliance.py b/tests/unit/test_sdk_run_reliance.py new file mode 100644 index 00000000000..5b6a4864e03 --- /dev/null +++ b/tests/unit/test_sdk_run_reliance.py @@ -0,0 +1,28 @@ +"""`Agent.run.reliance` posts the run to `run.reliance` under the agent's org and +namespace and returns the answer as the server sent it.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from loom import Agent + + +def test_reliance_posts_the_run_to_its_op() -> None: + agent = Agent(org="o", namespace="n", agent="a", api_key="k", base_url="http://x") + sent: list[tuple[str, dict[str, Any]]] = [] + answer = {"found": True, "items": [], "truncated": False} + + async def fake_post(op_path, payload, idempotency_key=None, *, timeout_s=None): + sent.append((op_path, payload)) + return answer + + agent.transport.post = fake_post # type: ignore[method-assign] + try: + out = asyncio.run(agent.run.reliance("r1")) + finally: + asyncio.run(agent.close()) + + assert sent == [("/v1/run.reliance", {"org": "o", "namespace": "n", "run_id": "r1"})] + assert out is answer From b5c62668b170eecce709675fadd88f7c84c27534 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 19:26:32 +0000 Subject: [PATCH 09/18] A hash one read left out of a receipt stays out, and a whole body's receipt has a test over the wire A redacted or high-sensitivity row's note marks its hash as withheld, and no other note of that version adds it: a row redacted between a search's leg and its body read keeps its version, so the leg's hash named the removed text. The mark stays in the notes and is never stored. A row whose stored hash is set is noted without encoding its value; the value is hashed only where the column is unset. The design page says which reads hash the value they hold, what a hit served its source passage records, and that a governed definition of a later page keeps its hash. Tests: the keep-reading erasure test runs the erasure again where the first run ends with loom.read_receipts as its only residue, which the page documents, and reads the receipts step from the run that completed (a run that failed on residue lists no steps). The cleanup wait of the file-lookup test accepts the answer a second clear gets. New unit cases cover a withheld hash in both orders, a governed hit, a body no read returned, a shared copy that reads as high, a source passage and a later page's hits; new integration cases cover a whole body after a touch and a promoted row's shared copy. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 20 ++- server/memory/api/models_search.py | 6 +- server/memory/app/read_receipts.py | 25 ++- server/memory/domain/read_receipts.py | 24 ++- server/memory/domain/trust.py | 8 +- tests/integration/test_read_receipts.py | 100 ++++++++++-- tests/unit/test_read_receipts.py | 209 +++++++++++++++++++++--- tests/unit/test_term_leg.py | 23 +++ 8 files changed, 353 insertions(+), 62 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 8e23c3c7be7..21df350b7ca 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -86,6 +86,9 @@ session, and one op can read a row through more than one table. expanded to its whole body (`bodies`) records the body row read for it, which for a shared row is its copy in `loom.shared`, and a governed definition records the namespace's shared copy that the term leg served, never another row under the same key. +- **A hit served its source passage** (`bodies="source"`) is still its fact row: the + receipt names that row's revision as the search held it. The passage is a row of + `loom.memory_evidence`, which has no revision and gets no receipt. ### The version and the hash @@ -127,8 +130,18 @@ The hash is left empty, and the version still recorded, for: `anchor_first` and `recent_first` tiers read it; the other legs record the version only); - a hit of a later page of a paged search: the page was kept with each hit's version and - without its hash; -- a row whose stored hash is unset and whose value the read did not hold whole. + without its hash (a governed definition is read again for that page and keeps its + hash); +- a row whose stored hash is unset, where the read selected the row's columns and not + the row: a search leg, the stack's reads and a file lookup record the stored column + only. A read that holds the row whole (a key lookup, a whole body, a tier row, a + pack's recall, a matched procedure) hashes the value it holds, unless that value was + cut. + +A hash that one read of an op left out for the first two reasons stays out when another +read of the same version held it. A row redacted between a search's legs and its body +read keeps its version: the leg read the removed text's hash, and the answer carries the +redacted row. Under the Postgres authority a key lookup, a whole body, a matched procedure and `knowledge.get` serve the head Postgres holds, and the receipt names that head without @@ -310,7 +323,8 @@ ORDER BY first_read ## Cost -- **On the request's path**, a note is a dictionary write, and the reads that note a +- **On the request's path**, a note is a dictionary write (a row whose stored hash is + unset is first hashed from the value the read holds), and the reads that note a revision select its columns from the rows they already read: `content_sha256` in the main fact leg; `version`, `content_sha256` and `redacted_at` in the stack's pinned and recent reads; `version` and `redacted_at` in the file read; `version` in the diff --git a/server/memory/api/models_search.py b/server/memory/api/models_search.py index 3d7bbb5b926..e65e421875a 100644 --- a/server/memory/api/models_search.py +++ b/server/memory/api/models_search.py @@ -560,7 +560,11 @@ def _omit_unrequested(self, handler: SerializerFunctionWrapHandler) -> dict[str, _row_identity: tuple[str, str, str] | None = None # Private, what `pg_validation` checks. The set chunk whose passage the hit shows. _row_chunk: ChunkRef | None = None - # The stored version when the wire's is 0. + # Private: the version of the stored row the hit's text came from, where that is not + # the row `version` names: a tier row (whose wire version is 0), a governed + # definition's shared copy, a whole body read after the search. A read receipt records + # it before `version`. `pg_validation` checks the search document `version` names and + # reads this one only where the wire's is 0. _row_version: int = 0 # A chunk made into its row's hit shows the chunk's type, not the row's. _chunk_typed: bool = False diff --git a/server/memory/app/read_receipts.py b/server/memory/app/read_receipts.py index f3f9068928d..8cb8b5112b2 100644 --- a/server/memory/app/read_receipts.py +++ b/server/memory/app/read_receipts.py @@ -127,8 +127,12 @@ def note_memory( text's).""" notes = _open_notes() if notes is not None and namespace and key: - blank = high or redacted or not is_content_hash(sha256) - add_note(notes, MEMORY, namespace, key, Noted(int(version or 0), "" if blank else sha256)) + noted = Noted( + int(version or 0), + sha256 if is_content_hash(sha256) else "", + withheld=high or redacted, + ) + add_note(notes, MEMORY, namespace, key, noted) @_never_fails @@ -163,18 +167,13 @@ def note_selected(namespace: str, rows: Iterable[Mapping[str, Any]]) -> None: continue sha = row.get("content_sha256") text = sha.decode("ascii", "replace") if isinstance(sha, bytes) else str(sha or "") - blank = ( - row.get("redacted_at") is not None - or str(row.get("sensitivity") or "") == "high" - or not is_content_hash(text) - ) - add_note( - notes, - MEMORY, - str(row.get("namespace") or namespace), - key, - Noted(int(row.get("version") or 0), "" if blank else text), + noted = Noted( + int(row.get("version") or 0), + text if is_content_hash(text) else "", + withheld=row.get("redacted_at") is not None + or str(row.get("sensitivity") or "") == "high", ) + add_note(notes, MEMORY, str(row.get("namespace") or namespace), key, noted) @_never_fails diff --git a/server/memory/domain/read_receipts.py b/server/memory/domain/read_receipts.py index 498f05952e8..9f7d9cf5890 100644 --- a/server/memory/domain/read_receipts.py +++ b/server/memory/domain/read_receipts.py @@ -29,11 +29,15 @@ class Item(NamedTuple): class Noted(NamedTuple): """The revision a read held: a memory row's version and content hash, or a document's - revision and stored version. An empty hash and a zero version read as not recorded.""" + revision and stored version. An empty hash and a zero version read as not recorded. + `withheld` marks a hash the read left out on purpose (a redacted or high-sensitivity + row): no other note of that version adds it. The mark stays in the notes and is never + stored.""" version: int = 0 sha256: str = "" doc_version: int = 0 + withheld: bool = False # The revisions noted for each (kind, namespace, key), by version: one key can hold a row @@ -49,17 +53,18 @@ class Noted(NamedTuple): def add_note(notes: Notes, kind: str, namespace: str, key: str, noted: Noted) -> None: """Keep `noted` for the item. A second note of the same version adds what the first - lacked: one leg reads a row's hash and another only its version.""" + lacked: one leg reads a row's hash and another only its version. A hash either read + withheld stays out: the row was redacted or labelled between the two reads.""" held = notes.setdefault((kind, namespace, key), {}) earlier = held.get(noted.version) - if earlier is None: - held[noted.version] = noted - else: - held[noted.version] = Noted( + if earlier is not None: + noted = Noted( noted.version, earlier.sha256 or noted.sha256, _agreed(earlier.doc_version, noted.doc_version), + earlier.withheld or noted.withheld, ) + held[noted.version] = noted._replace(sha256="") if noted.withheld else noted def _agreed(earlier: int, later: int) -> int: @@ -70,8 +75,9 @@ def _agreed(earlier: int, later: int) -> int: def _stored(noted: Noted) -> Noted: - """`noted` as a receipt stores it: a stored version the notes disagree on is 0.""" - return noted if noted.doc_version >= 0 else noted._replace(doc_version=0) + """`noted` as a receipt stores it: a stored version the notes disagree on is 0, and + the mark of a withheld hash is dropped.""" + return noted._replace(doc_version=max(noted.doc_version, 0), withheld=False) def revision_of(item: Item, notes: Notes) -> Noted | None: @@ -90,7 +96,7 @@ def revision_of(item: Item, notes: Notes) -> Noted | None: if not rows: return NOT_RECORDED if held else None if len(rows) == 1: - return rows[0] + return _stored(rows[0]) hashes = {noted.sha256 for noted in rows} return Noted(0, hashes.pop()) if len(hashes) == 1 else NOT_RECORDED diff --git a/server/memory/domain/trust.py b/server/memory/domain/trust.py index 09d24c741aa..c786c2980e6 100644 --- a/server/memory/domain/trust.py +++ b/server/memory/domain/trust.py @@ -120,11 +120,13 @@ def row_verification(r: Mapping[str, Any]) -> VerificationState: def row_content_sha256(row: Any) -> str: """A MemoryRow's live hash (`live_sha256`); its `value` is decoded, so it is re-encoded - to hash a row whose column is unset.""" + to hash a row whose column is unset, and only such a row.""" + stored = getattr(row, "content_sha256", None) + if hash_is_set(hash_text(stored)): + return live_sha256(stored, None) value = getattr(row, "value", None) whole = value is not None and not getattr(row, "value_truncated", False) - value_json = json.dumps(value, default=str) if whole else None - return live_sha256(getattr(row, "content_sha256", None), value_json) + return live_sha256(stored, json.dumps(value, default=str) if whole else None) def live_sha256(stored: str | bytes | None, value_json: str | None) -> str: diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 3a03122ab4c..76cb5e20987 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -255,16 +255,14 @@ async def test_a_file_lookup_records_the_callers_row_of_another_namespace( owner = mint_test_token(org=ORG, namespaces=[home, records], roles=["writer"], subject="w") operator = mint_test_token(org="*", roles=["platform_admin"], subject="rr-operator") - async def default_scope(**body: Any) -> bool: - """Set or clear the scope a read with no named scope takes (deployment-wide); - whether the server took it.""" + async def default_scope(**body: Any) -> httpx.Response: + """Set or clear the scope a read with no named scope takes (deployment-wide).""" async with httpx.AsyncClient(timeout=30.0) as http: - r = await http.post( + return await http.post( f"{control_plane_url}/v1/admin/settings.set", json={"name": "memory_search_default_namespace_scope", **body}, headers={"Authorization": f"Bearer {operator}"}, ) - return r.status_code == 200 async def printed(a: Any) -> bool: out = await _read(a, "memory.for_file", run, path=path, tags=[repo]) @@ -272,8 +270,11 @@ async def printed(a: Any) -> bool: async def shipped(a: Any) -> bool: """Clear the override, again when a clear was refused, and say whether no lookup - prints the row any more: each web process answers some of them.""" - if not await default_scope(clear=True): + prints the row any more: each web process answers some of them, and takes the + cleared override at its next refresh.""" + cleared = await default_scope(clear=True) + # After a clear that took, the next one answers that no override is left. + if cleared.status_code != 200 and "no override to reset" not in cleared.text: return False return not any([await printed(a) for _ in range(_WEB_PROCESS_LOOKUPS)]) @@ -289,7 +290,7 @@ async def shipped(a: Any) -> bool: files=[path], tags=[repo], ) - assert await default_scope(value="all_mine") + assert (await default_scope(value="all_mine")).status_code == 200 try: await eventually( lambda: printed(a), @@ -425,6 +426,73 @@ async def served() -> str: assert (later["version"], later["content_sha256"]) == (second[0], second_hash) +async def _served_whole(reader: Any, key: str, **body: Any) -> tuple[str, dict[str, Any]]: + """A search by `reader` that served `key` its whole body: its request id and the hit.""" + + async def served() -> tuple[str, dict[str, Any]] | None: + rid = _request_id("body") + out = await _read(reader, "memory.search", request_id=rid, bodies="unit", **body) + hits = [h for h in out["results"] if h["memory_key"] == key] + return (rid, hits[0]) if hits and not hits[0].get("body_truncated") else None + + return await eventually(served, description=f"a search serves {key} whole") + + +async def test_a_whole_body_names_the_row_it_was_read_from( + control_plane_url: str, ch_client: Any +) -> None: + """`bodies="unit"` reads a hit's row after the legs, and the answer carries that + read's text: the receipt names the row as that read held it. A row touched since it + was indexed is past the version its search document holds.""" + from loom import Agent + + ns = _ns("body") + async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: + await a.memory.set("backup_window", FIRST, memory_type="semantic") + written = await _stored(ch_client, ns, "backup_window") + await _read(a, "memory.touch", memory_key="backup_window", ttl_seconds=86_400) + + async def touched() -> tuple[int, str] | None: + now = await _stored(ch_client, ns, "backup_window") + return now if now[0] > written[0] else None + + stored = await eventually(touched, description="the touch writes a newer row") + rid, hit = await _served_whole(a, "backup_window", query=QUERY) + + assert FIRST in hit["content_excerpt"] + assert hit["version"] < stored[0] # the search document is the row as it was indexed + [receipt] = await _landed(ch_client, ns, request_id=rid, item_key="backup_window") + assert (receipt["version"], receipt["content_sha256"]) == stored + + +REVENUE_NOTE = "The yearly subscription revenue target is ten million." + + +async def test_a_promoted_rows_whole_body_names_its_shared_copy( + control_plane_url: str, ch_client: Any, admin: Any +) -> None: + """Under shared scope a promoted row is served from its copy in `loom.shared`, which + stores no hash: the receipt names the copy's version and holds the hash of the value + the copy carries, which the row it was promoted from stores.""" + from loom import Agent + + ns = _ns("copy") + row = {"namespace": ns, "agent": "-", "memory_key": "revenue-note"} + async with Agent(org=ORG, namespace=ns, agent="bot", base_url=control_plane_url) as bot: + await _read(admin, "memory.set", **row, value=REVENUE_NOTE, memory_type="semantic") + await _read(admin, "memory.promote", **row) + rid, hit = await _served_whole( + bot, "revenue-note", query="yearly subscription revenue", scope="shared", top_k=5 + ) + + assert hit["content_excerpt"] == REVENUE_NOTE + copy = await _stored(ch_client, ns, "revenue-note", table="loom.shared") + source = await _stored(ch_client, ns, "revenue-note", "-") + assert copy[0] != source[0] + [receipt] = await _landed(ch_client, ns, request_id=rid, item_key="revenue-note") + assert (receipt["version"], receipt["content_sha256"]) == (copy[0], source[1]) + + async def test_a_receipt_names_the_run_its_requests_exposure_row_names( control_plane_url: str, ch_client: Any ) -> None: @@ -674,13 +742,21 @@ async def both_kinds(user: str = user) -> list[dict[str, Any]]: ) +def _receipts_deleted(result: dict[str, Any]) -> int: + """How many receipts a completed erasure's last run deleted.""" + steps = {s["step"]: s for s in result["steps"]} + return int(steps["read_receipts.delete"]["rows_affected"]) + + @pytest.mark.slow async def test_a_user_who_keeps_reading_is_still_erased( control_plane_url: str, ch_client: Any, admin: Any ) -> None: """Each read the user makes while the saga runs writes a receipt behind its step. The census counts the reads stamped up to the second the erasure was recorded in, so the - erasure completes and the later receipts stay.""" + erasure completes and the later receipts stay. A read stamped in that second whose + receipt lands behind the step is counted once: the erasure then names the table as + its only residue and completes when it is run again.""" from loom import Agent ns = _ns("busy") @@ -707,12 +783,14 @@ async def keep_reading() -> int: finally: erased.set() reads = await reader + if result["status"] != "completed": # a failed run lists its residue and no steps + assert set(result["residue"]) == {"loom.read_receipts"}, result + result = await admin.erasure.request_user_id(user, requester="ops@example.com") await _read(a, "knowledge.get", request_id=after, source_uri=uri, user_id=user) assert reads > 0 assert (result["status"], result["residue_count"]) == ("completed", 0) - steps = {s["step"]: s for s in result["steps"]} - assert steps["read_receipts.delete"]["rows_affected"] >= 1 + assert _receipts_deleted(result) >= 1 # the read made before the erasure is gone; one made after it is the user's new activity [kept] = await _landed(ch_client, ns, request_id=after) assert kept["user_id"] == user diff --git a/tests/unit/test_read_receipts.py b/tests/unit/test_read_receipts.py index 794b5bf417d..21850200527 100644 --- a/tests/unit/test_read_receipts.py +++ b/tests/unit/test_read_receipts.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json import re from collections.abc import Callable, Iterator from datetime import UTC, datetime @@ -105,6 +106,28 @@ def test_a_second_note_of_a_version_adds_what_the_first_lacked() -> None: assert notes == {(MEMORY, "n", "k"): {3: Noted(3, SHA)}} +@pytest.mark.parametrize("withheld_first", [False, True]) +def test_a_hash_one_note_withheld_is_not_added_by_another(withheld_first: bool) -> None: + """A row redacted or labelled between two reads of one version: the read that found + it so leaves the hash out, and the other read's hash is not recorded for it.""" + held, withheld = Noted(3, SHA), Noted(3, withheld=True) + notes = _notes( + *( + (MEMORY, "n", "k", noted) + for noted in ([withheld, held] if withheld_first else [held, withheld]) + ), + (MEMORY, "n", "k", Noted(3, OTHER_SHA)), # nor a later read's + ) + # the receipt holds the version and no hash, and nothing of the mark + assert revision_of(Item(MEMORY, "n", "k", 3), notes) == Noted(3) + assert revision_of(Item(MEMORY, "n", "k"), notes) == Noted(3) + assert every_noted(notes) == [(Item(MEMORY, "n", "k", 3), Noted(3))] + # a hash passed with the mark is dropped too + assert _notes((MEMORY, "n", "k", Noted(3, SHA, withheld=True))) == { + (MEMORY, "n", "k"): {3: Noted(3, withheld=True)} + } + + def test_two_stored_versions_of_one_document_revision_are_not_recorded() -> None: notes: Notes = {} chunk = Item(DOCUMENT, "n", "doc", 2, 0) @@ -1060,6 +1083,24 @@ def note() -> None: ] +def test_a_row_with_a_stored_hash_is_not_encoded_to_note_it() -> None: + """A note runs on the read's path: only a row whose stored hash is unset has its + value encoded, to hash it.""" + from server.memory.domain.trust import row_content_sha256, sha256_value_json + + class Value: + encoded = 0 + + def __str__(self) -> str: + Value.encoded += 1 + return "v" + + assert row_content_sha256(_row(value=Value())) == SHA + assert Value.encoded == 0 + assert row_content_sha256(_row(value=Value(), content_sha256="")) == sha256_value_json('"v"') + assert Value.encoded == 1 + + def test_selected_rows_are_noted_as_the_statement_read_them( written: list[list[dict[str, Any]]], ) -> None: @@ -1197,40 +1238,72 @@ def note() -> None: assert "_memory_hits" not in out.model_dump() -def test_a_whole_body_is_receipted_at_the_row_or_the_shared_copy_it_was_read_from( - written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +def _serve_whole_bodies( + monkeypatch: pytest.MonkeyPatch, + hits: list[Any], + leg_notes: dict[str, tuple[int, str]], + *, + rows: dict[str, Any] | None = None, + copies: dict[str, tuple[str, int]] | None = None, ) -> None: - """A search that serves whole bodies reads each after its legs: a row of loom.memory - under the hit's identity, a shared row from its copy in loom.shared. The receipt names - the revision that read returned; a hit the budget cut keeps its leg's.""" + """Answer a search that serves whole bodies with `hits`. Its legs noted `leg_notes` + (key: version, hash); the body read of loom.memory returns `rows` and the one of + loom.shared returns `copies`, each by key.""" import server.memory.store as memory_repo from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput from server.memory.app.search import payload - from server.memory.domain.trust import live_sha256 from server.memory.store import shared as shared_repo - copy, long_copy = '"the promoted text"', '"' + "s" * 40_000 + '"' + async def read_rows(identity: Any, keys: list[str], **_kw: Any) -> list[Any]: + return [row for key, row in (rows or {}).items() if key in keys] - async def rows(identity: Any, keys: list[str], **_kw: Any) -> list[Any]: - return [_row(memory_key=key, value="the row's text", version=9) for key in keys] + async def read_copies(org: str, namespace: str, keys: list[str]) -> dict[str, tuple[str, int]]: + return {key: copy for key, copy in (copies or {}).items() if key in keys} - async def copies(org: str, namespace: str, keys: list[str]) -> dict[str, tuple[str, int]]: - return {"shared": (copy, 4), "cut": (long_copy, 6)} - - monkeypatch.setattr(memory_repo, "get_many_by_keys", rows) - monkeypatch.setattr(shared_repo, "shared_values", copies) - own, shared, cut = _hit("own", version=8), _hit("shared"), _hit("cut", version=5) - own._row_identity = ("a", "-", "-") - shared._row_identity = cut._row_identity = ("_shared", "-", "-") - input = MemorySearchInput(org="o", namespace="n", query="q", bodies="unit") + monkeypatch.setattr(memory_repo, "get_many_by_keys", read_rows) + monkeypatch.setattr(shared_repo, "shared_values", read_copies) async def handler(input: MemorySearchInput) -> MemorySearchOutput: - for key, version in (("own", 8), ("cut", 5)): # the legs: each search document - rr.note_memory("n", key, version=version, sha256=OTHER_SHA) - await payload._expand_unit_bodies([own, shared, cut], input) - return MemorySearchOutput(results=[own, shared, cut], embedding_model="e") + for key, (version, sha256) in leg_notes.items(): + rr.note_memory("n", key, version=version, sha256=sha256) + await payload._expand_unit_bodies(hits, input) + return MemorySearchOutput(results=hits, embedding_model="e") + input = MemorySearchInput(org="o", namespace="n", query="q", bodies="unit") _run(rr.records_receipts(rr.search_items)(handler), input) + + +def _own(key: str, **fields: Any) -> Any: + """A hit whose leg read its row's identity: a row of loom.memory an agent wrote.""" + hit = _hit(key, **fields) + hit._row_identity = ("a", "-", "-") + return hit + + +def _shared(key: str, **fields: Any) -> Any: + """A hit of a promoted row: its body is its copy in loom.shared.""" + hit = _hit(key, **fields) + hit._row_identity = ("_shared", "-", "-") + return hit + + +def test_a_whole_body_is_receipted_at_the_row_or_the_shared_copy_it_was_read_from( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +) -> None: + """A search that serves whole bodies reads each after its legs: a row of loom.memory + under the hit's identity, a shared row from its copy in loom.shared. The receipt names + the revision that read returned; a hit the budget cut keeps its leg's.""" + from server.memory.domain.trust import live_sha256 + + copy, long_copy = '"the promoted text"', '"' + "s" * 40_000 + '"' + own, shared, cut = _own("own", version=8), _shared("shared"), _shared("cut", version=5) + _serve_whole_bodies( + monkeypatch, + [own, shared, cut], + {"own": (8, OTHER_SHA), "cut": (5, OTHER_SHA)}, # the legs: each search document + rows={"own": _row(memory_key="own", value="the row's text", version=9)}, + copies={"shared": (copy, 4), "cut": (long_copy, 6)}, + ) assert (own.content_excerpt, shared.content_excerpt) == ("the row's text", "the promoted text") assert cut.body_truncated is True assert _receipts(written) == [ @@ -1240,6 +1313,98 @@ async def handler(input: MemorySearchInput) -> MemorySearchOutput: ] +def test_a_hit_no_body_read_served_keeps_the_revision_its_leg_noted( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +) -> None: + """The body step changes a receipt only where it serves a body it read: a governed + hit carries the copy the term leg read, a row the body read did not return keeps its + clip, and a shared copy whose text reads as high is not served.""" + governed = _hit("definition/arr", governed=True, version=9, row_version=12) + gone, secret = _own("gone", version=5), _shared("secret", version=3) + _serve_whole_bodies( + monkeypatch, + [governed, gone, secret], + {"definition/arr": (12, SHA), "gone": (5, SHA), "secret": (3, SHA)}, + copies={"secret": (json.dumps({"password": "hunter2xyz"}), 4)}, + ) + assert (governed.content_excerpt, gone.content_excerpt, secret.content_excerpt) == ("x",) * 3 + assert _receipts(written) == [ + _receipt(MEMORY, "n", "definition/arr", 12, SHA), # not its search document's 9 + _receipt(MEMORY, "n", "gone", 5, SHA), + _receipt(MEMORY, "n", "secret", 3, SHA), # not the copy's version 4 + ] + + +def test_a_row_redacted_before_its_body_read_is_receipted_without_the_hash_its_leg_noted( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +) -> None: + """A redaction between a search's legs and its body read keeps the row's version. The + leg noted the removed text's hash; the answer carries the redacted row.""" + hit = _own("own", version=8) + redacted = _row(memory_key="own", value="[redacted]", version=8, redacted_at=_REDACTED_AT) + _serve_whole_bodies(monkeypatch, [hit], {"own": (8, SHA)}, rows={"own": redacted}) + assert hit.content_excerpt == "[redacted]" + assert _receipts(written) == [_receipt(MEMORY, "n", "own", 8)] + + +class _Evidence: + """Answers the two reads of a source passage: a fact's links, then the passages.""" + + def __init__(self, links: dict[str, str], passages: dict[str, str]) -> None: + self.links, self.passages = links, passages + + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: + if "loom.memory_belief_sources" in sql: + return [ + {"namespace": "n", "memory_key": key, "evidence_id": eid} + for key, eid in self.links.items() + ] + return [{"eid": eid, "body": body} for eid, body in self.passages.items()] + + +def test_a_hit_served_its_source_passage_is_receipted_as_the_fact_row_it_is( + written: list[list[dict[str, Any]]], monkeypatch: pytest.MonkeyPatch +) -> None: + """`bodies="source"` puts the passage a fact was extracted from in the hit's text. + The hit is still that fact row: its receipt names the row's revision as the search + held it, and the passage, which has no revision, gets none.""" + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + from server.memory.app.search import payload + + eid = "11111111-1111-4111-8111-111111111111" + evidence = _Evidence({"fact": eid}, {eid: "the transcript turn the fact came from"}) + monkeypatch.setattr(payload, "get_client", lambda: evidence) + hit = _hit("fact", version=7) + + async def handler(input: MemorySearchInput) -> MemorySearchOutput: + rr.note_memory("n", "fact", version=7, sha256=SHA) # the fact leg + assert await payload._expand_source_bodies([hit], input) == (1, 0) + return MemorySearchOutput(results=[hit], embedding_model="e") + + input = MemorySearchInput(org="o", namespace="n", query="q", bodies="source") + _run(rr.records_receipts(rr.search_items)(handler), input) + assert hit.content_excerpt == "the transcript turn the fact came from" + assert _receipts(written) == [_receipt(MEMORY, "n", "fact", 7, SHA)] + + +def test_a_later_pages_hit_is_receipted_at_the_version_the_page_kept( + written: list[list[dict[str, Any]]], +) -> None: + """A page parked for a later request keeps each hit's version and no hash, and that + request runs no leg: its receipt names the version and leaves the hash out.""" + from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput + from server.memory.app import search_pages + + back = search_pages.unparked(search_pages._parked(_own("fact", version=7))) + assert back is not None + out = MemorySearchOutput(results=[back], embedding_model="e") + _run( + _op(lambda: None, out, rr.search_items), + MemorySearchInput(org="o", namespace="n", query="q"), + ) + assert _receipts(written) == [_receipt(MEMORY, "n", "fact", 7)] + + def test_a_document_search_receipts_each_chunk_at_its_revision( written: list[list[dict[str, Any]]], ) -> None: diff --git a/tests/unit/test_term_leg.py b/tests/unit/test_term_leg.py index e849879d114..7245d7961f2 100644 --- a/tests/unit/test_term_leg.py +++ b/tests/unit/test_term_leg.py @@ -95,6 +95,29 @@ async def test_a_governed_hit_carries_and_notes_the_shared_copy_it_serves( assert notes == {(MEMORY, "n", "definition/arr"): {41: stored}} +async def test_a_later_page_notes_the_copy_its_check_read(store: dict[str, Any]) -> None: + """A governed hit parked for a later page is served only while the copy governed now + holds its text: that page's receipt names the copy its check read, not the one the + first page did.""" + from server.memory.app import read_receipts + from server.memory.domain.read_receipts import MEMORY, Noted, Notes + from server.memory.domain.trust import live_sha256 + + row = {**_row("definition/arr", "ARR"), "version": 41} + store["rows"] = [row] + [parked] = (await term_leg._read("o", "n", "what is ARR", set(), None, "m")).hits + row["version"] = 43 # promoted again with the same text + notes: Notes = {} + token = read_receipts._notes.set(notes) + try: + [served] = await term_leg.refresh_parked("o", "n", "what is ARR", [parked], whole=False) + finally: + read_receipts._notes.reset(token) + assert served is parked and served._row_version == 43 + stored = Noted(43, live_sha256(None, row["value"])) + assert notes == {(MEMORY, "n", "definition/arr"): {43: stored}} + + async def test_a_query_naming_no_term_reads_no_source(store: dict[str, Any]) -> None: store["rows"] = [_row("definition/arr", "ARR")] assert await _keys("what did we ship") == ("complete", []) From 0b34236a245df9836717b24f4831de10a8138a65 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 20:25:31 +0000 Subject: [PATCH 10/18] A token's reads have a wire test, and the page names two more reads that get no receipt The design page names two more reads that get no receipt: a hit that is no stored memory row, and a memory.ask answer reused from an earlier one. A stored hash is read through hash_text where a statement's rows are noted, and a row whose hash is set returns the column's text without a second decode. A comment says why the fan-out of search.query hands its served hits to the handler inside the payload. Tests: a read made under a token and as no end user is filed under the token's subject and id, and a user erasure of that subject removes it while another subject's receipt stays. The keep-reading test waits for the last read's receipt before it runs the erasure a second time. The file-lookup test clears its override and waits out one refresh, as the receipts switch does. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/read-receipts.md | 6 ++ server/memory/app/loom_search/fanout.py | 3 +- server/memory/app/loom_search/handler.py | 2 +- server/memory/app/read_receipts.py | 5 +- server/memory/domain/trust.py | 5 +- tests/integration/test_read_receipts.py | 82 ++++++++++++++++-------- 6 files changed, 71 insertions(+), 32 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 21df350b7ca..cbc9e6c0f00 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -178,6 +178,12 @@ revision, `doc_version` is 0: not recorded. A document receipt has no hash. count, `memory.brief` nothing of them, a context pack cites namespace, URI and section, and a stack entry names the URI. The memory rows of the same answer get their receipts. `knowledge.search`, `knowledge.get` and `search.query` receipt documents. +- **A hit that is no stored memory row**: a summary, a record, an observation, a derived + or a computed row. It names no row of `loom.memory` at a version; the stored rows of + the same answer get their receipts. +- **A `memory.ask` answer reused from an earlier one** (`memory_ask_precedents`, off by + default). It returns the keys the earlier answer cited and no hits, and reads no row, + so nothing is noted. - **A `memory.get` of a `chunk:` key**, which serves a passage and its neighbours. - **Reads that list or inspect rather than recall**: `memory.list`, `memory.keys`, `memory.inspect`, exports, version history, `memory.related`, `memory.recall`, diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 08cea602e56..8c05efd281f 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -514,7 +514,8 @@ async def search_sections( # The key `search_sections` returns the search models of the served memory rows under. # It is no section of the answer: the op's handler takes it off the payload and keeps the -# models on the output (`SearchOutput._memory_hits`). +# models on the output (`SearchOutput._memory_hits`). The models ride in the payload, not +# beside it, so a function that stands in for the fan-out returns sections alone. SERVED_MEMORY_HITS = "_memory_hits" diff --git a/server/memory/app/loom_search/handler.py b/server/memory/app/loom_search/handler.py index 570d11e6589..20bf39ca900 100644 --- a/server/memory/app/loom_search/handler.py +++ b/server/memory/app/loom_search/handler.py @@ -101,7 +101,7 @@ async def handle_search(input: SearchInput) -> SearchOutput: ] ) _record_gap_miss(input, payload, repo_namespace or "") - served = payload.pop(SERVED_MEMORY_HITS, []) + served = payload.pop(SERVED_MEMORY_HITS, []) # none from a stand-in fan-out out = SearchOutput.model_validate(payload) out._memory_hits = served return out diff --git a/server/memory/app/read_receipts.py b/server/memory/app/read_receipts.py index 8cb8b5112b2..947c4e9d0ea 100644 --- a/server/memory/app/read_receipts.py +++ b/server/memory/app/read_receipts.py @@ -37,7 +37,7 @@ from server.core import instances, request_work from server.core.diagnostics import public_diagnostics -from server.core.hashing import as_valid_unicode +from server.core.hashing import as_valid_unicode, hash_text from server.core.naming import is_reserved_name, named from server.memory.app import after_write from server.memory.app.served_reads import reader @@ -165,8 +165,7 @@ def note_selected(namespace: str, rows: Iterable[Mapping[str, Any]]) -> None: key = str(row.get("memory_key") or "") if not key: continue - sha = row.get("content_sha256") - text = sha.decode("ascii", "replace") if isinstance(sha, bytes) else str(sha or "") + text = hash_text(row.get("content_sha256")) noted = Noted( int(row.get("version") or 0), text if is_content_hash(text) else "", diff --git a/server/memory/domain/trust.py b/server/memory/domain/trust.py index c786c2980e6..de7f163ad11 100644 --- a/server/memory/domain/trust.py +++ b/server/memory/domain/trust.py @@ -122,8 +122,9 @@ def row_content_sha256(row: Any) -> str: """A MemoryRow's live hash (`live_sha256`); its `value` is decoded, so it is re-encoded to hash a row whose column is unset, and only such a row.""" stored = getattr(row, "content_sha256", None) - if hash_is_set(hash_text(stored)): - return live_sha256(stored, None) + text = hash_text(stored) + if hash_is_set(text): + return text value = getattr(row, "value", None) whole = value is not None and not getattr(row, "value_truncated", False) return live_sha256(stored, json.dumps(value, default=str) if whole else None) diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 76cb5e20987..771b473ab4c 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -12,6 +12,8 @@ from __future__ import annotations import asyncio +import base64 +import json import os import sys import uuid @@ -34,8 +36,6 @@ ORG = unique_org("read-receipts") FIRST = "the nightly backup of the orders cluster runs at 02:00 UTC" SECOND = "the nightly backup of the orders cluster runs at 04:30 UTC" -# Each web process answers some of a run of calls; this many reach every one. -_WEB_PROCESS_LOOKUPS = 6 QUERY = "when does the nightly backup of the orders cluster run" _COLUMNS = ( @@ -268,16 +268,6 @@ async def printed(a: Any) -> bool: out = await _read(a, "memory.for_file", run, path=path, tags=[repo]) return [hit["namespace"] for hit in out["hits"]] == [records] - async def shipped(a: Any) -> bool: - """Clear the override, again when a clear was refused, and say whether no lookup - prints the row any more: each web process answers some of them, and takes the - cleared override at its next refresh.""" - cleared = await default_scope(clear=True) - # After a clear that took, the next one answers that no override is left. - if cleared.status_code != 200 and "no override to reset" not in cleared.text: - return False - return not any([await printed(a) for _ in range(_WEB_PROCESS_LOOKUPS)]) - async with Agent( org=ORG, namespace=home, agent="w", base_url=control_plane_url, api_key=owner ) as a: @@ -298,12 +288,9 @@ async def shipped(a: Any) -> bool: description="the file's block prints the caller's row of another namespace", ) finally: - await eventually( - lambda: shipped(a), - max_wait=30.0, - interval=0.5, - description="every server process serves the shipped scope again", - ) + cleared = await default_scope(clear=True) + assert cleared.status_code == 200, cleared.text + await overrides_adopted() # every process serves the shipped scope again stored = await _stored(ch_client, records, "backup_window") rows = await _landed(ch_client, records, run_id=run) @@ -742,6 +729,46 @@ async def both_kinds(user: str = user) -> list[dict[str, Any]]: ) +def _token_id(token: str) -> str: + """The id a minted token carries: its `jti` claim.""" + claims = token.split(".")[1] + return str(json.loads(base64.urlsafe_b64decode(claims + "=" * (-len(claims) % 4)))["jti"]) + + +@pytest.mark.slow +async def test_a_user_erasure_removes_the_reads_made_under_the_users_token( + control_plane_url: str, ch_client: Any, admin: Any, mint_test_token: Any +) -> None: + """A read made under a token and as no end user is filed under the token's subject + and id. Erasing that subject as a user removes it, and leaves another subject's.""" + from loom import Agent + + ns = _ns("token") + erased, kept = f"dana-{uuid.uuid4().hex[:6]}", f"erin-{uuid.uuid4().hex[:6]}" + read: dict[str, tuple[str, str]] = {} + for subject in (erased, kept): + token = mint_test_token(org=ORG, namespaces=[ns], roles=["writer"], subject=subject) + async with Agent( + org=ORG, namespace=ns, agent="w", base_url=control_plane_url, api_key=token + ) as a: + await a.memory.set(f"editor_{subject}", f"{subject} edits in a terminal") + rid = _request_id("token") + got = await _read(a, "memory.get", request_id=rid, memory_key=f"editor_{subject}") + assert got["found"] is True + read[subject] = (rid, _token_id(token)) + + for subject, (rid, token_id) in read.items(): + [receipt] = await _landed(ch_client, ns, request_id=rid) + reader = (receipt["actor"], receipt["token_id"], receipt["user_id"]) + assert reader == (subject, token_id, "-") + + result = await admin.erasure.request_user_id(erased, requester="ops@example.com") + assert result["status"] == "completed" + assert _receipts_deleted(result) >= 1 + assert _receipts(ch_client, ns, request_id=read[erased][0]) == [] + assert [r["actor"] for r in _receipts(ch_client, ns, request_id=read[kept][0])] == [kept] + + def _receipts_deleted(result: dict[str, Any]) -> int: """How many receipts a completed erasure's last run deleted.""" steps = {s["step"]: s for s in result["steps"]} @@ -769,26 +796,31 @@ async def test_a_user_who_keeps_reading_is_still_erased( await _landed(ch_client, ns, request_id=before) erased = asyncio.Event() - async def keep_reading() -> int: - reads = 0 + async def keep_reading() -> list[str]: + """Read until the erasure answers: the request id of each read, in order.""" + made: list[str] = [] while not erased.is_set(): - await _read(a, "knowledge.get", source_uri=uri, user_id=user) - reads += 1 + made.append(_request_id("busy")) + await _read(a, "knowledge.get", request_id=made[-1], source_uri=uri, user_id=user) await asyncio.sleep(0.05) - return reads + return made reader = asyncio.create_task(keep_reading()) try: result = await admin.erasure.request_user_id(user, requester="ops@example.com") finally: erased.set() - reads = await reader + made = await reader if result["status"] != "completed": # a failed run lists its residue and no steps assert set(result["residue"]) == {"loom.read_receipts"}, result + # The second run is recorded at a new second. The reads have stopped, and a + # process sends its receipts in the order of their reads: once the last one + # has landed, none is left to land behind the second run's step. + await _landed(ch_client, ns, request_id=made[-1]) result = await admin.erasure.request_user_id(user, requester="ops@example.com") await _read(a, "knowledge.get", request_id=after, source_uri=uri, user_id=user) - assert reads > 0 + assert made assert (result["status"], result["residue_count"]) == ("completed", 0) assert _receipts_deleted(result) >= 1 # the read made before the erasure is gone; one made after it is the user's new activity From 022419999b75e3d107d3f1e5f572a5d9d2ab9f3e Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 20:47:39 +0000 Subject: [PATCH 11/18] The dashboard's entry chunk fits its budget with the run detail's read list RunReliance is the third importer of useShowMore, so the build makes the hook a chunk of its own and the entry chunk's preload map gains its file name and the references to it: 58 characters, where the budget has 24 to spare, and `npm --prefix frontend run budget` fails. refreshDetail is in its own module, not in lib/format.ts, which loads with the shell. Only the lazily loaded Code view calls it, so it lands in that view's chunk and adds none: the entry chunk is 122,822 characters against 122,880, with 117 scripts in the build either way. The budget script and RunReliance are unchanged. The e2e fixture of run.reliance sits above the run.get comment, so that comment is on its function. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- frontend/e2e/fixtures.ts | 6 +++--- frontend/src/lib/format.test.ts | 9 --------- frontend/src/lib/format.ts | 8 -------- frontend/src/lib/refreshDetail.test.ts | 10 ++++++++++ frontend/src/lib/refreshDetail.ts | 8 ++++++++ frontend/src/views/Code.tsx | 3 ++- 6 files changed, 23 insertions(+), 21 deletions(-) create mode 100644 frontend/src/lib/refreshDetail.test.ts create mode 100644 frontend/src/lib/refreshDetail.ts diff --git a/frontend/e2e/fixtures.ts b/frontend/e2e/fixtures.ts index f6d87de1efe..1eca83c16cc 100644 --- a/frontend/e2e/fixtures.ts +++ b/frontend/e2e/fixtures.ts @@ -1448,9 +1448,6 @@ function runRowsFixture(n: number, namespace: string): Record[] })); } -/** `run.get` for one of `runs` (RunGetOutput in server/tasks/api/models_run.py): the - * row and what the server derives live — the keys recalled and written, the session's - * turns and cost, the budgets passed. An unknown id answers `found: false`. */ /** What a run read, one row of each state: a memory recalled and reported, a document only * recalled, a memory reported at a revision the run was served, and a report with no record. */ const RUN_RELIANCE_FIXTURE = { @@ -1495,6 +1492,9 @@ const RUN_RELIANCE_FIXTURE = { ], }; +/** `run.get` for one of `runs` (RunGetOutput in server/tasks/api/models_run.py): the + * row and what the server derives live — the keys recalled and written, the session's + * turns and cost, the budgets passed. An unknown id answers `found: false`. */ function runGetFixture(runs: Record[], runId: string): Record { const run = runs.find((r) => r.run_id === runId); if (!run) { diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.ts index 73635776237..44a53b4d88c 100644 --- a/frontend/src/lib/format.test.ts +++ b/frontend/src/lib/format.test.ts @@ -6,7 +6,6 @@ import { daysLeftToRestore, displaySubject, formatBytesShort, - refreshDetail, isServiceSubject, relativeTime, restoreText, @@ -135,14 +134,6 @@ describe("formatBytesShort", () => { }); }); -describe("refreshDetail", () => { - it("drops the fields a code.refresh caller left empty", () => { - expect(refreshDetail("agent=catchup expected_head=")).toBe("agent=catchup"); - expect(refreshDetail("agent=ci expected_head=4645c25c46fc")).toBe("agent=ci expected_head=4645c25c46fc"); - expect(refreshDetail("")).toBe(""); - }); -}); - // A day heading over the memories is a date, so it can be told apart from last week's: // "Today" and "Yesterday" carry theirs, and an earlier day is its date, never a weekday. describe("dayLabel", () => { diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 5be28ec9754..fefbb4e59c3 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -256,14 +256,6 @@ export function absoluteTime(time: string | null | undefined): string { return d ? fmt("abs", { dateStyle: "medium", timeStyle: "short" }).format(d) : (time ?? ""); } -/** A `code.refresh` caller line without the fields the caller left empty (`expected_head=`). */ -export function refreshDetail(detail: string): string { - return (detail || "") - .split(/\s+/) - .filter((part) => part && !part.endsWith("=")) - .join(" "); -} - /** What a card shows for a high row, which the list sends without its value. */ export const SENSITIVE_LABEL = "Sensitive: open it to read"; /** The same, where the view cannot open the row itself. */ diff --git a/frontend/src/lib/refreshDetail.test.ts b/frontend/src/lib/refreshDetail.test.ts new file mode 100644 index 00000000000..e98f9282803 --- /dev/null +++ b/frontend/src/lib/refreshDetail.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from "vitest"; +import { refreshDetail } from "./refreshDetail"; + +describe("refreshDetail", () => { + it("drops the fields a code.refresh caller left empty", () => { + expect(refreshDetail("agent=catchup expected_head=")).toBe("agent=catchup"); + expect(refreshDetail("agent=ci expected_head=4645c25c46fc")).toBe("agent=ci expected_head=4645c25c46fc"); + expect(refreshDetail("")).toBe(""); + }); +}); diff --git a/frontend/src/lib/refreshDetail.ts b/frontend/src/lib/refreshDetail.ts new file mode 100644 index 00000000000..6632cbdb4c6 --- /dev/null +++ b/frontend/src/lib/refreshDetail.ts @@ -0,0 +1,8 @@ +/** A `code.refresh` caller line without the fields the caller left empty (`expected_head=`). + * Its own module: only the Code view reads it, so the shell's chunk does not carry it. */ +export function refreshDetail(detail: string): string { + return (detail || "") + .split(/\s+/) + .filter((part) => part && !part.endsWith("=")) + .join(" "); +} diff --git a/frontend/src/views/Code.tsx b/frontend/src/views/Code.tsx index b577aab73da..96c0412c817 100644 --- a/frontend/src/views/Code.tsx +++ b/frontend/src/views/Code.tsx @@ -27,7 +27,8 @@ import { restrictedReason } from "../lib/namespaceUpdate"; import { useGrantRows } from "../lib/useGrantRows"; import { setViewParam, urlParam, useStore, useIdentity } from "../lib/state"; import { hasPlatformAdminClaim, holdsAdminGrant } from "../lib/role"; -import { fmtInt, relativeTime, listTime, parseChTime, refreshDetail } from "../lib/format"; +import { fmtInt, relativeTime, listTime, parseChTime } from "../lib/format"; +import { refreshDetail } from "../lib/refreshDetail"; import { humanizeError, errorLine } from "../lib/errorWords"; import { useAbortableEffect, useVisiblePoll } from "../lib/hooks"; import { EmptyState } from "../components/EmptyState"; From 4f73593f833a3377c2af93501f249351e30c86e6 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 20:47:46 +0000 Subject: [PATCH 12/18] run.reliance's receipt read runs under the caller-shaped ceilings, and its pages state what bounds it A run id on a read is client input, and the receipt statement groups every receipt that carries it before its LIMIT, so its cost is the caller's to shape: one id on 2 million receipts of distinct revisions costs a call about 600 MB. receipted_items runs inside caller_shaped("one run id for each run"): a read past the row, time or memory ceiling answers 422 with the way to narrow it, where a memory refusal of the statement is otherwise a 500 with no hint. The run row's point read stays outside. The statement is unchanged. The wire comment, the reference and the runs page give the per-item cap in its unit, (content hash, version) pairs. A version read with and without its hash is two pairs and a receipt that names no revision is one, so an item past its 32 pairs can list fewer than 32 versions, or all of them, with truncated true. The statement and the cap are unchanged. RunRelianceInput's first sentence names `run_id`: the loom_op catalogue row lists no identity key as an argument, so its purpose is where a caller over MCP learns what to send. The Go models' schema digest follows the docstring. Docs: - The runs page: a memory's versions are those of the stored row the read held (the memory row's, its search document's or a shared copy's), which memory.history does not all list; the Python SDK row names the reads that carry a run (header or body, in a run scope and with auto_run) and no op that writes no receipt; the answer's bounds are not the read's. - The read-receipts page: the measured cost of the read as a range with its conditions, where the filter test alone reaches the op's budget, budget.violated as the sign of it, and the ceilings and the read deadline. Tests: - The receipt read alone runs in the caller-shaped scope, and a cap inside it is a ValidationError with the hint. - The bound of run.complete's memories_used is at most DERIVED_LIMIT: a cut answer keeps every reported item only while that holds. - A version read both ways counts twice against the pair cap. - The cross-surface integration test holds a not_recorded item: the SDK and the CLI answer as HTTP, and MCP lists the same items and states without the empty fields its transport drops. - A narrowed token is checked with honours_read_scope, which also covers a group key, and three case names say what the cases check. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- docs/architecture/read-receipts.md | 19 +++- docs/features/runs.md | 42 +++++--- docs/reference/operations.md | 2 +- docs/reference/operations/run.md | 4 +- sdk/go/wire/models.gen.go | 2 +- sdk/python/loom/ops.py | 4 +- sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 2 +- server/tasks/api/models_run.py | 8 +- server/tasks/store/runs.py | 55 ++++++----- tests/integration/test_run_reliance.py | 27 +++-- tests/unit/test_run_reliance.py | 99 +++++++++++++++++-- 11 files changed, 199 insertions(+), 65 deletions(-) diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index 43aed464cee..fd5430a5a6f 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -334,7 +334,17 @@ gives the answer's states and limits. that exists, and an upper bound at its close would drop the reads a resumed session labels after the close. The read takes the `(org, namespace)` prefix of the key and then tests the bloom filter on every granule of the namespace, so its cost grows with - the receipts the namespace keeps, not with the deployment's. + the receipts the namespace keeps, not with the deployment's. The statement reads and + groups every receipt under the label before its `LIMIT`, so its cost also grows with + the receipts that carry the run's id. +- **What the read costs.** Measured on a local ClickHouse, warm, for one run of 20 items + with two threads: in a namespace of 4 million receipts the filter test takes 3 to 7 ms + and the statement 36 to 55 ms; in one of 16 million, 14 to 38 ms and 49 to 111 ms. At + that rate, 0.9 to 2.4 ms a million receipts, the filter test alone takes the op's + 300 ms budget at 125 to 340 million receipts in one namespace. A `budget.violated` + event for `run.reliance` is the sign that a namespace has reached that size. A run id + on 2 million receipts of distinct revisions makes one call use about 600 MB and take + over a second. - **No hash in the answer.** A receipt written before a row was redacted or labelled high-sensitivity keeps that read's hash for the receipt's lifetime, and the hash of a short secret names it as well as the value does. The op groups and matches on the hash @@ -342,7 +352,12 @@ gives the answer's states and limits. answered with no version. - **No reader in the answer.** The statement selects no reader column. - **A failed read fails the op.** A partial list would print "not recorded" for a - receipt that was not read. + receipt that was not read. A run id on a read is client input, so the receipt read is + the caller's to shape and runs under the caller-shaped ceilings + (`LOOM_CH_CALLER_SHAPED_*`): one that needs more rows, time or memory answers 422. One + past the read deadline (`LOOM_CH_TIMEOUT_READ_S`, + [statement classes](clickhouse.md#statement-classes-deadlines-and-traffic-classes)) + fails the op. ## Cost diff --git a/docs/features/runs.md b/docs/features/runs.md index e0380a41ecd..7645f6b6f3e 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -138,17 +138,33 @@ Each item has one state, true as of the read: An item's `revisions` are what the record holds, highest version first, and each one's `versions` are the stored versions under which the run was served one content. For a -memory they are the `version` of `memory.history`, as decimal text, and the dashboard -shows the time that version was written. For a document they are its revision number. A -`not_recorded` item has no revision: the answer never fills in the item's latest. +memory each is the version of the stored row the read held, as decimal text: the memory +row's, its search document's or a shared copy's, by the kind of read +([the version and the hash](../architecture/read-receipts.md#the-version-and-the-hash)). +`memory.history` lists versions of the memory row alone, so a version served by a search +hit can be absent from it. The dashboard shows the time that version encodes. For a +document each is its revision number. A `not_recorded` item has no revision: the answer +never fills in the item's latest. `run.get` answers a different question from other sources: its `recalled` and `recalled_keys` come from the search trace log and the keys a client sent at the close, this list from the receipts, so the two can differ. -The answer holds at most 500 recorded items and the 32 highest recorded versions of -each. Past either bound `truncated` is true; every reported item is kept, then the items -served most recently. +The answer holds at most 500 recorded items and the 32 highest recorded pairs of content +hash and version of each. A version read with and without its hash is two pairs, and a +receipt that names no revision is one, so an item past its 32 pairs can list fewer than +32 versions, or every version the record holds. Past either bound `truncated` is true; +every reported item is kept, then the items served most recently. + +Those bounds are on the answer, not on the read. The read's cost grows with the receipts +the namespace keeps and with the receipts that carry the run's id. An id that one +long-lived client sends on every read is the costly case: it is one list of every read +labelled with it. The read runs under the caller-shaped caps +(`LOOM_CH_CALLER_SHAPED_MAX_ROWS_TO_READ` and its time and memory peers); one that needs +more answers 422, and a run id of its own for each run avoids it. A read past the read +deadline (`LOOM_CH_TIMEOUT_READ_S`, 30 s by default) fails the op. Neither answers a +partial list. [The op that reads a run](../architecture/read-receipts.md#the-op-that-reads-a-run) +gives the measured cost. ```bash loom call run.reliance run_id= --namespace @@ -165,13 +181,13 @@ for item in answer["items"]: A read is listed when its receipt names the run. Which reads carry the run depends on the caller: -| Caller | Its reads are listed when | -| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Any HTTP client | The request's body names the run (`run_id`), or the request carries the `X-Loom-Run-Id` header. On a recall read a body `run_id` also filters to the run's own rows, so label such a read with the header. | -| The Python SDK | The read is made in a run scope, which sends the header on `memory.search`, `memory.search_trace`, `memory.ask` and `memory.list`, and on no document read. | -| The Rust SDK | The client is bound to a run: it sends the header on every call. | -| The TypeScript, Go and Ruby SDKs | The call's input names the run. These SDKs send no run header. | -| An MCP session | The read is one the session's run labels ([reading the table](../architecture/read-receipts.md#reading-the-table) names them). No answer gives an agent the id of its session's run, so over MCP an agent calls `run.reliance` through `loom_op` for a run id it holds: one it opened with `run.begin`, or one a person gave it. | +| Caller | Its reads are listed when | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Any HTTP client | The request's body names the run (`run_id`), or the request carries the `X-Loom-Run-Id` header. On a recall read a body `run_id` also filters to the run's own rows, so label such a read with the header. | +| The Python SDK | In a run scope, `memory.search` and `memory.ask` carry the header, and `memory.get`, `memory.bulk_get` and `context.pack` carry the run in their body; `memory.get_by_id`, `procedure.match` and the document reads carry neither. With `auto_run` and no scope open, every `memory.*`, `working_memory.*`, `observe.*` and `context.*` read carries the header; `procedure.match` and the document reads carry none. | +| The Rust SDK | The client is bound to a run: it sends the header on every call. | +| The TypeScript, Go and Ruby SDKs | The call's input names the run. These SDKs send no run header. | +| An MCP session | The read is one the session's run labels ([reading the table](../architecture/read-receipts.md#reading-the-table) names them). No answer gives an agent the id of its session's run, so over MCP an agent calls `run.reliance` through `loom_op` for a run id it holds: one it opened with `run.begin`, or one a person gave it. | A document read with the header: diff --git a/docs/reference/operations.md b/docs/reference/operations.md index bcf53332329..4887f91a920 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -709,7 +709,7 @@ Fields for every `run` op: [operations/run.md](operations/run.md). | [`run.get`](operations/run.md#runget) | Replay one run: goal, status, final response, the memories it relied on, the memory_keys it wrote, how many memories it recalled and observed, and what its model turns cost. | viewer | read | yes | | | [`run.grade`](operations/run.md#rungrade) | A verdict on a CLOSED run, usually days after it — a maintainer confirmed the finding, CI passed, a reviewer rejected it. | writer | idempotent | no | yes | | [`run.list`](operations/run.md#runlist) | A page of a namespace's agent runs and their match count (`total`), filtered and sorted. | viewer | read | no | | -| [`run.reliance`](operations/run.md#runreliance) | What one run was served, at which revisions, and what its client reported relying on. | viewer | read | no | | +| [`run.reliance`](operations/run.md#runreliance) | What run `run_id` was served, at which revisions, and what its client reported relying on. | viewer | read | no | | | [`run.retract_credit`](operations/run.md#runretract_credit) | Cancel the usage credit of one run, or of the caller's labels over at most 30 days. | writer | idempotent | no | yes | ### search diff --git a/docs/reference/operations/run.md b/docs/reference/operations/run.md index 536c4b00ecb..7e0fcbbc6cd 100644 --- a/docs/reference/operations/run.md +++ b/docs/reference/operations/run.md @@ -165,7 +165,7 @@ A page of a namespace's agent runs and their match count (`total`), filtered and ## `run.reliance` -What one run was served, at which revisions, and what its client reported relying on. +What run `run_id` was served, at which revisions, and what its client reported relying on. `POST /v1/run.reliance` · MCP `loom_run_reliance` · role `viewer` · read · not listed under the MCP `all` toolset @@ -179,7 +179,7 @@ What one run was served, at which revisions, and what its client reported relyin | --- | --- | --- | | `found` | `bool` | False when the namespace holds no run with this id; `items` is then empty. | | `items` | `list[RunRelianceItem]` | One entry per item: `returned` (served, not reported), `reported` (the client's claim, for an item the record holds), `reported_and_served` (the claim names a served revision), `not_recorded` (reported, no record: not a mismatch). | -| `truncated` | `bool` | True when the answer is cut: it keeps every reported item, then the items served most recently, 500 recorded items in all, and the 32 highest recorded versions of each. | +| `truncated` | `bool` | True when the answer is cut: it keeps every reported item, then the items served most recently, 500 recorded items in all, and the 32 highest recorded (content hash, version) pairs of each. | ## `run.retract_credit` diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 405d7b03bf9..2d225537ed2 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: b9b823ead18dc9b7169d4c5f37fa4c9f6f051a75cf7bb920eeeeb19dc5b6271d +// Registry model schema SHA-256: f41e313c0787239fc0d3b5faaa314bffa8b94c902e772f26b8cc7abf17a02d1b // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index fddedfeafe0..495af9b1a88 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -19860,7 +19860,7 @@ class RunListOutput(TypedDict, total=False): class RunRelianceInput(TypedDict, total=False): - "What one run was served, at which revisions, and what its client reported relying on." + "What run `run_id` was served, at which revisions, and what its client reported relying on." org: Required[str] namespace: Required[str] @@ -19868,7 +19868,7 @@ class RunRelianceInput(TypedDict, total=False): class RunRelianceBody(TypedDict, total=False): - "What one run was served, at which revisions, and what its client reported relying on." + "What run `run_id` was served, at which revisions, and what its client reported relying on." org: NotRequired[str] namespace: NotRequired[str] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 5272872a6db..0efe8b47826 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -2631,7 +2631,7 @@ def list(body = nil, request_options: nil, **fields) end # `run.reliance` (viewer, read-only, experimental). - # What one run was served, at which revisions, and what its client reported relying on. + # What run `run_id` was served, at which revisions, and what its client reported relying on. # Required: org, namespace, run_id. def reliance(body = nil, request_options: nil, **fields) call_op("run.reliance", body, fields, request_options) diff --git a/server/tasks/api/models_run.py b/server/tasks/api/models_run.py index 8ed756e27de..a494542e73b 100644 --- a/server/tasks/api/models_run.py +++ b/server/tasks/api/models_run.py @@ -407,7 +407,7 @@ class RunGetOutput(BaseModel): class RunRelianceInput(BaseModel): - """What one run was served, at which revisions, and what its client reported relying on. + """What run `run_id` was served, at which revisions, and what its client reported relying on. Each item has one state.""" @@ -449,8 +449,10 @@ class RunRelianceOutput(BaseModel): # items first, in the order reported; then the others, last served first. items: list[RunRelianceItem] = Field(default_factory=list) # True when the answer is cut: it keeps every reported item, then the items served - # most recently, 500 recorded items in all, and the 32 highest recorded versions of - # each. + # most recently, 500 recorded items in all, and the 32 highest recorded (content hash, + # version) pairs of each. A version read with and without its hash is two pairs, and a + # receipt that names no revision is one: an item past its 32 pairs can list fewer than + # 32 versions, or every version the record holds. truncated: bool = False diff --git a/server/tasks/store/runs.py b/server/tasks/store/runs.py index 52ae853e6b0..6ef752810a3 100644 --- a/server/tasks/store/runs.py +++ b/server/tasks/store/runs.py @@ -16,7 +16,7 @@ from datetime import datetime from typing import Any -from server.core.ch import sequential_reads +from server.core.ch import caller_shaped, sequential_reads from server.core.leases import key_exists from server.identity.domain.read_scope import ReadFilters, scope_and from server.memory.domain.read_receipts import MEMORY @@ -467,35 +467,38 @@ async def receipted_items( last served first, each with its highest recorded (hash, version) pairs; and whether the answer is cut (more than DERIVED_LIMIT items, or more than RECEIPT_PAIRS pairs of one).""" - # One row an item, so the cap never splits one, and a report holds fewer keys than + # One row an item, so the cap never splits one, and a report holds no more keys than # the cap: a cut answer keeps every reported item's receipts. The pairs are sorted # before they are cut, or which of them survive would differ between two calls. # No time bound: a read can carry the run's id before its row is written and after # it closes. - rows = await ch.query_all( - """ - SELECT kind, item_key, max(ts) AS last_served, - arraySlice( - arrayReverseSort(p -> (p.2, p.1), groupUniqArray((content_sha256, version))), - 1, {pairs:UInt32} - ) AS seen - FROM loom.read_receipts - WHERE org = {org:String} AND namespace = {ns:String} AND run_id = {rid:String} - GROUP BY kind, item_key - ORDER BY (kind = {memory:String} AND has({reported:Array(String)}, item_key)) DESC, - last_served DESC, kind, item_key - LIMIT {lim:UInt32} - """, - params={ - "org": org, - "ns": ns, - "rid": run_id, - "reported": reported, - "memory": MEMORY, - "pairs": RECEIPT_PAIRS + 1, - "lim": DERIVED_LIMIT + 1, - }, - ) + # A run id on a read is client input and the aggregate grows with the receipts that + # carry it, so the read is the caller's to shape: a cap refuses it and says why. + with caller_shaped("one run id for each run"): + rows = await ch.query_all( + """ + SELECT kind, item_key, max(ts) AS last_served, + arraySlice( + arrayReverseSort(p -> (p.2, p.1), groupUniqArray((content_sha256, version))), + 1, {pairs:UInt32} + ) AS seen + FROM loom.read_receipts + WHERE org = {org:String} AND namespace = {ns:String} AND run_id = {rid:String} + GROUP BY kind, item_key + ORDER BY (kind = {memory:String} AND has({reported:Array(String)}, item_key)) DESC, + last_served DESC, kind, item_key + LIMIT {lim:UInt32} + """, + params={ + "org": org, + "ns": ns, + "rid": run_id, + "reported": reported, + "memory": MEMORY, + "pairs": RECEIPT_PAIRS + 1, + "lim": DERIVED_LIMIT + 1, + }, + ) cut = len(rows) > DERIVED_LIMIT or any(len(r["seen"]) > RECEIPT_PAIRS for r in rows) served = [ Served( diff --git a/tests/integration/test_run_reliance.py b/tests/integration/test_run_reliance.py index 969f109d300..ec5dba2e3a9 100644 --- a/tests/integration/test_run_reliance.py +++ b/tests/integration/test_run_reliance.py @@ -3,9 +3,10 @@ A read under a run lists the item at the version the read held; a report of a key reads beside the versions served and never names one of them; a report with no read on record says the recall is not recorded, also for a read made with receipts off. The -op answers alike over HTTP, the Python SDK, the CLI and MCP by name, a run id two -namespaces share lists each namespace's own items, and a cut answer keeps the -reported item and each item's highest versions. +op answers alike over HTTP, the Python SDK and the CLI, and lists the same items and +states over MCP by name, where an answer leaves out its empty fields. A run id two +namespaces share lists each namespace's own items, and a cut answer keeps the reported +item and each item's highest versions. """ from __future__ import annotations @@ -151,7 +152,7 @@ async def test_a_report_without_a_record_is_not_recorded_also_with_receipts_off( assert states["read_while_on"]["state"] == "returned" -async def test_http_the_sdk_the_cli_and_mcp_by_name_answer_alike( +async def test_the_sdk_and_the_cli_answer_as_http_and_mcp_by_name_lists_the_same_items_and_states( control_plane_url: str, ch_client: Any, capsys: pytest.CaptureFixture[str] ) -> None: from loom import Agent, cli @@ -159,10 +160,12 @@ async def test_http_the_sdk_the_cli_and_mcp_by_name_answer_alike( ns = _ns("alike") async with Agent(org=ORG, namespace=ns, agent="w", base_url=control_plane_url) as a: await a.memory.set("snapshots", FIRST, memory_type="semantic") + # its own content: a write that repeats another key's content stores no row + await a.memory.set("never_read", SECOND, memory_type="semantic") run = await _begin(a) await _read(a, "memory.get", run, memory_key="snapshots") await _landed(ch_client, ns, run_id=run) - await a.run.complete(run, memories_used=["snapshots"]) + await a.run.complete(run, memories_used=["snapshots", "never_read"]) body = {"org": ORG, "namespace": ns, "run_id": run} over_http = (await a.transport.post_with_meta("/v1/run.reliance", body)).data @@ -178,14 +181,22 @@ async def test_http_the_sdk_the_cli_and_mcp_by_name_answer_alike( over_mcp = _loom_op(control_plane_url, token, "run.reliance", {"namespace": ns, "run_id": run}) assert not over_mcp.get("isError"), over_mcp - [item] = over_http["items"] - assert (item["key"], item["state"]) == ("snapshots", "reported") - for answer in (from_sdk, from_cli, over_mcp["structuredContent"]): + assert {item["key"]: item["state"] for item in over_http["items"]} == { + "snapshots": "reported", + "never_read": "not_recorded", + } + for answer in (from_sdk, from_cli): assert {k: answer[k] for k in ("found", "items", "truncated")} == { "found": True, "items": over_http["items"], "truncated": False, } + listed = over_mcp["structuredContent"] + assert (listed["found"], listed["truncated"]) == (True, False) + # an MCP answer leaves out an empty field (docs/reference/mcp.md, Results) + assert listed["items"] == [ + {k: v for k, v in item.items() if v not in ("", [])} for item in over_http["items"] + ] async def test_the_same_run_id_in_another_namespace_lists_that_namespace_only( diff --git a/tests/unit/test_run_reliance.py b/tests/unit/test_run_reliance.py index a1ae4b78c0c..1d5cef50fa3 100644 --- a/tests/unit/test_run_reliance.py +++ b/tests/unit/test_run_reliance.py @@ -17,8 +17,10 @@ import pytest +import server.core.ch as ch_core +from server.core.errors import ValidationError from server.memory.domain.read_receipts import DOCUMENT, MEMORY -from server.tasks.api.models_run import RunRelianceInput, RunRelianceOutput +from server.tasks.api.models_run import RunCompleteInput, RunRelianceInput, RunRelianceOutput from server.tasks.domain.reliance import ( Reported, Revision, @@ -178,6 +180,7 @@ def _reliance( ) +# `-` is the label of a read made outside a run; `run.begin` never stores a row under it. @pytest.mark.parametrize("run_id", ["zz", "-"]) def test_an_unknown_run_reads_no_receipt(env, run_id: str) -> None: fake, h = env @@ -188,7 +191,7 @@ def test_an_unknown_run_reads_no_receipt(env, run_id: str) -> None: assert [kind for kind, _, _ in fake.calls] == ["one"] -def test_the_receipt_read_binds_the_addressed_org_and_namespace_and_the_run_rows_id(env) -> None: +def test_the_receipt_read_binds_the_addressed_org_namespace_and_run_id(env) -> None: fake, h = env fake.one.append(_run_row(org="o", namespace="n", run_id="r1", memories_used=["k1", "k2"])) @@ -267,6 +270,16 @@ def test_a_cut_answer_says_so_and_keeps_every_reported_item(env) -> None: assert rows[-1]["item_key"] not in {i.key for i in out.items} +def test_a_report_holds_no_more_keys_than_the_cap() -> None: + # Reported items sort first, so the cut keeps them all only while this holds. + (bound,) = [ + m.max_length + for m in RunCompleteInput.model_fields["memories_used"].metadata + if hasattr(m, "max_length") + ] + assert bound <= runs_store.DERIVED_LIMIT + + def test_a_cut_answer_keeps_the_first_pairs_of_an_item(env) -> None: fake, h = env # Highest version first, as the statement sorts them; one pair more than is kept. @@ -281,6 +294,33 @@ def test_a_cut_answer_keeps_the_first_pairs_of_an_item(env) -> None: assert listed == [V1 + n for n in range(runs_store.RECEIPT_PAIRS, 0, -1)] +def _read_both_ways(versions: int) -> list[tuple[str, int]]: + """`versions` versions of one item, each read with its hash and without, highest + first as the statement sorts them.""" + return [pair for n in range(versions, 0, -1) for pair in ((f"{n:064x}", V1 + n), ("", V1 + n))] + + +def test_the_pair_cap_counts_a_version_read_with_and_without_its_hash_twice(env) -> None: + fake, h = env + half = runs_store.RECEIPT_PAIRS // 2 + fake.one.extend([_run_row(), _run_row()]) + # Half the cap's count of versions fills it; the pair past it names no revision. + fake.all.append([_receipts("k", [*_read_both_ways(half), ("", 0)])]) + # One version more is two pairs more: the statement returns one pair more than is kept. + fake.all.append([_receipts("k", _read_both_ways(half + 1)[: runs_store.RECEIPT_PAIRS + 1])]) + + nothing_dropped, lowest_dropped = _reliance(h), _reliance(h) + + # Cut, with every version the record holds listed. + assert nothing_dropped.truncated is True + listed = [[int(v) for v in r.versions] for r in nothing_dropped.items[0].revisions] + assert listed == [[V1 + n] for n in range(half, 0, -1)] + # Cut, with fewer versions listed than the cap's count: the highest of them. + assert lowest_dropped.truncated is True + listed = [[int(v) for v in r.versions] for r in lowest_dropped.items[0].revisions] + assert listed == [[V1 + n] for n in range(half + 1, 1, -1)] + + def test_an_answer_within_both_caps_is_not_cut(env) -> None: fake, h = env pairs = [("", V1 + n) for n in range(runs_store.RECEIPT_PAIRS)] @@ -327,9 +367,52 @@ async def failing(sql, params=None): _reliance(h) -def test_a_run_closed_again_with_no_report_lists_no_reported_item(env) -> None: +def test_only_the_receipt_read_runs_under_the_caller_shaped_ceilings(env) -> None: + fake, h = env + fake.one.append(_run_row()) + shaped: list[tuple[str, bool]] = [] + query_one, query_all = fake.query_one, fake.query_all + + async def one(sql, params=None): + shaped.append(("one", ch_core.caller_shaped_var.get())) + return await query_one(sql, params) + + async def every(sql, params=None): + shaped.append(("all", ch_core.caller_shaped_var.get())) + return await query_all(sql, params) + + fake.query_one, fake.query_all = one, every + + _reliance(h) + + # A run id on a read is client input, so the read grouped by it is the caller's to + # shape; the point read of the run's row is not. + assert shaped == [("one", False), ("all", True)] + + +def test_a_receipt_read_past_a_ceiling_is_refused_with_the_way_to_narrow_it(env) -> None: + fake, h = env + fake.one.append(_run_row(memories_used=["k1"])) + over = RuntimeError( + "Code: 241. DB::Exception: Query memory limit exceeded: would use 3.74 GiB " + "(attempt to allocate chunk of 4.00 MiB), maximum: 3.73 GiB: While executing " + "AggregatingTransform. (MEMORY_LIMIT_EXCEEDED)" + ) + + async def capped(sql, params=None): + # As the client does for a statement's own cap inside the scope. + ch_core._raise_if_caller_cap(over) + raise over + + fake.query_all = capped + + with pytest.raises(ValidationError, match=r"narrow it \(one run id for each run\)"): + _reliance(h) + + +def test_a_closed_run_with_no_report_lists_no_reported_item(env) -> None: fake, h = env - # The run's last close named no memory, so the row holds no report. + # The row holds no report. fake.one.append(_run_row(status="completed", memories_used=[])) fake.all.append([_receipts("k1", [(H1, V1)])]) @@ -364,18 +447,22 @@ def test_only_the_domain_module_spells_a_state() -> None: def test_the_op_is_viewer_read_only_experimental_and_unlisted() -> None: - from server.identity.domain.read_scope import NARROW_SAFE_OPS, SCOPED_OPS + from server.identity.domain.read_scope import honours_read_scope from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME from server.operations.toolsets import _MCP_HIDDEN_OPS, listed_under_all + from server.transport import mcp_op op = OPERATIONS_BY_NAME["run.reliance"] assert op.required_role == Role.VIEWER and op.read_only and op.idempotent and not op.audit assert op.maturity == "experimental" # Callable by name through `loom_op`, in no listing. assert not listed_under_all(op) and op.name not in _MCP_HIDDEN_OPS + # The catalogue row lists no identity key as an argument, so its purpose names the one + # the caller must send. + assert "`run_id`" in mcp_op._row(op)["purpose"] # A run's receipts name rows other users wrote: a narrowed token is refused. - assert op.name not in SCOPED_OPS and op.name not in NARROW_SAFE_OPS + assert not honours_read_scope(op.name) def test_the_reference_row_of_items_names_each_state() -> None: From c35da0fe3a014b3a13c9e0e6f5b4e8f01eb5c8be Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 20:51:17 +0000 Subject: [PATCH 13/18] The keep-reading test reruns the erasure until it completes, and a row's set hash is checked once Each server process sends its own receipts. The test waited for the last read's receipt, which proves only that the process that served it has sent. It now runs the erasure again until one completes, and each run that does not must name the receipts table as its only residue. row_content_sha256 returns the stored hash when it is set and hashes the value otherwise, without handing the stored column to live_sha256 for a second check that could not pass. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- server/memory/domain/trust.py | 2 +- tests/integration/test_read_receipts.py | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/server/memory/domain/trust.py b/server/memory/domain/trust.py index de7f163ad11..76ac6f638f3 100644 --- a/server/memory/domain/trust.py +++ b/server/memory/domain/trust.py @@ -127,7 +127,7 @@ def row_content_sha256(row: Any) -> str: return text value = getattr(row, "value", None) whole = value is not None and not getattr(row, "value_truncated", False) - return live_sha256(stored, json.dumps(value, default=str) if whole else None) + return sha256_value_json(json.dumps(value, default=str)) if whole else "" def live_sha256(stored: str | bytes | None, value_json: str | None) -> str: diff --git a/tests/integration/test_read_receipts.py b/tests/integration/test_read_receipts.py index 771b473ab4c..f143db943ea 100644 --- a/tests/integration/test_read_receipts.py +++ b/tests/integration/test_read_receipts.py @@ -813,11 +813,22 @@ async def keep_reading() -> list[str]: made = await reader if result["status"] != "completed": # a failed run lists its residue and no steps assert set(result["residue"]) == {"loom.read_receipts"}, result - # The second run is recorded at a new second. The reads have stopped, and a - # process sends its receipts in the order of their reads: once the last one - # has landed, none is left to land behind the second run's step. + + async def erased_again() -> dict[str, Any] | None: + """One more run, recorded at a later second: its result once it completes.""" + again = await admin.erasure.request_user_id(user, requester="ops@example.com") + if again["status"] == "completed": + return again + assert set(again["residue"]) == {"loom.read_receipts"}, again + return None + + # The reads have stopped. The process that served the last one has sent every + # receipt of its own once that one has landed; another process may still hold + # one for a send interval, and a run that finds it behind its step is run again. await _landed(ch_client, ns, request_id=made[-1]) - result = await admin.erasure.request_user_id(user, requester="ops@example.com") + result = await eventually( + erased_again, max_wait=60.0, interval=1.0, description="the erasure completes" + ) await _read(a, "knowledge.get", request_id=after, source_uri=uri, user_id=user) assert made From d043a977bb7dbda422db924e3ca8ea43a513445e Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 21:24:09 +0000 Subject: [PATCH 14/18] The settings reference names run.reliance among the caller-shaped reads run.reliance's receipt read runs inside caller_shaped, so the three LOOM_CH_CALLER_SHAPED_* ceilings bound it: a read past one answers 422. The comment above those settings lists the reads they bound, and the settings reference and the settings file template print it. An operator who lowers a ceiling for code.grep reads there that the same ceiling refuses run.reliance. docs/reference/configuration.md and loom.example.yaml are regenerated. The settings schema carries no comment and is unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- docs/reference/configuration.md | 2 +- loom.example.yaml | 14 +++++++------- server/settings/catalog.py | 5 +++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 06fe40596f4..f9b3b8f04f6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -192,7 +192,7 @@ ClickHouse connection, query shaping and vector storage. ### Caller-shaped read ceilings -Ceilings for the reads a caller shapes (code.grep, code.search with a pattern or globs, memory.aggregate, memory.record.query). A ceiling only lowers the statement's own value, so no request can widen it; 0 = none. The shipped loom_reader profile (nlp_user_settings.xml) caps these three at their defaults, with a floor no statement can go under (time: 0.05 s, code.grep's statement floor), so none can be set to 0 even in the SQL. Raising a setting above its cap needs the profile raised too; a 0 sends no ceiling, so the profile's cap applies (code.grep's deadline is then clamped to ch_timeout_read_s, which the profile's cap matches). +Ceilings for the reads a caller shapes (code.grep, code.search with a pattern or globs, memory.aggregate, memory.record.query, run.reliance). A ceiling only lowers the statement's own value, so no request can widen it; 0 = none. The shipped loom_reader profile (nlp_user_settings.xml) caps these three at their defaults, with a floor no statement can go under (time: 0.05 s, code.grep's statement floor), so none can be set to 0 even in the SQL. Raising a setting above its cap needs the profile raised too; a 0 sends no ceiling, so the profile's cap applies (code.grep's deadline is then clamped to ch_timeout_read_s, which the profile's cap matches). | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | diff --git a/loom.example.yaml b/loom.example.yaml index cd534ae66ed..59509d2fed2 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -143,13 +143,13 @@ settings: # --- caller-shaped read ceilings --- # Ceilings for the reads a caller shapes (code.grep, code.search with a pattern or - # globs, memory.aggregate, memory.record.query). A ceiling only lowers the statement's - # own value, so no request can widen it; 0 = none. The shipped loom_reader profile - # (nlp_user_settings.xml) caps these three at their defaults, with a floor no - # statement can go under (time: 0.05 s, code.grep's statement floor), so none can be - # set to 0 even in the SQL. Raising a setting above its cap needs the profile raised - # too; a 0 sends no ceiling, so the profile's cap applies (code.grep's deadline is - # then clamped to ch_timeout_read_s, which the profile's cap matches). + # globs, memory.aggregate, memory.record.query, run.reliance). A ceiling only lowers + # the statement's own value, so no request can widen it; 0 = none. The shipped + # loom_reader profile (nlp_user_settings.xml) caps these three at their defaults, with + # a floor no statement can go under (time: 0.05 s, code.grep's statement floor), so + # none can be set to 0 even in the SQL. Raising a setting above its cap needs the + # profile raised too; a 0 sends no ceiling, so the profile's cap applies (code.grep's + # deadline is then clamped to ch_timeout_read_s, which the profile's cap matches). # Seconds one caller-shaped read may run (the read class default); 0 = no ceiling, so # the loom_reader profile's cap applies. [restart] diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 1ca5bfa3aea..f6c3b53c7c6 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -747,8 +747,9 @@ class ClickHouseSettings(BaseModel): # reconnect can land on the replica that just failed, so a single retry is not enough. ch_replica_bound_retries: int = Field(default=2, ge=1, le=5) # Ceilings for the reads a caller shapes (code.grep, code.search with a - # pattern or globs, memory.aggregate, memory.record.query). A ceiling only - # lowers the statement's own value, so no request can widen it; 0 = none. + # pattern or globs, memory.aggregate, memory.record.query, run.reliance). A + # ceiling only lowers the statement's own value, so no request can widen it; + # 0 = none. # The shipped loom_reader profile (nlp_user_settings.xml) caps these three at # their defaults, with a floor no statement can go under (time: 0.05 s, # code.grep's statement floor), so none can be set to 0 even in the SQL. From 948021a2541781bc37c0eeb6fe37bb262903e19f Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 21:24:11 +0000 Subject: [PATCH 15/18] The replay's e2e axe check waits for the table of what the run read The section that lists what a run read loads from its own request, run.reliance, after run.get's answer draws the rest of the replay. A test that waits only for run.get's text can run axe before the table is drawn, and passes whether or not axe read it. The replay test waits for the table by its role and name before the axe check, so a replay that draws no table fails. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Mohammad Lareb Zafar --- frontend/e2e/runs.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/e2e/runs.spec.ts b/frontend/e2e/runs.spec.ts index 03e52691d03..8bd87b5b0ec 100644 --- a/frontend/e2e/runs.spec.ts +++ b/frontend/e2e/runs.spec.ts @@ -35,6 +35,7 @@ test("a run's replay opens and has no WCAG A/AA violations", async ({ page }) => const dialog = page.getByRole("dialog"); await expect(dialog).toBeVisible(); await expect(dialog.getByText("recalled keys")).toBeVisible(); + await expect(dialog.getByRole("table", { name: "What this run read" })).toBeVisible(); expect(errors).toEqual([]); expect(await violations(page)).toEqual([]); }); From 927edf2b7c3a41e157bb4c6e916241a5df7a290c Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 22:21:46 +0000 Subject: [PATCH 16/18] The reader user's problem and the deployment page name run.reliance run.reliance's receipt read runs inside caller_shaped, so it runs as LOOM_CH_READER_USER and fails while ClickHouse refuses that user. The comment above the ceilings in server/settings/catalog.py lists it; two other lists of the same reads left it out: - the docstring and the message of _reader_user_problems (ch_reader_user_failing in /v1/health and loom doctor), which tell an operator which ops fail; - the Read-only user bullet of docs/operations/deployment.md. The three lists name the same five reads. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/operations/deployment.md | 6 +++--- server/observability/problems.py | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 1aaabb0e942..2abe12e02c3 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -155,9 +155,9 @@ The bundled ClickHouse starts with the files in `deploy/clickhouse-config/`: | `named_collections.xml` | Named collections for ClickHouse's `ai*` SQL functions. Git-ignored; defines none as shipped; keys come via `from_env`. | - **Read-only user.** Loom runs the reads a caller shapes (`code.grep`, a patterned - `code.search`, `memory.aggregate`, `memory.record.query`) as `LOOM_CH_READER_USER`, - which `compose.yaml` and the local stack set to `loom_reader` (set it in `.env` for - `dev/docker-compose.cloud.yml`), so none of them can write, + `code.search`, `memory.aggregate`, `memory.record.query`, `run.reliance`) as + `LOOM_CH_READER_USER`, which `compose.yaml` and the local stack set to `loom_reader` + (set it in `.env` for `dev/docker-compose.cloud.yml`), so none of them can write, change schema or grant. It has SELECT on `loom.*` only (it cannot read `system.query_log`) and a read-only profile whose time, memory and rows-read caps each have a ceiling no statement can raise and a floor no statement can go under (time: diff --git a/server/observability/problems.py b/server/observability/problems.py index 2e5bb3da7ab..865b30bebf4 100644 --- a/server/observability/problems.py +++ b/server/observability/problems.py @@ -892,8 +892,8 @@ def _git_proxy_problems(settings: Any, state: HealthState) -> list[Problem]: def _reader_user_problems(settings: Any, state: HealthState) -> list[Problem]: """The caller-shaped reads (code.grep, code.search with a pattern or globs, - memory.aggregate, memory.record.query) run as the reader user, so they all - fail while ClickHouse refuses it.""" + memory.aggregate, memory.record.query, run.reliance) run as the reader user, + so they all fail while ClickHouse refuses it.""" if state.ch_reader_ok is not False: return [] user = settings.ch_reader_user @@ -914,8 +914,8 @@ def _reader_user_problems(settings: Any, state: HealthState) -> list[Problem]: "ch_reader_user_failing", "error", f"A read as LOOM_CH_READER_USER={user} failed (the boot probe, or `loom doctor`): " - "code.grep, code.search with a pattern or globs, memory.aggregate and " - "memory.record.query fail while it does.", + "code.grep, code.search with a pattern or globs, memory.aggregate, " + "memory.record.query and run.reliance fail while it does.", fix, source="runtime", ) From bc807149841b47d83c603fa3a8817c02c8e8e8f2 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 23:41:28 +0000 Subject: [PATCH 17/18] The knowledge factory guide says run.reliance lists the revision a run was served The guide and two comments, one in the example and one in its unit test, said that no op serves a read's receipt. `run.reliance` lists the versions a run was served, and the example does not call it. The guide says so in its table of what Loom enforces, in its paragraph on `not_read` and in its coverage table, and the table's row links to "What a run read" in docs/features/runs.md. The example's calls, its `revision_receipts` coverage entry and expected.json are unchanged. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/guides/knowledge-factory-workflow.md | 54 +++++++++---------- sdk/python/examples/knowledge_factory.py | 3 +- .../test_sdk_example_knowledge_factory.py | 5 +- 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/docs/guides/knowledge-factory-workflow.md b/docs/guides/knowledge-factory-workflow.md index 15450b78113..9e771a574f9 100644 --- a/docs/guides/knowledge-factory-workflow.md +++ b/docs/guides/knowledge-factory-workflow.md @@ -115,22 +115,22 @@ knowledge: no request of the example holds one of them. ## What Loom enforces and what the example arranges -| Property | Loom | The example | -| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -| Publication needs `admin` on the namespace | Enforced: `memory.promote` answers 403 to a `writer` | | -| An approval names the exact text | Enforced: `approved_sha256`, else 409 `PRECONDITION_FAILED` with `current_sha256` | Reads the text again after a 409 | -| A write does not replace a revision its writer did not read | Enforced for a write that sends `if_match_sha256`: 409 when the row holds another hash | Both of the curator's writes send it | -| The approver of a definition is a person | Not enforced: a service account with `admin` can promote | Preflight requires a person's token for the reviewer | -| The approver is not the author | Not enforced for a promotion | By tokens: the curator holds `writer`; the result shows author and approver | -| Deciding a proposal needs `admin` on the namespace | Enforced: `memory.proposal_decide` answers 403 to a `writer` | | -| A person other than the proposer accepts a proposal | Enforced by `memory.proposal_decide` ([proposals](../features/memory/writing.md#proposals)) | The reviewer cannot accept a note it proposed: 200 with nothing decided | -| A proposal is not served | Enforced: a `proposed` row is in no search result | The same search returns the row once it is accepted | -| A `writer` cannot change an active team row without review | Not enforced | A limit, below | -| The approved definition stays served during review | No: an edit of its source row ends governance until the next approval | The reporter uses a definition only from a governed hit | -| The link from the problem to the correction | Not held | Text in the promotion's `rationale` that names run 1 | -| The revision a run was served | Kept as a read receipt where one is written; no op serves it ([runs](../features/runs.md)) | Prints `not_read`: it calls ops only | -| An independent grader | Not enforced: `run.grade` takes any `writer` | The reviewer's token grades; the audit row shows who called | -| No duplicate publication | Not enforced: `memory.promote` is not idempotent | One call; one that gets no usable answer is settled by reads | +| Property | Loom | The example | +| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| Publication needs `admin` on the namespace | Enforced: `memory.promote` answers 403 to a `writer` | | +| An approval names the exact text | Enforced: `approved_sha256`, else 409 `PRECONDITION_FAILED` with `current_sha256` | Reads the text again after a 409 | +| A write does not replace a revision its writer did not read | Enforced for a write that sends `if_match_sha256`: 409 when the row holds another hash | Both of the curator's writes send it | +| The approver of a definition is a person | Not enforced: a service account with `admin` can promote | Preflight requires a person's token for the reviewer | +| The approver is not the author | Not enforced for a promotion | By tokens: the curator holds `writer`; the result shows author and approver | +| Deciding a proposal needs `admin` on the namespace | Enforced: `memory.proposal_decide` answers 403 to a `writer` | | +| A person other than the proposer accepts a proposal | Enforced by `memory.proposal_decide` ([proposals](../features/memory/writing.md#proposals)) | The reviewer cannot accept a note it proposed: 200 with nothing decided | +| A proposal is not served | Enforced: a `proposed` row is in no search result | The same search returns the row once it is accepted | +| A `writer` cannot change an active team row without review | Not enforced | A limit, below | +| The approved definition stays served during review | No: an edit of its source row ends governance until the next approval | The reporter uses a definition only from a governed hit | +| The link from the problem to the correction | Not held | Text in the promotion's `rationale` that names run 1 | +| The revision a run was served | Kept as a read receipt where one is written; `run.reliance` lists it ([what a run read](../features/runs.md#what-a-run-read)) | Prints `not_read`: it does not call `run.reliance` | +| An independent grader | Not enforced: `run.grade` takes any `writer` | The reviewer's token grades; the audit row shows who called | +| No duplicate publication | Not enforced: `memory.promote` is not idempotent | One call; one that gets no usable answer is settled by reads | [Governed definitions in search](../concepts/identities-and-namespaces.md#governed-definitions-in-search) explains when a definition is governed and how a query matches its term. @@ -226,9 +226,9 @@ A governed hit carries no version and no hash, so the two run stages print `revision: "not_read"` beside what the read did carry. `not_read` says that the example did not read the revision, not that Loom holds none. Where receipts are written, Loom keeps the revision each labelled read held as a read receipt under the run's `run_id` -([what gets none](../architecture/read-receipts.md#what-gets-none)). No op serves a -receipt: it is read with SQL -([reading the table](../architecture/read-receipts.md#reading-the-table)). +([what gets none](../architecture/read-receipts.md#what-gets-none)). `run.reliance` +lists the versions a run was served +([what a run read](../features/runs.md#what-a-run-read)); the example does not call it. `returned` holds what `run.get` reports and nothing else. It reads `not_recorded` unless the server keeps the search trace log (`LOOM_SEARCH_TRACE_LOG_ENABLED`); it then lists @@ -239,14 +239,14 @@ means that it holds no count, not zero ## Coverage -| Entry | Exercised | Needs | -| ------------------------------------------------------------------------------------------------ | --------- | ---------------------------------- | -| `run_1`, `investigation`, `review`, `publication`, `run_2`, `evidence`, `control_question` | yes | | -| `report`, `repeated_report` | no | Problem reports that Loom holds | -| `curation_pass`, `interrupted_pass_retry`, `stale_source_refusal`, `duplicate_publication_guard` | no | A curation pass | -| `revision_receipts` | no | An op that serves a read's receipt | -| `real_agent_run` | no | An agent runner; does not gate | -| `mcp_path` | no | An MCP client; does not gate | +| Entry | Exercised | Needs | +| ------------------------------------------------------------------------------------------------ | --------- | ------------------------------------------------------------------ | +| `run_1`, `investigation`, `review`, `publication`, `run_2`, `evidence`, `control_question` | yes | | +| `report`, `repeated_report` | no | Problem reports that Loom holds | +| `curation_pass`, `interrupted_pass_retry`, `stale_source_refusal`, `duplicate_publication_guard` | no | A curation pass | +| `revision_receipts` | no | A call of `run.reliance` in the example, and a check of its answer | +| `real_agent_run` | no | An agent runner; does not gate | +| `mcp_path` | no | An MCP client; does not gate | The table is a constant of the example's version. An entry reads exercised only in the version that makes its calls and checks them, never at run time. diff --git a/sdk/python/examples/knowledge_factory.py b/sdk/python/examples/knowledge_factory.py index a8e3f42568f..de5c665860d 100644 --- a/sdk/python/examples/knowledge_factory.py +++ b/sdk/python/examples/knowledge_factory.py @@ -973,7 +973,8 @@ async def reporting_run(self, number: int, approved: dict[str, Any]) -> None: credit = {field: closed.get(field) for field in expected["credit"]} self.check(f"{name}_credit_counts", credit == expected["credit"], json.dumps(credit)) # The governed hit carries no revision. Where receipts are written, Loom keeps the - # one it served as a read receipt, which no op serves, so the stage says `not_read`. + # one it served as a read receipt. `run.reliance` lists it and this example does + # not call that op, so the stage says `not_read`. self.entry().update(served=served, revision="not_read") self.result["runs"][name] = { "run_id": run_id, diff --git a/tests/unit/test_sdk_example_knowledge_factory.py b/tests/unit/test_sdk_example_knowledge_factory.py index bfe8b78e1ea..0871b834ce2 100644 --- a/tests/unit/test_sdk_example_knowledge_factory.py +++ b/tests/unit/test_sdk_example_knowledge_factory.py @@ -608,8 +608,9 @@ async def test_coverage_has_one_source_and_qualified_follows_the_gating_entries( assert "control_unaffected_by_the_correction" in checks(result) # Where receipts are written, Loom keeps the revision a run was served as a read - # receipt, which no op serves. The entry needs that op, and a run stage says it read - # no revision, not that none is kept. + # receipt, which `run.reliance` lists. The example does not call that op, so the + # entry names it as its need, and a run stage says it read no revision, not that + # none is kept. assert kf.COVERAGE["revision_receipts"]["needs"] == "read_receipts_op" revisions = {entry["stage"]: entry.get("revision") for entry in result["stages"]} assert (revisions["run_1"], revisions["run_2"]) == ("not_read", "not_read") From 77afb38217570f4d17b60d97c646d65fcbc58ee2 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 23:41:36 +0000 Subject: [PATCH 18/18] The reliance section's table holds the ref useShowMore returns `useShowMore` takes the type of the element that holds its rows. The section passes `HTMLTableElement`, reads the rows from the argument of `rows` and gives the hook's `list` to the table, so it keeps no ref of its own. The section's Show more test fails when the table lacks that ref. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- frontend/src/flows/RunReliance.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/frontend/src/flows/RunReliance.tsx b/frontend/src/flows/RunReliance.tsx index a95858ab426..98f229847f8 100644 --- a/frontend/src/flows/RunReliance.tsx +++ b/frontend/src/flows/RunReliance.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { Badge } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; import { Table, type TableRowType } from "@clickhouse/click-ui/Table"; @@ -103,12 +103,11 @@ function Covers() { } function Items({ items, cut }: { items: RunRelianceItem[]; cut: boolean }) { - const table = useRef(null); - const how: ShowMoreRows = { + const how: ShowMoreRows = { key: itemId, // The rows are the table's, not a list's: each drawn item with the chip that opens it. - rows: () => - [...(table.current?.querySelectorAll("[data-reliance-item]") ?? [])].flatMap( + rows: (table) => + [...(table?.querySelectorAll("[data-reliance-item]") ?? [])].flatMap( (cell): Array<[string, HTMLElement]> => { const button = cell.querySelector("button"); return button ? [[cell.dataset.relianceItem ?? "", button]] : []; @@ -121,7 +120,7 @@ function Items({ items, cut }: { items: RunRelianceItem[]; cut: boolean }) { const rows = useMemo(() => items.slice(0, drawn).map(itemRow), [items, drawn]); return (
-
+
{more.moreLabel && (