From 1f10b486604a77a8245df2485d64d7dc6f56bf6a Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 08:54:59 +0000 Subject: [PATCH 1/3] A curator draft is a private review candidate a person accepts by hash A drafted answer is text no person has read, so it is stored as a candidate of the learnings review queue with source_kind curator_draft, which only the namespace's administrators list, count or decide. No memory read path changes. learnings.list serves an administrator the draft's content_sha256 and its evidence pointer. learnings.review promotes it only for a person who administers the namespace and sends that hash as approved_sha256; a service account may reject. The promotion writes the curator's namespace-wide row through memory.set with the reviewer as actor, source_class derived, source_trace curator:, the absent precondition, and grounding and evidence set through two private attributes no request body reaches. A decided draft takes no other decision, and a promotion that stopped after its write completes on a repeat. Migration 139 adds loom.learnings_queue.evidence. Review of the kind waits for every live replica to have it, because an older build lists the kind to viewers. Redacting the fact a draft became blanks its candidate, found by the row's source_trace. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/curator.md | 71 +++ docs/architecture/rolling-upgrades.md | 21 + docs/features/memory/writing.md | 10 + docs/guides/without-the-dashboard.md | 1 + docs/operations/upgrades.md | 6 +- docs/reference/operations/learnings.md | 5 +- .../migrations/139_curator_draft_evidence.sql | 10 + schemas/schema.sql | 3 +- sdk/go/wire/models.gen.go | 53 +- sdk/python/loom/learnings.py | 6 + sdk/python/loom/ops.py | 4 + sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 2 +- sdk/rust/src/wire_models.rs | 21 + sdk/typescript/src/generated/ops.ts | 3 + server/memory/api/models_crud.py | 6 + server/memory/api/models_learnings.py | 30 +- server/memory/app/curator_draft_review.py | 145 +++++ server/memory/app/definition_queue.py | 4 +- server/memory/app/definition_review.py | 47 +- server/memory/app/learning_access.py | 11 +- server/memory/app/learnings.py | 178 +++--- server/memory/app/write.py | 4 + server/memory/domain/definitions.py | 10 + server/memory/store/history.py | 6 +- server/memory/store/learnings.py | 28 +- server/memory/store/pg_memory.py | 2 +- server/transport/mcp_descriptions.py | 10 +- tests/analyzer/shapes.txt | 14 +- .../test_curator_draft_candidate.py | 311 +++++++++++ tests/unit/snapshots/sdk_public_api.json | 3 +- tests/unit/test_curator_draft_candidate.py | 515 ++++++++++++++++++ tests/unit/test_definition_draft_redaction.py | 1 + tests/unit/test_definition_queue_erasure.py | 2 + tests/unit/test_schema_baseline.py | 1 + tests/unit/test_sdk_learnings_client.py | 13 + 35 files changed, 1399 insertions(+), 158 deletions(-) create mode 100644 schemas/migrations/139_curator_draft_evidence.sql create mode 100644 server/memory/app/curator_draft_review.py create mode 100644 tests/integration/test_curator_draft_candidate.py create mode 100644 tests/unit/test_curator_draft_candidate.py diff --git a/docs/architecture/curator.md b/docs/architecture/curator.md index bfbaee32f1d..634a0b94fb9 100644 --- a/docs/architecture/curator.md +++ b/docs/architecture/curator.md @@ -514,6 +514,71 @@ Each entry is the answer of one function of `server/memory/app/curator_gates.py` - The model step has two conditions that are not entries: a mode of `assist`, which the `mode` field says, and a namespace whose name is not reserved, which no setting changes. - The command line and the **Curator** tab list an unmet entry only where the stored mode needs it: none while the mode is `off`, the `pass` entries in any other mode, and the `opinions` entries in `assist`. The settings dialog, where an admin is choosing `assist`, lists every unmet entry but `mode`. +## Drafted answers + +A draft is an answer the curator wrote to a question several people asked, from one shared document. Until a person accepts it, it is text nobody has reviewed, so only the namespace's administrators read it. It is stored as a candidate of the [learnings review queue](../features/memory/procedures-and-learnings.md#learnings-review-queue) with `source_kind` `curator_draft`, and never as a memory row: no memory read, search or count holds it, and `memory.proposals` does not list it, because the proposal policy, the advice and the suite checks judge proposals and a draft is judged on the document it cites. This section describes the candidate, its review and the fact it becomes. No pass writes a draft. + +### The candidate + +| Column | Holds | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `memory_key` | The key the fact is written under, `curator/gap/`. | +| `proposed_value` | The drafted answer. | +| `source_resource_id` | The gap the draft answers. | +| `evidence` | A pointer as JSON, never a quote or a passage: the `kind`, `key`, `version` and `sha256` of the shared document the draft cites, the keys to `recheck`, the `run_id` of the pass that drafted it, and the draft it is a `redraft_of`. | + +`learnings.list` lists a draft only to a caller with the admin role on the namespace. For every other caller the row is absent from the list and from the counts of `learnings.quality`, and `memory.lineage` names no such candidate. The filter is part of each statement, so it applies before a limit or a count. An administrator's entry carries `content_sha256`, the server's hash of the drafted answer, and `evidence`, the pointer. An administrator whose grant is revoked stops reading drafts when the replica's grant cache refreshes, as for every read that needs the admin role. + +### The review + +`learnings.review` decides a draft. The operation needs the admin role, and a draft answers 404 `RESOURCE_NOT_FOUND` to a caller the namespace does not admit as an administrator, as a candidate that does not exist does. + +| Decision | Who | What it needs | +| --------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `promote` | A person who administers the namespace, signed in under their own name. | `approved_sha256` equal to the `content_sha256` the list served. An empty or different hash answers 409 `PRECONDITION_FAILED`, which does not return the stored hash. `destination` is `memory` or unset. | +| `reject` | Any caller with the admin role on the namespace, a service account included. | Nothing: `approved_sha256` is ignored. | + +- A service account that promotes is refused with 403 `AUTH_INSUFFICIENT`. +- One review of a draft runs at a time: a second answers 503 `OVERLOADED` while the first holds the draft's claim. +- A draft is decided once. A decided draft answers its status to a repeat of the same decision and 409 `PRECONDITION_FAILED` to the other one. Its `promoted` or `rejected` row is what records that the question was drafted, and a later draft of the same question is a new candidate that names it in `redraft_of`. +- A refusal writes nothing. + +### The fact + +A promotion writes the draft through `memory.set` as the curator's namespace-wide row and then records the decision: + +| Field | Value | +| ----------------------- | -------------------------------------------------------------------------------------- | +| Identity | `(org, namespace, loom-curator, -, -)` under the draft's `memory_key`, type `semantic` | +| `actor` | The reviewer, from the review's token: accepting the draft is the reviewer's write. | +| `source_class` | `derived` | +| `source_trace` | `curator:` | +| `source_resource_id` | The `key` of the cited document. | +| `grounding`, `evidence` | `verbatim` and the draft's pointer. No request body can set either column. | +| Precondition | `if_match_sha256: absent`: the write lands only where no live row holds the key. | + +A refusal of the write leaves the draft pending: a row now under the key (409 `PRECONDITION_FAILED`), a blacklisted value, or a conflict with a pinned fact. A review that stopped after the write and before the decision row completes on a repeat: a live row of the curator that carries the draft's trace and content hash is taken as written, and the repeat records the decision without a second write. Rejecting a draft writes no memory. + +### Redaction and erasure + +Redacting a version of the fact a draft became blanks that draft's candidate: its `proposed_value`, `rationale`, `decision_reason` and `evidence` in every version. The candidate is the one the row's `source_trace` names, read by id, whatever key the fact holds by then. A blanked draft answers `learnings.review` as a missing candidate does. A namespace erasure deletes every row of the namespace in `loom.learnings_queue`, drafts of every status included, in its `learnings_queue.delete` step. A candidate row of a private kind is written under the lease that step takes, so a write and the deletion never overlap. + +### Rolling back + +A build without drafts lists a `curator_draft` candidate, with its text, to every viewer of the namespace. So `learnings.review` of a draft answers 503 `OVERLOADED` until every live replica has the migration that adds `evidence` ([rolling upgrades](rolling-upgrades.md), rule 102), and a rollback below this build is not supported while a `curator_draft` row of any status exists. Rejecting the drafts does not make a rollback safe: a rejection keeps the draft's text on its status row. Before a rollback: + +1. Set `curator_mode` to `off` in every namespace, and let the reviews in flight end. +2. Delete the drafts, and check that none is left: + + ```sql + ALTER TABLE loom.learnings_queue DELETE WHERE source_kind = 'curator_draft' SETTINGS mutations_sync = 2; + SELECT count() FROM loom.learnings_queue WHERE source_kind = 'curator_draft'; + ``` + +3. Roll back. + +A fact a draft became is an ordinary memory row. It stays, and the older build serves it as it serves any fact. + ## Source entry points - `server/memory/api/ops_curator.py` (`curator_status`), `server/memory/api/models_curator.py`: the operation and its wire models. @@ -544,6 +609,9 @@ Each entry is the answer of one function of `server/memory/app/curator_gates.py` - `server/memory/app/curator_opinions.py` (`run_step`, `current_opinions`, `hash_prefix`): the model step, the opinions `curator.status` serves and the keyed prefix. - `server/memory/domain/curator_prompts.py` (`PROMPT_VERSION`, `OPINION_SYSTEM`, `opinion_user`, `parse_opinion`): the prompt, the two sets of codes with their titles, and the parse of an answer. - `server/memory/store/curator.py` (`opinion_rows`, `opinion_texts`): the proposals a model may be sent, and their cut text. +- `server/memory/domain/definitions.py` (`CURATOR_DRAFT_KIND`, `PRIVATE_CANDIDATE_KINDS`, `CURATOR_DRAFT_MIGRATION`): the kind of a draft, the candidates only an administrator reads, and the number of the migration that adds `evidence`. +- `server/memory/app/curator_draft_review.py` (`require_acceptance`, `fact`, `written`): who may accept a draft, the fact an acceptance writes, and the repeat that finds it written. `server/memory/app/learnings.py` (`handle_learnings_review`): the review. +- `server/memory/app/definition_review.py` (`redact_candidates`): the candidate a redaction blanks. - `server/memory/domain/curator.py` (the `MODEL_` codes, `OPINIONS_A_PASS`, `OPINION_START_SECONDS`, `OPINION_LOOKBACK_ROWS`, `OPINION_TEXT_MAX`, `OPINION_CALL_SECONDS`, `OPINION_FAILURES_STOP`): the gates' codes and the bounds of the model step. ## Invariants @@ -559,6 +627,9 @@ Each entry is the answer of one function of `server/memory/app/curator_gates.py` - An opinion is a verdict and a reason from closed sets. It changes no advice, no count and no decision, and no code reads it but `curator.status`. - An opinion is served only on the content the model read, and a stored opinion holds no value and no plain content hash. - An opinion is readable by whoever can read the proposal: the pass row that stores it is a run every viewer of the namespace may read, and the Runs page shows its metadata. The **Proposals** tab shows it to administrators because `curator.status` is an ADMIN op. +- A draft is read by the namespace's administrators only, in every status, and answers as a missing candidate to everyone else. +- A draft becomes a fact only when a person who administers the namespace accepts the hash of the text they were served. The fact's `actor` is that reviewer, and its `source_class` is `derived`. The curator performs no belief-revision verb: the promotion is the reviewer's Expand. +- A draft's `evidence` holds a pointer and no text of the document it cites. - A prerequisite is read by one function, which the worker, the model step and `curator.status` all call, and one that cannot be read is not met. - A pass reads one namespace, and its row carries the identity `(org, namespace, loom-curator, -, -)`. - A pass does not run when the fleet is not at the mode's migration, the classification cannot be read or the lease is held, and it keeps no count when the erasure ledger cannot be read. diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 3076c199a51..8bdf2477da6 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1668,6 +1668,27 @@ 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 curator's draft in the review queue** (`evidence` on `loom.learnings_queue`, + migration `139_curator_draft_evidence.sql`): N keeps a candidate of `source_kind` + `curator_draft` from everyone but the namespace's administrators in + `learnings.list`, `learnings.quality` and `memory.lineage`, and stores in + `evidence` a pointer to the document the draft cites. N-1 knows no such kind: it + lists the candidate, with its text, to every viewer of the namespace, counts it, + decides it on `learnings.review` as an ordinary candidate, with no person and no + hash, and writes a status row without `evidence`, which leaves the column's + default. So while any live replica, in every deployment sharing the database, has + a schema version below 139, or no heartbeat has been read, `learnings.review` of a + draft answers 503 `OVERLOADED` with `retry_after_s: 30`, and nothing writes the + kind. The gate protects the roll forward only. A rollback below N is not supported + while a `curator_draft` row of any status exists, and rejecting the drafts does not + make it safe, because a rejection keeps the draft's text on its status row. The way + back is `curator_mode` `off` in every namespace, then the statement that deletes + the rows, then the downgrade + ([drafted answers](curator.md#rolling-back)). A fact a draft became is an ordinary + memory row, which N-1 serves as any other. + `tests/unit/test_curator_draft_candidate.py` checks the gate and that its constant + names the migration file; 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/memory/writing.md b/docs/features/memory/writing.md index 98276f64456..fbeb85776ae 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -461,6 +461,16 @@ not know the code or the server sends none. Learnings have a review of their own: [learnings review queue](./procedures-and-learnings.md#learnings-review-queue). +Some candidates of that queue are private: only an administrator of the namespace lists +them, and everyone else gets neither the row nor a count of it. They are the definition +drafts (`source_kind` `knowledge_gap` and `query_history`, +[definition drafts](../../architecture/definition-drafts.md)) and a curator's drafted +answer (`curator_draft`, [drafted answers](../../architecture/curator.md#drafted-answers)). +A drafted answer is not a proposal: `memory.proposals` does not list it and no read +serves it. A person who administers the namespace accepts it with `learnings.review` +and `approved_sha256`, the `content_sha256` `learnings.list` served for it, and it +becomes a fact with that reviewer as its `actor`. + ### Deciding proposals from a script A decision is three calls: list the proposals, read each chosen text whole, decide with diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index 8e9ec413799..d37ca5b333f 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -85,6 +85,7 @@ are on `agent.account` and `agent.deployment`. | Review queue (conflicts) | `conflicts.list`, `conflicts.resolve`, `learnings.review` | `agent.conflicts.list()`, `.resolve(...)` | | Review queue (proposals) | `loom proposals list`, `show `, `accept`, `reject` ([proposals](../features/memory/writing.md#deciding-proposals-from-a-script)) | `agent.client.memory.proposals(...)`, `.proposal_decide(...)` | | Review queue (definitions) | `memory.definitions.list`, `memory.definitions.disputes` | `agent.client.memory.definitions_list()`, `.definitions_disputes()` | +| Review queue (drafted answers) | `learnings.list`, `learnings.review approved_sha256=` ([drafted answers](../architecture/curator.md#drafted-answers)) | `agent.learnings.list(...)`, `.review(..., approved_sha256=...)`, as a signed-in person | | Copy rules | `memory.copy_rule.set`, `memory.copy_rule.list`, `memory.copy_rule.delete` ([copy rules](../features/namespaces-and-sharing.md#copy-rules)) | `agent.client.memory.copy_rule_set(...)`, `.copy_rule_list(...)`, `.copy_rule_delete(...)`; TypeScript `client.memory.copyRuleSet(...)` | | Copy rule preview | `loom copy-rule run `, or `memory.copy_rule.run` ([preview a rule](../features/namespaces-and-sharing.md#preview-a-rule)) | `agent.client.memory.copy_rule_run(...)`; TypeScript `client.memory.copyRuleRun(...)`; `loom call memory.copy_rule.run rule_id=` | | Copy rule run | `loom copy-rule run --apply --revision ` ([run a rule](../features/namespaces-and-sharing.md#run-a-rule)) | `agent.client.memory.copy_rule_run({"rule_id": ..., "dry_run": False, "revision": ...})` | diff --git a/docs/operations/upgrades.md b/docs/operations/upgrades.md index 8a0ab29a04c..e2164acd538 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -420,7 +420,11 @@ The rules that let the two builds serve side by side are in ## Rollback -Redeploy the previous image; with the pair, `./redeploy.sh --rollback`. Before rolling +Redeploy the previous image; with the pair, `./redeploy.sh --rollback`. A rollback to a +build that does not know a curator's drafted answers is not supported while a +`curator_draft` row is in `loom.learnings_queue`: set `curator_mode` to `off` in every +namespace and delete those rows first +([drafted answers](../architecture/curator.md#rolling-back)). Before rolling back to a build without assistant-turn learnings, turn `memory_extract_agent_learnings` off and delete the rows of `loom.learnings_supporters` and the `assistant_turn` rows of `loom.learnings_queue` diff --git a/docs/reference/operations/learnings.md b/docs/reference/operations/learnings.md index ac43e0a6b24..b0eb748d21e 100644 --- a/docs/reference/operations/learnings.md +++ b/docs/reference/operations/learnings.md @@ -55,8 +55,9 @@ Approve or reject a pending learning. | `candidate_id` | `str` | required | The queued candidate to decide; one unknown in `namespace` answers 404. | | `decision` | `Literal['promote', 'reject']` | required | `promote` writes it to `destination` and marks it promoted; `reject` only marks it rejected. | | `reason` | `str` | `''` | Why; stored as `decision_reason` and carried into the promoted row's provenance. | -| `destination` | `Literal['memory', 'knowledge', 'both'] \| None` | `None` | Where a promotion lands: 'memory', 'knowledge' or 'both', but query_history and knowledge_gap drafts allow only 'memory'; unset is 'knowledge' for an assistant_turn rule and 'memory' otherwise. | -| `approver` | `str` | `'learnings-reviewer'` | Promotion label for other candidates (default 'learnings-reviewer'); query_history and knowledge_gap use the authenticated actor instead, and the audit subject always records the authenticated actor. | +| `destination` | `Literal['memory', 'knowledge', 'both'] \| None` | `None` | Where a promotion lands: 'memory', 'knowledge' or 'both', but query_history, knowledge_gap and curator_draft candidates allow only 'memory'; unset is 'knowledge' for an assistant_turn rule and 'memory' otherwise. | +| `approver` | `str` | `'learnings-reviewer'` | Promotion label for other candidates (default 'learnings-reviewer'); query_history, knowledge_gap and curator_draft use the authenticated actor instead, and the audit subject always records the authenticated actor. | +| `approved_sha256` | `str` | `''` | To promote a `curator_draft`: the `content_sha256` `learnings.list` served for it, so the text accepted is the text read. | | Output field | Type | Meaning | | --- | --- | --- | diff --git a/schemas/migrations/139_curator_draft_evidence.sql b/schemas/migrations/139_curator_draft_evidence.sql new file mode 100644 index 00000000000..e96329df104 --- /dev/null +++ b/schemas/migrations/139_curator_draft_evidence.sql @@ -0,0 +1,10 @@ +-- Where a review candidate's text comes from (docs/architecture/curator.md#drafted-answers). +-- +-- `evidence` is a pointer as JSON, written for a `curator_draft` candidate only: the kind +-- and key of the shared document the draft cites, that document's version and content +-- hash, the keys to check again before the draft is accepted, and the pass that drafted +-- it. It never holds a quote or a passage. '' for every other candidate and for a row +-- written before this file. Additive: a running pod of the previous build reads the +-- table by column name and writes a row without the column, which leaves ''. +ALTER TABLE loom.learnings_queue + ADD COLUMN IF NOT EXISTS `evidence` String DEFAULT ''; diff --git a/schemas/schema.sql b/schemas/schema.sql index 07f01742278..e1d48aa5d8d 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -2472,7 +2472,8 @@ CREATE TABLE IF NOT EXISTS loom.learnings_queue `seeded_from_msg_id` Nullable(String) DEFAULT NULL, `seeded_from_thread_id` Nullable(String) DEFAULT NULL, `agent` LowCardinality(String) DEFAULT '', - `source_resource_id` String DEFAULT '' + `source_resource_id` String DEFAULT '', + `evidence` String DEFAULT '' ) ENGINE = ReplacingMergeTree(version) PARTITION BY toYYYYMM(proposed_at) diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 35fe604d44f..1b4bd409f3a 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -6919,24 +6919,26 @@ type KnowledgeUpsertOutput struct { // LearningEntry is a model used by Loom operations. type LearningEntry struct { - CandidateID string `json:"candidate_id"` - MemoryKey string `json:"memory_key"` - MemoryType string `json:"memory_type"` - ProposedValue json.RawMessage `json:"proposed_value"` - SupporterCount int64 `json:"supporter_count"` - SupporterSessions *int64 `json:"supporter_sessions,omitempty"` - SupporterWriters *int64 `json:"supporter_writers,omitempty"` - ConfidenceAvg float64 `json:"confidence_avg"` - Supporters []string `json:"supporters"` - Rationale string `json:"rationale"` - SourceKind *string `json:"source_kind,omitempty"` - SourceResourceID *string `json:"source_resource_id,omitempty"` - Agent *string `json:"agent,omitempty"` - Status string `json:"status"` - ProposedAt string `json:"proposed_at"` - DecidedAt Optional[string] `json:"decided_at,omitempty"` - DecidedBy *string `json:"decided_by,omitempty"` - DecisionReason *string `json:"decision_reason,omitempty"` + CandidateID string `json:"candidate_id"` + MemoryKey string `json:"memory_key"` + MemoryType string `json:"memory_type"` + ProposedValue json.RawMessage `json:"proposed_value"` + SupporterCount int64 `json:"supporter_count"` + SupporterSessions *int64 `json:"supporter_sessions,omitempty"` + SupporterWriters *int64 `json:"supporter_writers,omitempty"` + ConfidenceAvg float64 `json:"confidence_avg"` + Supporters []string `json:"supporters"` + Rationale string `json:"rationale"` + SourceKind *string `json:"source_kind,omitempty"` + SourceResourceID *string `json:"source_resource_id,omitempty"` + ContentSHA256 *string `json:"content_sha256,omitempty"` + Evidence Optional[map[string]json.RawMessage] `json:"evidence,omitempty"` + Agent *string `json:"agent,omitempty"` + Status string `json:"status"` + ProposedAt string `json:"proposed_at"` + DecidedAt Optional[string] `json:"decided_at,omitempty"` + DecidedBy *string `json:"decided_by,omitempty"` + DecisionReason *string `json:"decision_reason,omitempty"` } // LearningsListInput is the request to learnings.list. @@ -6984,13 +6986,14 @@ type LearningsQualityRow struct { // LearningsReviewInput is the request to learnings.review. type LearningsReviewInput struct { - Org string `json:"org"` - Namespace string `json:"namespace"` - CandidateID string `json:"candidate_id"` - Decision string `json:"decision"` - Reason *string `json:"reason,omitempty"` - Destination Optional[string] `json:"destination,omitempty"` - Approver *string `json:"approver,omitempty"` + Org string `json:"org"` + Namespace string `json:"namespace"` + CandidateID string `json:"candidate_id"` + Decision string `json:"decision"` + Reason *string `json:"reason,omitempty"` + Destination Optional[string] `json:"destination,omitempty"` + Approver *string `json:"approver,omitempty"` + ApprovedSHA256 *string `json:"approved_sha256,omitempty"` } // LearningsReviewOutput is the response from learnings.review. diff --git a/sdk/python/loom/learnings.py b/sdk/python/loom/learnings.py index 44673dbb9a0..9c54e89999f 100644 --- a/sdk/python/loom/learnings.py +++ b/sdk/python/loom/learnings.py @@ -59,6 +59,7 @@ async def review( destination: str | None = None, reason: str = "", approver: str = "learnings-reviewer", + approved_sha256: str = "", ) -> dict[str, Any]: """Promote or reject one candidate. @@ -73,6 +74,10 @@ async def review( On 'reject' the queue row's status flips and nothing else runs. Idempotent: re-reviewing a decided candidate returns its state, except a bot's rule whose last supporter was erased, which answers 404. + + A curator's draft (`source_kind` 'curator_draft') is promoted by a person + who administers the namespace and passes `approved_sha256`: the + `content_sha256` `list()` returned for it. Another hash answers 409. """ return await self._agent.transport.post( "/v1/learnings.review", @@ -84,5 +89,6 @@ async def review( **({"destination": destination} if destination is not None else {}), "reason": reason, "approver": approver, + **({"approved_sha256": approved_sha256} if approved_sha256 else {}), }, ) diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index a4948ea6884..bcce1c0e5cb 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -14522,6 +14522,8 @@ class LearningEntry(TypedDict, total=False): rationale: Required[str] source_kind: NotRequired[str] source_resource_id: NotRequired[str] + content_sha256: NotRequired[str] + evidence: NotRequired[Optional[dict[str, Any]]] agent: NotRequired[str] status: Required[Literal["pending", "promoted", "rejected"]] proposed_at: Required[str] # date-time as ISO-8601 text @@ -14562,6 +14564,7 @@ class LearningsReviewInput(TypedDict, total=False): reason: NotRequired[str] destination: NotRequired[Optional[Literal["memory", "knowledge", "both"]]] approver: NotRequired[str] + approved_sha256: NotRequired[str] class LearningsReviewBody(TypedDict, total=False): @@ -14572,6 +14575,7 @@ class LearningsReviewBody(TypedDict, total=False): reason: NotRequired[str] destination: NotRequired[Optional[Literal["memory", "knowledge", "both"]]] approver: NotRequired[str] + approved_sha256: NotRequired[str] class LearningsReviewOutput(TypedDict, total=False): diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index f3367142c0e..cd93d0432b1 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -213,7 +213,7 @@ module Generated "knowledge.upsert" => OpSpec.new("knowledge.upsert", "knowledge", "upsert", true, false, "writer", "experimental", %w[org namespace source_uri content title description tags metadata original_bytes_b64 original_filename blob_content_type agent session_id source_class].freeze, %w[org namespace source_uri content].freeze), "learnings.list" => OpSpec.new("learnings.list", "learnings", "list", true, true, "viewer", "experimental", %w[org namespace status limit source_kind].freeze, %w[org namespace].freeze), "learnings.quality" => OpSpec.new("learnings.quality", "learnings", "quality", true, true, "viewer", "experimental", %w[org namespace source_kind].freeze, %w[org].freeze), - "learnings.review" => OpSpec.new("learnings.review", "learnings", "review", true, false, "admin", "experimental", %w[org namespace candidate_id decision reason destination approver].freeze, %w[org namespace candidate_id decision].freeze), + "learnings.review" => OpSpec.new("learnings.review", "learnings", "review", true, false, "admin", "experimental", %w[org namespace candidate_id decision reason destination approver approved_sha256].freeze, %w[org namespace candidate_id decision].freeze), "memory.agents_list" => OpSpec.new("memory.agents_list", "memory", "agents_list", true, true, "viewer", "stable", %w[org namespace agent user_id session_id run_id].freeze, %w[org namespace].freeze), "memory.aggregate" => OpSpec.new("memory.aggregate", "memory", "aggregate", true, true, "viewer", "experimental", %w[org namespace agent user_id session_id run_id agg_func agg_field group_by filter limit].freeze, %w[org namespace agent].freeze), "memory.append_batch" => OpSpec.new("memory.append_batch", "memory", "append_batch", true, false, "writer", "experimental", %w[org namespace agent user_id session_id run_id entries].freeze, %w[org namespace agent entries].freeze), diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 6ff8e322f3d..490ec53b503 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -32868,6 +32868,10 @@ pub struct LearningEntry { pub source_kind: String, #[serde(default = "default_learning_entry_source_resource_id")] pub source_resource_id: String, + #[serde(default = "default_learning_entry_content_sha256")] + pub content_sha256: String, + #[serde(default = "default_learning_entry_evidence")] + pub evidence: Option>, #[serde(default = "default_learning_entry_agent")] pub agent: String, pub status: LearningEntryStatus, @@ -33143,6 +33147,12 @@ pub struct LearningsReviewInput { deserialize_with = "present_value" )] pub approver: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub approved_sha256: Option, } impl LearningsReviewInput { pub fn new(candidate_id: impl Into, decision: LearningsReviewInputDecision) -> Self { @@ -33154,6 +33164,7 @@ impl LearningsReviewInput { reason: None, destination: None, approver: None, + approved_sha256: None, } } pub fn org(mut self, org: impl Into) -> Self { @@ -33180,6 +33191,10 @@ impl LearningsReviewInput { self.approver = Some(approver.into()); self } + pub fn approved_sha256(mut self, approved_sha256: impl Into) -> Self { + self.approved_sha256 = Some(approved_sha256.into()); + self + } pub async fn send( self, client: &crate::Client, @@ -72378,6 +72393,12 @@ fn default_learning_entry_source_kind() -> String { fn default_learning_entry_source_resource_id() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_learning_entry_content_sha256() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_learning_entry_evidence() -> Option> { + serde_json::from_str("null").expect("schema default") +} fn default_learning_entry_agent() -> String { serde_json::from_str("\"\"").expect("schema default") } diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 9bddc58b6e4..68d0f2ac572 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -5955,6 +5955,8 @@ export interface LearningEntry { rationale: string; source_kind?: string; source_resource_id?: string; + content_sha256?: string; + evidence?: Record | null; agent?: string; status: "pending" | "promoted" | "rejected"; proposed_at: string; // date-time @@ -5993,6 +5995,7 @@ export interface LearningsReviewInput { reason?: string; destination?: "memory" | "knowledge" | "both" | null; approver?: string; + approved_sha256?: string; } export interface LearningsReviewOutput { diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index 20f81d0ccce..818fa12924f 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -13,6 +13,7 @@ AfterValidator, BaseModel, Field, + PrivateAttr, SerializerFunctionWrapHandler, field_validator, model_serializer, @@ -420,6 +421,11 @@ class MemorySetInput(_Identity): # conflict-flags an established fact; a key that already holds one is # refused (409 KEY_HOLDS_FACT) — propose under a new key. proposed: bool = False + # Not on the wire: the row's `grounding` and `evidence` columns, set by the review + # that accepts a curator's draft (`learnings.review`) and by no request body. A + # private attribute is no field, so validation never reads either from a transport. + _grounding: str = PrivateAttr(default="") + _evidence: str = PrivateAttr(default="") @field_validator("expire_reason") @classmethod diff --git a/server/memory/api/models_learnings.py b/server/memory/api/models_learnings.py index fef761b5d76..7535eb38ee7 100644 --- a/server/memory/api/models_learnings.py +++ b/server/memory/api/models_learnings.py @@ -38,8 +38,17 @@ class _LearningEntry(BaseModel): supporters: list[str] rationale: str source_kind: str = "memory_supporters" - # The gap id or query-history group that produced a definition draft; empty otherwise. + # The gap id or query-history group that produced a definition draft, or the gap a + # `curator_draft` answers; empty otherwise. source_resource_id: str = "" + # `curator_draft` only ('' otherwise): the server's hash of `proposed_value`. Echo + # it as `approved_sha256` to `learnings.review`; never compute it. + content_sha256: str = "" + # `curator_draft` only (null otherwise): where the draft's text comes from, as a + # pointer: the `kind`, `key`, `version` and `sha256` of the shared document it + # cites, the keys to `recheck`, the `run_id` of the pass that drafted it and the + # draft it is a `redraft_of`. Never a quote or a passage. + evidence: dict[str, Any] | None = None # The agent an `assistant_turn` candidate is a rule for; '' for other producers. agent: str = "" status: LearningStatus @@ -63,18 +72,23 @@ class LearningsReviewInput(BaseModel): # The queued candidate to decide; one unknown in `namespace` answers 404. candidate_id: str # `promote` writes it to `destination` and marks it promoted; `reject` only marks - # it rejected. + # it rejected. A decided `curator_draft` takes no other decision (409). decision: ReviewDecision # Why; stored as `decision_reason` and carried into the promoted row's provenance. reason: str = "" - # Where a promotion lands: 'memory', 'knowledge' or 'both', but query_history - # and knowledge_gap drafts allow only 'memory'; unset is 'knowledge' for an - # assistant_turn rule and 'memory' otherwise. + # Where a promotion lands: 'memory', 'knowledge' or 'both', but query_history, + # knowledge_gap and curator_draft candidates allow only 'memory'; unset is + # 'knowledge' for an assistant_turn rule and 'memory' otherwise. destination: PromotionDestination | None = None - # Promotion label for other candidates (default 'learnings-reviewer'); query_history - # and knowledge_gap use the authenticated actor instead, and the audit subject - # always records the authenticated actor. + # Promotion label for other candidates (default 'learnings-reviewer'); query_history, + # knowledge_gap and curator_draft use the authenticated actor instead, and the audit + # subject always records the authenticated actor. approver: str = "learnings-reviewer" + # To promote a `curator_draft`: the `content_sha256` `learnings.list` served for it, + # so the text accepted is the text read. Empty or another hash answers 409 + # PRECONDITION_FAILED and changes nothing; ignored for every other candidate and on + # `reject`. + approved_sha256: str = "" class LearningsReviewOutput(BaseModel): diff --git a/server/memory/app/curator_draft_review.py b/server/memory/app/curator_draft_review.py new file mode 100644 index 00000000000..d2ee7b6cb47 --- /dev/null +++ b/server/memory/app/curator_draft_review.py @@ -0,0 +1,145 @@ +"""An administrator's review of a curator's draft: who may accept it, the hash that names +the text accepted, and the fact the acceptance writes.""" + +from __future__ import annotations + +import json +import uuid +from typing import Any + +import server.memory.store as memory_repo +from server.core.errors import ( + AuthInsufficientError, + OverloadedError, + PreconditionFailedError, + ValidationError, +) +from server.core.hashing import served_content_sha256 +from server.identity.app.reviewers import NotAReviewer, reviewer_subjects +from server.identity.domain.read_scope import WHOLE_NAMESPACE +from server.memory.api.models_crud import MemorySetInput +from server.memory.api.models_learnings import LearningsReviewInput +from server.memory.app.provenance import writer_actor +from server.memory.domain.definitions import CURATOR_DRAFT_MIGRATION +from server.tasks.domain.session_runs import PASS_AGENT + +# The `source_trace` of the fact an accepted draft becomes, before its candidate id. +TRACE = "curator:" + + +async def require_fleet() -> None: + """An older build lists a draft to every reader of the namespace, so no draft is + reviewed while one may serve.""" + from server.auth.machines import fleet_at + from server.core.ch import get_client + + if not await fleet_at(get_client(), CURATOR_DRAFT_MIGRATION): + raise OverloadedError( + "not every replica keeps a curator's draft private; retry after the rollout", + retry_after_s=30, + ) + + +def value(row: dict[str, Any]) -> Any: + """The draft's text, decoded; None for a blanked draft.""" + raw = row.get("proposed_value") + if not raw: + return None + try: + return json.loads(raw) + except (ValueError, TypeError): + return raw + + +def content_sha256(row: dict[str, Any]) -> str: + """The hash `learnings.list` serves for a draft and `approved_sha256` echoes.""" + return served_content_sha256(value(row)) + + +def pointer(row: dict[str, Any]) -> dict[str, Any] | None: + """The draft's stored evidence pointer; None when the row holds no JSON object.""" + try: + parsed = json.loads(row.get("evidence") or "") + except (ValueError, TypeError): + return None + return parsed if isinstance(parsed, dict) else None + + +def refuse_other_decision(input: LearningsReviewInput, row: dict[str, Any]) -> None: + """A draft is decided once: its `rejected` or `promoted` row is what keeps the + question from being drafted again, and a promotion's fact is already served.""" + target = "promoted" if input.decision == "promote" else "rejected" + if row["status"] not in ("pending", target): + raise PreconditionFailedError(f"this draft is already {row['status']}") + + +async def require_acceptance(input: LearningsReviewInput, row: dict[str, Any]) -> None: + """Refuse a promotion unless a person who administers the namespace accepts, under + their own name, the text `learnings.list` served them. Writes nothing.""" + if (input.destination or "memory") != "memory": + raise ValidationError("a curator draft is promoted only to memory") + try: + await reviewer_subjects(input.org, input.namespace, writer_actor()) + except NotAReviewer as e: + raise AuthInsufficientError("A human administrator must review the draft.") from e + if not input.approved_sha256 or input.approved_sha256 != content_sha256(row): + # Without the stored hash: the reviewer reads the draft again and approves the + # text it holds, never a hash whose text they have not seen. + raise PreconditionFailedError( + "`approved_sha256` is not the hash of this draft; list it again and approve " + "what it holds" + ) + if not str((pointer(row) or {}).get("key") or ""): + raise ValidationError("this draft cites no document, so there is nothing to accept") + + +def fact(org: str, namespace: str, row: dict[str, Any]) -> MemorySetInput: + """The write that makes an accepted draft a fact: the curator's namespace-wide row + under the draft's key, written only where no row is, resting on the document the + draft cites. The row's `actor` is the reviewer, stamped from the review's token.""" + cited = pointer(row) or {} + write = MemorySetInput( + org=org, + namespace=namespace, + agent=PASS_AGENT, + memory_key=row["memory_key"], + memory_type="semantic", + value=value(row), + source_class="derived", + source_trace=f"{TRACE}{row['candidate_id']}", + source_resource_id=str(cited.get("key") or ""), + if_match_sha256="absent", + ) + write._grounding = "verbatim" + write._evidence = str(row.get("evidence") or "") + return write + + +async def written(write: MemorySetInput) -> bool: + """Whether a promotion of this draft already wrote its fact: a review that stopped + between the write and its decision row completes on a repeat without a second + write, which the `absent` precondition would refuse.""" + head = await memory_repo.get_by_key( + memory_repo.Identity(org=write.org, namespace=write.namespace, agent=write.agent), + write.memory_key, + scope=WHOLE_NAMESPACE, + fresh=True, + strong=True, + include_expired=False, + ) + return ( + head is not None + and head.source_trace == write.source_trace + and served_content_sha256(head.value) == served_content_sha256(write.value) + ) + + +def candidate_of(agent: str, source_trace: str) -> str: + """The candidate id the row of an accepted draft names; '' for any other row, one + whose trace a caller wrote with no id in it included.""" + if agent != PASS_AGENT or not source_trace.startswith(TRACE): + return "" + try: + return str(uuid.UUID(source_trace.removeprefix(TRACE))) + except ValueError: + return "" diff --git a/server/memory/app/definition_queue.py b/server/memory/app/definition_queue.py index c550cf3ab2f..6a477ad5e04 100644 --- a/server/memory/app/definition_queue.py +++ b/server/memory/app/definition_queue.py @@ -11,12 +11,12 @@ from server.core.errors import ValidationError from server.erasure.app import ledger_reads from server.erasure.domain.scopes import may_cover -from server.memory.domain.definitions import DEFINITION_DRAFT_KINDS +from server.memory.domain.definitions import PRIVATE_CANDIDATE_KINDS from server.memory.store import learnings async def persist(row: dict[str, Any]) -> None: - if row.get("source_kind") not in DEFINITION_DRAFT_KINDS: + if row.get("source_kind") not in PRIVATE_CANDIDATE_KINDS: await learnings.insert_row(row) return async with writing(row) as uncertain: diff --git a/server/memory/app/definition_review.py b/server/memory/app/definition_review.py index 6d8a5107a9e..b1902494844 100644 --- a/server/memory/app/definition_review.py +++ b/server/memory/app/definition_review.py @@ -23,7 +23,7 @@ from server.memory.app.sensitivity_level import decoded_text, detect_level from server.memory.domain import definition_review as plan from server.memory.domain.definition_check import sensitivity_lapse -from server.memory.domain.definitions import definition_names, fold_name +from server.memory.domain.definitions import CURATOR_DRAFT_KIND, definition_names, fold_name from server.memory.store import shared as shared_repo from server.settings import settings @@ -132,20 +132,45 @@ async def promote_candidate( ) -async def redact_candidates(org: str, target: Any, head: Any) -> None: - """Scrub private drafts of the redacted text, serially with their review decisions.""" +async def _scrub(org: str, namespace: str, cid: str) -> None: + """Blank one private candidate, serially with its review decision.""" from server.core import leases + from server.memory.store import learnings + + async with leases.holding(f"definition.review/{org}/{namespace}/{cid}", ttl_s=30) as held: + if not held: + raise OverloadedError("a draft is being reviewed; retry redaction", retry_after_s=1) + async with lease_writes.fenced(f"definition.writer/{org}") as uncertain: + uncertain(True) + await learnings.scrub_private_candidate(org, namespace, cid) + uncertain(False) + + +async def redact_candidates(org: str, target: Any, head: Any) -> None: + """Scrub private drafts of the redacted text, serially with their review decisions. + + A definition's drafts are found by the text's hash or the row's `candidate-id:` tag. + The fact an accepted curator draft became names its candidate in its `source_trace` + under any key, so that candidate is read by id and no page is scanned.""" from server.core.ch import set_query_tag + from server.memory.app import curator_draft_review from server.memory.store import learnings + if head is not None and head.content_sha256 == target.content_sha256: + return + drafted = curator_draft_review.candidate_of(target.agent, target.source_trace) + if drafted: + set_query_tag("memory.redact.candidates") + candidate = await learnings.find_candidate(org, target.namespace, drafted) + if candidate is not None and candidate.get("source_kind") == CURATOR_DRAFT_KIND: + await _scrub(org, target.namespace, drafted) + return if (target.agent, target.user_id, target.session_id) != ( "-", "-", "-", ) or not target.memory_key.startswith("definition/"): return - if head is not None and head.content_sha256 == target.content_sha256: - return tagged = {t.removeprefix("candidate-id:") for t in target.tags if t.startswith("candidate-id:")} after = "" while True: @@ -164,15 +189,5 @@ async def redact_candidates(org: str, target: Any, head: Any) -> None: matches = False if not matches and cid not in tagged: continue - async with leases.holding( - f"definition.review/{org}/{target.namespace}/{cid}", ttl_s=30 - ) as held: - if not held: - raise OverloadedError( - "a draft is being reviewed; retry redaction", retry_after_s=1 - ) - async with lease_writes.fenced(f"definition.writer/{org}") as uncertain: - uncertain(True) - await learnings.scrub_private_candidate(org, target.namespace, cid) - uncertain(False) + await _scrub(org, target.namespace, cid) after = rows[-1]["candidate_id"] diff --git a/server/memory/app/learning_access.py b/server/memory/app/learning_access.py index f303c026408..eee31b3e800 100644 --- a/server/memory/app/learning_access.py +++ b/server/memory/app/learning_access.py @@ -1,13 +1,14 @@ -"""Access to unapproved definitions, which may contain a team's queries.""" +"""Access to private review candidates: unapproved definitions, which may contain a +team's queries, and a curator's drafts, which no person has read yet.""" from __future__ import annotations -from server.memory.domain.definitions import DEFINITION_DRAFT_KINDS +from server.memory.domain.definitions import PRIVATE_CANDIDATE_KINDS from server.settings import settings async def private_candidates_visible(org: str, namespace: str) -> bool: - """Only a namespace admin reads its unapproved gap and query-history drafts.""" + """Only a namespace admin reads its private candidates (`PRIVATE_CANDIDATE_KINDS`).""" from server.auth.authz import CachedGate from server.auth.context import current_auth from server.operations.base import Role @@ -19,7 +20,7 @@ async def private_candidates_visible(org: str, namespace: str) -> bool: async def candidate_visible(org: str, namespace: str, source_kind: str) -> bool: - """Ordinary learnings remain reader-visible; unapproved definitions need admin.""" - return source_kind not in DEFINITION_DRAFT_KINDS or await private_candidates_visible( + """Ordinary learnings remain reader-visible; a private candidate needs admin.""" + return source_kind not in PRIVATE_CANDIDATE_KINDS or await private_candidates_visible( org, namespace ) diff --git a/server/memory/app/learnings.py b/server/memory/app/learnings.py index 36474a058a2..67accfe8cb3 100644 --- a/server/memory/app/learnings.py +++ b/server/memory/app/learnings.py @@ -22,12 +22,16 @@ _LearningEntry, ) from server.memory.api.models_lifecycle import MemoryPromoteInput -from server.memory.app import blacklist_guard +from server.memory.app import blacklist_guard, curator_draft_review from server.memory.app.definition_queue import writing from server.memory.app.learning_access import private_candidates_visible from server.memory.app.provenance import writer_actor from server.memory.domain import assistant_rules -from server.memory.domain.definitions import DEFINITION_DRAFT_KINDS +from server.memory.domain.definitions import ( + CURATOR_DRAFT_KIND, + DEFINITION_DRAFT_KINDS, + PRIVATE_CANDIDATE_KINDS, +) from server.memory.domain.memory_types import is_definition from server.memory.store import learnings as learnings_repo from server.memory.store.rows import version_over @@ -42,7 +46,7 @@ async def handle_learnings_list( exclude = ( () if await private_candidates_visible(input.org, input.namespace) - else DEFINITION_DRAFT_KINDS + else PRIVATE_CANDIDATE_KINDS ) rows = await learnings_repo.list_by_status( input.org, @@ -60,6 +64,8 @@ async def handle_learnings_list( proposed_value = json.loads(r["proposed_value"]) if r["proposed_value"] else None except (ValueError, TypeError): proposed_value = r["proposed_value"] + # What a reviewer accepts a draft by, and what the draft rests on. + draft = r.get("source_kind") == CURATOR_DRAFT_KIND entries.append( _LearningEntry( candidate_id=str(r["candidate_id"]), @@ -74,6 +80,8 @@ async def handle_learnings_list( rationale=r["rationale"], source_kind=r.get("source_kind", "memory_supporters"), source_resource_id=str(r.get("source_resource_id") or ""), + content_sha256=curator_draft_review.content_sha256(r) if draft else "", + evidence=curator_draft_review.pointer(r) if draft else None, agent=str(r.get("agent") or ""), status=r["status"], proposed_at=r["proposed_at"], @@ -144,7 +152,7 @@ async def handle_learnings_quality( where += " AND source_kind = {sk:String}" params["sk"] = input.source_kind private_namespaces = None - if input.source_kind is None or input.source_kind in DEFINITION_DRAFT_KINDS: + if input.source_kind is None or input.source_kind in PRIVATE_CANDIDATE_KINDS: private_namespaces = await _private_quality_namespaces(input, where, params) rows = await learnings_repo.quality_by_namespace(where, params, private_namespaces) return LearningsQualityOutput( @@ -189,6 +197,12 @@ async def handle_learnings_review( it rejected and leaves what the promotion wrote (delete a knowledge promotion's `learning://` document with knowledge.delete to stop serving it). A bot's rule whose last supporter was erased answers 404. + + A `curator_draft` is read and decided by the namespace's administrators only + (404 below that). Promoting one needs a person signed in under their own name + and `approved_sha256`, the `content_sha256` `learnings.list` served; it + becomes the curator's namespace-wide fact with the reviewer as its `actor`. + A service account may reject one. A decided draft takes no other decision. """ from fastapi import HTTPException @@ -197,7 +211,7 @@ async def handle_learnings_review( input.namespace, input.candidate_id, ) - if row is not None and row.get("source_kind") in DEFINITION_DRAFT_KINDS: + if row is not None and row.get("source_kind") in PRIVATE_CANDIDATE_KINDS: if not await private_candidates_visible(input.org, input.namespace): raise HTTPException(status_code=404, detail={"code": "RESOURCE_NOT_FOUND"}) from server.core import leases @@ -209,7 +223,10 @@ async def handle_learnings_review( raise OverloadedError("another reviewer is deciding this draft", retry_after_s=1) from server.memory.app.definition_review import require_draft_fleet - await require_draft_fleet() + if row.get("source_kind") == CURATOR_DRAFT_KIND: + await curator_draft_review.require_fleet() + else: + await require_draft_fleet() row = await learnings_repo.find_candidate( input.org, input.namespace, input.candidate_id ) @@ -230,7 +247,7 @@ async def _review( ) -> LearningsReviewOutput: from fastapi import HTTPException - if row is not None and row.get("source_kind") in DEFINITION_DRAFT_KINDS: + if row is not None and row.get("source_kind") in PRIVATE_CANDIDATE_KINDS: if not row.get("proposed_value"): row = None # A bot rule with no supporter left (blanked once decided, deleted once pending @@ -254,11 +271,16 @@ async def _review( }, ) - private_definition = row.get("source_kind") in DEFINITION_DRAFT_KINDS + private = row.get("source_kind") in PRIVATE_CANDIDATE_KINDS now = naive_utc_now() target_status: Literal["promoted", "rejected"] = ( "promoted" if input.decision == "promote" else "rejected" ) + if row.get("source_kind") == CURATOR_DRAFT_KIND: + if input.decision == "promote": + # Before the repeat's answer below: a promotion is a person's, every time. + await curator_draft_review.require_acceptance(input, row) + curator_draft_review.refuse_other_decision(input, row) if row["status"] == target_status: return LearningsReviewOutput( @@ -268,59 +290,11 @@ async def _review( decided_at=now, ) - # Route promotion to memory, knowledge, or both. - promoted_to_shared = False - promoted_to_knowledge = False - knowledge_source_uri = "" + promoted_to_shared, knowledge_source_uri = False, None if input.decision == "promote": - # A bot rule is promoted with the confidence the reviewer saw: the mean over - # its supporters, not the filing session's own. Only the promotion reads it; - # the status row below keeps the candidate's own columns. - promoted = {**row, "confidence_avg": float(support[0]["confidence"])} if support else row - destination = input.destination or ("knowledge" if agent_rule else "memory") - if agent_rule: - # A pattern added after the rule was filed still refuses it, on every - # destination: memory.set checks the blacklist, knowledge.upsert does not. - await blacklist_guard.enforce_on_insert( - org=input.org, namespace=input.namespace, value=str(_proposed_value(row)) - ) - wants_memory = destination in ("memory", "both") - wants_knowledge = destination in ("knowledge", "both") - if private_definition: - if destination != "memory": - raise ValidationError("a definition draft is promoted only to memory") - from server.memory.app.definition_review import promote_candidate - - assert uncertain is not None # private reviews hold the evidence writer fence - await promote_candidate( - input.org, input.namespace, row, input.reason, uncertain=uncertain - ) - promoted_to_shared = True - if wants_memory and is_definition(row) and not private_definition: - # A definition reaches memory only through memory.promote of its namespace-wide - # row, which checks the approved hash. - raise ValidationError( - "a definition candidate is not promoted to memory by review: write the " - "definition as the namespace-wide row and promote it with memory.promote" - ) - if wants_memory and not private_definition: - await _do_promote( - input.org, - input.namespace, - promoted, - input.approver, - input.reason, - ) - promoted_to_shared = True - if wants_knowledge: - knowledge_source_uri = await _do_promote_to_knowledge( - input.org, - input.namespace, - promoted, - input.approver, - input.reason, - ) - promoted_to_knowledge = True + promoted_to_shared, knowledge_source_uri = await _promote( + input, row, support, agent_rule=agent_rule, uncertain=uncertain + ) # ReplacingMergeTree(version): new status row; FINAL reads the latest, so every # column is carried from the candidate — `seeded_from_*` keeps its conversation @@ -343,18 +317,14 @@ async def _review( "source_kind": row.get("source_kind", "memory_supporters"), "source_resource_id": str(row.get("source_resource_id") or ""), "agent": str(row.get("agent") or ""), + # A draft's pointer stays on its decided row, which a later pass reads. + "evidence": str(row.get("evidence") or ""), "seeded_from_thread_id": row.get("seeded_from_thread_id"), "seeded_from_msg_id": row.get("seeded_from_msg_id"), "status": target_status, - "proposed_at": row.get("proposed_at") - if private_definition - else row.get("proposed_at") or now, + "proposed_at": row.get("proposed_at") if private else row.get("proposed_at") or now, "decided_at": now, - "decided_by": ( - writer_actor("learnings-reviewer") - if row.get("source_kind") in DEFINITION_DRAFT_KINDS - else input.approver - ), + "decided_by": writer_actor("learnings-reviewer") if private else input.approver, "decision_reason": input.reason, "version": version_over(int(row.get("version") or 0)), } @@ -367,12 +337,70 @@ async def _review( candidate_id=str(row["candidate_id"]), new_status=target_status, promoted_to_shared=promoted_to_shared, - promoted_to_knowledge=promoted_to_knowledge, - knowledge_source_uri=knowledge_source_uri, + promoted_to_knowledge=knowledge_source_uri is not None, + knowledge_source_uri=knowledge_source_uri or "", decided_at=now, ) +async def _promote( + input: LearningsReviewInput, + row: dict[str, Any], + support: list[dict[str, Any]], + *, + agent_rule: bool, + uncertain: Callable[[bool], None] | None, +) -> tuple[bool, str | None]: + """Write a promoted candidate to memory, knowledge, or both. Returns whether memory + was written and the knowledge document's `source_uri` (None when none was written).""" + private_definition = row.get("source_kind") in DEFINITION_DRAFT_KINDS + curator_draft = row.get("source_kind") == CURATOR_DRAFT_KIND + # A bot rule is promoted with the confidence the reviewer saw: the mean over + # its supporters, not the filing session's own. Only the promotion reads it; + # the status row keeps the candidate's own columns. + promoted = {**row, "confidence_avg": float(support[0]["confidence"])} if support else row + destination = input.destination or ("knowledge" if agent_rule else "memory") + if agent_rule: + # A pattern added after the rule was filed still refuses it, on every + # destination: memory.set checks the blacklist, knowledge.upsert does not. + await blacklist_guard.enforce_on_insert( + org=input.org, namespace=input.namespace, value=str(_proposed_value(row)) + ) + wants_memory = destination in ("memory", "both") + promoted_to_shared = False + if private_definition: + if destination != "memory": + raise ValidationError("a definition draft is promoted only to memory") + from server.memory.app.definition_review import promote_candidate + + assert uncertain is not None # private reviews hold the evidence writer fence + await promote_candidate(input.org, input.namespace, row, input.reason, uncertain=uncertain) + promoted_to_shared = True + if wants_memory and is_definition(row) and not private_definition: + # A definition reaches memory only through memory.promote of its namespace-wide + # row, which checks the approved hash. + raise ValidationError( + "a definition candidate is not promoted to memory by review: write the " + "definition as the namespace-wide row and promote it with memory.promote" + ) + if wants_memory and not private_definition: + if curator_draft: + assert uncertain is not None # private reviews hold the evidence writer fence + uncertain(True) + # A refused write (a row now under a draft's key, the blacklist, a pinned + # conflict) bubbles up and the candidate stays pending. + await _do_promote(input.org, input.namespace, promoted, input.approver, input.reason) + if curator_draft: + assert uncertain is not None + uncertain(False) + promoted_to_shared = True + if destination in ("knowledge", "both"): + return promoted_to_shared, await _do_promote_to_knowledge( + input.org, input.namespace, promoted, input.approver, input.reason + ) + return promoted_to_shared, None + + def _proposed_value(candidate_row: dict[str, Any]) -> Any: """The candidate's value: `proposed_value` is JSON-encoded, or a plain string.""" raw_value = candidate_row["proposed_value"] @@ -470,9 +498,17 @@ async def _promote_via_memory_set( seeder candidate lands under the approver's `user_id`, judged against that user's rows as any write naming its user is; a bot rule (`assistant_turn`) as its agent's namespace-wide row (`user_id` '-'), which reads bounded to one user do not serve, - with the supporters' mean confidence.""" + with the supporters' mean confidence. A curator's draft lands as the curator's + namespace-wide row under the draft's key, only where no row is + (`curator_draft_review.fact`), and once: a repeat that finds it written writes nothing.""" from server.memory.app.write import handle_memory_set + if candidate_row.get("source_kind") == CURATOR_DRAFT_KIND: + write = curator_draft_review.fact(org, namespace, candidate_row) + if not await curator_draft_review.written(write): + # 409 PRECONDITION_FAILED (a row now under the key) bubbles up. + await handle_memory_set(write) + return deserialized = _proposed_value(candidate_row) # In both cases the approver is the row's `actor`, stamped from the review's token. diff --git a/server/memory/app/write.py b/server/memory/app/write.py index c196414e7bd..7d942e1221b 100644 --- a/server/memory/app/write.py +++ b/server/memory/app/write.py @@ -613,6 +613,10 @@ def _set_build_memory_row(w: _SetWrite) -> None: "concepts": [], "sensitivity": effective_sensitivity, } + if input._grounding: + # The review that accepts a curator's draft names what the fact rests on. + memory_row["grounding"] = input._grounding + memory_row["evidence"] = input._evidence if existing is not None: # A revision: every column not set above (usage counters, lineage) comes # from the live row; the builder resets the ones about the old value. diff --git a/server/memory/domain/definitions.py b/server/memory/domain/definitions.py index 972688bf618..21905fc6184 100644 --- a/server/memory/domain/definitions.py +++ b/server/memory/domain/definitions.py @@ -16,6 +16,16 @@ DEFINITION_KEY_PREFIX = "definition/" DEFINITION_DRAFT_KINDS = ("knowledge_gap", "query_history") +# A curator's drafted answer to a question several people asked: a review candidate +# that cites one shared document. Its text is unreviewed until a person accepts it. +CURATOR_DRAFT_KIND = "curator_draft" +# The migration that adds `loom.learnings_queue.evidence`, the first build that keeps a +# draft from everyone but the namespace's administrators +# (tests/unit/test_curator_draft_candidate.py ties it to the file). +CURATOR_DRAFT_MIGRATION = 139 +# The review candidates only a namespace administrator reads; every visibility filter, +# the erasure fence and the redaction scrub take this tuple. +PRIVATE_CANDIDATE_KINDS = (*DEFINITION_DRAFT_KINDS, CURATOR_DRAFT_KIND) def fold_name(name: str) -> str: diff --git a/server/memory/store/history.py b/server/memory/store/history.py index 91367a39b86..98e3084ddf2 100644 --- a/server/memory/store/history.py +++ b/server/memory/store/history.py @@ -99,6 +99,7 @@ class HistoryTarget: memory_id: str content_sha256: str # the hash of the version's text, which its search rows carry too tags: tuple[str, ...] = () + source_trace: str = "" # names the review candidate an accepted draft came from @classmethod def from_row(cls, r: Mapping[str, Any]) -> HistoryTarget: @@ -113,6 +114,7 @@ def from_row(cls, r: Mapping[str, Any]) -> HistoryTarget: version=int(r.get("version") or 0), content_sha256=str(r.get("content_sha256") or ""), tags=tuple(r.get("tags") or ()), + source_trace=str(r.get("source_trace") or ""), ) @@ -245,13 +247,13 @@ async def find_history_target( ch = ch or _default_client() cols = ( "org, memory_id, namespace, agent, user_id, session_id, memory_key, version, " - "toStringCutToZero(content_sha256) AS content_sha256, tags" + "toStringCutToZero(content_sha256) AS content_sha256, tags, source_trace" ) at = "org = {org:String} AND memory_id = {mid:UUID} AND version = {v:UInt64}" r = await ch.query_one( f""" SELECT org, toString(memory_id) AS memory_id, namespace, agent, user_id, session_id, - memory_key, version, content_sha256, tags + memory_key, version, content_sha256, tags, source_trace FROM ( SELECT {cols} FROM loom.memory_versions WHERE {at} UNION ALL diff --git a/server/memory/store/learnings.py b/server/memory/store/learnings.py index 7fd2dae5e58..c52a55b7212 100644 --- a/server/memory/store/learnings.py +++ b/server/memory/store/learnings.py @@ -11,7 +11,7 @@ from typing import Any from server.core.repo_base import _CHClient, _default_client -from server.memory.domain.definitions import DEFINITION_DRAFT_KINDS +from server.memory.domain.definitions import PRIVATE_CANDIDATE_KINDS async def list_by_status( @@ -46,7 +46,7 @@ async def list_by_status( f""" SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, - source_kind, source_resource_id, agent, + source_kind, source_resource_id, agent, evidence, status, proposed_at, decided_at, decided_by, decision_reason FROM loom.learnings_queue FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} @@ -64,7 +64,7 @@ async def private_candidate_namespaces(where: str, params: dict[str, Any]) -> li rows = await _default_client().query_all( f"""SELECT DISTINCT namespace FROM loom.learnings_queue FINAL WHERE {where} AND source_kind IN {{private_kinds:Array(String)}}""", - params={**params, "private_kinds": list(DEFINITION_DRAFT_KINDS)}, + params={**params, "private_kinds": list(PRIVATE_CANDIDATE_KINDS)}, ) return [str(r["namespace"]) for r in rows] @@ -77,7 +77,9 @@ async def quality_by_namespace( if private_namespaces is not None: where += """ AND (source_kind NOT IN {private_kinds:Array(String)} OR namespace IN {draft_admin_ns:Array(String)})""" - params.update(private_kinds=list(DEFINITION_DRAFT_KINDS), draft_admin_ns=private_namespaces) + params.update( + private_kinds=list(PRIVATE_CANDIDATE_KINDS), draft_admin_ns=private_namespaces + ) return await _default_client().query_all( f""" SELECT namespace, @@ -107,8 +109,8 @@ async def find_candidate( and the candidate side of `memory.lineage`'s provenance chain. `seeded_from_*` is surfaced so lineage can point at the originating - conversation turn; `supporter_count`, `confidence_avg`, `proposed_at` and `agent` - so a review's new version carries them forward. + conversation turn; `supporter_count`, `confidence_avg`, `proposed_at`, `agent` and + `evidence` so a review's new version carries them forward. """ ch = ch or _default_client() from server.core.ch import sequential_reads @@ -120,7 +122,7 @@ async def find_candidate( status, supporters, rationale, source_kind, source_resource_id, version, seeded_from_thread_id, seeded_from_msg_id, supporter_count, confidence_avg, proposed_at, - agent + agent, evidence FROM loom.learnings_queue FINAL WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} @@ -170,11 +172,13 @@ async def insert_row( *, ch: _CHClient | None = None, ) -> None: - """Insert a queue row; review writes a new row with the decided status.""" + """Insert a queue row; review writes a new row with the decided status. Every row + carries `evidence`: a version written without the column would read as a candidate + that cites nothing.""" ch = ch or _default_client() await ch.insert( "loom.learnings_queue", - [row], + [{"evidence": "", **row}], settings={"async_insert": 0, "wait_for_async_insert": 1}, ) @@ -299,7 +303,7 @@ async def private_candidates_after(org: str, namespace: str, after: str) -> list params={ "org": org, "ns": namespace, - "kinds": list(DEFINITION_DRAFT_KINDS), + "kinds": list(PRIVATE_CANDIDATE_KINDS), "after": after, }, ) @@ -309,14 +313,14 @@ async def scrub_private_candidate(org: str, namespace: str, candidate_id: str) - """Blank all versions, including the row a previous status copied.""" await _default_client().execute( "ALTER TABLE loom.learnings_queue UPDATE proposed_value = '', " - "rationale = '', decision_reason = '' " + "rationale = '', decision_reason = '', evidence = '' " "WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} " "AND source_kind IN {kinds:Array(String)} SETTINGS mutations_sync = 2", params={ "org": org, "ns": namespace, "cid": candidate_id, - "kinds": list(DEFINITION_DRAFT_KINDS), + "kinds": list(PRIVATE_CANDIDATE_KINDS), }, ) diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 5af3de3a3bc..45d1a9eb1d5 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -1811,7 +1811,7 @@ async def history_target(org: str, memory_id: str, version: int) -> dict[str, An r = await pg.fetchrow( f"SELECT org, memory_id::text AS memory_id, namespace, {_meta('agent')} AS agent, " f"user_id, {_meta('session_id')} AS session_id, {_meta('memory_key')} AS memory_key, " - "version, content_sha256, row->'tags' AS tags " + "version, content_sha256, row->'tags' AS tags, row->>'source_trace' AS source_trace " "FROM loom.memory_revisions WHERE org = $1 AND memory_id = $2 AND version = $3 LIMIT 1", org, mid, diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 7f2e584f886..a63cea0b963 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1314,15 +1314,19 @@ def revision_policy(update: str) -> str: "rejected). The queue holds memories " "several writers back (promoted to shared), conversation-seeded facts " "(promoted to a namespace memory row), and rules a bot stated about itself " - "(source_kind=assistant_turn, promoted to knowledge). Use when the user " - "wants to review the promotion queue or find a decided candidate's id." + "(source_kind=assistant_turn, promoted to knowledge). A curator's drafted " + "answer (source_kind=curator_draft) is listed to namespace admins only, with " + "the content_sha256 a review accepts it by and the document it cites. Use when " + "the user wants to review the promotion queue or find a decided candidate's id." ), "learnings.review": ( "Approve or reject a pending learning. Approving promotes a candidate " "several writers back to scope=shared, a conversation-seeded fact to a " "namespace memory row, and a bot's rule to the namespace's knowledge, " "where that bot's reads find it for every user; rejecting keeps the " - "candidate as rejected." + "candidate as rejected. A curator's draft is promoted only by a human admin " + "who passes approved_sha256, the content_sha256 learnings.list served, and " + "becomes a namespace fact; once decided it takes no other decision." ), # ---- Conflicts (contradicting memories) ---- "conflicts.list": ( diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 6ab1d020243..2a350411391 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -88,6 +88,7 @@ 089042275ad2 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 08a7cc3679db SELECT DISTINCT units, toString(digest) AS anchor FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?,?) AND scope_value={ns:String} AND user_id={uid:String}) OR (scope_kind=? AND 08bde665b126 SELECT count() AS n FROM loom.memory_belief_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} +08cb66088616 SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, evidence, status, proposed_at, decided_at, 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 @@ -267,6 +268,7 @@ 1e6bdc6d3711 SELECT ? AS present FROM loom.knowledge_sources WHERE (source_kind = ? OR kind = ? OR credential_mode = ?) LIMIT ? 1e749bd6ee04 ALTER TABLE loom.memory_chunk_sources DELETE WHERE (org = {org:String} AND (namespace, memory_key) IN {keys:Array(Tuple(String, String))}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:St 1e77b19a345b 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 +1e7e40d254eb SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, evidence, status, proposed_at, decided_at, 1ea0c8768c0e SELECT count() AS n FROM loom.shared FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} 1ef2654703f8 SELECT DISTINCT source_uri FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND arrayExists(u -> startsWith(source_uri, concat(u, ?)), {uris:Array(String)}) ORDER BY sour 1f46432bb4a5 SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, degree FROM ( SELECT src, dst, relation, direction, pair_co_occur, valid_from, valid_to, row_number() OVER (PARTITION BY src @@ -441,7 +443,6 @@ 311579a423b9 SELECT created_at, memory_key FROM loom.memory WHERE memory_id = {mid:UUID} AND org = {org:String} AND namespace = {in_ns:String} LIMIT ? 3117b6749ab2 SELECT thread_id, msg_id, role, content_excerpt AS embedded_text, ts, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND nam 311c3ee7bb8b SELECT j.source_uri AS source_uri, if(j.open_jobs > ?, j.open_ingestion_id, j.latest_ingestion_id) AS ingestion_id, if(j.open_jobs > ?, j.open_filename, j.latest_filename) AS filename, if(j.open_jobs -3129eb469639 SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, status, proposed_at, decided_at, decided_b 314265019cca SELECT def_path, count() AS prs FROM ( SELECT arrayJoin(arrayIntersect(files, {defs:Array(String)})) AS def_path FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AN 31448ef63205 SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, valid_to, dateDiff(?, valid_to, now()) AS days_past FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:S 31611f39fb5c SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { @@ -477,7 +478,6 @@ 33ce237afae6 SELECT source AS consumer_key, count() AS outcome_rows, countIf(action IN (?, ?)) AS outcome_positive, countIf(action IN (?, ?)) AS outcome_negative, countIf(action IN (?, ?)) AS shunt_rows, sum(token 33d179d9b1ff SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND (has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor))) 33db1f0050ff SELECT path, uniqExact(facet_kind, name) AS matched, groupArray((facet_kind, name, ordinal, line, confidence)) AS hits, ? AS co_occurs FROM loom.code_test_facets FINAL WHERE org = {org:String} AND nam -3403e1e98ed1 SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, status, proposed_at, decided_at, decided_b 341b6eb8dac2 ALTER TABLE loom.operator_edges 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 342653bd9d76 SELECT to_symbol_id AS symbol_id, max(to_q) AS qualified_name, count() AS fan_in_calls, countIf(NOT match(path, {noise:String})) AS fan_in_nontest, uniqExact(path) AS caller_files FROM ( SELECT to_sym 342f026b3008 SELECT count() AS n FROM loom.memory_code_link_queue WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -723,6 +723,7 @@ 4c7dd09282aa SELECT merge_commit_sha FROM loom.code_pr_history FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number = {pr:UInt32} AND tombstoned_at IS NULL AND merge_commit_sha != ? AND merged_ 4c809ae216d7 SELECT s.memory_key, s.value, cosineDistance(e.embedding, {emb:Array(Float32)}) AS dist FROM loom.shared s FINAL JOIN loom.memory_embeddings e FINAL ON e.org = s.org AND e.namespace = s.namespace AND 4cb8080c7ceb SELECT count() AS n FROM loom.scim_users FINAL WHERE deleted = ? AND has(addresses, {a:String}) +4cf17bafe68d SELECT candidate_id, memory_key, memory_type, proposed_value, status, supporters, rationale, source_kind, source_resource_id, version, seeded_from_thread_id, seeded_from_msg_id, supporter_count, confi 4cffb3ebff8e ALTER TABLE loom.conversations UPDATE is_saved = true, user_id = {uid:String}, saved_at = coalesce(saved_at, {at:DateTime64(?, ?)}) WHERE org = {org:String} AND namespace = {ns:String} AND agent = {ag 4d19c2282f56 ALTER TABLE loom.session_brief_revisions DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sy 4d35b2bfae9a SELECT count() AS n FROM loom.knowledge_reports WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? @@ -737,7 +738,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 = { @@ -1008,7 +1008,6 @@ 69df89f26d2c SELECT count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND actor IN {label_actors:Array(String)} AND ? 6a3370791075 SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND merged_at > now() - INTERVAL {days:UInt32} 6a5190d3f6a4 SELECT count() AS n FROM loom.memory_versions WHERE org = {org:String} AND namespace IN {ns:Array(String)} -6a53a350be30 SELECT candidate_id, memory_key, memory_type, proposed_value, status, supporters, rationale, source_kind, source_resource_id, version, seeded_from_thread_id, seeded_from_msg_id, supporter_count, confi 6a941a6c5e43 WITH ( SELECT max(computed_at) FROM loom.entity_communities WHERE org = {org:String} AND namespace = {ns:String} AND level = ? ) AS latest SELECT community_id, any(size) AS size, latest AS computed_at 6abb543e4d1a SELECT symbol_id, uniqExact(path) AS defined_files, min(match(path, {noise:String})) AS is_test, argMin(path, (match(path, {noise:String}), path)) AS def_path FROM ( SELECT symbol_id, argMax(path, ver 6ad106d09e67 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: @@ -1128,6 +1127,7 @@ 76ed76b066ae 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_ 76f47ab9df72 SELECT ? AS present FROM loom.code_caller_guards WHERE org = {org:String} AND namespace = {ns:String} LIMIT ? 77424b91d322 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} +77840831aca7 SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, evidence, status, proposed_at, decided_at, 778a3bb04c67 SELECT namespace, source_uri, title, description, tags, ingested_at, superseded_at, blob_path, blob_size, toString(blob_content_type) AS blob_content_type, original_filename, content_preview FROM loom 7799bb45ee57 SELECT ? FROM loom.memory_refusals WHERE org={org:String} AND ((scope_kind IN (?,?) AND scope_value={ns:String} AND user_id={uid:String}) OR (scope_kind=? AND scope_value={ns:String}) OR (scope_kind=? 77abb6560e82 ALTER TABLE loom.memory_code_links DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1314,7 +1314,6 @@ 878eb1ccb396 SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, embedding_model, embedding, version, content_sha256, status FROM loom.memory_embeddings FINAL WHERE (org, namespace, agent, 87f6acbd04a9 SELECT count() AS n FROM loom.search_misses WHERE org = {org:String} AND (has({spellings:Array(String)}, asker) OR has({spellings:Array(String)}, lowerUTF8(user_id))) 8821bc6c7261 SELECT count() AS n FROM loom.session_briefs WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? -884c1941f3ed SELECT candidate_id, memory_key, memory_type, proposed_value, supporter_count, confidence_avg, supporters, rationale, source_kind, source_resource_id, agent, status, proposed_at, decided_at, decided_b 8863d1cc780b SELECT author, uniqExact(pr_number) AS prs FROM loom.code_pr_reviews FINAL WHERE org = {org:String} AND namespace = {ns:String} AND comment_created_at >= now() - INTERVAL {days:UInt32} DAY AND is_bot 886a836d33a6 DELETE FROM loom.read_receipts WHERE (org = {org:String} AND ((has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor))) AND ts <= {recorded_at:DateTime}) 886a9aa8d0c3 SELECT count() AS n FROM loom.read_receipts WHERE org = {org:String} AND ((has({spellings:Array(String)}, lowerUTF8(user_id)) OR has({spellings:Array(String)}, lowerUTF8(actor))) AND ts <= {recorded_a @@ -1490,6 +1489,7 @@ 9a9a371beffd 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, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 9a9aaad3e6e4 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, 9ab0f1177c93 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_ +9ab7792b3f7c ALTER TABLE loom.learnings_queue UPDATE proposed_value = ?, rationale = ?, decision_reason = ?, evidence = ? WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} AND sour 9adfa8216cee ALTER TABLE loom.memory_code_link_queue DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 9ae3708317b3 SELECT if(consumer = ?, args[?], consumer) AS consumer_key, count() AS calls, countIf(NOT success) AS errors, countIf(NOT success AND error_code = ?) AS server_errors, round(errors / calls, ?) AS erro 9b1e4cc93d63 ALTER TABLE loom.memory_exposures DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? @@ -1629,6 +1629,7 @@ a75f46602856 SELECT count() AS n FROM loom.memory_drops WHERE org = {org:String} a7892d3b93cd SELECT thread_id, msg_id, any(role) AS role, argMax(substringUTF8(content, ?, {listed:UInt32}), ts) AS content, max(c.saved_at) AS saved_at FROM loom.conversations AS c WHERE org = {org:String} AND na a789ce3fb940 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND user_id = {uid:String} AND ? a79a82c3db28 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 +a7a846a61444 -- 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 a7e930ac6777 SELECT toDate(coalesce(temporal_anchor, valid_at)) AS event_date, cosineDistance(embedding, {q:Array(Float32)}) AS distance, substring(content_excerpt, ?, ?) AS excerpt, memory_key, temporal_anchor IS a819ade52d8a SELECT org, namespace, source_uri, version, revision, title, ingested_at, superseded_at, if(format != ?, toString(format), if(if(JSONType(metadata, ?) = ?, JSONExtractString(metadata, ?), ?) != ?, if( a85f83c11660 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND (namespace, memory_key) IN (SELECT namespace, memory_key FROM loom.memory WHERE org = {org:String} AND user_id = { @@ -1670,7 +1671,6 @@ ab6563a97507 ALTER TABLE loom.entity_triples DELETE WHERE (org = {org:String} AN ab694fe8e1a0 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 = { ab7b1d37942f SELECT count() AS n FROM loom.memory_exposures WHERE org = {org:String} AND namespace = {ns:String} AND ? abc727fc102d SELECT test_name, sum(runs) AS runs_in_window, sum(fails) AS fails_in_window, count() OVER () AS matches FROM loom.qa_test_daily FINAL WHERE org = {org:String} AND qa_namespace = {ns:String} AND day > -abcf251b1c48 ALTER TABLE loom.learnings_queue UPDATE proposed_value = ?, rationale = ?, decision_reason = ? WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID} AND source_kind IN {ki abfe0a1ce868 SELECT DISTINCT toString(candidate_id) AS id FROM (SELECT candidate_id FROM loom.learnings_supporters WHERE org = {org:String}) WHERE candidate_id IN {cids:Array(UUID)} ac2681a0817a ALTER TABLE loom.entity_summaries DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? ac3b913795e1 SELECT org, namespace, source_uri, chunk_idx, content, context, tags, doc_metadata, chunk_metadata, ingested_at, doc_superseded_at, embedding_model, embedding_dim FROM loom.chunks WHERE org = {org:Str @@ -1971,6 +1971,7 @@ c95637249d50 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. c97078eb79f8 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, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist c97976fc373a SELECT ts, event_type, org, namespace, actor, subject, request_id FROM loom.audit_log WHERE org = {org:String} AND namespace = {ns:String} AND namespace NOT IN {shown_hidden:Array(String)} AND NOT mat c99a26ec4116 SELECT count() AS n FROM loom.memory_record_conflicts FINAL WHERE org = {org:String} AND (prior_record_id IN (SELECT record_id FROM loom.memory_records WHERE org = {org:String} AND user_id = {uid:Stri +c9c614bb2295 SELECT org, toString(memory_id) AS memory_id, namespace, agent, user_id, session_id, memory_key, version, content_sha256, tags, source_trace FROM ( SELECT org, memory_id, namespace, agent, user_id, se c9d8f33ed466 SELECT memory_key, toString(memory_id) AS id, version, memory_type, toString(status) AS status, source_class, agent, user_id, session_id, actor, updated_at, sensitivity, org, namespace, redacted_at FR c9e1e8c68869 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} c9eabf7429ec SELECT toString(memory_id) AS id, substringUTF8( if(JSONType(value) = ?, JSONExtractString(value), value), ?, {chars:UInt32} ) AS text FROM loom.memory WHERE org = {org:String} AND namespace = {ns:Str @@ -2389,7 +2390,6 @@ f067ae13d549 SELECT chunk_id, path, scope, kind, start_line, end_line, content, f06c74498575 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id != {id:String} AND use f072c6c29b23 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 = { f08249ee1acf SELECT kind, name, status, description, cardinality, created_by, updated_at FROM loom.namespace_ontology FINAL WHERE org = {org:String} AND namespace = {ns:String} AND kind = {kind:String} AND status -f0c46bd2964b SELECT org, toString(memory_id) AS memory_id, namespace, agent, user_id, session_id, memory_key, version, content_sha256, tags FROM ( SELECT org, memory_id, namespace, agent, user_id, session_id, memo f0d1a655888a SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER f0e13f039554 ALTER TABLE loom.knowledge_source_listings DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? f106a32ca75c 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 diff --git a/tests/integration/test_curator_draft_candidate.py b/tests/integration/test_curator_draft_candidate.py new file mode 100644 index 00000000000..be6fdf7cf2a --- /dev/null +++ b/tests/integration/test_curator_draft_candidate.py @@ -0,0 +1,311 @@ +"""A curator's draft in the review queue, against a running server: only a namespace +administrator lists and decides it, a person accepts it by the hash served, the fact is +the reviewer's, a refused write leaves the draft pending, and it leaves with its +namespace.""" + +from __future__ import annotations + +import json +import uuid +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime +from typing import Any + +import httpx + +from server.memory.domain.definitions import CURATOR_DRAFT_KIND +from tests.integration._resources import unique_org + +VALUE = "Returns are accepted within 30 days of delivery." +KEY = "curator/gap/returns" +POINTER = { + "kind": "document", + "key": "handbook/returns", + "version": 3, + "sha256": "a" * 64, + "recheck": ["handbook/returns"], + "run_id": "cur-0000000001", + "redraft_of": "", +} +_COLUMNS = [ + "candidate_id", + "org", + "namespace", + "memory_key", + "memory_type", + "proposed_value", + "supporter_count", + "confidence_avg", + "supporters", + "rationale", + "status", + "proposed_at", + "version", + "source_kind", + "source_resource_id", + "evidence", +] +_CANDIDATE = ( + "SELECT status, decided_by, proposed_value, evidence FROM loom.learnings_queue FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} AND candidate_id = {cid:UUID}" +) +_FACT = ( + "SELECT agent, user_id, session_id, memory_type, tags, actor, source_class, source_trace, " + "source_resource_id, grounding, evidence FROM loom.memory FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} AND memory_key = {key:String} " + "AND tombstoned_at IS NULL" +) + + +def _token(org: str, ns: str, subject: str, role: str, *, person: bool) -> str: + from server.auth.jwt import mint_token + + return mint_token( + subject=subject, + org=org, + namespaces=[ns], + roles=[role], + ttl_seconds=600, + is_service_account=not person, + ) + + +def _seed(ch_client: Any, org: str, ns: str, *, key: str = KEY, value: str = VALUE) -> str: + """One pending draft, written as the queue's writer would write it.""" + cid = str(uuid.uuid4()) + ch_client.insert( + "loom.learnings_queue", + [ + [ + cid, + org, + ns, + key, + "semantic", + json.dumps(value), + 3, + 0.0, + [], + "A model wrote this answer from the cited document.", + "pending", + datetime(2026, 1, 1), + 1, + CURATOR_DRAFT_KIND, + "gap-returns", + json.dumps(POINTER), + ] + ], + column_names=_COLUMNS, + ) + return cid + + +class _Namespace: + """One fresh namespace with a token per kind of caller.""" + + def __init__(self, base_url: str, label: str) -> None: + self.url, self.org, self.ns = base_url, unique_org(label), "support" + self.scope = {"org": self.org, "namespace": self.ns} + self.alice = _token(self.org, self.ns, "alice", "admin", person=True) + self.robot = _token(self.org, self.ns, "sa:curation-bot", "admin", person=False) + self.writer = _token(self.org, self.ns, "wendy", "writer", person=True) + self.viewer = _token(self.org, self.ns, "vik", "viewer", person=True) + + def post(self, token: str, op: str, **body: Any) -> httpx.Response: + with httpx.Client(base_url=self.url, timeout=120.0) as c: + return c.post( + f"/v1/{op}", + json={**self.scope, **body}, + headers={"Authorization": f"Bearer {token}"}, + ) + + def ok(self, token: str, op: str, **body: Any) -> dict[str, Any]: + r = self.post(token, op, **body) + assert r.status_code == 200, f"{op}: {r.status_code} {r.text[:300]}" + return dict(r.json()) + + def drafts(self, token: str, status: str = "pending") -> list[dict[str, Any]]: + rows = self.ok(token, "learnings.list", status=status)["rows"] + return [r for r in rows if r["source_kind"] == CURATOR_DRAFT_KIND] + + def candidate(self, ch_client: Any, cid: str) -> tuple[Any, ...]: + rows = ch_client.query( + _CANDIDATE, parameters={"org": self.org, "ns": self.ns, "cid": cid} + ).result_rows + return tuple(rows[0]) if rows else () + + def facts(self, ch_client: Any, key: str = KEY) -> list[tuple[Any, ...]]: + return list( + ch_client.query( + _FACT, parameters={"org": self.org, "ns": self.ns, "key": key} + ).result_rows + ) + + +def test_only_an_admin_lists_and_reviews_a_draft(control_plane_url: str, ch_client: Any) -> None: + """Fails when a viewer or writer sees the row, a count of it, or anything but the + answer a candidate that does not exist gets.""" + space = _Namespace(control_plane_url, "draft-readers") + cid = _seed(ch_client, space.org, space.ns) + + (entry,) = space.drafts(space.alice) + assert (entry["candidate_id"], entry["proposed_value"]) == (cid, VALUE) + assert entry["evidence"] == POINTER and len(entry["content_sha256"]) == 64 + assert entry["source_resource_id"] == "gap-returns" + counted = space.ok(space.alice, "learnings.quality", source_kind=CURATOR_DRAFT_KIND) + assert [r["pending"] for r in counted["rows"]] == [1] + + for token in (space.viewer, space.writer): + for kind in (None, CURATOR_DRAFT_KIND): + listed = space.ok(token, "learnings.list", source_kind=kind) + assert listed["rows"] == [], listed + counts = space.ok(token, "learnings.quality", source_kind=kind) + assert counts["rows"] == [], counts + for decision in ("promote", "reject"): + body = {"decision": decision, "approved_sha256": entry["content_sha256"]} + refused = space.post(token, "learnings.review", candidate_id=cid, **body) + missing = space.post(token, "learnings.review", candidate_id=str(uuid.uuid4()), **body) + assert refused.status_code == missing.status_code >= 400, refused.text + assert refused.json()["detail"]["code"] == missing.json()["detail"]["code"], ( + refused.text + ) + assert VALUE not in refused.text and "handbook" not in refused.text + assert space.candidate(ch_client, cid)[0] == "pending" + + +def test_a_human_admin_promotes_by_hash_and_the_fact_is_served( + control_plane_url: str, ch_client: Any +) -> None: + """Fails when a service account or a wrong hash promotes, when the right one leaves + no served row, or when the row is not the reviewer's derived fact.""" + space = _Namespace(control_plane_url, "draft-accept") + cid = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + review = {"candidate_id": cid, "decision": "promote"} + + by_robot = space.post(space.robot, "learnings.review", **review, approved_sha256=sha) + assert by_robot.status_code == 403, by_robot.text + for wrong in ("", "b" * 64): + refused = space.post(space.alice, "learnings.review", **review, approved_sha256=wrong) + assert refused.status_code == 409, refused.text + assert refused.json()["detail"]["code"] == "PRECONDITION_FAILED" and sha not in refused.text + assert space.candidate(ch_client, cid)[0] == "pending" and space.facts(ch_client) == [] + + done = space.ok(space.alice, "learnings.review", **review, approved_sha256=sha, approver="x") + assert (done["new_status"], done["promoted_to_shared"]) == ("promoted", True) + status, decided_by, _, evidence = space.candidate(ch_client, cid) + assert (status, decided_by, json.loads(evidence)) == ("promoted", "human:alice", POINTER) + (fact,) = space.facts(ch_client) + assert fact[:5] == ("loom-curator", "-", "-", "semantic", []) + assert fact[5:9] == ("human:alice", "derived", f"curator:{cid}", POINTER["key"]) + assert (fact[9], json.loads(fact[10])) == ("verbatim", POINTER) + + # A viewer reads the accepted fact as any other, with the hash the reviewer approved. + got = space.ok(space.viewer, "memory.get", agent="loom-curator", memory_key=KEY) + assert (got["value"], got["content_sha256"]) == (VALUE, sha) + # The decided draft is listed to administrators under its status, and a repeat of + # the promotion answers it without a second write. + assert [r["candidate_id"] for r in space.drafts(space.alice, "promoted")] == [cid] + again = space.ok(space.alice, "learnings.review", **review, approved_sha256=sha) + assert again["new_status"] == "promoted" and len(space.facts(ch_client)) == 1 + + # No request body reaches the two columns the review set. + space.ok( + space.writer, + "memory.set", + agent="support-bot", + memory_key="forged", + value="A fact a writer states.", + grounding="verbatim", + evidence="forged", + _grounding="verbatim", + _evidence="forged", + ) + assert [(f[9], f[10]) for f in space.facts(ch_client, "forged")] == [("", "")] + + +def test_a_key_that_now_holds_a_row_refuses_and_the_draft_stays_pending( + control_plane_url: str, ch_client: Any +) -> None: + """Fails when the candidate is decided after a refused write, or the row under the + key is replaced by the draft.""" + space = _Namespace(control_plane_url, "draft-taken") + cid = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + space.ok( + space.writer, + "memory.set", + agent="loom-curator", + memory_key=KEY, + value="Returns need a receipt.", + ) + + refused = space.post( + space.alice, "learnings.review", candidate_id=cid, decision="promote", approved_sha256=sha + ) + assert refused.status_code == 409, refused.text + assert refused.json()["detail"]["code"] == "PRECONDITION_FAILED" + assert space.candidate(ch_client, cid)[0] == "pending" + got = space.ok(space.viewer, "memory.get", agent="loom-curator", memory_key=KEY) + assert got["value"] == "Returns need a receipt." + (fact,) = space.facts(ch_client) + assert (fact[5], fact[9]) == ("human:wendy", "") + + +def test_namespace_erasure_removes_a_draft(control_plane_url: str, ch_client: Any) -> None: + """Fails when the value or the pointer is selectable after the erasure, for a + pending draft or a decided one.""" + space = _Namespace(control_plane_url, "draft-erase") + pending = _seed(ch_client, space.org, space.ns) + rejected = _seed(ch_client, space.org, space.ns, key="curator/gap/refunds") + space.ok(space.robot, "learnings.review", candidate_id=rejected, decision="reject") + # A rejection copies the text and the pointer into its status row. + assert space.candidate(ch_client, rejected)[2:] == (json.dumps(VALUE), json.dumps(POINTER)) + + erased = space.ok( + space.alice, + "erasure.request", + scope_type="namespace", + scope_value=space.ns, + requester="ops", + ) + assert erased["status"] == "completed", erased + left = ch_client.query( + "SELECT count() FROM loom.learnings_queue WHERE org = {org:String} " + "AND (proposed_value != '' OR evidence != '')", + parameters={"org": space.org}, + ).result_rows + assert left == [(0,)] + assert space.candidate(ch_client, pending) == () == space.candidate(ch_client, rejected) + + +def test_two_reviews_of_one_draft_leave_one_decision( + control_plane_url: str, ch_client: Any +) -> None: + """A promotion and a rejection sent at once: fails when both answer success, or the + fact and the candidate's status disagree.""" + space = _Namespace(control_plane_url, "draft-race") + cid = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + + def send(decision: str) -> httpx.Response: + return space.post( + space.alice, + "learnings.review", + candidate_id=cid, + decision=decision, + approved_sha256=sha, + ) + + with ThreadPoolExecutor(max_workers=2) as pool: + promote, reject = pool.map(send, ("promote", "reject")) + codes = sorted((promote.status_code, reject.status_code)) + # The loser met the reviewer's claim (503) or the decision already made (409). + assert codes[0] == 200 and codes[1] in (409, 503), (promote.text, reject.text) + status = space.candidate(ch_client, cid)[0] + assert status == ("promoted" if promote.status_code == 200 else "rejected") + assert len(space.facts(ch_client)) == (1 if status == "promoted" else 0) + # Once it is decided, the other decision is refused whoever asks again. + other = "reject" if status == "promoted" else "promote" + assert send(other).status_code == 409 + assert space.candidate(ch_client, cid)[0] == status diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index 7800603dc3d..254f7ebb59c 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -3022,7 +3022,8 @@ "decision", "destination", "reason", - "approver" + "approver", + "approved_sha256" ] } }, diff --git a/tests/unit/test_curator_draft_candidate.py b/tests/unit/test_curator_draft_candidate.py new file mode 100644 index 00000000000..ed07a260cb2 --- /dev/null +++ b/tests/unit/test_curator_draft_candidate.py @@ -0,0 +1,515 @@ +"""A curator's draft is a private review candidate: a namespace administrator reads it, +a person accepts it by hash, and the accepted text is that reviewer's fact.""" + +from __future__ import annotations + +import json +import uuid +from contextlib import asynccontextmanager +from datetime import datetime +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +from fastapi import HTTPException + +from server.auth.jwt import AuthInfo +from server.core.errors import ( + AuthInsufficientError, + OverloadedError, + PreconditionFailedError, + ValidationError, +) +from server.core.hashing import served_content_sha256 +from server.memory.api.models_crud import MemorySetInput +from server.memory.api.models_learnings import ( + LearningsListInput, + LearningsQualityInput, + LearningsReviewInput, +) +from server.memory.app import ( + curator_draft_review, + definition_queue, + definition_review, + learning_access, + learnings, + write, +) +from server.memory.domain.definitions import ( + CURATOR_DRAFT_KIND, + CURATOR_DRAFT_MIGRATION, + DEFINITION_DRAFT_KINDS, + PRIVATE_CANDIDATE_KINDS, +) +from server.memory.store import learnings as repository +from server.memory.store.history import HistoryTarget +from server.operations.base import Role +from tests.unit.ch_fake import RecordingCH +from tests.unit.definition_queue_fake import install +from tests.unit.principals import NAMESPACE, ORG, acting_as, principal + +CID = str(uuid.UUID(int=7)) +KEY = "curator/gap/returns" +VALUE = "Returns are accepted within 30 days of delivery." +SHA = served_content_sha256(VALUE) +POINTER = { + "kind": "document", + "key": "handbook/returns", + "version": 3, + "sha256": "a" * 64, + "recheck": ["handbook/returns"], + "run_id": "cur-0000000001", + "redraft_of": "", +} +ALICE = principal("admin", subject="Alice", service_account=False) +ROBOT = principal("admin", subject="sa:robot") +READER = principal("viewer", subject="Rita", service_account=False) + + +def draft(**over: Any) -> dict[str, Any]: + return { + "candidate_id": CID, + "memory_key": KEY, + "memory_type": "semantic", + "proposed_value": json.dumps(VALUE), + "supporter_count": 3, + "confidence_avg": 0.0, + "supporters": [], + "rationale": "A model wrote this answer from the cited document.", + "source_kind": CURATOR_DRAFT_KIND, + "source_resource_id": "gap-1", + "agent": "", + "evidence": json.dumps(POINTER), + "seeded_from_thread_id": None, + "seeded_from_msg_id": None, + "status": "pending", + "proposed_at": datetime(2026, 1, 1), + "decided_at": None, + "decided_by": "", + "decision_reason": "", + "version": 10**19, + **over, + } + + +@pytest.fixture +def review(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """The review's seams: the candidate it reads, the fact it writes, the decision row + it records, the live row under the draft's key, and whether the fleet is ready.""" + from server.auth import aliases, authz + from server.core import leases + + state: dict[str, Any] = { + "fence": install(monkeypatch), + "candidate": draft(), + "head": None, + "fleet": True, + "writes": [], + "decisions": [], + } + + async def find(*a: Any, **kw: Any) -> Any: + return state["candidate"] + + async def decide(row: dict[str, Any]) -> None: + state["decisions"].append(row) + state["candidate"] = {**state["candidate"], **row} + + async def put(input: MemorySetInput) -> None: + state["writes"].append(input) + + async def head(identity: Any, key: str, **kw: Any) -> Any: + assert (identity.agent, identity.user_id, identity.session_id) == ("loom-curator", "-", "-") + assert key == KEY and kw["strong"] and not kw["include_expired"] + return state["head"] + + async def admits(self: authz.CachedGate, namespace: str, role: Role) -> bool: + assert (self.org, namespace, role) == (ORG, NAMESPACE, Role.ADMIN) + return Role.ADMIN in self.auth.roles + + async def read_aliases(org: str, subject: str, ch: Any) -> list[str]: + return [subject] + + async def fleet_at(ch: Any, migration: int) -> bool: + assert migration == CURATOR_DRAFT_MIGRATION + return bool(state["fleet"]) + + @asynccontextmanager + async def claim(name: str, **kw: Any) -> Any: + assert name == f"definition.review/{ORG}/{NAMESPACE}/{CID}" + yield True + + monkeypatch.setattr(leases, "holding", claim) + monkeypatch.setattr(authz.CachedGate, "admits", admits) + monkeypatch.setattr(aliases, "read_aliases", read_aliases) + monkeypatch.setattr("server.auth.machines.fleet_at", fleet_at) + monkeypatch.setattr("server.core.ch.get_client", lambda: object()) + monkeypatch.setattr(learnings.learnings_repo, "find_candidate", find) + monkeypatch.setattr(learnings.learnings_repo, "insert_row", decide) + monkeypatch.setattr(curator_draft_review.memory_repo, "get_by_key", head) + monkeypatch.setattr(write, "handle_memory_set", put) + return state + + +def request(decision: str = "promote", **kw: Any) -> LearningsReviewInput: + return LearningsReviewInput( + org=ORG, namespace=NAMESPACE, candidate_id=CID, decision=decision, **kw + ) + + +async def decide(auth: AuthInfo | None, decision: str = "promote", **kw: Any) -> Any: + with acting_as(auth): + return await learnings.handle_learnings_review(request(decision, **kw)) + + +# ---- visibility + + +async def test_every_visibility_use_takes_the_private_tuple( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Fails when a list, quality, erasure or scrub statement, the queue's erasure fence + or the lineage gate still filters on the definition kinds alone.""" + assert PRIVATE_CANDIDATE_KINDS == (*DEFINITION_DRAFT_KINDS, CURATOR_DRAFT_KIND) + private = list(PRIVATE_CANDIDATE_KINDS) + ch = RecordingCH(strict=False) + ch.install(monkeypatch) + monkeypatch.setattr(repository, "_default_client", lambda: ch) + + with acting_as(READER): + monkeypatch.setattr(learnings, "private_candidates_visible", _no) + await learnings.handle_learnings_list(LearningsListInput(org=ORG, namespace=NAMESPACE)) + await learnings.handle_learnings_quality( + LearningsQualityInput(org=ORG, namespace=NAMESPACE, source_kind=CURATOR_DRAFT_KIND) + ) + await repository.private_candidate_namespaces("org = {org:String}", {"org": ORG}) + await repository.private_candidates_after(ORG, NAMESPACE, "") + await repository.scrub_private_candidate(ORG, NAMESPACE, CID) + + listed, counted = ch.statements("ORDER BY proposed_at"), ch.statements("approve_ratio") + assert "source_kind NOT IN {excluded_kinds:Array(String)}" in listed[0].sql + assert listed[0].params["excluded_kinds"] == private + # A viewer who asks for the kind by name still gets no count of it. + assert "source_kind NOT IN {private_kinds:Array(String)}" in counted[0].sql + assert (counted[0].params["private_kinds"], counted[0].params["draft_admin_ns"]) == ( + private, + [], + ) + assert ch.statements("SELECT DISTINCT namespace")[0].params["private_kinds"] == private + assert ch.statements("toString(candidate_id) >")[0].params["kinds"] == private + scrub = ch.statements("ALTER TABLE loom.learnings_queue UPDATE")[0] + assert scrub.params["kinds"] == private and "evidence = ''" in scrub.sql + + monkeypatch.setattr(learning_access, "private_candidates_visible", _no) + assert not await learning_access.candidate_visible(ORG, NAMESPACE, CURATOR_DRAFT_KIND) + assert await learning_access.candidate_visible(ORG, NAMESPACE, "conversation_seeder") + + # The queue's writer fence is the erasure fence: a draft row takes it. + fence = install(monkeypatch) + await definition_queue.persist({**draft(), "org": ORG, "namespace": NAMESPACE}) + assert len(fence.reads) == 1 and len(ch.inserted("learnings_queue")) == 1 + await definition_queue.persist( + {**draft(source_kind="conversation_seeder"), "org": ORG, "namespace": NAMESPACE} + ) + assert len(fence.reads) == 1 + + +async def _no(*a: Any, **kw: Any) -> bool: + return False + + +async def test_only_an_admin_gets_a_draft_entry_with_its_hash_and_pointer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Fails when the entry of a draft lacks the hash a reviewer accepts it by or its + pointer, or when another candidate's entry carries either.""" + rows = [draft(), draft(candidate_id=str(uuid.UUID(int=8)), source_kind="conversation_seeder")] + ch = RecordingCH().on("FROM loom.learnings_queue FINAL", rows) + monkeypatch.setattr(repository, "_default_client", lambda: ch) + with acting_as(None): + out = await learnings.handle_learnings_list( + LearningsListInput(org=ORG, namespace=NAMESPACE) + ) + entry, other = out.rows + assert (entry.content_sha256, entry.evidence) == (SHA, POINTER) + assert (other.content_sha256, other.evidence) == ("", None) + assert "evidence" in ch.statements("ORDER BY proposed_at")[0].sql + + +# ---- review + + +@pytest.mark.parametrize( + ("auth", "approved", "refusal"), + [ + (ROBOT, SHA, AuthInsufficientError), + (ALICE, "", PreconditionFailedError), + (ALICE, "b" * 64, PreconditionFailedError), + (ALICE, SHA, None), + ], + ids=["service account", "no hash", "another hash", "the hash served"], +) +async def test_promote_needs_a_person_and_the_hash( + review: dict[str, Any], auth: AuthInfo, approved: str, refusal: type[Exception] | None +) -> None: + """Fails when any case but the last promotes, or a refusal writes anything.""" + if refusal is None: + out = await decide(auth, approved_sha256=approved) + assert (out.new_status, out.promoted_to_shared) == ("promoted", True) + assert len(review["writes"]) == 1 and review["decisions"][0]["status"] == "promoted" + return + with pytest.raises(refusal) as refused: + await decide(auth, approved_sha256=approved) + assert not review["writes"] and not review["decisions"] + # The 409 never returns the stored hash: a reviewer approves text they have read. + assert SHA not in str(getattr(refused.value, "payload", "")) + str(refused.value) + + +async def test_a_draft_is_promoted_only_to_memory(review: dict[str, Any]) -> None: + """Fails when a draft reaches the knowledge store, which serves it without the + curator's identity or its pointer.""" + for destination in ("knowledge", "both"): + with pytest.raises(ValidationError): + await decide(ALICE, approved_sha256=SHA, destination=destination) + assert not review["writes"] and not review["decisions"] + + +async def test_reject_needs_admin_only( + review: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a viewer rejects, or an administrator's service account cannot.""" + with pytest.raises(HTTPException) as missing: + await decide(READER, "reject") + assert missing.value.status_code == 404 + assert missing.value.detail == {"code": "RESOURCE_NOT_FOUND"} + assert not review["decisions"] + + out = await decide(ROBOT, "reject", approved_sha256="ignored", reason="not our policy") + assert (out.new_status, out.promoted_to_shared) == ("rejected", False) + assert not review["writes"] + row = review["decisions"][0] + assert (row["status"], row["decided_by"]) == ("rejected", "process:sa:robot") + # The decided row keeps the draft's pointer and its first proposal time. + assert row["evidence"] == json.dumps(POINTER) and row["proposed_at"] == datetime(2026, 1, 1) + assert row["version"] > 10**19 + + +async def test_the_promoted_row_is_the_reviewers_fact(review: dict[str, Any]) -> None: + """Fails when the write lacks `absent`, `derived`, the pointer or the curator agent, + or when the row or the decision is stamped with another actor.""" + await decide(ALICE, approved_sha256=SHA, approver="forged") + (fact,) = review["writes"] + assert (fact.org, fact.namespace, fact.agent, fact.user_id, fact.session_id) == ( + ORG, + NAMESPACE, + "loom-curator", + "-", + "-", + ) + assert (fact.memory_key, fact.memory_type, fact.value, fact.tags) == ( + KEY, + "semantic", + VALUE, + [], + ) + assert (fact.if_match_sha256, fact.source_class) == ("absent", "derived") + assert (fact.source_trace, fact.source_resource_id) == (f"curator:{CID}", POINTER["key"]) + assert (fact._grounding, fact._evidence) == ("verbatim", json.dumps(POINTER)) + assert review["decisions"][0]["decided_by"] == "human:Alice" + + state = write._SetWrite( + input=fact, + version=1, + retyped_from="", + existing=None, + expires_at=None, + serialized_value=json.dumps(VALUE), + new_sha=SHA, + ) + with acting_as(ALICE): + write._set_build_memory_row(state) + row = state.memory_row + assert (row["actor"], row["source_class"]) == ("human:Alice", "derived") + assert (row["grounding"], row["evidence"]) == ("verbatim", json.dumps(POINTER)) + + +async def test_a_draft_that_cites_no_document_is_not_promoted(review: dict[str, Any]) -> None: + """Fails when a draft with no pointer is written as a fact resting on a document.""" + review["candidate"] = draft(evidence="") + with pytest.raises(ValidationError): + await decide(ALICE, approved_sha256=SHA) + assert not review["writes"] and not review["decisions"] + + +@pytest.mark.parametrize( + ("first", "second"), [("promote", "reject"), ("reject", "promote")], ids=str +) +async def test_a_decided_draft_refuses_the_other_decision( + review: dict[str, Any], first: str, second: str +) -> None: + """The two orders of a promotion and a rejection that meet: fails when both + succeed, or the fact and the candidate's status disagree.""" + await decide(ALICE, first, approved_sha256=SHA) + with pytest.raises(PreconditionFailedError): + await decide(ALICE, second, approved_sha256=SHA) + assert [row["status"] for row in review["decisions"]] == [ + "promoted" if first == "promote" else "rejected" + ] + assert len(review["writes"]) == (1 if first == "promote" else 0) + # A repeat of the decision made answers its status and writes nothing more. + again = await decide(ALICE, first, approved_sha256=SHA) + assert again.new_status == review["decisions"][0]["status"] + assert len(review["decisions"]) == 1 and len(review["writes"]) <= 1 + + +async def test_a_promotion_interrupted_after_the_write_completes_on_retry( + review: dict[str, Any], +) -> None: + """Fails when a repeat writes the fact twice (which `absent` refuses, leaving the + draft pending for ever), or records a promotion over another row under the key.""" + review["head"] = SimpleNamespace(source_trace=f"curator:{CID}", value=VALUE) + out = await decide(ALICE, approved_sha256=SHA) + assert out.new_status == "promoted" and not review["writes"] + assert review["decisions"][0]["status"] == "promoted" + + for other in ( + SimpleNamespace(source_trace="", value=VALUE), + SimpleNamespace(source_trace=f"curator:{CID}", value="Another text."), + ): + review.update(candidate=draft(), head=other, writes=[], decisions=[]) + await decide(ALICE, approved_sha256=SHA) + # The write is sent, and its `absent` precondition is what refuses it. + assert [w.if_match_sha256 for w in review["writes"]] == ["absent"] + + +async def test_review_waits_for_the_fleet(review: dict[str, Any]) -> None: + """Fails when a draft is decided while a replica that lists it to viewers serves.""" + review["fleet"] = False + for decision in ("promote", "reject"): + with pytest.raises(OverloadedError): + await decide(ALICE, decision, approved_sha256=SHA) + assert not review["writes"] and not review["decisions"] + + +def test_the_fleet_constant_names_the_migration_file() -> None: + """Fails when the constant is not the number of the file that adds the column: a + renumbered file would open the gate on a fleet without it.""" + migrations = Path(__file__).parents[2] / "schemas" / "migrations" + body = (migrations / f"{CURATOR_DRAFT_MIGRATION:03d}_curator_draft_evidence.sql").read_text() + assert "ALTER TABLE loom.learnings_queue" in body and "`evidence`" in body + + +# ---- what a request may send + + +def test_clients_cannot_send_grounding_or_evidence() -> None: + """Fails when a wire `memory.set` body sets either private attribute, over the HTTP + transport's validation or the MCP tool's schema.""" + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport.arg_check import unknown_args + from server.transport.mcp_schemas import model_schema + + model = OPERATIONS_BY_NAME["memory.set"].input_model + assert model is MemorySetInput + forged = {"_grounding": "verbatim", "_evidence": "{}", "grounding": "verbatim", "evidence": "x"} + body = {"org": ORG, "namespace": NAMESPACE, "agent": "a", "memory_key": "k", "value": "v"} + # Both transports build the input with `model_validate` of the request's arguments. + for parsed in ( + model.model_validate({**body, **forged}), + model.model_validate_json(json.dumps({**body, **forged})), + ): + assert (parsed._grounding, parsed._evidence) == ("", "") + assert set(unknown_args(model, {**body, **forged})) == set(forged) + for schema in (model.model_json_schema(), model_schema(model)): + assert not {"grounding", "evidence", "_grounding", "_evidence"} & set(schema["properties"]) + # A copy the write path makes keeps what the review set. + fact = model.model_validate(body) + fact._grounding = "verbatim" + assert fact.model_copy(update={"memory_type": "semantic"})._grounding == "verbatim" + assert "_grounding" not in fact.model_dump() + + +# ---- redaction + + +def _target(**over: Any) -> HistoryTarget: + fields: dict[str, Any] = { + "org": ORG, + "memory_id": str(uuid.UUID(int=9)), + "namespace": NAMESPACE, + "agent": "loom-curator", + "user_id": "-", + "session_id": "-", + "memory_key": KEY, + "version": 5, + "content_sha256": SHA, + "source_trace": f"curator:{CID}", + } + return HistoryTarget(**{**fields, **over}) + + +@pytest.fixture +def scrubs(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + state: dict[str, Any] = {"candidate": draft(status="promoted"), "reads": [], "scrubbed": []} + install(monkeypatch) + + async def find(org: str, namespace: str, cid: str, **kw: Any) -> Any: + state["reads"].append(cid) + return state["candidate"] + + async def scrub(org: str, namespace: str, cid: str) -> None: + state["scrubbed"].append((org, namespace, cid)) + + async def page(*a: Any, **kw: Any) -> Any: + raise AssertionError("a promoted draft's candidate is read by id, never scanned for") + + monkeypatch.setattr(repository, "find_candidate", find) + monkeypatch.setattr(repository, "scrub_private_candidate", scrub) + monkeypatch.setattr(repository, "private_candidates_after", page) + return state + + +async def test_redacting_a_promoted_draft_blanks_its_candidate(scrubs: dict[str, Any]) -> None: + """Fails when the draft's text outlives the redaction of the fact it became, or the + candidate is looked for by scanning the queue.""" + await definition_review.redact_candidates(ORG, _target(), None) + assert scrubs["reads"] == [CID] and scrubs["scrubbed"] == [(ORG, NAMESPACE, CID)] + + +async def test_redacting_a_moved_promoted_draft_blanks_its_candidate( + scrubs: dict[str, Any], +) -> None: + """A move replaces the fact's key, tags and value: fails when the candidate is then + found by key or by the text's hash, which no longer name it.""" + moved = _target(memory_key="handbook/returns-window", tags=("policy",), content_sha256="c" * 64) + await definition_review.redact_candidates(ORG, moved, None) + assert scrubs["scrubbed"] == [(ORG, NAMESPACE, CID)] + + +@pytest.mark.parametrize( + ("target", "candidate"), + [ + (_target(agent="support-bot"), draft()), + (_target(source_trace="curator:not-an-id"), draft()), + (_target(), draft(source_kind="conversation_seeder")), + (_target(), None), + ], + ids=["another agent's row", "a trace with no id", "another kind", "no candidate"], +) +async def test_a_row_that_names_no_draft_blanks_nothing( + scrubs: dict[str, Any], target: HistoryTarget, candidate: Any +) -> None: + """Fails when a trace a caller wrote blanks a candidate that is no draft, or fails + the redaction it rides on.""" + scrubs["candidate"] = candidate + await definition_review.redact_candidates(ORG, target, None) + assert not scrubs["scrubbed"] + + +async def test_a_redacted_version_whose_text_is_still_live_keeps_the_draft( + scrubs: dict[str, Any], +) -> None: + """Fails when redacting an old version blanks the draft of the text still served.""" + await definition_review.redact_candidates(ORG, _target(), SimpleNamespace(content_sha256=SHA)) + assert not scrubs["reads"] and not scrubs["scrubbed"] diff --git a/tests/unit/test_definition_draft_redaction.py b/tests/unit/test_definition_draft_redaction.py index 26361957c89..82e6fd62040 100644 --- a/tests/unit/test_definition_draft_redaction.py +++ b/tests/unit/test_definition_draft_redaction.py @@ -29,6 +29,7 @@ async def test_redaction_reaches_exact_text_and_tag_but_not_other_drafts( namespace="n", content_sha256=served_content_sha256(VALUE), tags=("candidate-id:b",), + source_trace="", ) async def page(org: str, ns: str, after: str) -> Any: diff --git a/tests/unit/test_definition_queue_erasure.py b/tests/unit/test_definition_queue_erasure.py index b9c843e195d..499e6299e75 100644 --- a/tests/unit/test_definition_queue_erasure.py +++ b/tests/unit/test_definition_queue_erasure.py @@ -239,6 +239,7 @@ async def test_historical_redaction_cannot_finish_before_late_status_send( namespace="n", content_sha256=served_content_sha256(json.loads(VALUE)), tags=(), + source_trace="", ) async def page(org: str, namespace: str, after: str) -> Any: @@ -272,6 +273,7 @@ async def test_historical_scrub_holds_writer_fence_until_all_versions_settle( namespace="n", content_sha256=served_content_sha256(json.loads(VALUE)), tags=(), + source_trace="", ) async def page(org: str, namespace: str, after: str) -> Any: diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index ce15a349ee1..b1d7e0c4406 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", + "139_curator_draft_evidence.sql", ] diff --git a/tests/unit/test_sdk_learnings_client.py b/tests/unit/test_sdk_learnings_client.py index 73944345ad6..0cc055b0b4a 100644 --- a/tests/unit/test_sdk_learnings_client.py +++ b/tests/unit/test_sdk_learnings_client.py @@ -37,3 +37,16 @@ async def test_review_sends_destination_only_when_given() -> None: assert op == "/v1/learnings.review" assert "destination" not in unset assert given["destination"] == "memory" + + +@pytest.mark.asyncio +async def test_review_sends_the_approved_hash_only_when_given() -> None: + """Fails when the helper drops the hash a draft is accepted by, or sends an empty + one for every other candidate.""" + ag = _Agent() + c = LearningsClient(ag) # type: ignore[arg-type] + await c.review("cid-1", "promote") + await c.review("cid-1", "promote", approved_sha256="a" * 64) + (_, unset), (_, given) = ag.transport.calls + assert "approved_sha256" not in unset + assert given["approved_sha256"] == "a" * 64 From cf1ad5409db4f940682c17e876eb763cf8b52b69 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 10:05:40 +0000 Subject: [PATCH 2/3] A refused promotion of a curator draft releases the writer lease, and a merged write leaves the draft pending `learnings.review` marks the write of a draft's fact uncertain only while its outcome is unknown. A refusal `memory.set` raises before its insert (409 `PRECONDITION_FAILED`, 409 `PINNED_CONFLICT`, 422 `BLACKLISTED`) clears the mark, so the lease `definition.writer/` is released with the review and the next review, redaction or namespace erasure in the org is not refused until the lease expires. A failure of unknown outcome keeps the lease. `memory.set` merges a draft whose text a row of the namespace already states and stores no row under the draft's key. The review answers 409 `PRECONDITION_FAILED`, naming that row's key when the reviewer may read it, and the draft stays pending. The curator page, the comment on `MemorySetInput` and a test comment say that no `memory.set` body sets `grounding` or `evidence` and that a `memory.bulk_set` entry sets both. `learnings.list` takes a draft's value from the decode its hash is taken over. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/curator.md | 6 +- server/memory/api/models_crud.py | 7 +- server/memory/app/curator_draft_review.py | 27 +++++- server/memory/app/learnings.py | 37 +++++--- .../test_curator_draft_candidate.py | 41 ++++++++- tests/unit/test_curator_draft_candidate.py | 84 ++++++++++++++++++- 6 files changed, 178 insertions(+), 24 deletions(-) diff --git a/docs/architecture/curator.md b/docs/architecture/curator.md index b346159e49a..1423a115509 100644 --- a/docs/architecture/curator.md +++ b/docs/architecture/curator.md @@ -554,10 +554,12 @@ A promotion writes the draft through `memory.set` as the curator's namespace-wid | `source_class` | `derived` | | `source_trace` | `curator:` | | `source_resource_id` | The `key` of the cited document. | -| `grounding`, `evidence` | `verbatim` and the draft's pointer. No request body can set either column. | +| `grounding`, `evidence` | `verbatim` and the draft's pointer. No `memory.set` body sets either column. | | Precondition | `if_match_sha256: absent`: the write lands only where no live row holds the key. | -A refusal of the write leaves the draft pending: a row now under the key (409 `PRECONDITION_FAILED`), a blacklisted value, or a conflict with a pinned fact. A review that stopped after the write and before the decision row completes on a repeat: a live row of the curator that carries the draft's trace and content hash is taken as written, and the repeat records the decision without a second write. Rejecting a draft writes no memory. +A `memory.bulk_set` entry sets `grounding` and `evidence` on the row it writes, so neither column proves that a review accepted a row. + +A refusal of the write leaves the draft pending: a row now under the key (409 `PRECONDITION_FAILED`), a blacklisted value, a conflict with a pinned fact, or a text that a row of the namespace already states. `memory.set` merges such a text into that row and stores nothing under the draft's key, so the review answers 409 `PRECONDITION_FAILED`, naming that row's key when the reviewer may read it. None of these refusals keeps the lease that serializes the private candidate writes of the org, so the next review, redaction or erasure proceeds at once. A review that stopped after the write and before the decision row completes on a repeat: a live row of the curator that carries the draft's trace and content hash is taken as written, and the repeat records the decision without a second write. Rejecting a draft writes no memory. ### Redaction and erasure diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index 818fa12924f..088099a84d2 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -421,9 +421,10 @@ class MemorySetInput(_Identity): # conflict-flags an established fact; a key that already holds one is # refused (409 KEY_HOLDS_FACT) — propose under a new key. proposed: bool = False - # Not on the wire: the row's `grounding` and `evidence` columns, set by the review - # that accepts a curator's draft (`learnings.review`) and by no request body. A - # private attribute is no field, so validation never reads either from a transport. + # Not on the wire: the row's `grounding` and `evidence` columns, which the review + # that accepts a curator's draft (`learnings.review`) sets and no `memory.set` body + # can. A private attribute is no field, so validation never reads either from a + # transport. A `memory.bulk_set` entry sets both columns, so neither proves a review. _grounding: str = PrivateAttr(default="") _evidence: str = PrivateAttr(default="") diff --git a/server/memory/app/curator_draft_review.py b/server/memory/app/curator_draft_review.py index d2ee7b6cb47..6b508faba90 100644 --- a/server/memory/app/curator_draft_review.py +++ b/server/memory/app/curator_draft_review.py @@ -17,7 +17,7 @@ from server.core.hashing import served_content_sha256 from server.identity.app.reviewers import NotAReviewer, reviewer_subjects from server.identity.domain.read_scope import WHOLE_NAMESPACE -from server.memory.api.models_crud import MemorySetInput +from server.memory.api.models_crud import MemorySetInput, MemorySetOutput from server.memory.api.models_learnings import LearningsReviewInput from server.memory.app.provenance import writer_actor from server.memory.domain.definitions import CURATOR_DRAFT_MIGRATION @@ -25,6 +25,8 @@ # The `source_trace` of the fact an accepted draft becomes, before its candidate id. TRACE = "curator:" +# The refusals `memory.set` raises before it inserts a row. +_REFUSED_BEFORE_INSERT = frozenset({"PRECONDITION_FAILED", "PINNED_CONFLICT", "BLACKLISTED"}) async def require_fleet() -> None: @@ -134,6 +136,29 @@ async def written(write: MemorySetInput) -> bool: ) +def require_stored(answer: MemorySetOutput) -> None: + """Refuse a promotion whose write stored no row under the draft's key: `memory.set` + merges a text a row of the namespace already states and inserts nothing, so no row + would carry the reviewer, the draft's trace or its pointer.""" + if not answer.noop: + return + held = f" ({answer.merged_into_key!r})" if answer.merged_into_key else "" + raise PreconditionFailedError( + f"a row of this namespace{held} already states this draft's text, so no fact " + "was written; reject the draft" + ) + + +def stored_nothing(refusal: Exception) -> bool: + """Whether a refused promotion is known to have stored no row under the draft's key: + a refusal `memory.set` raises before its insert, or `require_stored` after its + answer. Any other failure leaves the write's outcome unknown.""" + if isinstance(refusal, PreconditionFailedError): + return True + detail = getattr(refusal, "detail", None) + return isinstance(detail, dict) and detail.get("code") in _REFUSED_BEFORE_INSERT + + def candidate_of(agent: str, source_trace: str) -> str: """The candidate id the row of an accepted draft names; '' for any other row, one whose trace a caller wrote with no id in it included.""" diff --git a/server/memory/app/learnings.py b/server/memory/app/learnings.py index 67accfe8cb3..46c59fe65f8 100644 --- a/server/memory/app/learnings.py +++ b/server/memory/app/learnings.py @@ -8,7 +8,7 @@ from typing import Any, Literal from server.core.datetimes import naive_utc_now -from server.core.errors import ValidationError +from server.core.errors import PreconditionFailedError, ValidationError from server.core.pg_lease import PublicationPending from server.memory.api.models_crud import MemorySetInput from server.memory.api.models_learnings import ( @@ -60,12 +60,16 @@ async def handle_learnings_list( entries = [] for r in rows: r = {**r, **support.get(str(r["candidate_id"]), {})} - try: - proposed_value = json.loads(r["proposed_value"]) if r["proposed_value"] else None - except (ValueError, TypeError): - proposed_value = r["proposed_value"] - # What a reviewer accepts a draft by, and what the draft rests on. + # What a reviewer accepts a draft by, and what the draft rests on. Its value + # comes from the decode its hash is taken over. draft = r.get("source_kind") == CURATOR_DRAFT_KIND + if draft: + proposed_value = curator_draft_review.value(r) + else: + try: + proposed_value = json.loads(r["proposed_value"]) if r["proposed_value"] else None + except (ValueError, TypeError): + proposed_value = r["proposed_value"] entries.append( _LearningEntry( candidate_id=str(r["candidate_id"]), @@ -353,6 +357,8 @@ async def _promote( ) -> tuple[bool, str | None]: """Write a promoted candidate to memory, knowledge, or both. Returns whether memory was written and the knowledge document's `source_uri` (None when none was written).""" + from fastapi import HTTPException + private_definition = row.get("source_kind") in DEFINITION_DRAFT_KINDS curator_draft = row.get("source_kind") == CURATOR_DRAFT_KIND # A bot rule is promoted with the confidence the reviewer saw: the mean over @@ -387,9 +393,17 @@ async def _promote( if curator_draft: assert uncertain is not None # private reviews hold the evidence writer fence uncertain(True) - # A refused write (a row now under a draft's key, the blacklist, a pinned - # conflict) bubbles up and the candidate stays pending. - await _do_promote(input.org, input.namespace, promoted, input.approver, input.reason) + try: + # A refused write (a row now under a draft's key, the blacklist, a pinned + # conflict, a text another row states) bubbles up and the candidate stays + # pending. + await _do_promote(input.org, input.namespace, promoted, input.approver, input.reason) + except (HTTPException, PreconditionFailedError) as refusal: + # Known to have stored no row: the org's writer fence is released now. Only + # a write of unknown outcome leaves it to expire. + if uncertain is not None and curator_draft_review.stored_nothing(refusal): + uncertain(False) + raise if curator_draft: assert uncertain is not None uncertain(False) @@ -500,14 +514,15 @@ async def _promote_via_memory_set( namespace-wide row (`user_id` '-'), which reads bounded to one user do not serve, with the supporters' mean confidence. A curator's draft lands as the curator's namespace-wide row under the draft's key, only where no row is - (`curator_draft_review.fact`), and once: a repeat that finds it written writes nothing.""" + (`curator_draft_review.fact`), and once: a repeat that finds it written writes nothing. + A write that stored no row, because another row states the text, is refused.""" from server.memory.app.write import handle_memory_set if candidate_row.get("source_kind") == CURATOR_DRAFT_KIND: write = curator_draft_review.fact(org, namespace, candidate_row) if not await curator_draft_review.written(write): # 409 PRECONDITION_FAILED (a row now under the key) bubbles up. - await handle_memory_set(write) + curator_draft_review.require_stored(await handle_memory_set(write)) return deserialized = _proposed_value(candidate_row) diff --git a/tests/integration/test_curator_draft_candidate.py b/tests/integration/test_curator_draft_candidate.py index be6fdf7cf2a..eff1c080f11 100644 --- a/tests/integration/test_curator_draft_candidate.py +++ b/tests/integration/test_curator_draft_candidate.py @@ -209,7 +209,8 @@ def test_a_human_admin_promotes_by_hash_and_the_fact_is_served( again = space.ok(space.alice, "learnings.review", **review, approved_sha256=sha) assert again["new_status"] == "promoted" and len(space.facts(ch_client)) == 1 - # No request body reaches the two columns the review set. + # No `memory.set` body reaches the two columns the review set. A `memory.bulk_set` + # entry sets both, so neither column proves that a review accepted a row. space.ok( space.writer, "memory.set", @@ -227,8 +228,9 @@ def test_a_human_admin_promotes_by_hash_and_the_fact_is_served( def test_a_key_that_now_holds_a_row_refuses_and_the_draft_stays_pending( control_plane_url: str, ch_client: Any ) -> None: - """Fails when the candidate is decided after a refused write, or the row under the - key is replaced by the draft.""" + """Fails when the candidate is decided after a refused write, the row under the key + is replaced by the draft, or the refusal keeps the next review of a private + candidate in the org out.""" space = _Namespace(control_plane_url, "draft-taken") cid = _seed(ch_client, space.org, space.ns) sha = space.drafts(space.alice)[0]["content_sha256"] @@ -250,6 +252,39 @@ def test_a_key_that_now_holds_a_row_refuses_and_the_draft_stays_pending( assert got["value"] == "Returns need a receipt." (fact,) = space.facts(ch_client) assert (fact[5], fact[9]) == ("human:wendy", "") + # The refusal released the org's writer lease, so the draft is rejected at once. + done = space.ok(space.robot, "learnings.review", candidate_id=cid, decision="reject") + assert done["new_status"] == "rejected" + + +def test_a_text_another_row_states_refuses_and_the_draft_stays_pending( + control_plane_url: str, ch_client: Any +) -> None: + """Fails when a draft whose text a row of the namespace already states is recorded + as promoted: `memory.set` merges it into that row and stores nothing under the + draft's key, so no row is the reviewer's fact.""" + space = _Namespace(control_plane_url, "draft-stated") + cid = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + space.ok( + space.writer, + "memory.set", + agent="support-bot", + memory_key="policy/returns", + memory_type="semantic", + value=VALUE, + ) + + refused = space.post( + space.alice, "learnings.review", candidate_id=cid, decision="promote", approved_sha256=sha + ) + assert refused.status_code == 409, refused.text + assert refused.json()["detail"]["code"] == "PRECONDITION_FAILED" + # The refusal names the row that states the text, which the reviewer may read. + assert "policy/returns" in refused.json()["detail"]["message"] + assert space.candidate(ch_client, cid)[0] == "pending" and space.facts(ch_client) == [] + done = space.ok(space.robot, "learnings.review", candidate_id=cid, decision="reject") + assert done["new_status"] == "rejected" def test_namespace_erasure_removes_a_draft(control_plane_url: str, ch_client: Any) -> None: diff --git a/tests/unit/test_curator_draft_candidate.py b/tests/unit/test_curator_draft_candidate.py index ed07a260cb2..2ee5d187e9a 100644 --- a/tests/unit/test_curator_draft_candidate.py +++ b/tests/unit/test_curator_draft_candidate.py @@ -22,7 +22,7 @@ ValidationError, ) from server.core.hashing import served_content_sha256 -from server.memory.api.models_crud import MemorySetInput +from server.memory.api.models_crud import MemorySetInput, MemorySetOutput from server.memory.api.models_learnings import ( LearningsListInput, LearningsQualityInput, @@ -95,8 +95,9 @@ def draft(**over: Any) -> dict[str, Any]: @pytest.fixture def review(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: - """The review's seams: the candidate it reads, the fact it writes, the decision row - it records, the live row under the draft's key, and whether the fleet is ready.""" + """The review's seams: the candidate it reads, the fact it writes and what the write + answers or refuses with, the decision row it records, the live row under the draft's + key, and whether the fleet is ready.""" from server.auth import aliases, authz from server.core import leases @@ -106,6 +107,8 @@ def review(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: "head": None, "fleet": True, "writes": [], + "answer": MemorySetOutput(version=1, memory_key=KEY, conflict_verdict="clear"), + "refusal": None, "decisions": [], } @@ -116,8 +119,12 @@ async def decide(row: dict[str, Any]) -> None: state["decisions"].append(row) state["candidate"] = {**state["candidate"], **row} - async def put(input: MemorySetInput) -> None: + async def put(input: MemorySetInput) -> MemorySetOutput: state["writes"].append(input) + if state["refusal"] is not None: + raise state["refusal"] + answer: MemorySetOutput = state["answer"] + return answer async def head(identity: Any, key: str, **kw: Any) -> Any: assert (identity.agent, identity.user_id, identity.session_id) == ("loom-curator", "-", "-") @@ -383,6 +390,75 @@ async def test_a_promotion_interrupted_after_the_write_completes_on_retry( assert [w.if_match_sha256 for w in review["writes"]] == ["absent"] +def _refused(status: int, code: str) -> HTTPException: + return HTTPException(status_code=status, detail={"code": code}) + + +@pytest.mark.parametrize( + "refusal", + [ + _refused(409, "PRECONDITION_FAILED"), + _refused(409, "PINNED_CONFLICT"), + _refused(422, "BLACKLISTED"), + ], + ids=["a row now under the key", "a pinned conflict", "the blacklist"], +) +async def test_a_refused_write_releases_the_writer_fence( + review: dict[str, Any], refusal: HTTPException +) -> None: + """Fails when a refusal `memory.set` raises before its insert decides the draft, or + leaves the org's writer fence to expire: until it does, every other write of a + private candidate in the org is refused, a rejection of this draft included.""" + review["refusal"] = refusal + with pytest.raises(HTTPException) as refused: + await decide(ALICE, approved_sha256=SHA) + assert refused.value is refusal + assert len(review["writes"]) == 1 and not review["decisions"] + assert not review["fence"].holders + + review["refusal"] = None + out = await decide(ROBOT, "reject") + assert out.new_status == "rejected" and not review["fence"].holders + + +@pytest.mark.parametrize( + "failure", + [RuntimeError("the connection dropped"), _refused(503, "BACKEND_UNAVAILABLE")], + ids=["a dropped connection", "an unavailable backend"], +) +async def test_a_write_of_unknown_outcome_keeps_the_writer_fence( + review: dict[str, Any], failure: Exception +) -> None: + """Fails when a write that may have stored its row releases the fence a namespace + erasure takes, which lets the erasure pass a row still on its way.""" + review["refusal"] = failure + with pytest.raises(type(failure)): + await decide(ALICE, approved_sha256=SHA) + assert not review["decisions"] + (holder,) = review["fence"].holders.values() + assert holder.retained + + +async def test_a_draft_another_row_already_states_stays_pending( + review: dict[str, Any], +) -> None: + """Fails when a write `memory.set` merged into a row that already states the text, + which stores nothing under the draft's key, is recorded as a promotion: no row would + carry the reviewer, the draft's trace or its pointer.""" + review["answer"] = MemorySetOutput( + version=1, + memory_key=KEY, + merged_into_key="handbook/returns-window", + conflict_verdict="merge", + noop=True, + ) + with pytest.raises(PreconditionFailedError) as refused: + await decide(ALICE, approved_sha256=SHA) + assert "handbook/returns-window" in str(refused.value) + assert len(review["writes"]) == 1 and not review["decisions"] + assert not review["fence"].holders + + async def test_review_waits_for_the_fleet(review: dict[str, Any]) -> None: """Fails when a draft is decided while a replica that lists it to viewers serves.""" review["fleet"] = False From b03bc9a45731f0f4ecc398c685ac8222bade2aff Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 10:45:42 +0000 Subject: [PATCH 3/3] A draft's promotion refused by a lock or a deleted text releases the writer lease `memory.set` refuses a draft's write with 423 `LOCKED` when a row under the draft's key is locked `read_only` and holds another text, and with 422 `VALIDATION_FAILED` (`reason: "forgotten"`) when the text is, or contains, a value deleted in the namespace. Neither leaves an insert on its way: the lock is read before the insert, and the deleted values are checked before each insert is sent. The review releases the lease `definition.writer/` on both, as it does on the other refusals of the write, so the next review, redaction or erasure in the org is not refused until that lease expires. Any other failure keeps the lease. `stored_nothing` is renamed `outcome_known`. The check of deleted values also runs before the embedding row is sent, after the memory row is in, so the helper answers what the lease needs: that no insert is on its way. The curator page lists each refusal of the write with its answer. It says that a merged write adds one `conflict.merge` count and, under `auto_reinforce`, one `evidence` usage event on the row merged into when the reviewer may read it, for each attempt. It limits "no memory row and no decision row" to the refusals raised before the write. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/curator.md | 19 ++++++- server/memory/app/curator_draft_review.py | 17 ++++--- server/memory/app/learnings.py | 14 +++--- .../test_curator_draft_candidate.py | 50 +++++++++++++++++++ tests/unit/test_curator_draft_candidate.py | 24 +++++++-- 5 files changed, 104 insertions(+), 20 deletions(-) diff --git a/docs/architecture/curator.md b/docs/architecture/curator.md index 1423a115509..ac7be837b9b 100644 --- a/docs/architecture/curator.md +++ b/docs/architecture/curator.md @@ -541,7 +541,7 @@ A draft is an answer the curator wrote to a question several people asked, from - A service account that promotes is refused with 403 `AUTH_INSUFFICIENT`. - One review of a draft runs at a time: a second answers 503 `OVERLOADED` while the first holds the draft's claim. - A draft is decided once. A decided draft answers its status to a repeat of the same decision and 409 `PRECONDITION_FAILED` to the other one. Its `promoted` or `rejected` row is what records that the question was drafted, and a later draft of the same question is a new candidate that names it in `redraft_of`. -- A refusal writes nothing. +- Each of these refusals is raised before the write: it stores no memory row and no decision row. ### The fact @@ -559,7 +559,22 @@ A promotion writes the draft through `memory.set` as the curator's namespace-wid A `memory.bulk_set` entry sets `grounding` and `evidence` on the row it writes, so neither column proves that a review accepted a row. -A refusal of the write leaves the draft pending: a row now under the key (409 `PRECONDITION_FAILED`), a blacklisted value, a conflict with a pinned fact, or a text that a row of the namespace already states. `memory.set` merges such a text into that row and stores nothing under the draft's key, so the review answers 409 `PRECONDITION_FAILED`, naming that row's key when the reviewer may read it. None of these refusals keeps the lease that serializes the private candidate writes of the org, so the next review, redaction or erasure proceeds at once. A review that stopped after the write and before the decision row completes on a repeat: a live row of the curator that carries the draft's trace and content hash is taken as written, and the repeat records the decision without a second write. Rejecting a draft writes no memory. +A refusal of the write leaves the draft pending and records no decision: + +| The write is refused by | The review answers | +| --------------------------------------------------------------------- | -------------------------------------------------- | +| A row now under the key | 409 `PRECONDITION_FAILED` | +| A row under the key that is locked `read_only` and holds another text | 423 `LOCKED` | +| A blacklisted value | 422 `BLACKLISTED` | +| A conflict with a pinned fact | 409 `PINNED_CONFLICT` | +| A text that is, or contains, a value deleted in the namespace | 422 `VALIDATION_FAILED` with `reason: "forgotten"` | +| A text that a row of the namespace already states | 409 `PRECONDITION_FAILED` | + +Deleting an accepted fact makes its text a deleted value ([refusal](../features/memory/conflicts-and-refusal.md#refusal-the-blacklist)), so a later draft that restates it is refused: reject that draft. + +`memory.set` merges a text that a row already states into that row and stores nothing under the draft's key. The review's answer names that row's key when the reviewer may read it. The merge itself is recorded: it adds one `conflict.merge` count to `loom.memory_drops`, and under the `auto_reinforce` [conflict policy](../features/memory/conflicts-and-refusal.md#namespace-conflict-policy), the default, it records one `evidence` usage event on that row when the reviewer may read it. A repeat of the promotion records both again. + +None of these refusals keeps the lease that serializes the private candidate writes of the org, so the next review, redaction or erasure proceeds at once. A review that stopped after the write and before the decision row completes on a repeat: a live row of the curator that carries the draft's trace and content hash is taken as written, and the repeat records the decision without a second write. Rejecting a draft writes no memory. ### Redaction and erasure diff --git a/server/memory/app/curator_draft_review.py b/server/memory/app/curator_draft_review.py index 6b508faba90..c86ea9ee08b 100644 --- a/server/memory/app/curator_draft_review.py +++ b/server/memory/app/curator_draft_review.py @@ -25,8 +25,10 @@ # The `source_trace` of the fact an accepted draft becomes, before its candidate id. TRACE = "curator:" -# The refusals `memory.set` raises before it inserts a row. -_REFUSED_BEFORE_INSERT = frozenset({"PRECONDITION_FAILED", "PINNED_CONFLICT", "BLACKLISTED"}) +# The refusal codes a draft's write can meet, each raised before `memory.set` inserts a row. +_REFUSED_BEFORE_INSERT = frozenset( + {"PRECONDITION_FAILED", "PINNED_CONFLICT", "BLACKLISTED", "LOCKED"} +) async def require_fleet() -> None: @@ -149,12 +151,15 @@ def require_stored(answer: MemorySetOutput) -> None: ) -def stored_nothing(refusal: Exception) -> bool: - """Whether a refused promotion is known to have stored no row under the draft's key: - a refusal `memory.set` raises before its insert, or `require_stored` after its - answer. Any other failure leaves the write's outcome unknown.""" +def outcome_known(refusal: Exception) -> bool: + """Whether a refused promotion left no insert on its way. `memory.set` raises its + refusal codes before its insert and checks a text against the namespace's deletions + before each insert it sends, and `require_stored` raises after the write's answer. + Any other failure leaves the write's outcome unknown.""" if isinstance(refusal, PreconditionFailedError): return True + if isinstance(refusal, ValidationError): + return refusal.extra.get("reason") == "forgotten" detail = getattr(refusal, "detail", None) return isinstance(detail, dict) and detail.get("code") in _REFUSED_BEFORE_INSERT diff --git a/server/memory/app/learnings.py b/server/memory/app/learnings.py index 46c59fe65f8..db1430ccdc8 100644 --- a/server/memory/app/learnings.py +++ b/server/memory/app/learnings.py @@ -394,14 +394,14 @@ async def _promote( assert uncertain is not None # private reviews hold the evidence writer fence uncertain(True) try: - # A refused write (a row now under a draft's key, the blacklist, a pinned - # conflict, a text another row states) bubbles up and the candidate stays - # pending. + # A refused write (a row now under a draft's key, a lock on it, the blacklist, + # a pinned conflict, a text a deletion refuses or another row states) bubbles + # up and the candidate stays pending. await _do_promote(input.org, input.namespace, promoted, input.approver, input.reason) - except (HTTPException, PreconditionFailedError) as refusal: - # Known to have stored no row: the org's writer fence is released now. Only - # a write of unknown outcome leaves it to expire. - if uncertain is not None and curator_draft_review.stored_nothing(refusal): + except (HTTPException, PreconditionFailedError, ValidationError) as refusal: + # No insert is on its way: the org's writer fence is released now. Only a + # write of unknown outcome leaves it to expire. + if uncertain is not None and curator_draft_review.outcome_known(refusal): uncertain(False) raise if curator_draft: diff --git a/tests/integration/test_curator_draft_candidate.py b/tests/integration/test_curator_draft_candidate.py index eff1c080f11..63f863bdb43 100644 --- a/tests/integration/test_curator_draft_candidate.py +++ b/tests/integration/test_curator_draft_candidate.py @@ -257,6 +257,56 @@ def test_a_key_that_now_holds_a_row_refuses_and_the_draft_stays_pending( assert done["new_status"] == "rejected" +def test_a_locked_row_under_the_key_refuses_and_the_draft_stays_pending( + control_plane_url: str, ch_client: Any +) -> None: + """Fails when a draft replaces a locked row under its key, or the lock's refusal + keeps the next review of a private candidate in the org out.""" + space = _Namespace(control_plane_url, "draft-locked") + cid = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + held = {"agent": "loom-curator", "memory_key": KEY} + space.ok(space.writer, "memory.set", value="Returns need a receipt.", **held) + assert space.ok(space.writer, "memory.lock", reason="legal hold", **held)["locked"] + + refused = space.post( + space.alice, "learnings.review", candidate_id=cid, decision="promote", approved_sha256=sha + ) + assert refused.status_code == 423, refused.text + assert refused.json()["detail"]["code"] == "LOCKED" + assert space.candidate(ch_client, cid)[0] == "pending" + got = space.ok(space.viewer, "memory.get", **held) + assert got["value"] == "Returns need a receipt." + done = space.ok(space.robot, "learnings.review", candidate_id=cid, decision="reject") + assert done["new_status"] == "rejected" + + +def test_a_redraft_of_a_deleted_fact_refuses_and_the_draft_stays_pending( + control_plane_url: str, ch_client: Any +) -> None: + """Fails when a draft that restates a fact deleted in the namespace is written, or + the deletion's refusal keeps the next review of a private candidate in the org out.""" + space = _Namespace(control_plane_url, "draft-forgotten") + first = _seed(ch_client, space.org, space.ns) + sha = space.drafts(space.alice)[0]["content_sha256"] + space.ok( + space.alice, "learnings.review", candidate_id=first, decision="promote", approved_sha256=sha + ) + space.ok(space.writer, "memory.delete", agent="loom-curator", memory_key=KEY) + assert space.facts(ch_client) == [] + again = _seed(ch_client, space.org, space.ns) + + refused = space.post( + space.alice, "learnings.review", candidate_id=again, decision="promote", approved_sha256=sha + ) + assert refused.status_code == 422, refused.text + detail = refused.json()["detail"] + assert (detail["code"], detail["reason"]) == ("VALIDATION_FAILED", "forgotten") + assert space.candidate(ch_client, again)[0] == "pending" and space.facts(ch_client) == [] + done = space.ok(space.robot, "learnings.review", candidate_id=again, decision="reject") + assert done["new_status"] == "rejected" + + def test_a_text_another_row_states_refuses_and_the_draft_stays_pending( control_plane_url: str, ch_client: Any ) -> None: diff --git a/tests/unit/test_curator_draft_candidate.py b/tests/unit/test_curator_draft_candidate.py index 2ee5d187e9a..7a725674d01 100644 --- a/tests/unit/test_curator_draft_candidate.py +++ b/tests/unit/test_curator_draft_candidate.py @@ -36,6 +36,7 @@ learnings, write, ) +from server.memory.domain import lock from server.memory.domain.definitions import ( CURATOR_DRAFT_KIND, CURATOR_DRAFT_MIGRATION, @@ -43,6 +44,7 @@ PRIVATE_CANDIDATE_KINDS, ) from server.memory.store import learnings as repository +from server.memory.store import refusals from server.memory.store.history import HistoryTarget from server.operations.base import Role from tests.unit.ch_fake import RecordingCH @@ -400,17 +402,25 @@ def _refused(status: int, code: str) -> HTTPException: _refused(409, "PRECONDITION_FAILED"), _refused(409, "PINNED_CONFLICT"), _refused(422, "BLACKLISTED"), + lock.refusal(SimpleNamespace(memory_key=KEY), "value", op="memory.set", mode="read_only"), + refusals._refused(), + ], + ids=[ + "a row now under the key", + "a pinned conflict", + "the blacklist", + "a locked row under the key", + "a text a deletion refuses", ], - ids=["a row now under the key", "a pinned conflict", "the blacklist"], ) async def test_a_refused_write_releases_the_writer_fence( - review: dict[str, Any], refusal: HTTPException + review: dict[str, Any], refusal: Exception ) -> None: """Fails when a refusal `memory.set` raises before its insert decides the draft, or leaves the org's writer fence to expire: until it does, every other write of a private candidate in the org is refused, a rejection of this draft included.""" review["refusal"] = refusal - with pytest.raises(HTTPException) as refused: + with pytest.raises(type(refusal)) as refused: await decide(ALICE, approved_sha256=SHA) assert refused.value is refusal assert len(review["writes"]) == 1 and not review["decisions"] @@ -423,8 +433,12 @@ async def test_a_refused_write_releases_the_writer_fence( @pytest.mark.parametrize( "failure", - [RuntimeError("the connection dropped"), _refused(503, "BACKEND_UNAVAILABLE")], - ids=["a dropped connection", "an unavailable backend"], + [ + RuntimeError("the connection dropped"), + _refused(503, "BACKEND_UNAVAILABLE"), + ValidationError("the value cannot be stored"), + ], + ids=["a dropped connection", "an unavailable backend", "a refusal of no known kind"], ) async def test_a_write_of_unknown_outcome_keeps_the_writer_fence( review: dict[str, Any], failure: Exception