diff --git a/docs/architecture/read-receipts.md b/docs/architecture/read-receipts.md index a683bde6c8..2f85aa3f0f 100644 --- a/docs/architecture/read-receipts.md +++ b/docs/architecture/read-receipts.md @@ -286,8 +286,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: @@ -443,6 +445,55 @@ When writing a statement over the table: `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. 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](clickhouse.md#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 @@ -675,6 +726,8 @@ own id alone. - `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 diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 8342975847..41cb3efc73 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 3dbacbd265..807abad98b 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -31,7 +31,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)). For a run opened over MCP, its session's reads made while it was open are there under the run's own id and under its session's run, except those filed under `-` or under another run @@ -130,6 +132,108 @@ 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 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 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 +``` + +```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 | 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). It is listed under the session's run, not under a run the agent opened with `run.begin`: that run lists the reads that name it, and its row names the session's run in `metadata.session_run`, which `run.get` returns ([MCP sessions](#mcp-sessions)). `run.reliance` reads the one id it is given and does not follow that key, so over MCP an agent calls it through `loom_op` once for each id, in the namespace that holds the run. | + +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 @@ -371,14 +475,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 and keeps its `metadata.session_run`, or names the calling MCP session's run when sent from another; 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 and keeps its `metadata.session_run`, or names the calling MCP session's run when sent from another; 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/knowledge-factory-workflow.md b/docs/guides/knowledge-factory-workflow.md index 15450b7811..9e771a574f 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/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index 9042e6c239..145edfe0ad 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -83,7 +83,7 @@ are on `agent.account` and `agent.deployment`. | Review queue (definitions) | `memory.definitions.list` | `agent.client.memory.definitions_list()` | | 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/operations/deployment.md b/docs/operations/deployment.md index 1aaabb0e94..2abe12e02c 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/docs/reference/configuration.md b/docs/reference/configuration.md index 05ff6ec9e7..2b8dd9871d 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/docs/reference/operations.md b/docs/reference/operations.md index 00f1235c5a..2306eb8e04 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 -387 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +388 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. @@ -711,6 +711,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 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 21c33e3f3b..03ef0e09b2 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 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 + +| 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 (content hash, version) pairs 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 2c165f5b1a..502cdb0a79 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -387 operations, 273 of them experimental. +388 operations, 274 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 1f93a10133..1eca83c16c 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) { @@ -1446,6 +1448,50 @@ function runRowsFixture(n: number, namespace: string): Record[] })); } +/** 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", + }, + ], +}; + /** `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`. */ diff --git a/frontend/e2e/runs.spec.ts b/frontend/e2e/runs.spec.ts index 03e52691d0..8bd87b5b0e 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([]); }); diff --git a/frontend/src/api/runs.test.ts b/frontend/src/api/runs.test.ts index ef0fa4d4dc..6d7b71209d 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 ba8f894c62..207bb9b363 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 0000000000..b476641557 --- /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 0000000000..98f229847f --- /dev/null +++ b/frontend/src/flows/RunReliance.tsx @@ -0,0 +1,222 @@ +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"; +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 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) => + [...(table?.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/format.test.ts b/frontend/src/lib/format.test.ts index 7363577623..44a53b4d88 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 5be28ec975..fefbb4e59c 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 0000000000..e98f928280 --- /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 0000000000..6632cbdb4c --- /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/lib/versionTime.test.ts b/frontend/src/lib/versionTime.test.ts new file mode 100644 index 0000000000..b10159b00e --- /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 0000000000..203c945e2f --- /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/Code.tsx b/frontend/src/views/Code.tsx index cce4caec31..b79747f466 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"; diff --git a/frontend/src/views/Runs.detail.test.tsx b/frontend/src/views/Runs.detail.test.tsx index 2e85d38cc9..dedad8ae5d 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 7194b8a112..9cf4032d42 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 62ce9b7cd2..17205dc0e0 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 ce191ae71a..a2873d1845 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 8cb429693a..1d250e6c06 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 b59bc67937..d84e855535 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/loom.example.yaml b/loom.example.yaml index 701871ecbc..2cd2e778ca 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/sdk/go/client.gen.go b/sdk/go/client.gen.go index 58cf76835f..8f4efe685d 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -2825,6 +2825,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 @@ -8159,6 +8171,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 de8083f52a..e570c3de4c 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: 3d28b5ff8c04d8ec257339bb43f11d5200b25670e5bf7dcb5dfd4e242d679a11 +// Registry model schema SHA-256: b16f6d929017e2e8c78f781b61ad1c470911724f386c47e92f1206c1222a6b95 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -11577,6 +11577,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/examples/knowledge_factory.py b/sdk/python/examples/knowledge_factory.py index a8e3f42568..de5c665860 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/sdk/python/loom/client.py b/sdk/python/loom/client.py index 2ef9d024b8..f0cb627e81 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -3133,6 +3133,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 9c02171f48..5bafc079a0 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -369,6 +369,7 @@ class OpSpec: "run.get", "run.grade", "run.list", + "run.reliance", "run.retract_credit", "search.query", "session.brief_delete", @@ -759,6 +760,7 @@ class OpSpec: "run.get", "run.grade", "run.list", + "run.reliance", "run.retract_credit", "search.query", "session.brief_delete", @@ -4779,6 +4781,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", @@ -19966,6 +19980,40 @@ class RunListOutput(TypedDict, total=False): total: NotRequired[Optional[int]] +class RunRelianceInput(TypedDict, total=False): + "What run `run_id` 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 run `run_id` 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 2e1d9fb38a..e1d938cc61 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 260d235de0..4fc8ed7b71 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 = 387 + OP_COUNT = 388 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -342,6 +342,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), @@ -2645,6 +2646,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 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) + 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 79f66646b6..edc64bf6d6 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -4730,6 +4730,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 dd3654c4e4..33163c5fc6 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -5061,6 +5061,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 6cdc749749..c667a6cafe 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -1434,6 +1434,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"], &[]), ( @@ -55144,22 +55145,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_2363")] - 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_2364")] - pub used_retracted: Integer, + pub revisions: Vec, #[serde(default = "default_2365")] - 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_2366")] - pub harm_retracted: Integer, + pub items: Vec, #[serde(default = "default_2367")] - 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_2368")] - pub more: bool, + pub run_id: String, #[serde(default = "default_2369")] + pub used_retracted: Integer, + #[serde(default = "default_2370")] + pub evidence_retracted: Integer, + #[serde(default = "default_2371")] + pub harm_retracted: Integer, + #[serde(default = "default_2372")] + pub events_written: Integer, + #[serde(default = "default_2373")] + pub more: bool, + #[serde(default = "default_2374")] pub dry_run: bool, } @@ -55316,39 +55401,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2372")] + #[serde(default = "default_2377")] pub content: String, - #[serde(default = "default_2373")] + #[serde(default = "default_2378")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2371")] + #[serde(default = "default_2376")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2374")] + #[serde(default = "default_2379")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2370")] - pub tracker: Option>, #[serde(default = "default_2375")] + pub tracker: Option>, + #[serde(default = "default_2380")] pub live: Option, - #[serde(default = "default_2376")] + #[serde(default = "default_2381")] pub memory: std::collections::HashMap, - #[serde(default = "default_2377")] + #[serde(default = "default_2382")] pub knowledge: std::collections::HashMap, - #[serde(default = "default_2378")] + #[serde(default = "default_2383")] pub profile: std::collections::HashMap, - #[serde(default = "default_2379")] + #[serde(default = "default_2384")] pub conversations: std::collections::HashMap, - #[serde(default = "default_2380")] + #[serde(default = "default_2385")] pub withheld: Option>, - #[serde(default = "default_2381")] + #[serde(default = "default_2386")] pub namespaces_skipped: Vec, } @@ -55552,7 +55637,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2382")] + #[serde(default = "default_2387")] pub revision: Integer, } @@ -55645,67 +55730,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2391")] + #[serde(default = "default_2396")] pub what: String, - #[serde(default = "default_2392")] + #[serde(default = "default_2397")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2394")] + #[serde(default = "default_2399")] pub tried: String, - #[serde(default = "default_2395")] + #[serde(default = "default_2400")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2397")] + #[serde(default = "default_2402")] pub what: String, - #[serde(rename = "ref", default = "default_2398")] + #[serde(rename = "ref", default = "default_2403")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2402")] + #[serde(default = "default_2407")] pub path: String, - #[serde(default = "default_2403")] + #[serde(default = "default_2408")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2388")] + #[serde(default = "default_2393")] pub goal: String, - #[serde(default = "default_2389")] + #[serde(default = "default_2394")] pub status: String, - #[serde(default = "default_2390")] + #[serde(default = "default_2395")] pub verification: String, - #[serde(default = "default_2393")] + #[serde(default = "default_2398")] pub decisions: Vec, - #[serde(default = "default_2396")] + #[serde(default = "default_2401")] pub dead_ends: Vec, - #[serde(default = "default_2399")] + #[serde(default = "default_2404")] pub done: Vec, - #[serde(default = "default_2400")] + #[serde(default = "default_2405")] pub open_questions: Vec, - #[serde(default = "default_2401")] + #[serde(default = "default_2406")] pub next_steps: Vec, - #[serde(default = "default_2404")] + #[serde(default = "default_2409")] pub files: Vec, - #[serde(default = "default_2405")] + #[serde(default = "default_2410")] pub constraints: Vec, - #[serde(default = "default_2406")] + #[serde(default = "default_2411")] pub pointers: Vec, - #[serde(default = "default_2407")] + #[serde(default = "default_2412")] pub client_summary: String, - #[serde(default = "default_2408")] + #[serde(default = "default_2413")] pub client_summary_at: String, } @@ -55713,45 +55798,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2383")] + #[serde(default = "default_2388")] pub brief_key: String, - #[serde(default = "default_2384")] + #[serde(default = "default_2389")] pub revision: Integer, - #[serde(default = "default_2385")] + #[serde(default = "default_2390")] pub snapshot_id: String, - #[serde(default = "default_2386")] + #[serde(default = "default_2391")] pub snapshot_key: String, - #[serde(default = "default_2387")] + #[serde(default = "default_2392")] pub rendered: String, - #[serde(default = "default_2409")] + #[serde(default = "default_2414")] pub sections: Option, - #[serde(default = "default_2410")] + #[serde(default = "default_2415")] pub project: String, - #[serde(default = "default_2411")] + #[serde(default = "default_2416")] pub branch: String, - #[serde(default = "default_2412")] + #[serde(default = "default_2417")] pub head_sha: String, - #[serde(default = "default_2413")] + #[serde(default = "default_2418")] pub author: String, - #[serde(default = "default_2414")] + #[serde(default = "default_2419")] pub trigger: String, - #[serde(default = "default_2415")] + #[serde(default = "default_2420")] pub actor: String, - #[serde(default = "default_2416")] + #[serde(default = "default_2421")] pub source_sessions: Vec, - #[serde(default = "default_2417")] + #[serde(default = "default_2422")] pub updated_at: Option, - #[serde(default = "default_2418")] + #[serde(default = "default_2423")] pub age_seconds: Integer, - #[serde(default = "default_2419")] + #[serde(default = "default_2424")] pub revisions: Integer, - #[serde(default = "default_2420")] + #[serde(default = "default_2425")] pub events_total: Integer, - #[serde(default = "default_2421")] + #[serde(default = "default_2426")] pub source_chars: Integer, - #[serde(default = "default_2422")] + #[serde(default = "default_2427")] pub brief_chars: Integer, - #[serde(default = "default_2423")] + #[serde(default = "default_2428")] pub deleted: bool, } @@ -55926,34 +56011,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2424")] + #[serde(default = "default_2429")] pub project: String, - #[serde(default = "default_2425")] + #[serde(default = "default_2430")] pub branch: String, - #[serde(default = "default_2426")] + #[serde(default = "default_2431")] pub agent: String, - #[serde(default = "default_2427")] + #[serde(default = "default_2432")] pub goal: String, - #[serde(default = "default_2428")] + #[serde(default = "default_2433")] pub status: String, - #[serde(default = "default_2429")] + #[serde(default = "default_2434")] pub author: String, - #[serde(default = "default_2430")] + #[serde(default = "default_2435")] pub actor: String, - #[serde(default = "default_2431")] + #[serde(default = "default_2436")] pub updated_at: Option, - #[serde(default = "default_2432")] + #[serde(default = "default_2437")] pub age_seconds: Integer, - #[serde(default = "default_2433")] + #[serde(default = "default_2438")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2434")] + #[serde(default = "default_2439")] pub briefs: Vec, - #[serde(default = "default_2435")] + #[serde(default = "default_2440")] pub rendered: String, } @@ -56093,25 +56178,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2439")] + #[serde(default = "default_2444")] pub events_in: Integer, - #[serde(default = "default_2440")] + #[serde(default = "default_2445")] pub windows: Integer, - #[serde(default = "default_2441")] + #[serde(default = "default_2446")] pub events_total: Integer, - #[serde(default = "default_2442")] + #[serde(default = "default_2447")] pub source_chars: Integer, - #[serde(default = "default_2443")] + #[serde(default = "default_2448")] pub brief_chars: Integer, - #[serde(default = "default_2444")] + #[serde(default = "default_2449")] pub compression_ratio: f64, - #[serde(default = "default_2445")] + #[serde(default = "default_2450")] pub dropped_ungrounded: Integer, - #[serde(default = "default_2446")] + #[serde(default = "default_2451")] pub tokens_in: Integer, - #[serde(default = "default_2447")] + #[serde(default = "default_2452")] pub tokens_out: Integer, - #[serde(default = "default_2448")] + #[serde(default = "default_2453")] pub llm_model: String, } @@ -56121,13 +56206,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2436")] + #[serde(default = "default_2441")] pub author: String, - #[serde(default = "default_2437")] + #[serde(default = "default_2442")] pub reason: String, - #[serde(default = "default_2438")] + #[serde(default = "default_2443")] pub rendered: String, - #[serde(default = "default_2449")] + #[serde(default = "default_2454")] pub stats: SessionBriefStats, } @@ -56872,39 +56957,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2450")] + #[serde(default = "default_2455")] pub reason: String, - #[serde(default = "default_2451")] + #[serde(default = "default_2456")] pub blocked_on: String, - #[serde(default = "default_2452")] + #[serde(default = "default_2457")] pub not_before: Option, - #[serde(default = "default_2453")] + #[serde(default = "default_2458")] pub resume_at: Option, - #[serde(default = "default_2454")] + #[serde(default = "default_2459")] pub deadline: Option, - #[serde(default = "default_2455")] + #[serde(default = "default_2460")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2456")] + #[serde(default = "default_2461")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2457")] + #[serde(default = "default_2462")] pub from_subject: String, - #[serde(default = "default_2458")] + #[serde(default = "default_2463")] pub origin: String, - #[serde(default = "default_2459")] + #[serde(default = "default_2464")] pub parent_task_id: Option, - #[serde(default = "default_2460")] + #[serde(default = "default_2465")] pub owner: String, - #[serde(default = "default_2461")] + #[serde(default = "default_2466")] pub attempt: Integer, - #[serde(default = "default_2462")] + #[serde(default = "default_2467")] pub fence: Integer, - #[serde(default = "default_2463")] + #[serde(default = "default_2468")] pub lease_until: Option, - #[serde(default = "default_2464")] + #[serde(default = "default_2469")] pub outcome: std::collections::HashMap, - #[serde(default = "default_2465")] + #[serde(default = "default_2470")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -56915,7 +57000,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2466")] + #[serde(default = "default_2471")] pub seq: Integer, } @@ -57316,10 +57401,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2467")] + #[serde(default = "default_2472")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2468")] + #[serde(default = "default_2473")] pub oldest: Option, } @@ -57406,7 +57491,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2469")] + #[serde(default = "default_2474")] pub next: String, } @@ -57745,7 +57830,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2470")] + #[serde(default = "default_2475")] pub task: Option, } @@ -57879,23 +57964,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2471")] + #[serde(default = "default_2476")] pub from_status: String, - #[serde(default = "default_2472")] + #[serde(default = "default_2477")] pub to_status: String, - #[serde(default = "default_2473")] + #[serde(default = "default_2478")] pub actor: String, - #[serde(default = "default_2474")] + #[serde(default = "default_2479")] pub agent: String, - #[serde(default = "default_2475")] + #[serde(default = "default_2480")] pub fence: Integer, - #[serde(default = "default_2476")] + #[serde(default = "default_2481")] pub version: Integer, - #[serde(default = "default_2477")] + #[serde(default = "default_2482")] pub reason: String, - #[serde(default = "default_2478")] + #[serde(default = "default_2483")] pub patch: std::collections::HashMap, - #[serde(default = "default_2479")] + #[serde(default = "default_2484")] pub note: String, pub ts: String, } @@ -58235,7 +58320,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2480")] + #[serde(default = "default_2485")] pub note: String, } @@ -58631,7 +58716,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2481")] + #[serde(default = "default_2486")] pub conflict: bool, } @@ -58994,19 +59079,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2482")] + #[serde(default = "default_2487")] pub intent: String, - #[serde(default = "default_2483")] + #[serde(default = "default_2488")] pub anchors: std::collections::HashMap, - #[serde(default = "default_2484")] + #[serde(default = "default_2489")] pub sections: Vec>, - #[serde(default = "default_2485")] + #[serde(default = "default_2490")] pub searched: Vec, - #[serde(default = "default_2486")] + #[serde(default = "default_2491")] pub lines: Vec, - #[serde(default = "default_2487")] + #[serde(default = "default_2492")] pub restricted: bool, - #[serde(default = "default_2488")] + #[serde(default = "default_2493")] pub verdict: String, } @@ -59102,17 +59187,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2489")] + #[serde(default = "default_2494")] pub tracker_namespace: String, - #[serde(default = "default_2490")] + #[serde(default = "default_2495")] pub tracker_namespaces: Vec, - #[serde(default = "default_2491")] + #[serde(default = "default_2496")] pub restricted: bool, - #[serde(default = "default_2492")] + #[serde(default = "default_2497")] pub kind: String, - #[serde(default = "default_2493")] + #[serde(default = "default_2498")] pub authorized: bool, - #[serde(default = "default_2494")] + #[serde(default = "default_2499")] pub templates: Vec, } @@ -59165,13 +59250,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2495")] + #[serde(default = "default_2500")] pub risk: std::collections::HashMap, - #[serde(default = "default_2496")] + #[serde(default = "default_2501")] pub open_issues: Vec>, - #[serde(default = "default_2497")] + #[serde(default = "default_2502")] pub known: bool, - #[serde(default = "default_2498")] + #[serde(default = "default_2503")] pub tracker_unavailable: bool, } @@ -59232,9 +59317,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2499")] + #[serde(default = "default_2504")] pub tables: Vec>, - #[serde(default = "default_2500")] + #[serde(default = "default_2505")] pub templates: std::collections::HashMap, } @@ -59287,66 +59372,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2511")] + #[serde(default = "default_2516")] pub status: String, - #[serde(default = "default_2512")] + #[serde(default = "default_2517")] pub reason: String, - #[serde(default = "default_2513")] + #[serde(default = "default_2518")] pub message: String, - #[serde(default = "default_2514")] + #[serde(default = "default_2519")] pub retried: bool, - #[serde(default = "default_2515")] + #[serde(default = "default_2520")] pub ms: Integer, - #[serde(default = "default_2516")] + #[serde(default = "default_2521")] pub cause: String, - #[serde(default = "default_2517")] + #[serde(default = "default_2522")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2501")] + #[serde(default = "default_2506")] pub verdict: String, - #[serde(default = "default_2502")] + #[serde(default = "default_2507")] pub items: Vec>, - #[serde(default = "default_2503")] + #[serde(default = "default_2508")] pub undecided: bool, - #[serde(default = "default_2504")] + #[serde(default = "default_2509")] pub epistemic: String, - #[serde(default = "default_2505")] + #[serde(default = "default_2510")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2506")] + #[serde(default = "default_2511")] pub judge: std::collections::HashMap, - #[serde(default = "default_2507")] + #[serde(default = "default_2512")] pub fit_at: String, - #[serde(default = "default_2508")] + #[serde(default = "default_2513")] pub fit: std::collections::HashMap, - #[serde(default = "default_2509")] + #[serde(default = "default_2514")] pub query: std::collections::HashMap, - #[serde(default = "default_2510")] + #[serde(default = "default_2515")] pub legs: std::collections::HashMap, - #[serde(default = "default_2518")] + #[serde(default = "default_2523")] pub leg_status: Vec, - #[serde(default = "default_2519")] + #[serde(default = "default_2524")] pub tracker_unavailable: bool, - #[serde(default = "default_2520")] + #[serde(default = "default_2525")] pub namespaces: Vec, - #[serde(default = "default_2521")] + #[serde(default = "default_2526")] pub by_namespace: std::collections::HashMap>, - #[serde(default = "default_2522")] + #[serde(default = "default_2527")] pub closest: Vec>, - #[serde(default = "default_2523")] + #[serde(default = "default_2528")] pub needs: Vec>, - #[serde(default = "default_2524")] + #[serde(default = "default_2529")] pub closest_note: String, - #[serde(default = "default_2525")] + #[serde(default = "default_2530")] pub nearest: Vec>, - #[serde(default = "default_2526")] + #[serde(default = "default_2531")] pub rerank: std::collections::HashMap, - #[serde(default = "default_2527")] + #[serde(default = "default_2532")] pub answer: String, - #[serde(default = "default_2528")] + #[serde(default = "default_2533")] pub related_prs: Vec>, } @@ -59553,17 +59638,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2529")] + #[serde(default = "default_2534")] pub known_flaky: bool, - #[serde(default = "default_2530")] + #[serde(default = "default_2535")] pub open_issues: Integer, - #[serde(default = "default_2531")] + #[serde(default = "default_2536")] pub issues: Vec>, - #[serde(default = "default_2532")] + #[serde(default = "default_2537")] pub verdict: String, - #[serde(default = "default_2533")] + #[serde(default = "default_2538")] pub tracker_unavailable: bool, - #[serde(default = "default_2534")] + #[serde(default = "default_2539")] pub signal: Option>, } @@ -59646,9 +59731,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2535")] + #[serde(default = "default_2540")] pub unknown: Vec, - #[serde(default = "default_2536")] + #[serde(default = "default_2541")] pub tracker_unavailable: bool, } @@ -59697,19 +59782,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2537")] + #[serde(default = "default_2542")] pub subject: std::collections::HashMap, - #[serde(default = "default_2538")] + #[serde(default = "default_2543")] pub verdict: String, - #[serde(default = "default_2539")] + #[serde(default = "default_2544")] pub items: Vec>, - #[serde(default = "default_2540")] + #[serde(default = "default_2545")] pub epistemic: String, - #[serde(default = "default_2541")] + #[serde(default = "default_2546")] pub record: std::collections::HashMap, - #[serde(default = "default_2542")] + #[serde(default = "default_2547")] pub computed_at: String, - #[serde(default = "default_2543")] + #[serde(default = "default_2548")] pub tracker_unavailable: bool, } @@ -59807,11 +59892,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2544")] + #[serde(default = "default_2549")] pub active_blockers: Integer, - #[serde(default = "default_2545")] + #[serde(default = "default_2550")] pub health: std::collections::HashMap, - #[serde(default = "default_2546")] + #[serde(default = "default_2551")] pub tracker_unavailable: bool, } @@ -59860,17 +59945,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2547")] + #[serde(default = "default_2552")] pub items: Vec>, - #[serde(default = "default_2548")] + #[serde(default = "default_2553")] pub query: std::collections::HashMap, - #[serde(default = "default_2549")] + #[serde(default = "default_2554")] pub legs: std::collections::HashMap, - #[serde(default = "default_2550")] + #[serde(default = "default_2555")] pub epistemic: String, - #[serde(default = "default_2551")] + #[serde(default = "default_2556")] pub tracker_unavailable: bool, - #[serde(default = "default_2552")] + #[serde(default = "default_2557")] pub namespaces: Vec, } @@ -59991,19 +60076,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2553")] + #[serde(default = "default_2558")] pub namespaces: Vec>, - #[serde(default = "default_2554")] + #[serde(default = "default_2559")] pub contract: std::collections::HashMap, - #[serde(default = "default_2555")] + #[serde(default = "default_2560")] pub roles: Vec, - #[serde(default = "default_2556")] + #[serde(default = "default_2561")] pub my_role: String, - #[serde(default = "default_2557")] + #[serde(default = "default_2562")] pub dry_run: bool, - #[serde(default = "default_2558")] + #[serde(default = "default_2563")] pub written: bool, - #[serde(default = "default_2559")] + #[serde(default = "default_2564")] pub view_templates: std::collections::HashMap, } @@ -60166,13 +60251,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2560")] + #[serde(default = "default_2565")] pub database: String, - #[serde(default = "default_2561")] + #[serde(default = "default_2566")] pub reachable: bool, - #[serde(default = "default_2562")] + #[serde(default = "default_2567")] pub contract: std::collections::HashMap, - #[serde(default = "default_2563")] + #[serde(default = "default_2568")] pub view_templates: std::collections::HashMap, } @@ -60212,11 +60297,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2564")] + #[serde(default = "default_2569")] pub tables: Vec>, - #[serde(default = "default_2565")] + #[serde(default = "default_2570")] pub roles: Vec, - #[serde(default = "default_2566")] + #[serde(default = "default_2571")] pub proposal: std::collections::HashMap, } @@ -60345,9 +60430,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2567")] + #[serde(default = "default_2572")] pub sources: Vec>, - #[serde(default = "default_2568")] + #[serde(default = "default_2573")] pub self_service: bool, } @@ -60400,9 +60485,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2569")] + #[serde(default = "default_2574")] pub deactivated: bool, - #[serde(default = "default_2570")] + #[serde(default = "default_2575")] pub namespaces_retired: Vec, } @@ -60443,9 +60528,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2571")] + #[serde(default = "default_2576")] pub contract: std::collections::HashMap, - #[serde(default = "default_2572")] + #[serde(default = "default_2577")] pub rotated_at: String, } @@ -60492,11 +60577,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2573")] + #[serde(default = "default_2578")] pub contract: std::collections::HashMap, - #[serde(default = "default_2574")] + #[serde(default = "default_2579")] pub dry_run: bool, - #[serde(default = "default_2575")] + #[serde(default = "default_2580")] pub written: bool, } @@ -60563,45 +60648,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2576")] + #[serde(default = "default_2581")] pub verdict: String, - #[serde(default = "default_2577")] + #[serde(default = "default_2582")] pub why: Vec, - #[serde(default = "default_2578")] + #[serde(default = "default_2583")] pub lower_bound: f64, - #[serde(default = "default_2579")] + #[serde(default = "default_2584")] pub window_days: Integer, - #[serde(default = "default_2580")] + #[serde(default = "default_2585")] pub since: String, - #[serde(default = "default_2581")] + #[serde(default = "default_2586")] pub features: std::collections::HashMap, - #[serde(default = "default_2582")] + #[serde(default = "default_2587")] pub infra: std::collections::HashMap, - #[serde(default = "default_2583")] + #[serde(default = "default_2588")] pub churn: std::collections::HashMap, - #[serde(default = "default_2584")] + #[serde(default = "default_2589")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2585")] + #[serde(default = "default_2590")] pub source: String, - #[serde(default = "default_2586")] + #[serde(default = "default_2591")] pub timings_ms: std::collections::HashMap, - #[serde(default = "default_2587")] + #[serde(default = "default_2592")] pub tracker_unavailable: bool, - #[serde(default = "default_2588")] + #[serde(default = "default_2593")] pub rollup: std::collections::HashMap, - #[serde(default = "default_2589")] + #[serde(default = "default_2594")] pub streak: std::collections::HashMap, - #[serde(default = "default_2590")] + #[serde(default = "default_2595")] pub smells: std::collections::HashMap, - #[serde(default = "default_2591")] + #[serde(default = "default_2596")] pub prior: std::collections::HashMap, - #[serde(default = "default_2592")] + #[serde(default = "default_2597")] pub unavailable_reason: String, - #[serde(default = "default_2593")] + #[serde(default = "default_2598")] pub candidates: Vec>, - #[serde(default = "default_2594")] + #[serde(default = "default_2599")] pub candidate_matches: Integer, - #[serde(default = "default_2595")] + #[serde(default = "default_2600")] pub resolved_from: String, } @@ -60705,9 +60790,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2596")] + #[serde(default = "default_2601")] pub recorded: bool, - #[serde(default = "default_2597")] + #[serde(default = "default_2602")] pub route: String, } @@ -60891,7 +60976,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2598")] + #[serde(default = "default_2603")] pub deliveries: Vec, } @@ -61013,14 +61098,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2599")] + #[serde(default = "default_2604")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2600")] + #[serde(default = "default_2605")] pub webhooks: Vec, } @@ -61202,7 +61287,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2601")] + #[serde(default = "default_2606")] pub fill_ratio: f64, } @@ -61426,15 +61511,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2602")] + #[serde(default = "default_2607")] pub content: String, - #[serde(default = "default_2603")] + #[serde(default = "default_2608")] pub char_limit: Integer, - #[serde(default = "default_2604")] + #[serde(default = "default_2609")] pub version: Integer, - #[serde(default = "default_2605")] + #[serde(default = "default_2610")] pub updated_at: Option, - #[serde(default = "default_2606")] + #[serde(default = "default_2611")] pub fill_ratio: f64, } @@ -61545,7 +61630,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2607")] + #[serde(default = "default_2612")] pub updated_at: Option, } @@ -61553,7 +61638,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2608")] + #[serde(default = "default_2613")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -69025,741 +69110,756 @@ fn default_2361() -> Vec { fn default_2362() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2363() -> String { +fn default_2363() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2364() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2365() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2366() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2367() -> bool { + serde_json::from_str("false").expect("schema default") +} +fn default_2368() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2364() -> Integer { +fn default_2369() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2365() -> Integer { +fn default_2370() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2366() -> Integer { +fn default_2371() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2367() -> Integer { +fn default_2372() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2368() -> bool { +fn default_2373() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2369() -> bool { +fn default_2374() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2370() -> Option> { +fn default_2375() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2371() -> LiveSearchResultsLive { +fn default_2376() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2372() -> String { +fn default_2377() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2373() -> LiveSearchHitLive { +fn default_2378() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2374() -> Vec { +fn default_2379() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2375() -> Option { +fn default_2380() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2376() -> std::collections::HashMap { +fn default_2381() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2377() -> std::collections::HashMap { +fn default_2382() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2378() -> std::collections::HashMap { +fn default_2383() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2379() -> std::collections::HashMap { +fn default_2384() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2380() -> Option> { +fn default_2385() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2381() -> Vec { +fn default_2386() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2382() -> Integer { +fn default_2387() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2383() -> String { +fn default_2388() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2384() -> Integer { +fn default_2389() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2385() -> String { +fn default_2390() -> String { 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() -> String { +fn default_2393() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2389() -> String { +fn default_2394() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2390() -> String { +fn default_2395() -> String { 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() -> String { +fn default_2399() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2395() -> String { +fn default_2400() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2396() -> Vec { +fn default_2401() -> Vec { 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() -> String { +fn default_2403() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2399() -> Vec { +fn default_2404() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2400() -> Vec { +fn default_2405() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2401() -> Vec { +fn default_2406() -> Vec { 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() -> Vec { +fn default_2409() -> Vec { 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() -> Vec { +fn default_2411() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2407() -> String { +fn default_2412() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2408() -> String { +fn default_2413() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2409() -> Option { +fn default_2414() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2410() -> String { +fn default_2415() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2411() -> String { +fn default_2416() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2412() -> String { +fn default_2417() -> String { serde_json::from_str("\"\"").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() -> Vec { +fn default_2421() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2417() -> Option { +fn default_2422() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2418() -> Integer { +fn default_2423() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2419() -> Integer { +fn default_2424() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2420() -> Integer { +fn default_2425() -> Integer { serde_json::from_str("0").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() -> bool { +fn default_2428() -> bool { serde_json::from_str("false").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() -> String { +fn default_2433() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2429() -> String { +fn default_2434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2430() -> String { +fn default_2435() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2431() -> Option { +fn default_2436() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2432() -> Integer { +fn default_2437() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2433() -> Integer { +fn default_2438() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2434() -> Vec { +fn default_2439() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2435() -> String { +fn default_2440() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2436() -> String { +fn default_2441() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2437() -> String { +fn default_2442() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2438() -> String { +fn default_2443() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2439() -> Integer { +fn default_2444() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2440() -> Integer { +fn default_2445() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2441() -> Integer { +fn default_2446() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2442() -> Integer { +fn default_2447() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2443() -> Integer { +fn default_2448() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2444() -> f64 { +fn default_2449() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2445() -> Integer { +fn default_2450() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2446() -> Integer { +fn default_2451() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2447() -> Integer { +fn default_2452() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2448() -> String { +fn default_2453() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2449() -> SessionBriefStats { +fn default_2454() -> 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_2450() -> String { +fn default_2455() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2451() -> String { +fn default_2456() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2452() -> Option { +fn default_2457() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2453() -> Option { +fn default_2458() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2454() -> Option { +fn default_2459() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2455() -> Integer { +fn default_2460() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2456() -> std::collections::HashMap { +fn default_2461() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2457() -> String { +fn default_2462() -> String { serde_json::from_str("\"\"").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() -> Integer { +fn default_2466() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2462() -> Integer { +fn default_2467() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2463() -> Option { +fn default_2468() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2464() -> std::collections::HashMap { +fn default_2469() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2465() -> String { +fn default_2470() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2466() -> Integer { +fn default_2471() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2467() -> String { +fn default_2472() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2468() -> Option { +fn default_2473() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2469() -> String { +fn default_2474() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2470() -> Option { +fn default_2475() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2471() -> String { +fn default_2476() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2472() -> String { +fn default_2477() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2473() -> String { +fn default_2478() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2474() -> String { +fn default_2479() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2475() -> Integer { +fn default_2480() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2476() -> Integer { +fn default_2481() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2477() -> String { +fn default_2482() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2478() -> std::collections::HashMap { +fn default_2483() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2479() -> String { +fn default_2484() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2480() -> String { +fn default_2485() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2481() -> bool { +fn default_2486() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2482() -> String { +fn default_2487() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2483() -> std::collections::HashMap { +fn default_2488() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2484() -> Vec> { +fn default_2489() -> Vec> { 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() -> Vec { +fn default_2491() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2487() -> bool { +fn default_2492() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2488() -> String { +fn default_2493() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2489() -> String { +fn default_2494() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2490() -> Vec { +fn default_2495() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2491() -> bool { +fn default_2496() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2492() -> String { +fn default_2497() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2493() -> bool { +fn default_2498() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2494() -> Vec { +fn default_2499() -> Vec { 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() -> Vec> { +fn default_2501() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2497() -> bool { +fn default_2502() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2498() -> bool { +fn default_2503() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2499() -> Vec> { +fn default_2504() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2500() -> std::collections::HashMap { +fn default_2505() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2501() -> String { +fn default_2506() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2502() -> Vec> { +fn default_2507() -> Vec> { 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() -> String { +fn default_2509() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2505() -> std::collections::HashMap { +fn default_2510() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2506() -> std::collections::HashMap { +fn default_2511() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2507() -> String { +fn default_2512() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2508() -> std::collections::HashMap { +fn default_2513() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2509() -> std::collections::HashMap { +fn default_2514() -> std::collections::HashMap { 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() -> String { +fn default_2516() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2512() -> String { +fn default_2517() -> String { 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() -> bool { +fn default_2519() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2515() -> Integer { +fn default_2520() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2516() -> String { +fn default_2521() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2517() -> String { +fn default_2522() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2518() -> Vec { +fn default_2523() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2519() -> bool { +fn default_2524() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2520() -> Vec { +fn default_2525() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2521() -> std::collections::HashMap> { +fn default_2526() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2522() -> Vec> { +fn default_2527() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2523() -> Vec> { +fn default_2528() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2524() -> String { +fn default_2529() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2525() -> Vec> { +fn default_2530() -> Vec> { serde_json::from_str("[]").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("\"\"").expect("schema default") } -fn default_2528() -> Vec> { +fn default_2533() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2529() -> bool { +fn default_2534() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2530() -> Integer { +fn default_2535() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2531() -> Vec> { +fn default_2536() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2532() -> String { +fn default_2537() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2533() -> bool { +fn default_2538() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2534() -> Option> { +fn default_2539() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2535() -> Vec { +fn default_2540() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2536() -> bool { +fn default_2541() -> bool { serde_json::from_str("false").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() -> String { +fn default_2543() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2539() -> Vec> { +fn default_2544() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2540() -> String { +fn default_2545() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2541() -> std::collections::HashMap { +fn default_2546() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2542() -> String { +fn default_2547() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2543() -> bool { +fn default_2548() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2544() -> Integer { +fn default_2549() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2545() -> std::collections::HashMap { +fn default_2550() -> std::collections::HashMap { 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() -> Vec> { +fn default_2552() -> Vec> { serde_json::from_str("[]").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() -> std::collections::HashMap { +fn default_2554() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2550() -> String { +fn default_2555() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2551() -> bool { +fn default_2556() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2552() -> Vec { +fn default_2557() -> Vec { 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() -> std::collections::HashMap { +fn default_2559() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2555() -> Vec { +fn default_2560() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2556() -> String { +fn default_2561() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2557() -> bool { +fn default_2562() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2558() -> bool { +fn default_2563() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2559() -> std::collections::HashMap { +fn default_2564() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2560() -> String { +fn default_2565() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2561() -> bool { +fn default_2566() -> bool { serde_json::from_str("true").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() -> std::collections::HashMap { +fn default_2568() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2564() -> Vec> { +fn default_2569() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2565() -> Vec { +fn default_2570() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2566() -> std::collections::HashMap { +fn default_2571() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2567() -> Vec> { +fn default_2572() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2568() -> bool { +fn default_2573() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2569() -> bool { +fn default_2574() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2570() -> Vec { +fn default_2575() -> Vec { 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() -> String { +fn default_2577() -> String { 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() -> bool { +fn default_2579() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2575() -> bool { +fn default_2580() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2576() -> String { +fn default_2581() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2577() -> Vec { +fn default_2582() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2578() -> f64 { +fn default_2583() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2579() -> Integer { +fn default_2584() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2580() -> String { +fn default_2585() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2581() -> std::collections::HashMap { +fn default_2586() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2582() -> std::collections::HashMap { +fn default_2587() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2583() -> std::collections::HashMap { +fn default_2588() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2584() -> std::collections::HashMap { +fn default_2589() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2585() -> String { +fn default_2590() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2586() -> std::collections::HashMap { +fn default_2591() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2587() -> bool { +fn default_2592() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2588() -> std::collections::HashMap { +fn default_2593() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2589() -> std::collections::HashMap { +fn default_2594() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2590() -> std::collections::HashMap { +fn default_2595() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2591() -> std::collections::HashMap { +fn default_2596() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2592() -> String { +fn default_2597() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2593() -> Vec> { +fn default_2598() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2594() -> Integer { +fn default_2599() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2595() -> String { +fn default_2600() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2596() -> bool { +fn default_2601() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2597() -> String { +fn default_2602() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2598() -> Vec { +fn default_2603() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2599() -> bool { +fn default_2604() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2600() -> Vec { +fn default_2605() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2601() -> f64 { +fn default_2606() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2602() -> String { +fn default_2607() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2603() -> Integer { +fn default_2608() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2604() -> Integer { +fn default_2609() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2605() -> Option { +fn default_2610() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2606() -> f64 { +fn default_2611() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2607() -> Option { +fn default_2612() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2608() -> Vec { +fn default_2613() -> 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 191f54d96d..7968b05515 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -8499,6 +8499,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 22156720cd..f89578f5be 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -9898,6 +9898,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; @@ -11382,6 +11406,7 @@ export type OpName = | "run.get" | "run.grade" | "run.list" + | "run.reliance" | "run.retract_credit" | "search.query" | "session.brief_delete" @@ -11772,6 +11797,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 }; @@ -12162,6 +12188,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 }, @@ -12225,4 +12252,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 387; +export const GENERATED_OP_COUNT = 388; diff --git a/server/observability/problems.py b/server/observability/problems.py index 2e5bb3da7a..865b30bebf 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", ) diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index 450a0060ef..65ae6f5294 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -1076,6 +1076,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 a4355121fb..91cf636841 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. @@ -6909,6 +6910,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 6035566a96..17817e6709 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 @@ -408,6 +410,56 @@ class RunGetOutput(BaseModel): over_budget: list[BudgetKind] = Field(default_factory=list) +class RunRelianceInput(BaseModel): + """What run `run_id` 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 (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 + + class RunListInput(BaseModel): org: str namespace: str diff --git a/server/tasks/api/ops_run.py b/server/tasks/api/ops_run.py index 79cb180639..b8144ee02f 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 feb4a01427..6398c597cf 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 @@ -52,11 +52,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 SESSION_RUN, is_session_run_id, session_run_of from server.tasks.store import runs as runs_store from server.tasks.store.rows import RunLedgerRow @@ -1195,6 +1200,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 0000000000..d87c90cf7f --- /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 b95c10cd5d..6ef752810a 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 @@ -16,17 +16,21 @@ 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 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,58 @@ 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 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. + # 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( + 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 +561,7 @@ async def live_memories_by_key( __all__ = [ "DERIVED_LIMIT", "LIST_ORDERS", + "RECEIPT_PAIRS", "RUN_COLUMNS", "RUN_TEXT_MATCH", "count_runs", @@ -513,6 +570,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 773a125ac6..a5f020b067 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 c4a8edbace..3e04485cab 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 84ff3d6cbd..c1ddc5f59e 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 = "" @@ -741,6 +744,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( @@ -1472,6 +1489,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 0000000000..ec5dba2e3a --- /dev/null +++ b/tests/integration/test_run_reliance.py @@ -0,0 +1,277 @@ +"""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 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 + +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_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 + + 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", "never_read"]) + + 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 + + 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( + 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 5d2230ac27..8634ab221d 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": "950106559dd036b3eddb0a47cc931fba6e033abe15f93fd98323452d26170f48", - "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 23492cbfac..3c3d882c0f 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -1732,6 +1732,10 @@ "body", "options" ], + "reliance": [ + "body", + "options" + ], "retract_credit": [ "body", "options" @@ -3624,6 +3628,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 0000000000..1d5cef50fa --- /dev/null +++ b/tests/unit/test_run_reliance.py @@ -0,0 +1,473 @@ +"""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 + +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 RunCompleteInput, 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)) + ) + + +# `-` 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 + + 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_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"])) + + 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_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. + 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 _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)] + 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_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 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 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 not honours_read_scope(op.name) + + +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_example_knowledge_factory.py b/tests/unit/test_sdk_example_knowledge_factory.py index bfe8b78e1e..0871b834ce 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") diff --git a/tests/unit/test_sdk_run_reliance.py b/tests/unit/test_sdk_run_reliance.py new file mode 100644 index 0000000000..5b6a4864e0 --- /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