diff --git a/docs/architecture/knowledge-reports.md b/docs/architecture/knowledge-reports.md new file mode 100644 index 0000000000..700f12ab4c --- /dev/null +++ b/docs/architecture/knowledge-reports.md @@ -0,0 +1,257 @@ +# Knowledge reports + +A knowledge report says that a memory claim or a document is incorrect or outdated, or +that the namespace is missing knowledge. Agents and clients file one with +`knowledge.reports.submit` when they find the problem while they work. A namespace's +admins are its maintainers: they read the queue with `knowledge.reports.list`, take a +report, ask for evidence, resolve it with the revision that corrected the target, or +dismiss it with a reason. A report never edits its target; the fix is an ordinary memory +or document write. + +```mermaid +flowchart LR + A["agent or client"] -->|"knowledge.reports.submit"| R["loom.knowledge_reports"] + R -->|"knowledge.reports.list / get"| M["maintainers (admins)"] + M -->|"knowledge.reports.update"| R + A -->|"knowledge.reports.evidence"| R +``` + +## Filing a report + +A report has a kind (`missing`, `incorrect` or `outdated`), the problem in the reporter's +words, an optional suggested correction and, except for missing knowledge, a target: + +| Target | `target_key` | `target_version` | `target_sha256` | +| ---------- | -------------- | ------------------ | ------------------------------------------- | +| `memory` | the memory key | the memory version | the `content_sha256` `memory.get` serves | +| `document` | the source URI | the revision | the `content_sha256` `knowledge.get` serves | + +A document report also names `target_doc_id`, the `doc_id` `knowledge.get` returned, +which says which copy at the address the reporter read (below). A revision or hash the +reporter did not say they read is stamped with what is there at submit. A client sends +only a hash an op returned, never one it computes. A document's is the hash its row +stores on every write, over its title and text in the form `knowledge.add` dedups on +(`sha256_document_text` in `server/core/hashing.py`), so an edit of the title alone also +marks the target changed. `knowledge.get` serves it as `content_sha256`; a report that +sends none takes the row's at submit. A row with no stored hash gives the +report none, and its revision alone says whether it changed. That includes a legacy +document at revision 0, which reads as changed once it has revision 1. A memory version +is a nanosecond timestamp above 2^53, which a JavaScript number rounds, so +`target_version` also takes a decimal string and a report carries `target_version_text`, +the same version as a string, as `memory.get` carries `version_text`. +Evidence is references only, `gap:`, `reflection:` or `run:`, at most 20 +distinct ones, never copied text. Each reference, and the report's `run_id`, is checked as +the caller would read what it points at (`server/knowledge/app/report_refs.py`): a run of +the namespace, the reflection memory at that key under the report's identity tuple, and a +gap of the latest build, which only namespace admins read, and only while +`knowledge.gaps.list` shows them one (`listed` in `server/knowledge/app/gaps.py`): with +gaps or query capture off, a build stored until its TTL ends is not read. A write that +cites one the caller cannot read is refused as not found, and a read serves only those +the caller can read then. Related reports name other report ids of the namespace that +the caller reads as `get` decides it: their own, or any for a maintainer. Another +reporter's report is refused as a missing one is, so a link never says whether an id +exists. The rules are in `server/knowledge/domain/reports.py`; a broken report is a 422. + +The reporter is the person the token stands for, as knowledge gaps count askers +(`token_person` and `folded_person` in `server/knowledge/app/people.py`): the token's end +user, else its creator, folded onto one spelling per person. A token no person stands +behind, such as an agent's own account, reports under its own principal. When the +service-account registry or the directory cannot be read the request is a 503 to retry, +never filed under the account itself, and a token tied to two accounts +is a 403; neither is filed or matched under another spelling, since the report id and the +reporter checks would stop matching once the person folds. Reads and evidence resolve the +caller before the report, so neither answer says whether it exists; a namespace admin whose +person cannot be folded still reads as a maintainer, unmatched as the reporter. With auth +off no token names a caller, so every caller is the reporter, as every caller is a +maintainer. + +The caller must be able to read the target: a memory key is read as `memory.get` reads it +under the body's identity tuple (`readable_version` in `server/memory/app/handlers.py`, +which serves nothing of the row), a document as `knowledge.get` reads it. A target the +caller cannot read answers 404, as a missing one does. `memory.get` falls back to the same +user's row under another agent or session, so a memory report takes the identity tuple of +the row the key was found in, and every later read of its target reads that row alone. An +`agent` of `*` reads the key across users, so only a row of the body's `user_id` counts: +another user's row answers 404, as the fallback never finds one. Any other report keeps +the body's `agent`, `user_id` and `session_id`. Neither tuple is the reporter. A first +filing whose `target_version` or `target_sha256` the row found now does not hold answers +409 `PRECONDITION_FAILED` and writes nothing: the reporter read another row of the key, +such as the one the fallback found before the caller's own row was written, or an older +version, and their words would be bound to this row. + +`knowledge.get` answers an address with the namespace's own document, else the newest +mirrored copy the caller may see, so the document at an address can change without any +write to it. A document report keeps the copy it was read in, `target_copy`: empty for the +namespace's own document, else the mirrored copy's `/` +(`document_copy` in `server/knowledge/app/document_reads.py`). Every later read of its +target reads that copy alone, so a document that appears at the same address later is +never taken for it. A first filing answers 409 `PRECONDITION_FAILED` when the document +found now is not the `target_doc_id` the reporter read, or holds another revision or +hash than the body names: the reporter read another copy at the address, or an older +revision, and their words would be bound to this one. Each copy counts revisions from 1, +and two copies can hold the same text, so neither the revision nor the hash names a +copy. Every write of a document's text gets a new `doc_id`, so the `doc_id` does. + +The report id is a hash of the org, namespace, reporter, kind, target and problem text +(whitespace folded), and for a memory target the found row's identity tuple. A document's +copy is not part of it: the copies visible at an address change between a filing and its +retry, so a repeat finds the report after its copy is gone or another copy appears, and +never files a second report against that other copy. The same reporter filing the same +problem about the same target gets the same report back, with or without an +Idempotency-Key, and two agents whose reads find one row file one report. A repeat returns +the report as it stands, bound to the copy or row it was filed about, resolved or +dismissed included: a maintainer reopens it. A repeat after its memory target is gone +finds the report only when the key was in the row of the body's own tuple, since no read +then says which row it was. Nor does a repeat find a report filed on another agent's or +session's row once the caller's own row is written at the key: the read then finds the +new row, so a repeat that names the version it read answers 409, and one that names +none files a report on the new row. A retry with the same Idempotency-Key replays the +first answer either way. + +## Reading reports + +`knowledge.reports.get` serves a report to its reporter and to the namespace's admins; +anyone else is answered not found. Each get checks the target again: `target_changed` +is true when its version or hash differs from what the report holds, or it is gone. A +caller who cannot read the target now sees the report with `target_readable` false and +without the words written about it, which may quote it: the problem, the correction and +a maintainer's reason. The reporter still reads their own problem and correction. +Evidence and related reports are served only while the caller reads what they point at. + +A mirrored copy's access list can change with each revision its source publishes, and no +copy keeps the list of an earlier revision, so reading the copy now does not prove the +caller could read the revision reported. Once the copy holds another revision or hash +(`target_changed`), its report's words are left out for every caller, the reporter's own +problem and correction aside, while `target_readable` stays true. A change to its access +list alone keeps the revision, and with it the words: they quote text the caller reads +now. The namespace's own documents and memory rows have the same readers at every +version, so a change to one of them keeps the words. + +A mirrored document's address belongs to its readers ([document sources](document-sources.md)). +An admin who may not know of a report's document sees no `target_key`, revision or +resolution for it: `known_documents` (`server/knowledge/app/document_reads.py`) knows a +report's copy when it is the namespace's own document, deleted ones included, or a +mirrored copy the caller's access list admits now. Another document at the same address +does not count. A page's own documents are checked from their row versions and its +mirrored copies together from their metadata, without reading any text, and a failed +check admits none. The reporter wrote the +address, so always reads it. + +Each mirrored copy a read admits, for its words or only for its address, keeps its proof +with the response (`source_publication`). The proof is checked again before the response +is sent, as for `knowledge.get` and `knowledge.list`, so access that ends after the read +refuses the response. Submit and update read the target only to check it and answer +nothing of it, so no proof goes with their answer: a version already written is never +answered as refused. + +`knowledge.reports.list` is the admins' queue, newest change first, filtered by state, +kind, target, assignee or reporter. Its rows carry no one's words and read no target, so +they carry no `target_changed`: both are read one report at a time. A row about a +document the admin may not know of carries no address, and a `target_key` filter finds +no report about one. That filter reads which copies of the address the reports are +about (`copies_at`, with sequential consistency, so no acknowledged report is missed), +keeps the ones the admin may know of and filters on them before the `limit`, so a newer +report about a hidden copy at the same address never empties a page. That check keeps no +proof. The copies of the rows on the page are checked again with their proofs, so access +to a copy the page leaves out never refuses it, and a row whose copy that second check +no longer admits leaves the page. A `memory` filter reads no copies. The queue is not +idempotent on the wire, so its answer never enters the replay cache: a stored page would +serve mirrored addresses without their proofs, and a retry reads the queue again. + +## Maintainers' actions + +`knowledge.reports.update` (admin, audited) applies one action and may link related +reports: + +| Action | From | To | Needs | +| ------------------ | ----------------------------- | ---------------- | ----------------------------- | +| `take` | any but resolved or dismissed | `taken` | sets the assignee | +| `release` | `taken` | `open` | clears the assignee | +| `request_evidence` | any but resolved or dismissed | `needs_evidence` | a reason | +| `resolve` | any but resolved or dismissed | `resolved` | `resolution_revision` | +| `dismiss` | any but resolved or dismissed | `dismissed` | a reason | +| `reopen` | `resolved` or `dismissed` | `open` | a reason; clears the assignee | + +`resolution_revision` names the published revision that corrected the target, not a +draft or a recommendation: for a report about a memory claim or a document, the revision +number readers are served now, which must be newer than the reported one. Memory versions +come from the clock, so a number between the two may never have been published. An +unchanged or gone target is not resolved (dismiss it with a reason). A report with no +target has no revision to check, so its resolution is the maintainer's words, and +`reason_by` names who wrote them as it does a reason. An action with words of its own (a +reason, or that resolution) replaces the reason and `reason_by`. One without, such as +`take`, `release` or the resolution of a report about a target, carries them forward, so +a question asked with `request_evidence` stays after the report is released. `reopen` +clears the assignee and the resolution. `expected_version` refuses an update made from a +stale read (409). + +`knowledge.reports.evidence` lets the reporter add references to their own report; any +other caller is answered not found, also while another change holds the report's claim, +since the reporter is checked before the claim. A report waiting for evidence goes back +to `taken` when a maintainer holds it, else to `open`. + +## Storage + +`loom.knowledge_reports` is a `ReplacingMergeTree(version)` sorted by +`(org, namespace, report_id)`: submit writes version 1 and every change the next version +of the whole row, read with `FINAL` (`server/knowledge/store/reports.py`). Each change is +a read, then a write, under the report's claim (`leases.holding`), so two writers never +both build on the same version; the second is told to retry (503). Each version is +inserted synchronously and every read, the queue included, uses +`select_sequential_consistency`, so the next read on any replica sees it. + +Every version carries the `actor` and `source_class` of the write that made it, stamped by +the server from the token (`writer_actor`, `source_class_for(default="asserted")`), never +from the body: a maintainer's change names the maintainer, added evidence the reporter. +`written_by` holds the person that token stands for, folded as the reporter is, so a +service account's version names its creator while its `actor` names the account. With +auth off the writer is the agent that filed the report, or `-` for an update. + +## Read scope + +A token bounded below the namespace (`read_scope` `own_user` or `own_session`) cannot call +`knowledge.reports.*` (`NARROW_REFUSED_PREFIXES` in `server/identity/domain/read_scope.py`): +the queue and a report hold other people's words. + +## Erasure + +A user erasure deletes every version of the reports the user filed, as reporter or under +their `user_id`, by the same spellings it erases knowledge gaps with. On the reports the +user maintained it clears, in every version, what names them or is their words: the +assignee, the writer's `actor` and `written_by` (matched on `written_by`, so a write +through the user's service account or as an end user is found), a `reason`, and the +resolution of a report with no target. `reason_by` names who wrote those words, since +later versions carry them forward under another writer, such as a maintainer who only +links a related report. A target's resolution is a checked revision number and stays. The +reporter's words stay +(`delete_knowledge_reports_by_user` in `server/erasure/store/steps_ledgers.py`). A +namespace erasure deletes the namespace's reports. The residue census counts both scopes. +The steps and the census count reports with `select_sequential_consistency`: on a replica +that has not fetched an acknowledged report, a count of zero would skip the step's +mutation and record no residue. +Deleting a memory, a document or a source deletes no report: a report copies nothing from +its target, which then reads as gone, so only the reporter reads the report's words. + +Each write takes the org's durable write fence (`writer_lease_name` in +`server/knowledge/domain/reports.py`), which both report erasure steps take too. Inside it, +while an erasure is unfinished, or has finished since the request started (`erasure_since`, +as knowledge gaps use), that reaches the report's namespace, its reporter, its user, its +assignee, the author of a reason the write carries forward or the writing maintainer, +submit, update and evidence answer 409 `ERASURE_RUNNING`. An insert whose outcome is +unknown, a cancelled send included, keeps the fence until its send bound passes, so an +erasure step never runs before a version that may still land. + +## Rolling upgrades + +An older build's erasure saga has no step for `loom.knowledge_reports`, so no report is +written while such a replica serves: while any live replica of any deployment kind +sharing the database has a schema below the migration that adds the table, or no +heartbeat can be read, submit, update and evidence answer 503 +(`every_replica_stores_reports` in `server/knowledge/app/reports.py`), as knowledge gaps +do ([rolling upgrades](rolling-upgrades.md)). Before a rollback, the +operator deletes the table's rows, and again after the first older replica serves. + +## Dashboard + +No dashboard page serves reports: maintainers read and act on them through the API, the +SDKs and `loom_op` (`NOT_IN_DASHBOARD` in `server/operations/dashboard.py`). diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 53e1085281..3076c199a5 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1657,6 +1657,17 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `frontend/src/views/assistant/cards/WorklistCard.test.tsx` checks N's card, and the mixed-version gate does not check this rule. +101. **Knowledge reports** (`loom.knowledge_reports`, migration + `137_knowledge_reports.sql`): N-1's erasure saga has no step for the table. So while + any live replica, in every deployment sharing the database, has a schema version + below 137, or no heartbeat has been read, `knowledge.reports.submit`, `update` and + `evidence` answer 503, as knowledge gaps do under rule 48; N-1 serves no + `knowledge.reports.*` op. Before a rollback, delete the table's rows, then delete + again after the first N-1 replica serves + ([knowledge reports](knowledge-reports.md#rolling-upgrades)). + `tests/unit/test_knowledge_reports.py` checks the refusal; the mixed-version gate + does not. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md index 74cca89140..eb078443dd 100644 --- a/docs/architecture/storage-layout.md +++ b/docs/architecture/storage-layout.md @@ -1068,6 +1068,7 @@ it holds no provider identity or credential. | `knowledge_suites` | MT `(org, namespace, suite, revision)` | Postgres `knowledge_suites` | SoR | census, `knowledge_suites.delete` | 3 | a namespace's regression suites, one row per published revision: a publish names the revision it was made from, a compare-and-set under a claim on the namespace's suites; `cases` holds the case text; named in `server/knowledge/store/suites.py`, `server/erasure/store/steps_ledgers.py` | | `knowledge_suite_results` | MT `(org, namespace, memory_key, suite, recorded_at)` | Postgres `knowledge_suite_results` | SoR | census, `knowledge_suites.delete` | 3 | the result sets a runner recorded for a suite's cases, one row per run for one content of a memory key: insert only, read by memory key and suite; it holds case ids and outcomes and no case text, and `config` values are free text; named in `server/knowledge/store/suite_results.py`, `server/erasure/store/steps_ledgers.py` | | `knowledge_suite_drafts` | MT `(org, namespace, suite, case_id, drafted_at)` | Postgres `knowledge_suite_drafts` | SoR | census, `knowledge_suites.delete` | 3 | the draft cases writers filed for a suite, and their dismissals: insert only, one row per draft and one more with empty `content` when it is dismissed; a draft is pending while no row of its id is a dismissal and no revision of the suite holds its id, which each read derives; `content` holds the case text, a dismissed draft's included; named in `server/knowledge/store/suite_drafts.py`, `server/erasure/store/steps_ledgers.py` | +| `knowledge_reports` | RMT(version) `(org, namespace, report_id)` | stays | SoR | census, `knowledge_reports.delete`, user scope too | — | problem reports on memory claims and document passages, the reporter's words and references to gaps, reflections and runs, never copied text; a user erasure deletes the reports the user filed and clears what names the user or is their words on the others ([knowledge reports](knowledge-reports.md#erasure)); named in `server/knowledge/store/reports.py`, `server/erasure/store/steps_ledgers.py` | | `conversations` | MT `(org, namespace, thread_id, ts, msg_id)`, by `toYYYYMM(ts)` | stays + Postgres `conversation_states` | SoR | census, `conversations.tombstone`, user scope too | 3 | messages, an append log read by scans; their tombstones and saved state move to Postgres `conversation_states` in wave 3 ([conversation state](#conversation-state)); named in `server/knowledge/store/conversations.py`, `server/erasure/store/exports.py` | | `conversation_threads` | RMT(updated_at) `(org, namespace, thread_id)`, by `toYYYYMM(created_at)` | stays | SoR | census, `conversations.tombstone`, user scope too | — | threads: the title, metadata and `run_id` a caller sets with `conversation.create` and `conversation.update`, and a model title for an untitled thread, with no TTL; it stays because its tombstones must reach every version of the row, as today's mutations do, and no reader needs a Postgres commit of it; an update merges onto the row it reads, so a write racing another write can lose a field, and one racing a thread delete or an erasure brings the thread back, a race of today's code that no wave changes ([conversation state](#conversation-state)); named in `server/knowledge/store/conversations.py`, `server/erasure/store/exports.py` | | `conversation_embeddings` | RMT(ts) `(org, namespace, embedding_model, thread_id, msg_id)`, by `toYYYYMM(ts)` | stays | Derived, SoR past its source's retention | census, `conversations.tombstone`, user scope too | — | message vectors, rebuildable at embedding cost while their messages are retained; it has no TTL, so past `conversations` retention its excerpt, vector and saved state are the only copy; its saved state and saver stay on its own rows as version-row inserts from wave 3 ([conversation state](#conversation-state)); named in `server/knowledge/store/conversations.py`, `server/erasure/store/mutations.py` | diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index bf6d09861a..bc82589dd8 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -88,30 +88,35 @@ a section the unit of retrieval, and the breadcrumb tells a hit where it came fr All operations are in the [knowledge group](../reference/operations.md#knowledge) of the operations reference. -| Operation | Role | Does | -| --------------------------- | ------ | -------------------------------------------------------------------------------------- | -| `knowledge.add` | writer | Store one document and its chunks. | -| `knowledge.bulk_add` | writer | Store up to 500 documents in one call; the same per-document behaviour as `add`. | -| `knowledge.upsert` | writer | Add or replace the document at a `source_uri`; earlier chunks are superseded. | -| `knowledge.search` | viewer | Hybrid passage search (vector, BM25 and exact keys fused). | -| `knowledge.get` | viewer | One document's full text and metadata by `source_uri`. | -| `knowledge.list` | viewer | Documents of one or more namespaces in cursor pages, filterable by tag and URI prefix. | -| `knowledge.outline` | viewer | A document's table of contents, and optionally one section's assembled text. | -| `knowledge.synthesize` | viewer | Complete a task over whole documents, or calculate over datasets, with the LLM. | -| `knowledge.citations.check` | viewer | Whether each quote is in the document revision it cites ([below](#checking-a-quote)). | -| `knowledge.update_metadata` | writer | Edit `title`, `description` or `tags`; `reindex=true` rewrites the chunks' context. | -| `knowledge.delete` | writer | Supersede a document and its chunks. | -| `knowledge.bulk_delete` | writer | The same for up to 500 `source_uris`. | -| `knowledge.restore` | writer | Undo a delete: the document's last version and its chunks are live again. | -| `knowledge.reads` | viewer | How often agents opened each document over the last `days` (1–30). | -| `knowledge.inspect` | viewer | A report on the namespace's documents ([below](#inspecting-a-namespaces-documents)). | -| `knowledge.dedup_list` | admin | Documents (and, optionally, chunks) of the namespace with identical content hashes. | -| `knowledge.dedup_resolve` | admin | Supersede one side of a duplicate pair. | -| `knowledge.ingest` | writer | Extract an uploaded file and publish it as a document revision (a job). | -| `knowledge.ingest_status` | viewer | A job's state, stage, coverage, warnings, failure and published revision. | -| `knowledge.ingest_cancel` | writer | Stop a job before it publishes. | -| `knowledge.formats` | viewer | The formats an ingest reads, the names that select each, and the upload's limits. | -| `knowledge.gaps.list` | admin | Questions several users asked that nothing answered ([below](#knowledge-gaps)). | +| Operation | Role | Does | +| ---------------------------- | ------ | -------------------------------------------------------------------------------------------------------------- | +| `knowledge.add` | writer | Store one document and its chunks. | +| `knowledge.bulk_add` | writer | Store up to 500 documents in one call; the same per-document behaviour as `add`. | +| `knowledge.upsert` | writer | Add or replace the document at a `source_uri`; earlier chunks are superseded. | +| `knowledge.search` | viewer | Hybrid passage search (vector, BM25 and exact keys fused). | +| `knowledge.get` | viewer | One document's full text and metadata by `source_uri`. | +| `knowledge.list` | viewer | Documents of one or more namespaces in cursor pages, filterable by tag and URI prefix. | +| `knowledge.outline` | viewer | A document's table of contents, and optionally one section's assembled text. | +| `knowledge.synthesize` | viewer | Complete a task over whole documents, or calculate over datasets, with the LLM. | +| `knowledge.citations.check` | viewer | Whether each quote is in the document revision it cites ([below](#checking-a-quote)). | +| `knowledge.update_metadata` | writer | Edit `title`, `description` or `tags`; `reindex=true` rewrites the chunks' context. | +| `knowledge.delete` | writer | Supersede a document and its chunks. | +| `knowledge.bulk_delete` | writer | The same for up to 500 `source_uris`. | +| `knowledge.restore` | writer | Undo a delete: the document's last version and its chunks are live again. | +| `knowledge.reads` | viewer | How often agents opened each document over the last `days` (1–30). | +| `knowledge.inspect` | viewer | A report on the namespace's documents ([below](#inspecting-a-namespaces-documents)). | +| `knowledge.dedup_list` | admin | Documents (and, optionally, chunks) of the namespace with identical content hashes. | +| `knowledge.dedup_resolve` | admin | Supersede one side of a duplicate pair. | +| `knowledge.ingest` | writer | Extract an uploaded file and publish it as a document revision (a job). | +| `knowledge.ingest_status` | viewer | A job's state, stage, coverage, warnings, failure and published revision. | +| `knowledge.ingest_cancel` | writer | Stop a job before it publishes. | +| `knowledge.formats` | viewer | The formats an ingest reads, the names that select each, and the upload's limits. | +| `knowledge.gaps.list` | admin | Questions several users asked that nothing answered ([below](#knowledge-gaps)). | +| `knowledge.reports.submit` | writer | Report a memory claim or document as wrong or outdated, or knowledge as missing ([below](#knowledge-reports)). | +| `knowledge.reports.get` | viewer | One report, for its reporter or an admin. | +| `knowledge.reports.list` | admin | The namespace's report queue, without anyone's words. | +| `knowledge.reports.update` | admin | Take, release, ask for evidence on, resolve, dismiss or reopen a report. | +| `knowledge.reports.evidence` | writer | The reporter adds evidence references to their own report. | `knowledge.search` and `knowledge.reads` are hidden from MCP: neither is listed, and `loom_op` refuses them too. An agent reaches the knowledge plane through @@ -2434,6 +2439,24 @@ curl -s localhost:7777/v1/knowledge.gaps.list -H "Authorization: Bearer $LOOM_AP How misses are recorded and grouped, their erasure and their rolling-upgrade notes are in [knowledge gaps](../architecture/knowledge-gaps.md). +## Knowledge reports + +An agent or client that finds a memory claim or a document wrong or outdated, or finds +knowledge missing, files a report with `knowledge.reports.submit`. A report never edits +its target. The namespace's admins read the queue with `knowledge.reports.list`, open a +report with `knowledge.reports.get`, and take, resolve with the revision that fixed the +target, or dismiss it with `knowledge.reports.update`. A reporter adds evidence to their +own report with `knowledge.reports.evidence`. + +```bash +curl -s localhost:7777/v1/knowledge.reports.submit -H "Authorization: Bearer $LOOM_API_KEY" \ + -H 'content-type: application/json' \ + -d '{"org":"dev","namespace":"local","agent":"cli","kind":"outdated","target_kind":"memory","target_key":"pricing/plan","problem":"The plan price changed."}' +``` + +The reporter, the read checks, the states and their erasure are in +[knowledge reports](../architecture/knowledge-reports.md). + ## Settings | Setting | Effect | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 91e85fb152..778c924ba7 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 -421 operations in 46 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +426 operations in 46 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. @@ -453,6 +453,11 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.query_history.list`](operations/knowledge.md#knowledgequery_historylist) | List the namespace's registered query-history sources. | admin | idempotent | no | | | [`knowledge.query_history.remove`](operations/knowledge.md#knowledgequery_historyremove) | Remove a query-history source registration from the namespace. | admin | idempotent | no | yes | | [`knowledge.reads`](operations/knowledge.md#knowledgereads) | How often agents opened each document over the last `days` (`knowledge.get` ledger rows; dashboard, assistant and bench traffic left out). | viewer | read | no | | +| [`knowledge.reports.evidence`](operations/knowledge.md#knowledgereportsevidence) | The reporter adds evidence to their own report, for example after a maintainer asked for it. | writer | write | no | | +| [`knowledge.reports.get`](operations/knowledge.md#knowledgereportsget) | One report, with the problem, the suggested correction and the evidence, when you can read its target. | viewer | read | no | | +| [`knowledge.reports.list`](operations/knowledge.md#knowledgereportslist) | The namespace's report queue for maintainers, newest change first. | admin | write | no | | +| [`knowledge.reports.submit`](operations/knowledge.md#knowledgereportssubmit) | Report that a memory claim or a document passage is incorrect or outdated, or that knowledge is missing. | writer | idempotent | no | | +| [`knowledge.reports.update`](operations/knowledge.md#knowledgereportsupdate) | A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens a report, or links related reports. dismiss, request_evidence and reopen need a reason. resolve names the published… | admin | write | no | yes | | [`knowledge.restore`](operations/knowledge.md#knowledgerestore) | Undo a `knowledge.delete` or `knowledge.bulk_delete` of one document. | writer | idempotent | no | yes | | [`knowledge.search`](operations/knowledge.md#knowledgesearch) | Search the user's uploaded document library — bills, contracts, receipts, resumes, policies, manuals, technical docs. | viewer | read | no | | | [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd) | Register a document source on a namespace, read with a shared credential, the caller's connected account, or a delegated Workspace crawl. | writer | write | no | yes | diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 3d7990d932..c85f804aa7 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -571,6 +571,118 @@ How often agents opened each document over the last `days` (`knowledge.get` ledg | `window_days` | `int` | The look-back window the counts cover, in days, after clamping to 1-30. | | `reads` | `list[dict[str, Any]]` | [{source_uri, reads, agents, last_read_at}], most read first | +## `knowledge.reports.evidence` + +The reporter adds evidence to their own report, for example after a maintainer asked for it. + +`POST /v1/knowledge.reports.evidence` · MCP `loom_knowledge_reports_evidence` · role `writer` · write · 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. | +| `report_id` | `str` | required | | +| `evidence` | `list[str]` | required | References only, never copied text: gap:, reflection: or run:. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `report_id` | `str` | | +| `state` | `Literal['open', 'taken', 'needs_evidence', 'resolved', 'dismissed']` | | +| `version` | `int` | | + +## `knowledge.reports.get` + +One report, with the problem, the suggested correction and the evidence, when you can read its target. + +`POST /v1/knowledge.reports.get` · MCP `loom_knowledge_reports_get` · 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. | +| `report_id` | `str` | required | | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `found` | `bool` | | +| `report` | `KnowledgeReportDetail \| None` | | + +## `knowledge.reports.list` + +The namespace's report queue for maintainers, newest change first. + +`POST /v1/knowledge.reports.list` · MCP `loom_knowledge_reports_list` · role `admin` · write · 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. | +| `states` | `list[Literal['open', 'taken', 'needs_evidence', 'resolved', 'dismissed']]` | *(computed)* | | +| `kinds` | `list[Literal['missing', 'incorrect', 'outdated']]` | *(computed)* | | +| `target_kind` | `Literal['', 'memory', 'document']` | `''` | | +| `target_key` | `str` | `''` | | +| `assignee` | `str` | `''` | | +| `reporter` | `str` | `''` | | +| `limit` | `int` | `50` | | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `reports` | `list[KnowledgeReport]` | | + +## `knowledge.reports.submit` + +Report that a memory claim or a document passage is incorrect or outdated, or that knowledge is missing. + +`POST /v1/knowledge.reports.submit` · MCP `loom_knowledge_reports_submit` · role `writer` · idempotent · 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. | +| `agent` | `str` | `'-'` | The writing or reading agent; `'-'` or `'*'` means any agent where the op allows it. | +| `user_id` | `str` | `'-'` | The end user the row belongs to; `'-'` for none. | +| `session_id` | `str` | `'-'` | The session or conversation the row belongs to; `'-'` for none. | +| `run_id` | `str` | `''` | The run that hit the problem. | +| `kind` | `Literal['missing', 'incorrect', 'outdated']` | required | | +| `target_kind` | `Literal['', 'memory', 'document']` | `''` | memory or document; empty for a missing-knowledge report. | +| `target_key` | `str` | `''` | The memory key, or the document's source URI. | +| `target_version` | `int \| str` | `0` | The memory version or document revision you read; a decimal string keeps a memory version exact in JavaScript. | +| `target_sha256` | `str` | `''` | The content_sha256 an op returned for the target, empty when you have none: memory.get's for a memory, the document row's for a document. | +| `target_doc_id` | `str` | `''` | For a document: the doc_id knowledge.get returned for the copy you read; required for a document. | +| `problem` | `str` | required | What is wrong or missing. | +| `suggested_correction` | `str` | `''` | | +| `evidence` | `list[str]` | *(computed)* | References only, never copied text: gap:, reflection: or run:. | +| `related` | `list[str]` | *(computed)* | Other report ids about the same problem. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `report_id` | `str` | | +| `state` | `Literal['open', 'taken', 'needs_evidence', 'resolved', 'dismissed']` | | +| `version` | `int` | | + +## `knowledge.reports.update` + +A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens a report, or links related reports. dismiss, request_evidence and reopen need a reason. resolve names the published… + +`POST /v1/knowledge.reports.update` · MCP `loom_knowledge_reports_update` · role `admin` · write · audited · 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. | +| `report_id` | `str` | required | | +| `action` | `Literal['take', 'release', 'request_evidence', 'resolve', 'dismiss', 'reopen'] \| None` | `None` | | +| `reason` | `str` | `''` | | +| `resolution_revision` | `str` | `''` | | +| `related` | `list[str]` | *(computed)* | Report ids to link. | +| `expected_version` | `int \| None` | `None` | Refuse when the report changed since this version. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `report_id` | `str` | | +| `state` | `Literal['open', 'taken', 'needs_evidence', 'resolved', 'dismissed']` | | +| `version` | `int` | | + ## `knowledge.restore` Undo a `knowledge.delete` or `knowledge.bulk_delete` of one document. diff --git a/docs/reference/schema.md b/docs/reference/schema.md index 4f721a5eb8..e67931db79 100644 --- a/docs/reference/schema.md +++ b/docs/reference/schema.md @@ -142,7 +142,7 @@ the `loom` tables each view reads, and, for each materialized view, its target, -204 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix. +205 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix. #### Tables @@ -248,6 +248,7 @@ the `loom` tables each view reads, and, for each materialized view, its target, | `knowledge_ingestions` | `ReplacingMergeTree(version)` | `(org, namespace, ingestion_id)` | | `toDateTime(updated_at) + toIntervalDay(30)` | | | `knowledge_mirror_latch` | `KeeperMap('/loom/knowledge_mirror_latch')` | | | | | | `knowledge_mirrors` | `ReplacingMergeTree(version)` | `(org, namespace, mirror)` | | | | +| `knowledge_reports` | `ReplacingMergeTree(version)` | `(org, namespace, report_id)` | | | | | `knowledge_source_listings` | `ReplacingMergeTree(version)` | `(org, namespace, source_id)` | | | | | `knowledge_source_push` | `ReplacingMergeTree(version)` | `(org, namespace, source_id)` | | | | | `knowledge_sources` | `ReplacingMergeTree(version)` | `(org, namespace, name)` | | | | diff --git a/docs/reference/status.md b/docs/reference/status.md index 38dd161e52..cb4331c2ae 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -421 operations, 307 of them experimental. +426 operations, 312 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -52,7 +52,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `help` | 0 | [`help.get`](operations/help.md#helpget), [`help.search`](operations/help.md#helpsearch) | | `inbox` | 0 | [`inbox.list`](operations/inbox.md#inboxlist), [`inbox.policy_list`](operations/inbox.md#inboxpolicy_list), [`inbox.policy_set`](operations/inbox.md#inboxpolicy_set), [`inbox.principals`](operations/inbox.md#inboxprincipals), [`inbox.register`](operations/inbox.md#inboxregister) | | `insights` | 0 | [`insights.catalog`](operations/insights.md#insightscatalog), [`insights.query`](operations/insights.md#insightsquery) | -| `knowledge` | 5 | [`knowledge.bulk_delete`](operations/knowledge.md#knowledgebulk_delete), [`knowledge.citations.check`](operations/knowledge.md#knowledgecitationscheck), [`knowledge.dataset_approve`](operations/knowledge.md#knowledgedataset_approve), [`knowledge.dataset_get`](operations/knowledge.md#knowledgedataset_get), [`knowledge.dedup_list`](operations/knowledge.md#knowledgededup_list), [`knowledge.dedup_resolve`](operations/knowledge.md#knowledgededup_resolve), [`knowledge.delete`](operations/knowledge.md#knowledgedelete), [`knowledge.formats`](operations/knowledge.md#knowledgeformats), [`knowledge.gaps.draft`](operations/knowledge.md#knowledgegapsdraft), [`knowledge.gaps.list`](operations/knowledge.md#knowledgegapslist), [`knowledge.ingest`](operations/knowledge.md#knowledgeingest), [`knowledge.ingest_cancel`](operations/knowledge.md#knowledgeingest_cancel), [`knowledge.ingest_status`](operations/knowledge.md#knowledgeingest_status), [`knowledge.inspect`](operations/knowledge.md#knowledgeinspect), [`knowledge.move`](operations/knowledge.md#knowledgemove), [`knowledge.outline`](operations/knowledge.md#knowledgeoutline), [`knowledge.query`](operations/knowledge.md#knowledgequery), [`knowledge.query_history.add`](operations/knowledge.md#knowledgequery_historyadd), [`knowledge.query_history.list`](operations/knowledge.md#knowledgequery_historylist), [`knowledge.query_history.remove`](operations/knowledge.md#knowledgequery_historyremove), [`knowledge.reads`](operations/knowledge.md#knowledgereads), [`knowledge.restore`](operations/knowledge.md#knowledgerestore), [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd), [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck), [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect), [`knowledge.source.list`](operations/knowledge.md#knowledgesourcelist), [`knowledge.source.live`](operations/knowledge.md#knowledgesourcelive), [`knowledge.source.parse_links`](operations/knowledge.md#knowledgesourceparse_links), [`knowledge.source.push_configure`](operations/knowledge.md#knowledgesourcepush_configure), [`knowledge.source.push_confirm`](operations/knowledge.md#knowledgesourcepush_confirm), [`knowledge.source.push_status`](operations/knowledge.md#knowledgesourcepush_status), [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove), [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate), [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now), [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate), [`knowledge.source.worker.claim`](operations/knowledge.md#knowledgesourceworkerclaim), [`knowledge.source.worker.commit`](operations/knowledge.md#knowledgesourceworkercommit), [`knowledge.source.worker.put`](operations/knowledge.md#knowledgesourceworkerput), [`knowledge.source.worker.stored`](operations/knowledge.md#knowledgesourceworkerstored), [`knowledge.source.worker_accounts`](operations/knowledge.md#knowledgesourceworker_accounts), [`knowledge.source.worker_approve`](operations/knowledge.md#knowledgesourceworker_approve), [`knowledge.source.worker_assign`](operations/knowledge.md#knowledgesourceworker_assign), [`knowledge.source.worker_enroll`](operations/knowledge.md#knowledgesourceworker_enroll), [`knowledge.source.worker_link`](operations/knowledge.md#knowledgesourceworker_link), [`knowledge.source.worker_preview`](operations/knowledge.md#knowledgesourceworker_preview), [`knowledge.source.worker_profiles`](operations/knowledge.md#knowledgesourceworker_profiles), [`knowledge.source.worker_register`](operations/knowledge.md#knowledgesourceworker_register), [`knowledge.source.worker_unlink`](operations/knowledge.md#knowledgesourceworker_unlink), [`knowledge.suites.add_draft`](operations/knowledge.md#knowledgesuitesadd_draft), [`knowledge.suites.dismiss_drafts`](operations/knowledge.md#knowledgesuitesdismiss_drafts), [`knowledge.suites.get`](operations/knowledge.md#knowledgesuitesget), [`knowledge.suites.list`](operations/knowledge.md#knowledgesuiteslist), [`knowledge.suites.publish`](operations/knowledge.md#knowledgesuitespublish), [`knowledge.suites.results`](operations/knowledge.md#knowledgesuitesresults), [`knowledge.suites.submit_results`](operations/knowledge.md#knowledgesuitessubmit_results), [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize), [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata), [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | +| `knowledge` | 5 | [`knowledge.bulk_delete`](operations/knowledge.md#knowledgebulk_delete), [`knowledge.citations.check`](operations/knowledge.md#knowledgecitationscheck), [`knowledge.dataset_approve`](operations/knowledge.md#knowledgedataset_approve), [`knowledge.dataset_get`](operations/knowledge.md#knowledgedataset_get), [`knowledge.dedup_list`](operations/knowledge.md#knowledgededup_list), [`knowledge.dedup_resolve`](operations/knowledge.md#knowledgededup_resolve), [`knowledge.delete`](operations/knowledge.md#knowledgedelete), [`knowledge.formats`](operations/knowledge.md#knowledgeformats), [`knowledge.gaps.draft`](operations/knowledge.md#knowledgegapsdraft), [`knowledge.gaps.list`](operations/knowledge.md#knowledgegapslist), [`knowledge.ingest`](operations/knowledge.md#knowledgeingest), [`knowledge.ingest_cancel`](operations/knowledge.md#knowledgeingest_cancel), [`knowledge.ingest_status`](operations/knowledge.md#knowledgeingest_status), [`knowledge.inspect`](operations/knowledge.md#knowledgeinspect), [`knowledge.move`](operations/knowledge.md#knowledgemove), [`knowledge.outline`](operations/knowledge.md#knowledgeoutline), [`knowledge.query`](operations/knowledge.md#knowledgequery), [`knowledge.query_history.add`](operations/knowledge.md#knowledgequery_historyadd), [`knowledge.query_history.list`](operations/knowledge.md#knowledgequery_historylist), [`knowledge.query_history.remove`](operations/knowledge.md#knowledgequery_historyremove), [`knowledge.reads`](operations/knowledge.md#knowledgereads), [`knowledge.reports.evidence`](operations/knowledge.md#knowledgereportsevidence), [`knowledge.reports.get`](operations/knowledge.md#knowledgereportsget), [`knowledge.reports.list`](operations/knowledge.md#knowledgereportslist), [`knowledge.reports.submit`](operations/knowledge.md#knowledgereportssubmit), [`knowledge.reports.update`](operations/knowledge.md#knowledgereportsupdate), [`knowledge.restore`](operations/knowledge.md#knowledgerestore), [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd), [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck), [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect), [`knowledge.source.list`](operations/knowledge.md#knowledgesourcelist), [`knowledge.source.live`](operations/knowledge.md#knowledgesourcelive), [`knowledge.source.parse_links`](operations/knowledge.md#knowledgesourceparse_links), [`knowledge.source.push_configure`](operations/knowledge.md#knowledgesourcepush_configure), [`knowledge.source.push_confirm`](operations/knowledge.md#knowledgesourcepush_confirm), [`knowledge.source.push_status`](operations/knowledge.md#knowledgesourcepush_status), [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove), [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate), [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now), [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate), [`knowledge.source.worker.claim`](operations/knowledge.md#knowledgesourceworkerclaim), [`knowledge.source.worker.commit`](operations/knowledge.md#knowledgesourceworkercommit), [`knowledge.source.worker.put`](operations/knowledge.md#knowledgesourceworkerput), [`knowledge.source.worker.stored`](operations/knowledge.md#knowledgesourceworkerstored), [`knowledge.source.worker_accounts`](operations/knowledge.md#knowledgesourceworker_accounts), [`knowledge.source.worker_approve`](operations/knowledge.md#knowledgesourceworker_approve), [`knowledge.source.worker_assign`](operations/knowledge.md#knowledgesourceworker_assign), [`knowledge.source.worker_enroll`](operations/knowledge.md#knowledgesourceworker_enroll), [`knowledge.source.worker_link`](operations/knowledge.md#knowledgesourceworker_link), [`knowledge.source.worker_preview`](operations/knowledge.md#knowledgesourceworker_preview), [`knowledge.source.worker_profiles`](operations/knowledge.md#knowledgesourceworker_profiles), [`knowledge.source.worker_register`](operations/knowledge.md#knowledgesourceworker_register), [`knowledge.source.worker_unlink`](operations/knowledge.md#knowledgesourceworker_unlink), [`knowledge.suites.add_draft`](operations/knowledge.md#knowledgesuitesadd_draft), [`knowledge.suites.dismiss_drafts`](operations/knowledge.md#knowledgesuitesdismiss_drafts), [`knowledge.suites.get`](operations/knowledge.md#knowledgesuitesget), [`knowledge.suites.list`](operations/knowledge.md#knowledgesuiteslist), [`knowledge.suites.publish`](operations/knowledge.md#knowledgesuitespublish), [`knowledge.suites.results`](operations/knowledge.md#knowledgesuitesresults), [`knowledge.suites.submit_results`](operations/knowledge.md#knowledgesuitessubmit_results), [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize), [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata), [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | | `learnings` | 0 | [`learnings.list`](operations/learnings.md#learningslist), [`learnings.quality`](operations/learnings.md#learningsquality), [`learnings.review`](operations/learnings.md#learningsreview) | | `memory` | 38 | [`memory.aggregate`](operations/memory.md#memoryaggregate), [`memory.append_batch`](operations/memory.md#memoryappend_batch), [`memory.apply`](operations/memory.md#memoryapply), [`memory.assign_category`](operations/memory.md#memoryassign_category), [`memory.auto_retirements`](operations/memory.md#memoryauto_retirements), [`memory.backlinks`](operations/memory.md#memorybacklinks), [`memory.copy_rule.delete`](operations/memory.md#memorycopy_ruledelete), [`memory.copy_rule.list`](operations/memory.md#memorycopy_rulelist), [`memory.copy_rule.run`](operations/memory.md#memorycopy_rulerun), [`memory.copy_rule.set`](operations/memory.md#memorycopy_ruleset), [`memory.copy_to`](operations/memory.md#memorycopy_to), [`memory.cross_promote`](operations/memory.md#memorycross_promote), [`memory.dedup_collapse`](operations/memory.md#memorydedup_collapse), [`memory.definitions.disputes`](operations/memory.md#memorydefinitionsdisputes), [`memory.definitions.list`](operations/memory.md#memorydefinitionslist), [`memory.delete_version`](operations/memory.md#memorydelete_version), [`memory.demonstrate`](operations/memory.md#memorydemonstrate), [`memory.demote`](operations/memory.md#memorydemote), [`memory.exposure_summary`](operations/memory.md#memoryexposure_summary), [`memory.extraction_retry_mine`](operations/memory.md#memoryextraction_retry_mine), [`memory.extraction_status_mine`](operations/memory.md#memoryextraction_status_mine), [`memory.history`](operations/memory.md#memoryhistory), [`memory.import`](operations/memory.md#memoryimport), [`memory.import_curated`](operations/memory.md#memoryimport_curated), [`memory.inspect`](operations/memory.md#memoryinspect), [`memory.keys`](operations/memory.md#memorykeys), [`memory.lineage`](operations/memory.md#memorylineage), [`memory.lock`](operations/memory.md#memorylock), [`memory.outcome`](operations/memory.md#memoryoutcome), [`memory.outline`](operations/memory.md#memoryoutline), [`memory.owner_report`](operations/memory.md#memoryowner_report), [`memory.pin`](operations/memory.md#memorypin), [`memory.promote`](operations/memory.md#memorypromote), [`memory.proposal_decide`](operations/memory.md#memoryproposal_decide), [`memory.proposals`](operations/memory.md#memoryproposals), [`memory.record.conflicts`](operations/memory.md#memoryrecordconflicts), [`memory.redact`](operations/memory.md#memoryredact), [`memory.reindex`](operations/memory.md#memoryreindex), [`memory.reject`](operations/memory.md#memoryreject), [`memory.related`](operations/memory.md#memoryrelated), [`memory.stack`](operations/memory.md#memorystack), [`memory.statuses`](operations/memory.md#memorystatuses), [`memory.sweep_expired`](operations/memory.md#memorysweep_expired), [`memory.timeline`](operations/memory.md#memorytimeline), [`memory.touch`](operations/memory.md#memorytouch), [`memory.unlock`](operations/memory.md#memoryunlock), [`memory.unpin`](operations/memory.md#memoryunpin) | | `memory_schema` | 1 | [`memory_schema.approve`](operations/memory_schema.md#memory_schemaapprove), [`memory_schema.list`](operations/memory_schema.md#memory_schemalist), [`memory_schema.propose`](operations/memory_schema.md#memory_schemapropose) | diff --git a/schemas/migrations/137_knowledge_reports.sql b/schemas/migrations/137_knowledge_reports.sql new file mode 100644 index 0000000000..78f73ede9b --- /dev/null +++ b/schemas/migrations/137_knowledge_reports.sql @@ -0,0 +1,50 @@ +-- Knowledge problem reports (docs/architecture/knowledge-reports.md). +-- +-- One row per report version: submit writes version 1 and each disposition change the +-- next, read with FINAL. A report about a memory claim holds its key, version and +-- content hash; one about a document holds its source URI, revision and content hash, +-- and in `target_copy` the copy it was read in (empty for the namespace's own document, +-- else a mirrored copy's mirror and source id); a missing-knowledge report holds no +-- target. Each version carries the `actor` and `source_class` the server stamped on the +-- write that made it, and in `written_by` the person that token stands for, folded as +-- the reporter is, whom a user erasure matches (a service account's version names its +-- creator). `problem` and `suggested_correction` are the reporter's words, erased with +-- the reporter (user erasure) and the namespace; `reason`, and the `resolution_revision` +-- of a report with no target, are the words of the maintainer `reason_by` names, erased +-- with them. Nothing is copied from the target: evidence is references only (gap, +-- reflection and run ids). Older builds do not read this table. +CREATE TABLE IF NOT EXISTS loom.knowledge_reports +( + `org` LowCardinality(String), + `namespace` LowCardinality(String), + `agent` LowCardinality(String) DEFAULT '-', + `user_id` String DEFAULT '-', + `session_id` String DEFAULT '-', + `report_id` String, + `version` UInt64, + `kind` LowCardinality(String), + `state` LowCardinality(String), + `target_kind` LowCardinality(String) DEFAULT '', + `target_key` String DEFAULT '', + `target_version` UInt64 DEFAULT 0, + `target_sha256` String DEFAULT '', + `target_copy` String DEFAULT '', + `problem` String, + `suggested_correction` String DEFAULT '', + `run_id` String DEFAULT '', + `evidence` Array(String) DEFAULT [], + `related` Array(String) DEFAULT [], + `reporter` String, + `assignee` String DEFAULT '', + `reason` String DEFAULT '', + `reason_by` String DEFAULT '', + `resolution_revision` String DEFAULT '', + `actor` String DEFAULT '', + `written_by` String DEFAULT '', + `source_class` LowCardinality(String) DEFAULT '', + `created_at` DateTime64(3, 'UTC'), + `updated_at` DateTime64(3, 'UTC') DEFAULT now64(3) +) +ENGINE = ReplacingMergeTree(version) +ORDER BY (org, namespace, report_id) +SETTINGS non_replicated_deduplication_window = 1000; diff --git a/schemas/schema.sql b/schemas/schema.sql index 4b3d207472..07f0174227 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -16,13 +16,13 @@ -- Do NOT hand-edit. Edit schemas/migrations/*.sql and re-dump. -- CI verifies this file matches what migrations would produce. -- --- Counts: 204 tables + 5 views + 19 materialized views. +-- Counts: 205 tables + 5 views + 19 materialized views. CREATE DATABASE IF NOT EXISTS `loom`; CREATE DATABASE IF NOT EXISTS `loom_telemetry`; -- ====================================================================== --- Tables (204) +-- Tables (205) -- ====================================================================== -- loom.acl_versions @@ -2259,6 +2259,43 @@ ENGINE = ReplacingMergeTree(version) ORDER BY (org, namespace, mirror) SETTINGS non_replicated_deduplication_window = 1000, index_granularity = 8192; +-- loom.knowledge_reports +CREATE TABLE IF NOT EXISTS loom.knowledge_reports +( + `org` LowCardinality(String), + `namespace` LowCardinality(String), + `agent` LowCardinality(String) DEFAULT '-', + `user_id` String DEFAULT '-', + `session_id` String DEFAULT '-', + `report_id` String, + `version` UInt64, + `kind` LowCardinality(String), + `state` LowCardinality(String), + `target_kind` LowCardinality(String) DEFAULT '', + `target_key` String DEFAULT '', + `target_version` UInt64 DEFAULT 0, + `target_sha256` String DEFAULT '', + `target_copy` String DEFAULT '', + `problem` String, + `suggested_correction` String DEFAULT '', + `run_id` String DEFAULT '', + `evidence` Array(String) DEFAULT [], + `related` Array(String) DEFAULT [], + `reporter` String, + `assignee` String DEFAULT '', + `reason` String DEFAULT '', + `reason_by` String DEFAULT '', + `resolution_revision` String DEFAULT '', + `actor` String DEFAULT '', + `written_by` String DEFAULT '', + `source_class` LowCardinality(String) DEFAULT '', + `created_at` DateTime64(3, 'UTC'), + `updated_at` DateTime64(3, 'UTC') DEFAULT now64(3) +) +ENGINE = ReplacingMergeTree(version) +ORDER BY (org, namespace, report_id) +SETTINGS non_replicated_deduplication_window = 1000, index_granularity = 8192; + -- loom.knowledge_source_listings CREATE TABLE IF NOT EXISTS loom.knowledge_source_listings ( diff --git a/scripts/codegen/sdk_go_gen.py b/scripts/codegen/sdk_go_gen.py index 854df24c12..c19b1e6698 100644 --- a/scripts/codegen/sdk_go_gen.py +++ b/scripts/codegen/sdk_go_gen.py @@ -85,11 +85,15 @@ "memory.update": {"agent"}, # Omission keeps the namespace-wide ambiguity check. } _SNAPSHOT_KEY = "NamespaceSnapshotOutput" -# conflicts.list reads and compares the memory row's ClickHouse UInt64 version. +# conflicts.list compares the memory row's ClickHouse UInt64 version, and a report's +# target_version is a UInt64 column; both overflow int64. _UINT64_FIELDS = { - "ConflictsListInput": "before_version", - "ConflictsListOutput": "next_before_version", - "_ConflictRow": "version", + ("server.memory.api.models_conflicts", "ConflictsListInput"): "before_version", + ("server.memory.api.models_conflicts", "ConflictsListOutput"): "next_before_version", + ("server.memory.api.models_conflicts", "_ConflictRow"): "version", + ("server.knowledge.api.models_reports", "KnowledgeReportsSubmitInput"): "target_version", + ("server.knowledge.api.models_reports", "KnowledgeReport"): "target_version", + ("server.knowledge.api.models_reports", "KnowledgeReportDetail"): "target_version", } # Keep the existing Client.Search method and SearchHit result type. _GROUP_NAMES = {"search": "LoomSearch"} @@ -159,9 +163,8 @@ def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue: self.by_alias = by_alias if self.mode == "serialization" and issubclass(model, ProjectedRow): result.pop("required", None) - if model.__module__ == "server.memory.api.models_conflicts": - if field := _UINT64_FIELDS.get(model.__name__): - result["properties"][field]["x-loom-go-uint64"] = True + if field := _UINT64_FIELDS.get((model.__module__, model.__name__)): + result["properties"][field]["x-loom-go-uint64"] = True return result @@ -237,6 +240,9 @@ def render(self, schema: dict[str, Any], *, unsigned: bool = False) -> str: return self.names[_ref_key(schema["$ref"])] if "anyOf" in schema: branches = [item for item in schema["anyOf"] if item.get("type") != "null"] + # A UInt64 that also takes a decimal string for JavaScript: Go's uint64 is exact. + if unsigned and {item.get("type") for item in branches} == {"integer", "string"}: + return "*uint64" if len(branches) < len(schema["anyOf"]) else "uint64" if len(branches) == 1 and len(branches) < len(schema["anyOf"]): inner = self.render(branches[0], unsigned=unsigned) return inner if inner == _RAW else f"*{inner}" diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index efbda1a37d..7ea04d7109 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -1439,6 +1439,42 @@ type KnowledgeReadsInput = wire.KnowledgeReadsInput // KnowledgeReadsOutput is the response from knowledge.reads. type KnowledgeReadsOutput = wire.KnowledgeReadsOutput +// KnowledgeReport is a model used by Loom operations. +type KnowledgeReport = wire.KnowledgeReport + +// KnowledgeReportDetail is a model used by Loom operations. +type KnowledgeReportDetail = wire.KnowledgeReportDetail + +// KnowledgeReportsEvidenceInput is the request to knowledge.reports.evidence. +type KnowledgeReportsEvidenceInput = wire.KnowledgeReportsEvidenceInput + +// KnowledgeReportsEvidenceOutput is the response from knowledge.reports.evidence. +type KnowledgeReportsEvidenceOutput = wire.KnowledgeReportsEvidenceOutput + +// KnowledgeReportsGetInput is the request to knowledge.reports.get. +type KnowledgeReportsGetInput = wire.KnowledgeReportsGetInput + +// KnowledgeReportsGetOutput is the response from knowledge.reports.get. +type KnowledgeReportsGetOutput = wire.KnowledgeReportsGetOutput + +// KnowledgeReportsListInput is the request to knowledge.reports.list. +type KnowledgeReportsListInput = wire.KnowledgeReportsListInput + +// KnowledgeReportsListOutput is the response from knowledge.reports.list. +type KnowledgeReportsListOutput = wire.KnowledgeReportsListOutput + +// KnowledgeReportsSubmitInput is the request to knowledge.reports.submit. +type KnowledgeReportsSubmitInput = wire.KnowledgeReportsSubmitInput + +// KnowledgeReportsSubmitOutput is the response from knowledge.reports.submit. +type KnowledgeReportsSubmitOutput = wire.KnowledgeReportsSubmitOutput + +// KnowledgeReportsUpdateInput is the request to knowledge.reports.update. +type KnowledgeReportsUpdateInput = wire.KnowledgeReportsUpdateInput + +// KnowledgeReportsUpdateOutput is the response from knowledge.reports.update. +type KnowledgeReportsUpdateOutput = wire.KnowledgeReportsUpdateOutput + // KnowledgeRestoreInput is the request to knowledge.restore. type KnowledgeRestoreInput = wire.KnowledgeRestoreInput @@ -6185,6 +6221,72 @@ func (s KnowledgeService) Reads(ctx context.Context, opts ...Option[KnowledgeRea return callOperation[KnowledgeReadsOutput](s.client, ctx, "knowledge.reads", in) } +// ReportsEvidence calls knowledge.reports.evidence. +func (s KnowledgeService) ReportsEvidence(ctx context.Context, in KnowledgeReportsEvidenceInput) (*KnowledgeReportsEvidenceOutput, error) { + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeReportsEvidenceOutput](s.client, ctx, "knowledge.reports.evidence", in) +} + +// ReportsGet calls knowledge.reports.get. +// Use WithInput to supply additional request fields. +func (s KnowledgeService) ReportsGet(ctx context.Context, reportID string, opts ...Option[KnowledgeReportsGetInput]) (*KnowledgeReportsGetOutput, error) { + in := applyOptions(opts) + in.ReportID = reportID + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeReportsGetOutput](s.client, ctx, "knowledge.reports.get", in) +} + +// ReportsList calls knowledge.reports.list. +// Use WithInput to supply additional request fields. +func (s KnowledgeService) ReportsList(ctx context.Context, opts ...Option[KnowledgeReportsListInput]) (*KnowledgeReportsListOutput, error) { + in := applyOptions(opts) + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeReportsListOutput](s.client, ctx, "knowledge.reports.list", in) +} + +// ReportsSubmit calls knowledge.reports.submit. +func (s KnowledgeService) ReportsSubmit(ctx context.Context, in KnowledgeReportsSubmitInput) (*KnowledgeReportsSubmitOutput, error) { + if in.Agent == nil && s.client.identity.Agent != "" { + in.Agent = Ptr(s.client.identity.Agent) + } + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeReportsSubmitOutput](s.client, ctx, "knowledge.reports.submit", in) +} + +// ReportsUpdate calls knowledge.reports.update. +// Use WithInput to supply additional request fields. +func (s KnowledgeService) ReportsUpdate(ctx context.Context, reportID string, opts ...Option[KnowledgeReportsUpdateInput]) (*KnowledgeReportsUpdateOutput, error) { + in := applyOptions(opts) + in.ReportID = reportID + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeReportsUpdateOutput](s.client, ctx, "knowledge.reports.update", in) +} + // Restore calls knowledge.restore. // Use WithInput to supply additional request fields. func (s KnowledgeService) Restore(ctx context.Context, sourceURI string, opts ...Option[KnowledgeRestoreInput]) (*KnowledgeRestoreOutput, error) { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 7b586769f4..1f18695f78 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -5857,6 +5857,159 @@ type KnowledgeReadsOutput struct { Reads *[]map[string]json.RawMessage `json:"reads,omitempty"` } +// KnowledgeReport is a model used by Loom operations. +type KnowledgeReport struct { + ReportID string `json:"report_id"` + Version int64 `json:"version"` + Kind string `json:"kind"` + State string `json:"state"` + TargetKind *string `json:"target_kind,omitempty"` + TargetKey *string `json:"target_key,omitempty"` + TargetVersion *uint64 `json:"target_version,omitempty"` + TargetVersionText *string `json:"target_version_text,omitempty"` + Reporter string `json:"reporter"` + Assignee *string `json:"assignee,omitempty"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +// KnowledgeReportDetail is a model used by Loom operations. +type KnowledgeReportDetail struct { + ReportID string `json:"report_id"` + Version int64 `json:"version"` + Kind string `json:"kind"` + State string `json:"state"` + TargetKind *string `json:"target_kind,omitempty"` + TargetKey *string `json:"target_key,omitempty"` + TargetVersion *uint64 `json:"target_version,omitempty"` + TargetVersionText *string `json:"target_version_text,omitempty"` + Reporter string `json:"reporter"` + Assignee *string `json:"assignee,omitempty"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + TargetChanged *bool `json:"target_changed,omitempty"` + Problem string `json:"problem"` + SuggestedCorrection *string `json:"suggested_correction,omitempty"` + RunID *string `json:"run_id,omitempty"` + Evidence *[]string `json:"evidence,omitempty"` + Related *[]string `json:"related,omitempty"` + Reason *string `json:"reason,omitempty"` + ResolutionRevision *string `json:"resolution_revision,omitempty"` + TargetReadable *bool `json:"target_readable,omitempty"` +} + +// KnowledgeReportsEvidenceInput is the request to knowledge.reports.evidence. +type KnowledgeReportsEvidenceInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + ReportID string `json:"report_id"` + Evidence []string `json:"evidence"` +} + +// KnowledgeReportsEvidenceOutput is the response from knowledge.reports.evidence. +type KnowledgeReportsEvidenceOutput 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"` + ReportID string `json:"report_id"` + State string `json:"state"` + Version int64 `json:"version"` +} + +// KnowledgeReportsGetInput is the request to knowledge.reports.get. +type KnowledgeReportsGetInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + ReportID string `json:"report_id"` +} + +// KnowledgeReportsGetOutput is the response from knowledge.reports.get. +type KnowledgeReportsGetOutput 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"` + Report Optional[KnowledgeReportDetail] `json:"report,omitempty"` +} + +// KnowledgeReportsListInput is the request to knowledge.reports.list. +type KnowledgeReportsListInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + States *[]string `json:"states,omitempty"` + Kinds *[]string `json:"kinds,omitempty"` + TargetKind *string `json:"target_kind,omitempty"` + TargetKey *string `json:"target_key,omitempty"` + Assignee *string `json:"assignee,omitempty"` + Reporter *string `json:"reporter,omitempty"` + Limit *int64 `json:"limit,omitempty"` +} + +// KnowledgeReportsListOutput is the response from knowledge.reports.list. +type KnowledgeReportsListOutput 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"` + Reports *[]KnowledgeReport `json:"reports,omitempty"` +} + +// KnowledgeReportsSubmitInput is the request to knowledge.reports.submit. +type KnowledgeReportsSubmitInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + Agent *string `json:"agent,omitempty"` + UserID *string `json:"user_id,omitempty"` + SessionID *string `json:"session_id,omitempty"` + RunID *string `json:"run_id,omitempty"` + Kind string `json:"kind"` + TargetKind *string `json:"target_kind,omitempty"` + TargetKey *string `json:"target_key,omitempty"` + TargetVersion *uint64 `json:"target_version,omitempty"` + TargetSHA256 *string `json:"target_sha256,omitempty"` + TargetDocID *string `json:"target_doc_id,omitempty"` + Problem string `json:"problem"` + SuggestedCorrection *string `json:"suggested_correction,omitempty"` + Evidence *[]string `json:"evidence,omitempty"` + Related *[]string `json:"related,omitempty"` +} + +// KnowledgeReportsSubmitOutput is the response from knowledge.reports.submit. +type KnowledgeReportsSubmitOutput 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"` + ReportID string `json:"report_id"` + State string `json:"state"` + Version int64 `json:"version"` +} + +// KnowledgeReportsUpdateInput is the request to knowledge.reports.update. +type KnowledgeReportsUpdateInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + ReportID string `json:"report_id"` + Action Optional[string] `json:"action,omitempty"` + Reason *string `json:"reason,omitempty"` + ResolutionRevision *string `json:"resolution_revision,omitempty"` + Related *[]string `json:"related,omitempty"` + ExpectedVersion Optional[int64] `json:"expected_version,omitempty"` +} + +// KnowledgeReportsUpdateOutput is the response from knowledge.reports.update. +type KnowledgeReportsUpdateOutput 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"` + ReportID string `json:"report_id"` + State string `json:"state"` + Version int64 `json:"version"` +} + // KnowledgeRestoreInput is the request to knowledge.restore. type KnowledgeRestoreInput struct { Org string `json:"org"` diff --git a/sdk/go/wire/models_test.go b/sdk/go/wire/models_test.go index b907b7b213..7f16641d40 100644 --- a/sdk/go/wire/models_test.go +++ b/sdk/go/wire/models_test.go @@ -2,6 +2,7 @@ package wire_test import ( "encoding/json" + "math" "testing" "github.com/ClickHouse/loom/sdk/go/wire" @@ -87,6 +88,28 @@ func TestDecodeProjectedMemoryGet(t *testing.T) { } } +func TestDecodeKnowledgeReportsAtTheLargestTargetVersion(t *testing.T) { + // target_version is a ClickHouse UInt64, so the API accepts up to its maximum. + var got wire.KnowledgeReportsGetOutput + if err := json.Unmarshal([]byte(`{"found":true,"report":{"target_version":18446744073709551615}}`), &got); err != nil { + t.Fatal(err) + } + report, ok := got.Report.Get() + if !ok || report.TargetVersion == nil || *report.TargetVersion != math.MaxUint64 { + t.Fatal("get lost the largest target version") + } + var list wire.KnowledgeReportsListOutput + if err := json.Unmarshal([]byte(`{"reports":[{"target_version":18446744073709551615}]}`), &list); err != nil { + t.Fatal(err) + } + if list.Reports == nil || len(*list.Reports) != 1 { + t.Fatal("list lost its report") + } + if v := (*list.Reports)[0].TargetVersion; v == nil || *v != math.MaxUint64 { + t.Fatal("list lost the largest target version") + } +} + func TestDecodeProjectedMemoryGetDistinguishesNullAndOmitted(t *testing.T) { var out wire.MemoryGetOutput if err := json.Unmarshal([]byte(`{"found":true,"expires_at":null}`), &out); err != nil { diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index 4173c56fa0..166d8b5b95 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -1552,6 +1552,51 @@ async def reads( "_ops.KnowledgeReadsOutput", await self._agent.call("knowledge.reads", body, **options) ) + async def reports_evidence( + self, body: _ops.KnowledgeReportsEvidenceBody | None = None, /, **options: Any + ) -> _ops.KnowledgeReportsEvidenceOutput: + """`knowledge.reports.evidence`.""" + return cast( + "_ops.KnowledgeReportsEvidenceOutput", + await self._agent.call("knowledge.reports.evidence", body, **options), + ) + + async def reports_get( + self, body: _ops.KnowledgeReportsGetBody | None = None, /, **options: Any + ) -> _ops.KnowledgeReportsGetOutput: + """`knowledge.reports.get`.""" + return cast( + "_ops.KnowledgeReportsGetOutput", + await self._agent.call("knowledge.reports.get", body, **options), + ) + + async def reports_list( + self, body: _ops.KnowledgeReportsListBody | None = None, /, **options: Any + ) -> _ops.KnowledgeReportsListOutput: + """`knowledge.reports.list`.""" + return cast( + "_ops.KnowledgeReportsListOutput", + await self._agent.call("knowledge.reports.list", body, **options), + ) + + async def reports_submit( + self, body: _ops.KnowledgeReportsSubmitBody | None = None, /, **options: Any + ) -> _ops.KnowledgeReportsSubmitOutput: + """`knowledge.reports.submit`.""" + return cast( + "_ops.KnowledgeReportsSubmitOutput", + await self._agent.call("knowledge.reports.submit", body, **options), + ) + + async def reports_update( + self, body: _ops.KnowledgeReportsUpdateBody | None = None, /, **options: Any + ) -> _ops.KnowledgeReportsUpdateOutput: + """`knowledge.reports.update`.""" + return cast( + "_ops.KnowledgeReportsUpdateOutput", + await self._agent.call("knowledge.reports.update", body, **options), + ) + async def restore( self, body: _ops.KnowledgeRestoreBody | None = None, /, **options: Any ) -> _ops.KnowledgeRestoreOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 078e438baf..964d2b6895 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -195,6 +195,11 @@ class OpSpec: "knowledge.query_history.list", "knowledge.query_history.remove", "knowledge.reads", + "knowledge.reports.evidence", + "knowledge.reports.get", + "knowledge.reports.list", + "knowledge.reports.submit", + "knowledge.reports.update", "knowledge.restore", "knowledge.search", "knowledge.source.add", @@ -619,6 +624,11 @@ class OpSpec: "knowledge.query_history.list", "knowledge.query_history.remove", "knowledge.reads", + "knowledge.reports.evidence", + "knowledge.reports.get", + "knowledge.reports.list", + "knowledge.reports.submit", + "knowledge.reports.update", "knowledge.restore", "knowledge.search", "knowledge.source.add", @@ -2759,6 +2769,66 @@ class OpSpec: False, True, ), + "knowledge.reports.evidence": OpSpec( + "knowledge.reports.evidence", + "KnowledgeReportsEvidenceInput", + "KnowledgeReportsEvidenceBody", + "KnowledgeReportsEvidenceOutput", + False, + "writer", + "experimental", + 300, + False, + False, + ), + "knowledge.reports.get": OpSpec( + "knowledge.reports.get", + "KnowledgeReportsGetInput", + "KnowledgeReportsGetBody", + "KnowledgeReportsGetOutput", + True, + "viewer", + "experimental", + 100, + False, + True, + ), + "knowledge.reports.list": OpSpec( + "knowledge.reports.list", + "KnowledgeReportsListInput", + "KnowledgeReportsListBody", + "KnowledgeReportsListOutput", + False, + "admin", + "experimental", + 200, + False, + False, + ), + "knowledge.reports.submit": OpSpec( + "knowledge.reports.submit", + "KnowledgeReportsSubmitInput", + "KnowledgeReportsSubmitBody", + "KnowledgeReportsSubmitOutput", + True, + "writer", + "experimental", + 400, + False, + False, + ), + "knowledge.reports.update": OpSpec( + "knowledge.reports.update", + "KnowledgeReportsUpdateInput", + "KnowledgeReportsUpdateBody", + "KnowledgeReportsUpdateOutput", + False, + "admin", + "experimental", + 300, + True, + False, + ), "knowledge.restore": OpSpec( "knowledge.restore", "KnowledgeRestoreInput", @@ -12709,6 +12779,206 @@ class KnowledgeReadsOutput(TypedDict, total=False): reads: NotRequired[list[dict[str, Any]]] +class KnowledgeReportsEvidenceInput(TypedDict, total=False): + "The reporter adds evidence to their own report, for example after a maintainer" + + org: Required[str] + namespace: Required[str] + report_id: Required[str] + evidence: Required[list[str]] + + +class KnowledgeReportsEvidenceBody(TypedDict, total=False): + "The reporter adds evidence to their own report, for example after a maintainer" + + org: NotRequired[str] + namespace: NotRequired[str] + report_id: Required[str] + evidence: Required[list[str]] + + +class KnowledgeReportsEvidenceOutput(TypedDict, total=False): + report_id: Required[str] + state: Required[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]] + version: Required[int] + + +class KnowledgeReportsGetInput(TypedDict, total=False): + "One report, with the problem, the suggested correction and the evidence, when you" + + org: Required[str] + namespace: Required[str] + report_id: Required[str] + + +class KnowledgeReportsGetBody(TypedDict, total=False): + "One report, with the problem, the suggested correction and the evidence, when you" + + org: NotRequired[str] + namespace: NotRequired[str] + report_id: Required[str] + + +class KnowledgeReportsGetOutput(TypedDict, total=False): + found: Required[bool] + report: NotRequired[Optional["KnowledgeReportDetail"]] + + +class KnowledgeReportDetail(TypedDict, total=False): + report_id: Required[str] + version: Required[int] + kind: Required[Literal["missing", "incorrect", "outdated"]] + state: Required[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + target_version: NotRequired[int] + target_version_text: NotRequired[str] + reporter: Required[str] + assignee: NotRequired[str] + created_at: Required[str] # date-time as ISO-8601 text + updated_at: Required[str] # date-time as ISO-8601 text + target_changed: NotRequired[bool] + problem: Required[str] + suggested_correction: NotRequired[str] + run_id: NotRequired[str] + evidence: NotRequired[list[str]] + related: NotRequired[list[str]] + reason: NotRequired[str] + resolution_revision: NotRequired[str] + target_readable: NotRequired[bool] + + +class KnowledgeReportsListInput(TypedDict, total=False): + "The namespace's report queue for maintainers, newest change first. Rows carry no" + + org: Required[str] + namespace: Required[str] + states: NotRequired[list[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]]] + kinds: NotRequired[list[Literal["missing", "incorrect", "outdated"]]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + assignee: NotRequired[str] + reporter: NotRequired[str] + limit: NotRequired[int] + + +class KnowledgeReportsListBody(TypedDict, total=False): + "The namespace's report queue for maintainers, newest change first. Rows carry no" + + org: NotRequired[str] + namespace: NotRequired[str] + states: NotRequired[list[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]]] + kinds: NotRequired[list[Literal["missing", "incorrect", "outdated"]]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + assignee: NotRequired[str] + reporter: NotRequired[str] + limit: NotRequired[int] + + +class KnowledgeReportsListOutput(TypedDict, total=False): + reports: NotRequired[list["KnowledgeReport"]] + + +class KnowledgeReport(TypedDict, total=False): + report_id: Required[str] + version: Required[int] + kind: Required[Literal["missing", "incorrect", "outdated"]] + state: Required[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + target_version: NotRequired[int] + target_version_text: NotRequired[str] + reporter: Required[str] + assignee: NotRequired[str] + created_at: Required[str] # date-time as ISO-8601 text + updated_at: Required[str] # date-time as ISO-8601 text + + +class KnowledgeReportsSubmitInput(TypedDict, total=False): + "Report that a memory claim or a document passage is incorrect or outdated, or that" + + org: Required[str] + namespace: Required[str] + agent: NotRequired[str] + user_id: NotRequired[str] + session_id: NotRequired[str] + run_id: NotRequired[str] + kind: Required[Literal["missing", "incorrect", "outdated"]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + target_version: NotRequired[Union[int, str]] + target_sha256: NotRequired[str] + target_doc_id: NotRequired[str] + problem: Required[str] + suggested_correction: NotRequired[str] + evidence: NotRequired[list[str]] + related: NotRequired[list[str]] + + +class KnowledgeReportsSubmitBody(TypedDict, total=False): + "Report that a memory claim or a document passage is incorrect or outdated, or that" + + org: NotRequired[str] + namespace: NotRequired[str] + agent: NotRequired[str] + user_id: NotRequired[str] + session_id: NotRequired[str] + run_id: NotRequired[str] + kind: Required[Literal["missing", "incorrect", "outdated"]] + target_kind: NotRequired[Literal["", "memory", "document"]] + target_key: NotRequired[str] + target_version: NotRequired[Union[int, str]] + target_sha256: NotRequired[str] + target_doc_id: NotRequired[str] + problem: Required[str] + suggested_correction: NotRequired[str] + evidence: NotRequired[list[str]] + related: NotRequired[list[str]] + + +class KnowledgeReportsSubmitOutput(TypedDict, total=False): + report_id: Required[str] + state: Required[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]] + version: Required[int] + + +class KnowledgeReportsUpdateInput(TypedDict, total=False): + "A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens" + + org: Required[str] + namespace: Required[str] + report_id: Required[str] + action: NotRequired[ + Optional[Literal["take", "release", "request_evidence", "resolve", "dismiss", "reopen"]] + ] + reason: NotRequired[str] + resolution_revision: NotRequired[str] + related: NotRequired[list[str]] + expected_version: NotRequired[Optional[int]] + + +class KnowledgeReportsUpdateBody(TypedDict, total=False): + "A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens" + + org: NotRequired[str] + namespace: NotRequired[str] + report_id: Required[str] + action: NotRequired[ + Optional[Literal["take", "release", "request_evidence", "resolve", "dismiss", "reopen"]] + ] + reason: NotRequired[str] + resolution_revision: NotRequired[str] + related: NotRequired[list[str]] + expected_version: NotRequired[Optional[int]] + + +class KnowledgeReportsUpdateOutput(TypedDict, total=False): + report_id: Required[str] + state: Required[Literal["open", "taken", "needs_evidence", "resolved", "dismissed"]] + version: Required[int] + + class KnowledgeRestoreInput(TypedDict, total=False): "Undo a `knowledge.delete` or `knowledge.bulk_delete` of one document." diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 446963af22..f3367142c0 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 = 421 + OP_COUNT = 426 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -168,6 +168,11 @@ module Generated "knowledge.query_history.list" => OpSpec.new("knowledge.query_history.list", "knowledge", "query_history_list", true, false, "admin", "experimental", %w[fields org namespace limit].freeze, %w[org namespace].freeze), "knowledge.query_history.remove" => OpSpec.new("knowledge.query_history.remove", "knowledge", "query_history_remove", true, false, "admin", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.reads" => OpSpec.new("knowledge.reads", "knowledge", "reads", true, true, "viewer", "experimental", %w[org namespace days source_uris].freeze, %w[org namespace].freeze), + "knowledge.reports.evidence" => OpSpec.new("knowledge.reports.evidence", "knowledge", "reports_evidence", false, false, "writer", "experimental", %w[org namespace report_id evidence].freeze, %w[org namespace report_id evidence].freeze), + "knowledge.reports.get" => OpSpec.new("knowledge.reports.get", "knowledge", "reports_get", true, true, "viewer", "experimental", %w[org namespace report_id].freeze, %w[org namespace report_id].freeze), + "knowledge.reports.list" => OpSpec.new("knowledge.reports.list", "knowledge", "reports_list", false, false, "admin", "experimental", %w[org namespace states kinds target_kind target_key assignee reporter limit].freeze, %w[org namespace].freeze), + "knowledge.reports.submit" => OpSpec.new("knowledge.reports.submit", "knowledge", "reports_submit", true, false, "writer", "experimental", %w[org namespace agent user_id session_id run_id kind target_kind target_key target_version target_sha256 target_doc_id problem suggested_correction evidence related].freeze, %w[org namespace kind problem].freeze), + "knowledge.reports.update" => OpSpec.new("knowledge.reports.update", "knowledge", "reports_update", false, false, "admin", "experimental", %w[org namespace report_id action reason resolution_revision related expected_version].freeze, %w[org namespace report_id].freeze), "knowledge.restore" => OpSpec.new("knowledge.restore", "knowledge", "restore", true, false, "writer", "experimental", %w[org namespace source_uri if_revision].freeze, %w[org namespace source_uri].freeze), "knowledge.search" => OpSpec.new("knowledge.search", "knowledge", "search", true, true, "viewer", "stable", %w[org namespace query tags since_seconds top_k namespace_scope namespaces search_mode lexical_weight narrow_spans collapse_sections uri_prefix session_ids source_classes formats block_types rerank].freeze, %w[org namespace query].freeze), "knowledge.source.add" => OpSpec.new("knowledge.source.add", "knowledge", "source_add", false, false, "writer", "experimental", %w[org namespace name kind items links config include credential_mode crawl_options credential dry_run].freeze, %w[org namespace name kind].freeze), @@ -1501,6 +1506,41 @@ def reads(body = nil, request_options: nil, **fields) call_op("knowledge.reads", body, fields, request_options) end + # `knowledge.reports.evidence` (writer, writes, experimental). + # The reporter adds evidence to their own report, for example after a maintainer + # Required: org, namespace, report_id, evidence. + def reports_evidence(body = nil, request_options: nil, **fields) + call_op("knowledge.reports.evidence", body, fields, request_options) + end + + # `knowledge.reports.get` (viewer, read-only, experimental). + # One report, with the problem, the suggested correction and the evidence, when you + # Required: org, namespace, report_id. + def reports_get(body = nil, request_options: nil, **fields) + call_op("knowledge.reports.get", body, fields, request_options) + end + + # `knowledge.reports.list` (admin, writes, experimental). + # The namespace's report queue for maintainers, newest change first. Rows carry no + # Required: org, namespace. + def reports_list(body = nil, request_options: nil, **fields) + call_op("knowledge.reports.list", body, fields, request_options) + end + + # `knowledge.reports.submit` (writer, writes, Idempotency-Key, experimental). + # Report that a memory claim or a document passage is incorrect or outdated, or that + # Required: org, namespace, kind, problem. + def reports_submit(body = nil, request_options: nil, **fields) + call_op("knowledge.reports.submit", body, fields, request_options) + end + + # `knowledge.reports.update` (admin, writes, experimental). + # A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens + # Required: org, namespace, report_id. + def reports_update(body = nil, request_options: nil, **fields) + call_op("knowledge.reports.update", body, fields, request_options) + end + # `knowledge.restore` (writer, writes, Idempotency-Key, experimental). # Undo a `knowledge.delete` or `knowledge.bulk_delete` of one document. # Required: org, namespace, source_uri. diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index faaed5c3d6..fb1aaff94c 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -2369,6 +2369,91 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("knowledge.gaps.draft", &request, options) } + /// Call `knowledge.reports.submit`. + pub fn knowledge_reports_submit( + &self, + request: crate::KnowledgeReportsSubmitInput, + ) -> Result { + self.knowledge_reports_submit_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.submit` with per-request options and metadata. + pub fn knowledge_reports_submit_with_options( + &self, + request: crate::KnowledgeReportsSubmitInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.submit", &request, options) + } + /// Call `knowledge.reports.get`. + pub fn knowledge_reports_get( + &self, + request: crate::KnowledgeReportsGetInput, + ) -> Result { + self.knowledge_reports_get_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.get` with per-request options and metadata. + pub fn knowledge_reports_get_with_options( + &self, + request: crate::KnowledgeReportsGetInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.get", &request, options) + } + /// Call `knowledge.reports.list`. + pub fn knowledge_reports_list( + &self, + request: crate::KnowledgeReportsListInput, + ) -> Result { + self.knowledge_reports_list_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.list` with per-request options and metadata. + pub fn knowledge_reports_list_with_options( + &self, + request: crate::KnowledgeReportsListInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.list", &request, options) + } + /// Call `knowledge.reports.update`. + pub fn knowledge_reports_update( + &self, + request: crate::KnowledgeReportsUpdateInput, + ) -> Result { + self.knowledge_reports_update_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.update` with per-request options and metadata. + pub fn knowledge_reports_update_with_options( + &self, + request: crate::KnowledgeReportsUpdateInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.update", &request, options) + } + /// Call `knowledge.reports.evidence`. + pub fn knowledge_reports_evidence( + &self, + request: crate::KnowledgeReportsEvidenceInput, + ) -> Result { + self.knowledge_reports_evidence_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.evidence` with per-request options and metadata. + pub fn knowledge_reports_evidence_with_options( + &self, + request: crate::KnowledgeReportsEvidenceInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.evidence", &request, options) + } /// Call `knowledge.citations.check`. pub fn knowledge_citations_check( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index 5402d284b6..cf239b386a 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -2546,6 +2546,99 @@ impl crate::Client { ) -> Result, crate::CallFailure> { self.call("knowledge.gaps.draft", &request, options).await } + /// Call `knowledge.reports.submit`. + pub async fn knowledge_reports_submit( + &self, + request: crate::KnowledgeReportsSubmitInput, + ) -> Result { + self.knowledge_reports_submit_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.submit` with per-request options and metadata. + pub async fn knowledge_reports_submit_with_options( + &self, + request: crate::KnowledgeReportsSubmitInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.submit", &request, options) + .await + } + /// Call `knowledge.reports.get`. + pub async fn knowledge_reports_get( + &self, + request: crate::KnowledgeReportsGetInput, + ) -> Result { + self.knowledge_reports_get_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.get` with per-request options and metadata. + pub async fn knowledge_reports_get_with_options( + &self, + request: crate::KnowledgeReportsGetInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.get", &request, options).await + } + /// Call `knowledge.reports.list`. + pub async fn knowledge_reports_list( + &self, + request: crate::KnowledgeReportsListInput, + ) -> Result { + self.knowledge_reports_list_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.list` with per-request options and metadata. + pub async fn knowledge_reports_list_with_options( + &self, + request: crate::KnowledgeReportsListInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.list", &request, options).await + } + /// Call `knowledge.reports.update`. + pub async fn knowledge_reports_update( + &self, + request: crate::KnowledgeReportsUpdateInput, + ) -> Result { + self.knowledge_reports_update_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.update` with per-request options and metadata. + pub async fn knowledge_reports_update_with_options( + &self, + request: crate::KnowledgeReportsUpdateInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.update", &request, options) + .await + } + /// Call `knowledge.reports.evidence`. + pub async fn knowledge_reports_evidence( + &self, + request: crate::KnowledgeReportsEvidenceInput, + ) -> Result { + self.knowledge_reports_evidence_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.reports.evidence` with per-request options and metadata. + pub async fn knowledge_reports_evidence_with_options( + &self, + request: crate::KnowledgeReportsEvidenceInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.reports.evidence", &request, options) + .await + } /// Call `knowledge.citations.check`. pub async fn knowledge_citations_check( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 4c0135bc70..98d4f5b71a 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -887,6 +887,41 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ &["namespace", "org"], &[], ), + ( + "knowledge.reports.submit", + true, + false, + &["namespace", "org"], + &[], + ), + ( + "knowledge.reports.get", + true, + true, + &["namespace", "org"], + &[], + ), + ( + "knowledge.reports.list", + false, + false, + &["namespace", "org"], + &[], + ), + ( + "knowledge.reports.update", + false, + false, + &["namespace", "org"], + &[], + ), + ( + "knowledge.reports.evidence", + false, + false, + &["namespace", "org"], + &[], + ), ( "knowledge.citations.check", true, @@ -27695,6 +27730,823 @@ impl KnowledgeReadsInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsEvidenceOutputState { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsEvidenceOutput { + pub report_id: String, + pub state: KnowledgeReportsEvidenceOutputState, + pub version: Integer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsEvidenceInput { + #[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 report_id: String, + pub evidence: Vec, +} +impl KnowledgeReportsEvidenceInput { + pub fn new( + report_id: impl Into, + evidence: impl IntoIterator>, + ) -> Self { + Self { + org: None, + namespace: None, + report_id: report_id.into(), + evidence: evidence.into_iter().map(Into::into).collect(), + } + } + 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("knowledge.reports.evidence", &self, options) + .await + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportDetailKind { + #[serde(rename = "missing")] + Missing, + #[serde(rename = "incorrect")] + Incorrect, + #[serde(rename = "outdated")] + Outdated, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportDetailState { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportDetailTargetKind { + #[serde(rename = "")] + Empty, + #[serde(rename = "memory")] + Memory, + #[serde(rename = "document")] + Document, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportDetail { + pub report_id: String, + pub version: Integer, + pub kind: KnowledgeReportDetailKind, + pub state: KnowledgeReportDetailState, + #[serde(default = "default_knowledge_report_detail_target_kind")] + pub target_kind: KnowledgeReportDetailTargetKind, + #[serde(default = "default_knowledge_report_detail_target_key")] + pub target_key: String, + #[serde(default = "default_knowledge_report_detail_target_version")] + pub target_version: Integer, + #[serde(default = "default_knowledge_report_detail_target_version_text")] + pub target_version_text: String, + pub reporter: String, + #[serde(default = "default_knowledge_report_detail_assignee")] + pub assignee: String, + pub created_at: String, + pub updated_at: String, + #[serde(default = "default_knowledge_report_detail_target_changed")] + pub target_changed: bool, + pub problem: String, + #[serde(default = "default_knowledge_report_detail_suggested_correction")] + pub suggested_correction: String, + #[serde(default = "default_knowledge_report_detail_run_id")] + pub run_id: String, + #[serde(default = "default_knowledge_report_detail_evidence")] + pub evidence: Vec, + #[serde(default = "default_knowledge_report_detail_related")] + pub related: Vec, + #[serde(default = "default_knowledge_report_detail_reason")] + pub reason: String, + #[serde(default = "default_knowledge_report_detail_resolution_revision")] + pub resolution_revision: String, + #[serde(default = "default_knowledge_report_detail_target_readable")] + pub target_readable: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsGetOutput { + pub found: bool, + #[serde(default = "default_knowledge_reports_get_output_report")] + pub report: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsGetInput { + #[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 report_id: String, +} +impl KnowledgeReportsGetInput { + pub fn new(report_id: impl Into) -> Self { + Self { + org: None, + namespace: None, + report_id: report_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("knowledge.reports.get", &self, options).await + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportKind { + #[serde(rename = "missing")] + Missing, + #[serde(rename = "incorrect")] + Incorrect, + #[serde(rename = "outdated")] + Outdated, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportState { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportTargetKind { + #[serde(rename = "")] + Empty, + #[serde(rename = "memory")] + Memory, + #[serde(rename = "document")] + Document, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReport { + pub report_id: String, + pub version: Integer, + pub kind: KnowledgeReportKind, + pub state: KnowledgeReportState, + #[serde(default = "default_knowledge_report_target_kind")] + pub target_kind: KnowledgeReportTargetKind, + #[serde(default = "default_knowledge_report_target_key")] + pub target_key: String, + #[serde(default = "default_knowledge_report_target_version")] + pub target_version: Integer, + #[serde(default = "default_knowledge_report_target_version_text")] + pub target_version_text: String, + pub reporter: String, + #[serde(default = "default_knowledge_report_assignee")] + pub assignee: String, + pub created_at: String, + pub updated_at: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsListOutput { + #[serde(default = "default_knowledge_reports_list_output_reports")] + pub reports: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsListInputStatesItem { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsListInputKindsItem { + #[serde(rename = "missing")] + Missing, + #[serde(rename = "incorrect")] + Incorrect, + #[serde(rename = "outdated")] + Outdated, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsListInputTargetKind { + #[serde(rename = "")] + Empty, + #[serde(rename = "memory")] + Memory, + #[serde(rename = "document")] + Document, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsListInput { + #[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, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub states: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub kinds: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_kind: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_key: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub assignee: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub reporter: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub limit: Option, +} +impl Default for KnowledgeReportsListInput { + fn default() -> Self { + Self::new() + } +} +impl KnowledgeReportsListInput { + pub fn new() -> Self { + Self { + org: None, + namespace: None, + states: None, + kinds: None, + target_kind: None, + target_key: None, + assignee: None, + reporter: None, + limit: None, + } + } + 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 fn states(mut self, states: Vec) -> Self { + self.states = Some(states); + self + } + pub fn kinds(mut self, kinds: Vec) -> Self { + self.kinds = Some(kinds); + self + } + pub fn target_kind(mut self, target_kind: KnowledgeReportsListInputTargetKind) -> Self { + self.target_kind = Some(target_kind); + self + } + pub fn target_key(mut self, target_key: impl Into) -> Self { + self.target_key = Some(target_key.into()); + self + } + pub fn assignee(mut self, assignee: impl Into) -> Self { + self.assignee = Some(assignee.into()); + self + } + pub fn reporter(mut self, reporter: impl Into) -> Self { + self.reporter = Some(reporter.into()); + self + } + pub fn limit(mut self, limit: impl Into) -> Self { + self.limit = Some(limit.into()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("knowledge.reports.list", &self, options).await + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsSubmitOutputState { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsSubmitOutput { + pub report_id: String, + pub state: KnowledgeReportsSubmitOutputState, + pub version: Integer, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsSubmitInputKind { + #[serde(rename = "missing")] + Missing, + #[serde(rename = "incorrect")] + Incorrect, + #[serde(rename = "outdated")] + Outdated, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsSubmitInputTargetKind { + #[serde(rename = "")] + Empty, + #[serde(rename = "memory")] + Memory, + #[serde(rename = "document")] + Document, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum KnowledgeReportsSubmitInputTargetVersion { + Variant0(Integer), + Variant1(String), +} +impl<'de> Deserialize<'de> for KnowledgeReportsSubmitInputTargetVersion { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + if let Ok(value) = serde_json::from_value::(value.clone()) { + return Ok(Self::Variant0(value)); + } + if let Ok(value) = serde_json::from_value::(value.clone()) { + return Ok(Self::Variant1(value)); + } + Err(serde::de::Error::custom( + "no matching variant for KnowledgeReportsSubmitInputTargetVersion", + )) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsSubmitInput { + #[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, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub agent: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub user_id: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub session_id: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub run_id: Option, + pub kind: KnowledgeReportsSubmitInputKind, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_kind: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_key: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_version: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_sha256: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub target_doc_id: Option, + pub problem: String, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub suggested_correction: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub evidence: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub related: Option>, +} +impl KnowledgeReportsSubmitInput { + pub fn new(kind: KnowledgeReportsSubmitInputKind, problem: impl Into) -> Self { + Self { + org: None, + namespace: None, + agent: None, + user_id: None, + session_id: None, + run_id: None, + kind, + target_kind: None, + target_key: None, + target_version: None, + target_sha256: None, + target_doc_id: None, + problem: problem.into(), + suggested_correction: None, + evidence: None, + related: None, + } + } + 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 fn agent(mut self, agent: impl Into) -> Self { + self.agent = Some(agent.into()); + self + } + pub fn user_id(mut self, user_id: impl Into) -> Self { + self.user_id = Some(user_id.into()); + self + } + pub fn session_id(mut self, session_id: impl Into) -> Self { + self.session_id = Some(session_id.into()); + self + } + pub fn run_id(mut self, run_id: impl Into) -> Self { + self.run_id = Some(run_id.into()); + self + } + pub fn target_kind(mut self, target_kind: KnowledgeReportsSubmitInputTargetKind) -> Self { + self.target_kind = Some(target_kind); + self + } + pub fn target_key(mut self, target_key: impl Into) -> Self { + self.target_key = Some(target_key.into()); + self + } + pub fn target_version( + mut self, + target_version: KnowledgeReportsSubmitInputTargetVersion, + ) -> Self { + self.target_version = Some(target_version); + self + } + pub fn target_sha256(mut self, target_sha256: impl Into) -> Self { + self.target_sha256 = Some(target_sha256.into()); + self + } + pub fn target_doc_id(mut self, target_doc_id: impl Into) -> Self { + self.target_doc_id = Some(target_doc_id.into()); + self + } + pub fn suggested_correction(mut self, suggested_correction: impl Into) -> Self { + self.suggested_correction = Some(suggested_correction.into()); + self + } + pub fn evidence(mut self, evidence: impl IntoIterator>) -> Self { + self.evidence = Some(evidence.into_iter().map(Into::into).collect()); + self + } + pub fn related(mut self, related: impl IntoIterator>) -> Self { + self.related = Some(related.into_iter().map(Into::into).collect()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client + .call("knowledge.reports.submit", &self, options) + .await + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsUpdateOutputState { + #[serde(rename = "open")] + Open, + #[serde(rename = "taken")] + Taken, + #[serde(rename = "needs_evidence")] + NeedsEvidence, + #[serde(rename = "resolved")] + Resolved, + #[serde(rename = "dismissed")] + Dismissed, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsUpdateOutput { + pub report_id: String, + pub state: KnowledgeReportsUpdateOutputState, + pub version: Integer, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeReportsUpdateInputAction { + #[serde(rename = "take")] + Take, + #[serde(rename = "release")] + Release, + #[serde(rename = "request_evidence")] + RequestEvidence, + #[serde(rename = "resolve")] + Resolve, + #[serde(rename = "dismiss")] + Dismiss, + #[serde(rename = "reopen")] + Reopen, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeReportsUpdateInput { + #[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 report_id: String, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub action: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub reason: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub resolution_revision: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub related: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub expected_version: Option>, +} +impl KnowledgeReportsUpdateInput { + pub fn new(report_id: impl Into) -> Self { + Self { + org: None, + namespace: None, + report_id: report_id.into(), + action: None, + reason: None, + resolution_revision: None, + related: None, + expected_version: None, + } + } + 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 fn action(mut self, action: KnowledgeReportsUpdateInputAction) -> Self { + self.action = Some(Some(action)); + self + } + pub fn action_null(mut self) -> Self { + self.action = Some(None); + self + } + pub fn reason(mut self, reason: impl Into) -> Self { + self.reason = Some(reason.into()); + self + } + pub fn resolution_revision(mut self, resolution_revision: impl Into) -> Self { + self.resolution_revision = Some(resolution_revision.into()); + self + } + pub fn related(mut self, related: impl IntoIterator>) -> Self { + self.related = Some(related.into_iter().map(Into::into).collect()); + self + } + pub fn expected_version(mut self, expected_version: impl Into) -> Self { + self.expected_version = Some(Some(expected_version.into())); + self + } + pub fn expected_version_null(mut self) -> Self { + self.expected_version = Some(None); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client + .call("knowledge.reports.update", &self, options) + .await + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[non_exhaustive] pub enum KnowledgeRestoreOutputReason { @@ -70809,6 +71661,66 @@ fn default_query_history_list_output_sources() -> Vec Vec> { serde_json::from_str("[]").expect("schema default") } +fn default_knowledge_report_detail_target_kind() -> KnowledgeReportDetailTargetKind { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_target_key() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_target_version() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_knowledge_report_detail_target_version_text() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_assignee() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_target_changed() -> bool { + serde_json::from_str("false").expect("schema default") +} +fn default_knowledge_report_detail_suggested_correction() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_run_id() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_evidence() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_knowledge_report_detail_related() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_knowledge_report_detail_reason() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_resolution_revision() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_detail_target_readable() -> bool { + serde_json::from_str("true").expect("schema default") +} +fn default_knowledge_reports_get_output_report() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_knowledge_report_target_kind() -> KnowledgeReportTargetKind { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_target_key() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_target_version() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_knowledge_report_target_version_text() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_report_assignee() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_knowledge_reports_list_output_reports() -> Vec { + serde_json::from_str("[]").expect("schema default") +} fn default_knowledge_restore_output_reason() -> KnowledgeRestoreOutputReason { serde_json::from_str("\"\"").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index afb7ec2126..27ec09551d 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -5007,6 +5007,81 @@ fn knowledge_gaps_draft() { assert!(encoded.is_object()); } #[test] +fn knowledge_reports_submit() { + let value: clickhouse_loom::KnowledgeReportsSubmitInput = serde_json::from_str( + "{\"org\":\"sample\",\"namespace\":\"sample\",\"kind\":\"missing\",\"problem\":\"sample\"}", + ) + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeReportsSubmitOutput = + serde_json::from_str("{\"report_id\":\"sample\",\"state\":\"open\",\"version\":1}") + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); +} +#[test] +fn knowledge_reports_get() { + let value: clickhouse_loom::KnowledgeReportsGetInput = serde_json::from_str( + "{\"org\":\"sample\",\"namespace\":\"sample\",\"report_id\":\"sample\"}", + ) + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeReportsGetOutput = + serde_json::from_str("{\"found\":false}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["report"], + serde_json::from_str::("null").unwrap(), + "knowledge.reports.get:report" + ); +} +#[test] +fn knowledge_reports_list() { + let value: clickhouse_loom::KnowledgeReportsListInput = + serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeReportsListOutput = serde_json::from_str("{}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["reports"], + serde_json::from_str::("[]").unwrap(), + "knowledge.reports.list:reports" + ); +} +#[test] +fn knowledge_reports_update() { + let value: clickhouse_loom::KnowledgeReportsUpdateInput = serde_json::from_str( + "{\"org\":\"sample\",\"namespace\":\"sample\",\"report_id\":\"sample\"}", + ) + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeReportsUpdateOutput = + serde_json::from_str("{\"report_id\":\"sample\",\"state\":\"open\",\"version\":1}") + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); +} +#[test] +fn knowledge_reports_evidence() { + let value: clickhouse_loom::KnowledgeReportsEvidenceInput = serde_json::from_str( + "{\"org\":\"sample\",\"namespace\":\"sample\",\"report_id\":\"sample\",\"evidence\":[]}", + ) + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeReportsEvidenceOutput = + serde_json::from_str("{\"report_id\":\"sample\",\"state\":\"open\",\"version\":1}") + .unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); +} +#[test] fn knowledge_citations_check() { let value: clickhouse_loom::KnowledgeCitationsCheckInput = serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\",\"citations\":[]}") diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index f6390e67a3..d180d1179f 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -62,6 +62,44 @@ describe("LoomClient", () => { expect(sent[1].version).toBe(exact); }); + it("files and reads a report on a memory version above 2^53 exactly", async () => { + const exact = "1800000000000000001"; + const sent: Array> = []; + let stored = ""; + const fetch = async (url: string, init: RequestInit) => { + // Keep the version as text, as the server keeps it as an integer. + const raw = init.body as string; + sent.push(JSON.parse(raw)); + let body = `{"found":true,"memory_key":"k","version":${exact},"version_text":"${exact}"}`; + if (url.endsWith("/knowledge.reports.submit")) { + stored = /"target_version":"?(\d+)"?/.exec(raw)?.[1] ?? ""; + body = `{"report_id":"r1","state":"open","version":1}`; + } else if (url.endsWith("/knowledge.reports.get")) { + const changed = stored !== exact; + body = `{"found":true,"report":{"report_id":"r1","version":1,"kind":"outdated","state":"open","target_kind":"memory","target_key":"k","target_version":${stored},"target_version_text":"${stored}","target_changed":${changed},"reporter":"u","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z","problem":"p"}}`; + } + return new Response(body, { status: 200 }); + }; + const c = new LoomClient(new Transport({ baseUrl: "http://x", fetch })); + const scope = { org: "o", namespace: "n" }; + const got = await c.call("memory.get", { ...scope, agent: "a", memory_key: "k" }); + // The number the client parsed is already rounded; the text is exact. + expect(String(got.version)).not.toBe(exact); + await c.call("knowledge.reports.submit", { + ...scope, + agent: "a", + kind: "outdated", + target_kind: "memory", + target_key: "k", + target_version: got.version_text ?? "", + problem: "p", + }); + expect(sent[1].target_version).toBe(exact); + const read = await c.call("knowledge.reports.get", { ...scope, report_id: "r1" }); + expect(read.report?.target_version_text).toBe(exact); + expect(read.report?.target_changed).toBe(false); + }); + it("exposes every generated group as a property", () => { const { c } = client(); for (const g of new Set(OPS.map((o) => o.group))) { diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 0eecae5a92..c13247b2c2 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4595,6 +4595,139 @@ export interface KnowledgeReadsOutput { reads?: Array>; } +export interface KnowledgeReportsEvidenceInput { + org: string; + namespace: string; + report_id: string; + /** References only, never copied text: gap:, reflection: or run:. */ + evidence: string[]; +} + +export interface KnowledgeReportsEvidenceOutput { + report_id: string; + state: "open" | "taken" | "needs_evidence" | "resolved" | "dismissed"; + version: number; +} + +export interface KnowledgeReportsGetInput { + org: string; + namespace: string; + report_id: string; +} + +export interface KnowledgeReportDetail { + report_id: string; + version: number; + kind: "missing" | "incorrect" | "outdated"; + state: "open" | "taken" | "needs_evidence" | "resolved" | "dismissed"; + target_kind?: "" | "memory" | "document"; + target_key?: string; + target_version?: number; + target_version_text?: string; + reporter: string; + assignee?: string; + created_at: string; // date-time + updated_at: string; // date-time + target_changed?: boolean; + problem: string; + suggested_correction?: string; + run_id?: string; + evidence?: string[]; + related?: string[]; + reason?: string; + resolution_revision?: string; + target_readable?: boolean; +} + +export interface KnowledgeReportsGetOutput { + found: boolean; + report?: KnowledgeReportDetail | null; +} + +export interface KnowledgeReportsListInput { + org: string; + namespace: string; + states?: Array<"open" | "taken" | "needs_evidence" | "resolved" | "dismissed">; + kinds?: Array<"missing" | "incorrect" | "outdated">; + target_kind?: "" | "memory" | "document"; + target_key?: string; + assignee?: string; + reporter?: string; + limit?: number; +} + +export interface KnowledgeReport { + report_id: string; + version: number; + kind: "missing" | "incorrect" | "outdated"; + state: "open" | "taken" | "needs_evidence" | "resolved" | "dismissed"; + target_kind?: "" | "memory" | "document"; + target_key?: string; + target_version?: number; + target_version_text?: string; + reporter: string; + assignee?: string; + created_at: string; // date-time + updated_at: string; // date-time +} + +export interface KnowledgeReportsListOutput { + reports?: KnowledgeReport[]; +} + +export interface KnowledgeReportsSubmitInput { + org: string; + namespace: string; + agent?: string; + user_id?: string; + session_id?: string; + /** The run that hit the problem. */ + run_id?: string; + kind: "missing" | "incorrect" | "outdated"; + /** memory or document; empty for a missing-knowledge report. */ + target_kind?: "" | "memory" | "document"; + /** The memory key, or the document's source URI. */ + target_key?: string; + /** The memory version or document revision you read; a decimal string keeps a memory version exact in JavaScript. */ + target_version?: number | string; + /** The content_sha256 an op returned for the target, empty when you have none: memory.get's for a memory, the document row's for a document. */ + target_sha256?: string; + /** For a document: the doc_id knowledge.get returned for the copy you read; required for a document. */ + target_doc_id?: string; + /** What is wrong or missing. */ + problem: string; + suggested_correction?: string; + /** References only, never copied text: gap:, reflection: or run:. */ + evidence?: string[]; + /** Other report ids about the same problem. */ + related?: string[]; +} + +export interface KnowledgeReportsSubmitOutput { + report_id: string; + state: "open" | "taken" | "needs_evidence" | "resolved" | "dismissed"; + version: number; +} + +export interface KnowledgeReportsUpdateInput { + org: string; + namespace: string; + report_id: string; + action?: "take" | "release" | "request_evidence" | "resolve" | "dismiss" | "reopen" | null; + reason?: string; + resolution_revision?: string; + /** Report ids to link. */ + related?: string[]; + /** Refuse when the report changed since this version. */ + expected_version?: number | null; +} + +export interface KnowledgeReportsUpdateOutput { + report_id: string; + state: "open" | "taken" | "needs_evidence" | "resolved" | "dismissed"; + version: number; +} + export interface KnowledgeRestoreInput { org: string; namespace: string; @@ -12413,6 +12546,11 @@ export type OpName = | "knowledge.query_history.list" | "knowledge.query_history.remove" | "knowledge.reads" + | "knowledge.reports.evidence" + | "knowledge.reports.get" + | "knowledge.reports.list" + | "knowledge.reports.submit" + | "knowledge.reports.update" | "knowledge.restore" | "knowledge.search" | "knowledge.source.add" @@ -12837,6 +12975,11 @@ export interface OpMap { "knowledge.query_history.list": { input: KnowledgeQueryHistoryListInput; output: KnowledgeQueryHistoryListOutput }; "knowledge.query_history.remove": { input: KnowledgeQueryHistoryRemoveInput; output: KnowledgeQueryHistoryRemoveOutput }; "knowledge.reads": { input: KnowledgeReadsInput; output: KnowledgeReadsOutput }; + "knowledge.reports.evidence": { input: KnowledgeReportsEvidenceInput; output: KnowledgeReportsEvidenceOutput }; + "knowledge.reports.get": { input: KnowledgeReportsGetInput; output: KnowledgeReportsGetOutput }; + "knowledge.reports.list": { input: KnowledgeReportsListInput; output: KnowledgeReportsListOutput }; + "knowledge.reports.submit": { input: KnowledgeReportsSubmitInput; output: KnowledgeReportsSubmitOutput }; + "knowledge.reports.update": { input: KnowledgeReportsUpdateInput; output: KnowledgeReportsUpdateOutput }; "knowledge.restore": { input: KnowledgeRestoreInput; output: KnowledgeRestoreOutput }; "knowledge.search": { input: KnowledgeSearchInput; output: KnowledgeSearchOutput }; "knowledge.source.add": { input: KnowledgeSourceAddInput; output: KnowledgeSourceAddOutput }; @@ -13261,6 +13404,11 @@ export const OPS: readonly OpSpec[] = [ { name: "knowledge.query_history.list", group: "knowledge", method: "queryHistoryList", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 250, audit: false, readOnly: false }, { name: "knowledge.query_history.remove", group: "knowledge", method: "queryHistoryRemove", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 1000, audit: true, readOnly: false }, { name: "knowledge.reads", group: "knowledge", method: "reads", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 500, audit: false, readOnly: true }, + { name: "knowledge.reports.evidence", group: "knowledge", method: "reportsEvidence", idempotent: false, role: "writer", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: false }, + { name: "knowledge.reports.get", group: "knowledge", method: "reportsGet", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 100, audit: false, readOnly: true }, + { name: "knowledge.reports.list", group: "knowledge", method: "reportsList", idempotent: false, role: "admin", maturity: "experimental", budgetP99Ms: 200, audit: false, readOnly: false }, + { name: "knowledge.reports.submit", group: "knowledge", method: "reportsSubmit", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 400, audit: false, readOnly: false }, + { name: "knowledge.reports.update", group: "knowledge", method: "reportsUpdate", idempotent: false, role: "admin", maturity: "experimental", budgetP99Ms: 300, audit: true, readOnly: false }, { name: "knowledge.restore", group: "knowledge", method: "restore", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 200, audit: true, readOnly: false, clientTimeoutMs: 300000 }, { name: "knowledge.search", group: "knowledge", method: "search", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 250, audit: false, readOnly: true }, { name: "knowledge.source.add", group: "knowledge", method: "sourceAdd", idempotent: false, role: "writer", maturity: "experimental", budgetP99Ms: 60000, audit: true, readOnly: false }, @@ -13532,4 +13680,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 421; +export const GENERATED_OP_COUNT = 426; diff --git a/server/auth/service_accounts.py b/server/auth/service_accounts.py index 7a3c54fc8c..6cac1d910f 100644 --- a/server/auth/service_accounts.py +++ b/server/auth/service_accounts.py @@ -66,11 +66,24 @@ async def agent_signup_tokens(org: str, namespace: str, *, ch: Any | None = None return {str(r["sa_subject"]) for r in rows} +class RegistryUnreadable(Exception): + """The service-account registry could not be read.""" + + async def sa_creator(org: str, sa_subject: str, *, ch: Any | None = None) -> SACreator | None: """The creator of the unrevoked service account `sa_subject` in `org`; None for a subject that is not one, a row with no creator, or a failed - read (fail closed: no inheritance). A found row is cached for the - revocation refresh interval; a miss or a failed read is not.""" + read (fail closed: no inheritance).""" + try: + return await read_sa_creator(org, sa_subject, ch=ch) + except RegistryUnreadable: + return None + + +async def read_sa_creator(org: str, sa_subject: str, *, ch: Any | None = None) -> SACreator | None: + """`sa_creator`, raising `RegistryUnreadable` where the read fails, for a caller that + records a person and must not take a failed read for an account with no creator. A + found row is cached for the revocation refresh interval; a miss or a failed read is not.""" if not sa_subject.startswith("sa:"): return None key = (org, sa_subject) @@ -79,7 +92,7 @@ async def sa_creator(org: str, sa_subject: str, *, ch: Any | None = None) -> SAC return hit[1] try: row = await _creator_row(org, sa_subject, ch=ch) - except Exception as e: # noqa: BLE001 — a failed read inherits nothing (fail closed) + except Exception as e: # every read failure reaches the caller as RegistryUnreadable log.warning( "service_accounts lookup failed for %s/%s: %s", log_value(org), @@ -87,7 +100,7 @@ async def sa_creator(org: str, sa_subject: str, *, ch: Any | None = None) -> SAC log_value(e), ) note_unreadable() - return None + raise RegistryUnreadable("the service-account registry could not be read") from e if row is not None and row["revoked_at"] is not None: return None creator = str((row or {}).get("created_by") or "") @@ -392,9 +405,11 @@ async def revoke(org: str, name: str) -> str | None: __all__ = [ + "RegistryUnreadable", "SACreator", "hand_down_lineage", "inheriting_creator", + "read_sa_creator", "revoke_created_by", "revoked_row", "sa_creator", diff --git a/server/core/ratelimit.py b/server/core/ratelimit.py index b539187033..a3c3cb63ed 100644 --- a/server/core/ratelimit.py +++ b/server/core/ratelimit.py @@ -114,6 +114,7 @@ "knowledge.list", "knowledge.outline", "knowledge.reads", + "knowledge.reports.get", "knowledge.source.inspect", "knowledge.source.list", "knowledge.source.live", diff --git a/server/erasure/app/saga_steps.py b/server/erasure/app/saga_steps.py index 5014ab0709..d13931968e 100644 --- a/server/erasure/app/saga_steps.py +++ b/server/erasure/app/saga_steps.py @@ -135,6 +135,13 @@ async def _step_delete_search_misses_by_user(org: str, user_id: str) -> int: return n + await ledger_steps.delete_search_misses_by_user(org, spellings) +async def _step_delete_knowledge_reports_by_user(org: str, user_id: str) -> int: + """The reports the user filed, and the user's name on the reports they took.""" + return await ledger_steps.delete_knowledge_reports_by_user( + org, await folded_spellings(org, user_id) + ) + + async def _step_delete_read_receipts_by_user(org: str, user_id: str) -> int: """The receipts of the user's reads: as the end user, or as the token's subject under any spelling the directory ties to the user.""" @@ -320,6 +327,7 @@ async def _step_erase_blobs_by_ns(org: str, namespace: _NS) -> int: ("code_search_trace.delete", ledger_steps.delete_code_search_trace_by_namespace), ("search_misses.delete", ledger_steps.delete_search_misses_by_namespace), ("knowledge_gaps.delete", ledger_steps.delete_knowledge_gaps_by_namespace), + ("knowledge_reports.delete", ledger_steps.delete_knowledge_reports_by_namespace), ("events.delete", ledger_steps.delete_events_by_namespace), ("memory_drops.delete", ledger_steps.delete_memory_drops_by_namespace), ("delete_version_checks.delete", ledger_steps.delete_delete_version_checks_by_namespace), @@ -346,6 +354,7 @@ async def _step_erase_blobs_by_ns(org: str, namespace: _NS) -> int: ("read_receipts.delete", _step_delete_read_receipts_by_user), ("code_search_trace.delete", ledger_steps.delete_code_search_trace_by_user), ("search_misses.delete", _step_delete_search_misses_by_user), + ("knowledge_reports.delete", _step_delete_knowledge_reports_by_user), ("events.delete", ledger_steps.delete_events_by_user), ("delete_version_checks.delete", ledger_steps.delete_delete_version_checks_by_user), ("memory_webhook_outbox.delete", ledger_steps.delete_memory_webhook_outbox_by_user), diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py index 7bc9aff30d..85c7d001de 100644 --- a/server/erasure/store/census.py +++ b/server/erasure/store/census.py @@ -19,7 +19,7 @@ from typing import Any from server.core import object_store, pg -from server.core.ch import class_timeout_s, statement_timeout +from server.core.ch import class_timeout_s, sequential_reads, statement_timeout from server.core.repo_base import _CHClient, _default_client from server.erasure.store.mutations import ( namespaces_of, @@ -36,6 +36,7 @@ ORPHAN_LEARNINGS, PAYLOAD_UID, RECEIPT_READER_UP_TO, + REPORT_PERSON, STEWARD_OR_ACTOR, UID, USER_CHUNKS, @@ -96,6 +97,9 @@ class Substrate: # scope alone: "1" counts org-wide (no namespace column), ANSWER_NS_EQ a code answer # asked in the namespace or quoting its memory; None → the namespace predicate. ns_pred: str | None = None + # Counted with sequential consistency: a replica behind an acknowledged write would + # count zero and pass the census with the row live. + sequential: bool = False def counted_in(self, scope_type: str) -> bool: return scope_type == "namespace" or self.user_pred is not None @@ -365,6 +369,16 @@ def owner(self, scope_type: str) -> str | None: # A gap names no user, so the census counts it in the namespace scope only; the # user's search_misses.delete step also deletes the builds of the user's namespaces. Substrate("loom.knowledge_gaps", "1", None, "knowledge_gaps.delete", None), + # A report holds its reporter's words; the user scope also counts the reports the user + # took, until the step clears their name from them. + Substrate( + "loom.knowledge_reports", + "1", + REPORT_PERSON, + "knowledge_reports.delete", + "knowledge_reports.delete", + sequential=True, + ), # When each mirrored source last listed, under its mirror's name: names and times. Substrate( "loom.knowledge_source_listings", "1", None, "knowledge_source_listings.delete", None @@ -929,8 +943,6 @@ async def worker_source_residue( ) -> int: """An owner's worker rows in every namespace, counted raw with sequential consistency, so a namespace the erasure's listing missed still counts.""" - from server.core.ch import sequential_reads - with sequential_reads(): row = await (ch or _default_client()).query_one( f"SELECT count() AS n FROM loom.knowledge_sources WHERE {worker_owner_rows(before)}", @@ -1081,7 +1093,10 @@ async def table_residue( if purge: live = "1" final = " FINAL" if live != "1" and sub.final else "" - with _count_deadline(scope_type): + with ( + _count_deadline(scope_type), + sequential_reads() if sub.sequential else contextlib.nullcontext(), + ): row = await ch.query_one( f"SELECT count() AS n FROM {table}{final} " f"WHERE org = {{org:String}} AND {pred} AND {live}", @@ -1163,7 +1178,7 @@ async def _owned_on_first_page(bucket: str, org: str, namespace: str) -> int: async def connected_restore_residue(*, ch: _CHClient | None = None) -> int: """Offline restore purges all account and connected-source history in this deployment; worker rows are counted too, so the census cannot pass while worker history exists.""" - from server.core.ch import sequential_reads, set_query_tag + from server.core.ch import set_query_tag set_query_tag("erasure.connected_accounts.restore") client = ch or _default_client() diff --git a/server/erasure/store/predicates.py b/server/erasure/store/predicates.py index ebcd364002..40f2e92039 100644 --- a/server/erasure/store/predicates.py +++ b/server/erasure/store/predicates.py @@ -196,6 +196,21 @@ MISS_ASKER = ( "(has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id)))" ) +# A knowledge report the user filed, as its reporter or under their user id, under any of +# the user's spellings, compared as MISS_ASKER compares them. +REPORT_FILED = ( + "(has({spellings:Array(String)}, lowerUTF8(reporter))" + " OR has({spellings:Array(String)}, lowerUTF8(user_id)))" +) +# A knowledge report the user maintained: took it, wrote a version (`written_by`, the person +# its token stood for, folded as the reporter is: a service account's `actor` names the +# account, not its creator) or gave its reason or the resolution of a report with no target +# (`reason_by`). The report stays its reporter's. +REPORT_TAKEN = "has({spellings:Array(String)}, lowerUTF8(assignee))" +REPORT_REASON_BY = "has({spellings:Array(String)}, lowerUTF8(reason_by))" +REPORT_WRITER = "has({spellings:Array(String)}, lowerUTF8(written_by))" +REPORT_MAINTAINED = f"({REPORT_TAKEN} OR {REPORT_REASON_BY} OR {REPORT_WRITER})" +REPORT_PERSON = f"({REPORT_FILED} OR {REPORT_MAINTAINED})" # A receipt of a read the user made: as the end user the read ran as, or as the token's # subject, under any of the user's spellings (`spellings`, as for `MISS_ASKER`). Both # columns keep the case the token gave them, so both are lower-cased here. diff --git a/server/erasure/store/steps_ledgers.py b/server/erasure/store/steps_ledgers.py index f9b66986e3..ddf1d1266a 100644 --- a/server/erasure/store/steps_ledgers.py +++ b/server/erasure/store/steps_ledgers.py @@ -21,6 +21,7 @@ from server.erasure.store import mutations as erasure_mutations from server.erasure.store.census import _count_deadline from server.erasure.store.mutations import ( + count_then_mutate, delete_scoped, namespaces_of, ns_list_predicate, @@ -37,12 +38,18 @@ RECEIPT_NS_BEFORE, RECEIPT_READER, RECEIPT_READER_UP_TO, + REPORT_FILED, + REPORT_MAINTAINED, + REPORT_REASON_BY, + REPORT_TAKEN, + REPORT_WRITER, STEWARD_OR_ACTOR, SUPPORTED_LEARNINGS, UID, label_actors, ) from server.erasure.store.steps_pg import delete_pg_idempotency +from server.knowledge.domain.reports import writer_lease_name as report_writer_lease_name from server.knowledge.domain.source_push import writer_lease_name as push_writer_lease_name from server.observability import events_stream from server.observability.budget_notifications import writer_lease_name @@ -434,6 +441,66 @@ async def delete_knowledge_gaps_by_user( ) +# Knowledge reports: the reporter's words, and what a maintainer wrote on them. Each +# column is cleared only where it names the user; every assignment reads the old row. A +# target's resolution is a checked revision number and stays; one with no target is words. +_REPORT_SCRUB = ( + f"UPDATE assignee = if({REPORT_TAKEN}, '', assignee)," + f" reason = if({REPORT_REASON_BY}, '', reason)," + f" resolution_revision = if(target_kind = '' AND {REPORT_REASON_BY}, '', resolution_revision)," + f" reason_by = if({REPORT_REASON_BY}, '', reason_by)," + f" actor = if({REPORT_WRITER}, '', actor)," + f" written_by = if({REPORT_WRITER}, '', written_by)" +) + + +async def delete_knowledge_reports_by_user( + org: str, spellings: Sequence[str], *, ch: _CHClient | None = None +) -> int: + """Every version of the reports the user filed. On a report the user maintained, every + version loses the user's name as assignee or writer and the reason they gave; the + reporter's words stay. Runs inside the reports' write fence, after any write in flight, + and counts in sequence: a replica behind an acknowledged report counts none.""" + params = {"spellings": list(spellings)} + where = f"org = {{org:String}} AND {REPORT_MAINTAINED}" + async with lease_writes.fenced(report_writer_lease_name(org), ch=ch) as uncertain: + uncertain(True) + with sequential_reads(): + n = await delete_scoped( + "loom.knowledge_reports", org=org, scope_where=REPORT_FILED, params=params, ch=ch + ) + n += await count_then_mutate( + "loom.knowledge_reports", + count_where=where, + mutation=_REPORT_SCRUB, + mutation_where=where, + params={"org": org, **params}, + final=False, + ch=ch, + ) + uncertain(False) + return n + + +async def delete_knowledge_reports_by_namespace( + org: str, namespace: str | Sequence[str], *, ch: _CHClient | None = None +) -> int: + """Runs inside the reports' write fence, after any write in flight, and counts in + sequence, as the user step does.""" + async with lease_writes.fenced(report_writer_lease_name(org), ch=ch) as uncertain: + uncertain(True) + with sequential_reads(): + n = await delete_scoped( + "loom.knowledge_reports", + org=org, + scope_where=NS_EQ, + params={"ns": namespace}, + ch=ch, + ) + uncertain(False) + return n + + async def delete_knowledge_gaps_by_namespace( org: str, namespace: str | Sequence[str], *, ch: _CHClient | None = None ) -> int: diff --git a/server/identity/domain/read_scope.py b/server/identity/domain/read_scope.py index 6b327d8aef..283f9f3069 100644 --- a/server/identity/domain/read_scope.py +++ b/server/identity/domain/read_scope.py @@ -510,11 +510,12 @@ def with_read_identity[M: BaseModel](input: M, scope: ReadFilters) -> M: # Ops under a NARROW_SAFE_OPS prefix that still refuse a narrowed token: a knowledge -# gap lists other people's questions, and a regression suite is the namespace's record, -# read by its administrators only. +# gap lists other people's questions, a knowledge report holds other people's words, and a +# regression suite is the namespace's record, read by its administrators only. NARROW_REFUSED_PREFIXES: tuple[str, ...] = ( "knowledge.gaps.", "knowledge.query_history.", + "knowledge.reports.", "knowledge.suites.", ) # Single ops refused the same way: a live source read and worker setup answer only a diff --git a/server/knowledge/api/models_reports.py b/server/knowledge/api/models_reports.py new file mode 100644 index 0000000000..8323d55cb3 --- /dev/null +++ b/server/knowledge/api/models_reports.py @@ -0,0 +1,188 @@ +"""Wire models of `knowledge.reports.*`.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Literal + +from pydantic import BaseModel, Field, field_validator, model_validator + +ReportKindWire = Literal["missing", "incorrect", "outdated"] +ReportStateWire = Literal["open", "taken", "needs_evidence", "resolved", "dismissed"] +TargetKindWire = Literal["", "memory", "document"] +ReportActionWire = Literal["take", "release", "request_evidence", "resolve", "dismiss", "reopen"] + +_EVIDENCE_HELP = "References only, never copied text: gap:, reflection: or run:." + + +class KnowledgeReportsSubmitInput(BaseModel): + """Report that a memory claim or a document passage is incorrect or outdated, or that + knowledge is missing. A report never edits its target: a maintainer reviews it and + resolves it with the revision that fixed the target, or dismisses it with a reason. + A retry with the same Idempotency-Key returns the same report.""" + + org: str + namespace: str + agent: str = "-" + user_id: str = "-" + session_id: str = "-" + run_id: str = Field(default="", max_length=128, description="The run that hit the problem.") + kind: ReportKindWire + target_kind: TargetKindWire = Field( + default="", description="memory or document; empty for a missing-knowledge report." + ) + target_key: str = Field( + default="", max_length=512, description="The memory key, or the document's source URI." + ) + # The column is UInt64: a larger number must fail here, not at the insert. A decimal + # string is accepted, as memory.delete_version's version: a memory version is a + # nanosecond timestamp above 2^53, which a JavaScript number rounds. + target_version: int | str = Field( + default=0, + description="The memory version or document revision you read; a decimal string" + " keeps a memory version exact in JavaScript.", + ) + target_sha256: str = Field( + default="", + pattern=r"^([0-9a-f]{64})?$", + description="The content_sha256 an op returned for the target, empty when you have" + " none: memory.get's for a memory, the document row's for a document.", + ) + target_doc_id: str = Field( + default="", + max_length=64, + description="For a document: the doc_id knowledge.get returned for the copy you read;" + " required for a document.", + ) + problem: str = Field(min_length=1, max_length=2000, description="What is wrong or missing.") + suggested_correction: str = Field(default="", max_length=4000) + evidence: list[str] = Field(default_factory=list, description=_EVIDENCE_HELP) + related: list[str] = Field( + default_factory=list, description="Other report ids about the same problem." + ) + + @field_validator("target_version") + @classmethod + def _decimal(cls, v: int | str) -> int: + if isinstance(v, str): + if not (v.isascii() and v.isdigit()): + raise ValueError("`target_version` is a version number") + v = int(v) + if not 0 <= v < 2**64: + raise ValueError("`target_version` is a version number") + return v + + +class KnowledgeReportsSubmitOutput(BaseModel): + report_id: str + state: ReportStateWire + version: int + + +class KnowledgeReportsGetInput(BaseModel): + """One report, with the problem, the suggested correction and the evidence, when you + can read its target. A mirrored document's words need the revision it reports.""" + + org: str + namespace: str + report_id: str = Field(min_length=1, max_length=64) + + +class KnowledgeReport(BaseModel): + report_id: str + version: int + kind: ReportKindWire + state: ReportStateWire + target_kind: TargetKindWire = "" + target_key: str = "" + target_version: int = 0 + # The same version as a decimal string, exact for a JavaScript caller (a memory + # version is above 2^53, which JSON.parse rounds). Set from `target_version`. + target_version_text: str = "" + reporter: str + assignee: str = "" + created_at: datetime + updated_at: datetime + + @model_validator(mode="after") + def _target_version_text(self) -> KnowledgeReport: + self.target_version_text = str(self.target_version) + return self + + +class KnowledgeReportDetail(KnowledgeReport): + # True when the target changed or was deleted since the report was filed. + target_changed: bool = False + problem: str + suggested_correction: str = "" + run_id: str = "" + evidence: list[str] = Field(default_factory=list) + related: list[str] = Field(default_factory=list) + reason: str = "" + resolution_revision: str = "" + # False when the caller cannot read the target now, or it is gone: a maintainer then + # sees the report without its words, as for a mirrored copy that changed since. + target_readable: bool = True + + +class KnowledgeReportsGetOutput(BaseModel): + found: bool + report: KnowledgeReportDetail | None = None + + +class KnowledgeReportsListInput(BaseModel): + """The namespace's report queue for maintainers, newest change first. Rows carry no + problem text, correction or target state: open one with knowledge.reports.get.""" + + org: str + namespace: str + states: list[ReportStateWire] = Field(default_factory=list) + kinds: list[ReportKindWire] = Field(default_factory=list) + target_kind: TargetKindWire = "" + target_key: str = Field(default="", max_length=512) + assignee: str = Field(default="", max_length=256) + reporter: str = Field(default="", max_length=256) + limit: int = Field(default=50, ge=1, le=200) + + +class KnowledgeReportsListOutput(BaseModel): + reports: list[KnowledgeReport] = Field(default_factory=list) + + +class KnowledgeReportsUpdateInput(BaseModel): + """A maintainer takes, releases, asks for evidence on, resolves, dismisses or reopens + a report, or links related reports. dismiss, request_evidence and reopen need a + reason. resolve names the published revision that corrected the target.""" + + org: str + namespace: str + report_id: str = Field(min_length=1, max_length=64) + action: ReportActionWire | None = None + reason: str = Field(default="", max_length=2000) + resolution_revision: str = Field(default="", max_length=128) + related: list[str] = Field(default_factory=list, description="Report ids to link.") + expected_version: int | None = Field( + default=None, ge=1, description="Refuse when the report changed since this version." + ) + + +class KnowledgeReportsUpdateOutput(BaseModel): + report_id: str + state: ReportStateWire + version: int + + +class KnowledgeReportsEvidenceInput(BaseModel): + """The reporter adds evidence to their own report, for example after a maintainer + asked for it. The report goes back to its maintainer, or to the queue.""" + + org: str + namespace: str + report_id: str = Field(min_length=1, max_length=64) + evidence: list[str] = Field(min_length=1, description=_EVIDENCE_HELP) + + +class KnowledgeReportsEvidenceOutput(BaseModel): + report_id: str + state: ReportStateWire + version: int diff --git a/server/knowledge/api/ops_reports.py b/server/knowledge/api/ops_reports.py new file mode 100644 index 0000000000..3e69541591 --- /dev/null +++ b/server/knowledge/api/ops_reports.py @@ -0,0 +1,89 @@ +"""The `knowledge.reports.*` operation declarations; their wire models are in +`models_reports`.""" + +from __future__ import annotations + +from server.knowledge.api.models_reports import ( + KnowledgeReportsEvidenceInput, + KnowledgeReportsEvidenceOutput, + KnowledgeReportsGetInput, + KnowledgeReportsGetOutput, + KnowledgeReportsListInput, + KnowledgeReportsListOutput, + KnowledgeReportsSubmitInput, + KnowledgeReportsSubmitOutput, + KnowledgeReportsUpdateInput, + KnowledgeReportsUpdateOutput, +) +from server.knowledge.app.reports import ( + handle_knowledge_reports_evidence, + handle_knowledge_reports_get, + handle_knowledge_reports_list, + handle_knowledge_reports_submit, + handle_knowledge_reports_update, +) +from server.operations.base import Operation, Role + +# A keyed retry replays its answer; without a key the report id finds the filed report, within +# the bounds docs/architecture/knowledge-reports.md names. +knowledge_reports_submit = Operation( + name="knowledge.reports.submit", + maturity="experimental", + input_model=KnowledgeReportsSubmitInput, + output_model=KnowledgeReportsSubmitOutput, + handler=handle_knowledge_reports_submit, + idempotent=True, + required_role=Role.WRITER, +) + +# A reporter reads their own report; a maintainer reads any. +knowledge_reports_get = Operation( + name="knowledge.reports.get", + maturity="experimental", + input_model=KnowledgeReportsGetInput, + output_model=KnowledgeReportsGetOutput, + handler=handle_knowledge_reports_get, + idempotent=True, + required_role=Role.VIEWER, +) + +# Admin: the queue names other people's reports. Not idempotent, so its answer never +# enters the replay cache, which would serve mirrored addresses without their proofs. +knowledge_reports_list = Operation( + name="knowledge.reports.list", + maturity="experimental", + input_model=KnowledgeReportsListInput, + output_model=KnowledgeReportsListOutput, + handler=handle_knowledge_reports_list, + idempotent=False, + required_role=Role.ADMIN, +) + +knowledge_reports_update = Operation( + name="knowledge.reports.update", + maturity="experimental", + input_model=KnowledgeReportsUpdateInput, + output_model=KnowledgeReportsUpdateOutput, + handler=handle_knowledge_reports_update, + idempotent=False, + required_role=Role.ADMIN, + audit=True, +) + +knowledge_reports_evidence = Operation( + name="knowledge.reports.evidence", + maturity="experimental", + input_model=KnowledgeReportsEvidenceInput, + output_model=KnowledgeReportsEvidenceOutput, + handler=handle_knowledge_reports_evidence, + idempotent=False, + required_role=Role.WRITER, +) + +OPERATIONS = [ + knowledge_reports_submit, + knowledge_reports_get, + knowledge_reports_list, + knowledge_reports_update, + knowledge_reports_evidence, +] diff --git a/server/knowledge/app/document_reads.py b/server/knowledge/app/document_reads.py index 3a37d293a9..280444bb77 100644 --- a/server/knowledge/app/document_reads.py +++ b/server/knowledge/app/document_reads.py @@ -35,7 +35,7 @@ from server.knowledge.app import pg_serving, source_publication from server.knowledge.app.readable import readable_namespaces from server.knowledge.app.source_access import ReadPlan -from server.knowledge.app.source_corpus import LostCorpus +from server.knowledge.app.source_corpus import LostCorpus, Proofs from server.knowledge.app.source_list_proofs import ListProofs from server.knowledge.app.source_listing import Position from server.knowledge.domain.chunk_metadata import read_structure @@ -416,6 +416,68 @@ async def handle_knowledge_get(input: KnowledgeGetInput) -> KnowledgeGetOutput: ) +async def document_copy( + org: str, namespace: str, source_uri: str, copy: str | None = None, *, publish: bool +) -> tuple[DocumentRow, str] | None: + """The document at `source_uri` as `knowledge.get` reads it, and the copy it was read + in: '' for the namespace's own, else a mirrored copy's `/`. With + `copy`, that copy alone is read, so another document that later appears at the same + address never stands in for it. `publish` retains a mirrored copy's proof for a + response that serves what the read found, as a get does.""" + from server.knowledge.app import source_access, source_documents + + plan = await source_access.prepare(org, [namespace]) + if not copy: + row = await _ordinary_get_row( + KnowledgeGetInput(org=org, namespace=namespace, source_uri=source_uri) + ) + if row is not None: + return row, "" + if copy == "": + return None + if not plan.marked: + return None + pair = _copy_pair(source_uri, copy) if copy else None + checked = await source_documents.get(plan, namespace, source_uri, copy=pair) + if checked is None: + return None + if publish: + source_publication.retain_document(plan, checked) + mirror, uri = checked.row.namespace, checked.row.source_uri + return checked.row, f"{mirror}/{uri.rpartition('#')[2]}" + + +def _copy_pair(source_uri: str, copy: str) -> tuple[str, str]: + """A mirrored copy's (mirror, source URI) pair from the name `document_copy` gives it.""" + mirror, _, source = copy.partition("/") + return mirror, f"{source_uri}#{source}" + + +async def known_documents( + org: str, namespace: str, targets: list[tuple[str, str]], *, publish: bool +) -> set[tuple[str, str]]: + """The (source URI, copy) pairs among `targets`, copies named as `document_copy` names + them, that the caller may know of: the namespace's own document, deleted ones included, + as `knowledge.get` serves them to every reader, and a mirrored copy the caller's access + list admits now, read once for all of them (`source_documents.admitted_copies`). No + text is read or served. `publish` retains the admitted copies' proofs for a response + that serves their addresses, so access that ends before it is sent refuses it.""" + from server.knowledge.app import source_access, source_documents + from server.knowledge.store import documents as documents_repo + + wanted = list(dict.fromkeys(targets)) + plan = await source_access.prepare(org, [namespace]) + own = [uri for uri, copy in wanted if not copy] + known = {(uri, "") for uri in await documents_repo.known_uris(org, namespace, own)} + pairs = {_copy_pair(uri, copy): (uri, copy) for uri, copy in wanted if copy} + if plan.marked and pairs: + admitted = await source_documents.admitted_copies(plan, namespace, list(pairs)) + if publish: + source_publication.retain(Proofs(plan, tuple(admitted))) + known |= {pairs[(i.candidate["namespace"], i.candidate["source_uri"])] for i in admitted} + return known + + async def ordinary_get(input: KnowledgeGetInput) -> KnowledgeGetOutput: """Read an ordinary document for mining without preparing a mirror leg.""" return _get_output(await _ordinary_get_row(input), input.source_uri) diff --git a/server/knowledge/app/gaps.py b/server/knowledge/app/gaps.py index f8d274e66d..32632eb635 100644 --- a/server/knowledge/app/gaps.py +++ b/server/knowledge/app/gaps.py @@ -5,7 +5,7 @@ memory section abstained. A miss stores the query, so it is recorded only when the operator opted in (`knowledge_gaps_enabled`) and the request's capture level is not `off`, the answer the trace log reads for its query column (an unreadable consent reads as -`off`). The asker is the person the token stands for (`_asker`), never a body field, so +`off`). The asker is the person the token stands for (`token_person`), never a body field, so tokens a person mints for themselves count once. A user erasure deletes the misses whose asker or `user_id` is the user. """ @@ -26,6 +26,7 @@ KnowledgeGapsListOutput, _KnowledgeGap, ) +from server.knowledge.app.people import one_person, token_person from server.knowledge.domain.gaps import normalize_query from server.knowledge.store import gaps as gaps_store from server.memory.domain.sensitivity import detect_sensitivity, reads_high @@ -79,7 +80,7 @@ def record_miss( if settings.effective_identity_provider() == "single-user": # One identity for every caller: a gap, which needs several askers, never forms. return - asker, end_user = _asker() + asker, end_user = token_person() if not asker or not _capturing(): return normalized = normalize_query(query) @@ -137,7 +138,7 @@ async def _insert(row: dict[str, Any], started_s: int) -> None: unfinished at `started_s` or has finished since, and delete it if one starts before the row lands.""" try: - asker = await _person(row["org"], row["asker"]) + asker = await one_person(row["org"], row["asker"]) if not asker: return org, namespace = row["org"], row["namespace"] @@ -213,71 +214,6 @@ def _invoked(op: str) -> bool: return current_operation() == op -def _asker() -> tuple[str, str]: - """(asker, end user): the person the token stands for. The end user of an end-user - token; else the token's `creator` claim, the person at the root of a delegated token - or service account, so the tokens a person mints for themselves count once; else the - token's subject. ('', '') without a token.""" - from server.auth.context import current_auth - from server.core.principals import USER, principal_id - - auth = current_auth() - if auth is None: - return "", "" - end_user = principal_id(auth.subject, USER) - if end_user: - return end_user, end_user - root = auth.creator or auth.subject - return root or "", "" - - -async def _person(org: str, asker: str) -> str: - """The asker folded onto one spelling per person: a service account's creator, and a - human's spelling as the directory ties it (the login handle for a contact email), so - one person's two spellings count once and a user erasure finds them. '' when either - cannot be read.""" - from server.auth.aliases import login_handle - - asker = await _registered_creator(org, asker) - if not asker: - return "" - try: - folded = await login_handle(org, asker) - if folded is None: # tied to two accounts: not one person - return "" - return folded - except Exception as e: # noqa: BLE001 — an unreadable tie records no miss, never a guess - log.warning("knowledge gap asker not resolved: %s", type(e).__name__) - return "" - - -# Service accounts a creator chain may climb before it is treated as unresolved. -_MAX_CREATOR_HOPS = 8 # not a setting: a bound on a registry walk, not a deployment's capacity - - -async def _registered_creator(org: str, asker: str) -> str: - """The person behind a service account, for a token minted without the `creator` - claim: the first subject in its creator chain that is not a service account, as the - registry records it; any other asker as given. '' when the chain cannot be read, has - no person in it, or is longer than `_MAX_CREATOR_HOPS`: an unknown principal is - never counted as a separate person.""" - from server.auth.service_accounts import sa_creator - - subject = asker - for _ in range(_MAX_CREATOR_HOPS): - if not subject.startswith("sa:"): - return subject - creator = await sa_creator(org, subject) - if creator is None or not creator.subject: - return "" - if creator.kind == "agent": - # An agent sign-up: the namespace made its own account, and no person stands - # behind it. - return "" - subject = creator.subject - return "" - - def every_replica_erases_gaps() -> bool: """Whether every live replica runs a build whose erasure knows the gap tables (`instances.every_live_replica_at`).""" @@ -286,6 +222,12 @@ def every_replica_erases_gaps() -> bool: return instances.every_live_replica_at(GAPS_MIGRATION) +def listed() -> bool: + """Whether `knowledge.gaps.list` shows this request a stored build: gaps are on, every + replica erases them and the request may keep query text.""" + return settings.knowledge_gaps_enabled and every_replica_erases_gaps() and _capturing() + + async def handle_knowledge_gaps_list(input: KnowledgeGapsListInput) -> KnowledgeGapsListOutput: """The namespace's gaps of its latest finished build, most askers first. Empty while gaps are off; 503 while an older replica serves (the rollout gate of diff --git a/server/knowledge/app/people.py b/server/knowledge/app/people.py new file mode 100644 index 0000000000..09f52b2262 --- /dev/null +++ b/server/knowledge/app/people.py @@ -0,0 +1,96 @@ +"""The person a request's token stands for, folded onto one spelling per person. + +Knowledge gaps count askers and knowledge reports name reporters this way, so one +person's tokens count once and a user erasure finds their rows by their spellings. +""" + +from __future__ import annotations + +import logging + +log = logging.getLogger(__name__) + +# Service accounts a creator chain may climb before it is treated as unresolved. +_MAX_CREATOR_HOPS = 8 # not a setting: a bound on a registry walk, not a deployment's capacity + + +def token_person() -> tuple[str, str]: + """(person, end user): the person the token stands for. The end user of an end-user + token; else the token's `creator` claim, the person at the root of a delegated token + or service account, so the tokens a person mints for themselves count once; else the + token's subject. ('', '') without a token.""" + from server.auth.context import current_auth + from server.core.principals import USER, principal_id + + auth = current_auth() + if auth is None: + return "", "" + end_user = principal_id(auth.subject, USER) + if end_user: + return end_user, end_user + root = auth.creator or auth.subject + return root or "", "" + + +class PersonUnresolved(Exception): + """The directory could not be read, or ties the subject to two accounts.""" + + def __init__(self, message: str, *, tied: bool = False) -> None: + super().__init__(message) + self.tied = tied + + +async def one_person(org: str, subject: str) -> str: + """`subject` folded onto one spelling per person: a service account's creator, and a + human's spelling as the directory ties it (the login handle for a contact email), so + one person's two spellings count once and a user erasure finds them. '' when either + cannot be read.""" + try: + return await folded_person(org, subject) + except PersonUnresolved: + return "" + + +async def folded_person(org: str, subject: str) -> str: + """`one_person`, raising `PersonUnresolved` where the service-account registry or the + directory fails, or the directory ties the subject to two accounts. '' only when no + person stands behind the subject.""" + from server.auth.aliases import login_handle + + subject = await _registered_creator(org, subject) + if not subject: + return "" + try: + folded = await login_handle(org, subject) + except Exception as e: + log.warning("token person not resolved: %s", type(e).__name__) + raise PersonUnresolved("the directory could not be read") from e + if folded is None: + raise PersonUnresolved("the directory ties the token to two accounts", tied=True) + return folded + + +async def _registered_creator(org: str, subject: str) -> str: + """The person behind a service account, for a token minted without the `creator` + claim: the first subject in its creator chain that is not a service account, as the + registry records it; any other subject as given. '' when the chain has no person in it + or is longer than `_MAX_CREATOR_HOPS`: an unknown principal is never counted as a + separate person. A registry that cannot be read raises `PersonUnresolved`, since the + same token names its person once the registry answers.""" + from server.auth.service_accounts import RegistryUnreadable, read_sa_creator + + for _ in range(_MAX_CREATOR_HOPS): + if not subject.startswith("sa:"): + return subject + try: + creator = await read_sa_creator(org, subject) + except RegistryUnreadable as e: + raise PersonUnresolved("the service-account registry could not be read") from e + if creator is None or not creator.subject: + return "" + if creator.kind == "agent": + # An agent sign-up: the namespace made its own account, and no person stands + # behind it. + return "" + subject = creator.subject + return "" diff --git a/server/knowledge/app/report_refs.py b/server/knowledge/app/report_refs.py new file mode 100644 index 0000000000..f1203f8226 --- /dev/null +++ b/server/knowledge/app/report_refs.py @@ -0,0 +1,52 @@ +"""What a knowledge report's references point at, checked as the caller would read it. + +A run is one of the namespace's runs, read as `run.get` reads it. A reflection is the +reflection memory at that key (`reflection:`), read under the report's identity +tuple as `memory.get` would serve it. A gap is in the namespace's latest gap build, and +only its admins read one, while `knowledge.gaps.list` shows them a build: a gap's samples +are other people's questions. Nothing a reference points at is served or copied. +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from server.knowledge.app import gaps +from server.knowledge.store import gaps as gaps_store + + +async def readable(row: dict[str, Any], refs: list[str], *, admin: bool) -> list[str]: + """The references in `refs` the caller reads now, in their order. `row` holds the + report's org, namespace and identity tuple.""" + found = await asyncio.gather(*(_readable(row, ref, admin=admin) for ref in refs)) + return [ref for ref, ok in zip(refs, found, strict=True) if ok] + + +async def _readable(row: dict[str, Any], ref: str, *, admin: bool) -> bool: + kind, _, ident = ref.partition(":") + org, namespace = row["org"], row["namespace"] + if kind == "run": + from server.tasks.app.run import run_exists + + return await run_exists(org, namespace, ident) + if kind == "reflection": + from server.memory.api.models_crud import MemoryGetInput + from server.memory.app.handlers import readable_version + + lookup = MemoryGetInput( + org=org, + namespace=namespace, + agent=row["agent"], + user_id=row["user_id"], + session_id=row["session_id"], + memory_key=ref, + ) + return await readable_version(lookup) is not None + if kind == "gap": + return ( + admin + and gaps.listed() + and await gaps_store.gap_for_draft(org, namespace, ident) is not None + ) + return False diff --git a/server/knowledge/app/reports.py b/server/knowledge/app/reports.py new file mode 100644 index 0000000000..b1b2b57b0b --- /dev/null +++ b/server/knowledge/app/reports.py @@ -0,0 +1,661 @@ +"""`knowledge.reports.*`: problem reports about memory claims and document passages. + +A reporter says a memory claim or a document is incorrect or outdated, or that knowledge +is missing. Maintainers (namespace admins) take a report, ask for evidence, resolve it +with the revision that corrected the target, or dismiss it with a reason. A report never +edits its target. The reporter is the person the token stands for (`token_person`), +never a body field, so a user erasure finds their reports. Every get checks that the +caller can read the target now; a report whose target the caller cannot read hides the +words written about it. Rules live in `server.knowledge.domain.reports`, statements in +`server.knowledge.store.reports` (docs/architecture/knowledge-reports.md). +""" + +from __future__ import annotations + +import hashlib +import json +import time +from contextlib import AbstractAsyncContextManager +from typing import Any, NamedTuple + +from server.auth import machines +from server.core import ch, lease_writes, leases +from server.core.datetimes import naive_utc_now +from server.core.errors import ( + AuthInsufficientError, + BackendUnavailableError, + ErasureRunningError, + NotFoundError, + OverloadedError, + PreconditionFailedError, + ValidationError, +) +from server.knowledge.api.models_reports import ( + KnowledgeReport, + KnowledgeReportDetail, + KnowledgeReportsEvidenceInput, + KnowledgeReportsEvidenceOutput, + KnowledgeReportsGetInput, + KnowledgeReportsGetOutput, + KnowledgeReportsListInput, + KnowledgeReportsListOutput, + KnowledgeReportsSubmitInput, + KnowledgeReportsSubmitOutput, + KnowledgeReportsUpdateInput, + KnowledgeReportsUpdateOutput, +) +from server.knowledge.app import report_refs +from server.knowledge.app.people import PersonUnresolved, folded_person, token_person +from server.knowledge.domain import reports as rules +from server.knowledge.store import reports as reports_store +from server.memory.app.provenance import writer_actor +from server.memory.domain.provenance import source_class_for + +# The migration that adds loom.knowledge_reports; an older replica's erasure saga has no +# step for it, so no report is written while one serves in any deployment kind. +REPORTS_MIGRATION = 137 # tests/unit/test_knowledge_reports.py ties it to the file + +# A report's changes are read-modify-write under this claim, one writer at a time. +_CLAIM_TTL_S = 30.0 # not a setting: one change's bound, not a capacity +_CLAIM_WAIT_S = 5.0 # not a setting: how long a second writer waits its turn + + +async def every_replica_stores_reports() -> bool: + """Whether every live replica of every deployment kind runs a build whose erasure + knows loom.knowledge_reports. An unread fleet counts as no.""" + return await machines.fleet_at(ch.get_client(), REPORTS_MIGRATION) + + +async def _require_rollout() -> None: + if not await every_replica_stores_reports(): + raise OverloadedError( + "not every replica serves knowledge reports yet; retry once the rollout is done", + retry_after_s=30, + ) + + +def _stamped(row: dict[str, Any], writer: str) -> dict[str, Any]: + """The version with its writer stamped from the token, never the body: `actor` is the + token's principal and `written_by` the person it stands for (`writer`, from `_person`), + whom a user erasure matches. With auth off `writer` is the identity's agent or '-'.""" + return { + **row, + "actor": writer_actor(writer), + "written_by": writer, + "source_class": source_class_for(default="asserted"), + } + + +def _refusal(e: rules.ReportRefused) -> ValidationError: + return ValidationError(str(e)) + + +def _cited(evidence: list[str], run_id: str) -> list[str]: + return [*evidence, f"run:{run_id}"] if run_id else list(evidence) + + +def _cites_gaps(refs: list[str]) -> bool: + return any(ref.startswith("gap:") for ref in refs) + + +async def _check_cited(row: dict[str, Any], refs: list[str]) -> None: + """Refuse a reference the caller cannot read, answered as not found whether it is + missing or only unreadable.""" + admin = _cites_gaps(refs) and await _maintainer(row["org"], row["namespace"]) + readable = set(await report_refs.readable(row, refs, admin=admin)) + unread = [ref for ref in refs if ref not in readable] + if unread: + raise ValidationError(f"evidence {unread[0][:80]!r} was not found") + + +async def _person(org: str) -> str: + """The person the token stands for, folded onto one spelling; the token's own principal + when no person stands behind it (an agent's own account); '' with auth off. An unfolded + person is refused, never stored under a spelling that stops matching once it folds.""" + person, _ = token_person() + if not person: + return "" + try: + return await folded_person(org, person) or person + except PersonUnresolved as e: + if e.tied: + raise AuthInsufficientError( + "the directory ties the token to two accounts; a report needs one person" + ) from e + raise BackendUnavailableError("the directory could not be read; retry") from e + + +async def _maintainer(org: str, namespace: str) -> bool: + """Whether the caller administers the namespace now, as the gate decides it: a lowered + grant ends an older token's admin claim. With auth off everyone does.""" + from server.auth.authz import row_in_scope + from server.operations.base import Role + + return await row_in_scope(org, namespace, Role.ADMIN) + + +class _Target(NamedTuple): + """A target as the caller reads it: its version or revision and `content_sha256`, a + memory target's row identity, and a document's copy (`document_copy`) and doc_id.""" + + version: int + sha256: str + identity: tuple[str, str, str] | None = None + copy: str = "" + doc_id: str = "" + + +async def _target_now( + row: dict[str, Any], *, exact: bool = True, publish: bool = False +) -> _Target | None: + """The target as the caller can read it now, `_Target(0, '')` for a report with no + target, None when the caller cannot read it or it is gone. A memory target is read + under the report's identity tuple: `exact` reads only the row stored under it, the one + the report is about; otherwise as `memory.get` reads it, which may find another agent's + or session's row of the same user, never another user's. A document target is read in + the report's copy alone, so another document at its address never stands in for it; + otherwise as `knowledge.get` reads it. `publish` keeps a mirrored copy's proof for a + response that serves words about it; a write's answer serves none.""" + if not row["target_kind"]: + return _Target(0, "") + if row["target_kind"] == "memory": + from server.memory.api.models_crud import MemoryGetInput + from server.memory.app.handlers import readable_version + + found = await readable_version( + MemoryGetInput( + org=row["org"], + namespace=row["namespace"], + agent=row["agent"], + user_id=row["user_id"], + session_id=row["session_id"], + memory_key=row["target_key"], + ), + exact=exact, + ) + # Agent "*" reads the key across users: a report keeps its user, as `same_user` does. + if found is None or found.user_id != row["user_id"]: + return None + return _Target( + found.version, found.content_sha256, (found.agent, found.user_id, found.session_id) + ) + from server.knowledge.app.document_reads import document_copy + + read = await document_copy( + row["org"], + row["namespace"], + row["target_key"], + row["target_copy"] if exact else None, + publish=publish, + ) + if read is None: + return None + doc, copy = read + return _Target(doc.revision, doc.content_sha256, copy=copy, doc_id=doc.doc_id) + + +def _changed(row: dict[str, Any], now: _Target | None) -> bool: + if not row["target_kind"]: + return False + if now is None: + return True + # A legacy document is at revision 0 with no hash until its first numbered revision. + return int(row["target_version"]) != now.version or bool( + row["target_sha256"] and row["target_sha256"] != now.sha256 + ) + + +async def _known_documents( + org: str, namespace: str, rows: list[dict[str, Any]] +) -> set[tuple[str, str]]: + """The documents `rows` are about, as (address, copy) pairs, that the caller may know + of: a mirrored copy's address belongs to its readers alone. Their proofs are kept for + the response that serves these rows.""" + from server.knowledge.app.document_reads import known_documents + + targets = [(r["target_key"], r["target_copy"]) for r in rows if r["target_kind"] == "document"] + return await known_documents(org, namespace, targets, publish=True) if targets else set() + + +async def _known_copies(org: str, namespace: str, address: str, copies: list[str]) -> list[str]: + """The copies of one address among `copies` the caller may know of now. No proof is + kept: only the rows a page serves are checked for the response (`_known_documents`).""" + from server.knowledge.app.document_reads import known_documents + + if not copies: + return [] + pairs = [(address, c) for c in copies] + return sorted(c for _, c in await known_documents(org, namespace, pairs, publish=False)) + + +def _addressed(row: dict[str, Any], known: set[tuple[str, str]]) -> bool: + """Whether the caller may read the report's target address: any memory key (the + namespace's readers read every one) or a document whose copy is in `known`.""" + return row["target_kind"] != "document" or (row["target_key"], row["target_copy"]) in known + + +def _is_reporter(row: dict[str, Any], person: str) -> bool: + """Whether the caller filed the report. With auth off no token names a caller, so every + caller is its reporter, as every caller is a maintainer.""" + return not person or row["reporter"] == person + + +def _summary(row: dict[str, Any], *, known: bool = True) -> KnowledgeReport: + """A report's row; `known` False leaves out its document's address and revision, which + a caller who may not know of the document does not read (`known_documents`).""" + return KnowledgeReport( + report_id=row["report_id"], + version=int(row["version"]), + kind=row["kind"], + state=row["state"], + target_kind=row["target_kind"], + target_key=row["target_key"] if known else "", + target_version=int(row["target_version"]) if known else 0, + reporter=row["reporter"], + assignee=row["assignee"], + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +def _report_id(row: dict[str, Any]) -> str: + """The same reporter filing the same problem about the same target gets the same id, so + a retry without an Idempotency-Key still files one report. A memory target is the row + its key was read in, named by that row's identity tuple: two reads that find one row + file one report, and the same key in two users' rows is two targets. A document target + is its address: the copies visible at it change between a filing and its retry, so the + copy is bound in the row and never names the report.""" + basis = [ + row["org"], + row["namespace"], + row["reporter"], + row["kind"], + row["target_kind"], + row["target_key"], + " ".join(row["problem"].split()), + ] + if row["target_kind"] == "memory": + basis += [row["agent"], row["user_id"], row["session_id"]] + return hashlib.sha256(json.dumps(basis).encode()).hexdigest()[:32] + + +async def _readable_reports( + org: str, namespace: str, ids: list[str], person: str | None, *, admin: bool | None = None +) -> set[str]: + """The ids in `ids` of reports the caller reads as `get` decides it: their own, or any + that exists for a maintainer. `person` None matches no reporter; `admin` None asks.""" + rows = await reports_store.latest_many(org, namespace, ids) + found = {r["report_id"] for r in rows if person is not None and _is_reporter(r, person)} + # The admin check reads grants: it is asked only where the answer depends on it. + if len(found) < len(rows) and ( + admin if admin is not None else await _maintainer(org, namespace) + ): + found = {r["report_id"] for r in rows} + return found + + +async def _linked( + org: str, namespace: str, own: str, linked: list[str], adding: list[str], person: str +) -> list[str]: + """`linked` followed by the ids in `adding` it lacks, each a report the caller reads + (`_readable_reports`); a missing and an unreadable one get the same refusal. A link + already held stays even if its report was erased.""" + new = [i for i in dict.fromkeys(adding) if i and i not in linked] + if own in new: + raise ValidationError("a report cannot be related to itself") + if len(linked) + len(new) > rules.MAX_RELATED: + raise ValidationError(f"at most {rules.MAX_RELATED} related reports") + found = await _readable_reports(org, namespace, new, person) + missing = [i for i in new if i not in found] + if missing: + raise ValidationError(f"related report {missing[0][:64]!r} was not found") + return [*linked, *new] + + +async def _fenced_insert(row: dict[str, Any], started_s: int, people: set[str]) -> None: + """Insert a report version inside the write fence both report erasers take, refusing + while an erasure reaching the report is unfinished or has finished since `started_s`. + A send whose outcome is unknown keeps the fence until it settles, so an eraser never + runs before it lands. `people`: everyone the version names (`_named`) and its writer.""" + from server.knowledge.app.gaps import erasure_since + + org, namespace = row["org"], row["namespace"] + reaching = {p for p in people if p and p != "-"} + name = rules.writer_lease_name(org) + async with lease_writes.fenced_many([name], wait_s=_CLAIM_WAIT_S) as uncertain: + if await erasure_since(org, namespace, started_s, reaching): + raise ErasureRunningError("an erasure reaching this report is running; retry after it") + uncertain(True) + await reports_store.insert_version(row) + uncertain(False) + + +def _named(row: dict[str, Any]) -> set[str]: + """The people a stored version names, whose erasure a write carrying it forward must + wait for: the reporter, the row's user, the assignee and the reason's author.""" + return {row["reporter"], row["user_id"], row["assignee"], row["reason_by"]} + + +def _claim(org: str, namespace: str, report_id: str) -> AbstractAsyncContextManager[bool]: + """One writer of a report at a time, across replicas.""" + return leases.holding( + f"knowledge-report:{org}:{namespace}:{report_id}", ttl_s=_CLAIM_TTL_S, wait_s=_CLAIM_WAIT_S + ) + + +def _first_version( + input: KnowledgeReportsSubmitInput, reporter: str, problem: str, evidence: list[str] +) -> dict[str, Any]: + """Version 1 of a report under the body's identity tuple, before its id, its links + and the target it read are known.""" + now = naive_utc_now() + return { + "org": input.org, + "namespace": input.namespace, + "agent": input.agent, + "user_id": input.user_id, + "session_id": input.session_id, + "report_id": "", + "version": 1, + "kind": input.kind, + "state": "open", + "target_kind": input.target_kind, + "target_key": input.target_key, + "target_version": int(input.target_version), # the validator made it an int + "target_sha256": input.target_sha256, + "target_copy": "", + "problem": problem, + "suggested_correction": input.suggested_correction.strip(), + "run_id": input.run_id, + "evidence": evidence, + "related": [], + "reporter": reporter, + "assignee": "", + "reason": "", + "reason_by": "", + "resolution_revision": "", + "written_by": "", + "created_at": now, + "updated_at": now, + } + + +def _check_read(input: KnowledgeReportsSubmitInput, target: _Target) -> None: + """Refuse a report whose version, hash or doc_id the target found now does not hold: it + was read in another memory row or document copy at the key, or an older version, and + its words would bind to this one. Copies can share a revision and text, never a doc_id.""" + version, sha = int(input.target_version), input.target_sha256 + if input.target_kind and ( + (input.target_kind == "document" and input.target_doc_id != target.doc_id) + or (version and version != target.version) + or (sha and sha != target.sha256) + ): + raise PreconditionFailedError( + f"{input.target_kind} {input.target_key[:200]!r} is not the version you read;" + " read it again" + ) + + +def _busy() -> OverloadedError: + return OverloadedError("another change to this report is running; retry", retry_after_s=1) + + +async def handle_knowledge_reports_submit( + input: KnowledgeReportsSubmitInput, +) -> KnowledgeReportsSubmitOutput: + """File a report, or return the one the same reporter already filed about the same + problem, in the state it is in now. The caller must be able to read the target; one + they cannot read answers as not found.""" + await _require_rollout() + started_s = int(time.time()) + try: + rules.check_target(input.kind, input.target_kind, input.target_key, input.target_doc_id) + problem = rules.check_problem(input.problem) + evidence = rules.check_evidence(input.evidence) + except rules.ReportRefused as e: + raise _refusal(e) from e + person = await _person(input.org) + row = _first_version(input, person or input.agent, problem, evidence) + # Read before the id: a memory key binds the report to the row memory.get finds it in, + # which may be another agent's or session's row of the same user. A document's copy is + # bound too, but only a first filing stores it: a repeat returns the stored report. + target = await _target_now(row, exact=False) + if target is not None: + row["target_copy"] = target.copy + if target.identity is not None: + row["agent"], row["user_id"], row["session_id"] = target.identity + report_id = row["report_id"] = _report_id(row) + # A repeat is answered before the checks that could have changed since the first filing. + existing = await reports_store.latest(input.org, input.namespace, report_id) + if existing is not None: + return KnowledgeReportsSubmitOutput( + report_id=report_id, state=existing["state"], version=int(existing["version"]) + ) + if target is None: + raise NotFoundError(f"{input.target_kind} {input.target_key[:200]!r} was not found") + _check_read(input, target) + row["related"] = await _linked(input.org, input.namespace, report_id, [], input.related, person) + # What the reporter read, else what is there now. + row["target_version"] = int(input.target_version) or target.version + row["target_sha256"] = input.target_sha256 or target.sha256 + await _check_cited(row, _cited(evidence, input.run_id)) + async with _claim(input.org, input.namespace, report_id) as held: + if not held: + raise _busy() + existing = await reports_store.latest(input.org, input.namespace, report_id) + if existing is not None: + return KnowledgeReportsSubmitOutput( + report_id=report_id, state=existing["state"], version=int(existing["version"]) + ) + people = {row["reporter"], row["user_id"]} + await _fenced_insert(_stamped(row, row["reporter"]), started_s, people) + return KnowledgeReportsSubmitOutput(report_id=report_id, state="open", version=1) + + +async def handle_knowledge_reports_get( + input: KnowledgeReportsGetInput, +) -> KnowledgeReportsGetOutput: + """One report for its reporter or a maintainer; anyone else is answered not found. A + maintainer who cannot read the target now sees the report without its words.""" + # Resolved before the read, so a refusal never says whether the report exists. + person: str | None + try: + person = await _person(input.org) + except (AuthInsufficientError, BackendUnavailableError): + # A maintainer reads any report, so only the reporter match is lost. + if not await _maintainer(input.org, input.namespace): + raise + person = None + row = await reports_store.latest(input.org, input.namespace, input.report_id) + if row is None: + return KnowledgeReportsGetOutput(found=False) + mine = person is not None and _is_reporter(row, person) + # The admin check reads grants: it is asked only where the answer depends on it. + admin: bool | None = None + if not mine or _cites_gaps(row["evidence"]): + admin = await _maintainer(input.org, input.namespace) + if not mine and not admin: + return KnowledgeReportsGetOutput(found=False) + target = await _target_now(row, publish=True) + readable = target is not None + changed = _changed(row, target) + # A mirrored copy's access list can change with each revision: reading it now proves + # access to the reported revision only while the copy still holds that revision. + quotable = readable and not (row["target_copy"] and changed) + # The reporter wrote the address; anyone else reads it only if they may know of it. + known = ( + mine + or readable + or _addressed(row, await _known_documents(input.org, input.namespace, [row])) + ) + # Each reference and related report is served only while this caller reads it. + cited = set( + await report_refs.readable(row, _cited(row["evidence"], row["run_id"]), admin=bool(admin)) + ) + related = await _readable_reports( + input.org, input.namespace, list(row["related"]), person, admin=admin + ) + # Words about the target may quote it: the reporter reads their own, and anyone reads + # the rest only while they read what was reported. + detail = KnowledgeReportDetail( + **_summary(row, known=known).model_dump(), + target_changed=changed, + problem=row["problem"] if mine or quotable else "", + suggested_correction=row["suggested_correction"] if mine or quotable else "", + run_id=row["run_id"] if f"run:{row['run_id']}" in cited else "", + evidence=[ref for ref in row["evidence"] if ref in cited], + related=[i for i in row["related"] if i in related], + reason=row["reason"] if quotable else "", + resolution_revision=row["resolution_revision"] if known else "", + target_readable=readable, + ) + return KnowledgeReportsGetOutput(found=True, report=detail) + + +async def handle_knowledge_reports_list( + input: KnowledgeReportsListInput, +) -> KnowledgeReportsListOutput: + """The namespace's queue, newest change first, without anyone's words. A row about a + document the caller may not know of carries no address.""" + copies: list[str] | None = None + if input.target_key and input.target_kind != "memory": + # The address's copies the caller may know of, applied before the limit: a report on + # a hidden copy is never found and never takes a place on the page. + filed = await reports_store.copies_at(input.org, input.namespace, input.target_key) + copies = await _known_copies(input.org, input.namespace, input.target_key, filed) + rows = await reports_store.list_reports( + input.org, + input.namespace, + states=list(input.states), + kinds=list(input.kinds), + target_kind=input.target_kind, + target_key=input.target_key, + assignee=input.assignee, + reporter=input.reporter, + limit=input.limit, + copies=copies, + ) + # Checked again for the page's own copies, with proofs: a copy the page leaves out never + # holds the response, and a filtered page drops a copy the caller stopped knowing. + known = await _known_documents(input.org, input.namespace, rows) + if copies is not None: + rows = [r for r in rows if _addressed(r, known)] + return KnowledgeReportsListOutput( + reports=[_summary(r, known=_addressed(r, known)) for r in rows] + ) + + +async def handle_knowledge_reports_update( + input: KnowledgeReportsUpdateInput, +) -> KnowledgeReportsUpdateOutput: + """A maintainer's action on a report, and links to related reports. A report about a + target that changed can still be resolved; one that is gone can be dismissed.""" + await _require_rollout() + started_s = int(time.time()) + if input.action is None and not input.related: + raise ValidationError("name an action or related reports to link") + try: + if input.action is not None: + rules.check_action( + input.action, + reason=input.reason, + resolution_revision=input.resolution_revision, + ) + elif input.reason or input.resolution_revision: + raise rules.ReportRefused("reason and resolution_revision go with an action") + except rules.ReportRefused as e: + raise _refusal(e) from e + person = await _person(input.org) + maintainer = person or "-" + async with _claim(input.org, input.namespace, input.report_id) as held: + if not held: + raise _busy() + row = await reports_store.latest(input.org, input.namespace, input.report_id) + if row is None: + raise NotFoundError(f"report {input.report_id!r} was not found") + if input.expected_version is not None and int(row["version"]) != input.expected_version: + raise PreconditionFailedError( + f"report {input.report_id!r} is at version {row['version']}," + f" not {input.expected_version}" + ) + next_row = dict(row) + if input.action is not None: + try: + next_row["state"] = rules.next_state(row["state"], input.action) + if input.action == "resolve" and row["target_kind"]: + served = await _target_now(row) + rules.check_resolution( + input.resolution_revision.strip(), + int(row["target_version"]), + None if served is None else served.version, + ) + except rules.ReportRefused as e: + raise _refusal(e) from e + if input.action == "take": + next_row["assignee"] = maintainer + elif input.action in ("release", "reopen"): + next_row["assignee"] = "" + reason, resolution = input.reason.strip(), input.resolution_revision.strip() + if input.action in ("resolve", "reopen"): # reopen clears the resolution + next_row["resolution_revision"] = resolution + # A reason, and a resolution with no target, are words `reason_by` wrote: an action + # with words replaces them, one without carries them forward. Erasure clears both. + if reason or (input.action == "resolve" and not row["target_kind"]): + next_row["reason"], next_row["reason_by"] = reason, maintainer + if input.related: + next_row["related"] = await _linked( + input.org, + input.namespace, + row["report_id"], + list(row["related"]), + input.related, + person, + ) + next_row["version"] = int(row["version"]) + 1 + next_row["updated_at"] = naive_utc_now() + await _fenced_insert(_stamped(next_row, maintainer), started_s, {*_named(row), maintainer}) + return KnowledgeReportsUpdateOutput( + report_id=row["report_id"], state=next_row["state"], version=next_row["version"] + ) + + +async def _own_report(input: KnowledgeReportsEvidenceInput, person: str) -> dict[str, Any]: + """The caller's own report, else not found whether it is missing or another's.""" + row = await reports_store.latest(input.org, input.namespace, input.report_id) + if row is None or not _is_reporter(row, person): + raise NotFoundError(f"report {input.report_id!r} was not found") + return row + + +async def handle_knowledge_reports_evidence( + input: KnowledgeReportsEvidenceInput, +) -> KnowledgeReportsEvidenceOutput: + """The reporter adds evidence to their own report; another caller is answered not + found. A report waiting for evidence goes back to its maintainer, or to the queue.""" + await _require_rollout() + started_s = int(time.time()) + # Resolved before the read, so a refusal never says whether the report exists. + person = await _person(input.org) + # Checked before the claim as well: a busy report answers another caller 404, not 503. + await _own_report(input, person) + async with _claim(input.org, input.namespace, input.report_id) as held: + if not held: + raise _busy() + row = await _own_report(input, person) + try: + evidence = rules.check_evidence(list(row["evidence"]) + input.evidence) + state = rules.after_evidence(row["state"], row["assignee"]) + except rules.ReportRefused as e: + raise _refusal(e) from e + await _check_cited(row, [ref for ref in evidence if ref not in row["evidence"]]) + next_row = { + **row, + "evidence": evidence, + "state": state, + "version": int(row["version"]) + 1, + "updated_at": naive_utc_now(), + } + await _fenced_insert(_stamped(next_row, row["reporter"]), started_s, _named(row)) + return KnowledgeReportsEvidenceOutput( + report_id=row["report_id"], state=state, version=next_row["version"] + ) diff --git a/server/knowledge/app/source_documents.py b/server/knowledge/app/source_documents.py index f45131bc36..f9da4e4a08 100644 --- a/server/knowledge/app/source_documents.py +++ b/server/knowledge/app/source_documents.py @@ -76,13 +76,18 @@ async def refresh(plan: ReadPlan, document: CheckedDocument) -> CheckedDocument return None -async def get(plan: ReadPlan, namespace: str, source_uri: str) -> CheckedDocument | None: - """Admit metadata before text, then retain only an unchanged, freshly admitted copy.""" +async def get( + plan: ReadPlan, namespace: str, source_uri: str, *, copy: tuple[str, str] | None = None +) -> CheckedDocument | None: + """Admit metadata before text, then retain only an unchanged, freshly admitted copy. + `copy`, a (mirror, source URI) pair, reads that copy alone.""" pairs = sorted( (mirror, source_uri + "#" + source) for (mirror, source), original in plan.discovery_sources.items() if original == namespace ) + if copy is not None: + pairs = [pair for pair in pairs if pair == copy] set_query_tag("knowledge.mirror.document") with private_work(), sequential_reads(): candidates = await _discover(plan, pairs) @@ -124,6 +129,30 @@ async def get(plan: ReadPlan, namespace: str, source_uri: str) -> CheckedDocumen return None +async def admitted_copies( + plan: ReadPlan, namespace: str, copies: list[tuple[str, str]] +) -> list[Admitted]: + """The copies among `copies`, (mirror, source URI) pairs of this namespace's mirrors, + that the reader's access list admits now, decided from metadata in bounded batches: no + text is read. A failed read admits none, as every mirror leg fails closed.""" + pairs = sorted( + { + (mirror, uri) + for mirror, uri in copies + if plan.discovery_sources.get((mirror, uri.rpartition("#")[2])) == namespace + } + ) + set_query_tag("knowledge.mirror.document_admission") + with private_work(), sequential_reads(): + candidates = await _discover(plan, pairs) + admitted: list[Admitted] = [] + for start in range(0, len(candidates), 64): + admitted.extend(await plan.check(candidates[start : start + 64])) + if plan.failed or plan.unread: + return [] + return [item for item in admitted if plan.current(item)] + + async def _chunk_batch(plan: ReadPlan, batch: list[dict[str, Any]], model: str) -> list[Hydrated]: admitted = await plan.check(batch, chunks=True) hydrated = await source_search.hydrate( diff --git a/server/knowledge/domain/reports.py b/server/knowledge/domain/reports.py new file mode 100644 index 0000000000..b135318e6c --- /dev/null +++ b/server/knowledge/domain/reports.py @@ -0,0 +1,137 @@ +"""Knowledge problem reports: kinds, states and the transitions between them. + +A report says that a memory claim or a document passage is incorrect or outdated, or +that knowledge is missing. Maintainers take it, ask for evidence, resolve it with the +revision that corrected the target, or dismiss it with a reason. A report never edits +its target. No I/O here; the handlers in `server/knowledge/app/reports.py` load and +store rows. +""" + +from __future__ import annotations + +import re +from typing import Literal + +ReportKind = Literal["missing", "incorrect", "outdated"] +ReportState = Literal["open", "taken", "needs_evidence", "resolved", "dismissed"] +TargetKind = Literal["memory", "document"] +MaintainerAction = Literal["take", "release", "request_evidence", "resolve", "dismiss", "reopen"] + +FINAL_STATES: frozenset[str] = frozenset({"resolved", "dismissed"}) + +# Evidence a report may cite, by prefix: a knowledge gap, a reflection, a graded run. +EVIDENCE_PREFIXES: tuple[str, ...] = ("gap", "reflection", "run") +_EVIDENCE_ID = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") +MAX_EVIDENCE = 20 # not a setting: a bound on one report's citations, not a capacity +MAX_RELATED = 20 # not a setting: a bound on one report's links + + +def writer_lease_name(org: str) -> str: + """The durable write fence every report write and both report erasers take.""" + return f"knowledge_reports.writer/{org}" + + +class ReportRefused(ValueError): + """The request breaks a report rule; the message says which.""" + + +def check_target(kind: str, target_kind: str, target_key: str, doc_id: str = "") -> None: + """Incorrect and outdated reports name what is wrong; a missing-knowledge report may + name nothing. A document names the doc_id it was read as: copies at one address can + share a revision and text, so only the doc_id says which copy was read.""" + if target_kind and not target_key: + raise ReportRefused("a target names its memory key or document source URI") + if target_key and not target_kind: + raise ReportRefused("a target key needs target_kind memory or document") + if kind in ("incorrect", "outdated") and not target_kind: + raise ReportRefused(f"an {kind} report names the memory or document it is about") + if target_kind == "document" and not doc_id: + raise ReportRefused("a document report names the target_doc_id knowledge.get returned") + if doc_id and target_kind != "document": + raise ReportRefused("target_doc_id is only for a document") + + +def check_problem(problem: str) -> str: + """The problem as stored: trimmed, and never empty.""" + text = problem.strip() + if not text: + raise ReportRefused("a report says what is wrong or missing") + return text + + +def check_evidence(refs: list[str]) -> list[str]: + """Each reference is `gap:`, `reflection:` or `run:`. Returns them in + order with duplicates dropped; a repeat does not count toward `MAX_EVIDENCE`.""" + seen: dict[str, None] = {} + for ref in refs: + if ref in seen: + continue + prefix, _, ident = ref.partition(":") + if prefix not in EVIDENCE_PREFIXES or not _EVIDENCE_ID.match(ident): + raise ReportRefused( + f"evidence reference {ref[:40]!r} is not gap:, reflection: or run:" + ) + seen[ref] = None + if len(seen) > MAX_EVIDENCE: + raise ReportRefused(f"at most {MAX_EVIDENCE} evidence references") + return list(seen) + + +def next_state(state: ReportState, action: str) -> ReportState: + """The state a maintainer action moves a report to. Refuses an action that does not + apply in the current state.""" + if action == "reopen": + if state not in FINAL_STATES: + raise ReportRefused(f"only a resolved or dismissed report reopens, not {state}") + return "open" + if state in FINAL_STATES: + raise ReportRefused(f"a {state} report changes only by reopen") + if action == "take": + return "taken" + if action == "release": + if state != "taken": + raise ReportRefused("only a taken report is released") + return "open" + if action == "request_evidence": + return "needs_evidence" + if action == "resolve": + return "resolved" + if action == "dismiss": + return "dismissed" + raise ReportRefused(f"unknown action {action!r}") + + +def check_action(action: str, *, reason: str, resolution_revision: str) -> None: + """A dismissal and an evidence request say why. A resolution names the published + revision that corrected the target: a draft or a recommendation is not a fix.""" + if action in ("dismiss", "request_evidence", "reopen") and not reason.strip(): + raise ReportRefused(f"{action} needs a reason") + if action == "resolve" and not resolution_revision.strip(): + raise ReportRefused("resolve names the published revision that corrected the target") + if action != "resolve" and resolution_revision: + raise ReportRefused("resolution_revision is only for resolve") + + +def check_resolution(revision: str, reported: int, served: int | None) -> None: + """A resolution of a report about a target names the revision readers are served now, + which is newer than the reported one. Memory versions come from the clock, so a number + between the two may never have been published.""" + if served is None: + raise ReportRefused("the target is gone, so no published revision corrects it") + # isdigit() alone passes digits int() refuses, such as '²'. + if not (revision.isascii() and revision.isdigit()): + raise ReportRefused("resolution_revision is the target's revision number") + if served <= reported: + raise ReportRefused(f"the target has no revision newer than reported revision {reported}") + if int(revision) != served: + raise ReportRefused(f"readers are served revision {served}, not {revision}") + + +def after_evidence(state: ReportState, assignee: str) -> ReportState: + """Where a report goes when its reporter adds evidence: back to its maintainer when + one took it, else back to the queue.""" + if state in FINAL_STATES: + raise ReportRefused(f"a {state} report takes no more evidence") + if state != "needs_evidence": + return state + return "taken" if assignee else "open" diff --git a/server/knowledge/store/documents.py b/server/knowledge/store/documents.py index 5c6a746ab8..9b1f21bc58 100644 --- a/server/knowledge/store/documents.py +++ b/server/knowledge/store/documents.py @@ -217,18 +217,46 @@ async def get_many_by_uris( commit adopts (`pg_documents.commit`). A head that owes nothing while ClickHouse holds no row at its version, read where every write is, was erased by such a build: it is dropped, not served.""" + newest = await _newest(org, namespace, source_uris, include_superseded, ch, lean=False) + return [ + _hydrate(r) for r in newest.values() if include_superseded or r.get("superseded_at") is None + ] + + +async def known_uris( + org: str, namespace: str, source_uris: list[str], *, ch: _CHClient | None = None +) -> set[str]: + """The sources among `source_uris` that have a document, deleted ones included, as + `get_many_by_uris` finds them but without reading any text: the version of each row + and head is all it reads. A head it finds erased is left in place, as in + `revision_heads`: the text read drops it.""" + return set(await _newest(org, namespace, source_uris, True, ch, lean=True)) + + +async def _newest( + org: str, + namespace: str, + source_uris: list[str], + include_superseded: bool, + ch: _CHClient | None, + *, + lean: bool, +) -> dict[str, dict[str, Any]]: + """Each source's newest row as `get_many_by_uris` finds it. With `lean` a row holds its + source and version alone, and a head is never dropped.""" from server.core import pg if not source_uris: - return [] + return {} if not pg.enabled(): - return [ - _hydrate(r) for r in await _read(org, namespace, source_uris, include_superseded, ch) - ] + rows = await _read(org, namespace, source_uris, include_superseded, ch, lean) + return {str(r["source_uri"]): r for r in rows} from server.knowledge.store import pg_documents - heads = await pg_documents.heads(org, namespace, source_uris) - newest = {r["source_uri"]: r for r in await _read(org, namespace, source_uris, True, ch)} + heads = await (pg_documents.head_versions if lean else pg_documents.heads)( + org, namespace, source_uris + ) + newest = {r["source_uri"]: r for r in await _read(org, namespace, source_uris, True, ch, lean)} # A head that owes nothing is published: a replica showing nothing at its version is # behind, or a build that keeps no heads erased it (a purge leaves older writers' # rows). Confirmed where every write is, then dropped. @@ -240,14 +268,17 @@ async def get_many_by_uris( if unbacked: with sequential_reads(): confirmed = { - r["source_uri"]: r for r in await _read(org, namespace, unbacked, True, ch) + r["source_uri"]: r for r in await _read(org, namespace, unbacked, True, ch, lean) } for uri in unbacked: got = confirmed.get(uri) if got is not None and int(got["version"]) >= int(heads[uri].row["version"]): newest[uri] = got continue - await pg_documents.drop_unbacked(org, namespace, uri, int(heads[uri].row["version"])) + if not lean: + await pg_documents.drop_unbacked( + org, namespace, uri, int(heads[uri].row["version"]) + ) heads.pop(uri) if got is not None: newest[uri] = got @@ -258,9 +289,7 @@ async def get_many_by_uris( # place (an older build's erasure tombstone, an erased original). if uri not in newest or int(newest[uri]["version"]) < int(head.row["version"]): newest[uri] = head.row - return [ - _hydrate(r) for r in newest.values() if include_superseded or r.get("superseded_at") is None - ] + return newest async def _read( @@ -269,9 +298,10 @@ async def _read( source_uris: list[str], include_superseded: bool, ch: _CHClient | None, + lean: bool = False, ) -> list[dict[str, Any]]: """The sources' latest loom.documents rows in ClickHouse (only live ones unless - `include_superseded`).""" + `include_superseded`); with `lean`, their source and version alone.""" ch = ch or _default_client() where = [ "org = {org:String}", @@ -280,15 +310,20 @@ async def _read( ] if not include_superseded: where.append("superseded_at IS NULL") - return await ch.query_all( - f""" - SELECT org, namespace, source_uri, doc_id, title, description, content, + columns = ( + "source_uri, version" + if lean + else """org, namespace, source_uri, doc_id, title, description, content, tags, metadata, version, superseded_at, ingested_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, original_filename, content_sha256, blob_erased_at, agent, user_id, session_id, actor, toString(source_class) AS source_class, revision, toString(format) AS format, artifact_sha256, parser, coverage, - ingestion_id, access_json + ingestion_id, access_json""" + ) + return await ch.query_all( + f""" + SELECT {columns} FROM loom.documents FINAL WHERE {" AND ".join(where)} """, diff --git a/server/knowledge/store/pg_documents.py b/server/knowledge/store/pg_documents.py index 1dcb138648..80d55622eb 100644 --- a/server/knowledge/store/pg_documents.py +++ b/server/knowledge/store/pg_documents.py @@ -316,6 +316,27 @@ async def heads(org: str, namespace: str, uris: Sequence[str]) -> dict[str, Head return {str(r["source_uri"]): Head(decode_row(r["row"]), bool(r["owed"])) for r in got} +async def head_versions(org: str, namespace: str, uris: Sequence[str]) -> dict[str, Head]: + """`heads` without the rows: each head's row holds only its version, so no text is + read.""" + uris = [u for u in uris if not pg.unstorable(u)] + if not uris or pg.unstorable([org, namespace]): + return {} + got = await pg.fetch( + "SELECT h.source_uri, h.version, EXISTS (SELECT 1 FROM loom.knowledge_deliveries d " + "WHERE (d.org, d.namespace, d.source_uri, d.version) = " + "(h.org, h.namespace, h.source_uri, h.version) AND NOT d.settled) AS owed " + "FROM loom.knowledge_heads h " + "WHERE h.org = $1 AND h.namespace = $2 AND h.source_uri = ANY($3::text[])", + org, + namespace, + sorted(set(uris)), + ) + return { + str(r["source_uri"]): Head({"version": int(r["version"])}, bool(r["owed"])) for r in got + } + + async def head_lists(org: str, namespace: str, uris: Sequence[str]) -> dict[str, str]: """The permission list (`access_json`) of each live head among these sources, read without the rest of the row.""" diff --git a/server/knowledge/store/reports.py b/server/knowledge/store/reports.py new file mode 100644 index 0000000000..7b759b2682 --- /dev/null +++ b/server/knowledge/store/reports.py @@ -0,0 +1,154 @@ +"""Every statement over loom.knowledge_reports. + +A ReplacingMergeTree(version) sorted by (org, namespace, report_id): submit writes +version 1 and each change the next version of the whole row, so a read takes the latest +with FINAL. Every read filters on the (org, namespace) prefix. +""" + +from __future__ import annotations + +from typing import Any + +from server.core.repo_base import _CHClient, _default_client + +TABLE = "loom.knowledge_reports" + +COLUMNS: tuple[str, ...] = ( + "org", + "namespace", + "agent", + "user_id", + "session_id", + "report_id", + "version", + "kind", + "state", + "target_kind", + "target_key", + "target_version", + "target_sha256", + "target_copy", + "problem", + "suggested_correction", + "run_id", + "evidence", + "related", + "reporter", + "assignee", + "reason", + "reason_by", + "resolution_revision", + "actor", + "written_by", + "source_class", + "created_at", + "updated_at", +) +_SELECT = ", ".join(f"`{c}`" for c in COLUMNS) +# A change reads the head another replica just wrote: a stale head would pass a version +# check and write a second version with the same number. +_SEQUENTIAL = " SETTINGS select_sequential_consistency = 1" + + +async def insert_version(row: dict[str, Any], *, ch: _CHClient | None = None) -> None: + """One version of a report, every column, inserted synchronously so it is written + before the change answers; a sequential read on any replica then sees it.""" + await (ch or _default_client()).insert( + TABLE, + [{c: row[c] for c in COLUMNS}], + settings={"async_insert": 0, "wait_for_async_insert": 1}, + ) + + +async def latest( + org: str, namespace: str, report_id: str, *, ch: _CHClient | None = None +) -> dict[str, Any] | None: + """The latest version of one report, or None when it does not exist, read with + sequential consistency.""" + row = await (ch or _default_client()).query_one( + f"SELECT {_SELECT} FROM {TABLE} FINAL" + " WHERE org = {org:String} AND namespace = {ns:String} AND report_id = {id:String}" + " LIMIT 1" + _SEQUENTIAL, + params={"org": org, "ns": namespace, "id": report_id}, + ) + return dict(row) if row else None + + +async def latest_many( + org: str, namespace: str, report_ids: list[str], *, ch: _CHClient | None = None +) -> list[dict[str, Any]]: + """The latest versions of the given reports that exist, read with sequential + consistency.""" + if not report_ids: + return [] + rows = await (ch or _default_client()).query_all( + f"SELECT {_SELECT} FROM {TABLE} FINAL" + " WHERE org = {org:String} AND namespace = {ns:String}" + " AND report_id IN {ids:Array(String)}" + _SEQUENTIAL, + params={"org": org, "ns": namespace, "ids": report_ids}, + ) + return [dict(r) for r in rows] + + +async def list_reports( + org: str, + namespace: str, + *, + states: list[str], + kinds: list[str], + target_kind: str, + target_key: str, + assignee: str, + reporter: str, + limit: int, + copies: list[str] | None = None, + ch: _CHClient | None = None, +) -> list[dict[str, Any]]: + """The namespace's reports, newest change first, read with sequential consistency so + a page shows every acknowledged change. An empty filter matches every report; + `reporter` and `assignee` compare exactly. With `copies`, a document report is listed + only when its copy is one of them, before the limit.""" + where = ["org = {org:String}", "namespace = {ns:String}"] + params: dict[str, Any] = {"org": org, "ns": namespace, "limit": limit} + if states: + where.append("state IN {states:Array(String)}") + params["states"] = states + if kinds: + where.append("kind IN {kinds:Array(String)}") + params["kinds"] = kinds + if target_kind: + where.append("target_kind = {tk:String}") + params["tk"] = target_kind + if target_key: + where.append("target_key = {tkey:String}") + params["tkey"] = target_key + if assignee: + where.append("assignee = {assignee:String}") + params["assignee"] = assignee + if reporter: + where.append("reporter = {reporter:String}") + params["reporter"] = reporter + if copies is not None: + where.append("(target_kind != 'document' OR has({copies:Array(String)}, target_copy))") + params["copies"] = copies + rows = await (ch or _default_client()).query_all( + f"SELECT {_SELECT} FROM {TABLE} FINAL WHERE {' AND '.join(where)}" + " ORDER BY updated_at DESC, report_id LIMIT {limit:UInt32}" + _SEQUENTIAL, + params=params, + ) + return [dict(r) for r in rows] + + +async def copies_at( + org: str, namespace: str, target_key: str, *, ch: _CHClient | None = None +) -> list[str]: + """The copies the namespace's document reports at `target_key` are about: the + namespace's own ('') and one per mirrored source. Read with sequential consistency: + the list keeps only these copies, so a copy this read missed drops its reports.""" + rows = await (ch or _default_client()).query_all( + f"SELECT DISTINCT target_copy FROM {TABLE} FINAL" + " WHERE org = {org:String} AND namespace = {ns:String}" + " AND target_kind = 'document' AND target_key = {tkey:String}" + _SEQUENTIAL, + params={"org": org, "ns": namespace, "tkey": target_key}, + ) + return [str(r["target_copy"]) for r in rows] diff --git a/server/memory/app/handlers.py b/server/memory/app/handlers.py index 650be43e6c..7cdfb30ac6 100644 --- a/server/memory/app/handlers.py +++ b/server/memory/app/handlers.py @@ -10,7 +10,7 @@ import asyncio import logging from datetime import UTC, datetime, timedelta -from typing import Any +from typing import Any, NamedTuple from fastapi import HTTPException @@ -325,9 +325,9 @@ def same_user(row: Any, identity: Any) -> bool: return str(getattr(row, "user_id", "") or "") == str(getattr(identity, "user_id", "") or "") -async def _point_lookup(identity: Any, input: MemoryGetInput) -> Any: - """The row at `input.memory_key` for this identity, else the same user's - row under any agent. +async def _point_lookup(identity: Any, input: MemoryGetInput, *, wide: bool = True) -> Any: + """The row at `input.memory_key` for this identity, else, when `wide`, the same + user's row under any agent. A get names a key, not the agent that wrote it: a Claude Code session (agent `claude-code`) asking for a key loom_search just served must find the row even when the @@ -355,9 +355,9 @@ async def _point_lookup(identity: Any, input: MemoryGetInput) -> Any: include_expired=False, # an expired fact reads as gone, like search scope=request_scope(), ) - if row is not None or identity.agent == "*": + if row is not None or identity.agent == "*" or not wide: return row - wide = memory_repo.Identity( + namespace_wide = memory_repo.Identity( org=identity.org, namespace=identity.namespace, agent="*", @@ -366,7 +366,7 @@ async def _point_lookup(identity: Any, input: MemoryGetInput) -> Any: ) with traced("ch.query.memory", op="point_lookup_wide", memory_key=input.memory_key): row = await memory_repo.get_by_key( - wide, + namespace_wide, input.memory_key, as_of=input.as_of, include_usage_totals=True, @@ -399,13 +399,11 @@ def _verdict_from_status(status: Any, duplicate_of: Any = "") -> str: return _STATUS_VERDICT.get(s, s) -async def handle_memory_get(input: MemoryGetInput) -> MemoryGetOutput: - # Exact-key reads are still reads: apply the same token read-scope ceiling - # as search before constructing the point-lookup identity. Without this, - # a token pinned to one end user could name another user in the body and - # retrieve that row by key. +def _within_read_scope(input: MemoryGetInput) -> MemoryGetInput: + """Exact-key reads are still reads: the token's read-scope ceiling applies before the + point-lookup identity is built, so a token pinned to one end user cannot name another + user in the body and read that row by key.""" from server.identity.domain.read_scope import resolve_read_filters - from server.operations import read_projection filters = resolve_read_filters( requested="namespace", @@ -418,8 +416,55 @@ async def handle_memory_get(input: MemoryGetInput) -> MemoryGetOutput: identity_updates["user_id"] = filters.user_id if filters.session_id is not None and filters.session_id != input.session_id: identity_updates["session_id"] = filters.session_id - if identity_updates: - input = input.model_copy(update=identity_updates) + return input.model_copy(update=identity_updates) if identity_updates else input + + +class ReadableRow(NamedTuple): + """A row `readable_version` found: its version, its served content hash and the + identity tuple it is stored under, never its value.""" + + version: int + content_sha256: str + agent: str + user_id: str + session_id: str + + +async def readable_version(input: MemoryGetInput, *, exact: bool = False) -> ReadableRow | None: + """The row `memory.get` would serve the caller at `input.memory_key`, or None when it + serves none; with `exact`, only a row stored under the input's own identity tuple. + Nothing of the row is served, so no read exposure or sensitive-read audit is + recorded.""" + import server.memory.store as memory_repo + from server.core.ch import own_write_reads + + if input.memory_key.startswith("chunk:"): + return None + input = _within_read_scope(input) + identity = memory_repo.Identity( + org=input.org, + namespace=input.namespace, + agent=input.agent, + user_id=input.user_id, + session_id=input.session_id, + ) + with own_write_reads(): + row = await _point_lookup(identity, input, wide=not exact) + if row is None: + return None + return ReadableRow( + int(row.version or 0), + served_content_sha256(row.value), + row.agent, + row.user_id, + row.session_id, + ) + + +async def handle_memory_get(input: MemoryGetInput) -> MemoryGetOutput: + from server.operations import read_projection + + input = _within_read_scope(input) # Resolve the field whitelist before the read so an unknown name is a 422 that cost no # statement; None = every field. diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index 322dc77446..069d57e92d 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -256,6 +256,26 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "the assistant agent's SQL tool; no dashboard page calls it until the Assistant " "page's chat" ), + "knowledge.reports.submit": ( + "an agent or client files a report when it finds a claim or passage wrong, " + "outdated or missing while it works" + ), + "knowledge.reports.evidence": ( + "the reporter, an agent or client, adds evidence to its own report when a " + "maintainer asks for it" + ), + "knowledge.reports.get": ( + "maintainers read a report through the API and SDKs; no dashboard page calls it " + "until the report queue page" + ), + "knowledge.reports.list": ( + "maintainers read the queue through the API and SDKs; no dashboard page calls it " + "until the report queue page" + ), + "knowledge.reports.update": ( + "maintainers act on a report through the API and SDKs; no dashboard page calls it " + "until the report queue page" + ), "knowledge.source.live": ( "Requires a protected live result view; the dashboard reads stored copies" ), diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index b2e4610def..1f3a8c05fd 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -511,6 +511,11 @@ "sdk_method", "dashboard", ), + "knowledge.reports.evidence": ("sdk_method",), + "knowledge.reports.get": ("sdk_method",), + "knowledge.reports.list": ("sdk_method",), + "knowledge.reports.submit": ("sdk_method",), + "knowledge.reports.update": ("sdk_method",), "knowledge.restore": ( "sdk_method", "dashboard", diff --git a/server/operations/registry.py b/server/operations/registry.py index 858e6b985f..a6b4718f09 100644 --- a/server/operations/registry.py +++ b/server/operations/registry.py @@ -35,6 +35,7 @@ from server.knowledge.api import ops_gaps as knowledge_gaps from server.knowledge.api import ops_knowledge as knowledge from server.knowledge.api import ops_query_history as query_history +from server.knowledge.api import ops_reports as knowledge_reports from server.knowledge.api import ops_source_live as knowledge_source_live from server.knowledge.api import ops_source_push as knowledge_source_push from server.knowledge.api import ops_source_worker as knowledge_source_worker @@ -82,6 +83,7 @@ connections, knowledge_source_push, knowledge_gaps, + knowledge_reports, knowledge_citations, query_history, help_docs, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 8124074436..34860ebcd1 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -6712,6 +6712,14 @@ class TrackerSettings(BaseModel): "knowledge.query_history.list": 250, "knowledge.query_history.remove": 1000, "knowledge.gaps.list": 300, + # server/knowledge/app/reports.py: a write takes the report's claim (Keeper round trips), + # reads it with FINAL and inserts synchronously; submit and get add the target's read + # (a memory point lookup or the document's get), list a FINAL read and its documents'. + "knowledge.reports.submit": 400, + "knowledge.reports.get": 100, + "knowledge.reports.list": 200, + "knowledge.reports.update": 300, + "knowledge.reports.evidence": 300, # A publish takes the claim on the namespace's suites, reads every suite's current # selection and this suite's cases, and inserts one row; a read is one aggregate over # the namespace's rows, and a get also checks its cases' origin runs in one read. diff --git a/server/tasks/app/run.py b/server/tasks/app/run.py index 45a953255a..d47947b527 100644 --- a/server/tasks/app/run.py +++ b/server/tasks/app/run.py @@ -1159,6 +1159,12 @@ async def handle_run_grade(input: RunGradeInput) -> RunGradeOutput: ) +async def run_exists(org: str, namespace: str, run_id: str) -> bool: + """Whether the namespace holds the run `run.get` would answer for, read without + serving it.""" + return await runs_store.fetch_run(get_client(), org, namespace, run_id) is not None + + # A window retraction spans at most this long, and one call cancels at most this many # labels (a call that reaches it answers `more`; the next continues, as the cancelled # ones net to zero). A dry run counts the same first page and answers `more` too. diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index ba74a79c29..6ab1d02024 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -179,6 +179,7 @@ 1425256025b1 SELECT src, dst, relation, direction, pair_co_occur, provenance FROM ( -- The aggregate alias must NOT be `co_occur`: shadowing the source -- column makes ClickHouse resolve the HAVING reference into 14697ca6bfd3 ALTER TABLE loom.dataset_rows DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 147a8c9b17f2 SELECT sum(upstream_cost_usd) AS spent, sumIf(upstream_cost_usd, operation = {op:String}) AS own, sumIf(upstream_cost_usd, user_id = {uid:String}) AS user_spent, sumIf(upstream_cost_usd, user_id = {ui +14c45bec17a4 SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND namespace = {ns:String} AND ? 14c924c1ec78 SELECT agent, user_id, session_id, memory_key, arrayReverseSort(groupArray((version, deleted, target))) AS versions FROM ( SELECT agent, user_id, session_id, memory_key, version, tombstoned_at IS NOT 1531893b0f7d SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 154aea8f41f9 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a @@ -215,6 +216,7 @@ 190702c74f85 SELECT ts, actor, subject FROM loom.audit_log WHERE org = ? AND namespace = ? AND event_type = {event:String} AND ({name:String} = ? OR JSONExtractString(subject, ?) = {name:String}) ORDER BY ts DESC 190758ec6ba2 SELECT count() AS n FROM loom.memory_drops WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 19091cfef8cd SELECT memory_key, memory_type, content_excerpt, valid_at, created_at, namespace, count() OVER () AS total_matching FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:Strin +19323c5c6650 SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND namespace = {ns:String} 19660391746f SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND source_uri = {uri:String} AND doc_superseded_at IS NULL AND (org, namespace, embedding_model, source_uri, 1987660b5a9d ALTER TABLE loom.entity_edge_rows DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 19acdb7285ea SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} @@ -445,7 +447,6 @@ 31611f39fb5c SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { 31716a5618f9 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 31b4d2370bfc SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a -31d74aa8ec27 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 32003fb01e5d SELECT holder, acquired_at, ttl_s, (renewed_at + toIntervalSecond(ttl_s)) < now64(?) AS stale FROM loom._migration_lock WHERE name = {name:String} 321ac4055c75 SELECT count() AS n FROM loom.tasks WHERE org = {org:String} AND namespace = {ns:String} 321fcca0963a ALTER TABLE loom.memory_records UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mut @@ -482,6 +483,7 @@ 342f026b3008 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND namespace = {ns:String} AND ? 343b7c396165 SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace IN {ns:Array(String)} 345bb4f0bdc6 SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +34601f272cdd ALTER TABLE loom.knowledge_reports UPDATE assignee = if(has({spellings:Array(String)}, lowerUTF8(assignee)), ?, assignee), reason = if(has({spellings:Array(String)}, lowerUTF8(reason_by)), ?, reason), 348ab5a553ad SELECT org, namespace, source_uri, chunk_idx, content, tags, doc_metadata, chunk_metadata, ingested_at, doc_superseded_at, embedding_model, embedding_dim, embedding, created_at, embed_attempts, embed_ 34912ecbbcb8 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} 349d1b15dfc4 SELECT count() AS n FROM loom.dataset_rows WHERE org = {org:String} AND user_id = {uid:String} @@ -708,6 +710,7 @@ 4b25bd59f082 SELECT DISTINCT org, namespace, name, source_id, source_kind, owner_subject, connection_id FROM loom.knowledge_sources WHERE credential_mode = ? AND NOT (source_kind = ? OR kind = ? OR credential_mode 4b65a7bc66f1 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} 4ba366a556c0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +4ba463d0c1ac ALTER TABLE loom.knowledge_reports DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4baa66e24a1e SELECT pr_number, title, author, labels, merged_at, merge_commit_sha, linked_issues, body_excerpt FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND has(files, {p 4bcc327f9556 ALTER TABLE loom.knowledge_gaps DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4bfcae48a0ba ALTER TABLE loom.query_history_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -722,6 +725,7 @@ 4cb8080c7ceb SELECT count() AS n FROM loom.scim_users FINAL WHERE deleted = ? AND has(addresses, {a:String}) 4cffb3ebff8e ALTER TABLE loom.conversations UPDATE is_saved = true, user_id = {uid:String}, saved_at = coalesce(saved_at, {at:DateTime64(?, ?)}) WHERE org = {org:String} AND namespace = {ns:String} AND agent = {ag 4d19c2282f56 ALTER TABLE loom.session_brief_revisions DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sy +4d35b2bfae9a SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 4d76718ea54e ALTER TABLE loom.memory DELETE WHERE (org = {org:String} AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pairs:Array(Tuple(String, String))})) A 4d7bac78429c ALTER TABLE loom.memory_record_versions DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4d9a606cf567 SELECT memory_key, suite, content_sha256, suite_revision, sets, countEqual(newest, ?) AS passed, countEqual(newest, ?) AS failed, countEqual(newest, ?) AS unavailable FROM (SELECT memory_key, suite, c @@ -733,6 +737,7 @@ 4f15bec9d213 SELECT toString(memory_id) AS id, version, value_preview, value_len > ? AS cut FROM loom.memory WHERE org = {org:String} AND namespace = {ns:String} AND (memory_id, version) IN {pairs:Array(Tuple(UUID 4f59cd517107 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user 4f71b021bf53 ALTER TABLE loom.knowledge_source_push DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? +4fc463cb49dd -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 4fd22a03732e SELECT count() AS n FROM loom.dataset_rows WHERE org = {org:String} AND namespace = {ns:String} 4ff808acccee SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 5000543b86ce SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { @@ -938,6 +943,7 @@ 62958ba7ae8e SELECT uniqExact(path) AS n FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND lower(content) LIKE {sc_ 62b8af846501 SELECT count() AS n FROM loom.consolidation_runs WHERE org = {org:String} AND namespace = {ns:String} 62bbe484caba SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +62cdbe0c18eb SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(assignee)) OR has({spellings:Array(String)}, lowerUTF8(reason_by)) OR has({spelli 6337dbb0bbab SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, toString(indexed_commit) AS indexed_commit FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_line, cont 63a839f81adb SELECT namespace, source_uri, title, description, tags, ingested_at, superseded_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, original_filename, content_preview FROM loom 63a93557a802 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this @@ -1160,6 +1166,7 @@ 7aad3247f4a7 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL 7ad0b1c2f4ef SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 7ad2d6cd3530 SELECT brief_key, revision, agent, user_id, session_id, head_sha, trigger, author, sections, rendered, events_total, source_chars, brief_chars, actor, updated_at, tombstoned_at, version FROM loom.sess +7ad6bd2d2d2d SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(reporter)) OR has({spellings:Array(String)}, lowerUTF8(user_id))) 7ada090d2235 ALTER TABLE loom.shared UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_ta 7b00f0e38432 SELECT namespace, source_id, `group`, members, read_at, deleted FROM loom.knowledge_group_members FINAL WHERE org = {org:String} AND (namespace, source_id, `group`) IN {groups:Array(Tuple(String, Stri 7b11cdb24e8b SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? @@ -1363,6 +1370,7 @@ 8d8144c55065 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 8d8ef51731bc SELECT count() AS n FROM loom.learnings_queue WHERE org = {org:String} AND namespace = {ns:String} AND ? 8daebcf8169c SELECT count() AS n FROM loom.entity_triple_rows WHERE org = {org:String} AND (user_id = {uid:String} OR (namespace, memory_id) IN (SELECT toString(namespace), memory_id FROM (SELECT namespace, agent, +8db56f6f9c2d SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND namespace IN {ns:Array(String)} 8dba6a4f2a78 ALTER TABLE loom.memory_reinforcement DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 8defed91c48e SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {o 8df9f540d745 SELECT countIf(tombstoned_at IS NULL) AS live, countIf(tombstoned_at IS NOT NULL) AS dead, max(updated_at) AS last_updated, groupUniqArray(embedding_dim) AS dims FROM loom.qa_item_embeddings FINAL WHE @@ -1695,6 +1703,7 @@ ae4e819b95ea SELECT count() AS n FROM loom.entity_edge_rows WHERE org = {org:Str ae5b8ffb587a SELECT l.memory_key AS memory_key, toString(l.memory_id) AS memory_id, l.code_namespace AS code_namespace, l.path AS path, l.qualified_name AS qualified_name, l.state AS state, l.changed_since AS chan ae7d2da05030 SELECT count() AS n FROM loom.memory_extraction_queue WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? ae99c20b3d1e 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 +af259ff33f9d ALTER TABLE loom.knowledge_reports DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? af399844e950 ALTER TABLE loom.memory_record_fields DELETE WHERE (org = {org:String} AND record_id IN {ids:Array(UUID)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = af8aae57db93 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} afdcda2bf23a SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), arrayConcat((SELECT groupUniqArray(memory_key) FROM loom.memory WHERE org @@ -2027,6 +2036,7 @@ cea581143d39 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_ cec032d1cb17 SELECT user_id FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:String} AND is_sav cec3f5ad060e SELECT org, namespace, agent, user_id, session_id, memory_id, memory_key, memory_type, value, confidence, source_trace, version, tombstoned_at, created_at, expires_at, sensitivity FROM loom.memory FIN cee7e1df6fac SELECT jti, revoked_at, expires_at, reason, revoked_by, issued_before, version FROM loom.revoked_tokens FINAL WHERE jti = {j:String} AND expires_at > now() +cefd6e74a08f ALTER TABLE loom.knowledge_reports DELETE WHERE (org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(reporter)) OR has({spellings:Array(String)}, lowerUTF8(user_id)))) AND ({erasure_mutat cf0cc9e2222f SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns:String} cf104f8e96d5 SELECT ? FROM loom.memory_extraction_queue FINAL WHERE org={org:String} AND namespace={namespace:String} AND agent={agent:String} AND user_id={user_id:String} AND session_id={session_id:String} AND qu cf1e114983a0 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), @@ -2232,6 +2242,7 @@ e0f548d3f7a8 SELECT agent, user_id, session_id, embedding_model, summary_text, k e0f90e7e0243 ALTER TABLE loom.memory_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_ e107d944ecff SELECT n.namespace AS namespace, n.description AS description, n.kind AS kind, n.owner_email AS owner_email, n.requires_approval AS requires_approval, toString(n.visibility) AS visibility, toString(n. e10df0e1e1d9 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} +e11b0dbecfc9 SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND ((has({spellings:Array(String)}, lowerUTF8(reporter)) OR has({spellings:Array(String)}, lowerUTF8(user_id))) OR (has({spell e12eb5c134dc SELECT {literals:Array(String)}[held] AS literal, chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description FROM loom.code_chunks FINAL ARRAY JOIN arrayFilter( i -> m e1357e7c3edf DELETE FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND content_sha256 NOT IN {live:A e1458e7f082a SELECT namespace, count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND superseded_at IS NULL GROUP BY namespace LIMIT {lim:UInt32} diff --git a/tests/integration/test_knowledge_reports.py b/tests/integration/test_knowledge_reports.py new file mode 100644 index 0000000000..c95788388a --- /dev/null +++ b/tests/integration/test_knowledge_reports.py @@ -0,0 +1,360 @@ +"""Knowledge reports against a real ClickHouse: a report version stored and read back with +every column, the latest version winning, the queue's filters, the handlers' submit, +update and evidence under the per-report claim, and both erasure steps. The handlers run +in-process with auth off, where the reporter is the identity's agent.""" + +from __future__ import annotations + +import sys +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from server.core.ch import get_client # noqa: E402 +from server.erasure.store import steps_ledgers # noqa: E402 +from server.erasure.store.predicates import REPORT_PERSON # noqa: E402 +from server.knowledge.api.models_reports import ( # noqa: E402 + KnowledgeReportsEvidenceInput, + KnowledgeReportsGetInput, + KnowledgeReportsSubmitInput, + KnowledgeReportsUpdateInput, +) +from server.knowledge.app import reports as reports_app # noqa: E402 +from server.knowledge.store import reports as reports_store # noqa: E402 +from server.memory.api.models_crud import MemoryGetInput, MemorySetInput # noqa: E402 +from server.memory.app.handlers import handle_memory_get # noqa: E402 +from server.memory.app.write import handle_memory_set # noqa: E402 +from server.tasks.api.models_run import RunBeginInput # noqa: E402 +from server.tasks.app.run import handle_run_begin # noqa: E402 +from tests.integration._resources import unique_org # noqa: E402 + +pytestmark = pytest.mark.usefixtures("ch_target_required") + +NS = "reports" +T0 = datetime(2026, 1, 5, 9, 30, 0, 123000) + + +@pytest.fixture(autouse=True) +async def _ch_connected(): + ch = get_client() + await ch.connect() + yield + await ch.disconnect() + + +def _row(org: str, report_id: str, **kw: Any) -> dict[str, Any]: + return { + "org": org, + "namespace": NS, + "agent": "claude-code", + "user_id": "bob", + "session_id": "s1", + "report_id": report_id, + "version": 1, + "kind": "outdated", + "state": "open", + "target_kind": "document", + "target_key": "docs/pricing.md", + "target_version": 3, + "target_sha256": "a" * 64, + "target_copy": "acl-0123456789abcdef01234567/11111111-1111-4111-8111-111111111111", + "problem": "The price changed.", + "suggested_correction": "It is $20.", + "run_id": "r1", + "evidence": ["run:r1", "gap:g1"], + "related": ["other"], + "reporter": "alice", + "assignee": "", + "reason": "", + "reason_by": "", + "resolution_revision": "", + "actor": "human:alice", + "written_by": "alice", + "source_class": "asserted", + "created_at": T0, + "updated_at": T0, + **kw, + } + + +async def test_a_version_stores_every_column_and_the_latest_wins() -> None: + org = unique_org("reportsi") + first = _row(org, "r-1") + await reports_store.insert_version(first) + got = await reports_store.latest(org, NS, "r-1") + assert got == first + + taken = _row( + org, + "r-1", + version=2, + state="taken", + assignee="maria", + actor="human:maria", + written_by="maria", + updated_at=T0 + timedelta(minutes=1), + ) + await reports_store.insert_version(taken) + assert await reports_store.latest(org, NS, "r-1") == taken + assert [r["report_id"] for r in await reports_store.latest_many(org, NS, ["r-1", "x"])] == [ + "r-1" + ] + assert await reports_store.latest(org, "other", "r-1") is None + + +async def test_the_queue_filters_and_orders_by_the_latest_change() -> None: + org = unique_org("reportsq") + await reports_store.insert_version( + _row(org, "a", kind="missing", target_kind="", target_key="") + ) + await reports_store.insert_version( + _row(org, "b", state="taken", assignee="maria", updated_at=T0 + timedelta(minutes=5)) + ) + + async def ids(**kw: Any) -> list[str]: + base: dict[str, Any] = { + "states": [], + "kinds": [], + "target_kind": "", + "target_key": "", + "assignee": "", + "reporter": "", + "limit": 50, + } + rows = await reports_store.list_reports(org, NS, **{**base, **kw}) + return [r["report_id"] for r in rows] + + assert await ids() == ["b", "a"] + assert await ids(states=["open"]) == ["a"] + assert await ids(kinds=["missing"]) == ["a"] + assert await ids(target_kind="document", target_key="docs/pricing.md") == ["b"] + assert await ids(assignee="maria") == ["b"] + assert await ids(reporter="nobody") == [] + # An older report on the namespace's own copy of b's address: a copy filter applies + # before the limit, and keeps every report that is not about a document. + mirrored = _row(org, "b")["target_copy"] + await reports_store.insert_version( + _row(org, "c", target_copy="", updated_at=T0 + timedelta(minutes=1)) + ) + assert sorted(await reports_store.copies_at(org, NS, "docs/pricing.md")) == ["", mirrored] + assert await ids(target_key="docs/pricing.md", limit=1) == ["b"] + assert await ids(target_key="docs/pricing.md", copies=[""], limit=1) == ["c"] + assert await ids(copies=[]) == ["a"] + + +async def test_handlers_file_take_and_add_evidence_under_the_claim( + monkeypatch: pytest.MonkeyPatch, +) -> None: + org = unique_org("reportsh") + monkeypatch.setattr(reports_app, "every_replica_stores_reports", AsyncMock(return_value=True)) + body = {"org": org, "namespace": NS, "agent": "cli"} + out = await reports_app.handle_knowledge_reports_submit( + KnowledgeReportsSubmitInput(**body, kind="missing", problem="No refund policy.") + ) + again = await reports_app.handle_knowledge_reports_submit( + KnowledgeReportsSubmitInput(**body, kind="missing", problem="No refund policy.") + ) + assert again.report_id == out.report_id and again.version == 1 + + async def writer() -> tuple[str, str, str]: + row = await reports_store.latest(org, NS, out.report_id) + assert row is not None + return row["actor"], row["written_by"], row["source_class"] + + # Each version names its own writer; with auth off, the identity's agent or "-". + assert await writer() == ("cli", "cli", "asserted") + + upd = {"org": org, "namespace": NS, "report_id": out.report_id} + taken = await reports_app.handle_knowledge_reports_update( + KnowledgeReportsUpdateInput(**upd, action="take") + ) + asked = await reports_app.handle_knowledge_reports_update( + KnowledgeReportsUpdateInput(**upd, action="request_evidence", reason="Which runs?") + ) + assert (taken.version, asked.state, asked.version) == (2, "needs_evidence", 3) + assert await writer() == ("-", "-", "asserted") + # A run the report cites must exist in the namespace. + await handle_run_begin(RunBeginInput(**body, run_id="r9", goal="Find the refund policy.")) + added = await reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(**upd, evidence=["run:r9"]) + ) + assert (added.state, added.version) == ("taken", 4) + assert await writer() == ("cli", "cli", "asserted") + + got = await reports_app.handle_knowledge_reports_get(KnowledgeReportsGetInput(**upd)) + assert got.found and got.report is not None + report = got.report + # With auth off no person stands behind the maintainer: the identity's sentinel. + assert (report.reporter, report.assignee, report.evidence) == ("cli", "-", ["run:r9"]) + assert report.problem == "No refund policy." and report.target_readable + + +async def test_a_memory_version_above_2_53_is_filed_and_read_back_exactly( + monkeypatch: pytest.MonkeyPatch, +) -> None: + org = unique_org("reportsv") + monkeypatch.setattr(reports_app, "every_replica_stores_reports", AsyncMock(return_value=True)) + key = {"org": org, "namespace": NS, "agent": "cli", "memory_key": "pricing/plan"} + await handle_memory_set(MemorySetInput(**key, value="The plan is $20 a month.")) + read = await handle_memory_get(MemoryGetInput(**key)) + # A nanosecond version, which a JavaScript number rounds: the client sends the text. + assert read.version_text is not None and int(read.version_text) > 2**53 + out = await reports_app.handle_knowledge_reports_submit( + KnowledgeReportsSubmitInput( + org=org, + namespace=NS, + agent="cli", + kind="outdated", + target_kind="memory", + target_key="pricing/plan", + target_version=read.version_text, + problem="The plan is $25 a month now.", + ) + ) + row = await reports_store.latest(org, NS, out.report_id) + assert row is not None and row["target_version"] == int(read.version_text) + got = await reports_app.handle_knowledge_reports_get( + KnowledgeReportsGetInput(org=org, namespace=NS, report_id=out.report_id) + ) + assert got.report is not None + report = got.report + assert (report.target_version_text, report.target_changed) == (read.version_text, False) + + +async def test_a_user_erasure_deletes_filed_reports_and_clears_the_taker() -> None: + org = unique_org("reportse") + await reports_store.insert_version(_row(org, "filed", reporter="alice")) + await reports_store.insert_version(_row(org, "as-user", reporter="carol", user_id="Alice")) + await reports_store.insert_version(_row(org, "taken", reporter="carol", assignee="alice")) + await steps_ledgers.delete_knowledge_reports_by_user(org, ["alice"]) + assert await reports_store.latest(org, NS, "filed") is None + assert await reports_store.latest(org, NS, "as-user") is None + kept = await reports_store.latest(org, NS, "taken") + assert kept is not None and kept["assignee"] == "" and kept["reporter"] == "carol" + + +async def test_a_user_erasure_clears_what_a_maintainer_wrote_in_every_version() -> None: + org = unique_org("reportsm") + asked = {"reporter": "carol", "reason": "Which run?", "reason_by": "alice"} + carol = {"actor": "human:carol", "written_by": "carol"} + await reports_store.insert_version(_row(org, "asked", **carol)) + # alice asked for evidence without taking the report; carol's evidence carried it on. + await reports_store.insert_version( + _row(org, "asked", version=2, state="needs_evidence", actor="human:Alice", **asked) + ) + await reports_store.insert_version( + _row(org, "asked", version=3, evidence=["run:r1", "run:r2"], **carol, **asked) + ) + # alice resolved a missing-knowledge report in her own words; mark's link carried them. + missing = { + "reporter": "carol", + "kind": "missing", + "target_kind": "", + "target_key": "", + "target_version": 0, + "target_sha256": "", + } + resolved = {**missing, "state": "resolved", "resolution_revision": "See the FAQ."} + await reports_store.insert_version(_row(org, "missing", **carol, **missing)) + await reports_store.insert_version( + _row(org, "missing", version=2, actor="human:Alice", reason_by="alice", **resolved) + ) + await reports_store.insert_version( + _row( + org, + "missing", + version=3, + related=["other", "asked"], + actor="human:mark", + written_by="mark", + reason_by="alice", + **resolved, + ) + ) + census = ( + "SELECT count() AS n FROM loom.knowledge_reports FINAL" + f" WHERE org = {{org:String}} AND {REPORT_PERSON}" + ) + params = {"org": org, "spellings": ["alice"]} + assert (await get_client().query_one(census, params))["n"] == 2 + await steps_ledgers.delete_knowledge_reports_by_user(org, ["alice"]) + assert (await get_client().query_one(census, params))["n"] == 0 + # No version, merged or not, still names alice or holds her words. + left = await get_client().query_one( + "SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String}" + " AND (reason_by != '' OR reason != '' OR resolution_revision != ''" + " OR lowerUTF8(actor) = 'human:alice' OR written_by = 'alice')", + {"org": org}, + ) + assert left["n"] == 0 + kept = await reports_store.latest(org, NS, "asked") + assert kept is not None + assert (kept["reporter"], kept["problem"], kept["actor"]) == ( + "carol", + "The price changed.", + "human:carol", + ) + assert kept["evidence"] == ["run:r1", "run:r2"] + linked = await reports_store.latest(org, NS, "missing") + assert linked is not None + assert (linked["state"], linked["actor"], linked["related"]) == ( + "resolved", + "human:mark", + ["other", "asked"], + ) + + +async def test_a_user_erasure_finds_the_versions_their_service_account_wrote() -> None: + org = unique_org("reportss") + carol = {"reporter": "carol", "actor": "human:carol", "written_by": "carol"} + await reports_store.insert_version(_row(org, "linked", **carol)) + # alice linked a related report through her service account, whose principal is not her + # name: the version's writer is all that ties it to her. + await reports_store.insert_version( + _row( + org, + "linked", + version=2, + reporter="carol", + related=["other", "x"], + actor="process:sa:alice-bot", + written_by="alice", + ) + ) + census = ( + "SELECT count() AS n FROM loom.knowledge_reports FINAL" + f" WHERE org = {{org:String}} AND {REPORT_PERSON}" + ) + params = {"org": org, "spellings": ["alice"]} + assert (await get_client().query_one(census, params))["n"] == 1 + await steps_ledgers.delete_knowledge_reports_by_user(org, ["alice"]) + assert (await get_client().query_one(census, params))["n"] == 0 + kept = await reports_store.latest(org, NS, "linked") + assert kept is not None + assert (kept["actor"], kept["written_by"], kept["reporter"], kept["related"]) == ( + "", + "", + "carol", + ["other", "x"], + ) + + +async def test_a_namespace_erasure_deletes_the_namespace_s_reports() -> None: + org = unique_org("reportsn") + await reports_store.insert_version(_row(org, "r")) + await reports_store.insert_version({**_row(org, "kept"), "namespace": "other"}) + await steps_ledgers.delete_knowledge_reports_by_namespace(org, NS) + assert await reports_store.latest(org, NS, "r") is None + assert await reports_store.latest(org, "other", "kept") is not None + rows = await get_client().query_all( + "SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String}" + " AND namespace = {ns:String}", + {"org": org, "ns": NS}, + ) + assert rows[0]["n"] == 0 diff --git a/tests/integration/test_read_scope_isolation.py b/tests/integration/test_read_scope_isolation.py index 4ba618b7bc..e14f531f70 100644 --- a/tests/integration/test_read_scope_isolation.py +++ b/tests/integration/test_read_scope_isolation.py @@ -65,7 +65,7 @@ # required field has one of these types (a schema's fields, a policy's rule, a skill # folder's files, a worker source's resources, an assigned source's selection word and # its host ids, a copy rule's conditions, a review's content hash, a worker upload's -# text hash and type). +# text hash and type, a report's evidence references). _SHAPED_HINTS: dict[str, dict[type, Any]] = { "fields": {list: [{"name": "canary"}]}, "actions": {list: ["memory.set"]}, @@ -84,6 +84,9 @@ "if_match_sha256": {str: "a" * 64}, "outcomes": {list: [{"case_id": "canary", "candidate": "pass"}]}, "config": {dict: {"model": "canary"}}, + # knowledge.reports.evidence takes references; knowledge.source.worker_register takes + # its preview's evidence, one string. + "evidence": {list: ["run:canary"], str: "canary"}, # knowledge.suites.add_draft and dismiss_drafts: a case its model accepts, and an id # of the shape the server issues, so the answer is the gate's. "case": {SuiteCaseDraft: {"kind": "decline", "prompt": "canary"}}, diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 5217bd3928..1f4a49ee29 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -124,7 +124,6 @@ server/knowledge/app/connected_restore.py::offline_refusal::1 server/knowledge/app/conversations.py::_embed_turn::1 write # conversation.append: the turn is stored; its embedding row records the failure server/knowledge/app/datasets.py::_forget_quietly::1 write # a snapshot the approval no longer serves; an erasure deletes it server/knowledge/app/gaps.py::_insert::1 telemetry # the background gap-miss insert; the search answered before it ran -server/knowledge/app/gaps.py::_person::1 telemetry # the background gap-miss insert's asker fold; no answer reads it server/knowledge/app/gaps.py::erasure_since::1 fail_closed # an unread ledger counts as an erasure: the draft, source change or miss is refused server/knowledge/app/gaps.py::record_miss::1 telemetry # a knowledge-gap miss is telemetry; the search answer is whole server/knowledge/app/ingest_run.py::run::1 logged_only_nonanswer # the ingest worker's job run; the job ends failed with code internal diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index e674d3e9d1..7800603dc3 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -976,6 +976,26 @@ "body", "options" ], + "reports_evidence": [ + "body", + "options" + ], + "reports_get": [ + "body", + "options" + ], + "reports_list": [ + "body", + "options" + ], + "reports_submit": [ + "body", + "options" + ], + "reports_update": [ + "body", + "options" + ], "restore": [ "body", "options" diff --git a/tests/unit/test_cell_scan_tables.py b/tests/unit/test_cell_scan_tables.py index e098106a62..66a90d79c5 100644 --- a/tests/unit/test_cell_scan_tables.py +++ b/tests/unit/test_cell_scan_tables.py @@ -97,6 +97,7 @@ "loom.knowledge_ingest_cancels", "loom.knowledge_ingestions", "loom.knowledge_mirrors", + "loom.knowledge_reports", "loom.knowledge_source_listings", "loom.knowledge_source_push", "loom.knowledge_sources", diff --git a/tests/unit/test_documents_repo.py b/tests/unit/test_documents_repo.py index a9e33232fc..676b53a227 100644 --- a/tests/unit/test_documents_repo.py +++ b/tests/unit/test_documents_repo.py @@ -146,7 +146,9 @@ async def _heads(org: str, namespace: str, uris: list[str]) -> dict[str, Any]: @pytest.mark.asyncio async def test_get_many_by_uris_emits_array_filter() -> None: ch = StubCH() - ch.query_all_returns.append([_doc_row(), _doc_row()]) + ch.query_all_returns.append( + [{**_doc_row(), "source_uri": "kb://a.md"}, {**_doc_row(), "source_uri": "kb://b.md"}] + ) rows = await get_many_by_uris( "clickhouse", "ns", @@ -462,3 +464,71 @@ async def insert(self, table, rows, settings=None): with pytest.raises(asyncio.CancelledError) as raised: await insert_one({**_doc_row(), "version": 5}, over=0, ch=_CH()) # type: ignore[arg-type] assert pg.may_have_committed(raised.value) + + +def _address_check(monkeypatch: pytest.MonkeyPatch, ch: StubCH, *, owed: bool = False) -> list[str]: + """Route a report page's address check to `ch` and one Postgres head; returns the + Postgres statements it sends.""" + from server.core import pg + from server.knowledge.app import source_access + from server.knowledge.store import documents + + statements: list[str] = [] + head = {**_doc_row(), "source_uri": "kb://head", "version": 3} + + async def fetch(sql: str, *args: Any) -> list[dict[str, Any]]: + statements.append(sql) + return [{"source_uri": "kb://head", "version": 3, "row": head, "owed": owed}] + + async def execute(sql: str, *args: Any) -> None: + raise AssertionError("an address check writes nothing") + + async def prepare(org: str, namespaces: list[str]) -> Any: + return source_access.ReadPlan(org) + + monkeypatch.setattr(documents, "_default_client", lambda: ch) + monkeypatch.setattr(source_access, "prepare", prepare) + monkeypatch.setattr(pg, "fetch", fetch) + monkeypatch.setattr(pg, "execute", execute) + return statements + + +@pytest.mark.asyncio +async def test_a_report_page_checks_addresses_without_reading_document_text( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.knowledge.app.document_reads import known_documents + + gone = { + **_doc_row(), + "source_uri": "kb://gone", + "superseded_at": datetime(2026, 5, 2, tzinfo=UTC), + } + ch = StubCH() + ch.query_all_returns.append([gone]) + _address_check(monkeypatch, ch) + targets = [("kb://gone", ""), ("kb://never", "")] + known = await known_documents("clickhouse", "ns", targets, publish=False) + assert known == {("kb://gone", "")} + sql = ch.query_all_calls[0][0] + assert "content" not in sql and "superseded_at IS NULL" not in sql + + +@pytest.mark.asyncio +@pytest.mark.parametrize("owed", [True, False]) +async def test_under_postgres_an_address_check_reads_heads_without_their_rows( + monkeypatch: pytest.MonkeyPatch, owed: bool +) -> None: + """A head owed to ClickHouse is a commit not yet published, so its address is known. + One owing nothing that ClickHouse no longer holds was erased, as `knowledge.get` finds + it, and the check leaves dropping it to a text read.""" + from server.core import pg + from server.knowledge.app.document_reads import known_documents + + ch = StubCH() + statements = _address_check(monkeypatch, ch, owed=owed) + monkeypatch.setattr(pg, "enabled", lambda: True) + known = await known_documents("clickhouse", "ns", [("kb://head", "")], publish=False) + assert (("kb://head", "") in known) is owed + assert all("h.row" not in sql for sql in statements) + assert all("content" not in sql for sql, _ in ch.query_all_calls) diff --git a/tests/unit/test_erasure_knowledge_reports_sql.py b/tests/unit/test_erasure_knowledge_reports_sql.py new file mode 100644 index 0000000000..ca9fc5db72 --- /dev/null +++ b/tests/unit/test_erasure_knowledge_reports_sql.py @@ -0,0 +1,157 @@ +"""A user erasure clears a maintainer from the knowledge reports they wrote on, run as real +SQL on clickhouse-local. A version's `actor` is the token's principal, such as an end +user's `human:user:` or a service account's `process:sa:`, and `written_by` the +person it stands for, which the erasure matches. A resolution with no target is the +maintainer's words and goes with them. The reporter's versions and words stay.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +import pytest + +from server.core import lease_writes +from server.erasure.store import steps_ledgers as ledger_steps +from server.erasure.store.predicates import REPORT_PERSON +from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl + +pytestmark = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") + +NAMED = f"SELECT count() AS n FROM loom.knowledge_reports WHERE org = 'o' AND {REPORT_PERSON}" +FAQ = "See the billing FAQ." + + +def _versions(*rows: str) -> str: + """Every version in one part, not folded on insert: the test reads each version, and a + later local process may merge separate parts down to each report's newest.""" + return ( + "INSERT INTO loom.knowledge_reports (org, namespace, report_id, version, kind, state," + " target_kind, problem, related, reporter, reason, reason_by, resolution_revision," + " actor, written_by, created_at) SETTINGS optimize_on_insert = 0 VALUES " + ", ".join(rows) + ) + + +def _version( + report_id: str, + version: int, + actor: str, + writer: str, + *, + reason: str = "", + reason_by: str = "", + target_kind: str = "memory", + resolution: str = "", + related: tuple[str, ...] = (), +) -> str: + links = ", ".join(f"'{r}'" for r in related) + return ( + f"('o', 'ns', '{report_id}', {version}, 'incorrect', 'open', '{target_kind}'," + f" 'The price changed.', [{links}], 'alice', '{reason}', '{reason_by}'," + f" '{resolution}', '{actor}', '{writer}', now64(3))" + ) + + +@pytest.fixture +def unfenced(monkeypatch: pytest.MonkeyPatch) -> None: + @asynccontextmanager + async def fenced(name: str, **_: Any) -> AsyncIterator[Callable[[bool], None]]: + yield lambda _uncertain: None + + monkeypatch.setattr(lease_writes, "fenced", fenced) + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("unfenced") +async def test_an_end_user_maintainer_is_cleared_from_every_version(tmp_path: Path) -> None: + ch = KeptCH( + tmp_path, + ddl("knowledge_reports"), + _versions( + _version("r1", 1, "human:alice", "alice"), + # erin asked for evidence without taking the report; alice's version carries it. + _version("r1", 2, "human:user:erin", "erin", reason="Which invoice?", reason_by="erin"), + _version("r1", 3, "human:alice", "alice", reason="Which invoice?", reason_by="erin"), + # erin only linked a related report: her name is the writer and nothing else. + _version("r2", 1, "human:alice", "alice"), + _version("r2", 2, "human:user:erin", "erin"), + # erin linked another through her service account, whose principal is not her name. + _version("r5", 1, "human:alice", "alice"), + _version("r5", 2, "process:sa:erin-bot", "erin"), + ), + ) + erin = {"spellings": ["erin"]} + assert (await ch.query_one(NAMED, erin))["n"] == 4 + + await ledger_steps.delete_knowledge_reports_by_user("o", ["erin"], ch=ch) + + assert (await ch.query_one(NAMED, erin))["n"] == 0 + rows = await ch.query_all( + "SELECT report_id, version, problem, reason, reason_by, actor, written_by" + " FROM loom.knowledge_reports ORDER BY report_id, version" + ) + assert [ + (r["report_id"], r["version"], r["actor"], r["written_by"], r["reason_by"]) for r in rows + ] == [ + ("r1", 1, "human:alice", "alice", ""), + ("r1", 2, "", "", ""), + ("r1", 3, "human:alice", "alice", ""), + ("r2", 1, "human:alice", "alice", ""), + ("r2", 2, "", "", ""), + ("r5", 1, "human:alice", "alice", ""), + ("r5", 2, "", "", ""), + ] + assert {r["reason"] for r in rows} == {""} + assert {r["problem"] for r in rows} == {"The price changed."} + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("unfenced") +async def test_a_targetless_resolution_goes_with_its_author(tmp_path: Path) -> None: + ch = KeptCH( + tmp_path, + ddl("knowledge_reports"), + _versions( + _version("r3", 1, "human:alice", "alice", target_kind=""), + # erin resolved a missing-knowledge report in her own words; mark's link carried them. + _version( + "r3", 2, "human:erin", "erin", target_kind="", resolution=FAQ, reason_by="erin" + ), + _version( + "r3", + 3, + "human:mark", + "mark", + target_kind="", + resolution=FAQ, + reason_by="erin", + related=("r4",), + ), + # A target's resolution is the checked revision number, no one's words. + _version("r4", 1, "human:alice", "alice"), + _version("r4", 2, "human:erin", "erin", resolution="7"), + ), + ) + erin = {"spellings": ["erin"]} + assert (await ch.query_one(NAMED, erin))["n"] == 3 + + await ledger_steps.delete_knowledge_reports_by_user("o", ["erin"], ch=ch) + + assert (await ch.query_one(NAMED, erin))["n"] == 0 + rows = await ch.query_all( + "SELECT report_id, version, resolution_revision, reason_by, related, actor" + " FROM loom.knowledge_reports ORDER BY report_id, version" + ) + assert [ + (r["report_id"], r["version"], r["resolution_revision"], r["reason_by"], r["actor"]) + for r in rows + ] == [ + ("r3", 1, "", "", "human:alice"), + ("r3", 2, "", "", ""), + ("r3", 3, "", "", "human:mark"), + ("r4", 1, "", "", "human:alice"), + ("r4", 2, "7", "", ""), + ] + assert rows[2]["related"] == ["r4"] diff --git a/tests/unit/test_erasure_step_order.py b/tests/unit/test_erasure_step_order.py index 2b61548f55..e773d9d2b9 100644 --- a/tests/unit/test_erasure_step_order.py +++ b/tests/unit/test_erasure_step_order.py @@ -172,6 +172,15 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("read_receipts.delete", ((L, "loom.read_receipts"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"),)), ("search_misses.delete", ((D, "loom.knowledge_gaps"), (D, "loom.search_misses"))), + ( + "knowledge_reports.delete", + ( + ("OTHER", "INSERT"), # the reports' write fence + (D, "loom.knowledge_reports"), + (U, "loom.knowledge_reports"), + (D, "loom._migration_lock"), + ), + ), ("events.delete", ((D, "loom.events"),)), ("delete_version_checks.delete", ((D, "loom.delete_version_checks"),)), ("memory_webhook_outbox.delete", ((D, "loom.memory_webhook_outbox"),)), @@ -273,6 +282,10 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("code_search_trace.delete", ((D, "loom.code_search_trace"), (D, "loom.code_search_outcome"))), ("search_misses.delete", ((D, "loom.search_misses"),)), ("knowledge_gaps.delete", ((D, "loom.knowledge_gaps"),)), + ( + "knowledge_reports.delete", + (("OTHER", "INSERT"), (D, "loom.knowledge_reports"), (D, "loom._migration_lock")), + ), ("events.delete", ((D, "loom.events"),)), ("memory_drops.delete", ((D, "loom.memory_drops"),)), ("delete_version_checks.delete", ((D, "loom.delete_version_checks"),)), @@ -411,6 +424,10 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("code_search_trace.delete", ((D, "loom.code_search_trace"), (D, "loom.code_search_outcome"))), ("search_misses.delete", ((D, "loom.search_misses"),)), ("knowledge_gaps.delete", ((D, "loom.knowledge_gaps"),)), + ( + "knowledge_reports.delete", + (("OTHER", "INSERT"), (D, "loom.knowledge_reports"), (D, "loom._migration_lock")), + ), ("events.delete", ((D, "loom.events"),)), ("memory_drops.delete", ((D, "loom.memory_drops"),)), ("delete_version_checks.delete", ((D, "loom.delete_version_checks"),)), @@ -618,6 +635,15 @@ def _push_delete(namespaces: int) -> tuple[str, tuple[tuple[str, str], ...]]: ("read_receipts.delete", ((L, "loom.read_receipts"),)), ("code_search_trace.delete", ((D, "loom.code_search_trace"),)), ("search_misses.delete", ((D, "loom.knowledge_gaps"), (D, "loom.search_misses"))), + ( + "knowledge_reports.delete", + ( + ("OTHER", "INSERT"), # the reports' write fence + (D, "loom.knowledge_reports"), + (U, "loom.knowledge_reports"), + (D, "loom._migration_lock"), + ), + ), ("events.delete", ((D, "loom.events"),)), ("delete_version_checks.delete", ((D, "loom.delete_version_checks"),)), ("memory_webhook_outbox.delete", ((D, "loom.memory_webhook_outbox"),)), diff --git a/tests/unit/test_erasure_verify.py b/tests/unit/test_erasure_verify.py index 03711b14a7..43505d39e2 100644 --- a/tests/unit/test_erasure_verify.py +++ b/tests/unit/test_erasure_verify.py @@ -5,6 +5,8 @@ from __future__ import annotations import asyncio +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager from typing import Any import pytest @@ -137,7 +139,7 @@ def test_census_covers_every_substrate_and_uses_final_on_soft_deleted_tables() - out = asyncio.run(erasure_census.residue_census("o", "namespace", "ns", ch=ch)) assert set(out) == set(erasure_census.census_tables("namespace")) # every namespace-scoped substrate, entity, cache, chunk-link and code table - assert len(out) == 81 and sum(out.values()) == 0 + assert len(out) == 82 and sum(out.values()) == 0 by_table = {sql.split("FROM ")[1].split()[0]: sql for sql, _ in ch.query_one_calls} assert ( " FINAL" in by_table["loom.memory"] and "tombstoned_at IS NULL" in by_table["loom.memory"] @@ -218,7 +220,7 @@ def test_census_user_scope_skips_namespace_only_tables() -> None: "loom.task_events", } <= set(out) assert "loom.memory_answers" not in out - assert len(out) == 58 + assert len(out) == 59 assert "loom.blob_uploads" in out # who uploaded what: the user's go # the user's supporter rows, and any bot-rule candidate left with no supporter assert {"loom.learnings_queue", "loom.learnings_supporters"} <= set(out) @@ -234,6 +236,34 @@ async def query_one(self, sql, params=None): asyncio.run(erasure_census.residue_census("o", "namespace", "ns", ch=_BrokenCH([]))) +def test_the_report_counts_read_every_acknowledged_report(monkeypatch) -> None: + # A replica behind an acknowledged report counts zero: the step would send no + # mutation and the census would record no residue. + from server.core import lease_writes + from server.core.ch import sequential_reads_active + from server.erasure.store import steps_ledgers + + @asynccontextmanager + async def fenced(name: str, **_: Any) -> AsyncIterator[Callable[[bool], None]]: + yield lambda _uncertain: None + + monkeypatch.setattr(lease_writes, "fenced", fenced) + sequential: list[bool] = [] + + class _CH(_StubCH): + async def query_one(self, sql, params=None): + if "loom.knowledge_reports" in sql: + sequential.append(sequential_reads_active()) + return await super().query_one(sql, params) + + ch = _CH([]) + asyncio.run(steps_ledgers.delete_knowledge_reports_by_namespace("o", "ns", ch=ch)) + asyncio.run(steps_ledgers.delete_knowledge_reports_by_user("o", ["alice"], ch=ch)) + asyncio.run(erasure_census.residue_census("o", "namespace", "ns", ch=ch)) + asyncio.run(erasure_census.residue_census("o", "user_id", "alice", ch=ch, spellings=["alice"])) + assert sequential == [True] * 5 + + def test_verify_step_fails_closed_on_residue_and_fills_the_holder(monkeypatch) -> None: async def _census(org, scope_type, scope_value, *, ch=None, spellings=()): return {"loom.memory": 0, "loom.memory_belief_sources": 3, "loom.memory_records": 1} diff --git a/tests/unit/test_every_list_is_projectable.py b/tests/unit/test_every_list_is_projectable.py index 0c8f8bf922..010faebd12 100644 --- a/tests/unit/test_every_list_is_projectable.py +++ b/tests/unit/test_every_list_is_projectable.py @@ -39,6 +39,7 @@ def _wire_model_files() -> list[Path]: "CollectionListInput": "four short fields per collection; a page is read whole", "BlacklistListInput": "a short admin list; no page reads it in part", "KnowledgeGapsListInput": "a short admin list of at most 200 gaps; the tile reads it whole", + "KnowledgeReportsListInput": "an admin queue of at most 200 short rows that carry no text", "CodeHistoryInput": "a per-file history read whole", "CodeSymbolHistoryInput": "a per-symbol history read whole", "ConflictsAllowlistListInput": "a short admin list", diff --git a/tests/unit/test_knowledge_gaps.py b/tests/unit/test_knowledge_gaps.py index 852d11aca2..0597024abe 100644 --- a/tests/unit/test_knowledge_gaps.py +++ b/tests/unit/test_knowledge_gaps.py @@ -190,7 +190,7 @@ async def canonical(org: str, subject: str) -> str | None: } return ties.get(subject, subject.lower()) - monkeypatch.setattr("server.auth.service_accounts.sa_creator", creator) + monkeypatch.setattr("server.auth.service_accounts.read_sa_creator", creator) monkeypatch.setattr("server.auth.aliases.login_handle", canonical) for asker in ( "sa:bot", diff --git a/tests/unit/test_knowledge_report_refs.py b/tests/unit/test_knowledge_report_refs.py new file mode 100644 index 0000000000..15953458d4 --- /dev/null +++ b/tests/unit/test_knowledge_report_refs.py @@ -0,0 +1,76 @@ +"""A report reference is readable when what it points at exists for the caller: a run of +the namespace, the reflection memory at that key under the report's identity tuple, and a +gap of the latest build, for an admin only and while `knowledge.gaps.list` shows it.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from server.knowledge.app import gaps as gaps_app +from server.knowledge.app import report_refs +from server.settings import settings + +ROW = {"org": "o", "namespace": "ns", "agent": "a", "user_id": "bob", "session_id": "s1"} + + +@pytest.fixture +def held(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, ...]]: + """What exists: runs, reflection keys and gaps; returns each lookup made.""" + asked: list[tuple[str, ...]] = [] + + async def run_exists(org: str, namespace: str, run_id: str) -> bool: + asked.append(("run", org, namespace, run_id)) + return run_id == "r1" + + async def readable_version(input: Any) -> tuple[int, str] | None: + asked.append(("memory", input.user_id, input.session_id, input.memory_key)) + return (1, "a" * 64) if input.memory_key == "reflection:r1" else None + + async def gap_for_draft(org: str, namespace: str, gap_id: str) -> dict[str, Any] | None: + asked.append(("gap", gap_id)) + return {"head": "x"} if gap_id == "g1" else None + + monkeypatch.setattr("server.tasks.app.run.run_exists", run_exists) + monkeypatch.setattr("server.memory.app.handlers.readable_version", readable_version) + monkeypatch.setattr(report_refs.gaps_store, "gap_for_draft", gap_for_draft) + monkeypatch.setattr(settings, "knowledge_gaps_enabled", True) + monkeypatch.setattr(gaps_app, "every_replica_erases_gaps", lambda: True) + monkeypatch.setattr(gaps_app, "current_capture_level", lambda: "query") + return asked + + +def test_each_kind_is_read_as_its_own_op_reads_it(held: list[tuple[str, ...]]) -> None: + refs = ["run:r1", "run:r2", "reflection:r1", "reflection:r2", "gap:g1", "gap:g2", "x:1"] + got = asyncio.run(report_refs.readable(ROW, refs, admin=True)) + assert got == ["run:r1", "reflection:r1", "gap:g1"] + assert ("run", "o", "ns", "r1") in held + # The reflection is read under the report's identity tuple, at the reference as its key. + assert ("memory", "bob", "s1", "reflection:r1") in held + + +def test_a_gap_is_read_only_by_an_admin(held: list[tuple[str, ...]]) -> None: + assert asyncio.run(report_refs.readable(ROW, ["gap:g1", "run:r1"], admin=False)) == ["run:r1"] + # Not even looked up for a caller who may not read it. + assert not [a for a in held if a[0] == "gap"] + + +@pytest.mark.parametrize( + "switch", + [ + ("settings", "knowledge_gaps_enabled", False), + ("gaps", "current_capture_level", lambda: "off"), + ("gaps", "every_replica_erases_gaps", lambda: False), + ], + ids=["gaps off", "capture off", "older replica"], +) +def test_a_stored_gap_is_not_read_while_the_gap_list_shows_none( + held: list[tuple[str, ...]], monkeypatch: pytest.MonkeyPatch, switch: tuple[str, str, Any] +) -> None: + # The build that holds g1 is still stored: it expires by its TTL, never shown meanwhile. + owner, name, value = switch + monkeypatch.setattr(settings if owner == "settings" else gaps_app, name, value) + assert asyncio.run(report_refs.readable(ROW, ["gap:g1", "run:r1"], admin=True)) == ["run:r1"] + assert not [a for a in held if a[0] == "gap"] diff --git a/tests/unit/test_knowledge_reports.py b/tests/unit/test_knowledge_reports.py new file mode 100644 index 0000000000..22ef21e335 --- /dev/null +++ b/tests/unit/test_knowledge_reports.py @@ -0,0 +1,1872 @@ +"""Knowledge reports: filing one (the reporter from the token, the target read check, the +id a retry repeats), who reads it, the maintainers' actions, the reporter's evidence, the +queue without anyone's words, and the rollout gate.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import uuid +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import ValidationError as PydanticValidationError + +from server.auth import bearer +from server.auth.jwt import AuthInfo +from server.core import grant_cache, idempotency, request_tail +from server.core.errors import ( + AuthInsufficientError, + BackendUnavailableError, + ErasureRunningError, + NotFoundError, + OverloadedError, + PreconditionFailedError, + ValidationError, +) +from server.core.hashing import sha256_document_text +from server.identity.domain.read_scope import honours_read_scope +from server.knowledge.api.models_reports import ( + KnowledgeReport, + KnowledgeReportsEvidenceInput, + KnowledgeReportsGetInput, + KnowledgeReportsListInput, + KnowledgeReportsSubmitInput, + KnowledgeReportsUpdateInput, +) +from server.knowledge.app import document_reads, source_access, source_documents +from server.knowledge.app import reports as reports_app +from server.knowledge.app.people import PersonUnresolved +from server.knowledge.domain import reports as rules +from server.knowledge.store import documents +from server.knowledge.store import reports as reports_store +from server.operations.base import Role, grant_rank + +_EVERY_REPLICA = reports_app.every_replica_stores_reports + +ORG, NS = "o", "ns" + + +def _auth(subject: str, role: Role = Role.WRITER) -> AuthInfo: + return AuthInfo( + subject=subject, org=ORG, namespaces=(NS,), roles=(role,), is_service_account=False + ) + + +class _Store: + """loom.knowledge_reports as its latest versions.""" + + def __init__(self) -> None: + self.rows: dict[str, dict[str, Any]] = {} + self.inserts: list[dict[str, Any]] = [] + self.fences: list[list[str]] = [] + # References nothing points at; a gap is read only by an admin. + self.missing: set[str] = set() + self.marks: list[bool] = [] + + async def latest(self, org: str, namespace: str, report_id: str, **_: Any) -> Any: + row = self.rows.get(report_id) + return dict(row) if row else None + + async def latest_many(self, org: str, namespace: str, ids: list[str], **_: Any) -> Any: + return [dict(self.rows[i]) for i in ids if i in self.rows] + + async def insert_version(self, row: dict[str, Any], **_: Any) -> None: + self.inserts.append(dict(row)) + current = self.rows.get(row["report_id"]) + if current is None or row["version"] >= current["version"]: + self.rows[row["report_id"]] = dict(row) + + async def list_reports( + self, + org: str, + namespace: str, + *, + target_kind: str = "", + target_key: str = "", + copies: list[str] | None = None, + limit: int = 50, + **_: Any, + ) -> Any: + """Filtered as the statement filters, `copies` included, then cut to `limit`.""" + rows = [r for r in self.rows.values() if not target_key or r["target_key"] == target_key] + rows = [r for r in rows if not target_kind or r["target_kind"] == target_kind] + if copies is not None: + rows = [r for r in rows if r["target_kind"] != "document" or r["target_copy"] in copies] + return sorted(rows, key=lambda r: r["updated_at"], reverse=True)[:limit] + + async def copies_at(self, org: str, namespace: str, target_key: str, **_: Any) -> Any: + docs = (r for r in self.rows.values() if r["target_kind"] == "document") + return sorted({r["target_copy"] for r in docs if r["target_key"] == target_key}) + + +@pytest.fixture +def store(monkeypatch: pytest.MonkeyPatch) -> _Store: + s = _Store() + for name in ("latest", "latest_many", "insert_version", "list_reports", "copies_at"): + monkeypatch.setattr(reports_store, name, getattr(s, name)) + monkeypatch.setattr(reports_app, "every_replica_stores_reports", AsyncMock(return_value=True)) + + @asynccontextmanager + async def holding(name: str, **_: Any) -> AsyncIterator[bool]: + yield True + + monkeypatch.setattr(reports_app.leases, "holding", holding) + + @asynccontextmanager + async def fenced(names: list[str], **_: Any) -> AsyncIterator[Any]: + s.fences.append(names) + yield s.marks.append + + monkeypatch.setattr(reports_app.lease_writes, "fenced_many", fenced) + + async def readable(row: dict[str, Any], refs: list[str], *, admin: bool) -> list[str]: + return [r for r in refs if r not in s.missing and (admin or not r.startswith("gap:"))] + + monkeypatch.setattr(reports_app.report_refs, "readable", readable) + + async def same(org: str, subject: str) -> str: + return subject + + monkeypatch.setattr(reports_app, "folded_person", same) + _erasures(monkeypatch, []) + return s + + +def _erasures(monkeypatch: pytest.MonkeyPatch, answers: list[bool]) -> list[set[str] | None]: + """Answer the fence's erasure reads in order (False once they run out); returns the + people each read asked about.""" + asked: list[set[str] | None] = [] + + async def since(org: str, namespace: str, since_s: int, people: set[str] | None) -> bool: + asked.append(people) + return answers.pop(0) if answers else False + + monkeypatch.setattr("server.knowledge.app.gaps.erasure_since", since) + return asked + + +def _as(monkeypatch: pytest.MonkeyPatch, subject: str, role: Role = Role.WRITER) -> None: + auth = _auth(subject, role) + monkeypatch.setattr("server.auth.context.current_auth", lambda: auth) + + +# The doc_id `_target` serves for a document. +DOC_ID = "5f0c8b52-7d4e-4c55-9a51-0d1c2b3a4f5e" + + +def _target(monkeypatch: pytest.MonkeyPatch, state: tuple[int, str] | None) -> None: + """The target reads as `state`; a memory key is found in the row the report names, a + document as `DOC_ID`.""" + + async def now(row: dict[str, Any], *, exact: bool = True, publish: bool = False) -> Any: + if not row["target_kind"]: + return reports_app._Target(0, "") + if state is None: + return None + if row["target_kind"] == "document": + return reports_app._Target(*state, doc_id=DOC_ID) + return reports_app._Target(*state, (row["agent"], row["user_id"], row["session_id"])) + + monkeypatch.setattr(reports_app, "_target_now", now) + + +def _submit(**kw: Any) -> Any: + body = { + "org": ORG, + "namespace": NS, + "agent": "claude-code", + "kind": "incorrect", + "target_kind": "memory", + "target_key": "pricing/plan", + "problem": "The plan price changed in March.", + **kw, + } + return asyncio.run( + reports_app.handle_knowledge_reports_submit(KnowledgeReportsSubmitInput(**body)) + ) + + +def _update(**kw: Any) -> Any: + return asyncio.run( + reports_app.handle_knowledge_reports_update( + KnowledgeReportsUpdateInput(org=ORG, namespace=NS, **kw) + ) + ) + + +def _get(report_id: str) -> Any: + return asyncio.run( + reports_app.handle_knowledge_reports_get( + KnowledgeReportsGetInput(org=ORG, namespace=NS, report_id=report_id) + ) + ) + + +def _list(**kw: Any) -> list[Any]: + return asyncio.run( + reports_app.handle_knowledge_reports_list( + KnowledgeReportsListInput(org=ORG, namespace=NS, **kw) + ) + ).reports + + +def _known(monkeypatch: pytest.MonkeyPatch, known: set[str]) -> None: + """The document addresses the caller may know of are those in `known`.""" + + async def known_documents( + org: str, namespace: str, targets: list[tuple[str, str]], **_: Any + ) -> set[tuple[str, str]]: + return {t for t in targets if t[0] in known} + + monkeypatch.setattr(document_reads, "known_documents", known_documents) + + +def test_the_migration_constant_names_the_table_s_file() -> None: + migrations = Path(__file__).resolve().parents[2] / "schemas" / "migrations" + assert (migrations / f"{reports_app.REPORTS_MIGRATION:03d}_knowledge_reports.sql").exists() + + +class _Fleet: + """Live beats as `instances.read_live` reads them: this deployment kind, or every kind.""" + + def __init__(self, rows: list[dict[str, Any]]) -> None: + self.rows = rows + + async def query_all(self, sql: str, params: dict[str, Any], **_: Any) -> list[dict[str, Any]]: + return [ + r + for r in self.rows + if params.get("all_deployments") or r["deployment"] == params["dep"] + ] + + +@pytest.mark.parametrize("deployment", [False, True]) +def test_submit_waits_for_an_older_replica_of_the_other_deployment_kind( + store: _Store, monkeypatch: pytest.MonkeyPatch, deployment: bool +) -> None: + from server.core import ch, instances + from server.settings import settings + + at = reports_app.REPORTS_MIGRATION + fleet = _Fleet( + [ + {"deployment": int(deployment), "schema_version": at}, + {"deployment": int(not deployment), "schema_version": at - 1}, + ] + ) + monkeypatch.setattr(settings, "deployment", deployment) + monkeypatch.setattr(ch, "get_client", lambda: fleet) + monkeypatch.setattr(instances, "live_rows", lambda: [{"schema_version": at}]) + monkeypatch.setattr(reports_app, "every_replica_stores_reports", _EVERY_REPLICA) + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + with pytest.raises(OverloadedError): + _submit() + assert store.inserts == [] + fleet.rows[1]["schema_version"] = at + assert _submit().state == "open" + + +async def test_writes_wait_while_the_fleet_is_unread(monkeypatch: pytest.MonkeyPatch) -> None: + from server.core import ch + + monkeypatch.setattr(ch, "get_client", lambda: _Fleet([])) + assert not await _EVERY_REPLICA() + + +def test_a_serving_replica_at_schema_version_135_holds_report_writes( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.core import ch + + # Migration 135 is the newest before the reports table; a replica there has no report + # erasure step. + at = reports_app.REPORTS_MIGRATION + fleet = _Fleet([{"deployment": 0, "schema_version": v} for v in (135, at)]) + monkeypatch.setattr(ch, "get_client", lambda: fleet) + monkeypatch.setattr(reports_app, "every_replica_stores_reports", _EVERY_REPLICA) + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + with pytest.raises(OverloadedError): + _submit() + assert store.inserts == [] + fleet.rows[0]["schema_version"] = at + assert _submit().state == "open" + + +def test_submit_refuses_while_an_older_replica_serves( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + monkeypatch.setattr(reports_app, "every_replica_stores_reports", AsyncMock(return_value=False)) + with pytest.raises(OverloadedError): + _submit() + assert store.inserts == [] + + +def test_a_narrowed_token_cannot_reach_reports() -> None: + for op in ("submit", "get", "list", "update", "evidence"): + assert not honours_read_scope(f"knowledge.reports.{op}") + + +def test_submit_files_an_open_report_under_the_token_s_person( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + out = _submit(user_id="bob", evidence=["run:r1", "reflection:r1", "run:r1"]) + assert (out.state, out.version) == ("open", 1) + row = store.rows[out.report_id] + # The reporter is the token's person, never a body field. + assert row["reporter"] == "alice" and row["user_id"] == "bob" + # What the reporter did not say it read is stamped from the target now. + assert (row["target_version"], row["target_sha256"]) == (3, "a" * 64) + assert row["evidence"] == ["run:r1", "reflection:r1"] + assert row["assignee"] == "" and row["reason"] == "" + + +def test_a_retry_files_the_same_report_once(store: _Store, monkeypatch: pytest.MonkeyPatch) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + first = _submit() + again = _submit(problem=" The plan price changed in March. ") + assert again.report_id == first.report_id and len(store.inserts) == 1 + other = _submit(problem="The plan was renamed.") + assert other.report_id != first.report_id + _as(monkeypatch, "carol") + assert _submit().report_id != first.report_id + + +def test_the_same_key_in_two_rows_is_two_reports( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + bob = _submit(user_id="bob") + assert _submit(user_id="bob").report_id == bob.report_id + others = { + _submit(user_id="carl").report_id, + _submit(user_id="bob", agent="other-agent").report_id, + _submit(user_id="bob", session_id="s2").report_id, + } + assert bob.report_id not in others and len(others) == 3 + assert {r["user_id"] for r in store.rows.values()} == {"bob", "carl"} + # A document is read by its URI alone, so the tuple does not split its reports. + doc = {"target_kind": "document", "target_key": "gdrive://doc", "target_doc_id": DOC_ID} + assert _submit(**doc, user_id="bob").report_id == _submit(**doc, user_id="carl").report_id + + +def test_two_agents_that_read_one_row_file_one_report_bound_to_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from types import SimpleNamespace + + from server.memory.app import handlers + + # bob's only row at the key, written by the mcp agent in session s1. + stored = SimpleNamespace( + version=4, value={"text": "x"}, agent="mcp", user_id="bob", session_id="s1" + ) + lookups: list[tuple[str, str, bool]] = [] + + async def lookup(identity: Any, input: Any, *, wide: bool = True) -> Any: + lookups.append((identity.agent, identity.session_id, wide)) + if (identity.agent, identity.user_id, identity.session_id) == ("mcp", "bob", "s1"): + return stored + # memory.get falls back to the same user's row under any agent and session. + return stored if wide and identity.user_id == "bob" else None + + monkeypatch.setattr(handlers, "_point_lookup", lookup) + _as(monkeypatch, "alice") + first = _submit(agent="claude-code", user_id="bob") + again = _submit(agent="cursor", user_id="bob") + assert again.report_id == first.report_id and len(store.inserts) == 1 + row = store.rows[first.report_id] + assert (row["agent"], row["user_id"], row["session_id"]) == ("mcp", "bob", "s1") + # Later reads look in that row only, never another row of bob's the fallback finds. + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(first.report_id).report.target_readable + assert lookups[-1] == ("mcp", "s1", False) + + +def test_a_version_read_in_another_row_files_no_report_on_the_row_there_now( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from types import SimpleNamespace + + from server.memory.app import handlers + + # bob's row under the mcp agent, which memory.get falls back to for claude-code. + mcp = SimpleNamespace( + version=100, value={"t": "$10"}, agent="mcp", user_id="bob", session_id="-" + ) + rows = {"mcp": mcp} + + async def lookup(identity: Any, input: Any, *, wide: bool = True) -> Any: + found = rows.get(identity.agent) + return found if found is not None or not wide else mcp + + monkeypatch.setattr(handlers, "_point_lookup", lookup) + _as(monkeypatch, "alice") + body = {"agent": "claude-code", "user_id": "bob", "target_version": 100} + first = _submit(**body) + # claude-code then writes its own row at the key, which memory.get now finds first. + rows["claude-code"] = SimpleNamespace( + version=200, value={"t": "$12"}, agent="claude-code", user_id="bob", session_id="-" + ) + for problem in ("The plan price changed in March.", "The $10 is wrong."): + with pytest.raises(PreconditionFailedError, match="read it again"): + _submit(**body, problem=problem) + assert [(r["agent"], r["target_version"]) for r in store.inserts] == [("mcp", 100)] + # Read again, the report is about the row read. + again = _submit(agent="claude-code", user_id="bob", target_version=200) + assert again.report_id != first.report_id + assert store.rows[again.report_id]["agent"] == "claude-code" + + +def test_a_wildcard_agent_binds_the_report_to_a_row_of_its_own_user( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from types import SimpleNamespace + + from server.memory.app import handlers + + carol = SimpleNamespace( + version=6, value={"t": "c"}, agent="mcp", user_id="carol", session_id="s9" + ) + bob = SimpleNamespace(version=4, value={"t": "b"}, agent="cli", user_id="bob", session_id="s1") + newest = [carol] + + async def lookup(identity: Any, input: Any, *, wide: bool = True) -> Any: + # agent "*" drops every identity filter: the newest row at the key, any user's. + return newest[0] if identity.agent == "*" else None + + monkeypatch.setattr(handlers, "_point_lookup", lookup) + _as(monkeypatch, "alice") + with pytest.raises(NotFoundError): + _submit(agent="*", user_id="bob") + assert store.inserts == [] + newest[0] = bob + row = store.rows[_submit(agent="*", user_id="bob").report_id] + assert (row["agent"], row["user_id"], row["session_id"]) == ("cli", "bob", "s1") + + +@pytest.mark.parametrize( + ("body", "message"), + [ + ({"target_kind": "", "target_key": ""}, "names the memory or document"), + ({"target_kind": "", "target_key": "k"}, "needs target_kind"), + ({"evidence": ["note:hello"]}, "is not gap:"), + ], +) +def test_submit_refuses_a_broken_report( + store: _Store, monkeypatch: pytest.MonkeyPatch, body: dict[str, Any], message: str +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + with pytest.raises(ValidationError, match=message): + _submit(**body) + assert store.inserts == [] + + +def test_a_target_version_above_uint64_is_refused_before_any_write() -> None: + body = {"org": ORG, "namespace": NS, "kind": "incorrect", "problem": "Wrong."} + target = {"target_kind": "memory", "target_key": "pricing/plan"} + top = 2**64 - 1 # loom.knowledge_reports.target_version is UInt64 + for sent in (top, str(top)): + submitted = KnowledgeReportsSubmitInput(**body, **target, target_version=sent) + assert submitted.target_version == top + for bad in (top + 1, str(top + 1), -1, "-1", "1e3", " 7", "١٢", ""): + with pytest.raises(PydanticValidationError, match="target_version"): + KnowledgeReportsSubmitInput(**body, **target, target_version=bad) + + +def test_a_memory_version_above_2_53_stays_exact_from_submit_to_get( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + # A nanosecond memory version: a JavaScript number would read it as ...000. + exact = 1_800_000_000_000_000_001 + _as(monkeypatch, "alice") + _target(monkeypatch, (exact, "a" * 64)) + body = { + "org": ORG, + "namespace": NS, + "agent": "claude-code", + "kind": "outdated", + "target_kind": "memory", + "target_key": "pricing/plan", + "target_version": str(exact), + "problem": "The plan price changed in March.", + } + submitted = KnowledgeReportsSubmitInput.model_validate_json(json.dumps(body)) + rid = asyncio.run(reports_app.handle_knowledge_reports_submit(submitted)).report_id + assert store.rows[rid]["target_version"] == exact + _as(monkeypatch, "maria", Role.ADMIN) + report = json.loads(_get(rid).model_dump_json())["report"] + assert report["target_version_text"] == str(exact) + assert report["target_changed"] is False + listed = asyncio.run( + reports_app.handle_knowledge_reports_list(KnowledgeReportsListInput(org=ORG, namespace=NS)) + ) + assert json.loads(listed.model_dump_json())["reports"][0]["target_version_text"] == str(exact) + + +def test_a_missing_knowledge_report_names_no_target( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, None) + out = _submit(kind="missing", target_kind="", target_key="", problem="No refund policy.") + assert store.rows[out.report_id]["target_kind"] == "" + + +def test_a_target_the_reporter_cannot_read_is_not_found( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, None) + with pytest.raises(NotFoundError): + _submit() + assert store.inserts == [] + + +def test_related_reports_must_exist_and_not_be_the_report( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + with pytest.raises(ValidationError, match="was not found"): + _submit(related=["nope"]) + first = _submit() + second = _submit(problem="Also the currency.", related=[first.report_id]) + assert store.rows[second.report_id]["related"] == [first.report_id] + with pytest.raises(ValidationError, match="itself"): + _update(report_id=first.report_id, related=[first.report_id]) + + +def test_a_report_links_only_reports_its_caller_can_read( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + alices = _submit().report_id + _as(monkeypatch, "carol") + # Another reporter's report is refused as a missing one is, so a link cannot probe ids. + refusals = [] + for rid in (alices, "nope"): + with pytest.raises(ValidationError, match="was not found") as refused: + _submit(problem="Also the currency.", related=[rid]) + refusals.append(str(refused.value).replace(rid, "")) + assert refusals[0] == refusals[1] + assert store.inserts and all(r["reporter"] == "alice" for r in store.inserts) + carols = _submit(problem="Also the currency.").report_id + linked = _submit(problem="And the tax.", related=[carols]).report_id + assert store.rows[linked]["related"] == [carols] + # A maintainer reads every report, so links any. + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=carols, related=[alices]) + assert store.rows[carols]["related"] == [alices] + + +def test_a_report_serves_only_the_related_reports_its_caller_can_read( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + alices = _submit().report_id + _as(monkeypatch, "carol") + carols = _submit(problem="Also the currency.").report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=carols, related=[alices]) + assert _get(carols).report.related == [alices] + # Carol reads her report but not alice's, so its link does not say alice's exists. + _as(monkeypatch, "carol") + assert _get(carols).report.related == [] + assert store.rows[carols]["related"] == [alices] + + +def test_only_the_reporter_and_maintainers_read_a_report( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit(suggested_correction="It is $20 now.").report_id + mine = _get(rid) + assert mine.found and mine.report.problem.startswith("The plan price") + assert mine.report.suggested_correction == "It is $20 now." + _as(monkeypatch, "carol") + assert _get(rid).found is False + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(rid).report.reporter == "alice" + assert _get("missing").found is False + + +def test_a_lowered_grant_ends_an_admin_token_s_reading( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + ranks = {NS: grant_rank("admin")} + + async def grants(org: str, subject: str) -> grant_cache.GrantMap: + return grant_cache.GrantMap(ranks=ranks if subject == "maria" else {}) + + monkeypatch.setattr(grant_cache, "_read", grants) + grant_cache.clear() + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(rid).found + # The token still claims admin; the live grant fell to viewer. + ranks[NS] = grant_rank("viewer") + grant_cache.clear() + assert _get(rid).found is False + + +def test_a_changed_or_unreadable_target_shows_as_such( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(rid).report.target_changed is False + _target(monkeypatch, (4, "b" * 64)) + assert _get(rid).report.target_changed is True + _update(report_id=rid, action="request_evidence", reason="Section 3 still says $10.") + assert _get(rid).report.reason == "Section 3 still says $10." + # A maintainer who cannot read the target now sees the report without its words, a + # maintainer's reason included: it may quote the target as the problem may. + _target(monkeypatch, None) + hidden = _get(rid).report + assert hidden.target_changed and not hidden.target_readable + assert hidden.problem == "" and hidden.suggested_correction == "" and hidden.reason == "" + # The reporter keeps reading their own words, and only those. + _as(monkeypatch, "alice") + own = _get(rid).report + assert own.problem != "" and own.reason == "" + + +def test_a_document_s_address_is_served_only_to_whoever_may_know_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "drive://plans/q3.md" + _as(monkeypatch, "alice") + _target(monkeypatch, (7, "a" * 64)) + rid = _submit( + target_kind="document", target_key=uri, target_version=7, target_doc_id=DOC_ID + ).report_id + # A mirrored document whose access list leaves maria out: neither get nor the queue + # names it or its revision, and a filter on its address finds nothing. + _target(monkeypatch, None) + _known(monkeypatch, set()) + _as(monkeypatch, "maria", Role.ADMIN) + hidden = _get(rid).report + assert (hidden.target_key, hidden.target_version, hidden.target_version_text) == ("", 0, "0") + assert [(r.report_id, r.target_key, r.target_version) for r in _list()] == [(rid, "", 0)] + assert _list(target_key=uri) == [] + # A maintainer who may know the document sees its address. + _known(monkeypatch, {uri}) + assert _get(rid).report.target_key == uri + assert [r.target_key for r in _list(target_key=uri)] == [uri] + # Its reporter wrote the address, so always reads it. + _known(monkeypatch, set()) + _as(monkeypatch, "alice") + assert _get(rid).report.target_key == uri + + +MIRROR = "acl-" + "1" * 24 +SID_A, SID_B = "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222" + + +class _Copies: + """The documents at an address as the document reads find them: the namespace's own + and mirrored copies, each admitted to the readers its access list names.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.reader = "" + self.ordinary: dict[str, documents.DocumentRow] = {} + self.mirrored: dict[tuple[str, str], tuple[documents.DocumentRow, set[str]]] = {} + self.plan = source_access.ReadPlan(ORG, marked=True) + self.plan._bindings = ((MIRROR, SID_A, NS), (MIRROR, SID_B, NS)) + monkeypatch.setattr(self.plan, "check", self.check) + monkeypatch.setattr(self.plan, "current", lambda item: True) + monkeypatch.setattr(self.plan, "current_evidence", lambda item: True) + monkeypatch.setattr(source_access, "prepare", AsyncMock(return_value=self.plan)) + monkeypatch.setattr(source_documents, "_discover", self.discover) + monkeypatch.setattr(source_documents.store, "contents", self.contents) + monkeypatch.setattr(documents, "get_one", self.get_one) + monkeypatch.setattr(documents, "known_uris", self.known) + + def _row(self, namespace: str, uri: str, content: str, revision: int, title: str = "") -> Any: + return documents.DocumentRow( + org=ORG, + namespace=namespace, + source_uri=uri, + doc_id=str(uuid.uuid5(uuid.NAMESPACE_URL, f"{namespace}/{uri}@{revision}")), + title=title, + content=content, + tags=[f"source-id:{uri.rpartition('#')[2]}"] if namespace == MIRROR else [], + version=10, + revision=revision, + ingested_at=datetime(2026, 1, max(revision, 1), tzinfo=UTC), + content_sha256=sha256_document_text(f"{title}\n{content}"), + ) + + def mirror(self, uri: str, sid: str, content: str, revision: int, readers: set[str]) -> None: + copy = f"{uri}#{sid}" + self.mirrored[(MIRROR, copy)] = (self._row(MIRROR, copy, content, revision), readers) + + def own(self, uri: str, content: str, revision: int, title: str = "") -> None: + self.ordinary[uri] = self._row(NS, uri, content, revision, title) + + def read(self, uri: str) -> dict[str, Any]: + """What `knowledge.get` serves the reader at `uri`, as a report names it.""" + found = asyncio.run(document_reads.document_copy(ORG, NS, uri, publish=False)) + assert found is not None + return {"target_doc_id": found[0].doc_id, "target_version": found[0].revision} + + async def discover(self, plan: Any, pairs: list[tuple[str, str]]) -> list[dict[str, str]]: + return [{"namespace": m, "source_uri": u} for m, u in pairs if (m, u) in self.mirrored] + + async def check(self, candidates: list[dict[str, Any]], *, chunks: bool = False) -> Any: + out = [] + for c in candidates: + row, readers = self.mirrored.get((c["namespace"], c["source_uri"]), (None, set())) + if row is not None and self.reader in readers: + doc = {**row.model_dump(), "namespace": row.namespace} + out.append(source_access.Admitted(namespace=NS, candidate=c, document=doc)) + return out + + async def contents(self, org: str, ns: str, uri: str, version: int, revision: int) -> Any: + row = self.mirrored.get((ns, uri), (None, set()))[0] + return row if row is not None and row.revision == revision else None + + async def get_one(self, org: str, ns: str, uri: str, **_: Any) -> Any: + return self.ordinary.get(uri) + + async def known(self, org: str, ns: str, uris: list[str], **_: Any) -> Any: + return {u for u in uris if u in self.ordinary} + + +def test_a_document_is_known_by_its_namespace_or_its_access_list( + monkeypatch: pytest.MonkeyPatch, +) -> None: + plan = source_access.ReadPlan(ORG) + monkeypatch.setattr(source_access, "prepare", AsyncMock(return_value=plan)) + reads: list[list[str]] = [] + + async def documents(org: str, ns: str, uris: list[str]) -> Any: + reads.append(uris) + return set(uris) + + monkeypatch.setattr("server.knowledge.store.documents.known_uris", documents) + + asked: list[list[tuple[str, str]]] = [] + + async def mirrored(plan: Any, namespace: str, pairs: list[tuple[str, str]]) -> Any: + asked.append(pairs) + doc = {"version": 10, "revision": 2, "ingested_at": datetime(2026, 1, 2, tzinfo=UTC)} + return [ + source_access.Admitted(NS, {"namespace": m, "source_uri": u}, doc) + for m, u in pairs + if u.startswith("drive://mine") + ] + + monkeypatch.setattr(source_documents, "admitted_copies", mirrored) + mine, theirs = (f"{MIRROR}/{SID_A}", f"{MIRROR}/{SID_B}") + targets = [("kb://deleted", ""), ("drive://mine", mine), ("drive://theirs", theirs)] + # The namespace's own document, deleted ones included, is known to its every reader. + assert asyncio.run(document_reads.known_documents(ORG, NS, targets, publish=False)) == { + ("kb://deleted", "") + } + assert reads == [["kb://deleted"]] and asked == [] + # A mirrored copy is known only where the caller's access list admits that copy, asked + # once for every copy on the page. + plan.marked = True + assert asyncio.run( + document_reads.known_documents(ORG, NS, [*targets, targets[1]], publish=False) + ) == { + ("kb://deleted", ""), + ("drive://mine", mine), + } + assert asked == [[(MIRROR, f"drive://mine#{SID_A}"), (MIRROR, f"drive://theirs#{SID_B}")]] + + +def test_a_mirrored_copy_is_admitted_from_metadata_alone( + monkeypatch: pytest.MonkeyPatch, +) -> None: + plan = source_access.ReadPlan(ORG) + plan._bindings = ((MIRROR, SID_A, NS), ("acl-" + "2" * 24, SID_A, "elsewhere")) + discovered: list[list[tuple[str, str]]] = [] + + async def discover(plan: Any, pairs: list[tuple[str, str]]) -> list[dict[str, str]]: + discovered.append(pairs) + return [{"namespace": m, "source_uri": s} for m, s in pairs] + + monkeypatch.setattr(source_documents, "_discover", discover) + listed = {f"drive://mine#{SID_A}", f"drive://stale#{SID_A}"} + + async def check(candidates: list[dict[str, str]], *, chunks: bool = False) -> Any: + return [ + source_access.Admitted(namespace=NS, candidate=c, document={}) + for c in candidates + if c["source_uri"] in listed + ] + + monkeypatch.setattr(plan, "check", check) + monkeypatch.setattr(plan, "current", lambda item: "stale" not in item.candidate["source_uri"]) + + async def no_text(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("an address check reads no document text") + + monkeypatch.setattr(source_documents.store, "contents", no_text) + pairs = [(MIRROR, f"drive://{name}#{SID_A}") for name in ("mine", "stale", "theirs")] + # Admitted, with a current proof, and only in this namespace's mirrors: one read for + # the whole page, however many copies it holds. + other = ("acl-" + "2" * 24, f"drive://mine#{SID_A}") + admitted = asyncio.run(source_documents.admitted_copies(plan, NS, [*pairs, other])) + assert [item.candidate["source_uri"] for item in admitted] == [f"drive://mine#{SID_A}"] + assert discovered == [pairs] + # A failed check admits nothing, as every mirror leg fails closed. + plan.failed = True + assert asyncio.run(source_documents.admitted_copies(plan, NS, pairs)) == [] + + +def test_a_document_report_stays_bound_to_the_copy_it_was_filed_about( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + rid = _submit( + target_kind="document", target_key=uri, problem="The $10 is wrong.", **copies.read(uri) + ).report_id + # Other documents appear at the same address, which maria reads: another mirrored copy, + # then the namespace's own document. Neither stands in for the copy alice reported. + for replace in ( + lambda: copies.mirror(uri, SID_B, "x", 5, {"maria"}), + lambda: copies.own(uri, "y", 5), + ): + replace() + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + hidden = _get(rid).report + assert not hidden.target_readable + assert (hidden.problem, hidden.target_key, hidden.target_version) == ("", "", 0) + assert [r.target_key for r in _list()] == [""] and _list(target_key=uri) == [] + with pytest.raises(ValidationError, match="target is gone"): + _update(report_id=rid, action="resolve", resolution_revision="5") + # The reporter still reads the copy they reported, unchanged. + copies.reader = "alice" + _as(monkeypatch, "alice") + own = _get(rid).report + assert own.target_readable and not own.target_changed and own.problem != "" + # Once maria's access list admits alice's copy, she reads the report. + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "maria"}) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + report = _get(rid).report + assert report.target_readable and report.problem != "" and report.target_key == uri + + +def test_a_document_report_holds_the_document_s_stored_content_sha256( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "kb:plan" + copies = _Copies(monkeypatch) + copies.own(uri, "Q3 price: $10", 2, title="Q3 plan") + stored = copies.ordinary[uri].content_sha256 + _as(monkeypatch, "alice") + body = {"target_kind": "document", "target_key": uri, **copies.read(uri)} + # A hash of the text is not the document's content_sha256: a client hashes nothing. + with pytest.raises(PreconditionFailedError, match="read it again"): + _submit(**body, target_sha256=hashlib.sha256(b"Q3 price: $10").hexdigest()) + rid = _submit(**body, target_sha256=stored).report_id + unsent = _submit(**body, problem="The $10 is the Q2 price.").report_id + assert store.rows[rid]["target_sha256"] == store.rows[unsent]["target_sha256"] == stored + # The stored hash covers the title: an edit of the title alone keeps the doc_id and the + # revision, and the target reads as changed. + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(rid).report.target_changed is False + copies.own(uri, "Q3 price: $10", 2, title="Q3 plan (draft)") + edited = _get(rid).report + # The namespace's own document has the same readers at every version: words stay. + assert edited.target_changed is True and edited.problem != "" + + +def test_a_document_row_with_no_stored_hash_is_followed_by_its_revision( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "kb:plan" + copies = _Copies(monkeypatch) + copies.own(uri, "Q3 price: $10", 2) + copies.ordinary[uri] = copies.ordinary[uri].model_copy(update={"content_sha256": ""}) + _as(monkeypatch, "alice") + body = {"target_kind": "document", "target_key": uri, **copies.read(uri)} + with pytest.raises(PreconditionFailedError, match="read it again"): + _submit(**body, target_sha256="a" * 64) + rid = _submit(**body).report_id + assert store.rows[rid]["target_sha256"] == "" + assert _get(rid).report.target_changed is False + copies.own(uri, "Q3 price: $12", 3) + assert _get(rid).report.target_changed is True + + +def test_a_legacy_document_with_no_revision_is_followed_into_its_first_revision( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "kb:plan" + copies = _Copies(monkeypatch) + copies.own(uri, "Q3 price: $10", 0) + copies.ordinary[uri] = copies.ordinary[uri].model_copy(update={"content_sha256": ""}) + _as(monkeypatch, "alice") + rid = _submit(target_kind="document", target_key=uri, **copies.read(uri)).report_id + assert (store.rows[rid]["target_version"], store.rows[rid]["target_sha256"]) == (0, "") + assert _get(rid).report.target_changed is False + copies.own(uri, "Q3 price: $12", 1) + assert _get(rid).report.target_changed is True + + +def test_a_mirrored_copy_s_words_are_served_only_while_it_holds_the_reported_revision( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "mark"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + rid = _submit( + target_kind="document", + target_key=uri, + problem="It says $10.", + suggested_correction="Q3 price: $12", + **copies.read(uri), + ).report_id + copies.reader = "mark" + _as(monkeypatch, "mark", Role.ADMIN) + _update(report_id=rid, action="request_evidence", reason="Where is $10 from?") + words = ("It says $10.", "Q3 price: $12", "Where is $10 from?") + # The access list admits maria to the same revision: she reads the text they quote. + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "mark", "maria"}) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + report = _get(rid).report + assert (report.problem, report.suggested_correction, report.reason) == words + # The source replaces the copy with revision 3 under another access list. maria reads + # revision 3 and never read revision 2, which the words may quote. + copies.mirror(uri, SID_A, "Q3 price: $12", 3, readers={"alice", "maria"}) + hidden = _get(rid).report + assert hidden.target_readable and hidden.target_changed and hidden.target_key == uri + assert (hidden.problem, hidden.suggested_correction, hidden.reason) == ("", "", "") + # The reporter keeps her own words; the reason may quote a revision she never read. + copies.reader = "alice" + _as(monkeypatch, "alice") + own = _get(rid).report + assert (own.problem, own.suggested_correction, own.reason) == (*words[:2], "") + + +@pytest.mark.parametrize( + ("text", "revision"), + [("Q3 price: $10", 2), ("Q3 price: $12", 2), ("Q3 price: $12", 5)], + ids=["same revision and text", "same revision", "another revision"], +) +def test_a_first_filing_names_the_copy_it_read_by_its_doc_id( + store: _Store, monkeypatch: pytest.MonkeyPatch, text: str, revision: int +) -> None: + """Between alice's read of her private copy and her first submit, the namespace's own + document appears at the address. Copies can share a revision and text, so only the + doc_id knowledge.get served says which copy she read.""" + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + read = copies.read(uri) + copies.own(uri, text, revision) + body = {"target_kind": "document", "target_key": uri, "problem": "The $10 is wrong."} + with pytest.raises(PreconditionFailedError, match="read it again"): + _submit(**body, **read) + unnamed = {k: v for k, v in read.items() if k != "target_doc_id"} + with pytest.raises(ValidationError, match="target_doc_id"): + _submit(**body, **unnamed) + assert store.inserts == [] + # Read again, the report is about the copy she read. + rid = _submit(**body, **copies.read(uri)).report_id + assert store.rows[rid]["target_copy"] == "" + + +def test_a_filter_on_an_address_keeps_the_copies_the_caller_knows_before_the_limit( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"bob"}) + copies.reader = "bob" + _as(monkeypatch, "bob") + private = _submit(target_kind="document", target_key=uri, **copies.read(uri)).report_id + copies.own(uri, "Q3 price: $12", 3) + copies.reader = "alice" + _as(monkeypatch, "alice") + visible = _submit(target_kind="document", target_key=uri, **copies.read(uri)).report_id + # The report on the private mirror is the newer change. + store.rows[private]["updated_at"] = store.rows[visible]["updated_at"] + timedelta(minutes=1) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + assert [r.report_id for r in _list(target_key=uri, limit=1)] == [visible] + assert [r.target_key for r in _list(limit=1)] == [""] + + +@pytest.mark.parametrize("read", ["list", "get"]) +def test_a_mirrored_address_is_rechecked_before_the_response_is_sent( + store: _Store, monkeypatch: pytest.MonkeyPatch, read: str +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "maria"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + rid = _submit(target_kind="document", target_key=uri, **copies.read(uri)).report_id + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + # With the copy's text missing, get serves its address alone, as list does. + monkeypatch.setattr(source_documents.store, "contents", AsyncMock(return_value=None)) + sent: list[dict[str, Any]] = [] + + async def respond(revoke: bool) -> None: + async def app(scope: Any, receive: Any, send: Any) -> None: + if read == "list": + out: Any = await reports_app.handle_knowledge_reports_list( + KnowledgeReportsListInput(org=ORG, namespace=NS) + ) + else: + out = await reports_app.handle_knowledge_reports_get( + KnowledgeReportsGetInput(org=ORG, namespace=NS, report_id=rid) + ) + if revoke: + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": out.model_dump_json().encode()}) + + async def send(message: dict[str, Any]) -> None: + sent.append(message) + + await request_tail.RequestTailMiddleware(app)({"type": "http"}, None, send) + + asyncio.run(respond(revoke=False)) + assert uri.encode() in sent[-1]["body"] + # The access list drops maria after the handler returns: the response is refused unsent. + sent.clear() + with pytest.raises(request_tail.RequiredTailError): + asyncio.run(respond(revoke=True)) + assert sent == [] + + +@pytest.mark.parametrize("left_out", ["by the limit", "by a memory filter"]) +def test_a_mirrored_copy_left_off_the_page_never_holds_the_response( + store: _Store, monkeypatch: pytest.MonkeyPatch, left_out: str +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "maria"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + mirrored = _submit(target_kind="document", target_key=uri, **copies.read(uri)).report_id + # A newer report at the same address about the namespace's own document, or about a + # memory key spelled like the address: only it is on the page. + if left_out == "by the limit": + copies.own(uri, "Q3 price: $12", 3) + shown = _submit( + target_kind="document", target_key=uri, problem="It is $12.", **copies.read(uri) + ).report_id + filters: dict[str, Any] = {"target_key": uri, "limit": 1} + else: + shown = "m" * 32 + store.rows[shown] = { + **store.rows[mirrored], + "report_id": shown, + "target_kind": "memory", + "target_copy": "", + } + filters = {"target_kind": "memory", "target_key": uri} + store.rows[shown]["updated_at"] = store.rows[mirrored]["updated_at"] + timedelta(minutes=1) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + sent: list[dict[str, Any]] = [] + + async def app(scope: Any, receive: Any, send: Any) -> None: + out = await reports_app.handle_knowledge_reports_list( + KnowledgeReportsListInput(org=ORG, namespace=NS, **filters) + ) + # The access list drops maria before the response goes out; the page never named + # the copy she lost. + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": out.model_dump_json().encode()}) + + async def send(message: dict[str, Any]) -> None: + sent.append(message) + + asyncio.run(request_tail.RequestTailMiddleware(app)({"type": "http"}, None, send)) + page = json.loads(sent[-1]["body"])["reports"] + assert [(r["report_id"], r["target_key"]) for r in page] == [(shown, uri)] + + +def test_a_filtered_page_drops_a_copy_its_caller_stopped_knowing( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "drive://plans/q3.md" + _as(monkeypatch, "alice") + _target(monkeypatch, (7, "a" * 64)) + _submit(target_kind="document", target_key=uri, target_doc_id=DOC_ID) + _as(monkeypatch, "maria", Role.ADMIN) + + async def known_documents( + org: str, namespace: str, targets: list[tuple[str, str]], *, publish: bool + ) -> set[tuple[str, str]]: + # Access ends between the filter and the check of the page's own rows. + return set() if publish else set(targets) + + monkeypatch.setattr(document_reads, "known_documents", known_documents) + assert _list(target_key=uri) == [] + + +def test_a_queue_retried_with_its_key_reads_source_access_again( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.operations.registry import ALL_OPERATIONS + from server.settings import settings + from server.transport import gates + from server.transport import http as http_mod + + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "maria"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + _submit(target_kind="document", target_key=uri, **copies.read(uri)) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + # The replay cache, as loom.idempotency answers it. + replays: dict[str, Any] = {} + + async def check(key: str, body_hash: str) -> idempotency.CacheResult: + hit = replays.get(key) + if hit is None: + return idempotency.CacheResult(hit=None, conflict=False) + return idempotency.CacheResult( + hit=idempotency.CacheHit(status_code=200, body=hit, headers={}), conflict=False + ) + + async def keep(*, idempotency_key: str, response_body: Any, **_: Any) -> None: + replays[idempotency_key] = response_body + + async def admit(*_a: Any, **_k: Any) -> gates.Target: + return gates.Target(org=ORG, namespace=NS, named_namespace=NS, register_namespace=NS) + + async def nothing(*_a: Any, **_k: Any) -> None: + return None + + op = next(o for o in ALL_OPERATIONS if o.name == "knowledge.reports.list") + monkeypatch.setattr(idempotency, "check", check) + monkeypatch.setattr(idempotency, "store", keep) + monkeypatch.setattr(http_mod, "ALL_OPERATIONS", [op]) + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr( + bearer, "authenticate_token", AsyncMock(return_value=_auth("maria", Role.ADMIN)) + ) + monkeypatch.setattr(http_mod, "_authorize", admit) + monkeypatch.setattr(http_mod, "_rate_limit", lambda *a, **k: None) + monkeypatch.setattr(http_mod, "_emit_event", lambda *a, **k: None) + monkeypatch.setattr("server.transport._common.emit_budget_violation", nothing) + app = FastAPI() + app.include_router(http_mod.build_router()) + app.add_middleware(request_tail.RequestTailMiddleware) + client = TestClient(app) + + def queue() -> Any: + headers = {"Authorization": "Bearer maria", "Idempotency-Key": "k1"} + answer = client.post(f"/v1/{op.name}", json={"org": ORG, "namespace": NS}, headers=headers) + assert answer.status_code == 200, answer.text + return [r["target_key"] for r in answer.json()["reports"]] + + assert queue() == [uri] + # The access list drops maria: a retry with the same key reads the queue again rather + # than replaying an address she no longer reads. + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + assert queue() == [""] + + +@pytest.mark.parametrize("write", ["submit", "resolve"]) +def test_a_write_that_landed_is_answered_after_access_to_its_target_ends( + store: _Store, monkeypatch: pytest.MonkeyPatch, write: str +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice", "maria"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + read = copies.read(uri) + if write == "resolve": + rid = _submit(target_kind="document", target_key=uri, **read).report_id + copies.mirror(uri, SID_A, "Q3 price: $20", 5, readers={"alice", "maria"}) + copies.reader = "maria" + _as(monkeypatch, "maria", Role.ADMIN) + sent: list[dict[str, Any]] = [] + + async def app(scope: Any, receive: Any, send: Any) -> None: + if write == "submit": + out: Any = await reports_app.handle_knowledge_reports_submit( + KnowledgeReportsSubmitInput( + org=ORG, + namespace=NS, + agent="claude-code", + kind="incorrect", + target_kind="document", + target_key=uri, + problem="The $10 is wrong.", + **read, + ) + ) + else: + out = await reports_app.handle_knowledge_reports_update( + KnowledgeReportsUpdateInput( + org=ORG, namespace=NS, report_id=rid, action="resolve", resolution_revision="5" + ) + ) + # Access to the target ends once the version is written: the write's answer serves + # nothing of the document, so it still goes out. + row = copies.mirrored[(MIRROR, f"{uri}#{SID_A}")][0] + copies.mirrored[(MIRROR, f"{uri}#{SID_A}")] = (row, set()) + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": out.model_dump_json().encode()}) + + async def send(message: dict[str, Any]) -> None: + sent.append(message) + + asyncio.run(request_tail.RequestTailMiddleware(app)({"type": "http"}, None, send)) + state = "open" if write == "submit" else "resolved" + assert store.inserts[-1]["state"] == state + assert json.loads(sent[-1]["body"])["state"] == state + + +def test_the_queue_carries_no_one_s_words(store: _Store, monkeypatch: pytest.MonkeyPatch) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + _submit(suggested_correction="It is $20 now.") + out = asyncio.run( + reports_app.handle_knowledge_reports_list(KnowledgeReportsListInput(org=ORG, namespace=NS)) + ) + assert len(out.reports) == 1 + assert ( + set(KnowledgeReport.model_fields) & {"problem", "suggested_correction", "reason"} == set() + ) + assert "price" not in out.model_dump_json() + # A row reads no target, so it says nothing of whether the target changed. + assert "target_changed" not in out.reports[0].model_dump() + + +def test_a_maintainer_takes_asks_and_resolves( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + assert _update(report_id=rid, action="take").state == "taken" + assert store.rows[rid]["assignee"] == "maria" + with pytest.raises(ValidationError, match="needs a reason"): + _update(report_id=rid, action="request_evidence") + out = _update(report_id=rid, action="request_evidence", reason="Which invoice?") + assert (out.state, out.version) == ("needs_evidence", 3) + with pytest.raises(ValidationError, match="published revision"): + _update(report_id=rid, action="resolve") + _target(monkeypatch, (7, "b" * 64)) + out = _update(report_id=rid, action="resolve", resolution_revision="7") + assert out.state == "resolved" and store.rows[rid]["resolution_revision"] == "7" + with pytest.raises(ValidationError, match="only by reopen"): + _update(report_id=rid, action="take") + assert _update(report_id=rid, action="reopen", reason="Still wrong.").state == "open" + assert store.rows[rid]["assignee"] == "" + + +def test_each_version_is_stamped_with_the_token_that_wrote_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=rid, action="request_evidence", reason="Which invoice?") + _as(monkeypatch, "alice") + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=["run:r2"]) + ) + ) + assert [(r["version"], r["actor"], r["source_class"]) for r in store.inserts] == [ + (1, "human:alice", "asserted"), + (2, "human:maria", "asserted"), + (3, "human:alice", "asserted"), + ] + + +def test_a_service_account_s_version_names_the_person_behind_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + linked = _submit(problem="Also the currency.").report_id + bot = AuthInfo( + subject="sa:maria-bot", + org=ORG, + namespaces=(NS,), + roles=(Role.ADMIN,), + is_service_account=True, + creator="maria", + ) + monkeypatch.setattr("server.auth.context.current_auth", lambda: bot) + # The bot links alice's report as a maintainer; its live grant is the gate's to check. + monkeypatch.setattr(reports_app, "_maintainer", AsyncMock(return_value=True)) + # A link names maria nowhere else: the version's writer is what a user erasure matches. + _update(report_id=rid, related=[linked]) + row = store.rows[rid] + assert (row["actor"], row.get("written_by")) == ("process:sa:maria-bot", "maria") + assert [r.get("written_by") for r in store.inserts] == ["alice", "alice", "maria"] + + +@pytest.mark.parametrize( + ("served", "revision", "message"), + [ + ((3, "a" * 64), "3", "no revision newer"), # the target is unchanged + ((7, "b" * 64), "draft-8", "revision number"), + ((7, "b" * 64), "²", "revision number"), # a digit to isdigit(), not to int() + ((7, "b" * 64), "8", "readers are served revision 7"), + # Memory versions come from the clock, so one between the two may never have existed. + ((7, "b" * 64), "5", "readers are served revision 7"), + (None, "7", "target is gone"), + ], +) +def test_a_resolution_names_a_published_correcting_revision( + store: _Store, + monkeypatch: pytest.MonkeyPatch, + served: tuple[int, str] | None, + revision: str, + message: str, +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + _target(monkeypatch, served) + with pytest.raises(ValidationError, match=message): + _update(report_id=rid, action="resolve", resolution_revision=revision) + assert store.rows[rid]["state"] == "open" + _target(monkeypatch, (9, "c" * 64)) + assert _update(report_id=rid, action="resolve", resolution_revision="9").state == "resolved" + + +def test_a_reason_names_the_maintainer_who_wrote_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + # Asked without taking the report: no assignee, but the reason is maria's. + _update(report_id=rid, action="request_evidence", reason="Which invoice?") + assert (store.rows[rid]["assignee"], store.rows[rid]["reason_by"]) == ("", "maria") + _as(monkeypatch, "alice") + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=["run:r2"]) + ) + ) + # The reporter's version carries the reason forward and still names who wrote it. + row = store.rows[rid] + assert (row["reason"], row["reason_by"]) == ("Which invoice?", "maria") + assert row["actor"] == "human:alice" + + +def test_an_action_without_words_keeps_the_reason_the_report_holds( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=rid, action="take") + _update(report_id=rid, action="request_evidence", reason="Which invoice?") + _as(monkeypatch, "alice") + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=["run:r2"]) + ) + ) + # Release, take and a resolution with a target bring no words of their own. + _as(monkeypatch, "mark", Role.ADMIN) + _update(report_id=rid, action="release") + _update(report_id=rid, action="take") + _target(monkeypatch, (7, "b" * 64)) + _update(report_id=rid, action="resolve", resolution_revision="7") + row = store.rows[rid] + assert (row["reason"], row["reason_by"], row["resolution_revision"]) == ( + "Which invoice?", + "maria", + "7", + ) + assert _get(rid).report.reason == "Which invoice?" + # Reopening says why, and the report is no longer resolved. + _update(report_id=rid, action="reopen", reason="Section 3 still says $10.") + row = store.rows[rid] + assert (row["reason"], row["reason_by"], row["resolution_revision"]) == ( + "Section 3 still says $10.", + "mark", + "", + ) + + +def test_a_targetless_resolution_names_the_maintainer_who_wrote_it( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + missing = {"kind": "missing", "target_kind": "", "target_key": ""} + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit(**missing, problem="No refund policy.").report_id + linked = _submit(**missing, problem="No returns page.").report_id + about_memory = _submit().report_id + _as(monkeypatch, "mark", Role.ADMIN) + _update(report_id=rid, action="request_evidence", reason="Which page did you expect?") + _as(monkeypatch, "maria", Role.ADMIN) + # Nothing checks a resolution with no target against a revision: it is maria's words, + # and the one author `reason_by` names, so mark's question does not stay beside them. + _update(report_id=rid, action="resolve", resolution_revision="See the billing FAQ.") + row = store.rows[rid] + assert (row["resolution_revision"], row["reason"], row["reason_by"]) == ( + "See the billing FAQ.", + "", + "maria", + ) + # Linking carries the words forward under mark's version, still naming maria. + _as(monkeypatch, "mark", Role.ADMIN) + asked = _erasures(monkeypatch, []) + _update(report_id=rid, related=[linked]) + row = store.rows[rid] + assert (row["resolution_revision"], row["reason_by"]) == ("See the billing FAQ.", "maria") + assert row["actor"] == "human:mark" and "maria" in (asked[-1] or set()) + # A target's resolution is the checked revision number, no one's words. + _target(monkeypatch, (7, "b" * 64)) + _update(report_id=about_memory, action="resolve", resolution_revision="7") + assert store.rows[about_memory]["reason_by"] == "" + + +def test_a_write_carrying_a_reason_stops_at_its_author_s_erasure( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + linked = _submit(problem="Also the currency.").report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=rid, action="request_evidence", reason="Which invoice?") + + async def maria_erased(org: str, ns: str, since_s: int, people: set[str] | None) -> bool: + return people is None or "maria" in people + + monkeypatch.setattr("server.knowledge.app.gaps.erasure_since", maria_erased) + before = len(store.inserts) + # Both writes copy maria's reason forward: landing after her erasure would restore it. + _as(monkeypatch, "alice") + with pytest.raises(ErasureRunningError): + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput( + org=ORG, namespace=NS, report_id=rid, evidence=["run:r2"] + ) + ) + ) + _as(monkeypatch, "mark", Role.ADMIN) + with pytest.raises(ErasureRunningError): + _update(report_id=rid, related=[linked]) + assert len(store.inserts) == before + + +def test_a_reference_is_checked_on_write_and_on_every_read( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + store.missing = {"run:gone"} + for body in ({"evidence": ["run:gone"]}, {"run_id": "gone"}, {"evidence": ["gap:g1"]}): + # Missing, or a gap only admins read: refused alike, and nothing is filed. + with pytest.raises(ValidationError, match="was not found"): + _submit(**body) + assert store.inserts == [] + rid = _submit(run_id="r1", evidence=["run:r1", "reflection:r1"]).report_id + + def add(refs: list[str]) -> Any: + return asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=refs) + ) + ) + + with pytest.raises(ValidationError, match="'run:gone' was not found"): + add(["run:gone"]) + # What the report already cites is not checked again on a write. + store.missing = {"reflection:r1", "run:r1"} + add(["run:r2", "reflection:r1"]) + # A read serves only what the caller can read now. + report = _get(rid).report + assert (report.evidence, report.run_id) == (["run:r2"], "") + assert store.rows[rid]["evidence"] == ["run:r1", "reflection:r1", "run:r2"] + + +def test_an_update_names_something_to_change( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + with pytest.raises(ValidationError, match="name an action"): + _update(report_id=rid) + _as(monkeypatch, "alice") + other = _submit(problem="Also the currency.").report_id + _as(monkeypatch, "maria", Role.ADMIN) + with pytest.raises(ValidationError, match="go with an action"): + _update(report_id=rid, related=[other], reason="why") + with pytest.raises(NotFoundError): + _update(report_id="missing", action="take") + + +def test_an_update_from_a_stale_version_is_refused( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=rid, action="take") + with pytest.raises(PreconditionFailedError): + _update(report_id=rid, action="dismiss", reason="Duplicate.", expected_version=1) + assert _update( + report_id=rid, action="dismiss", reason="Duplicate.", expected_version=2 + ).state == ("dismissed") + + +def test_a_second_writer_is_told_to_retry(store: _Store, monkeypatch: pytest.MonkeyPatch) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + + @asynccontextmanager + async def held_elsewhere(name: str, **_: Any) -> AsyncIterator[bool]: + assert name == f"knowledge-report:{ORG}:{NS}:{rid}" + yield False + + monkeypatch.setattr(reports_app.leases, "holding", held_elsewhere) + _as(monkeypatch, "maria", Role.ADMIN) + with pytest.raises(OverloadedError): + _update(report_id=rid, action="take") + assert len(store.inserts) == 1 + + +def test_only_the_reporter_adds_evidence(store: _Store, monkeypatch: pytest.MonkeyPatch) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit(evidence=["run:r1"]).report_id + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=rid, action="take") + _update(report_id=rid, action="request_evidence", reason="Which run?") + + def add(refs: list[str]) -> Any: + return asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=refs) + ) + ) + + with pytest.raises(NotFoundError): + add(["run:r2"]) + _as(monkeypatch, "alice") + out = add(["run:r2", "run:r1"]) + # Back to the maintainer who took it. + assert out.state == "taken" + assert store.rows[rid]["evidence"] == ["run:r1", "run:r2"] + with pytest.raises(ValidationError): + add(["bad"]) + + +def test_evidence_on_a_busy_report_says_nothing_to_another_caller( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + + @asynccontextmanager + async def held_elsewhere(name: str, **_: Any) -> AsyncIterator[bool]: + yield False + + monkeypatch.setattr(reports_app.leases, "holding", held_elsewhere) + # A report another writer holds answers carol as a missing one does, never 503. + _as(monkeypatch, "carol") + for report_id in (rid, "f" * 32): + with pytest.raises(NotFoundError): + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput( + org=ORG, namespace=NS, report_id=report_id, evidence=["run:r2"] + ) + ) + ) + assert len(store.inserts) == 1 + + +def test_the_memory_check_serves_nothing_and_skips_chunk_keys( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.memory.api.models_crud import MemoryGetInput + from server.memory.app import handlers + + class _Row: + version = 4 + value = {"text": "x"} + agent, user_id, session_id = "mcp", "-", "-" + + seen: list[str] = [] + + async def lookup(identity: Any, input: MemoryGetInput, *, wide: bool = True) -> Any: + seen.append(input.memory_key) + return _Row() + + monkeypatch.setattr(handlers, "_point_lookup", lookup) + monkeypatch.setattr("server.auth.context.current_auth", lambda: None) + body = {"org": ORG, "namespace": NS, "agent": "a"} + got = asyncio.run(handlers.readable_version(MemoryGetInput(memory_key="k", **body))) + assert got is not None and got.version == 4 and len(got.content_sha256) == 64 + # The identity of the row found, which may be another agent's than the one asked under. + assert (got.agent, got.user_id, got.session_id) == ("mcp", "-", "-") + chunk = MemoryGetInput(memory_key="chunk:1", **body) + assert asyncio.run(handlers.readable_version(chunk)) is None + assert seen == ["k"] + + +def test_a_running_erasure_refuses_a_report(store: _Store, monkeypatch: pytest.MonkeyPatch) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + asked = _erasures(monkeypatch, [True]) + with pytest.raises(ErasureRunningError): + _submit(user_id="bob") + assert store.inserts == [] and asked == [{"alice", "bob"}] + + +def test_a_write_holds_the_erasers_fence_until_its_send_settles( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + rid = _submit().report_id + assert store.fences == [[rules.writer_lease_name(ORG)]] and store.marks == [True, False] + _as(monkeypatch, "maria", Role.ADMIN) + asked = _erasures(monkeypatch, []) + landed = store.insert_version + + async def interrupted(row: dict[str, Any], **_: Any) -> None: + await landed(row) + raise asyncio.CancelledError + + monkeypatch.setattr(reports_store, "insert_version", interrupted) + with pytest.raises(asyncio.CancelledError): + _update(report_id=rid, action="take") + # Left uncertain: the fence keeps its holder until the send's bound, so an eraser + # taking it runs after the version lands. + assert store.marks[-1] is True + # The maintainer and the reporter are both people a user erasure may name. + assert asked[0] == {"alice", "maria"} + + +def test_a_link_to_an_erased_report_does_not_block_new_links( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + first = _submit(problem="One.").report_id + second = _submit(problem="Two.", related=[first]).report_id + third = _submit(problem="Three.").report_id + del store.rows[first] # erased since it was linked + _as(monkeypatch, "maria", Role.ADMIN) + _update(report_id=second, related=[third, third]) + assert store.rows[second]["related"] == [first, third] + + +def test_a_retry_returns_the_report_after_its_target_or_link_is_gone( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + first = _submit(problem="One.").report_id + second = _submit(problem="Two.", related=[first]) + del store.rows[first] # the related report was erased + _target(monkeypatch, None) # and the target is gone + again = _submit(problem="Two.", related=[first]) + assert (again.report_id, again.version) == (second.report_id, 1) + + +@pytest.mark.parametrize("change", ["own copy appears", "mirrored copy is gone"]) +def test_a_document_retry_returns_the_report_whichever_copy_is_there_now( + store: _Store, monkeypatch: pytest.MonkeyPatch, change: str +) -> None: + uri = "gdrive:plan" + copies = _Copies(monkeypatch) + copies.mirror(uri, SID_A, "Q3 price: $10", 2, readers={"alice"}) + copies.reader = "alice" + _as(monkeypatch, "alice") + body = { + "target_kind": "document", + "target_key": uri, + "problem": "The $10 is wrong.", + **copies.read(uri), + } + first = _submit(**body) + assert store.rows[first.report_id]["target_copy"] == f"{MIRROR}/{SID_A}" + if change == "own copy appears": + copies.own(uri, "Q3 price: $12", 5) + else: + copies.mirrored.clear() + again = _submit(**body) + assert (again.report_id, again.version) == (first.report_id, 1) + # Nothing is filed against the other copy, and the report keeps the one it was about. + assert len(store.inserts) == 1 + assert store.rows[first.report_id]["target_copy"] == f"{MIRROR}/{SID_A}" + + +def test_a_whitespace_only_problem_is_refused( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + with pytest.raises(ValidationError, match="what is wrong or missing"): + _submit(problem=" \n\t ") + assert store.inserts == [] + + +@pytest.mark.parametrize( + ("failure", "refusal"), + [ + (PersonUnresolved("the directory could not be read"), BackendUnavailableError), + (PersonUnresolved("tied", tied=True), AuthInsufficientError), + ], +) +def test_a_reporter_the_directory_cannot_fold_is_refused( + store: _Store, monkeypatch: pytest.MonkeyPatch, failure: Exception, refusal: type +) -> None: + _as(monkeypatch, "Alice@Example.test") + _target(monkeypatch, (3, "a" * 64)) + + async def folded(org: str, subject: str) -> str: + return subject.lower() + + monkeypatch.setattr(reports_app, "folded_person", folded) + rid = _submit().report_id + + async def unfolded(org: str, subject: str) -> str: + raise failure + + monkeypatch.setattr(reports_app, "folded_person", unfolded) + # Never filed or matched under the token's raw spelling. + with pytest.raises(refusal): + _submit(problem="Another problem.") + assert len(store.inserts) == 1 + # A report that exists and one that does not are refused alike. + for report_id in (rid, "0" * 32): + with pytest.raises(refusal): + _get(report_id) + with pytest.raises(refusal): + asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput( + org=ORG, namespace=NS, report_id=report_id, evidence=["run:r2"] + ) + ) + ) + # A maintainer reads every report, so a failed fold costs them only the reporter match. + _as(monkeypatch, "maria", Role.ADMIN) + assert _get(rid).found and _get("0" * 32).found is False + _as(monkeypatch, "Alice@Example.test") + monkeypatch.setattr(reports_app, "folded_person", folded) + out = _get(rid) + assert out.found and out.report.reporter == "alice@example.test" + assert _submit().report_id == rid and len(store.inserts) == 1 + + +def test_a_service_account_registry_that_cannot_be_read_files_nothing( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.auth import service_accounts + from server.knowledge.app import people + + async def same(org: str, subject: str) -> str: + return subject + + monkeypatch.setattr(reports_app, "folded_person", people.folded_person) + monkeypatch.setattr("server.auth.aliases.login_handle", same) + monkeypatch.setattr(service_accounts, "_creators", {}) + owners = {"sa:bot": ("alice", "service_account"), "sa:agent-x": ("agent-x", "agent")} + down = [True] + + async def registry_row(org: str, subject: str, **_: Any) -> dict[str, Any] | None: + if down[0]: + raise ConnectionError("registry down") + creator, kind = owners[subject] + return { + "created_by": creator, + "kind": kind, + "inherit_creator_grants": True, + "revoked_at": None, + } + + monkeypatch.setattr(service_accounts, "_creator_row", registry_row) + _target(monkeypatch, (3, "a" * 64)) + # A token minted without the creator claim: only the registry names its person. + _as(monkeypatch, "sa:bot") + with pytest.raises(BackendUnavailableError): + _submit() + assert store.inserts == [] + down[0] = False + row = store.rows[_submit().report_id] + assert (row["reporter"], row["written_by"]) == ("alice", "alice") + # An account the registry confirms has no person behind it reports as itself. + _as(monkeypatch, "sa:agent-x") + row = store.rows[_submit().report_id] + assert (row["reporter"], row["written_by"]) == ("sa:agent-x", "sa:agent-x") + assert len(store.inserts) == 2 + + +def test_evidence_repeated_from_the_report_does_not_count_toward_the_cap( + store: _Store, monkeypatch: pytest.MonkeyPatch +) -> None: + _as(monkeypatch, "alice") + _target(monkeypatch, (3, "a" * 64)) + cited = [f"run:r{i}" for i in range(rules.MAX_EVIDENCE)] + rid = _submit(evidence=cited).report_id + out = asyncio.run( + reports_app.handle_knowledge_reports_evidence( + KnowledgeReportsEvidenceInput(org=ORG, namespace=NS, report_id=rid, evidence=cited[:3]) + ) + ) + assert out.version == 2 and store.rows[rid]["evidence"] == cited diff --git a/tests/unit/test_knowledge_reports_domain.py b/tests/unit/test_knowledge_reports_domain.py new file mode 100644 index 0000000000..1bf18bc351 --- /dev/null +++ b/tests/unit/test_knowledge_reports_domain.py @@ -0,0 +1,122 @@ +"""The report rules in `server.knowledge.domain.reports`: targets, evidence references +and the transitions a maintainer action makes.""" + +from __future__ import annotations + +import pytest + +from server.knowledge.domain.reports import ( + MAX_EVIDENCE, + ReportRefused, + after_evidence, + check_action, + check_evidence, + check_target, + next_state, +) + + +def test_a_missing_knowledge_report_needs_no_target() -> None: + check_target("missing", "", "") + + +@pytest.mark.parametrize("kind", ["incorrect", "outdated"]) +def test_an_incorrect_or_outdated_report_names_its_target(kind: str) -> None: + with pytest.raises(ReportRefused, match="names the memory or document"): + check_target(kind, "", "") + check_target(kind, "memory", "deploy_config") + + +def test_a_target_has_both_its_kind_and_its_key() -> None: + with pytest.raises(ReportRefused, match="names its memory key"): + check_target("incorrect", "document", "") + with pytest.raises(ReportRefused, match="needs target_kind"): + check_target("missing", "", "doc-1") + + +def test_only_a_document_names_the_doc_id_it_was_read_as() -> None: + with pytest.raises(ReportRefused, match="names the target_doc_id"): + check_target("incorrect", "document", "gdrive:plan") + check_target("incorrect", "document", "gdrive:plan", "doc-1") + with pytest.raises(ReportRefused, match="only for a document"): + check_target("incorrect", "memory", "deploy_config", "doc-1") + + +def test_evidence_keeps_order_and_drops_repeats() -> None: + refs = ["gap:g1", "run:r-9", "gap:g1", "reflection:x.1"] + assert check_evidence(refs) == ["gap:g1", "run:r-9", "reflection:x.1"] + + +@pytest.mark.parametrize("ref", ["memory:k", "gap:", "run", "gap:has space", "run:" + "x" * 129]) +def test_evidence_refuses_an_unknown_or_malformed_reference(ref: str) -> None: + with pytest.raises(ReportRefused, match="evidence reference"): + check_evidence([ref]) + + +def test_evidence_is_bounded() -> None: + with pytest.raises(ReportRefused, match=f"at most {MAX_EVIDENCE}"): + check_evidence([f"run:r{i}" for i in range(MAX_EVIDENCE + 1)]) + # Repeats do not count toward the bound. + refs = [f"run:r{i}" for i in range(MAX_EVIDENCE)] + assert check_evidence(refs + refs[:5]) == refs + + +@pytest.mark.parametrize( + ("state", "action", "after"), + [ + ("open", "take", "taken"), + ("taken", "take", "taken"), + ("taken", "release", "open"), + ("open", "request_evidence", "needs_evidence"), + ("taken", "resolve", "resolved"), + ("needs_evidence", "dismiss", "dismissed"), + ("resolved", "reopen", "open"), + ("dismissed", "reopen", "open"), + ], +) +def test_maintainer_actions_move_the_report(state: str, action: str, after: str) -> None: + assert next_state(state, action) == after + + +@pytest.mark.parametrize( + ("state", "action"), + [("resolved", "take"), ("dismissed", "resolve"), ("open", "release"), ("open", "reopen")], +) +def test_an_action_that_does_not_apply_is_refused(state: str, action: str) -> None: + with pytest.raises(ReportRefused): + next_state(state, action) + + +@pytest.mark.parametrize("action", ["dismiss", "request_evidence", "reopen"]) +def test_these_actions_say_why(action: str) -> None: + with pytest.raises(ReportRefused, match="needs a reason"): + check_action(action, reason=" ", resolution_revision="") + check_action(action, reason="duplicate of another report", resolution_revision="") + + +def test_a_resolution_names_the_published_revision() -> None: + with pytest.raises(ReportRefused, match="published revision"): + check_action("resolve", reason="", resolution_revision="") + check_action("resolve", reason="", resolution_revision="memory:deploy_config@7") + with pytest.raises(ReportRefused, match="only for resolve"): + check_action("take", reason="", resolution_revision="memory:deploy_config@7") + + +@pytest.mark.parametrize( + ("state", "assignee", "after"), + [ + ("needs_evidence", "maintainer-a", "taken"), + ("needs_evidence", "", "open"), + ("taken", "maintainer-a", "taken"), + ("open", "", "open"), + ], +) +def test_evidence_from_the_reporter_returns_the_report( + state: str, assignee: str, after: str +) -> None: + assert after_evidence(state, assignee) == after + + +def test_a_closed_report_takes_no_more_evidence() -> None: + with pytest.raises(ReportRefused, match="takes no more evidence"): + after_evidence("dismissed", "") diff --git a/tests/unit/test_knowledge_reports_store.py b/tests/unit/test_knowledge_reports_store.py new file mode 100644 index 0000000000..502cb92321 --- /dev/null +++ b/tests/unit/test_knowledge_reports_store.py @@ -0,0 +1,69 @@ +"""loom.knowledge_reports statements: a change reads the report head with sequential +consistency and writes the next version synchronously, so a writer on another replica +never checks its expected version against a stale head.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from server.knowledge.store import reports as reports_store + + +class _CH: + def __init__(self) -> None: + self.sql: list[str] = [] + self.insert_settings: list[dict[str, Any]] = [] + + async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> None: + self.sql.append(sql) + + async def query_all(self, sql: str, params: dict[str, Any] | None = None) -> list[Any]: + self.sql.append(sql) + return [] + + async def insert(self, table: str, rows: list[dict[str, Any]], **kw: Any) -> None: + self.insert_settings.append(kw.get("settings") or {}) + + +def test_head_reads_are_sequential_and_writes_synchronous() -> None: + ch = _CH() + asyncio.run(reports_store.latest("o", "ns", "r1", ch=ch)) + asyncio.run(reports_store.latest_many("o", "ns", ["r1", "r2"], ch=ch)) + assert len(ch.sql) == 2 + assert all(s.endswith("SETTINGS select_sequential_consistency = 1") for s in ch.sql) + row = dict.fromkeys(reports_store.COLUMNS, "") + asyncio.run(reports_store.insert_version(row, ch=ch)) + assert ch.insert_settings == [{"async_insert": 0, "wait_for_async_insert": 1}] + + +def test_the_queue_reads_every_acknowledged_change() -> None: + """A replica behind a take or a resolve would list the old state, or leave out a report + another replica acknowledged.""" + ch = _CH() + asyncio.run( + reports_store.list_reports( + "o", + "ns", + states=["taken"], + kinds=[], + target_kind="", + target_key="", + assignee="", + reporter="", + limit=50, + ch=ch, + ) + ) + [sql] = ch.sql + assert sql.endswith("SETTINGS select_sequential_consistency = 1") + + +def test_the_copies_at_an_address_are_read_from_every_acknowledged_report() -> None: + """The address filter keeps only these copies: a replica that missed a report would + drop it from a page the list query on another replica finds it for.""" + ch = _CH() + asyncio.run(reports_store.copies_at("o", "ns", "gdrive:plan", ch=ch)) + [sql] = ch.sql + assert f"FROM {reports_store.TABLE} FINAL" in sql + assert sql.endswith("SETTINGS select_sequential_consistency = 1") diff --git a/tests/unit/test_repository_column_sets_match_schema.py b/tests/unit/test_repository_column_sets_match_schema.py index 2089c21005..492b191ff1 100644 --- a/tests/unit/test_repository_column_sets_match_schema.py +++ b/tests/unit/test_repository_column_sets_match_schema.py @@ -21,6 +21,7 @@ # (repository module, constant, table, columns the DDL fills and no writer sends) CASES: list[tuple[str, str, str, frozenset[str]]] = [ ("server.knowledge.store.query_history", "_COLUMNS", "loom.query_history_sources", frozenset()), + ("server.knowledge.store.reports", "COLUMNS", "loom.knowledge_reports", frozenset()), ("server.memory.store.copy_rules", "_COLUMNS", "loom.memory_copy_rules", frozenset()), ( "server.tracker.store.daily", diff --git a/tests/unit/test_rmt_write_paths.py b/tests/unit/test_rmt_write_paths.py index 6230a5ec7c..e2cfee9de7 100644 --- a/tests/unit/test_rmt_write_paths.py +++ b/tests/unit/test_rmt_write_paths.py @@ -40,6 +40,7 @@ "memory_webhooks": ("builder", "test_memory_webhooks.py"), "knowledge_sources": ("builder", "test_knowledge_sources.py"), "knowledge_source_push": ("builder", "test_repository_column_sets_match_schema.py"), + "knowledge_reports": ("builder", "test_repository_column_sets_match_schema.py"), "query_history_sources": ("builder", "test_repository_column_sets_match_schema.py"), "memory_copy_rules": ("builder", "test_repository_column_sets_match_schema.py"), "knowledge_mirrors": ("builder", "test_knowledge_mirrors.py"), diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index 71e236eb69..ce15a349ee 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -186,6 +186,7 @@ def test_the_journal_files() -> None: "133_knowledge_suite_results.sql", "134_memory_copy_rules.sql", "135_knowledge_suite_drafts.sql", + "137_knowledge_reports.sql", ] diff --git a/tests/unit/test_sdk_go_codegen.py b/tests/unit/test_sdk_go_codegen.py index b4dbaa445b..6ea4df1084 100644 --- a/tests/unit/test_sdk_go_codegen.py +++ b/tests/unit/test_sdk_go_codegen.py @@ -176,3 +176,18 @@ def test_check_reports_stale_client_without_rewriting( assert sdk_go_gen.main(["--check"]) == 1 assert wire.read_bytes() == wire_bytes assert client.read_bytes() == stale_client + + +def test_a_uint64_that_also_takes_a_decimal_string_stays_uint64_in_go() -> None: + generated = build_source() + + def field(struct: str, name: str) -> str: + body = generated.split(f"type {struct} struct {{", 1)[1].split("\n}", 1)[0] + line = re.search(rf"^\s*{name}\s+(\S+)", body, re.M) + assert line is not None, body + return line[1] + + # JavaScript sends a report's target version as a string; Go's uint64 holds it exactly. + assert field("KnowledgeReportsSubmitInput", "TargetVersion") == "*uint64" + # A number-or-string field without the UInt64 mark keeps the raw JSON. + assert field("MemoryDeleteVersionInput", "Version") == "json.RawMessage"