diff --git a/docs/guides/knowledge-factory-workflow.md b/docs/guides/knowledge-factory-workflow.md index 81b8a33900..cb34a7ed94 100644 --- a/docs/guides/knowledge-factory-workflow.md +++ b/docs/guides/knowledge-factory-workflow.md @@ -2,11 +2,12 @@ Needs a disposable org on a Loom server and three tokens minted for it. [`sdk/python/examples/knowledge_factory.py`](../../sdk/python/examples/knowledge_factory.py) -runs one correction over HTTP: a weekly report fails on an outdated definition, a -writer prepares a correction from the source document, an administrator approves the -exact text, and a fresh run is served the published definition and passes on other -numbers. This guide gives the commands, what a pass proves, the reads that show it -without the script, and the limits. +runs one correction over HTTP: a weekly report fails on an outdated definition, the +reporter files a problem report against the revision it read, a writer prepares a +correction from the source document, an administrator approves the exact text and +resolves the report with the published revision, and a fresh run is served the +published definition and passes on other numbers. This guide gives the commands, what a +pass proves, the reads that show it without the script, and the limits. The reporter, the curator, the reviewer and the grader are scripted, and no call is answered by a model. A pass shows that Loom keeps its contract. It does not measure an @@ -14,13 +15,12 @@ agent. The run does not exercise the following, and its result lists each under `coverage`: -- a problem report that Loom holds, and a second report of the same problem - a curation pass, its retry after an interruption, a source that changed before the approval, and a guard against publishing twice - a run by a real agent, and the MCP transport -Until the first two are exercised the result reads `qualified: false`, also when -every check passes. +Until the first is exercised the result reads `qualified: false`, also when every +check passes. The [knowledge factory walkthrough](../use-cases/knowledge-factory.md#run-a-knowledge-factory-walkthrough) is a shell session that publishes a document and saves a lesson citing it. This guide @@ -97,39 +97,43 @@ Three things to know before running: ## The stages -| Stage | Token | What happens | -| --------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `preflight` | all three | Identity, claims, ops and fields, the absent team namespace; then the two writers' `memory.definitions.list` must answer 403 | -| `setup` | all three | `namespace.register` for both names with the run's marker, and the curator's refused read of the reporter's namespace; the definition (`memory.set`, `memory.promote`), the data dictionary (`knowledge.upsert`), the procedure (`procedure.add`), a personal request; then a `memory.search` of the shared scope for the copy the promotion wrote | -| `run_1` | reporter, reviewer | `run.begin`, a labelled `memory.search` and `memory.get`, the report on week 1's numbers, `run.complete` with a reflection, `run.grade`: fail, then `run.reliance`, which lists the copy the first promotion wrote | -| `report` | | Not exercised | -| `investigation` | curator | `knowledge.get` of the source document, then the candidate: `memory.set` with `if_match_sha256` and `source_resource_id`; the same write sent a second time answers 409 | -| `review` | all three | What a reader is served meanwhile, two refused promotions, an amended candidate, a stale approval refused with 409, a personal request proposed for the team and rejected, a team note proposed and accepted, a note the reviewer proposed and cannot accept | -| `publication` | reviewer | `memory.get` of the amended text, `memory.promote` of that read's hash, `memory.lineage`, `audit.list`, then a `memory.search` of the shared scope for the copy the promotion wrote | -| `run_2` | reporter, reviewer | A new client, session and run on week 2's numbers: the first search result is the governed definition, the report passes, and `run.reliance` lists the copy the correction's promotion wrote | -| `evidence` | reporter | `run.get` for both runs, the reflection, `memory.provenance` | +| Stage | Token | What happens | +| --------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `preflight` | all three | Identity, claims, ops and fields, the absent team namespace; then the two writers' `memory.definitions.list` must answer 403 | +| `setup` | all three | `namespace.register` for both names with the run's marker, and the curator's refused read of the reporter's namespace; the definition (`memory.set`, `memory.promote`), the data dictionary (`knowledge.upsert`), the procedure (`procedure.add`), a personal request; then a `memory.search` of the shared scope for the copy the promotion wrote | +| `run_1` | reporter, reviewer | `run.begin`, a labelled `memory.search` and `memory.get`, the report on week 1's numbers, `run.complete` with a reflection, `run.grade`: fail, then `run.reliance`, which lists the copy the first promotion wrote | +| `report` | reporter, reviewer | `memory.get` of the definition's source row, then `knowledge.reports.submit` against that revision with the run and its reflection as evidence, and the same submit a second time; the reviewer's `knowledge.reports.update`: `take`, then a `resolve` that answers 422; `knowledge.reports.get`, whose target and report id the reviewer hands the curator | +| `investigation` | curator | `memory.get` of the definition, which must hold the revision the report names; `knowledge.get` of the source document, then the candidate: `memory.set` with `if_match_sha256` and `source_resource_id`; the same write sent a second time answers 409 | +| `review` | all three | What a reader is served meanwhile, two refused promotions, an amended candidate, a stale approval refused with 409, a personal request proposed for the team and rejected, a team note proposed and accepted, a note the reviewer proposed and cannot accept | +| `publication` | reviewer | `memory.get` of the amended text, `memory.promote` of that read's hash, `memory.lineage`, `audit.list`, `knowledge.reports.update` with `resolve` and the published revision, then a `memory.search` of the shared scope for the copy the promotion wrote | +| `run_2` | reporter, reviewer | A new client, session and run on week 2's numbers: the first search result is the governed definition, the report passes, and `run.reliance` lists the copy the correction's promotion wrote | +| `evidence` | reporter | `run.get` for both runs, the reflection, `memory.provenance`, the resolved report (`knowledge.reports.get`) | The numbers come from the fixture's numbers source on every run and are never saved as knowledge: no request of the example holds one of them. ## What Loom enforces and what the example arranges -| Property | Loom | The example | -| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| Publication needs `admin` on the namespace | Enforced: `memory.promote` answers 403 to a `writer` | | -| An approval names the exact text | Enforced: `approved_sha256`, else 409 `PRECONDITION_FAILED` with `current_sha256` | Reads the text again after a 409 | -| A write does not replace a revision its writer did not read | Enforced for a write that sends `if_match_sha256`: 409 when the row holds another hash | Both of the curator's writes send it | -| The approver of a definition is a person | Not enforced: a service account with `admin` can promote | Preflight requires a person's token for the reviewer | -| The approver is not the author | Not enforced for a promotion | By tokens: the curator holds `writer`; the result shows author and approver | -| Deciding a proposal needs `admin` on the namespace | Enforced: `memory.proposal_decide` answers 403 to a `writer` | | -| A person other than the proposer accepts a proposal | Enforced by `memory.proposal_decide` ([proposals](../features/memory/writing.md#proposals)) | The reviewer cannot accept a note it proposed: 200 with nothing decided | -| A proposal is not served | Enforced: a `proposed` row is in no search result | The same search returns the row once it is accepted | -| A `writer` cannot change an active team row without review | Not enforced | A limit, below | -| The approved definition stays served during review | No: an edit of its source row ends governance until the next approval | The reporter uses a definition only from a governed hit | -| The link from the problem to the correction | Not held | Text in the promotion's `rationale` that names run 1 | -| The revision a run was served | Kept as a read receipt where one is written; `run.reliance` lists it ([what a run read](../features/runs.md#what-a-run-read)) | Reads it after each run and compares it with the copy the last promotion wrote; a run with no receipt fails | -| An independent grader | Not enforced: `run.grade` takes any `writer` | The reviewer's token grades; the audit row shows who called | -| No duplicate publication | Not enforced: `memory.promote` is not idempotent | One call; one that gets no usable answer is settled by reads | +| Property | Loom | The example | +| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| Publication needs `admin` on the namespace | Enforced: `memory.promote` answers 403 to a `writer` | | +| An approval names the exact text | Enforced: `approved_sha256`, else 409 `PRECONDITION_FAILED` with `current_sha256` | Reads the text again after a 409 | +| A write does not replace a revision its writer did not read | Enforced for a write that sends `if_match_sha256`: 409 when the row holds another hash | Both of the curator's writes send it | +| The approver of a definition is a person | Not enforced: a service account with `admin` can promote | Preflight requires a person's token for the reviewer | +| The approver is not the author | Not enforced for a promotion | By tokens: the curator holds `writer`; the result shows author and approver | +| Deciding a proposal needs `admin` on the namespace | Enforced: `memory.proposal_decide` answers 403 to a `writer` | | +| A person other than the proposer accepts a proposal | Enforced by `memory.proposal_decide` ([proposals](../features/memory/writing.md#proposals)) | The reviewer cannot accept a note it proposed: 200 with nothing decided | +| A proposal is not served | Enforced: a `proposed` row is in no search result | The same search returns the row once it is accepted | +| A `writer` cannot change an active team row without review | Not enforced | A limit, below | +| The approved definition stays served during review | No: an edit of its source row ends governance until the next approval | The reporter uses a definition only from a governed hit | +| The link from the problem to the correction | Held: a report keeps the revision it was filed against and, once resolved, its `resolution_revision` ([knowledge reports](../architecture/knowledge-reports.md)) | Files the report and resolves it with the revision the promotion published | +| One problem is one report | Enforced: the same reporter, kind, target and problem text give the same `report_id` | Sends the same `knowledge.reports.submit` twice | +| Only an administrator takes, resolves or dismisses a report | Enforced: `knowledge.reports.update` needs `admin` on the namespace | The reviewer takes and resolves; the curator holds `writer` and calls no report op | +| A resolution names a newer revision | Enforced: 422 while the target holds no revision newer than the reported one, and for a number other than the version `memory.get` serves | The reviewer's `resolve` before the correction is refused | +| A resolution names a published revision | Not enforced: a newer revision of the source row resolves a report, promoted or not | The reviewer resolves after the promotion; a limit, below | +| The revision a run was served | Kept as a read receipt where one is written; `run.reliance` lists it ([what a run read](../features/runs.md#what-a-run-read)) | Reads it after each run and compares it with the copy the last promotion wrote; a run with no receipt fails | +| An independent grader | Not enforced: `run.grade` takes any `writer` | The reviewer's token grades; the audit row shows who called | +| No duplicate publication | Not enforced: `memory.promote` is not idempotent | One call; one that gets no usable answer is settled by reads | [Governed definitions in search](../concepts/identities-and-namespaces.md#governed-definitions-in-search) explains when a definition is governed and how a query matches its term. @@ -179,7 +183,22 @@ explains when a definition is governed and how a query matches its term. (`client_reported`), and the grade with the caller Loom recorded (`graded`). Where `run.get` reports the keys the labelled search returned, the check fails unless `returned` holds the definition's key. -10. Every link between the stages is typed and says who holds it: `loom`, or `client` +10. A problem is reported against the revision that was read. The reporter reads the + definition's source row and files `knowledge.reports.submit` with that read's + `version_text` and `content_sha256`, the run in `run_id`, and two references as + evidence: `run:` and `reflection:`. The same request sent a second + time answers the same `report_id`, state and version. The report the reviewer then + reads names that revision, reads `target_changed: false` and serves both references. +11. Only an administrator takes, resolves or dismisses a report, and a report resolves + only with a newer revision. The reviewer takes the report. Its `resolve` that names + the reported revision answers 422 `VALIDATION_FAILED` with a message that names + that revision, and the report stays `taken` at version 2. Only its reporter and an + administrator read a report, so the reviewer hands the curator the target the + report names and its id; the curator reads that revision and calls no report op. + After the promotion the reviewer resolves the report with the `version_text` that + `memory.get` served, and the reporter reads its report as `resolved` with that + `resolution_revision`. +12. Every link between the stages is typed and says who holds it: `loom`, or `client` for a link that is only text the example wrote. `tests/unit/test_sdk_example_knowledge_factory.py` runs the example against a scripted @@ -212,23 +231,27 @@ With the names and ids of the result file, each read as the token named: `version` the correction's promotion wrote, the one run 2's stage and the `copy` of the `publication` stage name. The version is a number above 2^53: read it with a client that keeps integers whole, such as Python. +10. `knowledge.reports.get` with the `report_id` of `ids` (reviewer or reporter): `state` + is `resolved`, `target_version_text` is the version the `report` stage names and + `resolution_revision` the one the `publication` stage names. `knowledge.reports.list` + with `target_key` `definition/active-account` (reviewer): that one report. ## The result document -| Field | Holds | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `mode` | `deterministic`: every role is scripted | -| `status` | `passed`, `failed`, `not_ready` or `unavailable`; `running` in a file whose run did not reach its end | -| `qualified` | True when the run passed and every gating coverage entry is exercised | -| `run` | The run's id and marker, the base URL without any `user:password@`, the org, the two namespaces and the three subjects | -| `stages` | Each stage's status and request ids; a `revision` where the stage read one; for `setup` and `publication` the `copy` the promotion wrote; for the two runs `served` and the `revision` Loom recorded | -| `runs` | Per run: the report, the control question, `returned`, `client_reported`, `graded` | -| `links` | Problem, correction, source, review, published revision, later run and outcome: a typed `ref`, `held_by` and the `read` that shows it | -| `observations` | What a reader is served while a candidate awaits review; values of this path, not required behaviour | -| `coverage` | What this version exercises, and the capability each entry that is not exercised needs | -| `checks` | Every check, with its stage and a detail; a refusal, a grade, the search during review and the audited promotion name their request id | -| `ids` | The source document's `doc_id` and the two promotion events | -| `cleanup` | `not_run`, `completed` or `failed`; after a cleanup also `erasures` and `remains` | +| Field | Holds | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mode` | `deterministic`: every role is scripted | +| `status` | `passed`, `failed`, `not_ready` or `unavailable`; `running` in a file whose run did not reach its end | +| `qualified` | True when the run passed and every gating coverage entry is exercised | +| `run` | The run's id and marker, the base URL without any `user:password@`, the org, the two namespaces and the three subjects | +| `stages` | Each stage's status and request ids; a `revision` where the stage read one; for `report` the `handoff`, the target and the report id the reviewer hands the curator; for `setup` and `publication` the `copy` the promotion wrote; for the two runs `served` and the `revision` Loom recorded | +| `runs` | Per run: the report, the control question, `returned`, `client_reported`, `graded` | +| `links` | Problem, correction, source, review, published revision, later run and outcome: a typed `ref`, `held_by` and the `read` that shows it | +| `observations` | What a reader is served while a candidate awaits review; values of this path, not required behaviour | +| `coverage` | What this version exercises, and the capability each entry that is not exercised needs | +| `checks` | Every check, with its stage and a detail; a refusal, a grade, the search during review and the audited promotion name their request id | +| `ids` | The source document's `doc_id`, the two promotion events and the report's id | +| `cleanup` | `not_run`, `completed` or `failed`; after a cleanup also `erasures` and `remains` | A revision is the source row's `version_text` and `content_sha256` from one `memory.get`, with `read` saying which. The version is a decimal string: as a number it @@ -288,14 +311,13 @@ means that it holds no count, not zero ## Coverage -| Entry | Exercised | Needs | -| ------------------------------------------------------------------------------------------------ | --------- | ------------------------------- | -| `run_1`, `investigation`, `review`, `publication`, `run_2`, `evidence`, `control_question` | yes | | -| `revision_receipts` | yes | | -| `report`, `repeated_report` | no | Problem reports that Loom holds | -| `curation_pass`, `interrupted_pass_retry`, `stale_source_refusal`, `duplicate_publication_guard` | no | A curation pass | -| `real_agent_run` | no | An agent runner; does not gate | -| `mcp_path` | no | An MCP client; does not gate | +| Entry | Exercised | Needs | +| ---------------------------------------------------------------------------------------------------- | --------- | ------------------------------ | +| `run_1`, `report`, `investigation`, `review`, `publication`, `run_2`, `evidence`, `control_question` | yes | | +| `revision_receipts`, `repeated_report` | yes | | +| `curation_pass`, `interrupted_pass_retry`, `stale_source_refusal`, `duplicate_publication_guard` | no | A curation pass | +| `real_agent_run` | no | An agent runner; does not gate | +| `mcp_path` | no | An MCP client; does not gate | The table is a constant of the example's version. An entry reads exercised only in the version that makes its calls and checks them, never at run time. @@ -350,13 +372,14 @@ namespace with its grant, the audit rows, and the erasure ledger rows. Loom holds the knowledge, its review state and each run's evidence. The loop around them runs in the agent host. In the example a script plays every part. -| Part | The host | Loom | -| ---------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| The reporting agent, on a schedule | Starts each run, labels its reads with it, reports what it relied on | `run.begin`, `run.complete` with `memories_used` ([runs](../features/runs.md)) | -| The sweep that finds work | Lists failed and ungraded runs, and questions no source answered | `run.list` with `grade`; [`knowledge.gaps.list`](../features/knowledge.md#knowledge-gaps) where it is on | -| The curator | Reads the failed run and the source document, writes the candidate | `memory.set` with `if_match_sha256` and `source_resource_id` | -| The evaluator | Decides each grade and names itself in `source` | `run.grade` records the grade and its caller, and judges nothing | -| The display of what an answer used | Shows the keys a run reported and, where listed, those its search returned | `run.get`: `memories_used`, `recalled_keys`; `run.reliance`: the versions served | +| Part | The host | Loom | +| ---------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| The reporting agent, on a schedule | Starts each run, labels its reads with it, reports what it relied on | `run.begin`, `run.complete` with `memories_used` ([runs](../features/runs.md)) | +| The report of a problem | Files it against the revision the agent read, with the run as evidence; maintainers work the queue | `knowledge.reports.submit`, `knowledge.reports.list`, `knowledge.reports.update` ([knowledge reports](../architecture/knowledge-reports.md)) | +| The sweep that finds work | Lists failed and ungraded runs, and questions no source answered | `run.list` with `grade`; [`knowledge.gaps.list`](../features/knowledge.md#knowledge-gaps) where it is on | +| The curator | Reads the reported revision and the source document, writes the candidate | `memory.set` with `if_match_sha256` and `source_resource_id` | +| The evaluator | Decides each grade and names itself in `source` | `run.grade` records the grade and its caller, and judges nothing | +| The display of what an answer used | Shows the keys a run reported and, where listed, those its search returned | `run.get`: `memories_used`, `recalled_keys`; `run.reliance`: the versions served | ## Limits @@ -380,6 +403,21 @@ them runs in the agent host. In the example a script plays every part. approved hash before. Any other write that ends this way fails the run and is not sent again. - **`grade_source` is text the caller sent.** The audit row says who graded. +- **A resolution needs a newer revision, not a promotion.** `knowledge.reports.update` + compares `resolution_revision` with the version `memory.get` serves for the source + row. A candidate that awaits review is such a revision, so an administrator can + resolve a report before its correction is published. The example resolves after the + promotion. +- **Name the run when filing through the Python SDK.** `Agent.call` sends `-` for a + `run_id` the caller does not set, and `knowledge.reports.submit` reads it as a run: + the call answers 422 with `evidence 'run:-' was not found`. The example sends the + failed run's id. +- **The report stage needs every replica on the reports migration.** While a live + replica runs a schema below the migration that adds the reports table, + `knowledge.reports.submit` and `knowledge.reports.update` answer 503. A run that + reaches the `report` stage then ends `failed` there, after `setup` registered both + namespaces, whose names are spent. Run the example once the rolling upgrade is done + ([rolling upgrades](../architecture/knowledge-reports.md#rolling-upgrades)). - **The copy's version is read by a search.** `memory.promote` and `memory.lineage` answer no version of the shared copy, and `memory.get` serves the source row. The example reads the copy with a `memory.search` of the shared scope, so the read @@ -396,10 +434,14 @@ them runs in the agent host. In the example a script plays every part. run evidence differs. - **Minted, flat tokens only.** The tokens come from `loom mint-token` with `--namespaces` and `--roles`. Preflight refuses a token minted with - `--namespace-role`. A reviewer signed in through an identity provider, and a token - pinned to one user, are not covered by the example's tests. + `--namespace-role`. A token minted with a `--read-scope` below the namespace fails + the run: Loom refuses it `memory.promote`, `run.reliance` and every + `knowledge.reports.*` op, and bounds its reads to one user or session + ([read scope](../concepts/identities-and-namespaces.md#read-scope-inside-a-namespace)). + A reviewer signed in through an identity provider, and a token pinned to one user, + are not covered by the example's tests. - **Preview ops.** The example calls these ops that the [status page](../reference/status.md) lists as preview: - - marked `experimental`: `memory.definitions.list`, `memory.promote`, `memory.lineage`, `memory.proposals`, `memory.proposal_decide`, `knowledge.upsert`, `run.reliance`, `run.grade`, `audit.list`, `erasure.status`, `erasure.list` + - marked `experimental`: `memory.definitions.list`, `memory.promote`, `memory.lineage`, `memory.proposals`, `memory.proposal_decide`, `knowledge.upsert`, `knowledge.reports.submit`, `knowledge.reports.get`, `knowledge.reports.update`, `run.reliance`, `run.grade`, `audit.list`, `erasure.status`, `erasure.list` ## Related diff --git a/sdk/python/examples/README.md b/sdk/python/examples/README.md index 9233b36214..64c36a071c 100644 --- a/sdk/python/examples/README.md +++ b/sdk/python/examples/README.md @@ -59,8 +59,9 @@ check the SDK contracts; no captured live output is supplied. See the ## knowledge_factory.py -One correction of a published definition, from a failed report through an administrator's -approval of the exact text to a fresh run that is served it. Three tokens, a disposable +One correction of a published definition, from a failed report and the problem report +filed against the revision it read, through an administrator's approval of the exact +text, to a fresh run that is served it. Three tokens, a disposable org and one command; the script exits 0 when every check passes and writes a result document that lists every check and each stage's request ids. The reporter, the curator, the reviewer and the grader are scripted, and no call is answered by a diff --git a/sdk/python/examples/knowledge_factory.py b/sdk/python/examples/knowledge_factory.py index 83cc0aa88b..ede1f0d6d1 100644 --- a/sdk/python/examples/knowledge_factory.py +++ b/sdk/python/examples/knowledge_factory.py @@ -1,7 +1,8 @@ """Run the knowledge factory loop against a disposable Loom deployment with three tokens: -a weekly report fails on an outdated definition, a writer prepares a correction from the -source document, an administrator approves the exact text, and a fresh run is served the -published definition and passes on other numbers. +a weekly report fails on an outdated definition, the reporter files a problem report +against the revision it read, a writer prepares a correction from the source document, +an administrator approves the exact text and resolves the report with the published +revision, and a fresh run is served the published definition and passes on other numbers. python knowledge_factory.py run --result kf-result.json python knowledge_factory.py cleanup --result kf-result.json --accept-org-cache-loss @@ -63,6 +64,9 @@ SOURCE_URI = "urn:loom:example:kf:data-dictionary" QUESTION = "What is an active account?" GOAL = "Prepare the weekly account report" +# What the reporter saw, in run 1's reflection and in its report: not the fix, so no +# column name and no figure. +PROBLEM = "The definition names a column the numbers source does not have." GRADER = "fixture-grader" OWNER = "kf-example@loom.test" MARKER = "kf-example-run:" @@ -129,6 +133,18 @@ "memory.lineage": ["memory_key", "scope"], "knowledge.upsert": ["source_uri", "title", "content"], "knowledge.get": ["source_uri"], + "knowledge.reports.submit": [ + "run_id", + "kind", + "target_kind", + "target_key", + "target_version", + "target_sha256", + "problem", + "evidence", + ], + "knowledge.reports.get": ["report_id"], + "knowledge.reports.update": ["report_id", "action", "resolution_revision"], "procedure.add": ["name", "situation", "steps"], "run.begin": ["goal"], "memory.search": ["query", *(name for name in COPY if name not in ("agent", "session_id"))], @@ -162,12 +178,12 @@ def _entry(kind: str, exercised: bool, gates: bool = True, **more: Any) -> dict[ return {"kind": kind, "exercised": exercised, "gates_qualified": gates, **more} -# What this version exercises: the one source for the result's `coverage`, for the -# stages rendered as `not_exercised` and for `qualified`. An entry is switched to -# exercised by the change that adds its calls and checks, never at run time. +# What this version exercises: the one source for the result's `coverage` and for +# `qualified`. An entry is switched to exercised by the change that adds its calls and +# checks, never at run time. COVERAGE: dict[str, dict[str, Any]] = { "run_1": _entry("stage", True), - "report": _entry("stage", False, needs="knowledge_reports"), + "report": _entry("stage", True), "investigation": _entry("stage", True), "review": _entry("stage", True), "publication": _entry("stage", True), @@ -176,7 +192,7 @@ def _entry(kind: str, exercised: bool, gates: bool = True, **more: Any) -> dict[ "control_question": _entry("criterion", True), "curation_pass": _entry("criterion", False, needs="curation_pass"), "revision_receipts": _entry("criterion", True), - "repeated_report": _entry("criterion", False, needs="knowledge_reports"), + "repeated_report": _entry("criterion", True), "interrupted_pass_retry": _entry("criterion", False, needs="curation_pass"), "stale_source_refusal": _entry("criterion", False, needs="curation_pass"), "duplicate_publication_guard": _entry("criterion", False, needs="curation_pass"), @@ -254,6 +270,9 @@ class Held: doc_id: Any = None # Setup, then publication: the version of the shared copy the last promotion wrote. copy: str = "" + # Report: its id, and what the reviewer hands the curator: the target and the id. + report_id: str = "" + handoff: dict[str, Any] = field(default_factory=dict) # Investigation: the candidate's hash and the revision of the document it names. candidate_sha256: str = "" document_revision: Any = None @@ -425,11 +444,6 @@ def copy_version(found: dict[str, Any], approved: dict[str, Any]) -> str: def new_result(args: argparse.Namespace, run_id: str) -> dict[str, Any]: - stages = [] - for name in STAGES: - entry = COVERAGE.get(name, {"exercised": True}) - stage = {"stage": name, "status": "not_run" if entry["exercised"] else "not_exercised"} - stages.append(stage if entry["exercised"] else {**stage, "needs": entry["needs"]}) return { "mode": MODE, "status": "running", @@ -443,7 +457,7 @@ def new_result(args: argparse.Namespace, run_id: str) -> dict[str, Any]: "reporter_namespace": args.reporter_namespace, "subjects": {}, }, - "stages": stages, + "stages": [{"stage": name, "status": "not_run"} for name in STAGES], "runs": {}, "links": [], "observations": {}, @@ -632,6 +646,13 @@ def refusal(self, name: str, answer: Answer) -> bool: """A check that passes when Loom refused the call for the caller's role.""" return self.check(name, answer.denied, answer.text, answer.request_id) + def unrevised(self, name: str, answer: Answer, reported: str) -> bool: + """A check that passes when the server refused a resolution because the target + holds no revision newer than `reported`, which the refusal names.""" + named = f"reported revision {reported}" in str(answer.detail.get("message")) + refused = answer.status == 422 and answer.code == "VALIDATION_FAILED" and named + return self.check(name, refused, answer.text, answer.request_id) + def superseded(self, name: str, answer: Answer, current: str) -> bool: """A check that passes when the server refused a call that names a hash the row no longer holds, and named the hash it holds.""" @@ -1026,9 +1047,7 @@ async def reporting_run(self, number: int, approved: dict[str, Any]) -> None: report = produced["report"] closing: dict[str, Any] = {"memories_used": [DEFINITION_KEY, PROCEDURE_KEY]} if report and report["active_rate"] is None: - # The reporter records what it saw, not the fix: no column name, no figure. - failed = "The definition names a column the numbers source does not have." - closing["reflection"] = {"what_failed": [failed], "evidence": [DEFINITION_KEY]} + closing["reflection"] = {"what_failed": [PROBLEM], "evidence": [DEFINITION_KEY]} closed = await self.call( REPORTER, "run.complete", @@ -1167,15 +1186,77 @@ async def run_2(self) -> None: unaffected = same and first["grade"] == second["grade"] == "pass" self.check("control_unaffected_by_the_correction", unaffected) + # ---- stage 3: report --------------------------------------------------------------- + + async def report(self) -> None: + """The reporter reads the definition's source row and files a report against + that revision, citing run 1 and its reflection. Sent a second time, the report + is the same one. The reviewer takes it, and its resolution is refused while the + row holds no newer revision. Only its reporter and an administrator read a + report, so the reviewer reads it and hands the curator the target it names and + its id.""" + row = await self.definition_until(REPORTER, self.held.first_sha256) + read = revision(row, self.team, DEFINITION_KEY, "memory.get before the report") + run_1 = self.result["runs"]["run_1"]["run_id"] + cited = [f"run:{run_1}", f"reflection:{run_1}"] + # `run_id` names the run that met the problem. The SDK fills an unset one with + # "-", which the op reads as a run and refuses as one it cannot find. + filing = { + "agent": "-", + "run_id": run_1, + "kind": "outdated", + "target_kind": "memory", + "target_key": DEFINITION_KEY, + "target_version": read["version"], + "target_sha256": read["sha256"], + "problem": PROBLEM, + "evidence": cited, + } + filed = await self.call(REPORTER, "knowledge.reports.submit", **filing) + named = {"report_id": str(filed.get("report_id") or "")} + opened = (filed.get("state"), filed.get("version")) == ("open", 1) + self.check("report_filed_open", bool(named["report_id"]) and opened) + again = await self.call(REPORTER, "knowledge.reports.submit", **filing) + self.check("second_submit_returns_the_same_report", again == filed) + took = await self.call(REVIEWER, "knowledge.reports.update", action="take", **named) + taken = (took.get("state"), took.get("version")) == ("taken", 2) + self.check("report_taken_by_the_reviewer", taken) + early = await self.send( + REVIEWER, + "knowledge.reports.update", + action="resolve", + resolution_revision=read["version"], + **named, + ) + self.unrevised("resolve_before_publication_refused", early, read["version"]) + # Not repeated, here or in `evidence`: Loom reads a report with sequential + # consistency, so the read shows the last acknowledged change without a wait. + got = (await self.call(REVIEWER, "knowledge.reports.get", **named)).get("report") or {} + target = {"kind": got.get("target_kind"), "namespace": self.team} + target.update(key=got.get("target_key"), version=got.get("target_version_text")) + same = target == {name: read[name] for name in target} + unchanged = got.get("target_changed") is False and got.get("evidence") == cited + self.check("report_names_the_revision_that_was_read", same and unchanged) + kept = (got.get("state"), got.get("version"), got.get("resolution_revision")) + self.check("report_unchanged_by_the_refused_resolve", kept == ("taken", 2, "")) + self.held.report_id = named["report_id"] + self.held.handoff = {**named, "target": target} + self.result["ids"].update(named) + self.entry().update(revision=read, handoff=self.held.handoff) + # ---- stage 4: investigation -------------------------------------------------------- async def investigation(self) -> None: - """The curator reads the definition and the source document, then writes the - candidate against the revision it read, naming the document. This direct write - stands in for a curation pass. Sent a second time, the write names a revision - the row no longer holds, and the server refuses it.""" + """The curator reads the revision of the definition the reviewer handed it and + the source document, then writes the candidate against the revision it read, + naming the document. This direct write stands in for a curation pass. Sent a + second time, the write names a revision the row no longer holds, and the server + refuses it.""" held = self.held read = await self.definition_until(CURATOR, held.first_sha256) + handed = held.handoff["target"] + reported = (handed["key"], handed["version"]) == (DEFINITION_KEY, read.get("version_text")) + self.check("curator_read_the_reported_revision", reported) document, _, found = await self.until( lambda: self.call(CURATOR, "knowledge.get", source_uri=SOURCE_URI), is_found ) @@ -1407,8 +1488,9 @@ async def publication(self) -> None: """After the refused approval the reviewer reads the row again, compares it with the text it accepts and approves the hash of that read. The hash a refusal carried is never sent back unseen. A read that must show the curator's amendment - or the promotion is repeated until it does. The last read is of the shared copy - the promotion wrote.""" + or the promotion is repeated until it does. The reviewer then resolves the + report with the revision it published. The last read is of the shared copy the + promotion wrote.""" amended = self.fixture["curation.json"]["amended"] def read() -> Awaitable[dict[str, Any]]: @@ -1443,13 +1525,22 @@ def read() -> Awaitable[dict[str, Any]]: held.event, held.promote_request_id, held.published = event, request_id, published held.author, held.promoted_by = after.get("actor"), lineage.get("promoted_by") self.result["ids"]["promotion_events"].append(event) + resolved = await self.call( + REVIEWER, + "knowledge.reports.update", + report_id=held.report_id, + action="resolve", + resolution_revision=published["version"], + ) + closed = resolved.get("state") == "resolved" + self.check("report_resolved_with_the_published_revision", closed) self.entry()["copy"] = await self.shared_copy(amended) # ---- stage 8: evidence --------------------------------------------------------------- async def evidence(self) -> None: - """Read back, as the reporter, what Loom holds for each run and for the source - of the correction, and label every link between the stages.""" + """Read back, as the reporter, what Loom holds for each run, for the source of + the correction and for the report, and label every link between the stages.""" want = [DEFINITION_KEY, PROCEDURE_KEY] for name, run in self.result["runs"].items(): grade = self.fixture["expected.json"]["runs"][name]["grade"] @@ -1474,6 +1565,11 @@ async def evidence(self) -> None: ) linked = provenance.get("source_resource_id") == self.held.doc_id self.check("correction_names_the_source_document", linked) + named = {"report_id": self.held.report_id} + report = (await self.call(REPORTER, "knowledge.reports.get", **named)).get("report") or {} + resolution = (report.get("state"), report.get("resolution_revision")) + published = resolution == ("resolved", self.held.published["version"]) + self.check("report_names_the_published_revision", published) self.result["links"] = self.links() def links(self) -> list[dict[str, Any]]: @@ -1481,12 +1577,14 @@ def links(self) -> list[dict[str, Any]]: held, runs = self.held, self.result["runs"] run_1, run_2 = runs["run_1"]["run_id"], runs["run_2"]["run_id"] document = {"kind": "document", "source_uri": SOURCE_URI, "doc_id": held.doc_id} + report = {"kind": "report", "report_id": held.report_id} + report["resolution_revision"] = held.published["version"] review = {"kind": "promotion", "promotion_event": held.event} review.update(promoted_by=held.promoted_by, audit_request_id=held.promote_request_id) published = {name: value for name, value in held.published.items() if name != "read"} rows = [ ("problem", {"kind": "run", "run_id": run_1}, "loom"), - ("problem_to_correction", {"kind": "text", "field": "rationale"}, "client"), + ("problem_to_correction", report, "loom"), ("source_evidence", {**document, "revision": held.document_revision}, "loom"), ("correction", {**published, "author": held.author}, "loom"), ("review", review, "loom"), @@ -1496,7 +1594,7 @@ def links(self) -> list[dict[str, Any]]: ] reads = { "problem": "run.get: grade; memory.get: reflection:", - "problem_to_correction": "memory.lineage: rationale, text that names run 1", + "problem_to_correction": "knowledge.reports.get: state, resolution_revision", "source_evidence": "memory.provenance: source_resource_id; knowledge.get: doc_id", "correction": "memory.get: content_sha256, version_text, actor", "review": "memory.lineage: promoted_by, promotion_event; audit.list: actor", @@ -1515,9 +1613,6 @@ async def run(self) -> None: try: for name in STAGES: entry = self.entry(name) - if entry["status"] == "not_exercised": - say(f"{name}: not exercised (needs {entry['needs']})") - continue self.stage = name await self.run_stage(name, entry) # After preflight, so before the first write, and after every stage: diff --git a/sdk/python/examples/knowledge_factory_fixture/expected.json b/sdk/python/examples/knowledge_factory_fixture/expected.json index 7ea82ab2ce..0234bb68c4 100644 --- a/sdk/python/examples/knowledge_factory_fixture/expected.json +++ b/sdk/python/examples/knowledge_factory_fixture/expected.json @@ -98,8 +98,24 @@ }, { "stage": "report", - "status": "not_exercised", - "needs": "knowledge_reports" + "status": "passed", + "revision": { + "kind": "memory", + "namespace": "", + "key": "definition/active-account", + "version": "", + "sha256": "", + "read": "memory.get before the report" + }, + "handoff": { + "report_id": "", + "target": { + "kind": "memory", + "namespace": "", + "key": "definition/active-account", + "version": "" + } + } }, { "stage": "investigation", @@ -249,11 +265,12 @@ { "name": "problem_to_correction", "ref": { - "kind": "text", - "field": "rationale" + "kind": "report", + "report_id": "", + "resolution_revision": "" }, - "held_by": "client", - "read": "memory.lineage: rationale, text that names run 1" + "held_by": "loom", + "read": "knowledge.reports.get: state, resolution_revision" }, { "name": "source_evidence", @@ -335,9 +352,8 @@ }, "report": { "kind": "stage", - "exercised": false, - "gates_qualified": true, - "needs": "knowledge_reports" + "exercised": true, + "gates_qualified": true }, "investigation": { "kind": "stage", @@ -382,9 +398,8 @@ }, "repeated_report": { "kind": "criterion", - "exercised": false, - "gates_qualified": true, - "needs": "knowledge_reports" + "exercised": true, + "gates_qualified": true }, "interrupted_pass_retry": { "kind": "criterion", @@ -565,6 +580,55 @@ "detail": "", "request_id": "" }, + { + "name": "report_filed_open", + "stage": "report", + "passed": true, + "detail": "", + "request_id": "" + }, + { + "name": "second_submit_returns_the_same_report", + "stage": "report", + "passed": true, + "detail": "", + "request_id": "" + }, + { + "name": "report_taken_by_the_reviewer", + "stage": "report", + "passed": true, + "detail": "", + "request_id": "" + }, + { + "name": "resolve_before_publication_refused", + "stage": "report", + "passed": true, + "detail": "422 VALIDATION_FAILED", + "request_id": "" + }, + { + "name": "report_names_the_revision_that_was_read", + "stage": "report", + "passed": true, + "detail": "", + "request_id": "" + }, + { + "name": "report_unchanged_by_the_refused_resolve", + "stage": "report", + "passed": true, + "detail": "", + "request_id": "" + }, + { + "name": "curator_read_the_reported_revision", + "stage": "investigation", + "passed": true, + "detail": "", + "request_id": "" + }, { "name": "source_document_supports_the_correction", "stage": "investigation", @@ -782,6 +846,13 @@ "detail": "", "request_id": "" }, + { + "name": "report_resolved_with_the_published_revision", + "stage": "publication", + "passed": true, + "detail": "", + "request_id": "" + }, { "name": "run_2_first_result_governed", "stage": "run_2", @@ -879,11 +950,19 @@ "passed": true, "detail": "", "request_id": "" + }, + { + "name": "report_names_the_published_revision", + "stage": "evidence", + "passed": true, + "detail": "", + "request_id": "" } ], "ids": { "doc_id": "", - "promotion_events": ["", ""] + "promotion_events": ["", ""], + "report_id": "" }, "cleanup": "not_run" } diff --git a/tests/integration/test_sdk_example_knowledge_factory.py b/tests/integration/test_sdk_example_knowledge_factory.py index 2e562e97fe..33f5629a89 100644 --- a/tests/integration/test_sdk_example_knowledge_factory.py +++ b/tests/integration/test_sdk_example_knowledge_factory.py @@ -180,6 +180,11 @@ async def test_the_example_passes_against_a_live_server( # Nothing unreviewed was served as governed. assert passed["window_no_hit_governed"] and passed["window_reporter_blocked"] assert result["observations"]["approved_definition_served_during_review"] is False + # The report stage and the repeated report ran, and their checks passed. + exercised = [result["coverage"][name]["exercised"] for name in ("report", "repeated_report")] + assert exercised == [True, True] and result["stages"][3]["status"] == "passed" + assert passed["second_submit_returns_the_same_report"] + assert passed["resolve_before_publication_refused"] # One request id per call the stages sent. for entry in result["stages"]: if entry["status"] == "passed": @@ -235,6 +240,101 @@ async def test_the_reads_of_the_guide_show_what_the_result_says( assert (passed["grade"], passed["memories_used"]) == ("pass", used) +async def test_the_report_names_the_revision_read_and_the_revision_that_resolved_it( + example: ModuleType, first: Setup +) -> None: + """The report as Loom holds it once the run ended, read by the reviewer and by its + reporter: the revision it was filed against, its evidence, who took it and the + published revision that resolved it. The queue holds it once.""" + result = first.result + assert first.code == 0, [check for check in result["checks"] if not check["passed"]] + stages = {entry["stage"]: entry for entry in result["stages"]} + report_id = result["ids"]["report_id"] + run_1 = result["runs"]["run_1"]["run_id"] + published = stages["publication"]["revision"]["version"] + for who in ("reviewer", "reporter"): + got = (await first.call(who, "knowledge.reports.get", report_id=report_id))["report"] + assert (got["kind"], got["target_kind"]) == ("outdated", "memory"), who + assert got["target_key"] == example.DEFINITION_KEY, who + # The revision the reporter read: revision 1, as `memory.get` served its source row. + assert got["target_version_text"] == stages["report"]["revision"]["version"], who + assert got["target_version_text"] == stages["setup"]["revision"]["version"], who + assert got["problem"] == example.PROBLEM and got["run_id"] == run_1, who + assert got["evidence"] == [f"run:{run_1}", f"reflection:{run_1}"], who + assert (got["reporter"], got["assignee"]) == (SUBJECTS["reporter"], SUBJECTS["reviewer"]) + # Resolved with the revision the correction's promotion published, which is not + # the reported one: the target changed. + assert (got["state"], got["resolution_revision"]) == ("resolved", published), who + assert got["target_changed"] is True and got["target_readable"] is True, who + # Filed, taken and resolved: the repeat and the refused resolution wrote no version. + assert got["version"] == 3, who + assert stages["report"]["handoff"] == { + "report_id": report_id, + "target": { + "kind": "memory", + "namespace": TEAM, + "key": example.DEFINITION_KEY, + "version": stages["report"]["revision"]["version"], + }, + } + # The second submit filed no second report about the definition. + about = {"target_kind": "memory", "target_key": example.DEFINITION_KEY} + queue = (await first.call("reviewer", "knowledge.reports.list", **about))["reports"] + assert [(r["report_id"], r["state"]) for r in queue] == [(report_id, "resolved")] + # Only its reporter and an administrator read a report, and only an administrator + # reads the queue or changes a report: the curator holds `writer`. + hidden = await first.call("curator", "knowledge.reports.get", report_id=report_id) + assert hidden["found"] is False + reopen = {"report_id": report_id, "action": "reopen", "reason": "Not an administrator."} + for op, body in (("knowledge.reports.list", {}), ("knowledge.reports.update", reopen)): + refused = await first.send("curator", op, **body) + assert refused.status_code == 403, f"{op}: {refused.text}" + assert refused.json()["detail"]["code"] == "AUTH_INSUFFICIENT" + after = (await first.call("reviewer", "knowledge.reports.get", report_id=report_id))["report"] + assert (after["state"], after["version"]) == ("resolved", 3) + + +async def test_a_resolution_names_a_revision_newer_than_the_reported_one(first: Setup) -> None: + """What `knowledge.reports.update` checks for `resolve`, on a row of its own: the + refusal the example reads while the row is unchanged, and the limit the guide + names, that a newer revision resolves a report whether or not it was promoted.""" + key = "note/a-reported-note" + row = {"agent": "-", "memory_key": key} + await first.call("reviewer", "memory.set", **row, value={"note": "The first text."}) + read = await first.call("reporter", "memory.get", **row) + reported = read["version_text"] + filing = {"kind": "incorrect", "target_kind": "memory", "target_key": key} + filing.update(target_version=reported, target_sha256=read["content_sha256"]) + filed = await first.call( + "reporter", "knowledge.reports.submit", agent="-", problem="The note is wrong.", **filing + ) + resolve = {"report_id": filed["report_id"], "action": "resolve"} + + async def refusal(revision: str) -> str: + got = await first.send( + "reviewer", "knowledge.reports.update", **resolve, resolution_revision=revision + ) + assert got.status_code == 422, got.text + assert got.json()["detail"]["code"] == "VALIDATION_FAILED" + return str(got.json()["detail"]["message"]) + + said = await refusal(reported) + assert said == f"the target has no revision newer than reported revision {reported}" + unchanged = await first.call("reviewer", "knowledge.reports.get", report_id=filed["report_id"]) + assert (unchanged["report"]["state"], unchanged["report"]["version"]) == ("open", 1) + + # A writer's edit, which nobody reviewed or promoted, is a newer revision: a + # resolution must name it, and one that does is accepted. + await first.call("curator", "memory.set", **row, value={"note": "The second text."}) + edited = (await first.call("reviewer", "memory.get", **row))["version_text"] + assert int(edited) > int(reported) + assert await refusal(reported) == f"readers are served revision {edited}, not {reported}" + done = await first.call( + "reviewer", "knowledge.reports.update", **resolve, resolution_revision=edited + ) + assert (done["state"], done["version"]) == ("resolved", 2) + + async def test_the_fresh_run_is_served_the_published_revision( example: ModuleType, first: Setup, ch_client: Any ) -> None: diff --git a/tests/knowledge_factory_example.py b/tests/knowledge_factory_example.py index f94bc7bfdd..b2bb3f1d91 100644 --- a/tests/knowledge_factory_example.py +++ b/tests/knowledge_factory_example.py @@ -11,9 +11,9 @@ EXAMPLE = Path(__file__).resolve().parents[1] / "sdk/python/examples/knowledge_factory.py" -# The values that differ between two runs: ids, names, the address, hashes, versions and -# waits. The hits of the review window are an observation of the ordinary legs, which -# depend on the embedder. +# The values that differ between two runs: ids, names, the address, hashes, versions, +# the revision a report was resolved with and waits. The hits of the review window are +# an observation of the ordinary legs, which depend on the embedder. VOLATILE = frozenset( { "id", @@ -26,6 +26,8 @@ "version", "sha256", "run_id", + "report_id", + "resolution_revision", "doc_id", "promotion_event", "promotion_events", diff --git a/tests/unit/test_sdk_example_knowledge_factory.py b/tests/unit/test_sdk_example_knowledge_factory.py index 2a43dad0b9..cad3d5e8b9 100644 --- a/tests/unit/test_sdk_example_knowledge_factory.py +++ b/tests/unit/test_sdk_example_knowledge_factory.py @@ -43,6 +43,7 @@ "memory.definitions.list", "memory.lineage", "knowledge.get", + "knowledge.reports.get", "run.get", "run.reliance", "audit.list", @@ -149,8 +150,8 @@ def __init__(self) -> None: # the shared scope still read the search document of the promotion before. self.search_documents_late = 0 self.erasure: dict[str, Any] = {"status": "completed", "residue_count": 0} - tables = ("namespaces", "grants", "rows", "shared", "documents", "runs", "erasures") - self.state: dict[str, Any] = {name: {} for name in tables} | {"audit": []} + tables = ("namespaces", "grants", "rows", "shared", "documents", "runs", "reports") + self.state: dict[str, Any] = {name: {} for name in (*tables, "erasures")} | {"audit": []} self.before = copy.deepcopy(self.state) self.lagging: dict[tuple[str, str], list[Any]] = {} # Above 2^53 and not a double: a reader that holds it as a number rounds it. @@ -461,6 +462,88 @@ def on_knowledge_get(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: found = self.state["documents"].get(body["namespace"] + "|" + body["source_uri"]) return 200, {"found": found is not None, **(found or {})} + # ---- reports ----------------------------------------------------------------------- + + def cited(self, namespace: str, ref: str) -> bool: + """Whether a reference names a run of the namespace or a reflection it holds.""" + kind, _, ident = ref.partition(":") + if kind == "run": + return self.state["runs"].get(ident, {}).get("namespace") == namespace + rows = self.state["rows"].items() + held = any(k.startswith(namespace + "|") and r["memory_key"] == ref for k, r in rows) + return kind == "reflection" and held + + def on_knowledge_reports_submit(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: + basis = [body[name] for name in ("namespace", "kind", "target_key", "problem")] + if "a second submit files a second report" in self.wrong: + basis.append(call["request_id"]) + report_id = sha256(json.dumps([who["sub"], *basis]).encode()).hexdigest()[:32] + reports = self.state["reports"] + if report_id not in reports: + # A first filing names the row as `memory.get` serves it now, and references + # its reporter reads. + row = self.row({**body, "memory_key": body["target_key"]}) + if row is None: + return 404, refusal("RESOURCE_NOT_FOUND") + read = (int(body["target_version"]), body["target_sha256"]) + if read != (row["version"], row["content_sha256"]): + return 409, refusal("PRECONDITION_FAILED") + # The body's `run_id` is cited too, as sent: the SDK's "-" names no run. + refs = [*body["evidence"], "run:" + body["run_id"]] + if not all(self.cited(body["namespace"], ref) for ref in refs): + return 422, refusal("VALIDATION_FAILED") + report = {"report_id": report_id, "version": 1, "state": "open", "kind": body["kind"]} + report.update({name: body[name] for name in ("namespace", "agent", "problem")}) + report.update(target_kind=body["target_kind"], target_key=body["target_key"]) + report.update(target_version=row["version"], evidence=list(body["evidence"])) + report.update(reporter=who["sub"], assignee="", resolution_revision="") + reports[report_id] = report + held = reports[report_id] + return 200, {name: held[name] for name in ("report_id", "state", "version")} + + def reported(self, report: dict[str, Any]) -> Any: + """The row a report is about, as it is now.""" + key = {"namespace": report["namespace"], "memory_key": report["target_key"]} + return self.row(key, agent=report["agent"]) + + def on_knowledge_reports_get(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: + held = self.state["reports"].get(body["report_id"]) + if held is None or held["namespace"] != body["namespace"]: + return 200, {"found": False} + # A report is read by its reporter and by the namespace's administrators. + if held["reporter"] != who["sub"] and self.role(who, body["namespace"]) < RANK["admin"]: + return 200, {"found": False} + row = self.reported(held) + shown = {name: value for name, value in held.items() if name not in ("namespace", "agent")} + shown["target_version_text"] = str(held["target_version"]) + shown["target_changed"] = row is None or row["version"] != held["target_version"] + return 200, {"found": True, "report": shown} + + def on_knowledge_reports_update(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: + held = self.state["reports"].get(body["report_id"]) + if held is None or held["namespace"] != body["namespace"]: + return 404, refusal("RESOURCE_NOT_FOUND") + if held["state"] == "resolved": + return 422, refusal("VALIDATION_FAILED") + if body["action"] == "resolve": + # A resolution names the revision readers are served now, which is newer + # than the reported one. + reported, served = held["target_version"], self.reported(held)["version"] + unrevised = served <= reported and "a resolve needs no newer revision" not in self.wrong + if unrevised or int(body["resolution_revision"]) != served: + if "a refused resolve resolves" in self.wrong: + held.update(state="resolved", version=held["version"] + 1) + said = f"the target has no revision newer than reported revision {reported}" + if not unrevised: + said = f"readers are served revision {served}" + return 422, refusal("VALIDATION_FAILED", message=said) + held.update(state="resolved", resolution_revision=body["resolution_revision"]) + else: + held.update(state="taken", assignee=who["sub"]) + held["version"] += 1 + self.audited("knowledge.reports.update", who, call) + return 200, {name: held[name] for name in ("report_id", "state", "version")} + def on_run_begin(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: run_id = uuid.UUID(self.new_id()).hex run = {"namespace": body["namespace"], "status": "active", "grade": "", "searched": []} @@ -533,8 +616,9 @@ def on_erasure_request(self, who: Any, body: Any, call: Any) -> tuple[int, Any]: for table in ("rows", "shared", "documents"): kept = self.state[table].items() self.state[table] = {k: v for k, v in kept if not k.startswith(namespace + "|")} - runs = self.state["runs"].items() - self.state["runs"] = {k: v for k, v in runs if v["namespace"] != namespace} + for table in ("runs", "reports"): + kept = self.state[table].items() + self.state[table] = {k: v for k, v in kept if v["namespace"] != namespace} erasure_id = self.new_id() self.state["erasures"][erasure_id] = {"namespace": namespace, **self.erasure} return 200, {"erasure_id": erasure_id, **self.erasure} @@ -657,7 +741,7 @@ async def test_the_result_equals_the_expected_document( assert json.loads(printed.out) == result first, *_, last = printed.err.splitlines() assert "checks Loom's contract" in first and "does not measure an agent" in first - assert last == "8 of 16 coverage entries exercised; qualified: false" + assert last == "10 of 16 coverage entries exercised; qualified: false" async def test_coverage_has_one_source_and_qualified_follows_the_gating_entries( @@ -669,10 +753,8 @@ async def test_coverage_has_one_source_and_qualified_follows_the_gating_entries( checked = {check["stage"] for check in result["checks"]} for name, entry in kf.COVERAGE.items(): if entry["kind"] == "stage": - assert name in staged - assert (name in checked) == entry["exercised"] - status = stage(result, name)["status"] - assert (status == "not_exercised") == (not entry["exercised"]) + # Every stage runs, so its entry reads exercised and it holds checks. + assert entry["exercised"] and name in staged and name in checked if not entry["exercised"]: assert entry["needs"] assert "control_unaffected_by_the_correction" in checks(result) @@ -797,6 +879,7 @@ async def test_a_refusal_a_grade_and_the_window_search_carry_their_request_id( "window_no_hit_governed": server.ops("memory.search", REPORTER)[1], "reviewer_cannot_accept_its_own_proposal": server.ops(DECIDE, REVIEWER)[2], "run_1_graded_once": server.ops("run.grade")[0], + "resolve_before_publication_refused": server.ops(UPDATE)[1], "promotion_audited_to_the_reviewer": server.ops("memory.promote", REVIEWER)[2], } for name, call in decided.items(): @@ -813,10 +896,14 @@ async def test_versions_survive_a_reader_that_holds_numbers_as_doubles( revisions += [entry["copy"] for entry in result["stages"] if "copy" in entry] revisions += [run["control"]["revision"] for run in result["runs"].values()] revisions += [link["ref"] for link in result["links"] if "version" in link["ref"]] + revisions.append(stage(result, "report")["handoff"]["target"]) versions = [found["version"] for found in revisions if isinstance(found, dict)] + by_name = {link["name"]: link["ref"] for link in result["links"]} + versions.append(by_name["problem_to_correction"]["resolution_revision"]) # The two a run was served are among them: `run.reliance` answers decimal text. So - # are the two copies, whose version a search hit holds as a number. - assert len(versions) == 11 and all(isinstance(version, str) for version in versions) + # are the two copies, whose version a search hit holds as a number, and the two a + # report holds: the one it was filed against and the one that resolved it. + assert len(versions) == 14 and all(isinstance(version, str) for version in versions) as_doubles = json.loads(json.dumps(result), parse_int=float) assert as_doubles["stages"] == result["stages"] and as_doubles["links"] == result["links"] # As a number, the same version would not survive the round trip. @@ -1444,6 +1531,114 @@ async def test_no_request_holds_a_figure_of_the_numbers_source( assert numbers_in(["a1200", "1200-b", "0000-1200", "1200.5", "1.2.3", True]) == {"1200.5"} +# ---- the report ---------------------------------------------------------------------------- + + +async def test_the_report_names_the_revision_that_was_read( + kf: ModuleType, server: ScriptedLoom, tmp_path: Path +) -> None: + code, result = await run(kf, tmp_path / "result.json") + assert code == 0 and result["coverage"]["report"]["exercised"] is True + filed = stage(result, "report") + # The reporter reads the source row by key and files against that read: revision 1, + # which run 1 failed on, with its version as decimal text and the hash the read + # answered. A governed hit carries neither. + reads = [ + (c["body"]["agent"], c["body"]["memory_key"]) + for c in server.ops("memory.get", REPORTER) + if c["request_id"] in filed["request_ids"] + ] + assert reads == [("-", kf.DEFINITION_KEY)] + assert filed["revision"]["read"] == "memory.get before the report" + read = {name: filed["revision"][name] for name in ("version", "sha256")} + assert read == {name: stage(result, "setup")["revision"][name] for name in read} + first = server.ops(SUBMIT)[0] + sent = first["body"] + assert (first["subject"], sent["agent"], sent["kind"]) == (REPORTER, "-", "outdated") + assert (sent["target_kind"], sent["target_key"]) == ("memory", kf.DEFINITION_KEY) + assert (sent["target_version"], sent["target_sha256"]) == (read["version"], read["sha256"]) + # As a number, the version would not survive a reader that holds doubles. + assert int(float(int(sent["target_version"]))) != int(sent["target_version"]) + # The evidence is two references, to the run that failed and to its reflection; the + # problem is what the reporter saw, with no column name and no figure. + run_1 = result["runs"]["run_1"]["run_id"] + assert sent["evidence"] == [f"run:{run_1}", f"reflection:{run_1}"] + # The run is named in the body as well: unset, the SDK sends "-", which names no run. + assert sent["run_id"] == run_1 and first["run"] == "" + reflection = server.ops("run.complete")[0]["body"]["reflection"] + assert sent["problem"] == reflection["what_failed"][0] + assert "active_accounts" not in sent["problem"] and "active_users" not in sent["problem"] + assert not re.search(r"\d", sent["problem"]) and "suggested_correction" not in sent + + # The reviewer takes the report, reads it and hands the curator the target it names + # and its id. The curator holds `writer`: it calls no report op and reads the row. + stored = report(server) + assert result["ids"]["report_id"] == stored["report_id"] + names = {"kind": "memory", "namespace": TEAM, "key": kf.DEFINITION_KEY} + handed = {"report_id": stored["report_id"], "target": {**names, "version": read["version"]}} + assert filed["handoff"] == handed and stored["assignee"] == REVIEWER + callers = {c["subject"] for c in server.calls if c["op"].startswith("knowledge.reports.")} + assert callers == {REPORTER, REVIEWER} + assert {c["subject"] for c in server.ops(UPDATE)} == {REVIEWER} + assert checks(result)["curator_read_the_reported_revision"] is True + + # The report ends resolved with the revision the promotion published, which Loom + # holds as the link from the problem to its correction. + published = stage(result, "publication")["revision"]["version"] + assert (stored["state"], stored["resolution_revision"]) == ("resolved", published) + link = next(link for link in result["links"] if link["name"] == "problem_to_correction") + ref = {"kind": "report", "report_id": stored["report_id"], "resolution_revision": published} + assert (link["ref"], link["held_by"]) == (ref, "loom") + last = server.ops("knowledge.reports.get")[-1] + assert last["subject"] == REPORTER + assert last["request_id"] in stage(result, "evidence")["request_ids"] + + +async def test_a_second_submit_returns_the_same_report( + kf: ModuleType, server: ScriptedLoom, tmp_path: Path +) -> None: + code, result = await run(kf, tmp_path / "result.json") + assert code == 0 + first, second = server.ops(SUBMIT) + # The same request under another request id: the report's id alone makes the repeat + # the same report. + assert first["body"] == second["body"] and first["request_id"] != second["request_id"] + assert first["subject"] == second["subject"] == REPORTER + assert list(server.state["reports"]) == [result["ids"]["report_id"]] + assert checks(result)["second_submit_returns_the_same_report"] is True + exercised = {"kind": "criterion", "exercised": True, "gates_qualified": True} + assert result["coverage"]["repeated_report"] == exercised + # The repeat precedes the take, so its answer is the first one's. + assert server.calls.index(second) < server.calls.index(server.ops(UPDATE)[0]) + + +async def test_a_resolve_before_publication_is_refused( + kf: ModuleType, server: ScriptedLoom, tmp_path: Path +) -> None: + code, result = await run(kf, tmp_path / "result.json") + assert code == 0 + take, early, resolve = server.ops(UPDATE) + assert [c["body"]["action"] for c in (take, early, resolve)] == ["take", "resolve", "resolve"] + # The early resolution names the only revision there is, the reported one, before + # the curator writes a candidate. + filed = stage(result, "report") + assert early["request_id"] in filed["request_ids"] + assert early["body"]["resolution_revision"] == filed["revision"]["version"] + assert server.calls.index(early) < server.calls.index(server.ops(SET, CURATOR)[0]) + refused = next(c for c in result["checks"] if c["name"] == "resolve_before_publication_refused") + assert (refused["passed"], refused["detail"]) == (True, "422 VALIDATION_FAILED") + # The refusal changed nothing: the report the reviewer then read was still taken. + assert checks(result)["report_unchanged_by_the_refused_resolve"] is True + # The resolution follows the promotion of the amended text and names the revision + # `memory.get` served after it. + promoted = server.ops(PROMOTE, REVIEWER)[2] + assert server.calls.index(promoted) < server.calls.index(resolve) + published = stage(result, "publication")["revision"]["version"] + assert resolve["body"]["resolution_revision"] == published != filed["revision"]["version"] + assert resolve["request_id"] in stage(result, "publication")["request_ids"] + assert checks(result)["report_resolved_with_the_published_revision"] is True + + # ---- the reporter's namespace ------------------------------------------------------------ @@ -1499,6 +1694,10 @@ async def test_writes_are_sent_once(kf: ModuleType, server: ScriptedLoom, tmp_pa "run.begin": 2, "run.complete": 2, "run.grade": 2, + # The report and its repeat, which files nothing. + SUBMIT: 2, + # The take, the resolution refused before the correction, and the resolution. + UPDATE: 3, } assert {op: len(server.ops(op)) for op in once} == once promoted = [c["body"]["approved_sha256"] for c in server.ops("memory.promote", REVIEWER)] @@ -1556,7 +1755,7 @@ async def test_a_write_answered_by_a_page_is_not_accepted_and_not_sent_again( assert stage(result, stopped)["detail"] == f"{what}: INVALID_RESPONSE" assert len(server.ops(op)) == call and not server.ops("run.grade") later = kf.STAGES[kf.STAGES.index(stopped) + 1 :] - assert {stage(result, name)["status"] for name in later} <= {"not_run", "not_exercised"} + assert {stage(result, name)["status"] for name in later} <= {"not_run"} async def test_the_grade_is_sent_once_after_the_run_closed( @@ -1568,9 +1767,10 @@ async def test_the_grade_is_sent_once_after_the_run_closed( assert code == 0 run_1 = result["runs"]["run_1"]["run_id"] order = [c["op"] for c in server.calls if c["body"].get("run_id") == run_1] - # The reliance read follows the grade, and the evidence stage reads the run last. + # The reliance read follows the grade, the report and its repeat name the graded + # run, and the evidence stage reads the run last. closed = ["run.complete", "run.get", "run.get", "run.get", "run.grade"] - assert order == [*closed, "run.reliance", "run.get"] + assert order == [*closed, "run.reliance", SUBMIT, SUBMIT, "run.get"] assert len(server.ops("run.grade")) == 2 and checks(result)["run_1_graded_once"] is True graded = server.ops("run.grade")[0]["body"] assert (graded["grade"], graded["source"]) == ("fail", "fixture-grader") @@ -1594,9 +1794,12 @@ async def test_a_positive_read_is_repeated_until_it_shows_the_write( # revision 1, 2 the personal request, 3 the candidate and 5 the amendment. # `memory.promote` 1 is the first publication, 3 the reporter's refused one and 5 the # approval of the amended text. `memory.proposal_decide` 2 rejects and 3 accepts. -# `run.complete` 1 closes run 1 and `run.grade` 2 grades run 2. +# `run.complete` 1 closes run 1 and `run.grade` 2 grades run 2. The two +# `knowledge.reports.get` reads have no row: Loom reads a report with sequential +# consistency, so the read shows the last acknowledged change without a wait. REGISTER, SET = "namespace.register", "memory.set" PROMOTE, DECIDE = "memory.promote", "memory.proposal_decide" +SUBMIT, UPDATE = "knowledge.reports.submit", "knowledge.reports.update" LAGS: list[tuple[str, tuple[str, int], tuple[str, int], str, str]] = [ ("own namespace", (REGISTER, 1), (REGISTER, 1), REPORTER, "namespace.get"), ("own grant", (REGISTER, 1), (REGISTER, 1), REPORTER, "grants.list"), @@ -1605,6 +1808,7 @@ async def test_a_positive_read_is_repeated_until_it_shows_the_write( ("first verdict", (PROMOTE, 1), (PROMOTE, 1), REVIEWER, "memory.definitions.list"), ("first copy", (PROMOTE, 1), (PROMOTE, 1), REVIEWER, "memory.search"), ("personal request", (SET, 2), (SET, 2), REPORTER, "memory.get"), + ("revision 1 before the report", (SET, 1), ("run.grade", 1), REPORTER, "memory.get"), ("candidate", (SET, 3), (SET, 3), CURATOR, "memory.get"), ("lapse", (SET, 3), (SET, 3), REVIEWER, "memory.definitions.list"), ("lapse after the refusals", (SET, 3), (PROMOTE, 3), REVIEWER, "memory.definitions.list"), @@ -1784,6 +1988,11 @@ def shared(loom: ScriptedLoom) -> dict[str, Any]: return next(iter(loom.state["shared"].values())) +def report(loom: ScriptedLoom) -> dict[str, Any]: + """The one report.""" + return next(iter(loom.state["reports"].values())) + + def document(loom: ScriptedLoom) -> dict[str, Any]: return next(iter(loom.state["documents"].values())) @@ -1949,6 +2158,51 @@ def never_traced(loom: ScriptedLoom) -> None: wrong("a governed hit's receipt names the source row"), {"run_1_served_the_published_copy"}, ), + ( + "the report is filed in another state", + answers(SUBMIT, 1, report_id="0" * 32, state="taken", version=1), + {"report_filed_open"}, + ), + ( + "a second submit files a second report", + wrong("a second submit files a second report"), + {"second_submit_returns_the_same_report"}, + ), + ( + "the reviewer's take leaves the report open", + answers(UPDATE, 1, report_id="0" * 32, state="open", version=2), + {"report_taken_by_the_reviewer"}, + ), + ( + "a resolution is accepted while the target holds no newer revision", + wrong("a resolve needs no newer revision"), + {"resolve_before_publication_refused"}, + ), + ( + "the early resolution is refused for a reason that names no revision", + lambda loom: loom.script.update({(UPDATE, 2): coded(422, "VALIDATION_FAILED")}), + {"resolve_before_publication_refused"}, + ), + ( + "the report holds another revision than the one its reporter read", + after(SUBMIT, 1, edit(report, target_version=1)), + {"report_names_the_revision_that_was_read"}, + ), + ( + "the report holds no evidence", + after(SUBMIT, 1, edit(report, evidence=[])), + {"report_names_the_revision_that_was_read"}, + ), + ( + "a refused resolution resolves the report", + wrong("a refused resolve resolves"), + {"report_unchanged_by_the_refused_resolve"}, + ), + ( + "the definition changes between the report and the curator's read", + after("knowledge.reports.get", 1, edit(DEFINITION, version=1)), + {"curator_read_the_reported_revision"}, + ), ( "the source document holds another text", after("knowledge.upsert", 1, edit(document, content="Another text.")), @@ -2090,6 +2344,11 @@ def never_traced(loom: ScriptedLoom) -> None: after("memory.promote", 5, audited_to_another), {"promotion_audited_to_the_reviewer"}, ), + ( + "the resolution leaves the report taken", + answers(UPDATE, 3, report_id="0" * 32, state="taken", version=3), + {"report_resolved_with_the_published_revision"}, + ), ( "run 2 is served no governed hit", after("run.begin", 2, unpublish), @@ -2146,8 +2405,10 @@ def never_traced(loom: ScriptedLoom) -> None: {"run_1_evidence_read", "run_2_evidence_read"}, ), ( + # Dropped once the report that cites it is filed: a report whose reflection is + # gone is refused, which stops the run before the evidence stage reads it. "the reflection of run 1 is not kept", - after("run.complete", 1, drop_the_reflection), + after(SUBMIT, 2, drop_the_reflection), {"problem_recorded_by_the_reporter"}, ), ( @@ -2155,6 +2416,11 @@ def never_traced(loom: ScriptedLoom) -> None: after("memory.promote", 5, edit(DEFINITION, source_resource_id="")), {"correction_names_the_source_document"}, ), + ( + "the resolved report names another revision than the published one", + after(UPDATE, 3, edit(report, resolution_revision="1")), + {"report_names_the_published_revision"}, + ), ] @@ -2234,7 +2500,7 @@ async def test_a_403_that_is_not_looms_is_no_role_refusal( assert (exit_code, stage(result, stopped)["detail"]) == (code, said) assert {c["name"]: c["detail"] for c in result["checks"] if not c["passed"]} == failed later = kf.STAGES[kf.STAGES.index(stopped) + 1 :] - assert {stage(result, name)["status"] for name in later} <= {"not_run", "not_exercised"} + assert {stage(result, name)["status"] for name in later} <= {"not_run"} async def test_a_probe_miss_calls_admitted_only_a_call_that_was_not_refused( @@ -2283,6 +2549,7 @@ async def test_a_second_cleanup_sends_no_erasure( "preflight", "setup", "run_1", + "report", "investigation", "review", "publication", @@ -2299,9 +2566,7 @@ async def test_cleanup_after_a_stop_at_each_stage( monkeypatch: pytest.MonkeyPatch, stopped: str, ) -> None: - assert [ - name for name in kf.STAGES if kf.COVERAGE.get(name, {"exercised": True})["exercised"] - ] == STOPS + assert list(kf.STAGES) == STOPS async def stop(self: Any) -> None: raise kf.Stop("failed", "stopped by the test")