---
title: Read receipts
lastModified: '2026-12-05T05:03:56.000Z'
description: '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…'
---

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.

Two other receipts describe a read and are not rows of this table: the read receipt the
[outbound MCP source client](/docs/architecture/mcp-source-client) 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<br/>(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. 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                   |
| --------------------------------------------------- | ------------------------------------------ | --------------------------------------------- |
| `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                  | 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         |

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, 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
    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** 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, 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

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 the receipt of a governed definition, and of a
shared row served its whole body, 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, its whole body, a governed definition | 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 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
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](/docs/architecture/storage-authority#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
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](/docs/architecture/document-sources#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), `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`, `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 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`,
  `memory.timeline`, `facts.*`, `memory.record.query`, `procedure.list`,
  `knowledge.synthesize`, `knowledge.query`, and code answers that print memories.
- **A check of a quote** (`knowledge.citations.check`). It compares the quote with the
  cited document's text and answers a verdict: the answer carries no part of the
  document.
- **A document read under a read scope that does not resolve.** `knowledge.search` and
  `knowledge.get` take no `user_id` or `session_id`, so a call cannot complete the scope
  of an `own_session` token, or of an `own_user` token with no `read_user_id`. The read
  is served and its answer gets no receipt: each answer that carries an item logs
  `read receipts of <handler> not recorded`
  ([checking that receipts are written](#checking-that-receipts-are-written)). Over
  MCP, a `knowledge.get` under such a scope begins and joins no session run, whatever
  user or session its arguments name, and its op ledger row names no run.
- **A read made while receipts are not written**: `read_receipts_enabled` is off, a
  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 someone
who reads the table must not take it to mean the item was not served.

## 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, `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 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 under the agent, user and session
the request names: in its body over HTTP, and in the op's arguments over MCP (under
`loom_op`, the inner `arguments`; `_span_identity` in `server/transport/mcp_outcome.py`).
A token pinned to a user is filed as that user, whatever the request names, where its
read scope resolves ([what gets none](#what-gets-none)). A request with a named consumer
(the token's `consumer` claim, else the request's `consumer`, which the assistant toolset
sets to `loom-assistant`) is filed under that consumer as its `agent` on the four ops
with no agent field, whatever agent it names, and on `search.query` when its input names
no agent; the op ledger row of the same request names the agent the request names.

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 `run_id` of the op's input when the request
names one there, else the run bound to the request: the `X-Loom-Run-Id` header, or over
MCP the session's run, which labels every receipted op
([reading the table](#reading-the-table) names the calls it does not reach). A receipt,
the op ledger row and the exposure row of one request therefore name one run. A `run_id`
named on an op whose input has no such field names no run on any of the three, over
either transport: the request is filed under the run bound to it. 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.

A run opened over MCP with `run.begin` has an id of its own. A read of the session is
filed under that id only when it names it in `run_id`; its other reads are filed under
the session's run, except those filed under `-` or under another run the read names.
The run's row therefore names the session's run in `metadata.session_run`
(`_begin_metadata` in `server/tasks/app/run.py`). The receipts under either id made
while the run was open are the session's reads of that time filed under either id.
That is more than the run's own reads when the session did other work meanwhile, and
it leaves out a session read filed under `-` or under another run it names
([reading the table](#reading-the-table) names the cases). The label is set when the
request runs: a receipt filed without it joins no run later.

`metadata.session_run` is read by its form, `mcp-` and 40 hexadecimal digits
(`session_run_of` in `server/tasks/domain/session_runs.py`). The form is not proof that
this server wrote the value: a build that does not reserve the key stores what a client
sends there, lets `run.complete` overwrite it, and drops the server's value on a begin
sent again ([rolling upgrades](#rolling-upgrades)). The value may therefore choose which
receipts a run is read by and never whose ([invariants](#invariants)).

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

`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:

```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
```

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
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}
       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, 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, content_sha256,
         if(content_sha256 = '', version, 0)
ORDER BY first_read
```

The session's reads filed under either id while a run opened over MCP was open: the
receipts under the run's own id and under its session's run, from the run's start to
its close. `ts` is a whole second, so the window is whole seconds at both ends: a
session read made in the second the run opened in, before it opened, or in the second
it closed in, after it closed, is in the answer.

```sql
WITH run AS (
    SELECT extract(JSONExtractString(metadata, 'session_run'),
                   '^mcp-[0-9a-f]{40}$') AS session_run,
           toStartOfSecond(started_at) AS opened,
           ifNull(completed_at, now64(3)) AS closed
    FROM loom.agent_runs FINAL
    WHERE org = {org:String} AND namespace = {namespace:String} AND run_id = {run:String}
)
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 IN ({run:String}, (SELECT session_run FROM run))
  AND ts >= (SELECT opened FROM run) AND ts <= (SELECT closed FROM run)
GROUP BY namespace, kind, item_key, content_sha256,
         if(content_sha256 = '', version, 0)
ORDER BY first_read
```

`extract` applies the form rule, so a row that holds another value under `session_run`
adds nothing. For a run whose row names no session run, the statement returns the reads
filed under the run's own id: those that named it in `run_id` and, over HTTP, those sent
with it in `X-Loom-Run-Id`.

The answer is the session's reads filed under either id, which is not always what the
run read. A session read filed under neither is not in it: one filed under `-`, or
under another run it names (the rule on MCP reads below lists the calls). Five cases
have no statement:

- **Two runs open at once in one session** name the same session run, so each answer
  holds the other's reads.
- **A run opened again after it closed** keeps its first start: a begin sent again
  after `run.complete` clears the close and leaves `started_at` as it was, so the answer
  also holds the session's reads made while the run was closed.
- **A client that reconnects under a new `Mcp-Session-Id`** reads under an id the run's
  row does not name, so its reads after the reconnect are not in the answer.
- **A begin sent again from another MCP session** replaces the stored id with that
  session's, so the first session's reads leave the answer.
- **A run opened over HTTP whose agent reads over MCP** has those reads under the
  session's run, and its row names no session run, so nothing ties them to the run. The
  coding-agent plugins work this way: a hook calls `run.begin`, the model calls the MCP
  tools.

When writing a statement over the table:

- **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. 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 two
  statements above do.
- **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, a receipted read has the session's run, with exceptions.** The
  session's run labels an op whose input has a `run_id` field (`run.*` and `code.*`
  apart) and, by name, each receipted op whose input has none: `search.query`,
  `knowledge.get`, `memory.get_by_id`, `memory.for_file` and `procedure.match`
  (`_LABELLED_READS` in `server/transport/mcp_runs.py`, which also lists
  `knowledge.search`, an op only the assistant toolset serves). The op ledger row of
  a call names the run its receipts name, and no run where they name `-`: both read
  the run from the op's input, so a `run_id` named on an op whose input has no such
  field, as on the reads listed by name, names no run on either. Three kinds of call
  are filed otherwise: a read that names a `run_id` its input has a field for, under
  that run; a call of the assistant toolset, under the answer it serves; and a call
  in a session that has no run, under `-`. A session has no run when its calls send
  no `Mcp-Session-Id` and when its token has no default namespace (`session_label`);
  a `run.begin` in such a session records no `session_run`. In a session that has a
  run, a call of a labelled op joins it exactly when the read scope gate resolves the
  call's read scope: the run's caller (`Caller.of_call`) and the gate read the same
  keys, those the op's input declares, so a `user_id`, `session_id` or `read_scope`
  named on an op whose input has no such field changes neither. A read the gate
  serves under a scope it cannot complete joins no run and gets no receipt
  ([what gets none](#what-gets-none)). For up to a minute after a web process failed
  to begin the session's run, the session's reads that reach that process are filed
  under `-` too (`run_id_for`). A `run.begin` in that minute still records the
  session's run: the id is the same on every process, and the reads after the minute,
  or on another process, carry it. A run opened with `run.begin` is read through its
  own id and the session's run its row names, as the statement above does.
- **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.

### 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](/docs/features/runs#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. 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
  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. 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](/docs/architecture/clickhouse#statement-classes-deadlines-and-traffic-classes))
  fails the op.

## Cost

- **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
  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](/docs/architecture/clickhouse#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. 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 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                                                                                                                                                     |
| ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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 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 <handler> 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](/docs/architecture/clickhouse#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. A user erasure:

```mermaid
flowchart LR
    A["erasure recorded"] --> B["step: delete every<br/>receipt of the reader"]
    B --> C["census: count the reader's receipts stamped up to<br/>the second the erasure was recorded in"]
    R["the user's reads<br/>after that second"] -.->|"new receipts,<br/>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 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'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
  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 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](/docs/architecture/clickhouse#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
  `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 read deadline, `LOOM_CH_TIMEOUT_READ_S`)
  and resume the erasure
  ([abandoned sagas](/docs/features/memory/retention-and-erasure#abandoned-sagas)).

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
after an erasure's census is neither deleted nor counted by the erasure, in either scope
and whenever its read answered: the erasure reports `completed` with no residue. That
row holds identifiers and a hash, and stays until a re-verify run deletes it, the next
erasure of the same scope, or the table's TTL.

`loom erasure-re-verify --completed-since <ISO timestamp>` counts such rows for each
completed erasure whose census ran at or after that time, and exits 1 while any are
left. With `--resume` it deletes them through `read_receipts.delete`, the erasure's own
step, run with the bound its count has
([maintenance](/docs/operations/maintenance#erasure)):

- A user erasure: the reader's receipts stamped up to the second the erasure was
  recorded in, the census's predicate (`RECEIPT_READER_UP_TO`). The spellings are those
  the directory ties to the user when the command runs: a spelling it has dropped since
  the erasure is not matched, and an account it has tied to the user since has its
  receipts stamped up to that second deleted as the user's. When the directory cannot
  be read, the command counts and deletes nothing for that erasure and exits 1. The
  count reads `user_id` and `actor` of every receipt of the org under the DDL deadline,
  once for each erasure re-verified; with `--resume`, when the count is not zero, the
  step's delete and a recount read them again. `--org` and `--id` narrow a run.
- A namespace erasure: the receipts filed under the erased namespaces and stamped before
  the second the census finished in (`RECEIPT_NS_BEFORE`). A receipt stamped in that
  second or later stays: the namespace may hold other items by then. A read answered
  while the census ran is stamped before that second; it served an item written to the
  namespace after the erasure's steps, and its receipt is deleted too.

What a run does not reach:

- Nothing schedules the command. A receipt that lands after a run is found by the next
  one.
- The ledger lists an erasure for 89 days after its request; the table keeps a row 190
  days. An erasure that a restore replayed (`loom reconcile`) records no census time and
  is not listed.
- A read that began before the erasure and answered after the bound is stamped after it,
  and its receipt stays.
- Each bound compares a receipt's stamp, the clock of the replica that answered the
  read, with the clock of the process that recorded the erasure or ran its census, with
  no margin. A receipt stamped by a clock that runs ahead can fall after the bound and
  stay; one stamped by a clock that runs behind can fall before it and be deleted.

## 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`). 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](/docs/operations/upgrades#rollback)).

The run a row names differs by build too
([rolling upgrades](/docs/architecture/rolling-upgrades#the-rules), rule 76). Over MCP, an older build
labels no `knowledge.get`, `memory.get_by_id`, `memory.for_file` or `procedure.match`
with the session's run, and a run opened through it names no session run. It stores a
`metadata.session_run` a client sends, lets `run.complete` overwrite the stored one,
drops the server's on a begin sent again, and its truncation marker drops the key. No
gate holds the rollout for this: a run opened through an older replica is read by its
own id alone.

An older build also takes the caller of the session's run from every argument a call
names, where this build reads the keys the op's input declares (rule 78). Through an
older replica, a read that names a `user_id`, `session_id` or `read_scope` its op has no
field for is filed under `-` when that key resolves no read scope, a `knowledge.get`
that names the session of an `own_session` token begins a run, and the op ledger row of
a request that names a `run_id` its op has no field for names that run while its
receipts name the run bound to the request. No gate holds the rollout for this either,
and the rows an older build wrote stay as they are.

## 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.
- Over MCP the session's run labels every receipted op, not every call of one: an op
  whose input takes no `run_id` is in `_LABELLED_READS`, and
  [reading the table](#reading-the-table) lists the calls that are filed otherwise. A
  call has a caller for the session's run exactly when the read scope gate resolves its
  read scope from the op's input: an argument the input does not declare changes
  neither.
- An op that serves a run's receipts by `metadata.session_run` must scope them to what
  its caller may read itself: the value chooses which receipts, never whose. No op serves
  receipts by it.
- 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)
- `server/transport/mcp_runs.py` (`_LABELLED_READS`, `session_label`) and
  `server/tasks/domain/session_runs.py` (`session_run_of`): the run an MCP read is filed
  under
- `server/tasks/store/runs.py` (`receipted_items`, the statement `run.reliance` runs)
- `server/tasks/domain/reliance.py` (`revisions_of`, `reliance`: the states)

## Related

- [Memory architecture: erasure saga](/docs/architecture/memory-architecture#erasure-saga)
- [Rolling upgrades](/docs/architecture/rolling-upgrades)
- [Storage layout](/docs/architecture/storage-layout)
- [Runs](/docs/features/runs)
