diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb1f729584..daee213a37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1043,6 +1043,7 @@ jobs: tests/integration/test_knowledge_suite_drafts.py tests/integration/test_suite_results.py tests/integration/test_proposal_checks_state.py + tests/integration/test_proposal_checks_requirement.py # The statement corpus: every builder's shapes through # EXPLAIN QUERY TREE on the migrated service, and shapes.txt in step # with the builders. ~10 s; a rejection here is a statement that would @@ -1183,6 +1184,7 @@ jobs: tests/integration/test_served_reads.py tests/integration/test_read_receipts.py tests/integration/test_stewardship.py + tests/integration/test_proposal_checks_requirement.py tests/integration/test_memory_by_id.py tests/integration/test_memory_bulk.py tests/integration/test_memory_pin.py diff --git a/docs/architecture/regression-suites.md b/docs/architecture/regression-suites.md index 3af9144231..f3e8e9e461 100644 --- a/docs/architecture/regression-suites.md +++ b/docs/architecture/regression-suites.md @@ -38,6 +38,7 @@ the token (`writer_actor`). | `case_ids`, `case_kinds` | The cases' ids and kinds, in id order. | | `cases` | The cases, text included, as canonical JSON: sorted by id, sorted keys, compact. | | `written_by`, `written_at` | The publishing actor and the time. | +| `required` | 1 or 0 when the revision states the requirement, -1 when it states none. | A revision is one row and is never rewritten, so a merge has nothing to collapse and a read needs no `FINAL`. The current revisions of a namespace are one aggregate: per suite, @@ -46,6 +47,12 @@ tuple means two rows can never contribute different columns to one answer. That selects no case text and no case id; only `knowledge.suites.get` and the publish's read of its own suite add `cases` to the tuple. +The requirement is read beside the tuple, as +`argMaxIf(required, revision, required >= 0)`: the newest value a revision stated. A +build without the column inserts a revision that states none (the column's default, -1), +so the revision it publishes keeps the requirement of the one before it. A suite no +revision stated a requirement for is not required. + The table sets `index_granularity = 64`: it is small and every read names one namespace, so a small granule keeps a read from loading other namespaces' rows. The value is set when the table is created, because a self-hosted server refuses to change it on a table @@ -60,7 +67,8 @@ In order: 2. The body is checked without a read (`server/knowledge/domain/suites.py`): one case per id, the field each kind needs, a first revision that covers something, a case for a suite that covers something. A refusal names the case id and the field, never text. -3. The fleet gate: 503 unless every live replica can erase a suite +3. The fleet gate: 503 unless every live replica can erase a suite, and for a body with + `required: true` unless every live replica checks a required suite before an accept ([rolling upgrades](#rolling-upgrades)). 4. A claim on the namespace's suites, held for the rest of the call. A publish that cannot take it within 5 seconds answers 503. @@ -72,7 +80,13 @@ In order: writes. 8. A selection that overlaps another suite's current revision, or a new suite in a namespace that holds 200, is refused with 409. -9. One insert at `revision + 1`. +9. When the publish turns the requirement on or lowers it, the audit row + `knowledge.suites.requirement` ([a required suite](#a-required-suite)). A row that + cannot be written fails the publish with 503. +10. One insert at `revision + 1`. + +The requirement is part of the document that step 7 compares: `required` omitted takes +the current revision's value, so a body that only changes it writes a revision. The claim is what makes the revision a compare-and-set. The table keeps every row it is given, so two publishes that both read revision 3 would both insert revision 4. The @@ -258,6 +272,15 @@ row does not serve. The listing and `knowledge.suites.results` call the one stat function over the same deciding set (`server/knowledge/app/suite_checks.py`), so they agree for one key and hash. +The listing reads no whole value, so it has only the stored hash. A full read hashes the +value it serves, and the two hashes differ for some values, such as an object with a +null field, which the served value drops. A runner records under the hash of the full +read, and [an acceptance](#a-required-suite) reads the state of that hash. For such a +row the listing's state, and the advice made from it, are therefore for the stored hash: +with results recorded the row lists `outdated`, and under a required suite the blocker +`checks_required`, whatever the acceptance answers. Serving one state for both needs the +listing to read each row's whole value. + The checks are read after `only` and `limit`, for the page alone, in two statements: what each suite's current revision covers (no case kind, id or text), then, only when a listed key is covered, one aggregate over the sets of the covered keys, grouped by key, @@ -272,6 +295,45 @@ The listing never fails on the checks. When either read fails it answers with `c null on every row and `checks_unread` in `degraded`: an unread state is never served as `satisfied`, and the listing decides nothing. +## A required suite + +A suite published with `required: true` makes its checks a condition of an acceptance. +`memory.proposal_decide` with `accept` reads, for the rows it picked, the same two +statements as the listing: what each suite's current revision covers, then the deciding +sets of the covered keys, each for the hash of the value the row serves, which is the +hash a full read answers and an acceptance sends. A key a +required suite covers is accepted only when that state is `satisfied` at the current +revision. Otherwise it answers the code `checks_required` with a sentence that names the +suite, the revision and what the results say, and stays pending; the other keys of the +call are decided. + +- The check is the last refusal of an acceptance, after the proposer, the independence + and the hash checks, so it never hides one of them and a key it refuses is otherwise + acceptable. +- The two reads run one after the other inside the call's sequential reads, so both see + the writes the call's replica has taken. No broad `except` surrounds them: a read that + fails ends the call with a 5xx before any write. An unread state must not pass as + satisfied, and the listing's degraded answer has no place on a decision. +- A rejection, and the rejection an owner's policy writes, read no checks. +- The acceptance's audit row records what it read for a covered key: `checks`, with the + suite, the revision and the state. + +This narrows Expand: where an owner required a suite, a proposal becomes a served fact +only with a record that its exact text did not break the suite's cases. It adds no +revision operator and changes no stored fact. A reviewer's read of the text and the +runner's results are different evidence: without the check an acceptance can be sent +with the results failed, outdated or absent. The check is on the acceptance alone, +because that is the one path where a person's decision is asked for: a direct write by a +writer of the namespace, a definition draft approved in the review queue and a promotion +are not checked, and the maintainer's guide says so. + +A requirement is lowered by turning it off, or by removing a key, a prefix or a case +from a required suite. Each of those, and turning it on, writes +`knowledge.suites.requirement` with `audit.emit_strict` under the publish's claim and +before the insert: the suite, the revision before and after, the requirement before and +after, the keys and prefixes removed and the number of cases removed. The row is not +fail-open, since a requirement that can be lowered without a record holds nothing. + ## Who reads a suite A case states the answer an agent is expected to give, so the agents under test must not @@ -342,6 +404,14 @@ That build refuses to publish a draft's id that the current revision does not ho publishes a suite that already holds one, so a draft is taken through a replica of the newer build ([rule 86](rolling-upgrades.md#the-rules)). +A build without the `required` column accepts a proposal without reading a suite, so a +requirement stated while such a build serves would hold on some replicas only. +`knowledge.suites.publish` with `required: true` therefore answers 503 `OVERLOADED` +until every live replica runs the migration that adds the column; a publish without the +field, or with `false`, is held only by the suites gate. After a rollback the older +build accepts unchecked, and the stored requirement applies again once the newer build +serves ([rule 102](rolling-upgrades.md#the-rules)). + ## Limits | Limit | Value | diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 3076c199a5..ab30a1ad78 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1668,6 +1668,28 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `tests/unit/test_knowledge_reports.py` checks the refusal; the mixed-version gate does not. +102. **A required regression suite** (`knowledge.suites.publish`, `memory.proposal_decide`, + migration 138): N stores whether a revision requires the suite's checks in + `loom.knowledge_suites.required` and refuses an acceptance of a covered key whose + checks are not satisfied. N-1 has no such check and accepts the key. So + `knowledge.suites.publish` with `required: true` answers 503 `OVERLOADED` until every + live replica of every deployment on the store runs migration 138, and while the + fleet cannot be read: a requirement is never stated while a replica would skip it. A + publish without the field or with `false` is not held by this gate. The column is + `Int8 DEFAULT -1`, and N-1 names its columns when it inserts a revision, so a + revision N-1 publishes states no requirement and the reads take the newest stated + value (`argMaxIf(required, revision, required >= 0)`): the suite keeps the + requirement it had. N-1 ignores `required` in a request and names it in + `ignored_args`, and its answers carry no `required`, which a client reads as its + signal that the requirement was not taken. After a rollback N-1 accepts unchecked + and the stored requirement applies again once N serves; nothing is turned off first. + A publish N-1 serves writes no `knowledge.suites.requirement` row: a key, a prefix + or a case it removes from a required suite is recorded only in the counts of its + `knowledge.suites.publish` row, and the requirement holds less once N serves. + `tests/unit/test_proposal_requirement.py` checks the gate, the constant against the + migration's file name and the read of a row N-1 wrote, and the mixed-version gate + does not check this rule. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 1c4c73c48b..36d0faafe8 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -934,7 +934,9 @@ row shows none. When a listed proposal's key is covered by a regression suite, the tab has a **Suite checks** column beside **Graded runs**: the state of the suite's checks for each proposal's content, such as **4 of 4 passed**, **1 failed**, **No results yet** or **Results -outdated**, and an empty cell for a key no suite covers. It says **Checks unavailable** on +outdated**, and an empty cell for a key no suite covers. The cell of a suite that +[requires](regression-suites.md#require-passing-results) its checks ends with **· +required**. It says **Checks unavailable** on every row when the server could not read the checks. See [The state on each pending proposal](regression-suites.md#the-state-on-each-pending-proposal). @@ -944,8 +946,11 @@ covers the key went for the text shown: the state, who recorded the results, wit model and when, and one row a case with its baseline outcome, its outcome with the proposed text and the change between the two; a case's id opens its prompt and its expected behaviour. A role below `admin` reads the state the list shows, with the suite's name and -revision, and no case. The panel decides nothing, and a failed read of it leaves both -decisions as they are. +revision, and no case. For a suite that is not required the panel decides nothing. For a +required suite whose results the review read as not satisfied, **Accept** is unavailable +with the reason **A required suite's checks are not satisfied:** and the panel's own +first line; the comparison and the rejection stay. A failed read of the panel leaves both +decisions as they are, and the server answers an acceptance it refuses with its reason. See [Suite checks in a proposal's review](regression-suites.md#suite-checks-in-a-proposals-review). The Proposals tab's toolbar lists the queue **Newest first** or **Oldest first**, the @@ -1010,7 +1015,8 @@ badge whose read fails is hidden. suite: its name, the memory keys and key prefixes it covers, its cases counted by kind, its revision, and who published that revision and when. A row names the first three keys and the first three prefixes and counts the rest. A suite that covers no key is retired -and says **Covers nothing**. The drawer lists the page on a memory namespace only. +and says **Covers nothing**, and a suite that requires its checks says **Required** +beside its name. The drawer lists the page on a memory namespace only. **New suite** opens a dialog for the suite's name, which cannot be changed afterwards, at least one memory key or key prefix, and the first case. It publishes the suite's first @@ -1036,7 +1042,12 @@ marked **Added**, **Edited** or **Removed** on its row, and nothing is sent unti **Publish**. **Publish** counts the changes, lists them for confirmation, says that [results](regression-suites.md#read-the-results-of-a-proposal) recorded for the revision it replaces stop counting, and sends the whole suite as one revision, made from the -revision the page read: +revision the page read. The switch **Require passing results to accept a proposal** is +one of those changes: under it the page says **Holds proposals on these keys. A direct +write, a definition draft approved in the review queue and a promotion are not +checked.**, the confirmation of a publish that changes it adds that proposals on these +keys wait for new results, and after the publish the page says when a server a release +behind did not turn the requirement on, or off. After **Publish**: - When the suite was published after the page read it, nothing is written. The page reads the newer revision, applies the unpublished changes to it, names the cases changed on diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index 98276f6445..a39fce65b7 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -397,17 +397,18 @@ blocker removes it. `advice_reasons` is never empty: its entries, each a `code` acceptance, then what informs. A client shows the server's `title`, also for a code it does not know. -| Code | Title | When | Effect | -| ------------------ | ----------------------------- | --------------------------------------------------------- | ---------------- | -| `policy_ready` | Meets the evidence thresholds | `ready` is `accept` | advises `accept` | -| `policy_reject` | At the failed-run limit | `ready` is `reject` | advises `reject` | -| `contradicts_fact` | A conflict is recorded | `conflict_with` is not empty | blocks `accept` | -| `harm_reported` | A harm report is recorded | `harm_count` is above 0 | blocks `accept` | -| `usage_unread` | Usage counters unread | the usage counters could not be read | blocks `accept` | -| `sensitive` | Marked sensitive | `sensitivity` is `high` | blocks `accept` | -| `policy_unmet` | Evidence thresholds not met | graded runs exist and `ready` is empty | none | -| `untested` | No graded run relied on it | no graded pass or fail | none | -| `stale` | Waiting 14 days, never used | first proposed 14 days ago or more, and `used_count` is 0 | none | +| Code | Title | When | Effect | +| ------------------ | ----------------------------- | -------------------------------------------------------------- | ---------------- | +| `policy_ready` | Meets the evidence thresholds | `ready` is `accept` | advises `accept` | +| `policy_reject` | At the failed-run limit | `ready` is `reject` | advises `reject` | +| `contradicts_fact` | A conflict is recorded | `conflict_with` is not empty | blocks `accept` | +| `harm_reported` | A harm report is recorded | `harm_count` is above 0 | blocks `accept` | +| `usage_unread` | Usage counters unread | the usage counters could not be read | blocks `accept` | +| `sensitive` | Marked sensitive | `sensitivity` is `high` | blocks `accept` | +| `checks_required` | Required checks not satisfied | `checks.required` is set and `checks.state` is not `satisfied` | blocks `accept` | +| `policy_unmet` | Evidence thresholds not met | graded runs exist and `ready` is empty | none | +| `untested` | No graded run relied on it | no graded pass or fail | none | +| `stale` | Waiting 14 days, never used | first proposed 14 days ago or more, and `used_count` is 0 | none | Advice is not a decision: it changes nothing `memory.proposal_decide` allows. `only="ready"` filters on `ready`, so a proposal whose advice a blocker emptied stays in that listing with @@ -424,10 +425,21 @@ Each listed proposal whose key a [regression suite](../regression-suites.md) cov carries `checks`: the suite, its current revision, the state of the row's stored content (`satisfied`, `failed`, `missing` or `outdated`) and the deciding result set's cases by outcome, as [`knowledge.suites.results`](../regression-suites.md#read-the-results-of-a-proposal) -answers them for that key and hash. `checks` is null for a key no suite covers, for a +answers them for that key and hash. `checks.required` says whether the suite requires +them. `checks` is null for a key no suite covers, for a token narrowed below the namespace, and when the checks could not be read, which the answer's `degraded` names as `checks_unread`. +Where the covering suite is +[required](../regression-suites.md#require-passing-results), an acceptance needs the +checks `satisfied` for the exact text the proposal stores, at the suite's current +revision. A key that lacks them answers `checks_required` and stays pending; the other +keys of the call are decided. The check is the last of an acceptance's refusals, a +rejection reads no checks, and an acceptance whose checks cannot be read fails with a +5xx and decides nothing. It holds an acceptance and nothing else: a direct write to the +key, a definition draft approved in the review queue and a promotion are not checked. +Neither is a proposal under a key outside the suite's selection. + `memory.proposal_decide` requires an administrator. Acceptance also requires an authenticated human whose subject, including linked aliases, differs from the proposer. Service accounts and anonymous callers cannot approve. Either decision supplies @@ -629,6 +641,7 @@ a `code` with its `reason` sentence. A client shows a code it does not know by i | `not_independent` | The reviewer, or a linked alias, proposed it | `the reviewer proposed it; another administrator accepts it` | | `proposer_unknown` | The stored proposer is not a valid actor | `no proposer is recorded, so it cannot be accepted; reject it and propose it again` | | `value_refused` | An earlier deletion refuses the row's text | `the value is refused by an earlier deletion; delete the proposal` | +| `checks_required` | A required suite's checks are not satisfied | `suite (revision ) is required: ` | A decision never writes text an earlier deletion refuses: neither an acceptance nor a rejection. The key of such a proposal answers `value_refused` and stays pending, the @@ -656,8 +669,9 @@ text, a rejection sent with the hash of another text, two pending proposals of o with one text and with two, a text that gains a zero-width space after the plan, an acceptance by the proposer and one by a service account (refused whole with 403 `AUTH_INSUFFICIENT`), a value an earlier deletion refuses, a `high` row decided from the -list and from its full read, and a proposal written with no token on a server that -requires none. Three decisions are corrected with ordinary writes: the writer deletes an +list and from its full read, a proposal written with no token on a server that +requires none, and an acceptance of a key a required suite covers with no results for +its text. Three decisions are corrected with ordinary writes: the writer deletes an accepted fact and a proposal whose value is refused (`memory.delete`), and proposes a rejected key again. diff --git a/docs/features/observability/audit.md b/docs/features/observability/audit.md index a28bc5deae..69a678f4a7 100644 --- a/docs/features/observability/audit.md +++ b/docs/features/observability/audit.md @@ -19,24 +19,25 @@ primitive, not a compliance certification. ## What leaves an audit row -| Source | `event_type` | `subject` holds | -| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Any operation declared `audit=True` | the op name (`memory.delete`, `grants.create`) | the op's `audit_subject` when it declares one (no credential, or a hash for text an erasure must reach), else its validated input with every non-naming text value hashed, as JSON | -| `memory.set` (point writes) | `memory.set` | key, memory id, `content_sha256`, `source_class`, verdict, `pinned`. Never the value | -| `memory.update`, `memory.update_by_id` | the op name | key, memory id, `content_sha256`, `source_class`, version, and the conflict check's verdict before post-write marking (`duplicate` for a version written as one, empty when the revised row is not embedded: a type that is not, or a `high` value). Never the value | -| `memory.bulk_set` | `memory.bulk_set` | one hash-only row per write | -| Every revision committed under Postgres | `memory.revision` | key, memory id, version, `content_sha256`, `source_class`, status, `pinned`, tombstoned, and as actor the token's principal, else the pipeline stage's, else `-` in a request and `process:loom` for Loom's own jobs. Stored with the revision, so not fail-open: retried until it lands or is parked ([storage authority](../../architecture/storage-authority.md#audit)) | -| `memory.import` | `memory.bulk_set` for the facts it writes; `memory.import` for the category links it writes | the bulk write's hash-only row; for the links, `count` and `category_links` (key and category name). Never the text | -| A read of a `high` row, or of evidence held as `high` | `memory.sensitive_read` (from `memory.get`, `memory.get_by_id`, `memory.bulk_get`, `memory.history`, `memory.evidence`, `namespace.snapshot`, `erasure.export`, and `memory.export_evidence` with `include_high`) | key and memory id (`memory.history` and `erasure.export` add the version); for released evidence, its kind, session, chunk index and linked keys; for a conversation turn `erasure.export` serves, its agent, thread id and message id; for a thread, its agent and thread id | -| An admitted request to a restricted namespace | `namespace.restricted_access` (from an op naming it, `audit.list` naming it (transport `op`), the document download and upload, an inbox watch, `admin/claim_release`, `admin/namespace.adopt`, the delegated token mints and the MCP primer) | `op`, `transport`, the caller's `token_id` and `roles`; for a mint, `granted_to`, the new token's subject | -| Loom retiring memories on its own | `memory.auto_supersede` | `reason`, `count` and `retired`: up to 200 retired rows (id, key, agent, user and session, the row and key each retired behind, the judge's label, `judge_verdict`, `judge_confidence`, `judge_model` and `judge_prompt_version` for a conflict-resolver retirement, and `unconfirmed` (`"true"`) when the re-read could not confirm the retirement). Never the value. More rows split across several events | -| A retirement Loom refused for standing | `memory.auto_supersede_refused` | `reason` (`lower_standing_successor`), `path` (the retirement reason it would have recorded), `count` and `kept`: up to 200 rows left live (id, key, agent, user and session, and the row and key each would have retired behind). Never the value. More rows split across several events | -| `memory.copy_rule.run` | `memory.copy_rule.run`; `memory.copy_to` for each proposal a run writes | the rule id, `revision`, `conditions_sha256`, the source namespace, `dry_run`, the counts, `pending`, `reasons` and `truncated`; a run adds `applied_rows`, one entry a proposal written (the source's key, the copy's id and the `content_sha256` copied). The `memory.copy_to` row holds the source and copy ids, `proposed` and `copy_rule` (`@`). Never the value | -| `memory.restore` of a superseded row | `memory.unsupersede` | key, memory id, `superseded_by`, the restored `content_sha256` and `version` | -| A `grants.revoke` row taken under another spelling, or one of several | `grants.revoke` | `namespace`, the stored `subject`, `named` (the subject the call named), and `landed` (`"unknown"`) when the row's insert raised. Beside the op's own row, which holds the input | -| `skill.delete` | `skill.delete` | `name`, `revision` (0 for the whole skill), `deleted_revisions`, and `published_revision` and `published_content_sha256` when the delete took the served revision away. Never the text. Written before the delete and not fail-open: a delete whose row cannot be written answers 503 and deletes nothing | -| `skill.decide` that changes a skill | `skill.decide` | `name`, `revision`, `content_sha256`, `decision` (`publish`, `reject` or `archive`), the revision's `author` and `contributors`, and the note as `note_sha256` and `note_chars`. Never the text or the note. Written before the decision and not fail-open: a decision whose row cannot be written answers 503 and decides nothing. A decision the skill is already in writes no row | -| The server itself | `budget.violated`, `ratelimit.exceeded`, `worker.failed`, `audit.tamper_detected`, … | what the event is about | +| Source | `event_type` | `subject` holds | +| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Any operation declared `audit=True` | the op name (`memory.delete`, `grants.create`) | the op's `audit_subject` when it declares one (no credential, or a hash for text an erasure must reach), else its validated input with every non-naming text value hashed, as JSON | +| `memory.set` (point writes) | `memory.set` | key, memory id, `content_sha256`, `source_class`, verdict, `pinned`. Never the value | +| `memory.update`, `memory.update_by_id` | the op name | key, memory id, `content_sha256`, `source_class`, version, and the conflict check's verdict before post-write marking (`duplicate` for a version written as one, empty when the revised row is not embedded: a type that is not, or a `high` value). Never the value | +| `memory.bulk_set` | `memory.bulk_set` | one hash-only row per write | +| Every revision committed under Postgres | `memory.revision` | key, memory id, version, `content_sha256`, `source_class`, status, `pinned`, tombstoned, and as actor the token's principal, else the pipeline stage's, else `-` in a request and `process:loom` for Loom's own jobs. Stored with the revision, so not fail-open: retried until it lands or is parked ([storage authority](../../architecture/storage-authority.md#audit)) | +| `memory.import` | `memory.bulk_set` for the facts it writes; `memory.import` for the category links it writes | the bulk write's hash-only row; for the links, `count` and `category_links` (key and category name). Never the text | +| A read of a `high` row, or of evidence held as `high` | `memory.sensitive_read` (from `memory.get`, `memory.get_by_id`, `memory.bulk_get`, `memory.history`, `memory.evidence`, `namespace.snapshot`, `erasure.export`, and `memory.export_evidence` with `include_high`) | key and memory id (`memory.history` and `erasure.export` add the version); for released evidence, its kind, session, chunk index and linked keys; for a conversation turn `erasure.export` serves, its agent, thread id and message id; for a thread, its agent and thread id | +| An admitted request to a restricted namespace | `namespace.restricted_access` (from an op naming it, `audit.list` naming it (transport `op`), the document download and upload, an inbox watch, `admin/claim_release`, `admin/namespace.adopt`, the delegated token mints and the MCP primer) | `op`, `transport`, the caller's `token_id` and `roles`; for a mint, `granted_to`, the new token's subject | +| Loom retiring memories on its own | `memory.auto_supersede` | `reason`, `count` and `retired`: up to 200 retired rows (id, key, agent, user and session, the row and key each retired behind, the judge's label, `judge_verdict`, `judge_confidence`, `judge_model` and `judge_prompt_version` for a conflict-resolver retirement, and `unconfirmed` (`"true"`) when the re-read could not confirm the retirement). Never the value. More rows split across several events | +| A retirement Loom refused for standing | `memory.auto_supersede_refused` | `reason` (`lower_standing_successor`), `path` (the retirement reason it would have recorded), `count` and `kept`: up to 200 rows left live (id, key, agent, user and session, and the row and key each would have retired behind). Never the value. More rows split across several events | +| `memory.copy_rule.run` | `memory.copy_rule.run`; `memory.copy_to` for each proposal a run writes | the rule id, `revision`, `conditions_sha256`, the source namespace, `dry_run`, the counts, `pending`, `reasons` and `truncated`; a run adds `applied_rows`, one entry a proposal written (the source's key, the copy's id and the `content_sha256` copied). The `memory.copy_to` row holds the source and copy ids, `proposed` and `copy_rule` (`@`). Never the value | +| `memory.restore` of a superseded row | `memory.unsupersede` | key, memory id, `superseded_by`, the restored `content_sha256` and `version` | +| A `grants.revoke` row taken under another spelling, or one of several | `grants.revoke` | `namespace`, the stored `subject`, `named` (the subject the call named), and `landed` (`"unknown"`) when the row's insert raised. Beside the op's own row, which holds the input | +| `skill.delete` | `skill.delete` | `name`, `revision` (0 for the whole skill), `deleted_revisions`, and `published_revision` and `published_content_sha256` when the delete took the served revision away. Never the text. Written before the delete and not fail-open: a delete whose row cannot be written answers 503 and deletes nothing | +| `skill.decide` that changes a skill | `skill.decide` | `name`, `revision`, `content_sha256`, `decision` (`publish`, `reject` or `archive`), the revision's `author` and `contributors`, and the note as `note_sha256` and `note_chars`. Never the text or the note. Written before the decision and not fail-open: a decision whose row cannot be written answers 503 and decides nothing. A decision the skill is already in writes no row | +| A `knowledge.suites.publish` that turns a suite's requirement on or lowers it | `knowledge.suites.requirement` | `suite`, `revision_before`, `revision`, `required_before`, `required`, the `keys_removed` and `prefixes_removed`, and `cases_removed`, a count. Written when a publish turns the requirement on or off, or removes a key, a prefix or a case from a required suite. Written before the revision and not fail-open: a publish whose row cannot be written answers 503 and publishes nothing | +| The server itself | `budget.violated`, `ratelimit.exceeded`, `worker.failed`, `audit.tamper_detected`, … | what the event is about | The **Audit** column of the generated [operations reference](../../reference/operations.md) lists the ops the transport audits (the `audit` flag on each `Operation`); the memory writes in @@ -50,6 +51,12 @@ insert is logged and loses the row; the operation still succeeds. `skill.delete` `skill.decide` are declared `audit=False` and write their row themselves, before their first write to the skill (`audit.emit_strict`): the delete of reviewed text, and the decision that serves a text to a namespace's readers, are never without their record. +`knowledge.suites.publish` writes `knowledge.suites.requirement` the same way, before +the revision, beside the row the transport writes after it: a +[required suite](../regression-suites.md#require-passing-results) is never turned on or +lowered without its record. A build a release behind writes no such row: a publish it +serves after a rollback is recorded by its `knowledge.suites.publish` row alone +([rule 102](../../architecture/rolling-upgrades.md#the-rules)). For an `audit=True` op the subject is its `audit_subject` when it declares one, else the validated input as `audit.input_subject` shapes it. Fields that name what the call acted @@ -68,7 +75,8 @@ stored as `{"sha256", "chars"}`, its SHA-256 and length (the hash a memory's field's name: `memory.cross_promote`'s and `memory.copy_to`'s `rationale`, `memory.proposal_accept`'s and `memory.proposal_reject`'s `reason` (a `memory.proposal_reject` row the owner's policy writes records the policy's mode and -thresholds instead), and +thresholds instead; a `memory.proposal_accept` row of a key a regression suite covers +also holds `checks`, the suite, its revision and the state the acceptance read), and `triple.follows_row_supersession`'s `closed`, whose actor is the writing principal or `process:loom`. A hash of a short value can be recovered by guessing; the rule keeps long text out of the trail, not every word. An op whose input carries a credential (a tracker diff --git a/docs/features/regression-suites.md b/docs/features/regression-suites.md index 92696b3a6b..ed99ae6cd6 100644 --- a/docs/features/regression-suites.md +++ b/docs/features/regression-suites.md @@ -49,6 +49,7 @@ architecture section describes the design. | `memory_keys` | Exact memory keys the suite covers, at most 200. | | `memory_key_prefixes` | Prefixes of memory keys the suite covers, at most 50. A key that starts with a prefix is covered. | | `cases` | At most 200 cases. A suite that covers a key holds at least one. | +| `required` | Whether an accept of a covered key needs satisfied checks ([below](#require-passing-results)). | | `revision` | Counts from 1. Each publish that changes the suite writes the next revision; a revision is frozen. | A memory key is covered by at most one suite of its namespace. A publish whose keys or @@ -129,7 +130,7 @@ A publish that is refused writes nothing: | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 422 | Two cases share an id; a case lacks the field its kind needs, or has `withdrawn` on another kind; the first revision covers nothing; a suite that covers a key has no case; a new case id starts with `draft-` and is not a pending draft's; an `origin` entry is added to a case already stored or drafted; the namespace is a personal collection. | | 409 | The selection overlaps another suite's, or the namespace already holds 200 suites. | -| 503 | Another publish to the namespace's suites is being saved, or a rolling upgrade is not finished ([rule 86](../architecture/rolling-upgrades.md#the-rules)). Retry after `retry_after_s`. | +| 503 | Another publish to the namespace's suites is being saved, a rolling upgrade is not finished ([rules 86 and 102](../architecture/rolling-upgrades.md#the-rules)), or the record of a change to the requirement could not be written. Retry after `retry_after_s`. | `knowledge.suites.get` with `revision` set reads a past revision, and `knowledge.suites.list` lists every suite of the namespace with what it covers and its @@ -252,6 +253,14 @@ changes to it, names the cases that were changed on both sides, and publishes on [Maintain a suite from a file](#maintain-a-suite-from-a-file) is shown in the server's words and the changes are kept. +The switch **Require passing results to accept a proposal** on the suite's page sets +[the requirement](#require-passing-results). It is one more unpublished change and goes +out with **Publish**, whose confirmation adds that proposals on the suite's keys wait +for new results. Under the switch the page says what the requirement holds and what it +does not check. After the publish the page compares the answer's `required` with what +it sent and says so when a server a release behind did not take it. The list of suites +says **Required** beside the name of a suite that is. + Unpublished changes exist only in the open page. Leaving the page or switching the namespace asks before it discards them, and a reload discards them after the browser's own prompt. @@ -269,8 +278,9 @@ A runner is the evaluation job: a program outside Loom that runs a suite's cases [proposed fact](memory/writing.md#proposals) and records how each case went. One call of `knowledge.suites.submit_results` stores one result set: every case of the suite's current revision, for one memory key the suite covers and one exact content of it. Loom -runs no case and calls no model. Nothing is enforced on a result: an accept does not -read it. +runs no case and calls no model. A result holds an acceptance only where the suite is +required ([Require passing results](#require-passing-results)); elsewhere an acceptance +records the state it read and is not held by it. 1. Read the pending keys with `memory.proposals`, each proposal's full value and its `content_sha256` with `memory.get_by_id`, and the cases with `knowledge.suites.get`. @@ -379,13 +389,22 @@ Results are the suite's cases for this exact content. [`memory.proposals`](memory/writing.md#proposals) lists the same state on each proposal it returns, as `checks`: the suite, its current revision, the state and the deciding -set's `passed`, `failed` and `unavailable`, for the content hash stored with the row. A +set's `passed`, `failed` and `unavailable`, for the content hash stored with the row, +and `required`, whether the suite [requires](#require-passing-results) them. A `high` row, whose hash the listing does not serve, lists its state too. `checks` is null for a key no suite covers. The listing serves it to every reader of the namespace and holds no case id or text; a token narrowed to one user or session gets no `checks`. When the checks cannot be read the listing still answers, with `checks` null on every row and `checks_unread` in `degraded`. +The stored hash and the hash `memory.get_by_id` serves differ for some values, such as +an object with a null field. For such a row the listing's state and advice are for the +stored hash, and an acceptance reads the state of the served one, which is the hash a +runner records under. Once the runner has recorded results, the row lists `outdated`, +and under a required suite the blocker `checks_required`, while its acceptance goes +through when those results are satisfied. `knowledge.suites.results` with the hash of +the full read answers the state the acceptance reads. + In the dashboard the **Proposals** tab of the [Review queue](dashboard.md#the-admin-drawer) shows it in a **Suite checks** column, beside **Graded runs**. The column is drawn when a listed proposal has checks: @@ -400,6 +419,9 @@ beside **Graded runs**. The column is drawn when a listed proposal has checks: | `outdated` | **Results outdated** | a warning mark | | not read (`checks_unread`) | Checks unavailable | plain text, on every row of the list | +A cell of a required suite ends with **· required**, as in **No results yet · +required**. + ### Suite checks in a proposal's review The dashboard shows the results case by case to an administrator of the namespace. The @@ -434,9 +456,76 @@ results and links to [Record results from a runner](#record-results-from-a-runne the suite stopped covering the key after the list was read, it says **No regression suite covers this key** and links to the Regression suites page. -The panel decides nothing: both decisions work the same whatever it shows. When its -read fails it says so in its own line, and on a server that does not serve the results -the review shows no panel. +The panel decides nothing for a suite that is not required: both decisions work the same +whatever it shows. For a [required](#require-passing-results) suite whose results the +review read as not satisfied, **Accept** is unavailable and gives the reason, **A +required suite's checks are not satisfied:** followed by the panel's own first line. +The comparison still opens and a rejection works. When the panel's read fails it says so +in its own line and **Accept** stays available: the server decides, and answers the key +with its reason. On a server that does not serve the results the review shows no panel. + +## Require passing results + +A suite's owner makes satisfied checks a condition of an acceptance by publishing the +suite with `required: true`: + +```console +$ loom call knowledge.suites.publish --data @suite.json required:=true | jq '{revision, required}' +``` + +Read `required` in the answer: a server a release behind ignores the field and answers +without it. `knowledge.suites.get`, each row of `knowledge.suites.list`, +`knowledge.suites.results` and each proposal's `checks` carry `required` too. + +While the suite is required, `memory.proposal_decide` accepts a covered key only when +the state of the proposal's content, for the hash a full read serves, is `satisfied` at +the suite's current revision. Otherwise the key answers the code `checks_required` and +stays pending, the other keys of the call are decided, and `reason` names the suite, its +revision and what the results say: + +| State | `reason` ends with | +| ------------------------------- | ---------------------------------------------------------- | +| `failed` | `1 case failed for this content`, or `2 cases failed …` | +| `outdated` | `its results are for other content or an earlier revision` | +| `missing`, a case could not run | `1 case could not run for this content`, or `2 cases …` | +| `missing`, no set | `no results for this content` | + +The check comes after the other refusals of an acceptance, so a key answers +`checks_required` only when nothing else holds it. When the checks cannot be read the +call fails with a 5xx and decides no key: an unread state never passes as satisfied. A +rejection reads no checks, whoever sends it, and neither does the rejection an owner's +policy writes. + +The requirement is part of the revision: + +- A publish without `required` keeps the suite's value. A first revision without it is + not required. +- Turning it on or off writes a revision even when nothing else changes, and a revision + makes the recorded result sets `outdated`. Proposals on the suite's keys then wait for + the runner to record results for the new revision. +- `knowledge.suites.get` with `revision` set answers the requirement in force at that + revision. + +Turning the requirement on, turning it off, and removing a key, a prefix or a case from +a required suite each write an audit row, `knowledge.suites.requirement`, before the +revision. A publish whose row cannot be written answers 503 and publishes nothing. + +What a required suite does not hold: + +- A write that is not a proposal. `memory.set` without `proposed`, `memory.update` and + `memory.update_by_id` by a writer of the namespace are not checked. +- A definition draft approved in the review queue, and a promotion. +- A proposal under a key outside the suite's selection. Select by a prefix that puts the + topic first in the key, such as `metric/net_revenue/`, so a new key for the topic is + covered. +- A key the suite stops covering. Retiring the suite, or removing the key or its prefix, + frees the key, and the audit row names what was removed. + +`required: true` answers 503 until every server runs a release that checks it +([rule 102](../architecture/rolling-upgrades.md#the-rules)). There is nothing to turn off +before a rollback: a build a release behind accepts without the check, keeps the stored +requirement through the revisions it publishes, and the check applies again once the +newer build serves. ## What others can see @@ -448,11 +537,14 @@ name, the revision, the memory key, the content hash, the number of cases by out the names of the `config` pairs, never a case's id or a `config` value. Each draft is recorded with its memory key, the id the server issued, its kind, the length and a keyed hash of the case and the number of origin runs, and each dismissal with the suite's name -and the ids of the drafts, never a draft's text. +and the ids of the drafts, never a draft's text. A change to a suite's requirement is +recorded with the suite's name, the two revisions, the requirement before and after, the +keys and prefixes removed and the number of cases removed, and an acceptance of a +covered key with the suite's name, its revision and the state the acceptance read. Every reader of the namespace also sees, on each pending proposal `memory.proposals` -lists, the name of the suite that covers its key, the suite's revision, the state of the -proposal's content and the number of cases by outcome +lists, the name of the suite that covers its key, the suite's revision, whether it is +required, the state of the proposal's content and the number of cases by outcome ([The state on each pending proposal](#the-state-on-each-pending-proposal)). An agent that proposed a fact learns from it why the proposal waits, and no case. diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index 8e9ec41379..043adbb685 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -299,6 +299,16 @@ nothing, so a job checks the answer, as the last command does. In Python the cal `await agent.client.knowledge.suites_list()`, `.suites_get({"suite": "finance"})` and `.suites_publish({...})`. +To make the suite's checks a condition of accepting a proposal on its keys +([require passing results](../features/regression-suites.md#require-passing-results)), +publish it with `required`, and check that the answer says so: + +```console +$ loom call knowledge.suites.publish --data @suite.json required:=true | jq -e '.required' +``` + +`required:=false` turns it off, and a publish without the field keeps the suite's value. + An evaluation job records how the suite's cases went for one proposed content, and a reviewer reads the state of that content ([record results](../features/regression-suites.md#record-results-from-a-runner)): diff --git a/docs/operations/upgrades.md b/docs/operations/upgrades.md index 8a0ab29a04..b9bd02ab37 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -438,7 +438,12 @@ erasure that build runs leaves the namespace's suites; run the erasure again onc newer build serves (rule 86). The same holds for the result sets recorded for a suite's cases, when the rollback is to a build without `knowledge.suites.submit_results` (rule 91), and for the draft cases filed for a suite, when the rollback is to a build -without `knowledge.suites.add_draft` (rule 86). A namespace erasure +without `knowledge.suites.add_draft` (rule 86). A build that does not check a required +suite accepts proposals on its keys unchecked; nothing is turned off before the +rollback, and the stored requirement applies again once the newer build serves +(rule 102). A publish that build serves writes no `knowledge.suites.requirement` audit +row: a key, a prefix or a case it removes from a required suite shows only in the +counts of its `knowledge.suites.publish` row. A namespace erasure the previous build runs leaves the namespace's promoted rows live; step 14 of the upgrade procedure lists them once the newer build serves again (rule 45). After a rollback to a build without bot token maximums, every bot's tokens last an hour, diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 4f1a5a570f..2f5e9e8cb8 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -1412,6 +1412,7 @@ One revision of a suite with its cases; the current one by default, and with it | `written_by` | `str` | The actor (`human:` or `process:`) that published the revision. | | `written_at` | `datetime \| None` | When the revision was published (UTC); None when it does not exist. | | `drafts` | `list[SuiteDraft]` | The suite's pending drafts, oldest first: filed by `add_draft`, not dismissed and in no revision. | +| `required` | `bool` | Whether accepting a proposal on a key the suite covers needs satisfied checks, as of the revision read. | ## `knowledge.suites.list` @@ -1443,12 +1444,14 @@ Publish one frozen revision of a namespace's regression suite: the memory keys a | `memory_keys` | `list[str]` | required | Exact memory keys the suite covers, at most 200. | | `memory_key_prefixes` | `list[str]` | required | Prefixes of memory keys the suite covers, at most 50. | | `cases` | `list[SuiteCase]` | required | The whole set of cases of the new revision, at most 200. | +| `required` | `bool \| None` | `None` | Whether accepting a proposal on a covered key needs satisfied checks for its exact content at this revision; omitted keeps the suite's value, and a new suite is not required. | | Output field | Type | Meaning | | --- | --- | --- | | `written` | `bool` | True when this call wrote a new revision. | | `conflict` | `bool` | True when the suite moved past `expected_revision` and this document differs from its current one: nothing was written. | | `revision` | `int` | The suite's current revision after the call, which the next publish passes as `expected_revision`. | +| `required` | `bool` | Whether the suite is required after the call. | ## `knowledge.suites.results` @@ -1468,6 +1471,7 @@ The state of one content of a memory key under the suite that covers the key, wi | `covered` | `bool` | False when no suite of the namespace covers the key; every other field is then empty. | | `suite` | `str` | The suite that covers the key, and its current revision. | | `revision` | `int` | | +| `required` | `bool` | Whether accepting a proposal on this key needs the state `satisfied` for the proposal's content. | | `state` | `Literal['satisfied', 'failed', 'missing', 'outdated', '']` | `satisfied`, `failed` and `missing` describe the newest result set for this content at the current revision; `missing` is also the state when the key has no result set, and `outdated` when its only sets are for other content or an earlier… | | `passed` | `int` | Cases of the deciding set by their outcome with the candidate; zeros without one. | | `failed` | `int` | | diff --git a/frontend/src/api/review.ts b/frontend/src/api/review.ts index e39434920d..20276b3166 100644 --- a/frontend/src/api/review.ts +++ b/frontend/src/api/review.ts @@ -277,6 +277,8 @@ export interface SuiteChecks { passed: number; failed: number; unavailable: number; + /** Whether an accept needs the checks satisfied; absent from a server a release behind. */ + required?: boolean; } /** One key's outcome, the fields of diff --git a/frontend/src/api/suiteResults.ts b/frontend/src/api/suiteResults.ts index 9291ea006c..470efb22fb 100644 --- a/frontend/src/api/suiteResults.ts +++ b/frontend/src/api/suiteResults.ts @@ -29,6 +29,9 @@ export interface SuiteResults { /** The suite that covers the key, and its current revision. */ suite: string; revision: number; + /** Whether an accept of the key needs the state `satisfied`; absent from a server a + * release behind. */ + required?: boolean; /** What the newest result set for this content at the current revision says. `missing` * is also the state with no set, and `outdated` the state when the only sets are for * other content or an earlier revision. */ diff --git a/frontend/src/api/suites.ts b/frontend/src/api/suites.ts index ea0e10bdb7..1219c89188 100644 --- a/frontend/src/api/suites.ts +++ b/frontend/src/api/suites.ts @@ -43,6 +43,9 @@ export interface SuiteHead { written_at: string; /** How many drafts of the suite are pending; absent from a server that holds no drafts. */ pending_drafts?: number; + /** Whether an accept of a covered key needs satisfied checks; absent from a server a + * release behind. */ + required?: boolean; } export interface SuiteList { @@ -76,6 +79,9 @@ export interface SuiteDetail { written_at: string | null; /** The suite's pending drafts, oldest first; absent from a server that holds no drafts. */ drafts?: SuiteDraft[]; + /** Whether an accept of a covered key needs satisfied checks; absent from a server a + * release behind. */ + required?: boolean; } /** POST /v1/knowledge.suites.get: a suite's current revision, with its cases. */ @@ -90,6 +96,9 @@ export interface SuitePublished { conflict: boolean; /** The suite's current revision after the call. */ revision: number; + /** The suite's requirement after the call; absent from a server a release behind, which + * took none. */ + required?: boolean; } /** What one revision holds: the whole of what a publish sends for a suite. */ @@ -97,6 +106,8 @@ export interface SuiteDocument { memory_keys: string[]; memory_key_prefixes: string[]; cases: SuiteCase[]; + /** The requirement, on a publish that changes it: without it the suite keeps its own. */ + required?: boolean; } /** POST /v1/knowledge.suites.publish: `document` as the suite's next revision. `revision` @@ -116,6 +127,7 @@ export async function publishSuite( memory_keys: document.memory_keys, memory_key_prefixes: document.memory_key_prefixes, cases: document.cases, + ...(document.required === undefined ? {} : { required: document.required }), }); } diff --git a/frontend/src/lib/suiteChanges.ts b/frontend/src/lib/suiteChanges.ts index 0b5f0dd842..f62656b43f 100644 --- a/frontend/src/lib/suiteChanges.ts +++ b/frontend/src/lib/suiteChanges.ts @@ -20,6 +20,8 @@ export interface SuiteChanges { cases: CaseChange[]; keys: NameChanges; prefixes: NameChanges; + /** The requirement to publish, when it differs from the suite's. */ + required?: boolean; } export const NO_CHANGES: SuiteChanges = { @@ -29,7 +31,25 @@ export const NO_CHANGES: SuiteChanges = { }; export const changeCount = (c: SuiteChanges): number => - c.cases.length + c.keys.added.length + c.keys.removed.length + c.prefixes.added.length + c.prefixes.removed.length; + c.cases.length + + c.keys.added.length + + c.keys.removed.length + + c.prefixes.added.length + + c.prefixes.removed.length + + (c.required === undefined ? 0 : 1); + +/** The requirement as one of the changes, or nothing when `held`, the suite's own, is it. */ +const requirement = (required: boolean | undefined, held: boolean | undefined) => + required === undefined || required === (held ?? false) ? {} : { required }; + +/** The changes with the requirement set to `required`: no change when `base`, the + * revision the page read, holds it. */ +export const setRequired = (base: SuiteDocument, c: SuiteChanges, required: boolean): SuiteChanges => ({ + cases: c.cases, + keys: c.keys, + prefixes: c.prefixes, + ...requirement(required, base.required), +}); const byId = (a: SuiteCase, b: SuiteCase) => (a.case_id < b.case_id ? -1 : a.case_id > b.case_id ? 1 : 0); const cased = (doc: SuiteDocument) => new Map(doc.cases.map((c) => [c.case_id, c])); @@ -58,6 +78,7 @@ export function applyChanges(head: SuiteDocument, changes: SuiteChanges): SuiteD memory_keys: applyNames(head.memory_keys, changes.keys), memory_key_prefixes: applyNames(head.memory_key_prefixes, changes.prefixes), cases: [...cases.values()].sort(byId), + ...requirement(changes.required, head.required), }; } @@ -104,6 +125,7 @@ export function rebase(head: SuiteDocument, changes: SuiteChanges): SuiteChanges cases, keys: rebaseNames(head.memory_keys, changes.keys), prefixes: rebaseNames(head.memory_key_prefixes, changes.prefixes), + ...requirement(changes.required, head.required), }; } diff --git a/frontend/src/views/admin/ProposalChecks.tsx b/frontend/src/views/admin/ProposalChecks.tsx index 3e9bd7566e..abcde47a70 100644 --- a/frontend/src/views/admin/ProposalChecks.tsx +++ b/frontend/src/views/admin/ProposalChecks.tsx @@ -1,7 +1,7 @@ // The Suite checks panel of a proposal's review: how the regression suite that covers the // proposal's key went for the exact text under review, case by case, against the published // state. Every state, count and change shown is the server's; the panel decides nothing. -import { useId, useState } from "react"; +import { useId, useRef, useState } from "react"; import { Badge, type BadgeState } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; import { Icon } from "@clickhouse/click-ui/Icon"; @@ -60,6 +60,11 @@ function rank({ change, candidate }: SuiteCaseResult): number { return change === "fixed" ? 3 : 4; } +/** What holds an accept of the content `r` answers for: the panel's headline when the + * suite is required and its checks are not satisfied, else null. */ +export const requiredHold = (r: SuiteResults | null): string | null => + r?.covered && r.required && r.state !== "satisfied" ? headline(r).text : null; + /** The state in one badge: the list's words for it, with the revision a pass is of and * what an outdated result is for. */ function headline(r: SuiteResults): Words { @@ -79,22 +84,31 @@ export function ProposalChecks({ memoryKey, contentSha256, checks, + onResults, }: { scope: Scope; memoryKey: string; contentSha256: string; checks: SuiteChecks; + /** Told what the results read answered for `contentSha256`: null until it answers and + * when it fails. */ + onResults?: (results: SuiteResults | null, contentSha256: string) => void; }) { const reason = useOpReason("knowledge.suites.results", scope.namespace); const [read, setRead] = useState(null); const heading = useId(); + // The newest callback, kept out of the read's dependencies. + const report = useRef(onResults); + report.current = onResults; useAbortableEffect( async (signal, live) => { setRead(null); + report.current?.(null, contentSha256); if (reason) return; try { const results = await readSuiteResults(scope, memoryKey, contentSha256, { signal }); + if (live()) report.current?.(results, contentSha256); // The answer holds case ids and no case text: one read of the revision it names. const suite = results.covered && (results.cases ?? []).length > 0 diff --git a/frontend/src/views/admin/ProposalChecksCell.tsx b/frontend/src/views/admin/ProposalChecksCell.tsx index d8588f8196..1e0feedb8a 100644 --- a/frontend/src/views/admin/ProposalChecksCell.tsx +++ b/frontend/src/views/admin/ProposalChecksCell.tsx @@ -44,5 +44,7 @@ export function checksWords(c: PickChecks unavailable : null; const { text, state } = checksWords(checks); - return ; + // A required suite holds an accept until its checks are satisfied. + const words = checks.required ? `${text} · required` : text; + return ; } diff --git a/frontend/src/views/admin/Proposals.test.tsx b/frontend/src/views/admin/Proposals.test.tsx index 593c6103fc..787a4e5d0f 100644 --- a/frontend/src/views/admin/Proposals.test.tsx +++ b/frontend/src/views/admin/Proposals.test.tsx @@ -10,7 +10,7 @@ import { resetNamespaceRoleCache } from "../../lib/namespaceRole"; import { axeViolations } from "../../test/axe"; import { opNames, repositoryText } from "../../test/opNames"; import { ProposalsPanel } from "./Proposals"; -import { readSuiteResults } from "../../api/suiteResults"; +import { getSuiteAt, readSuiteResults, type SuiteResults } from "../../api/suiteResults"; vi.mock("../../components/Toast", () => ({ toast: vi.fn(), toastError: vi.fn(), ToastViewport: () => null })); vi.mock("../../api", async (importOriginal) => { @@ -1045,6 +1045,7 @@ async function serverCodes(): Promise { "not_independent", "proposer_unknown", "value_refused", + "checks_required", ]; return [...source.matchAll(/^[A-Z_]+ = "([a-z_]+)"$/gm)].map((m) => m[1]); } @@ -1623,6 +1624,131 @@ describe("the review's suite checks", () => { await waitFor(() => expect(api.decideProposals).toHaveBeenCalledTimes(1)); }); + /** What a required suite's results answer for the text under review: one case failed. */ + const REQUIRED: SuiteResults = { + covered: true, + suite: "finance", + revision: 5, + required: true, + state: "failed", + passed: 1, + failed: 1, + unavailable: 0, + runner: "process:sa:suite-runner", + config: { model: "scripted" }, + recorded_at: "2026-03-04T10:00:00.000Z", + earlier: 0, + earlier_failed: 0, + cases: [ + { case_id: "refund-window", kind: "expect", baseline: "pass", candidate: "fail", change: "regressed" }, + { case_id: "old-refund-window", kind: "must_not_state", baseline: "pass", candidate: "pass", change: "same" }, + ], + kinds: { expect: 1, decline: 0, must_not_state: 1 }, + }; + const HELD: MemoryProposal = { ...P, checks: checks({ state: "failed", passed: 1, failed: 1, required: true }) }; + + it("Accept says why it is unavailable, in the panel's words, and the comparison still opens", async () => { + // Fails when a required suite's failed checks leave Accept available, when the reason + // is not the panel's own first line, or when the hold closes the comparison or the + // rejection. + vi.mocked(readSuiteResults).mockResolvedValueOnce(REQUIRED); + vi.mocked(getSuiteAt).mockResolvedValueOnce({ + found: true, + revision: 5, + memory_keys: [P.memory_key], + memory_key_prefixes: [], + cases: [ + { + case_id: "refund-window", + kind: "expect", + prompt: "How long does a customer have to ask for a refund?", + expectation: "Thirty days from delivery.", + withdrawn: "", + origin: [], + }, + ], + written_by: "human:olga", + written_at: "2026-03-04T10:00:00.000Z", + }); + await show([HELD]); + const dialog = await open(); + const panel = await within(dialog).findByRole("region", { name: "Suite checks" }); + expect(await within(panel).findByText("1 failed")).toBeInTheDocument(); + const accept = within(dialog).getByRole("button", { name: "Accept reviewed fact" }); + await waitFor(() => expect(accept).toHaveAttribute("aria-disabled", "true")); + expect(accept).toHaveAccessibleDescription("A required suite's checks are not satisfied: 1 failed"); + await userEvent.click(accept); + expect(api.decideProposals).not.toHaveBeenCalled(); + // The comparison opens case by case. + const toggle = within(panel).getByRole("button", { name: "refund-window" }); + await userEvent.click(toggle); + expect(toggle).toHaveAttribute("aria-expanded", "true"); + expect(within(panel).getByText("Thirty days from delivery.")).toBeInTheDocument(); + expect(await axeViolations(dialog)).toEqual([]); + // A rejection reads no checks. + const reject = within(dialog).getByRole("button", { name: "Reject" }); + expect(reject).not.toHaveAttribute("aria-disabled"); + await userEvent.click(reject); + await waitFor(() => expect(api.decideProposals).toHaveBeenCalledTimes(1)); + expect(vi.mocked(api.decideProposals).mock.calls[0][2]).toBe("reject"); + }); + + it("Accept is available when a required suite's checks are satisfied", async () => { + // Fails when a required suite holds an accept its results allow. + vi.mocked(readSuiteResults).mockResolvedValueOnce({ ...REQUIRED, state: "satisfied", passed: 2, failed: 0 }); + await show([{ ...P, checks: checks({ required: true }) }]); + const dialog = await open(); + await within(dialog).findByText("2 of 2 passed · revision 5"); + expect(within(dialog).getByRole("button", { name: "Accept reviewed fact" })).not.toHaveAttribute("aria-disabled"); + }); + + it("Accept stays available when the checks read fails", async () => { + // Fails when the row's listed state, and not the review's own read, holds Accept: the + // server decides an accept the page could not check, and answers it with its reason. + vi.mocked(readSuiteResults).mockRejectedValueOnce(new api.ApiError({ status: 500, message: "boom" })); + vi.mocked(api.decideProposals).mockResolvedValueOnce({ + decided: 0, + results: [ + { + memory_key: P.memory_key, + decided: false, + status: "proposed", + reason: "suite finance (revision 5) is required: 1 case failed for this content", + code: "checks_required", + memory_id: P.memory_id, + }, + ], + }); + await show([HELD]); + const dialog = await open(); + expect(await within(dialog).findByRole("alert")).toHaveTextContent(/^Couldn't load the suite checks: /); + const accept = within(dialog).getByRole("button", { name: "Accept reviewed fact" }); + expect(accept).not.toHaveAttribute("aria-disabled"); + await userEvent.click(accept); + await waitFor(() => expect(api.decideProposals).toHaveBeenCalledTimes(1)); + expect(vi.mocked(api.decideProposals).mock.calls[0][2]).toBe("accept"); + }); + + it("a review that draws no panel is not held by what the review before it read", async () => { + // Fails when the failed checks one review read under a required suite keep Accept + // unavailable in the next review, of the same text under a key no suite covers. + vi.mocked(readSuiteResults).mockResolvedValueOnce(REQUIRED); + const uncovered: MemoryProposal = { ...SECOND, content_sha256: P.content_sha256 }; + await show([HELD, uncovered]); + const first = await open(); + const held = within(first).getByRole("button", { name: "Accept reviewed fact" }); + await waitFor(() => expect(held).toHaveAttribute("aria-disabled", "true")); + await userEvent.click(within(first).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + const second = await open(uncovered.memory_key); + expect(within(second).queryByRole("region", { name: "Suite checks" })).toBeNull(); + const accept = within(second).getByRole("button", { name: "Accept reviewed fact" }); + expect(accept).not.toHaveAttribute("aria-disabled"); + await userEvent.click(accept); + await waitFor(() => expect(api.decideProposals).toHaveBeenCalledTimes(1)); + expect(vi.mocked(api.decideProposals).mock.calls[0].slice(1, 3)).toEqual([[uncovered.memory_key], "accept"]); + }); + it("are not read for a proposal the review could not show", async () => { // Fails when checks are asked for, or drawn, under a text that is not on screen. vi.mocked(api.getMemoryById).mockResolvedValueOnce(whole(COVERED, { found: false })); @@ -1700,6 +1826,16 @@ describe("the Suite checks column", () => { expect(badgeState(text)).toBe(badge); }); + it("says which checks a suite requires", async () => { + // Fails when a required suite's cell reads like one that holds no accept. + await show([ + row("billing/plans/pro", checks({ state: "missing", passed: 0, required: true })), + row("billing/plans/team", checks({ state: "missing", passed: 0 })), + ]); + expect(cell("billing/plans/pro", "Suite checks")).toHaveTextContent(/^Suite checksNo results yet · required$/); + expect(cell("billing/plans/team", "Suite checks")).toHaveTextContent(/^Suite checksNo results yet$/); + }); + it("stands beside Graded runs, and a row no suite covers has an empty cell", async () => { // Fails when the column is drawn elsewhere, has no header, or a key no suite covers // shows a state. diff --git a/frontend/src/views/admin/Proposals.tsx b/frontend/src/views/admin/Proposals.tsx index 166065fcd3..a5e7ab24fe 100644 --- a/frontend/src/views/admin/Proposals.tsx +++ b/frontend/src/views/admin/Proposals.tsx @@ -35,7 +35,8 @@ import { MetaList, MetaRow } from "../../components/ui/Meta"; import { Unavailable } from "../../components/ui/Unavailable"; import { Modal, ModalFooter } from "../../components/ui/Modal"; import { TableSkeleton } from "../../components/Skeleton"; -import { ProposalChecks } from "./ProposalChecks"; +import type { SuiteResults } from "../../api/suiteResults"; +import { ProposalChecks, requiredHold } from "./ProposalChecks"; import { ChecksCell, checksUnread, hasChecksColumn, withChecksHeader } from "./ProposalChecksCell"; const HEADERS = [ @@ -127,6 +128,8 @@ export function ProposalsPanel() { const [reload, setReload] = useState(0); const [busy, setBusy] = useState(false); const [review, setReview] = useState(null); + // What the review's Suite checks panel read, and the content hash it read it for. + const [checksRead, setChecksRead] = useState<{ results: SuiteResults | null; sha: string } | null>(null); // The key under review as of the latest render, for a read that answers after it opened. const reviewKey = useRef(null); reviewKey.current = review?.proposal.memory_key ?? null; @@ -153,6 +156,9 @@ export function ProposalsPanel() { focusPanel.current = fromAddress; setNotice(null); setReason(""); + // What the review before this one read holds no accept here: this review's own panel + // reports again when it is drawn. + setChecksRead(null); setReview({ proposal }); setViewParam("key", proposal.memory_key); const read = await readProposal(scope, proposal); @@ -302,6 +308,11 @@ export function ProposalsPanel() { }, [rows]); const shared = review !== null && (perKey.get(review.proposal.memory_key) ?? 0) > 1 ? SHARED_KEY : null; const rejectReason = decideReason ?? shared; + // A required suite whose results, read for the text under review, are not satisfied: + // the server refuses that accept. Before the read answers, and when it fails, Accept + // stays available and the server decides. + const unmet = review?.row?.content_sha256 === checksRead?.sha ? requiredHold(checksRead?.results ?? null) : null; + const checksReason = unmet ? `A required suite's checks are not satisfied: ${unmet}` : null; const unread = !review?.row || !!review.error; // A batch names each row by the hash served with it, so it takes the rows the caller can @@ -401,6 +412,7 @@ export function ProposalsPanel() { memoryKey={review.proposal.memory_key} contentSha256={review.row.content_sha256} checks={review.proposal.checks} + onResults={(results, sha) => setChecksRead({ results, sha })} /> )}
@@ -426,7 +438,7 @@ export function ProposalsPanel() { Reject - + @@ -755,6 +767,7 @@ const UNDECIDED = new Map([ ["not_independent", "You proposed this. Another administrator accepts it."], ["proposer_unknown", "No proposer is recorded, so it cannot be accepted. Reject it and propose it again."], ["value_refused", "An earlier deletion refuses this text. Delete the proposal."], + ["checks_required", "A required suite's checks are not satisfied for this text."], ]); /** Why `proposal` was left undecided: the words of its result's code, or the server's diff --git a/frontend/src/views/admin/Suites.test.tsx b/frontend/src/views/admin/Suites.test.tsx index 50f6876f7f..55dd236e26 100644 --- a/frontend/src/views/admin/Suites.test.tsx +++ b/frontend/src/views/admin/Suites.test.tsx @@ -1153,6 +1153,100 @@ describe("Suites", () => { expect(suiteAddress()).toBeNull(); }); + // Fails if the switch sends a publish of its own, goes out without `required`, lacks its + // hint, or the confirmation does not say that proposals wait for new results. + it("the switch goes out with Publish and the confirmation says results stop counting", async () => { + vi.mocked(listSuites).mockResolvedValue({ suites: [{ ...FINANCE, required: true }, LEGACY] }); + vi.mocked(publishSuite).mockResolvedValue({ written: true, conflict: false, revision: 4, required: true }); + const user = userEvent.setup(); + page(); + // The list says which suite is required, beside its name. + expect(within(await rowOf("finance")).getByText("Required")).toBeInTheDocument(); + expect(within(await rowOf("legacy-pricing")).queryByText("Required")).toBeNull(); + await user.click(within(await rowOf("finance")).getByRole("button", { name: "finance" })); + await screen.findByRole("heading", { level: 1, name: "finance" }); + + const toggle = screen.getByRole("switch", { name: "Require passing results to accept a proposal" }); + expect(toggle).not.toBeChecked(); + expect(toggle).toHaveAccessibleDescription( + "Holds proposals on these keys. A direct write, a definition draft approved in the review queue and a promotion are not checked.", + ); + await user.click(toggle); + expect(toggle).toBeChecked(); + expect(vi.mocked(publishSuite)).not.toHaveBeenCalled(); + // Switched back, it is no change; switched on again, it is one. + await user.click(toggle); + expect(screen.getByRole("button", { name: "Publish" })).toHaveAttribute("aria-disabled", "true"); + await user.click(toggle); + + await user.click(screen.getByRole("button", { name: "Publish (1)" })); + const dialog = await screen.findByRole("dialog", { name: "Publish finance?" }); + expect( + within(within(dialog).getByRole("list", { name: "Require passing results to accept a proposal" })).getByText( + "Turned on", + ), + ).toBeInTheDocument(); + expect(dialog).toHaveAccessibleDescription( + "These changes are published together, as the suite's next revision. Results recorded for revision 3 stop counting; proposals on these keys wait for new results.", + ); + // The read after the publish answers the revision it wrote. + vi.mocked(getSuite).mockResolvedValue({ ...DETAIL, revision: 4, required: true }); + await user.click(within(dialog).getByRole("button", { name: "Publish" })); + await waitFor(() => expect(vi.mocked(publishSuite)).toHaveBeenCalledTimes(1)); + expect(vi.mocked(publishSuite).mock.calls[0][3]).toEqual({ + memory_keys: DETAIL.memory_keys, + memory_key_prefixes: DETAIL.memory_key_prefixes, + cases: DETAIL.cases, + required: true, + }); + expect(await screen.findByText("Published revision 4")).toBeInTheDocument(); + expect(screen.queryByText(/did not take the requirement/)).toBeNull(); + // The answer's requirement is the suite's now: the switch is on with nothing unpublished. + expect(screen.getByRole("switch", { name: "Require passing results to accept a proposal" })).toBeChecked(); + expect(screen.getByRole("button", { name: "Publish" })).toHaveAttribute("aria-disabled", "true"); + }); + + // Fails if a server that ignored `required` leaves the page showing the suite as required, + // or says nothing about the requirement it did not take. + it("says when the server did not take the requirement", async () => { + // A server a release behind: no `required` in the answer. + vi.mocked(publishSuite).mockResolvedValue({ written: false, conflict: false, revision: 3 }); + const user = userEvent.setup(); + await openSuite(user); + await user.click(screen.getByRole("switch", { name: "Require passing results to accept a proposal" })); + await publishNow(user, "Publish (1)"); + await waitFor(() => expect(vi.mocked(publishSuite)).toHaveBeenCalledTimes(1)); + expect(vi.mocked(publishSuite).mock.calls[0][3]).toMatchObject({ required: true }); + expect(await screen.findByRole("alert")).toHaveTextContent( + "This server did not take the requirement: it runs a release that does not check a required suite.", + ); + expect(screen.getByRole("switch", { name: "Require passing results to accept a proposal" })).not.toBeChecked(); + }); + + // Fails if a server that ignored `required: false` is said to hold no proposal, or the + // page shows the suite as no longer required. + it("says the suite is still required when the server did not turn the requirement off", async () => { + vi.mocked(getSuite).mockResolvedValue({ ...DETAIL, required: true }); + // A server a release behind: no `required` in the answer. + vi.mocked(publishSuite).mockResolvedValue({ written: true, conflict: false, revision: 4 }); + const user = userEvent.setup(); + await openSuite(user); + const toggle = screen.getByRole("switch", { name: "Require passing results to accept a proposal" }); + expect(toggle).toBeChecked(); + await user.click(toggle); + // The read after the publish answers the requirement that is still stored. + vi.mocked(getSuite).mockResolvedValue({ ...DETAIL, revision: 4, required: true }); + await publishNow(user, "Publish (1)"); + await waitFor(() => expect(vi.mocked(publishSuite)).toHaveBeenCalledTimes(1)); + expect(vi.mocked(publishSuite).mock.calls[0][3]).toMatchObject({ required: false }); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent( + "This server did not turn the requirement off: it runs a release that does not read it. The suite is still required, and a server on the newer release still holds proposals on these keys. Turn it off again once the server is upgraded.", + ); + expect(alert).not.toHaveTextContent("needs no results"); + expect(screen.getByRole("switch", { name: "Require passing results to accept a proposal" })).toBeChecked(); + }); + // Fails if a draft is sent before Publish, goes out under another id, stays listed as a // draft once it is one of the cases, or can be given another id (its origin follows it). it("Add to suite adds the draft as an unpublished case under its id", async () => { diff --git a/frontend/src/views/admin/Suites.tsx b/frontend/src/views/admin/Suites.tsx index 48891dab72..6c059cf04e 100644 --- a/frontend/src/views/admin/Suites.tsx +++ b/frontend/src/views/admin/Suites.tsx @@ -8,6 +8,7 @@ import { Badge } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; import { Icon } from "@clickhouse/click-ui/Icon"; import { Link } from "@clickhouse/click-ui/Link"; +import { Switch } from "@clickhouse/click-ui/Switch"; import { Table } from "@clickhouse/click-ui/Table"; import { getSuite, @@ -44,6 +45,7 @@ import { documentProblem, NO_CHANGES, rebase, + setRequired, removeCase, saveCase, setName, @@ -283,6 +285,7 @@ function SuiteList() { {row.suite} {retired &&
Covers nothing
} + {row.required &&
Required
}
), overflowMode: "wrap", @@ -381,6 +384,8 @@ function SuitePage({ name }: { name: string }) { const [gone, setGone] = useState(false); // Why the last Publish wrote nothing, in the server's words. const [refusal, setRefusal] = useState(null); + // The requirement the last Publish sent, when the answer does not hold it. + const [untaken, setUntaken] = useState(null); // The case form holds text that is not one of the changes yet. const [drafting, setDrafting] = useState(false); const [confirming, setConfirming] = useState(false); @@ -428,6 +433,7 @@ function SuitePage({ name }: { name: string }) { if (!detail || !next) return; setBusy(true); setRefusal(null); + setUntaken(null); try { const answer = await publishSuite(identity, name, detail.revision, next); if (answer.conflict) { @@ -450,8 +456,12 @@ function SuitePage({ name }: { name: string }) { ); setMoved(null); setChanges(NO_CHANGES); - // What was sent is the suite now; the read after it brings who wrote it and when. - setRead({ detail: { ...detail, ...next, revision: answer.revision }, error: null }); + // A server a release behind ignores the requirement and answers without one. + setUntaken(next.required !== undefined && answer.required !== next.required ? next.required : null); + // What was sent is the suite now, with the requirement the answer holds; the read + // after it brings who wrote it and when. + const required = answer.required ?? detail.required; + setRead({ detail: { ...detail, ...next, required, revision: answer.revision }, error: null }); setRetry((n) => n + 1); } } catch (e) { @@ -547,6 +557,18 @@ function SuitePage({ name }: { name: string }) { text={`Couldn't publish, and your changes are kept. ${refusal}`} /> )} + {detail && untaken !== null && ( + + )} {detail && next && ( setConfirming(false)} onPublish={() => void publish()} @@ -579,11 +602,15 @@ function SuitePage({ name }: { name: string }) { ); } +/** The switch that makes a suite's checks a condition of accepting a proposal. */ +const REQUIRE_LABEL = "Require passing results to accept a proposal"; + /** What Publish is about to send, by kind of change, before it sends it. */ function PublishDialog({ name, revision, changes, + required, busy, onCancel, onPublish, @@ -592,6 +619,8 @@ function PublishDialog({ /** The revision the changes were made on, which this publish replaces. */ revision: number; changes: SuiteChanges; + /** Whether the suite is required once this is published. */ + required: boolean; busy: boolean; onCancel: () => void; onPublish: () => void; @@ -609,13 +638,14 @@ function PublishDialog({ ["Memory keys removed", changes.keys.removed], ["Key prefixes added", changes.prefixes.added], ["Key prefixes removed", changes.prefixes.removed], + [REQUIRE_LABEL, changes.required === undefined ? [] : [changes.required ? "Turned on" : "Turned off"]], ]; return ( !open && !busy && onCancel()} title={`Publish ${name}?`} - description={`These changes are published together, as the suite's next revision. Results recorded for revision ${fmtInt(revision)} stop counting.`} + description={`These changes are published together, as the suite's next revision. Results recorded for revision ${fmtInt(revision)} stop counting${required ? "; proposals on these keys wait for new results" : ""}.`} className="w-full max-w-[520px]" >
@@ -626,7 +656,7 @@ function PublishDialog({
{label}
    {names.map((n) => ( -
  • +
  • {n}
  • ))} @@ -740,6 +770,18 @@ function SuiteBody({ names={next.memory_key_prefixes} {...selection("prefixes", detail.memory_key_prefixes)} /> +
    + onChange(setRequired(detail, changes, on === true))} + aria-describedby={`${panels}required`} + /> +

    + Holds proposals on these keys. A direct write, a definition draft approved in the review queue and a + promotion are not checked. +

    +
    OpSpec.new("knowledge.suites.dismiss_drafts", "knowledge", "suites_dismiss_drafts", true, false, "admin", "experimental", %w[org namespace suite case_ids].freeze, %w[org namespace suite case_ids].freeze), "knowledge.suites.get" => OpSpec.new("knowledge.suites.get", "knowledge", "suites_get", true, false, "admin", "experimental", %w[org namespace suite revision].freeze, %w[org namespace suite].freeze), "knowledge.suites.list" => OpSpec.new("knowledge.suites.list", "knowledge", "suites_list", true, false, "admin", "experimental", %w[org namespace].freeze, %w[org namespace].freeze), - "knowledge.suites.publish" => OpSpec.new("knowledge.suites.publish", "knowledge", "suites_publish", true, false, "admin", "experimental", %w[org namespace suite expected_revision memory_keys memory_key_prefixes cases].freeze, %w[org namespace suite expected_revision memory_keys memory_key_prefixes cases].freeze), + "knowledge.suites.publish" => OpSpec.new("knowledge.suites.publish", "knowledge", "suites_publish", true, false, "admin", "experimental", %w[org namespace suite expected_revision memory_keys memory_key_prefixes cases required].freeze, %w[org namespace suite expected_revision memory_keys memory_key_prefixes cases].freeze), "knowledge.suites.results" => OpSpec.new("knowledge.suites.results", "knowledge", "suites_results", true, false, "admin", "experimental", %w[org namespace memory_key content_sha256].freeze, %w[org namespace memory_key content_sha256].freeze), "knowledge.suites.submit_results" => OpSpec.new("knowledge.suites.submit_results", "knowledge", "suites_submit_results", true, false, "admin", "experimental", %w[org namespace suite revision memory_key content_sha256 outcomes config].freeze, %w[org namespace suite revision memory_key content_sha256 outcomes config].freeze), "knowledge.synthesize" => OpSpec.new("knowledge.synthesize", "knowledge", "synthesize", true, false, "viewer", "experimental", %w[org namespace user_id source_uris datasets task window_chars max_answer_chars max_windows].freeze, %w[org namespace task].freeze), diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index b931492136..d442d2b54e 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -31844,6 +31844,8 @@ pub struct KnowledgeSuitesGetOutput { pub written_at: Option, #[serde(default = "default_knowledge_suites_get_output_drafts")] pub drafts: Vec, + #[serde(default = "default_knowledge_suites_get_output_required")] + pub required: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -31911,6 +31913,8 @@ pub struct SuiteHead { pub written_at: String, #[serde(default = "default_suite_head_pending_drafts")] pub pending_drafts: Integer, + #[serde(default = "default_suite_head_required")] + pub required: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -31972,6 +31976,8 @@ pub struct KnowledgeSuitesPublishOutput { #[serde(default = "default_knowledge_suites_publish_output_conflict")] pub conflict: bool, pub revision: Integer, + #[serde(default = "default_knowledge_suites_publish_output_required")] + pub required: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -32059,6 +32065,12 @@ pub struct KnowledgeSuitesPublishInput { pub memory_keys: Vec, pub memory_key_prefixes: Vec, pub cases: Vec, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub required: Option>, } impl KnowledgeSuitesPublishInput { pub fn new( @@ -32076,6 +32088,7 @@ impl KnowledgeSuitesPublishInput { memory_keys: memory_keys.into_iter().map(Into::into).collect(), memory_key_prefixes: memory_key_prefixes.into_iter().map(Into::into).collect(), cases, + required: None, } } pub fn org(mut self, org: impl Into) -> Self { @@ -32086,6 +32099,14 @@ impl KnowledgeSuitesPublishInput { self.namespace = Some(namespace.into()); self } + pub fn required(mut self, required: bool) -> Self { + self.required = Some(Some(required)); + self + } + pub fn required_null(mut self) -> Self { + self.required = Some(None); + self + } pub async fn send( self, client: &crate::Client, @@ -32180,6 +32201,8 @@ pub struct KnowledgeSuitesResultsOutput { pub suite: String, #[serde(default = "default_knowledge_suites_results_output_revision")] pub revision: Integer, + #[serde(default = "default_knowledge_suites_results_output_required")] + pub required: bool, #[serde(default = "default_knowledge_suites_results_output_state")] pub state: KnowledgeSuitesResultsOutputState, #[serde(default = "default_knowledge_suites_results_output_passed")] @@ -43626,6 +43649,8 @@ pub struct ProposalChecks { pub passed: Integer, pub failed: Integer, pub unavailable: Integer, + #[serde(default = "default_proposal_checks_required")] + pub required: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -72258,21 +72283,33 @@ fn default_knowledge_suites_get_output_written_at() -> Option { fn default_knowledge_suites_get_output_drafts() -> Vec { serde_json::from_str("[]").expect("schema default") } +fn default_knowledge_suites_get_output_required() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_suite_head_pending_drafts() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_suite_head_required() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_knowledge_suites_list_output_suites() -> Vec { serde_json::from_str("[]").expect("schema default") } fn default_knowledge_suites_publish_output_conflict() -> bool { serde_json::from_str("false").expect("schema default") } +fn default_knowledge_suites_publish_output_required() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_knowledge_suites_results_output_suite() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_knowledge_suites_results_output_revision() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_knowledge_suites_results_output_required() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_knowledge_suites_results_output_state() -> KnowledgeSuitesResultsOutputState { serde_json::from_str("\"\"").expect("schema default") } @@ -73828,6 +73865,9 @@ fn default_memory_proposal_advice() -> MemoryProposalAdvice { fn default_memory_proposal_advice_reasons() -> Vec { serde_json::from_str("[]").expect("schema default") } +fn default_proposal_checks_required() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_memory_proposal_checks() -> Option { serde_json::from_str("null").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index 66af0936fa..dde0467b80 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -14257,6 +14257,11 @@ fn knowledge_suites_publish() { serde_json::from_str::("false").unwrap(), "knowledge.suites.publish:conflict" ); + assert_eq!( + encoded["required"], + serde_json::from_str::("false").unwrap(), + "knowledge.suites.publish:required" + ); } #[test] fn knowledge_suites_get() { @@ -14304,6 +14309,11 @@ fn knowledge_suites_get() { serde_json::from_str::("[]").unwrap(), "knowledge.suites.get:drafts" ); + assert_eq!( + encoded["required"], + serde_json::from_str::("false").unwrap(), + "knowledge.suites.get:required" + ); } #[test] fn knowledge_suites_list() { @@ -14374,6 +14384,11 @@ fn knowledge_suites_results() { serde_json::from_str::("0").unwrap(), "knowledge.suites.results:revision" ); + assert_eq!( + encoded["required"], + serde_json::from_str::("false").unwrap(), + "knowledge.suites.results:required" + ); assert_eq!( encoded["state"], serde_json::from_str::("\"\"").unwrap(), diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 15250c52bd..bf4cc06766 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -5747,6 +5747,7 @@ export interface KnowledgeSuitesGetOutput { written_by?: string; written_at?: string | null; drafts?: SuiteDraft[]; + required?: boolean; } export interface KnowledgeSuitesListInput { @@ -5763,6 +5764,7 @@ export interface SuiteHead { written_by: string; written_at: string; // date-time pending_drafts?: number; + required?: boolean; } export interface KnowledgeSuitesListOutput { @@ -5777,12 +5779,14 @@ export interface KnowledgeSuitesPublishInput { memory_keys: string[]; memory_key_prefixes: string[]; cases: SuiteCase[]; + required?: boolean | null; } export interface KnowledgeSuitesPublishOutput { written: boolean; conflict?: boolean; revision: number; + required?: boolean; } export interface KnowledgeSuitesResultsInput { @@ -5804,6 +5808,7 @@ export interface KnowledgeSuitesResultsOutput { covered: boolean; suite?: string; revision?: number; + required?: boolean; state?: "satisfied" | "failed" | "missing" | "outdated" | ""; passed?: number; failed?: number; @@ -8099,6 +8104,7 @@ export interface ProposalChecks { passed: number; failed: number; unavailable: number; + required?: boolean; } export interface ProposalPolicy { diff --git a/server/knowledge/api/models_suites.py b/server/knowledge/api/models_suites.py index 29dc06a8fa..7bfc0861c4 100644 --- a/server/knowledge/api/models_suites.py +++ b/server/knowledge/api/models_suites.py @@ -141,6 +141,12 @@ class KnowledgeSuitesPublishInput(BaseModel): # pending draft of the suite adds that draft, with the origin its drafter stored; # no other new case may take an id that starts with `draft-`. cases: list[SuiteCase] = Field(max_length=200) + # Whether accepting a proposal on a covered key needs satisfied checks for its exact + # content at this revision; omitted keeps the suite's value, and a new suite is not + # required. A change writes a revision, so results recorded before it read + # `outdated`. Check the answer's `required`: a server that does not hold the field + # ignores it. + required: bool | None = None class KnowledgeSuitesPublishOutput(BaseModel): @@ -152,6 +158,8 @@ class KnowledgeSuitesPublishOutput(BaseModel): # The suite's current revision after the call, which the next publish passes as # `expected_revision`. revision: int + # Whether the suite is required after the call. + required: bool = False class KnowledgeSuitesGetInput(BaseModel): @@ -182,6 +190,9 @@ class KnowledgeSuitesGetOutput(BaseModel): # in no revision. Served with the current revision (`revision` 0); empty on a read # that names a revision. drafts: list[SuiteDraft] = Field(default_factory=list) + # Whether accepting a proposal on a key the suite covers needs satisfied checks, as + # of the revision read. + required: bool = False class KnowledgeSuitesListInput(BaseModel): @@ -206,6 +217,8 @@ class _SuiteHead(BaseModel): written_at: datetime # How many drafts of the suite are pending. pending_drafts: int = 0 + # Whether accepting a proposal on a key the suite covers needs satisfied checks. + required: bool = False class KnowledgeSuitesListOutput(BaseModel): @@ -290,6 +303,9 @@ class KnowledgeSuitesResultsOutput(BaseModel): # The suite that covers the key, and its current revision. suite: str = "" revision: int = 0 + # Whether accepting a proposal on this key needs the state `satisfied` for the + # proposal's content. + required: bool = False # `satisfied`, `failed` and `missing` describe the newest result set for this # content at the current revision; `missing` is also the state when the key has no # result set, and `outdated` when its only sets are for other content or an earlier diff --git a/server/knowledge/app/suite_checks.py b/server/knowledge/app/suite_checks.py index cdc57c5cc4..4ba229dbc9 100644 --- a/server/knowledge/app/suite_checks.py +++ b/server/knowledge/app/suite_checks.py @@ -1,8 +1,9 @@ """The state of a regression suite's checks for many contents of memory keys at once, -as a listing reads it for the rows it returns. +as a listing reads it for the rows it returns and an accept for the rows it decides. `for_keys` answers, for each `(memory_key, content_sha256)` asked, the suite that covers -the key, its current revision, and the state and counts of the set that decides: the +the key, its current revision, whether it is required, and the state and counts of the +set that decides: the state `knowledge.suites.results` answers for that key and hash, from the same function (`server/knowledge/domain/suite_state.py`) over the same deciding set. It reads what the suites cover, then, only when a key is covered, the counts of the covered keys' sets: @@ -24,8 +25,8 @@ @dataclass(frozen=True) class Checks: """The checks of one content of a memory key: the suite that covers the key, its - current revision, the state of the content under it, and the deciding set's cases - by outcome (zeros without one).""" + current revision, the state of the content under it, the deciding set's cases by + outcome (zeros without one), and whether an accept needs the state `satisfied`.""" suite: str revision: int @@ -33,6 +34,7 @@ class Checks: passed: int failed: int unavailable: int + required: bool async def for_keys( @@ -53,6 +55,7 @@ async def for_keys( (h["suite"], h["memory_keys"], h["memory_key_prefixes"]) for h in heads ) revisions = {str(h["suite"]): int(h["revision"]) for h in heads} + required = {str(h["suite"]) for h in heads if h["required"]} suite_of = { key: suite for key in {key for key, _ in contents} @@ -86,5 +89,6 @@ async def for_keys( passed=counts.passed, failed=counts.failed, unavailable=counts.unavailable, + required=suite in required, ) return out diff --git a/server/knowledge/app/suite_results.py b/server/knowledge/app/suite_results.py index d7d9255cdc..3237bbd670 100644 --- a/server/knowledge/app/suite_results.py +++ b/server/knowledge/app/suite_results.py @@ -127,6 +127,7 @@ async def handle_knowledge_suites_results( covered=True, suite=suite, revision=revision, + required=bool(head["required"]), state=suite_state.state(_counts(deciding), other_set=other_set), kinds={kind: 0 for kind in get_args(CaseKind)} | suites.kind_counts(head["case_kinds"]), **(_deciding_fields(deciding, head) if deciding is not None else {}), diff --git a/server/knowledge/app/suites.py b/server/knowledge/app/suites.py index 0ac0a390f3..939cc37a4c 100644 --- a/server/knowledge/app/suites.py +++ b/server/knowledge/app/suites.py @@ -14,9 +14,15 @@ read of the current revision serves the pending ones, and a publish takes one by holding a case under its id, with the origin its drafter stored. +A revision also states whether the suite is required: whether accepting a proposal on +a key it covers needs satisfied checks (`server/memory/app/proposals.py`). A publish +that omits `required` keeps the requirement in force. + A publish's audit row records counts, the document's length and a keyed hash of it (`publish_audit_subject`): the audit log is read by every reader of the namespace and -outlives an erasure, so no case text or id reaches it. +outlives an erasure, so no case text or id reaches it. A publish that changes the +requirement, or takes a key, a prefix or a case out of a required suite, writes one +more row first, `knowledge.suites.requirement`, and fails when that row is not written. """ from __future__ import annotations @@ -33,7 +39,12 @@ from server.core import leases from server.core.ch import get_client, own_write_reads from server.core.datetimes import naive_utc_now -from server.core.errors import OverloadedError, PreconditionFailedError, ValidationError +from server.core.errors import ( + BackendUnavailableError, + OverloadedError, + PreconditionFailedError, + ValidationError, +) from server.knowledge.api.models_suites import ( KnowledgeSuitesGetInput, KnowledgeSuitesGetOutput, @@ -49,6 +60,7 @@ from server.knowledge.store import suite_drafts as drafts_repo from server.knowledge.store import suites as repo from server.memory.app.provenance import writer_actor +from server.observability import audit from server.operations.base import Role from server.settings import settings from server.tasks.app.run import existing_run_ids @@ -56,6 +68,10 @@ # 130_knowledge_suites.sql made the table: a build below it serves no suite op and its # namespace erasure leaves the rows. SUITES_MIGRATION = 130 # tests/unit/test_knowledge_suites.py ties it to the file +# 138_knowledge_suite_required.sql added the requirement: a build below it accepts a +# proposal without reading a suite, so no suite is required while one serves. +REQUIRED_MIGRATION = 138 # tests/unit/test_proposal_requirement.py ties it to the file +REQUIREMENT_EVENT = "knowledge.suites.requirement" async def handle_knowledge_suites_publish( @@ -72,9 +88,15 @@ async def handle_knowledge_suites_publish( prefixes = suites.selection(input.memory_key_prefixes) cases = [case.model_dump() for case in input.cases] suites.check_document(input.expected_revision, keys, prefixes, cases) - if not await machines.fleet_at(get_client(), SUITES_MIGRATION): + # A build below the requirement's migration accepts a proposal without its checks. + gate, serves = ( + (REQUIRED_MIGRATION, "checks a required suite before an accept") + if input.required + else (SUITES_MIGRATION, "serves regression suites") + ) + if not await machines.fleet_at(get_client(), gate): raise OverloadedError( - "not every replica serves regression suites yet; retry once the rollout is done", + f"not every replica {serves} yet; retry once the rollout is done", retry_after_s=30, ) name = "knowledge-suites:" + json.dumps([input.org, input.namespace]) @@ -95,15 +117,29 @@ async def handle_knowledge_suites_publish( cases = suites.with_stored_origins(cases, head_cases, drafts) suites.check_origin_namespaces(cases) document = suites.canonical(cases) - if head is not None and (keys, prefixes, document) == ( + was = bool(head["required"]) if head else False + required = was if input.required is None else input.required + if head is not None and (keys, prefixes, document, required) == ( list(head["memory_keys"]), list(head["memory_key_prefixes"]), head["cases"], + was, ): - return KnowledgeSuitesPublishOutput(written=False, revision=current) + return KnowledgeSuitesPublishOutput(written=False, revision=current, required=was) if input.expected_revision != current: - return KnowledgeSuitesPublishOutput(written=False, conflict=True, revision=current) + return KnowledgeSuitesPublishOutput( + written=False, conflict=True, revision=current, required=was + ) _check_namespace(input.suite, heads, keys, prefixes) + change = suites.requirement_change( + was, + required, + (head["memory_keys"] if head else (), keys), + (head["memory_key_prefixes"] if head else (), prefixes), + ([c["case_id"] for c in head_cases], [c["case_id"] for c in cases]), + ) + if change is not None: + await _record_requirement(input, current, change) await repo.insert_row( { "org": input.org, @@ -115,11 +151,39 @@ async def handle_knowledge_suites_publish( "case_ids": [case["case_id"] for case in cases], "case_kinds": [case["kind"] for case in cases], "cases": document, + "required": int(required), "written_by": writer_actor(), "written_at": naive_utc_now(), } ) - return KnowledgeSuitesPublishOutput(written=True, revision=current + 1) + return KnowledgeSuitesPublishOutput(written=True, revision=current + 1, required=required) + + +async def _record_requirement( + input: KnowledgeSuitesPublishInput, current: int, change: dict[str, Any] +) -> None: + """The audit row of a publish that turns the requirement on or off, or takes a key, a + prefix or a case out of a required suite. Written under the claim, before the + revision, and waited for: a requirement is never lowered without its record.""" + try: + await audit.emit_strict( + REQUIREMENT_EVENT, + org=input.org, + namespace=input.namespace, + actor=writer_actor() or "-", + subject={ + "suite": input.suite, + "revision_before": current, + "revision": current + 1, + **change, + }, + ) + except Exception as e: # a requirement must not change without its record + raise BackendUnavailableError( + "the change to the suite's requirement could not be recorded; nothing was " + "published, retry", + operation="knowledge.suites.publish", + ) from e async def _taken_drafts( @@ -202,6 +266,7 @@ async def handle_knowledge_suites_get(input: KnowledgeSuitesGetInput) -> Knowled ) for draft, case in zip(pending, drafted, strict=True) ], + required=bool(row["required"]), ) @@ -241,6 +306,7 @@ async def handle_knowledge_suites_list( written_by=str(r["written_by"]), written_at=r["written_at"], pending_drafts=pending.get(str(r["suite"]), 0), + required=bool(r["required"]), ) for r in rows ] diff --git a/server/knowledge/domain/suites.py b/server/knowledge/domain/suites.py index b510e3ef8f..4b22acaf31 100644 --- a/server/knowledge/domain/suites.py +++ b/server/knowledge/domain/suites.py @@ -37,6 +37,32 @@ def selection(values: Iterable[str]) -> list[str]: return sorted(set(values)) +def requirement_change( + was: bool, + required: bool, + keys: tuple[Sequence[str], Sequence[str]], + prefixes: tuple[Sequence[str], Sequence[str]], + case_ids: tuple[Sequence[str], Sequence[str]], +) -> dict[str, Any] | None: + """What a publish records about its suite's requirement, None when it records + nothing. `was` and `required` are the requirement before and after; each of `keys`, + `prefixes` and `case_ids` is the current revision's list and the next one's. A record + is due when the requirement changes, and when a required suite loses a key, a prefix + or a case: each lets through a proposal the suite held. It names the keys and the + prefixes and counts the cases: a case id can say what its case checks, and every + reader of the namespace reads the audit log.""" + gone = [sorted(set(before) - set(after)) for before, after in (keys, prefixes, case_ids)] + if required == was and not (was and any(gone)): + return None + return { + "required_before": was, + "required": required, + "keys_removed": gone[0], + "prefixes_removed": gone[1], + "cases_removed": len(gone[2]), + } + + def check_case(case: Case, label: str) -> None: """Refuse a case no revision may hold, naming it by `label` and the field: the rules between a case's kind and its fields, the same for a published case and a draft.""" diff --git a/server/knowledge/store/suites.py b/server/knowledge/store/suites.py index 974f4f9c95..13ac6ade5b 100644 --- a/server/knowledge/store/suites.py +++ b/server/knowledge/store/suites.py @@ -6,7 +6,13 @@ as a tuple, from the row of the highest revision, so no read mixes two rows. Only `head` selects `cases`, the column that holds case text; `heads` reads no text and no case id, `selections` reads what each suite covers and nothing else, and -`heads_with_ids` adds the ids for the results of a suite's cases.""" +`heads_with_ids` adds the ids for the results of a suite's cases. + +Every read answers `required`, the requirement in force at the revision it reads: the +newest value a revision at or below it states +(schemas/migrations/138_knowledge_suite_required.sql). A revision written by a build +without the column states none (-1) and leaves the requirement as it was; a suite no +revision states one for is not required.""" from __future__ import annotations @@ -19,14 +25,17 @@ _SCOPE = "org = {org:String} AND namespace = {ns:String}" -def _head_select(columns: tuple[str, ...], where: str) -> str: - """Each suite's highest revision under `where`, with `columns` of that row.""" +def _head_select(columns: tuple[str, ...], where: str, having: str = "") -> str: + """Each suite's highest revision under `where`, with `columns` of that row and the + requirement in force at it (`required`, 0 or 1). `having` keeps the suites whose + highest revision under `where` it admits.""" taken = ", ".join(f"head.{i} AS {name}" for i, name in enumerate(columns, 1)) return ( - f"SELECT suite, head_revision AS revision, {taken} FROM (" + f"SELECT suite, head_revision AS revision, required, {taken} FROM (" f"SELECT suite, max(revision) AS head_revision, " - f"argMax(({', '.join(columns)}), revision) AS head " - f"FROM loom.knowledge_suites WHERE {where} GROUP BY suite)" + f"argMax(({', '.join(columns)}), revision) AS head, " + f"argMaxIf(required, revision, required >= 0) AS required " + f"FROM loom.knowledge_suites WHERE {where} GROUP BY suite{having})" ) @@ -55,7 +64,8 @@ async def selections( org: str, namespace: str, *, ch: _CHClient | None = None ) -> list[dict[str, Any]]: """The current revision of every suite of the namespace, by name, with the memory - keys and key prefixes it covers: what says which suite covers a key.""" + keys and key prefixes it covers and whether it is required: what says which suite + covers a key.""" ch = ch or _default_client() rows: list[dict[str, Any]] = await ch.query_all( _head_select(("memory_keys", "memory_key_prefixes"), _SCOPE) @@ -91,10 +101,13 @@ async def head( ch = ch or _default_client() where = _SCOPE + " AND suite = {suite:String}" params: dict[str, Any] = {"org": org, "ns": namespace, "suite": suite} + having = "" if revision: - where += " AND revision = {rev:UInt32}" + # Every revision up to the named one: an earlier one may state its requirement. + where += " AND revision <= {rev:UInt32}" + having = " HAVING head_revision = {rev:UInt32}" params["rev"] = revision row: dict[str, Any] | None = await ch.query_one( - _head_select((*_HEAD_COLUMNS, "cases"), where), params=params + _head_select((*_HEAD_COLUMNS, "cases"), where, having), params=params ) return row diff --git a/server/memory/api/models_proposals.py b/server/memory/api/models_proposals.py index 7d92bfc39a..70cc42c100 100644 --- a/server/memory/api/models_proposals.py +++ b/server/memory/api/models_proposals.py @@ -10,7 +10,8 @@ that covers its key (`checks`), and for text a copy rule's run wrote the namespace and the rule it came from (`copied_from`, `copy_rule`). `memory.proposal_decide` requires an administrator; acceptance requires an authenticated human independent -of the proposer. An automatic policy may reject, but cannot accept. +of the proposer, and satisfied checks where the suite that covers the key is required. +An automatic policy may reject, but cannot accept. """ from __future__ import annotations @@ -51,8 +52,8 @@ class MemoryProposalsInput(BaseModel): class ProposalAdviceReason(BaseModel): # What holds for the proposal: `policy_ready`, `policy_reject`, `contradicts_fact`, - # `harm_reported`, `usage_unread`, `sensitive`, `policy_unmet`, `untested` or `stale`. - # A client shows a code it does not know by its title. + # `harm_reported`, `usage_unread`, `sensitive`, `checks_required`, `policy_unmet`, + # `untested` or `stale`. A client shows a code it does not know by its title. code: str # The words for it, at most 30 characters. title: str @@ -70,6 +71,9 @@ class ProposalChecks(BaseModel): passed: int failed: int unavailable: int + # True when the suite is required: `memory.proposal_decide` then accepts the proposal + # only in the state `satisfied`. + required: bool = False class MemoryProposal(BaseModel): @@ -104,8 +108,9 @@ class MemoryProposal(BaseModel): # A contradiction recorded on trial (surfaced when accepted). conflict_with: list[str] = Field(default_factory=list) # `ready`, with `accept` emptied by a recorded conflict, a harm report, unread usage - # counters or a `high` row; `reject` only at the policy's fail limit. Advice, not a - # decision: it changes nothing `memory.proposal_decide` allows. + # counters, a `high` row or required checks that are not satisfied; `reject` only at + # the policy's fail limit. Advice, not a decision: it changes nothing + # `memory.proposal_decide` allows. advice: Literal["", "accept", "reject"] = "" # Why, in a fixed order: what decides, what blocks an acceptance, what informs. Never # empty on a listed proposal. @@ -163,8 +168,10 @@ class MemoryProposalDecision(BaseModel): # The same as a word: "" when decided, else `not_found`, `not_proposed`, # `hash_required`, `changed` (the hash names no pending row of the key), `ambiguous` # (several pending rows match), `not_independent` (the reviewer proposed it), - # `proposer_unknown` or `value_refused` (an earlier deletion refuses the text, which - # no decision writes). A client shows a code it does not know by `reason`. + # `proposer_unknown`, `value_refused` (an earlier deletion refuses the text, which + # no decision writes) or `checks_required` (the suite that covers the key is required + # and its checks are not satisfied for this content). A client shows a code it does + # not know by `reason`. code: str = "" # The row decided or judged; "" when the key named none. memory_id: str = "" diff --git a/server/memory/app/proposals.py b/server/memory/app/proposals.py index f434979372..3186f117e7 100644 --- a/server/memory/app/proposals.py +++ b/server/memory/app/proposals.py @@ -14,6 +14,10 @@ at `reject_after_fails` fails (0 = never). Pass thresholds mark a proposal ready for review. A decision writes a full version and mirrors its status onto embeddings. +Where the regression suite that covers a proposal's key is required, an acceptance +also needs the suite's checks satisfied for the exact content accepted, at the suite's +current revision (`_required_checks`). Satisfied checks accept nothing: every other +refusal still applies. """ from __future__ import annotations @@ -26,10 +30,13 @@ from fastapi import HTTPException +from server.core.ch import sequential_reads from server.core.errors import ValidationError +from server.core.hashing import sha256_value from server.core.repo_base import query_all_sliced from server.identity.app.reviewers import NotAReviewer, independent, reviewer_subjects from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters, scope_and +from server.knowledge.app import suite_checks from server.memory.app import webhooks from server.memory.domain import proposal_triage as triage from server.memory.domain.proposal_policy import ProposalPolicy, parse_policy @@ -158,10 +165,39 @@ class DecideResult: memory_id: str = "" # the row decided or judged ('' when none) -def _undecided(key: str, code: str, row: Any = None) -> DecideResult: - """`key` left pending under `code`; `row` is the row that was judged, when one was.""" +def _undecided( + key: str, code: str, row: Any = None, checks: suite_checks.Checks | None = None +) -> DecideResult: + """`key` left pending under `code`; `row` is the row that was judged, when one was, + and `checks` the checks of its content, which word `checks_required`.""" memory_id = "" if row is None else str(row.memory_id) - return DecideResult(key, False, PROPOSED, triage.REASONS[code], code, memory_id) + if code == triage.CHECKS_REQUIRED and checks is not None: + reason = triage.checks_reason( + checks.suite, checks.revision, checks.state, checks.failed, checks.unavailable + ) + else: + reason = triage.REASONS[code] + return DecideResult(key, False, PROPOSED, reason, code, memory_id) + + +async def _required_checks( + org: str, namespace: str, picked: dict[str, Any], decision: Decision, *, ch: Any +) -> dict[str, suite_checks.Checks]: + """The suite checks of each picked row's content, by key, for an acceptance: the + state of the hash an acceptance binds, under the suite that covers the key. Empty for + a rejection, which reads no suite. Both reads are sequentially consistent, so a + failing set or a revision another replica just wrote is seen; a read that fails + fails the call, and nothing is accepted on checks that were not read.""" + if decision != "accept": + return {} + hashes = { + key: sha256_value(row.value) + for key, row in picked.items() + if not isinstance(row, DecideResult) + } + with sequential_reads(): + read = await suite_checks.for_keys(org, namespace, list(hashes.items()), ch=ch) + return {key: checks for (key, _), checks in read.items()} async def decide( @@ -205,6 +241,7 @@ async def decide( else None ) picked = await _picked(org, namespace, wanted, sent, ch=ch) + checks = await _required_checks(org, namespace, picked, decision, ch=ch) to_write: list[dict[str, Any]] = [] decided: list[Any] = [] out: list[DecideResult] = [] @@ -213,9 +250,11 @@ async def decide( if isinstance(row, DecideResult): out.append(row) continue - code = _refusal(row, decision, reviewers, None if sent is None else sent.get(key, "")) + code = _refusal( + row, decision, reviewers, None if sent is None else sent.get(key, ""), checks.get(key) + ) if code: - out.append(_undecided(key, code, row)) + out.append(_undecided(key, code, row, checks.get(key))) continue to_write.append(_decided_version(row, decision, actor, reason)) decided.append(row) @@ -233,7 +272,7 @@ async def decide( # non-active flips, and an accepted proposal's mirror still says proposed. await memory_repo.mirror_status_to_embeddings(to_write, ch=ch) await _audit_decisions( - org, namespace, decided, decision, actor=actor, reason=reason, policy=policy + org, namespace, decided, decision, checks, actor=actor, reason=reason, policy=policy ) if decision == "accept": await _surface_conflicts(org, decided) @@ -357,14 +396,25 @@ async def _not_pending(org: str, namespace: str, keys: list[str], *, ch: Any) -> return out -def _refusal(row: Any, decision: Decision, reviewers: set[str], sent: str | None) -> str: +def _refusal( + row: Any, + decision: Decision, + reviewers: set[str], + sent: str | None, + checks: suite_checks.Checks | None = None, +) -> str: """The code that leaves the picked `row` pending, '' when the decision stands. `sent` - is the hash the reviewer read; None for a decision that names no text. + is the hash the reviewer read; None for a decision that names no text. `checks` is + the state of the row's content under the suite that covers its key, None when no + suite does. An acceptance binds the whole value. A rejection is bound by the stored hash, which the listing serves, or by the hash of the served value, which a full read serves: - the two differ for an object with a null field, which the JSON column drops.""" - from server.core.hashing import hash_text, served_content_sha256, sha256_value + the two differ for an object with a null field, which the JSON column drops. + + A required suite refuses last, after the reviewer and the hash: its checks hold an + acceptance the other rules allow and allow none they refuse.""" + from server.core.hashing import hash_text, served_content_sha256 from server.memory.domain.trust import is_valid_actor, subject_of if decision == "accept": @@ -373,8 +423,10 @@ def _refusal(row: Any, decision: Decision, reviewers: set[str], sent: str | None return triage.PROPOSER_UNKNOWN if not independent(reviewers, {subject_of(proposer)}): return triage.NOT_INDEPENDENT - bound = not row.value_truncated and sent == sha256_value(row.value) - return "" if bound else triage.CHANGED + if row.value_truncated or sent != sha256_value(row.value): + return triage.CHANGED + held = checks is not None and checks.required and checks.state != "satisfied" + return triage.CHECKS_REQUIRED if held else "" if sent is None or sent == hash_text(row.content_sha256): return "" bound = not row.value_truncated and sent == served_content_sha256(row.value) @@ -410,11 +462,15 @@ async def _audit_decisions( namespace: str, rows: list[Any], decision: Decision, + checks: dict[str, suite_checks.Checks], *, actor: str, reason: str, policy: ProposalPolicy | None, ) -> None: + """One audit row per decided row. `checks` holds the suite checks an acceptance read, + by key: the row of a key a suite covers records the suite, its revision and the + state the content was accepted in.""" from server.observability import audit as _audit # A caller's reason is kept on a rejected row (`rejection_reason`), which erasure @@ -437,6 +493,11 @@ async def _audit_decisions( "memory_id": str(row.memory_id), "content_sha256": str(getattr(row, "content_sha256", "") or ""), **why, + **( + {"checks": {"suite": c.suite, "revision": c.revision, "state": c.state}} + if (c := checks.get(str(row.memory_key))) is not None + else {} + ), } for row in rows ], diff --git a/server/memory/app/proposals_ops.py b/server/memory/app/proposals_ops.py index 9df3452480..2bc16a12f1 100644 --- a/server/memory/app/proposals_ops.py +++ b/server/memory/app/proposals_ops.py @@ -179,6 +179,7 @@ def _advise(p: MemoryProposal, *, usage_read: bool, now: datetime) -> None: usage_read=usage_read, created_at=parse_iso_dt(p.created_at), now=now, + checks_held=(p.checks is not None and p.checks.required and p.checks.state != "satisfied"), ) p.advice_reasons = [ProposalAdviceReason(code=r.code, title=r.title) for r in reasons] diff --git a/server/memory/domain/proposal_advice.py b/server/memory/domain/proposal_advice.py index c4ae229152..3dc140a60e 100644 --- a/server/memory/domain/proposal_advice.py +++ b/server/memory/domain/proposal_advice.py @@ -1,8 +1,9 @@ """The advice on one pending proposal, and the reasons for it. The advice is what the policy's thresholds say (`ready`), with `accept` emptied by a -blocker: a recorded conflict, a harm report, usage counters that could not be read, or a -`high` row, whose text a listing does not serve. A rejection has one source, the policy's +blocker: a recorded conflict, a harm report, usage counters that could not be read, a +`high` row, whose text a listing does not serve, or required suite checks that are not +satisfied, which `memory.proposal_decide` refuses. A rejection has one source, the policy's fail limit, and no blocker removes it. Every row carries at least one reason, in one fixed order: what decides, what blocks an acceptance, what informs. @@ -28,11 +29,14 @@ "harm_reported": "A harm report is recorded", "usage_unread": "Usage counters unread", "sensitive": "Marked sensitive", + "checks_required": "Required checks not satisfied", "policy_unmet": "Evidence thresholds not met", "untested": "No graded run relied on it", "stale": f"Waiting {STALE_AFTER_DAYS} days, never used", } -_BLOCKERS = frozenset({"contradicts_fact", "harm_reported", "usage_unread", "sensitive"}) +_BLOCKERS = frozenset( + {"contradicts_fact", "harm_reported", "usage_unread", "sensitive", "checks_required"} +) class Reason(NamedTuple): @@ -52,11 +56,13 @@ def advise( usage_read: bool, created_at: datetime | None, now: datetime, + checks_held: bool = False, ) -> tuple[Advice, list[Reason]]: """The advice and its reasons for a proposal with these served fields. `usage_read` is false when the usage counters could not be read: their zeros then say nothing, so - the row is neither advised `accept` nor called unused. `created_at` and `now` are - naive UTC.""" + the row is neither advised `accept` nor called unused. `checks_held` is true when the + row's `checks` say the suite is required and the state is not `satisfied`. + `created_at` and `now` are naive UTC.""" graded = graded_passes + graded_fails > 0 waited = created_at is not None and now - created_at >= timedelta(days=STALE_AFTER_DAYS) holds = { @@ -66,6 +72,7 @@ def advise( "harm_reported": harm_count > 0, "usage_unread": not usage_read, "sensitive": sensitivity == "high", + "checks_required": checks_held, "policy_unmet": graded and not ready, "untested": not graded, "stale": waited and usage_read and used_count == 0, diff --git a/server/memory/domain/proposal_triage.py b/server/memory/domain/proposal_triage.py index 5ef47b4a6f..db0a15dbf8 100644 --- a/server/memory/domain/proposal_triage.py +++ b/server/memory/domain/proposal_triage.py @@ -12,7 +12,9 @@ from typing import Any # The closed set a result's `code` is drawn from: "" for a decided key, else why the key -# is left as it is. `not_proposed` words its sentence with the status the row holds. +# is left as it is. `not_proposed` words its sentence with the status the row holds, and +# `checks_required` with the suite and what its checks say (`checks_reason`). +CHECKS_REQUIRED = "checks_required" NOT_FOUND = "not_found" NOT_PROPOSED = "not_proposed" HASH_REQUIRED = "hash_required" @@ -37,6 +39,27 @@ Head = Mapping[str, Any] +def checks_reason(suite: str, revision: int, state: str, failed: int, unavailable: int) -> str: + """The sentence of `checks_required`: the required suite that covers the key, at its + current revision, and what its checks say of the proposed content. `state` is the + content's state under the suite, not `satisfied`; `failed` and `unavailable` count + the deciding set's cases. A set with a case that could not run and no set at all both + read `missing`, and the sentence tells them apart.""" + + def cases(n: int) -> str: + return f"{n} case" if n == 1 else f"{n} cases" + + if state == "failed": + what = f"{cases(failed)} failed for this content" + elif state == "outdated": + what = "its results are for other content or an earlier revision" + elif unavailable: + what = f"{cases(unavailable)} could not run for this content" + else: + what = "no results for this content" + return f"suite {suite} (revision {revision}) is required: {what}" + + def pick(pending: Sequence[Head], sent: str, bound: bool) -> tuple[Head | None, str]: """The pending row of one key that a decision is made on, or the code that leaves the key undecided. `pending` is every pending head of the key with its stored diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 7f2e584f88..bc433e1f14 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -941,7 +941,8 @@ def revision_policy(update: str) -> str: "`advice` is `ready` with `accept` emptied by a blocker, and " "`advice_reasons` says why: advice, not a decision. " "Each proposal lists the state of its regression suite's checks " - "(`checks`), when a suite covers its key. " + "(`checks`), when a suite covers its key; `checks.required` = an " + "accept needs them satisfied. " "`actor` is the proposer; `memory_keys` lists named keys only; " "`order` is `newest` (default) or `oldest`, the longest waiting first; " "`count_only` only counts." @@ -976,7 +977,9 @@ def revision_policy(update: str) -> str: "per key. `approved_sha256` maps each key to the `content_sha256` of " "the text that was read (memory.get_by_id to accept; that or " "memory.proposals to reject); a key without it stays undecided. Only " - "a human administrator who did not propose a row accepts it. Each " + "a human administrator who did not propose a row accepts it, and a " + "required regression suite refuses an accept whose checks are not " + "satisfied for that content. Each " "result has a `code` and the `memory_id` judged; each decision is a " "new version with an audit row." ), diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 6ab1d02024..11f7d92426 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -62,7 +62,6 @@ 05d68e77b952 SELECT m.memory_id, m.memory_key, m.value, m.pinned, m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, cosineDistance(e.embedding, {emb:Array(Float32)}) AS dist FROM loom.memory m FINAL JOIN loo 05db2cfdc678 DELETE FROM loom.knowledge_sources WHERE namespace = {ns:String} AND org = {org:String} AND owner_subject = {owner:String} AND (source_kind = ? OR kind = ? OR credential_mode = ?) AND toUnixTimestamp( 05eb1769fceb SELECT * FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model != {model:String} AND tombstoned_at IS NULL -06155e481571 SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS cases FROM (SELECT suite, max 06360b1e4608 SELECT neighbor, sum(w) AS weight, argMax(seed, w) AS via_seed FROM ( SELECT entity_b AS neighbor, co_occur AS w, entity_a AS seed FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns_ 065d1ae244d0 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 0663f6f57816 SELECT ? AS kind, value, total AS count FROM ( SELECT arrayJoin(tags) AS value, count() AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL A @@ -72,7 +71,6 @@ 069935ea2b36 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 06ad1b41aedd SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 06b297a2e8a7 SELECT src_path, test_path FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND method = {method:String} AND tombstoned_at IS NULL -06f330058e43 SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at FROM (SELECT suite, max(revision) AS hea 06ff2b38df31 SELECT count() AS n FROM loom.agent_runs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND grade != ? AND started_at >= now() - INTERVAL {win:UInt32} SECOND 07417011df11 SELECT category_id, count() AS item_count FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL GROUP BY category_id 0775de50682c SELECT max(updated_at) AS updated_at FROM loom.blacklist_version @@ -91,7 +89,6 @@ 08f67c0b9944 SELECT number, is_pr, state, state_reason, author, title, labels, opened_at, closed_at, merged_at, updated_at, head_sha, base_sha, files FROM loom.code_gh_items FINAL WHERE org = {org:String} AND name 091a5b6e28bb SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))} 092355e7be59 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this -0923f0605c0b SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS cases FROM (SELECT suite, max 092b4e7347ba ALTER TABLE loom.query_nodes DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 092fea064f1d SELECT org, namespace, source_uri, doc_id, title, description, content, tags, metadata, version, superseded_at, ingested_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, ori 0934ab49d07b SELECT toString(memory_id) AS id, uniqExact(version) AS versions FROM loom.memory_versions WHERE org = {org:String} AND namespace = {ns:String} AND memory_id IN {ids:Array(UUID)} GROUP BY memory_id @@ -297,7 +294,6 @@ 22612cf3a394 SELECT namespace, source_uri, public_namespace, public_uri FROM (SELECT namespace, source_uri, indexOf({bindings:Array(Tuple(String, String))}, (namespace, right(source_uri, ?))) AS binding, arrayElem 2261d5bd6945 SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND namespace = {ns:String} AND content_sha256 IN {hashes:Array(String)} AND source_uri != {ex:String} AND doc_superseded_at IS NULL AND ( 226e4e3d52e6 SELECT pr_number, title, merged_at FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND merged_at >= {since:DateTime} AND (arrayExists(f - -227d4ade6c4d SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS case_ids FROM (SELECT suite, 22bb5ae78bee SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 22d5f4746f1f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this 22e0a45e948a SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, concat(?, toString(chunk_index), ?, content_sha256) AS memory_ @@ -538,6 +534,7 @@ 39db945a8f03 ALTER TABLE loom.conversation_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {era 39f9fbc2c519 SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND user_id = {uid:String} 3a315e2ef1be ALTER TABLE loom.entity_canonical_map UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} +3a3682c8da21 SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS cases FROM (SELECT 3a6169b72b54 SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND user_id = {uid:String} 3a8471ec9ffe SELECT pr_number, any(title) AS title, any(author) AS author, min(merged_at) AS merged_at, max(opened_at) AS opened_at, any(files) AS files, any(linked_issues) AS linked_issues FROM loom.code_pr_histo 3a88608e1703 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? @@ -625,7 +622,6 @@ 425e85d1e2ab SELECT org, namespace, agent, user_id, session_id, run_id, goal, user_request, expected_outcome, environment, model, consumer, status, started_at, completed_at, duration_ms, final_response, confidence 426ca1677676 SELECT DISTINCT candidate_id FROM loom.learnings_queue WHERE org = {org:String} AND source_kind = ? AND proposed_value != ? AND candidate_id NOT IN (SELECT candidate_id FROM loom.learnings_supporters 42714bf1b036 SELECT scope_path AS path, summary, pagerank, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embeddin -428310584d02 SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS case_ids FROM (SELECT suite, 429f25bee1e2 SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND namespace = {ns:String} AND ? 42abfe52b2c7 ALTER TABLE loom.namespace_guides DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 42cb110e14f4 DELETE FROM loom.memory_chunks WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? @@ -707,6 +703,7 @@ 4a4a4fc0989b ALTER TABLE loom.knowledge_ingest_cancels DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s 4a536b32504b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 4aeabb5d4edf SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? +4b1fc95c4fbf -- 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 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 @@ -737,7 +734,6 @@ 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 = { @@ -829,6 +825,7 @@ 57b88b7f8883 SELECT thread_id, uniqExact(msg_id, cityHash64(content)) AS n FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id IN {tids:Array(String)} AND tombstoned_at IS NU 57b9aebb5d45 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_muta 57bdb4ada632 SELECT authority, epoch, deployment_id FROM loom.storage_authority FINAL SETTINGS select_sequential_consistency = ? +57bf3c3835de SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS cases FROM (SELECT 57e0686ba555 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {era 57fc18cfd1a4 SELECT pr_number, any(title) AS title, any(files) AS files, any(author) AS author, any(merge_commit_sha) AS merge_sha, min(merged_at) AS merged_at FROM loom.code_pr_history FINAL WHERE org = {org:Stri 5805dc626bcc SELECT countIf(NOT startsWith(path, ?)) AS source_files, countIf(NOT startsWith(path, ?) AND path NOT IN ( SELECT src_path FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:St @@ -1369,6 +1366,7 @@ 8d71b43b9e4c SELECT arrayConcat((SELECT groupUniqArray(memory_key) FROM loom.memory WHERE org = {org:String} AND user_id = {uid:String}), (SELECT groupUniqArray(memory_key) FROM (SELECT namespace, agent, user_id, 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 ? +8d98c3c3ba94 SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS case_ids FROM (SELE 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 = ? @@ -1386,7 +1384,6 @@ 8ee4f33d0c2f SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} 8ee5e12ce3f8 SELECT memory_type, retention_days, dedup_threshold, hot_quota, conflict_policy FROM loom.namespace_types FINAL WHERE org = {org:String} AND namespace = {ns:String} ORDER BY memory_type 8f11758986c7 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create -8f2f71955b54 SELECT suite, head_revision AS revision, head.? AS memory_keys, head.? AS memory_key_prefixes FROM (SELECT suite, max(revision) AS head_revision, argMax((memory_keys, memory_key_prefixes), revision) A 8f5abdba34be 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 = { 8fa56eef0912 SELECT count() AS n FROM loom.task_events WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 8fabc8412cfc SELECT subject, role, granted_by FROM loom.namespace_grants FINAL WHERE org = {org:String} AND namespace = {ns:String} AND revoked_at IS NULL AND status = ? @@ -1727,6 +1724,7 @@ b17835f57d67 ALTER TABLE loom.working_memory DELETE WHERE (org = {org:String} AN b1931bf6e5a4 SELECT DISTINCT owner_email, org FROM loom.namespaces FINAL WHERE contact_email = {email:String} AND active = ? AND owner_email != ? AND (password_hash = ? OR (org, namespace) IN ( SELECT org, namespa b19a91de5abc SELECT scope_path AS path, summary, pagerank, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embeddin b1ad3749748d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +b214988c8057 SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at, head.? AS case_ids FROM (SELE b21e9b73a809 SELECT count() AS n FROM loom.entity_degree WHERE org = {org:String} AND namespace IN {ns:Array(String)} b2233addfc9d ALTER TABLE loom.memory_belief_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b23268ea2de0 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { @@ -2206,6 +2204,7 @@ ddc00b268be8 SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sh dde8208a93a2 SELECT count() AS n FROM loom.entity_triple_memories WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? de2873bc124f SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc de291d5c538a SELECT memory_key, toString(memory_id) AS mid, version, content_sha256, agent, actor, memory_type, sensitivity, tags, toString(created_at) AS created, conflict_with, cross_promoted_from_namespace AS c +de4bf12818ee SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes FROM (SELECT suite, max(revision) AS head_revision, argMax((memory_keys, memory_key_prefixes), r de6e3a798fff DELETE FROM loom.entity_vectors WHERE (org = {org:String} AND (user_id = {uid:String} OR (namespace, memory_key) IN {keys:Array(Tuple(String, String))})) AND ({erasure_mutation_tag:String} = {erasure_ de7bbe4a4ec2 ALTER TABLE loom.memory_categories UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = { de842ab13a32 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 @@ -2496,6 +2495,7 @@ fbbbcced58d9 SELECT path, splitByChar(?, arrayElement(splitByChar(?, path), ?))[ fbcf516582ea SELECT source_uri, version, content_sha256, user_id, superseded_at IS NOT NULL AS deleted FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND source_uri IN {uris:Array(S fbd02f260158 SELECT ts, event_type, org, namespace, actor, subject, request_id, row_hash FROM loom.audit_log WHERE request_id = {rid:String} ORDER BY ts ASC LIMIT {limit:UInt32} fbd1ef24012c SELECT count() AS n FROM loom.tasks WHERE org = {org:String} AND namespace IN {ns:Array(String)} +fbd21f04b46a SELECT suite, head_revision AS revision, required, head.? AS memory_keys, head.? AS memory_key_prefixes, head.? AS case_kinds, head.? AS written_by, head.? AS written_at FROM (SELECT suite, max(revisi fbd318d47fef SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows fc00cc1815db SELECT namespace, countIf(status=?) AS pending, countIf(status=?) AS promoted, countIf(status=?) AS rejected, if(countIf(status IN (?,?)) > ?, countIf(status=?) / countIf(status IN (?,?)), ?) AS appro fc0e3b7e1c36 SELECT agent, count() AS rows, count() OVER () AS total FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {scope_uid:String} GROUP BY diff --git a/tests/fixtures/proposal_triage_set.json b/tests/fixtures/proposal_triage_set.json index 1f861c4d3c..11a985139b 100644 --- a/tests/fixtures/proposal_triage_set.json +++ b/tests/fixtures/proposal_triage_set.json @@ -1,7 +1,7 @@ { "about": "A labelled set of pending proposals. Each case holds one key, the writes that put it in the queue, the decision a script sends for it and the code that decision answers. The set is decided over HTTP with no model. It counts calls and undecided keys; it does not measure a reviewer's time.", "fields": { - "seed": "writes made before the plan is read: a proposal of the case's key (`propose`), a fact under another key (`set`) or a deletion (`delete`), by the writer as `release-bot` unless `as` and `agent` say otherwise", + "seed": "writes made before the plan is read: a proposal of the case's key (`propose`), a fact under another key (`set`), a deletion (`delete`) or a required regression suite that covers the case's key (`require`, the suite's name), by the writer as `release-bot` unless `as` and `agent` say otherwise", "after_plan": "writes made between the plan and the decision", "by": "who sends the decision", "hash": "the hash the decision sends: `read` is the full read of the listed row, `listed` the hash the list served, {`of`: key} the listed hash of another key", @@ -183,6 +183,20 @@ "code": "proposer_unknown", "replayed": "proposer_unknown", "pending": 1 + }, + { + "key": "refund_window", + "about": "An acceptance of a key a required suite covers, with no results recorded for its text.", + "seed": [ + { "require": "refunds", "as": "triage_bot" }, + { "propose": "Refunds are accepted for 30 days after delivery" } + ], + "decision": "accept", + "by": "reviewer", + "hash": "read", + "code": "checks_required", + "replayed": "checks_required", + "pending": 1 } ] } diff --git a/tests/integration/test_proposal_checks_requirement.py b/tests/integration/test_proposal_checks_requirement.py new file mode 100644 index 0000000000..906a9217b0 --- /dev/null +++ b/tests/integration/test_proposal_checks_requirement.py @@ -0,0 +1,472 @@ +"""Where a regression suite is required, `memory.proposal_decide` accepts a proposal on a +key the suite covers only with satisfied checks for the exact content proposed, at the +suite's current revision, against a running server. Satisfied checks accept nothing: a +service account, the proposer and a stale hash are still refused. + +Every call carries a token: a writer bot proposes, a runner bot with `admin` publishes +the suite and records results, and a human administrator accepts. The runner is +scripted: a table from case id to its outcome. No model is called. + +Skips without LOOM_BASE_URL (tests/integration/conftest.py). The server may enforce auth +or not, and run under either storage authority. +""" + +from __future__ import annotations + +import json +import os +from collections.abc import Iterator +from typing import Any + +import httpx +import pytest + +from server.auth.jwt import mint_token +from tests.integration._eventually import wait_until +from tests.integration._resources import unique_org + +NS = "finance" +SUITE = "finance" +PREFIX = "metric/net_revenue/" +KEY = PREFIX + "definition" +TEXT = "Net revenue is gross revenue minus refunds and chargebacks." +CASES = [ + { + "case_id": "refunds-subtracted", + "kind": "expect", + "prompt": "Does net revenue include refunded orders?", + "expectation": "No: refunds are subtracted from gross revenue.", + }, + { + "case_id": "gross-is-not-net", + "kind": "must_not_state", + "prompt": "Is net revenue the same as gross revenue?", + "withdrawn": "Net revenue equals gross revenue.", + }, +] +CASE_IDS = [case["case_id"] for case in CASES] +CONFIG = {"model": "scripted", "grader": "table"} +PEOPLE: dict[str, tuple[str, bool, list[str]]] = { + # name: subject, human, roles + "writer": ("release-bot", False, ["writer"]), + "runner": ("suite-runner", False, ["admin"]), + "reviewer": ("reviewer", True, ["admin"]), + "author": ("author", True, ["admin", "writer"]), +} + + +def _required(revision: int, what: str) -> str: + return f"suite {SUITE} (revision {revision}) is required: {what}" + + +class _Queue: + """A fresh org whose namespace holds the suite, with a token for each person.""" + + def __init__(self, http: httpx.Client) -> None: + self.http = http + self.org = unique_org("required-checks") + self.scope = {"org": self.org, "namespace": NS} + self.tokens = { + name: mint_token( + subject=subject, + org=self.org, + namespaces=[NS], + roles=roles, + ttl_seconds=600, + is_service_account=not human, + ) + for name, (subject, human, roles) in PEOPLE.items() + } + + def post(self, op: str, body: dict[str, Any], who: str) -> httpx.Response: + headers = {"Authorization": f"Bearer {self.tokens[who]}"} + return self.http.post(f"/v1/{op}", json={**self.scope, **body}, headers=headers) + + def call(self, op: str, body: dict[str, Any], who: str) -> dict[str, Any]: + r = self.post(op, body, who) + assert r.status_code == 200, f"{op}: {r.status_code} {r.text[:400]}" + answer: dict[str, Any] = r.json() + return answer + + def publish( + self, + *, + required: bool | None = None, + keys: tuple[str, ...] = (), + prefixes: tuple[str, ...] = (PREFIX,), + cases: list[dict[str, Any]] | None = None, + ) -> dict[str, Any]: + """Publish the suite's next revision on its current one; `required` None omits + the field.""" + head = self.call("knowledge.suites.get", {"suite": SUITE}, "runner") + body: dict[str, Any] = { + "suite": SUITE, + "expected_revision": head["revision"], + "memory_keys": list(keys), + "memory_key_prefixes": list(prefixes), + "cases": CASES if cases is None else cases, + } + if required is not None: + body["required"] = required + out = self.call("knowledge.suites.publish", body, "runner") + assert out["written"] is True, out + return out + + def propose(self, key: str = KEY, value: str = TEXT, who: str = "writer") -> str: + """Propose `value` under `key` and return the content hash the server served.""" + body = {"agent": "release-bot", "memory_key": key, "value": value, "proposed": True} + wrote = self.call("memory.set", body, who) + assert wrote["status"] == "proposed", wrote + return str(wrote["content_sha256"]) + + def record(self, sha: str, key: str = KEY, revision: int = 1, **candidate: str) -> None: + """The scripted runner: every case passes with the candidate unless `candidate` + names its outcome (a case id is passed with `_` for `-`).""" + sent = {name.replace("_", "-"): outcome for name, outcome in candidate.items()} + head = self.call("knowledge.suites.get", {"suite": SUITE, "revision": revision}, "runner") + outcomes = [ + {"case_id": c["case_id"], "candidate": sent.get(c["case_id"], "pass")} + for c in head["cases"] + ] + body = {"suite": SUITE, "revision": revision, "memory_key": key, "content_sha256": sha} + self.call( + "knowledge.suites.submit_results", + {**body, "outcomes": outcomes, "config": CONFIG}, + "runner", + ) + + def decide(self, hashes: dict[str, str], who: str = "reviewer") -> httpx.Response: + body = {"memory_keys": list(hashes), "decision": "accept", "approved_sha256": hashes} + return self.post("memory.proposal_decide", body, who) + + def accept(self, hashes: dict[str, str], who: str = "reviewer") -> dict[str, dict[str, Any]]: + """An accept of `hashes` (key to content hash) that answers: its results by key.""" + r = self.decide(hashes, who) + assert r.status_code == 200, r.text + results = r.json()["results"] + assert r.json()["decided"] == sum(result["decided"] for result in results) + return {result["memory_key"]: result for result in results} + + def refused(self, sha: str, why: str, key: str = KEY, who: str = "reviewer") -> None: + """An accept of `key` is refused as `checks_required` with the sentence `why`, + and the proposal stays pending.""" + result = self.accept({key: sha}, who)[key] + assert (result["decided"], result["code"], result["status"]) == ( + False, + "checks_required", + "proposed", + ), result + assert result["reason"] == why + + def results(self, sha: str, key: str = KEY) -> dict[str, Any]: + asked = {"memory_key": key, "content_sha256": sha} + return self.call("knowledge.suites.results", asked, "runner") + + def listed(self, want: int) -> dict[str, dict[str, Any]]: + """The pending proposals by key, once the list holds `want` of them: under the + Postgres authority a write reaches the list after it answers.""" + + def _rows() -> dict[str, dict[str, Any]] | None: + out = self.call("memory.proposals", {"limit": 500}, "reviewer") + assert "degraded" not in out, out["degraded"] + rows = {p["memory_key"]: p for p in out["proposals"]} + return rows if len(rows) == want else None + + return wait_until(_rows, max_wait=15, description=f"the list to hold {want} proposals") + + +@pytest.fixture +def queue(control_plane_url: str) -> Iterator[_Queue]: + with httpx.Client(base_url=control_plane_url, timeout=120) as http: + yield _Queue(http) + + +def test_blocked_until_both_cases_pass_on_one_content_and_an_independent_person_accepts( + queue: _Queue, +) -> None: + """Fails when the accept goes through while the candidate fixes one case and breaks + the other, or is refused once both pass on that content and an independent person + accepts.""" + published = queue.publish(required=True) + assert (published["revision"], published["required"]) == (1, True) + sha = queue.propose() + + # The candidate fixes the first case and breaks the second. + queue.record(sha, gross_is_not_net="fail") + queue.refused(sha, _required(1, "1 case failed for this content")) + assert queue.results(sha)["state"] == "failed" + + # Both pass on the same content: the checks are satisfied, and a person accepts. + queue.record(sha) + assert queue.results(sha)["state"] == "satisfied" + accepted = queue.accept({KEY: sha})[KEY] + assert (accepted["decided"], accepted["status"], accepted["code"]) == (True, "active", "") + served = queue.call("memory.get", {"agent": "release-bot", "memory_key": KEY}, "reviewer") + assert served["found"] and served["value"] == TEXT + + +def test_one_unavailable_case_leaves_the_proposal_unaccepted_with_no_failure( + queue: _Queue, +) -> None: + """Fails when a case that could not run lets the accept through, counts as a failed + case, or is listed as a regression.""" + queue.publish(required=True) + sha = queue.propose() + queue.record(sha, gross_is_not_net="unavailable") + queue.refused(sha, _required(1, "1 case could not run for this content")) + results = queue.results(sha) + assert (results["state"], results["passed"], results["failed"], results["unavailable"]) == ( + "missing", + 1, + 0, + 1, + ) + changes = {case["case_id"]: case["change"] for case in results["cases"]} + assert changes["gross-is-not-net"] == "unavailable" + assert "regressed" not in changes.values() + + +def test_the_rerun_then_waits_only_for_the_reviewer(queue: _Queue) -> None: + """Fails when the run with every case available does not satisfy the checks, or the + proposal is then held by anything but its review.""" + queue.publish(required=True) + sha = queue.propose() + queue.record(sha, gross_is_not_net="unavailable") + queue.refused(sha, _required(1, "1 case could not run for this content")) + + queue.record(sha) + row = queue.listed(1)[KEY] + assert (row["checks"]["state"], row["checks"]["required"]) == ("satisfied", True) + assert "checks_required" not in [reason["code"] for reason in row["advice_reasons"]] + accepted = queue.accept({KEY: sha})[KEY] + assert (accepted["decided"], accepted["status"]) == (True, "active") + + +def test_no_results_refuses_the_accept(queue: _Queue) -> None: + queue.publish(required=True) + sha = queue.propose() + queue.refused(sha, _required(1, "no results for this content")) + + +def test_an_edit_after_the_results_refuses_the_accept(queue: _Queue) -> None: + """Fails when results recorded for one text accept another text of the key.""" + queue.publish(required=True) + first = queue.propose() + queue.record(first) + assert queue.results(first)["state"] == "satisfied" + + edited = queue.propose(value="Net revenue is gross revenue minus refunds.") + assert edited != first + queue.refused(edited, _required(1, "its results are for other content or an earlier revision")) + # The hash of the text that was checked names no pending text any more. + stale = queue.accept({KEY: first})[KEY] + assert (stale["decided"], stale["code"]) == (False, "changed") + + +def test_a_new_suite_revision_after_the_results_refuses_the_accept(queue: _Queue) -> None: + """Fails when results for an earlier revision of the suite accept the proposal.""" + queue.publish(required=True) + sha = queue.propose() + queue.record(sha) + more = [*CASES, {"case_id": "card-number", "kind": "decline", "prompt": "Read me a card."}] + # The publish names no requirement: the suite keeps it. + published = queue.publish(cases=more) + assert (published["revision"], published["required"]) == (2, True) + queue.refused(sha, _required(2, "its results are for other content or an earlier revision")) + + queue.record(sha, revision=2) + assert queue.accept({KEY: sha})[KEY]["decided"] is True + + +def test_turning_required_on_outdates_recorded_results(queue: _Queue) -> None: + """Fails when results recorded before the suite was required satisfy it after: the + requirement is part of the revision. Fails too when a read of the suite, at its head, + at the revision before it or in the list, answers another requirement than that + revision's.""" + assert queue.publish()["required"] is False + sha = queue.propose() + queue.record(sha) + before = queue.results(sha) + assert (before["state"], before["required"], before["revision"]) == ("satisfied", False, 1) + + turned = queue.publish(required=True) + assert (turned["written"], turned["revision"], turned["required"]) == (True, 2, True) + after = queue.results(sha) + assert (after["state"], after["required"], after["revision"]) == ("outdated", True, 2) + queue.refused(sha, _required(2, "its results are for other content or an earlier revision")) + + head = queue.call("knowledge.suites.get", {"suite": SUITE}, "runner") + assert (head["revision"], head["required"]) == (2, True) + first = queue.call("knowledge.suites.get", {"suite": SUITE, "revision": 1}, "runner") + assert (first["revision"], first["required"]) == (1, False) + [listed] = queue.call("knowledge.suites.list", {}, "runner")["suites"] + assert (listed["suite"], listed["revision"], listed["required"]) == (SUITE, 2, True) + + +def test_a_service_account_and_the_proposer_cannot_accept_with_satisfied_checks( + queue: _Queue, +) -> None: + """Fails when satisfied checks let a service account, the proposer or a stale hash + accept.""" + queue.publish(required=True) + sha = queue.propose(who="author") + queue.record(sha) + assert queue.results(sha)["state"] == "satisfied" + + bot = queue.decide({KEY: sha}, "runner") + assert bot.status_code == 403, bot.text + own = queue.accept({KEY: sha}, "author")[KEY] + assert (own["decided"], own["code"]) == (False, "not_independent") + other = ("0" if sha[0] != "0" else "1") + sha[1:] + stale = queue.accept({KEY: other})[KEY] + assert (stale["decided"], stale["code"]) == (False, "changed") + assert queue.listed(1)[KEY]["checks"]["state"] == "satisfied" + + assert queue.accept({KEY: sha})[KEY]["decided"] is True + + +def test_an_accept_that_met_a_contradiction_still_lands_conflicted( + queue: _Queue, ch_client: Any +) -> None: + """Fails when satisfied checks land a proposal that recorded a contradiction on + trial as `active`.""" + if os.environ.get("LOOM_PG_DSN"): + pytest.skip("the conflict is recorded by a ClickHouse write the Postgres rows lack") + queue.publish(required=True) + fact = queue.call( + "memory.set", + {"agent": "release-bot", "memory_key": "fact/gross", "value": "Gross revenue is billed."}, + "writer", + ) + sha = queue.propose() + queue.record(sha) + # The conflict as the conflict mark writes it: the proposal's next version, still + # `proposed`, naming the contradicting fact. + ch_client.command( + """ + INSERT INTO loom.memory + SELECT * REPLACE (version + 1 AS version, [{peer:String}] AS conflict_with) + FROM loom.memory FINAL + WHERE org = {org:String} AND namespace = {ns:String} AND memory_key = {key:String} + """, + parameters={"org": queue.org, "ns": NS, "key": KEY, "peer": fact["memory_id"]}, + ) + accepted = queue.accept({KEY: sha})[KEY] + assert (accepted["decided"], accepted["status"]) == (True, "conflicted") + + +def test_turning_it_off_and_dropping_a_key_or_a_case_are_audited(queue: _Queue) -> None: + """Fails when a publish that turns the requirement off, or takes a key or a case out + of a required suite, leaves no `knowledge.suites.requirement` row, or a row names a + case.""" + other = "metric/gross_revenue/definition" + queue.publish(required=True, keys=(other,)) + queue.publish(keys=()) + queue.publish(keys=(), cases=CASES[:1]) + off = queue.publish(required=False, keys=(), cases=CASES[:1]) + assert (off["revision"], off["required"]) == (4, False) + + listed = queue.call( + "audit.list", {"event_type": "knowledge.suites.requirement", "limit": 100}, "runner" + ) + rows = sorted((json.loads(r["subject"]) for r in listed["rows"]), key=lambda s: s["revision"]) + assert {r["actor"] for r in listed["rows"]} == {"process:suite-runner"} + + def row(revision: int, was: bool, now: bool, **removed: Any) -> dict[str, Any]: + return { + "suite": SUITE, + "revision_before": revision - 1, + "revision": revision, + "required_before": was, + "required": now, + "keys_removed": [], + "prefixes_removed": [], + "cases_removed": 0, + **removed, + } + + assert rows == [ + row(1, False, True), + row(2, True, True, keys_removed=[other]), + row(3, True, True, cases_removed=1), + row(4, True, False), + ] + assert not [case_id for case_id in CASE_IDS if case_id in str(listed["rows"])] + + # Not required any more: a proposal with no results is accepted. + sha = queue.propose() + assert queue.accept({KEY: sha})[KEY]["decided"] is True + + +def test_listing_read_and_accept_give_one_state(queue: _Queue) -> None: + """Fails when the list, the results read and the accept disagree on the state of one + content, or the list advises accepting a row the accept refuses. + + Every value proposed is a string, whose stored hash is the hash a full read serves. + Where the two differ, as for an object with a null field, the list's state and advice + are for the stored hash and the accept's for the served one: that case is a + documented limit and is not asserted here.""" + queue.publish(required=True) + said = { + "satisfied": "", + "failed": "1 case failed for this content", + "empty": "no results for this content", + "unrun": "1 case could not run for this content", + "outdated": "its results are for other content or an earlier revision", + } + states = {**{name: name for name in said}, "empty": "missing", "unrun": "missing"} + hashes = {name: queue.propose(PREFIX + name, f"Net revenue, {name}.") for name in said} + queue.record(hashes["satisfied"], PREFIX + "satisfied") + queue.record(hashes["failed"], PREFIX + "failed", gross_is_not_net="fail") + queue.record(hashes["unrun"], PREFIX + "unrun", refunds_subtracted="unavailable") + other = ("0" if hashes["outdated"][0] != "0" else "1") + hashes["outdated"][1:] + queue.record(other, PREFIX + "outdated") + + rows = queue.listed(len(said)) + accepted = queue.accept({PREFIX + name: sha for name, sha in hashes.items()}) + for name, sha in hashes.items(): + key = PREFIX + name + row, results, result = rows[key], queue.results(sha, key), accepted[key] + assert row["checks"]["state"] == results["state"] == states[name], name + assert row["checks"]["required"] is True and results["required"] is True, name + held = "checks_required" in [reason["code"] for reason in row["advice_reasons"]] + assert held == (name != "satisfied"), name + assert row["advice"] != "accept" or not held, name + if name == "satisfied": + assert (result["decided"], result["status"]) == (True, "active") + else: + assert (result["decided"], result["code"]) == (False, "checks_required"), name + assert result["reason"] == _required(1, said[name]), name + + +def test_one_refused_key_does_not_stop_the_others(queue: _Queue) -> None: + """Fails when one key held by its checks leaves the other keys of the call + undecided.""" + queue.publish(required=True) + passing, failing = PREFIX + "passing", PREFIX + "failing" + hashes = { + passing: queue.propose(passing, "Net revenue excludes refunds."), + failing: queue.propose(failing, "Net revenue equals gross revenue."), + "office/badge": queue.propose("office/badge", "Badges are issued on the second floor."), + } + queue.record(hashes[passing], passing) + queue.record(hashes[failing], failing, gross_is_not_net="fail") + results = queue.accept(hashes) + assert {key: result["decided"] for key, result in results.items()} == { + passing: True, + failing: False, + "office/badge": True, + } + assert results[failing]["code"] == "checks_required" + assert queue.listed(1)[failing]["checks"]["state"] == "failed" + + +def test_a_proposal_no_suite_covers_is_accepted_as_before(queue: _Queue) -> None: + """Fails when a required suite holds a proposal on a key it does not cover.""" + queue.publish(required=True) + key = "office/parking" + sha = queue.propose(key, "Visitors park behind the loading dock.") + assert queue.listed(1)[key]["checks"] is None + assert queue.results(sha, key)["covered"] is False + accepted = queue.accept({key: sha})[key] + assert (accepted["decided"], accepted["status"], accepted["code"]) == (True, "active", "") diff --git a/tests/integration/test_proposal_checks_state.py b/tests/integration/test_proposal_checks_state.py index a11018b86b..715934bb05 100644 --- a/tests/integration/test_proposal_checks_state.py +++ b/tests/integration/test_proposal_checks_state.py @@ -37,7 +37,7 @@ # Every id and text of a case: none of it is in a listing's answer. CASE_WORDS = [str(case[field]) for case in CASES for field in case if field != "kind"] CONFIG = {"model": "scripted", "grader": "table", "trials": "1 of 1"} -CHECK_FIELDS = ("suite", "revision", "state", "passed", "failed", "unavailable") +CHECK_FIELDS = ("suite", "revision", "state", "passed", "failed", "unavailable", "required") def _post(base: str, token: str, op: str, body: dict[str, Any]) -> httpx.Response: @@ -141,7 +141,7 @@ def test_the_listing_and_the_results_read_give_one_state(url: str, mint_test_tok assert set(rows) == set(wrote.values()) # Before any set is recorded every covered row reads `missing`, with no count. assert {tuple(p["checks"][f] for f in CHECK_FIELDS) for p in rows.values()} == { - ("finance", 1, "missing", 0, 0, 0) + ("finance", 1, "missing", 0, 0, 0, False) } def row(name: str) -> dict[str, Any]: @@ -172,6 +172,7 @@ def agree(expected: dict[str, tuple[str, int, int, int, int]]) -> None: "passed": passed, "failed": failed, "unavailable": unavailable, + "required": False, }, name agree( @@ -224,6 +225,7 @@ def test_a_viewer_lists_the_state_and_no_case(url: str, mint_test_token: Any) -> "passed": 2, "failed": 1, "unavailable": 0, + "required": False, } # The whole answer, as sent: the value's own words are in it, a case's are not. assert "Pro costs forty a month." in answer.text diff --git a/tests/integration/test_proposal_triage_set.py b/tests/integration/test_proposal_triage_set.py index 8b6cbaf9e3..0a2dd12443 100644 --- a/tests/integration/test_proposal_triage_set.py +++ b/tests/integration/test_proposal_triage_set.py @@ -31,6 +31,13 @@ Path(__file__).parents[1].joinpath("fixtures", "proposal_triage_set.json").read_text("utf-8") ) _AGENT = "release-bot" +# The one case of a suite a `require` step publishes. +_CASE = { + "case_id": "window-stated", + "kind": "expect", + "prompt": "How long after delivery is a refund accepted?", + "expectation": "For 30 days after delivery.", +} # Where a case is labelled: the first call, the same call again, and the same call after # the correction. _LABELS = ("code", "replayed", "corrected") @@ -113,8 +120,8 @@ def call(self, op: str, body: dict[str, Any], who: str) -> dict[str, Any]: return answer def write(self, key: str, step: dict[str, Any]) -> None: - """One write of a case: a proposal of its key, a fact under another key, or the - deletion of a key.""" + """One write of a case: a proposal of its key, a fact under another key, the + deletion of a key, or a required suite that covers its key.""" who, agent = step.get("as", "writer"), step.get("agent", _AGENT) identity = {**self.scope, "agent": agent} if "delete" in step: @@ -124,6 +131,11 @@ def write(self, key: str, step: dict[str, Any]) -> None: elif "set" in step: body = {**identity, "memory_key": step["key"], "value": step["set"]} assert self.call("memory.set", body, who)["status"] == "active", step + elif "require" in step: + covers = {"memory_keys": [key], "memory_key_prefixes": [], "cases": [_CASE]} + suite = {"suite": step["require"], "expected_revision": 0, **covers} + body = {**self.scope, **suite, "required": True} + assert self.call("knowledge.suites.publish", body, who)["required"], step else: high = step.get("sensitivity") == "high" body = {**identity, "memory_key": key, "value": step["propose"], "proposed": True} diff --git a/tests/integration/test_suite_results.py b/tests/integration/test_suite_results.py index 6421f18ab8..b6759811bf 100644 --- a/tests/integration/test_suite_results.py +++ b/tests/integration/test_suite_results.py @@ -192,6 +192,7 @@ def test_a_candidate_that_fixes_one_case_and_breaks_another_reads_failed( "covered": False, "suite": "", "revision": 0, + "required": False, "state": "", "passed": 0, "failed": 0, diff --git a/tests/unit/test_knowledge_suite_drafts.py b/tests/unit/test_knowledge_suite_drafts.py index a006d1da3a..eacdb9fe77 100644 --- a/tests/unit/test_knowledge_suite_drafts.py +++ b/tests/unit/test_knowledge_suite_drafts.py @@ -295,7 +295,8 @@ def _row( def _revision(revision: int, case_ids: list[str], *, suite: str = "billing") -> str: return ( - "INSERT INTO loom.knowledge_suites VALUES " + "INSERT INTO loom.knowledge_suites (org, namespace, suite, revision, memory_keys, " + "memory_key_prefixes, case_ids, case_kinds, cases, written_by, written_at) VALUES " f"('o', 'ns', '{suite}', {revision}, ['k'], [], {case_ids}, " f"{['expect'] * len(case_ids)}, '[]', 'human:lead', '2026-10-21 10:00:00.000')" ) @@ -593,6 +594,7 @@ def test_only_get_and_the_origin_read_of_a_publish_select_draft_text( head = { "suite": "billing", "revision": 1, + "required": 0, "memory_keys": ["billing/refunds"], "memory_key_prefixes": [], "case_kinds": ["expect"], diff --git a/tests/unit/test_knowledge_suites.py b/tests/unit/test_knowledge_suites.py index 8887cf3cc2..21832b9c26 100644 --- a/tests/unit/test_knowledge_suites.py +++ b/tests/unit/test_knowledge_suites.py @@ -49,22 +49,30 @@ class _Suites: def __init__(self) -> None: self.rows: list[dict[str, Any]] = [] - def _newest(self, suite: str) -> dict[str, Any] | None: - rows = [r for r in self.rows if r["suite"] == suite] - return max(rows, key=lambda r: r["revision"]) if rows else None + def _at(self, suite: str, revision: int = 0) -> dict[str, Any] | None: + """The suite's row at `revision`, its newest by default, with the requirement in + force there: the newest one a revision at or below it states.""" + rows = sorted( + ( + r + for r in self.rows + if r["suite"] == suite and (not revision or r["revision"] <= revision) + ), + key=lambda r: r["revision"], + ) + if not rows or (revision and rows[-1]["revision"] != revision): + return None + stated = [r["required"] for r in rows if r.get("required", -1) >= 0] + return {**rows[-1], "required": stated[-1] if stated else 0} async def heads(self, org: str, namespace: str) -> list[dict[str, Any]]: - newest = [self._newest(s) for s in sorted({r["suite"] for r in self.rows})] - return [{k: r[k] for k in ("suite", "revision", *_HEAD)} for r in newest if r] + newest = [self._at(s) for s in sorted({r["suite"] for r in self.rows})] + return [{k: r[k] for k in ("suite", "revision", "required", *_HEAD)} for r in newest if r] async def head( self, org: str, namespace: str, suite: str, revision: int = 0 ) -> dict[str, Any] | None: - if not revision: - return self._newest(suite) - return next( - (r for r in self.rows if r["suite"] == suite and r["revision"] == revision), None - ) + return self._at(suite, revision) async def insert_row(self, row: dict[str, Any]) -> None: self.rows.append({**row, "written_at": AT}) @@ -545,7 +553,10 @@ def test_a_read_of_one_revision_filters_on_it() -> None: ch = RecordingCH().on("FROM loom.knowledge_suites", []) assert asyncio.run(suites_store.head("o", "ns", "billing", 3, ch=ch)) is None [statement] = ch.statements("loom.knowledge_suites") - assert "AND revision = {rev:UInt32}" in statement.sql + # The revisions up to the named one are read, so one below it can state the + # requirement; only the named one is answered. + assert "AND revision <= {rev:UInt32}" in statement.sql + assert "HAVING head_revision = {rev:UInt32}" in statement.sql assert statement.params == {"org": "o", "ns": "ns", "suite": "billing", "rev": 3} diff --git a/tests/unit/test_proposal_advice.py b/tests/unit/test_proposal_advice.py index f3fdb7baa8..9cdf5e3d55 100644 --- a/tests/unit/test_proposal_advice.py +++ b/tests/unit/test_proposal_advice.py @@ -31,6 +31,7 @@ "harm_reported", "usage_unread", "sensitive", + "checks_required", "policy_unmet", "untested", "stale", @@ -53,6 +54,7 @@ "harm_reported": {"harm_count": 1}, "usage_unread": {"usage_read": False, "used_count": 0}, "sensitive": {"sensitivity": "high"}, + "checks_required": {"checks_held": True}, } diff --git a/tests/unit/test_proposal_checks.py b/tests/unit/test_proposal_checks.py index f242baaad6..843a552547 100644 --- a/tests/unit/test_proposal_checks.py +++ b/tests/unit/test_proposal_checks.py @@ -32,6 +32,7 @@ _BILLING = { "suite": "billing", "revision": 5, + "required": 0, "memory_keys": ["billing/refunds"], "memory_key_prefixes": ["billing/plans/"], } @@ -173,6 +174,7 @@ async def test_the_listing_reads_checks_for_the_returned_rows_only(listing: Any) "passed": 3, "failed": 0, "unavailable": 0, + "required": False, } # `only` drops rows before the page is cut: the read names what the answer keeps. @@ -325,7 +327,7 @@ def test_the_state_is_the_one_the_results_read_derives( out = asyncio.run(suite_checks.for_keys("o", "n", [("k", _HASH), ("free", _HASH)], ch=ch)) # The key no suite covers has no entry. assert {content: astuple(c) for content, c in out.items()} == { - ("k", _HASH): ("billing", 5, state, *counts) + ("k", _HASH): ("billing", 5, state, *counts, False) } diff --git a/tests/unit/test_proposal_decide.py b/tests/unit/test_proposal_decide.py index da3fdd325d..84202abddb 100644 --- a/tests/unit/test_proposal_decide.py +++ b/tests/unit/test_proposal_decide.py @@ -60,7 +60,8 @@ class _Bench: """`proposals.decide` over a kept `loom.memory`, with what it sends beside the rows.""" def __init__(self, path: Path) -> None: - self.ch = KeptCH(path, ddl("memory")) + # An acceptance reads which suite covers its keys: none does here. + self.ch = KeptCH(path, ddl("memory"), ddl("knowledge_suites")) # One entry per insert into the audit log: the subjects of its rows. self.audits: list[list[dict[str, Any]]] = [] self.mirrored: list[str] = [] diff --git a/tests/unit/test_proposal_requirement.py b/tests/unit/test_proposal_requirement.py new file mode 100644 index 0000000000..0f7680b98c --- /dev/null +++ b/tests/unit/test_proposal_requirement.py @@ -0,0 +1,463 @@ +"""A required regression suite: a publish states the requirement and records every +change that lowers it, and an acceptance of a proposal on a key the suite covers needs +satisfied checks for the exact content accepted. A rejection reads no suite, and checks +that cannot be read fail the acceptance instead of letting it through.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.core import instances +from server.core.ch import sequential_reads_active +from server.core.errors import BackendUnavailableError, OverloadedError +from server.core.hashing import sha256_value +from server.core.paths import MIGRATIONS_DIR +from server.knowledge.api.models_suites import KnowledgeSuitesPublishInput +from server.knowledge.app import suite_checks +from server.knowledge.app import suites as suites_app +from server.knowledge.app.suite_drafts import DRAFTS_MIGRATION +from server.knowledge.store import suites as suites_store +from server.memory.app import proposals as p +from server.memory.domain import proposal_policy as pp +from server.memory.domain import proposal_triage as triage +from tests.unit.clickhouse_local import CLICKHOUSE, LocalCH, ddl +from tests.unit.principals import acting_as +from tests.unit.test_knowledge_suites import _FLEET_AT, ADMIN, _case, _Suites +from tests.unit.test_knowledge_suites import stored as stored # the fixture +from tests.unit.test_proposal_decide import _Bench, _id, _row +from tests.unit.test_proposal_decide import bench as bench # the fixture + +needs_clickhouse = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") + +_KEY = "billing/refunds" +_TEXT = "Refunds take thirty days" + + +def _checks(state: str = "satisfied", *, required: bool = True, **counts: int) -> Any: + """The checks of one content under the suite `finance` at revision 5.""" + of = {"passed": 0, "failed": 0, "unavailable": 0, **counts} + return suite_checks.Checks(suite="finance", revision=5, state=state, required=required, **of) # type: ignore[arg-type] + + +# --- the accept ----------------------------------------------------------------------- + + +class _Seen: + """A client that keeps the SQL of every statement it passes on.""" + + def __init__(self, ch: Any) -> None: + self._ch = ch + self.sql: list[str] = [] + + def __getattr__(self, name: str) -> Any: + inner = getattr(self._ch, name) + if name not in ("query_all", "query_one", "execute"): + return inner + + async def call(sql: str, *args: Any, **kwargs: Any) -> Any: + self.sql.append(sql) + return await inner(sql, *args, **kwargs) + + return call + + def suite_reads(self) -> list[str]: + return [sql for sql in self.sql if "loom.knowledge_suite" in sql] + + +@needs_clickhouse +async def test_a_reject_reads_no_checks(bench: _Bench, monkeypatch: pytest.MonkeyPatch) -> None: + """Fails when a rejection, a reviewer's or the owner policy's own, reads a suite + table. An acceptance through the same client does read one.""" + seen = _Seen(bench.ch) + bench.ch = seen # type: ignore[assignment] + await bench.seed( + _row(1, "by_hand", "one"), _row(2, "by_policy", "two"), _row(3, "accepted", "three") + ) + [rejected] = await bench.decide("reject", {"by_hand": sha256_value("one")}) + assert rejected.decided and rejected.status == "rejected" + + policy = pp.ProposalPolicy(mode="auto", min_passes=1, max_fails=0, reject_after_fails=1) + + async def _policy(*_a: Any, **_k: Any) -> pp.ProposalPolicy: + return policy + + async def _one_fail(*_a: Any, **_k: Any) -> dict[str, p.GradedCounts]: + return {"by_policy": p.GradedCounts(fails=1)} + + monkeypatch.setattr(p, "policy_for", _policy) + monkeypatch.setattr(p, "graded_counts", _one_fail) + assert [key for key, *_ in await p.apply_policy("o", "n", ["by_policy"], ch=seen)] == [ + "by_policy" + ] + assert seen.suite_reads() == [] + + [accepted] = await bench.decide("accept", {"accepted": sha256_value("three")}) + assert accepted.decided and len(seen.suite_reads()) == 1 + + +@needs_clickhouse +async def test_an_unreadable_checks_read_fails_the_accept(bench: _Bench) -> None: + """Fails when an acceptance goes through, or is answered as a refusal of its key, + while the suites cannot be read.""" + before = await bench.landed() + await bench.seed(_row(1, _KEY, _TEXT)) + table = {**before, (_KEY, _id(1)): ("proposed", 1)} + await bench.ch.execute("DROP TABLE loom.knowledge_suites") + with pytest.raises(Exception, match="knowledge_suites"): + await bench.decide("accept", {_KEY: sha256_value(_TEXT)}) + assert await bench.table() == table + assert [len(a) for a in bench.audits] == [1] and bench.mirrored == ["sentinel"] + + +async def test_the_accept_reads_checks_sequentially(monkeypatch: pytest.MonkeyPatch) -> None: + """Fails when the read of the suites or the read of their result sets runs outside + `sequential_reads()`: a replica behind another's failing set would accept.""" + seen: dict[str, bool] = {} + + async def _selections(*_a: Any, **_k: Any) -> list[dict[str, Any]]: + seen["suites"] = sequential_reads_active() + return [ + { + "suite": "finance", + "revision": 5, + "required": 1, + "memory_keys": [_KEY], + "memory_key_prefixes": [], + } + ] + + async def _counts(*_a: Any, **_k: Any) -> list[dict[str, Any]]: + seen["results"] = sequential_reads_active() + return [] + + monkeypatch.setattr(suite_checks.suites_repo, "selections", _selections) + monkeypatch.setattr(suite_checks.suite_results, "newest_counts", _counts) + picked = {_KEY: SimpleNamespace(value=_TEXT), "gone": p._undecided("gone", triage.CHANGED)} + # The listing's read is not: the spies tell the two apart. + await suite_checks.for_keys("o", "n", [(_KEY, sha256_value(_TEXT))]) + assert seen == {"suites": False, "results": False} + out = await p._required_checks("o", "n", picked, "accept", ch=None) + assert seen == {"suites": True, "results": True} + assert not sequential_reads_active() + assert out == {_KEY: _checks("missing")} + + +@pytest.mark.parametrize( + ("checks", "said"), + [ + (_checks("failed", passed=2, failed=1), "1 case failed for this content"), + (_checks("failed", failed=2, unavailable=1), "2 cases failed for this content"), + (_checks("missing"), "no results for this content"), + (_checks("missing", passed=2, unavailable=1), "1 case could not run for this content"), + (_checks("missing", unavailable=3), "3 cases could not run for this content"), + (_checks("outdated"), "its results are for other content or an earlier revision"), + ], +) +def test_each_state_has_its_refusal_text(checks: Any, said: str) -> None: + """Fails when a state that is not `satisfied` under a required suite accepts, or when + `missing` does not tell a set with a case that could not run from no set.""" + row = SimpleNamespace( + memory_id=_id(1), actor="process:author", value=_TEXT, value_truncated=False + ) + sent = sha256_value(_TEXT) + assert p._refusal(row, "accept", {"t"}, sent, checks) == triage.CHECKS_REQUIRED + result = p._undecided(_KEY, triage.CHECKS_REQUIRED, row, checks) + assert result.reason == f"suite finance (revision 5) is required: {said}" + assert (result.decided, result.code, result.memory_id) == (False, "checks_required", _id(1)) + + +def test_checks_refuse_last_and_only_when_required() -> None: + """Fails when satisfied checks accept what another rule refuses, or when checks that + are not required, or no checks, refuse.""" + row = SimpleNamespace(actor="process:author", value=_TEXT, value_truncated=False) + sent = sha256_value(_TEXT) + for allowed in (None, _checks("satisfied", passed=3), _checks("failed", required=False)): + assert p._refusal(row, "accept", {"t"}, sent, allowed) == "" + held = _checks("failed", failed=1) + passed = _checks("satisfied", passed=3) + for checks in (held, passed): + # The proposer, an unknown proposer and a stale hash are refused under either. + assert p._refusal(row, "accept", {"author"}, sent, checks) == triage.NOT_INDEPENDENT + nobody = SimpleNamespace(actor="", value=_TEXT, value_truncated=False) + assert p._refusal(nobody, "accept", {"t"}, sent, checks) == triage.PROPOSER_UNKNOWN + assert p._refusal(row, "accept", {"t"}, sha256_value("old"), checks) == triage.CHANGED + # A rejection is never held by a suite. + assert p._refusal(row, "reject", set(), None, held) == "" + + +@needs_clickhouse +async def test_an_accept_records_the_checks_it_read( + bench: _Bench, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when the audit row of an accepted key a suite covers lacks the suite, its + revision and the state, or a key no suite covers gains one.""" + + async def _for_keys(*_a: Any, **_k: Any) -> dict[tuple[str, str], Any]: + return {(_KEY, sha256_value(_TEXT)): _checks("satisfied", passed=3)} + + monkeypatch.setattr(p.suite_checks, "for_keys", _for_keys) + await bench.seed(_row(1, _KEY, _TEXT), _row(2, "plain", "other")) + out = await bench.decide("accept", {_KEY: sha256_value(_TEXT), "plain": sha256_value("other")}) + assert [r.decided for r in out] == [True, True] + [rows] = bench.audits + by_key = {row["memory_key"]: row for row in rows} + assert by_key[_KEY]["checks"] == {"suite": "finance", "revision": 5, "state": "satisfied"} + assert "checks" not in by_key["plain"] + + +# --- the heads statement -------------------------------------------------------------- + +_COLUMNS = ( + "org, namespace, suite, revision, memory_keys, memory_key_prefixes, case_ids, " + "case_kinds, cases, written_by, written_at" +) + + +def _revision(suite: str, revision: int, required: int | None) -> str: + """One revision; `required` None is a row a build without the column wrote, which + names no value for it.""" + named, value = ("", "") if required is None else (", required", f", {required}") + return ( + f"INSERT INTO loom.knowledge_suites ({_COLUMNS}{named}) VALUES " + f"('o', 'ns', '{suite}', {revision}, ['k/{suite}'], [], ['c'], ['expect'], '[]', " + f"'human:lead', '2026-10-21 10:00:00.000'{value})" + ) + + +@needs_clickhouse +def test_a_row_an_older_build_wrote_keeps_the_requirement() -> None: + """Fails when a revision that states no requirement reads as not required after a + required one, when a suite no revision states one for reads as required, or when a + read of a named revision answers a requirement stated after it.""" + local = LocalCH( + ddl("knowledge_suites"), + # Required at 1, then a revision from a build without the column. + _revision("kept", 1, 1), + _revision("kept", 2, None), + # Never stated: only revisions from a build without the column. + _revision("never", 1, None), + _revision("never", 2, None), + # Turned off at 3 after the older build's revision. + _revision("off", 1, 1), + _revision("off", 2, None), + _revision("off", 3, 0), + # Turned on at 2. + _revision("on", 1, 0), + _revision("on", 2, 1), + ) + want = {"kept": (2, 1), "never": (2, 0), "off": (3, 0), "on": (2, 1)} + for read in (suites_store.heads, suites_store.selections, suites_store.heads_with_ids): + rows = asyncio.run(read("o", "ns", ch=local)) # type: ignore[arg-type] + assert {r["suite"]: (r["revision"], r["required"]) for r in rows} == want, read.__name__ + + def at(suite: str, revision: int = 0) -> tuple[int, int] | None: + row = asyncio.run(suites_store.head("o", "ns", suite, revision, ch=local)) # type: ignore[arg-type] + return None if row is None else (row["revision"], row["required"]) + + assert {suite: at(suite) for suite in want} == want + assert (at("off", 1), at("off", 2), at("off", 3)) == ((1, 1), (2, 1), (3, 0)) + assert (at("on", 1), at("on", 2)) == ((1, 0), (2, 1)) + assert at("never", 1) == (1, 0) + assert at("kept", 3) is None and at("absent") is None + + +# --- the publish ---------------------------------------------------------------------- + + +def _publish( + expected: int, + *, + required: bool | None = None, + keys: tuple[str, ...] = ("billing/refunds", "billing/fees"), + prefixes: tuple[str, ...] = ("billing/plans/",), + cases: tuple[str, ...] = ("refund-window", "fee-waiver"), +) -> Any: + body = KnowledgeSuitesPublishInput( + org="o", + namespace="ns", + suite="billing", + expected_revision=expected, + memory_keys=list(keys), + memory_key_prefixes=list(prefixes), + cases=[_case(case_id) for case_id in cases], + required=required, + ) + with acting_as(ADMIN): + return asyncio.run(suites_app.handle_knowledge_suites_publish(body)) + + +@pytest.fixture +def audited(stored: _Suites, monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """The requirement rows a publish wrote, each with the revisions stored when it was + written.""" + rows: list[dict[str, Any]] = [] + + async def _emit(event: str, *, subject: dict[str, Any], **who: Any) -> str: + assert event == "knowledge.suites.requirement" + assert (who["org"], who["namespace"], who["actor"]) == ("o", "ns", "human:lead@example.com") + rows.append({**subject, "stored": len(stored.rows)}) + return "hash" + + monkeypatch.setattr(suites_app.audit, "emit_strict", _emit) + return rows + + +def test_lowering_a_requirement_writes_its_audit_row_first( + stored: _Suites, audited: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when turning the requirement off, or taking a key, a prefix or a case out of + a required suite, leaves no `knowledge.suites.requirement` row, when the row follows + the revision, or when the revision is written though the row was not.""" + + def row(before: int, was: bool, now: bool, **removed: Any) -> dict[str, Any]: + return { + "suite": "billing", + "revision_before": before, + "revision": before + 1, + "required_before": was, + "required": now, + "keys_removed": [], + "prefixes_removed": [], + "cases_removed": 0, + # Written before its revision: the suite still holds `before` rows. + "stored": before, + **removed, + } + + # Not required: a key leaves with no row. Turning it on writes one. + assert _publish(0).required is False + assert _publish(1, keys=("billing/refunds",)).written and audited == [] + assert _publish(2, required=True).required is True + assert audited == [row(2, False, True)] + # Required: a key, a prefix and a case each leave with a row; an added key does not. + assert _publish(3, keys=("billing/refunds",)).written + assert _publish(4, keys=("billing/refunds",), prefixes=()).written + assert _publish(5, keys=("billing/refunds",), prefixes=(), cases=("refund-window",)).written + assert _publish( + 6, keys=("billing/refunds", "billing/tax"), prefixes=(), cases=("refund-window",) + ).written + assert audited[1:] == [ + row(3, True, True, keys_removed=["billing/fees"]), + row(4, True, True, prefixes_removed=["billing/plans/"]), + row(5, True, True, cases_removed=1), + ] + # No case id reaches the row: it names keys and prefixes and counts cases. + assert "fee-waiver" not in str(audited) + + # The row that cannot be written: the publish fails and the suite is as it was. + async def _down(*_a: Any, **_k: Any) -> str: + raise RuntimeError("the audit log did not answer") + + monkeypatch.setattr(suites_app.audit, "emit_strict", _down) + held = [dict(r) for r in stored.rows] + assert len(held) == 7 + with pytest.raises(BackendUnavailableError): + _publish( + 7, + required=False, + keys=("billing/refunds", "billing/tax"), + prefixes=(), + cases=("refund-window",), + ) + assert stored.rows == held + # A publish that lowers nothing needs no row, so it lands. + assert _publish( + 7, + keys=("billing/refunds", "billing/tax", "billing/vat"), + prefixes=(), + cases=("refund-window",), + ).written + + +def test_turning_it_off_is_audited(stored: _Suites, audited: list[dict[str, Any]]) -> None: + assert _publish(0, required=True).required is True + assert _publish(1, required=False).model_dump() == { + "written": True, + "conflict": False, + "revision": 2, + "required": False, + } + assert [(r["required_before"], r["required"], r["stored"]) for r in audited] == [ + (False, True, 0), + (True, False, 1), + ] + + +def test_omitting_required_keeps_it(stored: _Suites, audited: list[dict[str, Any]]) -> None: + """Fails when a publish without `required` turns a requirement off or on, when a + first revision without it is required, or when a revision that states none (one an + older build wrote) ends the requirement.""" + first = _publish(0) + assert (first.written, first.required, stored.rows[-1]["required"]) == (True, False, 0) + assert _publish(1, required=True).required is True + kept = _publish(2, cases=("refund-window", "fee-waiver", "late-fee")) + assert (kept.written, kept.required, stored.rows[-1]["required"]) == (True, True, 1) + # A publish of the current document, with or without the field, writes nothing. + again = _publish(3, cases=("refund-window", "fee-waiver", "late-fee")) + stated = _publish(3, required=True, cases=("refund-window", "fee-waiver", "late-fee")) + assert [(a.written, a.revision, a.required) for a in (again, stated)] == [(False, 3, True)] * 2 + # A revision from a build without the column states nothing. + stored.rows.append({**stored.rows[-1], "revision": 4, "required": -1}) + after = _publish(4, cases=("refund-window", "fee-waiver")) + assert (after.written, after.required, stored.rows[-1]["required"]) == (True, True, 1) + # A stale publish answers the requirement in force and writes nothing. + stale = _publish(1, required=False, cases=("refund-window",)) + assert (stale.conflict, stale.revision, stale.required) == (True, 5, True) + assert len(audited) == 2 # turned on at 2, one case removed at 5 + + +@pytest.mark.parametrize("fleet", ["unread", "empty", "one below"]) +def test_requiring_waits_for_the_fleet( + stored: _Suites, audited: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch, fleet: str +) -> None: + """Fails when `required=true` is taken while a live replica is below the migration, + which accepts a proposal without reading a suite, or when a publish that requires + nothing waits for it.""" + + async def _read_live(ch: Any, *, all_deployments: bool = False) -> list[dict[str, Any]]: + assert all_deployments is True + if fleet == "unread": + raise RuntimeError("ClickHouse did not answer") + if fleet == "empty": + return [] + at = suites_app.REQUIRED_MIGRATION + return [{"schema_version": at}, {"schema_version": at - 1}] + + monkeypatch.setattr(suites_app.machines, "fleet_at", _FLEET_AT) + monkeypatch.setattr(instances, "read_live", _read_live) + with pytest.raises(OverloadedError) as refused: + _publish(0, required=True) + assert refused.value.extra["retry_after_s"] == 30 + assert stored.rows == [] and audited == [] + if fleet == "one below": + # The replica below the requirement serves suites: these publishes land. + assert _publish(0).written and _publish(1, required=False, cases=("refund-window",)).written + + +def test_a_fleet_at_the_migration_takes_the_requirement( + stored: _Suites, audited: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch +) -> None: + async def _read_live(ch: Any, *, all_deployments: bool = False) -> list[dict[str, Any]]: + return [{"schema_version": suites_app.REQUIRED_MIGRATION}] + + monkeypatch.setattr(suites_app.machines, "fleet_at", _FLEET_AT) + monkeypatch.setattr(instances, "read_live", _read_live) + assert _publish(0, required=True).required is True and len(audited) == 1 + + +def test_the_required_migration_constant_names_the_file() -> None: + """A renumbered migration fails here, not silently in the rollout gate.""" + name = f"{suites_app.REQUIRED_MIGRATION:03d}_knowledge_suite_required.sql" + assert (MIGRATIONS_DIR / name).exists() + # a build that serves suites, results and drafts and not the requirement is below it + assert suites_app.REQUIRED_MIGRATION > DRAFTS_MIGRATION > suites_app.SUITES_MIGRATION + + +def test_the_requirement_event_is_documented() -> None: + page = Path(__file__).resolve().parents[2] / "docs/features/observability/audit.md" + assert f"`{suites_app.REQUIREMENT_EVENT}`" in page.read_text("utf-8") diff --git a/tests/unit/test_proposal_triage_fixture.py b/tests/unit/test_proposal_triage_fixture.py index 0486857de5..ddeff9ff0e 100644 --- a/tests/unit/test_proposal_triage_fixture.py +++ b/tests/unit/test_proposal_triage_fixture.py @@ -34,7 +34,7 @@ def test_every_code_of_the_table_has_a_case() -> None: """Fails when a code of the documented set has no case, when a case is labelled with a code the table does not hold, or when the table and the server's set differ.""" documented = _documented_codes() - assert documented == {"", triage.NOT_PROPOSED, *triage.REASONS} + assert documented == {"", triage.NOT_PROPOSED, triage.CHECKS_REQUIRED, *triage.REASONS} # A case with `http` labels a call refused whole, whose code is the error's. answered = [case for case in SET["cases"] if "http" not in case] labelled = { diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index ce15a349ee..72a4fe3364 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -187,6 +187,7 @@ def test_the_journal_files() -> None: "134_memory_copy_rules.sql", "135_knowledge_suite_drafts.sql", "137_knowledge_reports.sql", + "138_knowledge_suite_required.sql", ] diff --git a/tests/unit/test_suite_results.py b/tests/unit/test_suite_results.py index 175945bbaf..d21800c267 100644 --- a/tests/unit/test_suite_results.py +++ b/tests/unit/test_suite_results.py @@ -44,6 +44,7 @@ HEAD = { "suite": "billing", "revision": 5, + "required": 0, "memory_keys": [KEY], "memory_key_prefixes": ["billing/plans/"], "case_ids": ["card-number", "old-window", "refund-window"], @@ -329,6 +330,7 @@ def test_a_key_no_suite_covers_reads_not_covered(ch: RecordingCH) -> None: "covered": False, "suite": "", "revision": 0, + "required": False, "state": "", "passed": 0, "failed": 0,