diff --git a/docs/architecture/curator.md b/docs/architecture/curator.md index bfbaee32f1..72be47789f 100644 --- a/docs/architecture/curator.md +++ b/docs/architecture/curator.md @@ -196,7 +196,7 @@ A key can be held by more than one agent, user or session, and the drawer reads The **Scheduled pass** card says [whether the pass runs](#whether-the-pass-runs): a badge and one sentence for the `state`, with the time `next_due_at` names where a pass is due, then the newest pass, when it started and how it ended in words for its `outcome`. A due time that is not ahead reads **now**: the first pass of a `waiting` namespace is due at the time of the call, and only `overdue` says how long ago a pass was due. One link, **Pass history**, opens the Runs page on the curator's runs (`/runs?agent=loom-curator`), where the newest pass is the first row. A `state` or an `outcome` the tab has no words for draws no sentence of another state's: the card keeps the last pass and the link, and shows the outcome's code. -Under the state the card lists each entry of [`setup`](#what-the-curator-needs) that is not met and that the namespace's mode needs, with who can change it. For a newest pass that ran in `assist` mode it adds one line: how the model step ended, in words for its `model` code, the calls it made and what they cost, then what the curator spent in 24 hours against its share of the cap, from the [`budget`](#budget) section. +Under the state the card lists each entry of [`setup`](#what-the-curator-needs) that is not met and that the namespace's mode needs, with what it is needed for (a pass, model opinions or a draftable question) and who can change it. For a newest pass that ran in `assist` mode it adds one line: how the model step ended, in words for its `model` code, the calls it made and what they cost, then what the curator spent in 24 hours against its share of the cap, from the [`budget`](#budget) section. - A list that holds 20 findings says "The first 20 are listed." under it. The answer carries no total, so the tab cannot say how many more the section has. - A section with `unavailable` shows the reason in words: `too_large` reads "Too many rows to list here" and `no_usage_labels` reads "No usage labels in this namespace yet". For `primer` the guide's meter stays and "Too many pinned facts to measure" takes the place of the pinned facts' meter, which lists no row. @@ -263,6 +263,8 @@ In `assist` mode the curator sends content of this namespace to the deployment's - the namespace's guide; - the text of each pending proposal of its shared scope that is not marked `high`, cut to 2,000 characters. +A pass in this mode also sends the deployment's embedder the text of each repeated question it searches the namespace's shared documents with ([the question walk](#the-question-walk)). The gap build sent the embedder the same text when it grouped the question. + The mode is the namespace's side of the choice. A pass also needs the deployment's own switch, `LOOM_CURATOR_ENABLED`, which only the operator sets and which is off by default. With both, [the scheduled pass](#the-scheduled-pass) reads the namespace. [What the curator needs](#what-the-curator-needs) lists every prerequisite and who changes it. | Surface | How | @@ -276,7 +278,7 @@ The note of the third option says, before anything is saved: - what is sent: the sentence and the list above, and that the model's answer accepts and rejects nothing; - the amount the curator's share of the namespace's daily cost cap allows in 24 hours, or that the namespace has no cap; -- each [prerequisite](#what-the-curator-needs) that is not met, except the mode itself, with who can change it. +- each [prerequisite](#what-the-curator-needs) that is not met, except the mode itself, with what it is needed for and who can change it. The amount and the entries come from one `curator.status` call with `sections: ["budget"]`. **Save** waits for its answer and is allowed with entries unmet: the mode is the admin's part, and the rest may be another person's. When the call fails the note says the needs could not be read, and **Save** still sends the mode. A stored `assist` keeps the note, with nothing to save. A caller below the admin role sees what is sent, and the dialog makes no call for them. @@ -294,7 +296,7 @@ The refusal judges the row the call writes, with no further read. A first row th ## The scheduled pass -The worker `curator` runs a pass over each namespace whose mode is not `off`, once every `LOOM_CURATOR_CADENCE_SECONDS` (a day by default, an hour at the least; a runtime override reaches the next tick). A pass counts what `curator.status` reports for the namespace and writes one row of the [run ledger](../features/runs.md#curator-passes) that says when it ran, how it ended and what it counted. It changes no fact and stores no finding: the report is still computed when someone asks for it. In `findings` mode it calls no model. In `assist` mode it then runs [the model step](#the-model-step), and its row also holds the model's opinions. +The worker `curator` runs a pass over each namespace whose mode is not `off`, once every `LOOM_CURATOR_CADENCE_SECONDS` (a day by default, an hour at the least; a runtime override reaches the next tick). A pass counts what `curator.status` reports for the namespace and writes one row of the [run ledger](../features/runs.md#curator-passes) that says when it ran, how it ended and what it counted. It changes no fact and stores no finding: the report is still computed when someone asks for it. In `findings` mode it calls no model. In `assist` mode it then runs [the model step](#the-model-step), and its row also holds the model's opinions. It then decides which of the questions people keep asking a shared document could answer ([the question walk](#the-question-walk)), and its row holds a count for each code. The worker is off until the operator sets `LOOM_CURATOR_ENABLED`. A stored mode this build does not know, which a later build wrote, runs the same pass as `findings`. @@ -320,17 +322,18 @@ For each due namespace the tick: 5. Writes the pass row as `active`. 6. Counts the sections in five steps: `proposals`, `flagged`, `stale`, `pin`, then `primer` and `unpin` together, which share one read of the pinned facts. Each calls the function `curator.status` computes that section with, at 20 findings a section. 7. In `assist` mode, and when every section was counted, runs [the model step](#the-model-step). -8. Reads the erasure ledger. An erasure of the namespace that was open during the pass, or a ledger that cannot be read, closes the pass with no count, no opinion and no `unanswered` entry. -9. Writes the row again as `completed` or `failed`, with the outcome. - -| `outcome` | `status` | When | -| -------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ok` | `completed` | Every section was counted. A namespace with nothing to find has every count at 0. | -| `time_bound` | `completed` | The pass reached 120 s. The row holds the sections counted until then. | -| `mode_changed` | `completed` | The mode was set to `off` during the pass, which is read before each step, or was no longer `assist` before a model call. Later steps and calls do not run. | -| `erasure` | `completed` | An erasure reached the namespace during the pass. The row holds no count. | -| `error` | `failed` | A read failed. The row holds no count, and the worker notes a failed leg. | -| `abandoned` | `failed` | The pass never closed its row, and a later tick closed it. | +8. In `assist` mode, and when the model step left the outcome `ok`, runs [the question walk](#the-question-walk). +9. Reads the erasure ledger. An erasure of the namespace that was open during the pass, or a ledger that cannot be read, closes the pass with no count, no opinion, no `unanswered` entry and no question. +10. Writes the row again as `completed` or `failed`, with the outcome. + +| `outcome` | `status` | When | +| -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `ok` | `completed` | Every section was counted. A namespace with nothing to find has every count at 0. | +| `time_bound` | `completed` | The pass reached 120 s. The row holds the sections counted and the questions decided until then. | +| `mode_changed` | `completed` | The mode was set to `off` during the pass, which is read before each step, or was no longer `assist` before a model call or a question of the walk. Later steps, calls and questions do not run. | +| `erasure` | `completed` | An erasure reached the namespace during the pass. The row holds no count. | +| `error` | `failed` | A read failed. The row holds no count, and the worker notes a failed leg. | +| `abandoned` | `failed` | The pass never closed its row, and a later tick closed it. | A pass that ends `error` is the namespace's pass of that cadence: the next one runs a cadence later. @@ -370,6 +373,43 @@ The model answers one JSON object, `{"verdict": ..., "reason": ...}`, with a `ve Three calls in a row that raised or ran out of time end the model work as `unavailable`. An answer outside the sets comes from a provider that is up, so it starts that count again and the step goes on to the next proposal. +### The question walk + +After the model step, a pass in `assist` mode takes the 20 most asked gaps of the namespace's latest [gap build](knowledge-gaps.md#grouping) and decides, for each, whether a shared document could answer it: a document written for no one user (`user_id` is `-`). It decides by code alone: it asks no chat model and writes no fact. A question gets one code, that of the first step that ends it: + +| Step | Code | When | +| ---- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | `gap_ineligible` | The gap may no longer be drafted from: the asker floor changed, the gap left the latest build, or fewer than `LOOM_KNOWLEDGE_GAPS_MIN_ASKERS` people still asked any of its questions. A rule that cannot be read ends the question the same way. | +| 1 | `erasure` | An erasure that may have deleted a question was open when the gaps were built or has finished since. A ledger that cannot be read counts as one. | +| 2 | `definition_draft_exists` | A [definition draft](definition-drafts.md) claims the gap. | +| 3 | `already_drafted` | A candidate of source kind `curator_draft` claims the gap, in any status, or the namespace holds a fact under [the gap's draft key](#the-draft-key), deleted or not. | +| 3 | `drafted_other_wording` | A candidate of that kind claims another wording the gap groups. | +| 4 | `no_evidence` | No passage of the namespace's shared documents answers the question. | +| 4 | `sensitive_passage` | Every passage that answers it reads as `high` ([sensitivity](security.md#sensitivity)). | +| | `draftable` | No step ended it. | + +Step 1 is the check `knowledge.gaps.draft` makes, through the one function both call ([knowledge gaps](knowledge-gaps.md#the-list-and-the-dashboard)). + +Step 4 searches the namespace's documents with the question: the vector, BM25 and exact-key legs, fused, over the chunks of shared documents. It takes the 4 passages that rank first and keeps those that answer the question, by the rule that keeps a search from being recorded as a miss: a passage as close as a hit that answers a query, or an exact-key match. A document written for one user is never read. A namespace with no shared document gets no search, and each question that reaches the step is `no_evidence`. + +No step runs, and every question is counted under the reason, in a namespace where one of these holds, the first that does: + +| Code | When | +| ----------------- | -------------------------------------------------------------------------------------- | +| `gaps_off` | `LOOM_KNOWLEDGE_GAPS_ENABLED` is off. | +| `capture_off` | The namespace's capture level is `off`, or cannot be read. | +| `mirrored_source` | An active document source of the namespace is mirrored, or its sources cannot be read. | + +The search embeds the question: the walk sends the question's text to the deployment's embedder, as the gap build did when it grouped the question, and sends a chat model nothing. The embedding is a call made for the org, recorded as the namespace's spend under the operation `worker.curator`. A walk that has a gap to decide, in a namespace where none of the three reasons above holds, therefore reads the org's model switch and the curator's share of the namespace's daily cost cap once, before its first question. While the calls are off, the share is spent or either cannot be read, it decides no question and the row holds no `questions`. The embedder refuses a call for an org whose calls were switched off after that read, which fails the walk. + +A namespace with no gap build, or with a build that holds no gap, counts 0 for `draftable`, and one of the three reasons above counts every question, whatever the switch and the share are. A pass in `findings` mode never walks. + +The walk reads the mode and the pass's 120 s before each question. A mode that is no longer `assist` ends the pass as `mode_changed` and the time as `time_bound`, and the row keeps the questions decided until then. A walk that fails is a failed leg of the worker: the pass keeps its counts and opinions, and its row holds no `questions`. + +#### The draft key + +The draft key of a gap is `curator/gap/`, where `k` is the first 12 hex digits of a hash of the gap's id, keyed with the deployment's root secret under a label of its own. A gap's id is derived from its question, and a key must not reveal the question. The walk reads the key under the namespace's shared identity (agent, user and session `-`), as of every write that landed. + ### The pass row A pass is a row of `loom.agent_runs`, whose key is `(org, namespace, run_id)`: @@ -387,18 +427,21 @@ A pass is a row of `loom.agent_runs`, whose key is `(org, namespace, run_id)`: A pass in `assist` mode adds what [the model step](#the-model-step) did: -| Key | Value | -| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `prompt_version` | The version of the prompt the step asks with (`PROMPT_VERSION` in `server/memory/domain/curator_prompts.py`). | -| `model` | How the model work ended: a code of the model step's table. | -| `llm_calls` | The calls the step made, failed ones included. | -| `spend_usd` | What they cost. | -| `opinions` | One entry an answer, at most 20: `memory_id`, `hash_prefix`, `verdict`, `reason` and `guide_revision`. | -| `unanswered` | One entry a proposal the step took up and stored no opinion on: `memory_id`, `hash_prefix` and `guide_revision`. Its call failed, its answer was outside the sets, or its text reads as `high` and was not sent. | +| Key | Value | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `prompt_version` | The version of the prompt the step asks with (`PROMPT_VERSION` in `server/memory/domain/curator_prompts.py`). | +| `model` | How the model work ended: a code of the model step's table. | +| `llm_calls` | The calls the step made, failed ones included. | +| `spend_usd` | What they cost. | +| `opinions` | One entry an answer, at most 20: `memory_id`, `hash_prefix`, `verdict`, `reason` and `guide_revision`. | +| `questions` | What [the question walk](#the-question-walk) decided: `counts`, a number for each code that holds a question and for `draftable` always, and `by_hash`, each question's code under 12 hex digits of a hash of its gap's id. Absent when the walk did not run. | +| `unanswered` | One entry a proposal the step took up and stored no opinion on: `memory_id`, `hash_prefix` and `guide_revision`. Its call failed, its answer was outside the sets, or its text reads as `high` and was not sent. | An opinion holds no key, no value and no word the model wrote: the two codes come from closed sets. An `unanswered` entry holds the same id, hash prefix and revision and no reason. `hash_prefix` is the first 16 hex digits of a hash of the proposal's content hash, keyed with the deployment's root secret. Every viewer of the namespace can read the row, and the row outlives the proposal. A reader without the key cannot test a guessed value against the prefix, as they could against a prefix of the plain content hash. A deployment that rotates the root secret asks about each pending proposal once more. -A proposal a pass took up is in `opinions` or in `unanswered`, 20 in all at the most, and an opinion is the longer entry. The largest row, with 20 opinions, stays under the 6,000 characters. +A proposal a pass took up is in `opinions` or in `unanswered`, 20 in all at the most, and an opinion is the longer entry. The largest row, with 20 opinions and 20 questions, stays under the 6,000 characters. + +`questions` holds no question, no gap id, no draft key and no passage. The hash that names a question is keyed with the deployment's root secret under a label of its own, apart from the draft key's: a gap's id is derived from its question, so a reader of the row could test a guessed question against a plain id, and cannot against the hash. Every read of pass rows is one statement (`pass_rows` in `server/tasks/store/runs.py`): the rows of the namespace whose `run_id` lies between `cur-` and the end of the `cur-` prefix, at a `version` of 4 × 10^18 or more, newest first. A request path writes the nanosecond clock as its version, which is below that floor. A row a caller opened under a pass-shaped id on a build that did not reserve the shape is therefore never read as a pass, however far ahead its id is dated. @@ -414,17 +457,18 @@ A pass the supervisor stops, or one that loses its lease, writes nothing more. I ### Bounds of the pass -| Bound | Value | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -| Namespaces a tick selects | 5,000. A deployment with more notes a failed leg on every tick, and the namespaces past the bound get no pass. | -| Pass rows the dueness reads | Two cadences back, 200 namespaces a statement, 4 rows a namespace. A read that fills is repeated a namespace at a time. | -| Time a pass has | 120 s, checked before each step. | -| Time a tick starts passes for | 720 s. The supervisor cuts a tick at 900 s, which leaves the last pass its 120 s. | -| Passes at once | One a namespace, by the lease, and one after another inside a tick. | -| Model calls a pass | 20, one at a time, none started after 60 s of the pass. Three in a row that raised or ran out of time end them. | -| One model call | 60 output tokens, a proposal text of 2,000 characters, and 15 s for the client's retries and fallback model together. | -| Model spend in a namespace | `LOOM_CURATOR_CAP_SHARE` of its daily cost cap, read before every call: at most one call past the share. | -| Opinions the step compares | The namespace's last 100 pass rows, and `LOOM_MEMORY_PROPOSALS_SCAN_CAP` pending proposals without their value. | +| Bound | Value | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Namespaces a tick selects | 5,000. A deployment with more notes a failed leg on every tick, and the namespaces past the bound get no pass. | +| Pass rows the dueness reads | Two cadences back, 200 namespaces a statement, 4 rows a namespace. A read that fills is repeated a namespace at a time. | +| Time a pass has | 120 s, checked before each step. | +| Time a tick starts passes for | 720 s. The supervisor cuts a tick at 900 s, which leaves the last pass its 120 s. | +| Passes at once | One a namespace, by the lease, and one after another inside a tick. | +| Model calls a pass | 20, one at a time, none started after 60 s of the pass. Three in a row that raised or ran out of time end them. | +| One model call | 60 output tokens, a proposal text of 2,000 characters, and 15 s for the client's retries and fallback model together. | +| Questions a pass decides | 20, the most asked first, with 4 passages a question; none is started after the pass's 120 s. | +| Model spend in a namespace | `LOOM_CURATOR_CAP_SHARE` of its daily cost cap, read before every call of the model step: at most one call past the share. The walk reads it once, before its first question: at most the embeddings of 20 questions past the share. | +| Opinions the step compares | The namespace's last 100 pass rows, and `LOOM_MEMORY_PROPOSALS_SCAN_CAP` pending proposals without their value. | ### Limits of the pass @@ -438,6 +482,8 @@ A pass the supervisor stops, or one that loses its lease, writes nothing more. I - A proposal past the newest `LOOM_MEMORY_PROPOSALS_SCAN_CAP` pending ones gets no opinion until the queue shortens. - A proposal whose call fails or answers outside the sets is not asked about again in the pass. Later passes ask again, after the proposals no pass took up. One that never gets an answer therefore costs a call in every pass that has a place left for it. - The model reads the first 2,000 characters of a proposal, and the guide whole. +- A question's code is that of one pass: the next pass decides it again, and nothing is stored for a question but its code. +- The walk reads the latest gap build, which the gap worker makes once a day. A question first asked after that build is not decided until the next. ## Whether the pass runs @@ -467,20 +513,21 @@ Every answer of `curator.status` holds five fields besides its sections, whateve `last_pass` is the namespace's newest pass, whatever the mode is now, or `null` for a namespace with none: -| Field | From | -| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `run_id`, `started_at`, `status`, `duration_ms` | The pass row's own columns, as `run.list` serves them. `duration_ms` is the time from the pass's start to the write that closed its row, 0 while it runs. | -| `outcome`, `mode`, `counts` | The row's `metadata`: how the pass ended, the mode it ran in and what it counted by section. | -| `model`, `llm_calls`, `spend_usd` | The row's `metadata`: how [the model step](#the-model-step) ended, the calls it made and what they cost. `not_called`, 0 and 0 for a pass in another mode. | +| Field | From | +| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `run_id`, `started_at`, `status`, `duration_ms` | The pass row's own columns, as `run.list` serves them. `duration_ms` is the time from the pass's start to the write that closed its row, 0 while it runs. | +| `outcome`, `mode`, `counts` | The row's `metadata`: how the pass ended, the mode it ran in and what it counted by section. | +| `model`, `llm_calls`, `spend_usd` | The row's `metadata`: how [the model step](#the-model-step) ended, the calls it made and what they cost. `not_called`, 0 and 0 for a pass in another mode. | +| `questions` | The row's `metadata`: one entry for each code of [the question walk](#the-question-walk) that holds a question, and for `draftable` always, with `code`, `title` and `count`, `draftable` first. Empty for a pass whose walk did not run. | A row whose metadata is not a JSON object answers with the row's columns, an empty `outcome` and `mode` and no count, and so does a value of another type for its field. Neither fails the call. The state costs two reads, the registry row and the namespace's newest pass row, beside the reads of [`setup`](#what-the-curator-needs), whose `deployment_on` and `fleet_ready` entries decide `deployment_off`. The pass row is read through [the statement every read of a pass uses](#the-pass-row), so a caller's row under a pass-shaped id is never the last pass. -| Surface | What it shows | -| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Command line | `loom curator status` prints the state line first, then one line for each unmet entry of `setup` the namespace's mode needs, then the last pass, the model line of a pass in `assist` mode and the budget line of a namespace in `assist` mode, then the findings and one line an opinion: the verdict's title, the reason's title and the proposal's key. | -| Dashboard | The **Scheduled pass** card of the **Curator** tab, above the findings, with the unmet entries under the state ([the dashboard tab](#the-dashboard-tab)). | +| Surface | What it shows | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Command line | `loom curator status` prints the state line first, then one line for each unmet entry of `setup` the namespace's mode needs, then the last pass, the model line and the questions line of a pass in `assist` mode and the budget line of a namespace in `assist` mode, then the findings and one line an opinion: the verdict's title, the reason's title and the proposal's key. | +| Dashboard | The **Scheduled pass** card of the **Curator** tab, above the findings, with the unmet entries under the state ([the dashboard tab](#the-dashboard-tab)). | A server on a build without these fields sends none of them. The command line and the tab then show the findings alone, and an answer without `setup` or `budget` lists no entry and no amount. @@ -488,31 +535,36 @@ A server on a build without these fields sends none of them. The command line an `setup` lists every prerequisite of the curator in the namespace, each once, with whether it is met now. It is computed on every call, in every mode, so an admin reads why no pass ran or no opinion was given, and what is still missing before a mode is set. -| Field | Meaning | -| ------------ | ----------------------------------------------------------------------------------------- | -| `code` | The prerequisite, from the table below. | -| `title` | What it is, in words. | -| `needed_for` | `pass` for one the scheduled pass needs, `opinions` for one the model step needs besides. | -| `met` | Whether it holds now. One that cannot be read is not met. | -| `changed_by` | Who can change it: `operator`, `org_admin` or `namespace_admin`. | - -| `code` | Needed for | Who changes it | Met when | -| ------------------ | ---------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `deployment_on` | `pass` | `operator` | `LOOM_CURATOR_ENABLED` is set. | -| `fleet_ready` | `pass` | `operator` | Every live replica has the migration that adds the mode. | -| `mode` | `pass` | `namespace_admin` | The namespace's mode is not `off`. | -| `restricted_serve` | `pass` | `operator` | The namespace is not restricted, or `LOOM_RESTRICTED_SERVE` is set. | -| `provider` | `opinions` | `operator` | The deployment has a model provider. | -| `model_on` | `opinions` | `org_admin` | The org's model calls are switched on. | -| `under_cap` | `opinions` | `namespace_admin` | The curator's share of the namespace's daily cost cap is unspent, and so is the cap. A namespace without a cap meets it. | -| `guide` | `opinions` | `namespace_admin` | The namespace has a guide. | - -Each entry is the answer of one function of `server/memory/app/curator_gates.py`, and the worker's tick, the pass and the model step call the same function before they act. The list is therefore what the worker reads, not a second account of it. The `deployment_on` entry is whether the worker supervisor starts the worker: whether its row of the worker registry is enabled, which the deployment's switch decides. +| Field | Meaning | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `code` | The prerequisite, from the table below. | +| `title` | What it is, in words. | +| `needed_for` | `pass` for one the scheduled pass needs, `opinions` for one the model step needs besides, `drafts` for one a question needs to be counted as `draftable`. | +| `met` | Whether it holds now. One that cannot be read is not met. | +| `changed_by` | Who can change it: `operator`, `org_admin` or `namespace_admin`. | + +| `code` | Needed for | Who changes it | Met when | +| -------------------- | ---------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `deployment_on` | `pass` | `operator` | `LOOM_CURATOR_ENABLED` is set. | +| `fleet_ready` | `pass` | `operator` | Every live replica has the migration that adds the mode. | +| `mode` | `pass` | `namespace_admin` | The namespace's mode is not `off`. | +| `restricted_serve` | `pass` | `operator` | The namespace is not restricted, or `LOOM_RESTRICTED_SERVE` is set. | +| `provider` | `opinions` | `operator` | The deployment has a model provider. | +| `model_on` | `opinions` | `org_admin` | The org's model calls are switched on. | +| `under_cap` | `opinions` | `namespace_admin` | The curator's share of the namespace's daily cost cap is unspent, and so is the cap. A namespace without a cap meets it. | +| `guide` | `opinions` | `namespace_admin` | The namespace has a guide. | +| `gaps_on` | `drafts` | `operator` | `LOOM_KNOWLEDGE_GAPS_ENABLED` is set. | +| `capture_on` | `drafts` | `namespace_admin` | The namespace's capture level is not `off`. | +| `shared_documents` | `drafts` | `namespace_admin` | The namespace holds a current document written for no one user (`user_id` is `-`). | +| `no_mirrored_source` | `drafts` | `namespace_admin` | No active document source of the namespace is mirrored. | + +Each entry is the answer of one function of `server/memory/app/curator_gates.py`, and the worker's tick, the pass, the model step and the question walk call the same function before they act. The list is therefore what the worker reads, not a second account of it. The `deployment_on` entry is whether the worker supervisor starts the worker: whether its row of the worker registry is enabled, which the deployment's switch decides. - A guide that cannot be read leaves its entry unmet and fails nothing else when no section asked for reads the guide as well: the other entries, the state and the sections still answer, and the answer names the entry in `degraded` (`curator.status: prerequisite_unread`, with its code). `primer` reads the guide, and so do `proposals` and `opinions` in a namespace in `assist` mode with a pending proposal a model may be sent: a call that asks for one of them fails. A registry row that cannot be read fails the call, because the state reads it too. Any other read that fails leaves its entry unmet and names nothing in `degraded`. - An entry is about now. How a pass that ran earlier ended is in `last_pass`, whose `model` holds `no_provider`, `off` or `over_cap` for a model step one of these stopped, and `not_called` for a namespace without a guide. - 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`. +- [The question walk](#the-question-walk) needs `model_on` and `under_cap` besides its `drafts` entries, because its search embeds the question. An entry needed for `drafts` stops no pass and no opinion. +- 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` and `drafts` entries in `assist`. The settings dialog, where an admin is choosing `assist`, lists every unmet entry but `mode`. ## Source entry points @@ -542,6 +594,10 @@ Each entry is the answer of one function of `server/memory/app/curator_gates.py` - `server/memory/domain/curator.py` (`PASS_STEPS`, the `OUTCOME_` codes, `PASS_SECONDS`, `PASS_ABANDONED_SECONDS`, `TICK_START_SECONDS`): the steps, the outcomes and the bounds. - `server/identity/app/restricted_access.py` (`note_worker_access`): the audit row of a pass over a restricted namespace. - `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/app/curator_questions.py` (`walk`, `draft_key`, `question_hash`): the question walk, the draft key and the hash a pass row names a question with. +- `server/knowledge/app/gap_drafts.py` (`eligibility`, `most_asked`): the check a gap draft and the walk share, and the gaps a walk decides. +- `server/knowledge/app/knowledge_search.py` (`shared_passages`), `server/knowledge/app/search.py` (`shared_only`): the search of the namespace's shared documents. +- `server/memory/domain/curator.py` (the `QUESTION_` codes, `QUESTION_TITLES`, `QUESTIONS_A_PASS`, `PASSAGES_A_QUESTION`, `DRAFT_SOURCE_KIND`, `DRAFT_KEY_PREFIX`): the codes of the walk with their titles, its bounds, and the kind and key prefix of a drafted answer. - `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/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. @@ -554,12 +610,14 @@ Each entry is the answer of one function of `server/memory/app/curator_gates.py` - A write named in `apply` that changes or re-writes a fact's content carries the content hash a read of the fact served when the report ran, and a fact with no such hash names no such write. - The findings name Reinforce (`memory.pin`) and its reversal (`memory.unpin`) for a person to run. The operation performs neither. - A pin candidate is a served fact: a proposal that was not accepted is never one. -- A scheduled pass performs no belief-revision verb: it writes its own run row, an audit row for a restricted namespace, the cost events of its model calls, and nothing else. -- A model is sent only the guide and pending proposals of the shared scope that are not `high`, each inside a fence, and only while the org's model switch is on, the namespace's mode is `assist` and the curator's share of the cap is unspent. Each of the three is read before every call, and one that cannot be read sends nothing. +- A scheduled pass performs no belief-revision verb: it writes its own run row, an audit row for a restricted namespace, the cost events of its model calls and of the walk's searches, and nothing else. +- A chat model is sent only the guide and pending proposals of the shared scope that are not `high`, each inside a fence, and only while the org's model switch is on, the namespace's mode is `assist` and the curator's share of the cap is unspent. Each of the three is read before every call, and one that cannot be read sends nothing. +- A pass sends the embedder only the text of each repeated question its walk searches with, which the gap build sent it before. The walk reads the org's model switch and the curator's share of the cap once, before its first question, and the mode before each question: one that cannot be read sends nothing. - 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 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 prerequisite is read by one function, which the worker, the model step, the question walk and `curator.status` all call, and one that cannot be read is not met. +- The question walk searches only documents written for no one user, and what it stores of a question is a code under a keyed hash: no question, no gap id, no draft key and no passage. - 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. - What is due and who runs it live in ClickHouse: the run ledger and the lease. diff --git a/docs/architecture/knowledge-gaps.md b/docs/architecture/knowledge-gaps.md index b5321398f5..274e54f30b 100644 --- a/docs/architecture/knowledge-gaps.md +++ b/docs/architecture/knowledge-gaps.md @@ -197,6 +197,14 @@ off. It lists what users asked, so it does not honour a read-narrowed token `knowledge.gaps.` prefix). The Library page shows a gaps tile for a namespace the viewer administers, on a deployment that records misses. +`knowledge.gaps.draft` and the curator's [question walk](curator.md#the-question-walk) +decide whether a gap may still be drafted from through one function (`eligibility` in +`server/knowledge/app/gap_drafts.py`), so a rule added there holds for both: knowledge +gaps are on, the asker floor is the one the caller read, the namespace's capture level +is not `off`, no erasure that may have deleted a question was open at the caller's +time or has finished since, the gap is in the latest build, and enough distinct people +still asked one of its questions, counted again from the stored misses. + ## Cost - On the request's path, a miss costs the rollout gate's cached read of the live replicas @@ -265,6 +273,7 @@ between. - `server/knowledge/domain/gaps.py` (`normalize_query`, `merge_groups`) - `server/knowledge/store/gaps.py` - `server/knowledge/workers/knowledge_gaps.py` +- `server/knowledge/app/gap_drafts.py` (`eligibility`, `handle_gap_draft`) ## Related diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 1c4c73c48b..f1ce369fbf 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -189,9 +189,10 @@ needs a person, or **Findings and model opinions, uses a model**, under which th also asks the deployment's model whether each pending proposal fits the namespace's guide. Before that third mode is saved, the dialog says what is sent to the model provider, how much the curator's share of the namespace's daily cost cap allows in 24 -hours, and each thing the curator still needs, with who can change it. Saving is allowed -while some are missing. The pass runs only where the deployment's operator has turned -the curator on. On a person's own namespace the control is disabled and says why. +hours, and each thing the curator still needs, with what it is needed for and who can +change it. Saving is allowed while some are missing. The pass runs only where the +deployment's operator has turned the curator on. On a person's own namespace the control +is disabled and says why. The dashboard's text follows the [copy rules](../development/dashboard-design.md#rules-a-change-is-checked-against): its @@ -988,7 +989,8 @@ says **Nothing to do**. Above the cards, **Scheduled pass** says in the namespace: off, not turned on for the deployment, waiting for its first pass, overdue, failed, or on with the time the next pass is due. Under that it lists [what the curator still needs](../architecture/curator.md#what-the-curator-needs) in the -namespace, each with who can change it: an operator of the deployment, an org admin or a +namespace, each with what it is needed for (a pass, model opinions or a draftable +question) and who can change it: an operator of the deployment, an org admin or a namespace admin. It shows when the newest pass ran and how it ended and, for a pass that asked a model, how that ended, the calls it made, what they cost and what the curator spent in 24 hours against its share of the namespace's daily cost cap. **Pass history** diff --git a/docs/features/runs.md b/docs/features/runs.md index 56110bd568..1e92c7a081 100644 --- a/docs/features/runs.md +++ b/docs/features/runs.md @@ -604,14 +604,14 @@ The curator's worker writes one row for each [scheduled pass](../architecture/cu over a namespace, so the ledger shows when the curator looked and how the pass ended. `run.list(agent="loom-curator")` lists a namespace's passes, newest first by default. -| Field | A pass's row | -| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `run_id` | `cur-` and the pass's start in epoch seconds. | -| `agent`, `user_id`, `session_id` | `loom-curator`, `-`, `-`: the row is the worker's, filed under no user and no session. | -| `environment`, `goal` | `worker`, `Curator pass (scheduled)`. | -| `status` | `active` while the pass runs, then `completed` or `failed`. | -| `memories_used`, `memories_written` | Empty. `run.list(memory_activity="with")` therefore leaves a pass out. | -| `metadata` | `mode`, `outcome`, `counts` and `unavailable` by section, and `duration_ms`. It holds no key, value or question. A pass in `assist` mode adds how its model calls ended, the model's [opinions](../architecture/curator.md#the-pass-row) and the proposals it has no opinion on: proposal ids and codes, no value. | +| Field | A pass's row | +| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `run_id` | `cur-` and the pass's start in epoch seconds. | +| `agent`, `user_id`, `session_id` | `loom-curator`, `-`, `-`: the row is the worker's, filed under no user and no session. | +| `environment`, `goal` | `worker`, `Curator pass (scheduled)`. | +| `status` | `active` while the pass runs, then `completed` or `failed`. | +| `memories_used`, `memories_written` | Empty. `run.list(memory_activity="with")` therefore leaves a pass out. | +| `metadata` | `mode`, `outcome`, `counts` and `unavailable` by section, and `duration_ms`. It holds no key, value or question. A pass in `assist` mode adds how its model calls ended, the model's [opinions](../architecture/curator.md#the-pass-row) and the proposals it has no opinion on: proposal ids and codes, no value. It also adds `questions`: a count for each code of [the question walk](../architecture/curator.md#the-question-walk), and each question's code under a keyed hash of its gap's id, never the question. | `agent` is a label any caller's `run.begin` can carry. A row is a pass when its `run_id` has the reserved shape. diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index 8e9ec41379..6389d64d44 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -153,8 +153,10 @@ neither line is printed. Between the two the command prints one line for each thing the namespace's mode needs that is not met, with who can change it ([what the curator needs](../architecture/curator.md#what-the-curator-needs)). A -namespace whose mode is `off` prints none, and what model opinions need is listed only in -`assist` mode, where a budget line follows the last pass: +namespace whose mode is `off` prints none, and what model opinions and a draftable +question need is listed only in `assist` mode. There a questions line follows the last +pass, with how many of the questions people keep asking a shared document could answer +and why not the others, and then a budget line: ```console $ loom curator status --namespace support @@ -163,6 +165,7 @@ not met: The deployment has a model provider (needed for model opinions; an oper not met: The namespace has a guide (needed for model opinions; a namespace admin can change it) last pass: cur-1799999940, started 2027-01-15T07:59:00.000Z, completed (ok), 1500 ms; counted proposals 2 model: no_provider; the deployment has no model provider; 0 calls, $0.0000 +questions: 1 draftable (A shared document could answer it), 2 no_evidence (No shared document answers it) budget: the curator spent $0.0000 of its $1.2500 share in 24 hours; the namespace $0.4000 of its $5.0000 daily cost cap ``` diff --git a/frontend/src/api/curator.ts b/frontend/src/api/curator.ts index e2bbbd19db..feec912c22 100644 --- a/frontend/src/api/curator.ts +++ b/frontend/src/api/curator.ts @@ -67,7 +67,8 @@ export interface CuratorLastPass { export interface CuratorSetup { code: string; title: string; - /** `pass`, or `opinions` for what the model's opinions need as well. */ + /** `pass`, `opinions` for what the model's opinions need as well, or `drafts` for what a + * repeated question needs to be counted as draftable. */ needed_for: string; met: boolean; /** The role that can change it: `operator`, `org_admin` or `namespace_admin`. */ diff --git a/frontend/src/components/CuratorSetup.tsx b/frontend/src/components/CuratorSetup.tsx index 67fb17be6d..426c2a98a1 100644 --- a/frontend/src/components/CuratorSetup.tsx +++ b/frontend/src/components/CuratorSetup.tsx @@ -1,5 +1,13 @@ import type { CuratorBudget, CuratorSetup } from "../api/curator"; +/** What a prerequisite is needed for, by the server's code; a code this build has no words + * for is shown as it is. */ +const NEEDED_FOR: Record = { + pass: "a pass", + opinions: "model opinions", + drafts: "a draftable question", +}; + /** Who can change a prerequisite, by the server's role code; a code this build has no * words for is shown as it is. */ const CHANGED_BY: Record = { @@ -9,8 +17,8 @@ const CHANGED_BY: Record = { }; /** The prerequisites that stand in the way of what `mode` asks for: none while it is off, - * what a pass needs in any other mode, and what the model's opinions need as well in - * `assist`. */ + * what a pass needs in any other mode, and what the model's opinions and a draftable + * question need as well in `assist`. */ export function unmetSetup(setup: CuratorSetup[] | undefined, mode: string | undefined): CuratorSetup[] { if (!mode || mode === "off") return []; return (setup ?? []).filter((s) => !s.met && (s.needed_for === "pass" || mode === "assist")); @@ -24,8 +32,9 @@ export function curatorAllowance(budget: CuratorBudget): string { return `The curator's model calls may spend up to $${budget.curator_cap_usd.toFixed(2)} in 24 hours, its share of this namespace's $${budget.cap_usd.toFixed(2)} daily cost cap.`; } -/** The prerequisites that are not met, each in the server's words with who can change it. - * An empty list draws nothing. */ +/** The prerequisites that are not met, each in the server's words with what it is needed + * for and who can change it: an entry a draftable question needs stops no pass and no + * opinion. An empty list draws nothing. */ export function UnmetSetup({ entries }: { entries: CuratorSetup[] }) { if (entries.length === 0) return null; return ( @@ -35,7 +44,10 @@ export function UnmetSetup({ entries }: { entries: CuratorSetup[] }) { {entries.map((s) => (
  • {s.title}.{" "} - {CHANGED_BY[s.changed_by] ?? s.changed_by} can change this. + + Needed for {NEEDED_FOR[s.needed_for] ?? s.needed_for}. {CHANGED_BY[s.changed_by] ?? s.changed_by} can + change this. +
  • ))} diff --git a/frontend/src/flows/NamespaceSettingsDialog.curator.test.tsx b/frontend/src/flows/NamespaceSettingsDialog.curator.test.tsx index 06fdb71aed..993580eae3 100644 --- a/frontend/src/flows/NamespaceSettingsDialog.curator.test.tsx +++ b/frontend/src/flows/NamespaceSettingsDialog.curator.test.tsx @@ -190,8 +190,8 @@ describe("NamespaceSettingsDialog curator mode", () => { ).toEqual([ "the namespace's guide;", "the text of each pending proposal of its shared scope that is not marked high, cut to 2,000 characters.", - "Title of provider. An operator of this deployment can change this.", - "Title of guide. A namespace admin can change this.", + "Title of provider. Needed for model opinions. An operator of this deployment can change this.", + "Title of guide. Needed for model opinions. A namespace admin can change this.", ]); expect(note()).toHaveTextContent( "The curator's model calls may spend up to $1.25 in 24 hours, its share of this namespace's $5.00 daily cost cap.", diff --git a/frontend/src/views/admin/Curator.test.tsx b/frontend/src/views/admin/Curator.test.tsx index 5a93d5f368..20267adc15 100644 --- a/frontend/src/views/admin/Curator.test.tsx +++ b/frontend/src/views/admin/Curator.test.tsx @@ -556,8 +556,9 @@ describe("CuratorPanel's scheduled pass", () => { need("mode", "pass", "namespace_admin", true), need("model_on", "opinions", "org_admin", false), need("guide", "opinions", "namespace_admin", false), - // A role a later server names is shown by its code. - need("drafts_on", "drafts", "reviewer", false), + need("gaps_on", "drafts", "operator", false), + // A purpose and a role a later server names are shown by their codes. + need("reports_on", "reports", "reviewer", false), ]; /** Clears the panel and the read it made, for the next one in the same test. */ const again = () => { @@ -569,22 +570,26 @@ describe("CuratorPanel's scheduled pass", () => { .queryAllByRole("listitem") .map((item) => item.textContent); - // Fails when a met entry is listed, when an unmet one is listed without who can change - // it, or when a mode that asks no model lists what only the opinions need. - it("lists unmet setup entries with who can change them", async () => { + // Fails when a met entry is listed, when an unmet one is listed without what it is + // needed for or who can change it, or when a mode that asks no model lists what only + // the opinions or a draftable question need. + it("lists unmet setup entries with what each is needed for and who can change it", async () => { await show({ ...FULL, mode: "assist", state: "deployment_off", next_due_at: null, setup: SETUP }); expect(passCard().getByText("Not met yet:")).toBeInTheDocument(); expect(unmet()).toEqual([ - "Title of deployment_on. An operator of this deployment can change this.", - "Title of model_on. An org admin can change this.", - "Title of guide. A namespace admin can change this.", - "Title of drafts_on. reviewer can change this.", + "Title of deployment_on. Needed for a pass. An operator of this deployment can change this.", + "Title of model_on. Needed for model opinions. An org admin can change this.", + "Title of guide. Needed for model opinions. A namespace admin can change this.", + "Title of gaps_on. Needed for a draftable question. An operator of this deployment can change this.", + "Title of reports_on. Needed for reports. reviewer can change this.", ]); expect(passCard().queryByText(/Title of mode\./)).toBeNull(); again(); // A mode that asks no model needs what a pass needs, and nothing more. await show({ ...FULL, mode: "findings", state: "deployment_off", next_due_at: null, setup: SETUP }); - expect(unmet()).toEqual(["Title of deployment_on. An operator of this deployment can change this."]); + expect(unmet()).toEqual([ + "Title of deployment_on. Needed for a pass. An operator of this deployment can change this.", + ]); again(); // Off asks for no pass, and a list with every entry met is not drawn. await show({ ...FULL, mode: "off", state: "off", next_due_at: null, setup: SETUP }); diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index 7ea04d7109..7498740066 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -887,6 +887,9 @@ type CuratorPrimer = wire.CuratorPrimer // CuratorProposals is a model used by Loom operations. type CuratorProposals = wire.CuratorProposals +// CuratorQuestionCount is a model used by Loom operations. +type CuratorQuestionCount = wire.CuratorQuestionCount + // CuratorSetup is a model used by Loom operations. type CuratorSetup = wire.CuratorSetup diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 35fe604d44..089ccaaf12 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -3835,16 +3835,17 @@ type CuratorFindings struct { // CuratorLastPass is a model used by Loom operations. type CuratorLastPass struct { - RunID string `json:"run_id"` - StartedAt string `json:"started_at"` - Status string `json:"status"` - Outcome string `json:"outcome"` - DurationMs int64 `json:"duration_ms"` - Mode string `json:"mode"` - Counts *map[string]int64 `json:"counts,omitempty"` - Model *string `json:"model,omitempty"` - LLMCalls *int64 `json:"llm_calls,omitempty"` - SpendUsd *float64 `json:"spend_usd,omitempty"` + RunID string `json:"run_id"` + StartedAt string `json:"started_at"` + Status string `json:"status"` + Outcome string `json:"outcome"` + DurationMs int64 `json:"duration_ms"` + Mode string `json:"mode"` + Counts *map[string]int64 `json:"counts,omitempty"` + Model *string `json:"model,omitempty"` + LLMCalls *int64 `json:"llm_calls,omitempty"` + SpendUsd *float64 `json:"spend_usd,omitempty"` + Questions *[]CuratorQuestionCount `json:"questions,omitempty"` } // CuratorOpinion is a model used by Loom operations. @@ -3886,6 +3887,13 @@ type CuratorProposals struct { Unavailable *string `json:"unavailable,omitempty"` } +// CuratorQuestionCount is a model used by Loom operations. +type CuratorQuestionCount struct { + Code string `json:"code"` + Title string `json:"title"` + Count int64 `json:"count"` +} + // CuratorSetup is a model used by Loom operations. type CuratorSetup struct { Code string `json:"code"` diff --git a/sdk/python/loom/cli_curator.py b/sdk/python/loom/cli_curator.py index 7722f13cd6..edd48db6ce 100644 --- a/sdk/python/loom/cli_curator.py +++ b/sdk/python/loom/cli_curator.py @@ -8,9 +8,11 @@ and one per finding: why the fact is listed, its key and the operation that fixes it. The primer line gives the tokens the guide and the pinned facts spend of their startup budgets. For a namespace in `assist` mode it also prints what the model work of the -newest pass did, what the curator spent of its share of the namespace's daily cost cap, -and one line per opinion: whether the model read the pending proposal as fitting the -namespace's guide, why, and the proposal's key. No fact's value is printed. `--json` +newest pass did, how many of the questions people keep asking a shared document could +answer and why not the others, what the curator spent of its share of the namespace's +daily cost cap, and one line per opinion: whether the model read the pending proposal +as fitting the namespace's guide, why, and the proposal's key. No fact's value and no +question is printed. `--json` prints the operation's answer, which holds each write's arguments. The caller is a namespace admin. @@ -166,7 +168,11 @@ def _line(text: object) -> str: # What a prerequisite is needed for and who can change it, by the answer's codes; a code # this build has no words for is printed as it is. -_NEEDED_FOR = {"pass": "a pass", "opinions": "model opinions"} +_NEEDED_FOR = { + "pass": "a pass", + "opinions": "model opinions", + "drafts": "a draftable question", +} _CHANGED_BY = { "operator": "an operator", "org_admin": "an org admin", @@ -176,8 +182,9 @@ def _line(text: object) -> str: def _unmet(answer: Mapping[str, Any]) -> list[str]: """One line for each thing the namespace's mode needs that is not met, with who can - change it: what a pass needs in a mode that is on, what the model's opinions need - as well while the mode is `assist`. No line for a namespace whose mode is `off`, + change it: what a pass needs in a mode that is on, what the model's opinions and a + draftable question need as well while the mode is `assist`. No line for a namespace + whose mode is `off`, which asks for no pass, none when each is met, and none from a server that lists none.""" setup, mode = answer.get("setup"), answer.get("mode") @@ -248,7 +255,7 @@ def _state(answer: Mapping[str, Any]) -> list[str]: f"last pass: {_line(last.get('run_id'))}, started {_line(last.get('started_at'))}, " f"{_line(last.get('status'))}{outcome}{took}{counted}" ) - out += _model(last) + out += _model(last) + _questions(last) return out + _budget(answer) @@ -279,6 +286,24 @@ def _model(last: Mapping[str, Any]) -> list[str]: ] +def _questions(last: Mapping[str, Any]) -> list[str]: + """The questions line of a pass that decided the namespace's repeated questions: + how many it gave each code, with the title the server sends for the code. No line + for a pass that decided none, and none from a server that sends no such counts.""" + counted = last.get("questions") + entries = [e for e in counted if isinstance(e, Mapping)] if isinstance(counted, list) else [] + if not entries: + return [] + return [ + "questions: " + + ", ".join( + f"{int(e.get('count') or 0)} {_line(e.get('code'))}" + + (f" ({_line(e['title'])})" if e.get("title") else "") + for e in entries + ) + ] + + def _titled(code: object) -> str: """A code the answer sends with its title: the title, else the code.""" if isinstance(code, Mapping): diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index a4948ea688..63f321c2de 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -10430,6 +10430,15 @@ class CuratorLastPass(TypedDict, total=False): model: NotRequired[str] llm_calls: NotRequired[int] spend_usd: NotRequired[float] + questions: NotRequired[list["CuratorQuestionCount"]] + + +class CuratorQuestionCount(TypedDict, total=False): + "How many of the questions people keep asking a pass decided one way." + + code: Required[str] + title: Required[str] + count: Required[int] class CuratorSetup(TypedDict, total=False): diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 6ff8e322f3..6ffd44898d 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -20718,6 +20718,14 @@ pub enum CuratorStatusOutputState { Overdue, } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct CuratorQuestionCount { + pub code: String, + pub title: String, + pub count: Integer, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct CuratorLastPass { @@ -20735,6 +20743,8 @@ pub struct CuratorLastPass { pub llm_calls: Integer, #[serde(default = "default_curator_last_pass_spend_usd")] pub spend_usd: f64, + #[serde(default = "default_curator_last_pass_questions")] + pub questions: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -70794,6 +70804,9 @@ fn default_curator_last_pass_llm_calls() -> Integer { fn default_curator_last_pass_spend_usd() -> f64 { serde_json::from_str("0.0").expect("schema default") } +fn default_curator_last_pass_questions() -> Vec { + serde_json::from_str("[]").expect("schema default") +} fn default_curator_status_output_last_pass() -> Option { serde_json::from_str("null").expect("schema default") } diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 9bddc58b6e..f74df2b494 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -2916,6 +2916,13 @@ export interface CuratorLastPass { model?: string; llm_calls?: number; spend_usd?: number; + questions?: CuratorQuestionCount[]; +} + +export interface CuratorQuestionCount { + code: string; + title: string; + count: number; } export interface CuratorSetup { diff --git a/server/knowledge/app/document_reads.py b/server/knowledge/app/document_reads.py index 280444bb77..cff5d9f7a5 100644 --- a/server/knowledge/app/document_reads.py +++ b/server/knowledge/app/document_reads.py @@ -58,6 +58,13 @@ async def document_tally(org: str, namespace: str) -> tuple[int, datetime | None return await documents_repo.current_document_tally(org, namespace) +async def has_shared_document(org: str, namespace: str) -> bool: + """Whether the namespace holds a current document written for no one user.""" + from server.knowledge.store import documents as documents_repo + + return await documents_repo.shared_document_exists(org, namespace) + + async def document_heads( org: str, namespace: str, source_uris: list[str] ) -> dict[str, DocumentHead]: diff --git a/server/knowledge/app/gap_drafts.py b/server/knowledge/app/gap_drafts.py index b0fb49713c..c24f635eca 100644 --- a/server/knowledge/app/gap_drafts.py +++ b/server/knowledge/app/gap_drafts.py @@ -1,9 +1,13 @@ -"""One private draft from a current gap's currently eligible normalized questions.""" +"""One private draft from a current gap's currently eligible normalized questions, and +the check that says whether a gap may still be drafted from: `knowledge.gaps.draft` and +the curator's question walk both decide it through `eligibility`.""" import time +from dataclasses import dataclass from fastapi import HTTPException +from server.core.datetimes import as_aware_utc from server.knowledge.api.models_gaps import KnowledgeGapsDraftInput, KnowledgeGapsDraftOutput from server.knowledge.app import gaps from server.knowledge.store import gaps as repo @@ -11,34 +15,80 @@ from server.observability import capture_consent from server.settings import settings +# Why nothing may be drafted from a gap: an erasure may have deleted a question it +# groups, or any other rule no longer holds. +ERASURE = "erasure" +INELIGIBLE = "gap_ineligible" -async def handle_gap_draft(input: KnowledgeGapsDraftInput) -> KnowledgeGapsDraftOutput: - started = int(time.time()) - minimum = settings.knowledge_gaps_min_askers - async def valid() -> bool: - return ( - settings.knowledge_gaps_enabled - and minimum == settings.knowledge_gaps_min_askers - and await capture_consent.level_uncached(input.org, input.namespace) != "off" - and not await gaps.erasure_since(input.org, input.namespace, started, None) - ) - - row = ( - await repo.gap_for_draft(input.org, input.namespace, input.gap_id) - if await valid() - else None - ) +@dataclass(frozen=True, slots=True) +class BuiltGap: + """One gap of a namespace's latest build.""" + + gap_id: str + head: str + samples: tuple[str, ...] + + +async def validity(org: str, namespace: str, since_s: int, minimum: int) -> str: + """Why nothing may be drafted from the namespace's gaps, '' when a draft may be: + gaps are on, the asker floor is still `minimum`, the namespace's capture level is + not `off`, and no erasure that may have deleted a question was unfinished at + `since_s` or has finished since (`gaps.erasure_since`, which counts an unreadable + ledger as one). A consent that cannot be read raises.""" + if not settings.knowledge_gaps_enabled or minimum != settings.knowledge_gaps_min_askers: + return INELIGIBLE + if await capture_consent.level_uncached(org, namespace) == "off": + return INELIGIBLE + if await gaps.erasure_since(org, namespace, since_s, None): + return ERASURE + return "" + + +async def eligibility( + org: str, namespace: str, gap_id: str, since_s: int, minimum: int +) -> tuple[str, list[str]]: + """Whether a draft may rest on the gap, and on which of its questions: '' with the + normalized questions of the gap that `minimum` distinct people still asked, counted + again from the stored misses, or why not with none. A gap that left the latest + build, or whose every question fell under the floor, is `INELIGIBLE`.""" + code = await validity(org, namespace, since_s, minimum) + if code: + return code, [] + row = await repo.gap_for_draft(org, namespace, gap_id) queries = ( - await repo.draft_queries( - input.org, - input.namespace, - [row["head"], *row["samples"]], - minimum, - ) + await repo.draft_queries(org, namespace, [row["head"], *row["samples"]], minimum) if row else [] ) + return ("" if queries else INELIGIBLE), queries + + +async def most_asked(org: str, namespace: str, limit: int) -> tuple[int, list[BuiltGap]]: + """The namespace's latest finished build: the epoch second it was built at and its + `limit` most asked gaps, most askers first. `(0, [])` for a namespace with no + build.""" + rows = await repo.latest_gaps(org, namespace, limit=limit) + marker = next((r for r in rows if not r["gap_id"]), None) + built_at = as_aware_utc(marker["built_at"]) if marker else None + if built_at is None: + return 0, [] + built = [ + BuiltGap(str(r["gap_id"]), str(r["head"]), tuple(str(s) for s in r["samples"])) + for r in rows + if r["gap_id"] + ] + return int(built_at.timestamp()), built + + +async def handle_gap_draft(input: KnowledgeGapsDraftInput) -> KnowledgeGapsDraftOutput: + started = int(time.time()) + minimum = settings.knowledge_gaps_min_askers + + async def valid() -> bool: + return not await validity(input.org, input.namespace, started, minimum) + + _, queries = await eligibility(input.org, input.namespace, input.gap_id, started, minimum) if not queries: raise HTTPException(status_code=404, detail={"code": "RESOURCE_NOT_FOUND"}) cid = await draft( diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 54fa83435a..473e08f7a3 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -204,6 +204,40 @@ async def handle_knowledge_search(input: KnowledgeSearchInput) -> KnowledgeSearc return checked.output +async def shared_passages(org: str, namespace: str, query: str, top_k: int) -> list[ChunkHit]: + """The passages of the namespace's shared documents that answer `query`, of the + `top_k` that rank first: the vector, BM25 and exact-key legs fused, each reading + only chunks of documents written for no one user, and each hit one its source's head + serves. A passage answers by the rule that keeps a search from being recorded as a + miss (`_missed`): it is as close as `_close`, or an exact-key match. A read made + for the namespace and not for a caller: it records no miss and no receipt.""" + from server.knowledge.app import bm25 as knowledge_bm25 + from server.knowledge.app import pg_serving + from server.knowledge.app.search import HybridSearchQuery + from server.knowledge.app.search_legs import collect + from server.knowledge.domain.exact_keys import query_keys + + embedder = get_embedder() + base = HybridSearchQuery( + org=org, + namespaces=(namespace,), + embedding_model=embedder.model_name, + query_vec=await embedder.embed(query), + top_k=top_k, + tokens=knowledge_bm25.tokenize(query), + keys=query_keys(query), + shared_only=True, + ) + + async def fetch(width: int) -> list[ChunkHit]: + legs = await collect(dataclasses.replace(base, top_k=width), "hybrid", lexical_weight=1.0) + return legs.ranked() + + hits, _ = await pg_serving.served_search(org, fetch, top_k) + close = _close() + return [h for h in hits[:top_k] if 1.0 - h.distance >= close or h.keys_matched] + + async def resolve_search(input: KnowledgeSearchInput) -> SearchRequest: from server.auth.context import current_auth from server.auth.gateway import is_end_user diff --git a/server/knowledge/app/search.py b/server/knowledge/app/search.py index 3ff48ff668..22c60a3906 100644 --- a/server/knowledge/app/search.py +++ b/server/knowledge/app/search.py @@ -52,6 +52,10 @@ class HybridSearchQuery: tokens: list[str] = field(default_factory=list) idfs: list[float] = field(default_factory=list) avgdl: float = 0.0 + # Only chunks of documents written for no one user (`user_id` is '-'). Set in + # process, by a read made for the namespace and not for a caller; no operation + # carries it. + shared_only: bool = False @dataclass(frozen=True) @@ -251,6 +255,8 @@ def _common_where(q: HybridSearchQuery) -> tuple[list[str], dict[str, Any]]: "q": q.query_vec, "top_k": int(q.top_k), } + if q.shared_only: + where.append("user_id = '-'") if q.tags: where.append("hasAny(tags, {tags:Array(String)})") params["tags"] = q.tags diff --git a/server/knowledge/store/documents.py b/server/knowledge/store/documents.py index 9b1f21bc58..4d8e65110d 100644 --- a/server/knowledge/store/documents.py +++ b/server/knowledge/store/documents.py @@ -184,6 +184,19 @@ async def current_document_tally( return (int(row["n"]), row["latest"]) if row else (0, None) +async def shared_document_exists(org: str, namespace: str, *, ch: _CHClient | None = None) -> bool: + """Whether the namespace holds a current document written for no one user + (`user_id` is '-').""" + ch = ch or _default_client() + row = await ch.query_one( + "SELECT 1 AS found FROM loom.documents FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND superseded_at IS NULL AND user_id = '-' LIMIT 1", + params={"org": org, "ns": namespace}, + ) + return row is not None + + async def current_document_counts( org: str, namespaces: list[str], *, ch: _CHClient | None = None ) -> dict[str, int]: diff --git a/server/memory/api/models_curator.py b/server/memory/api/models_curator.py index 5ef11dd4ef..488e5db982 100644 --- a/server/memory/api/models_curator.py +++ b/server/memory/api/models_curator.py @@ -3,7 +3,8 @@ facts whose linked code or source document changed, the startup budget the guide and the pinned facts spend, and the facts to pin or unpin, each finding with the write that applies it; whether the curator's scheduled pass runs in the namespace, with its newest -pass and what the curator still needs there; the opinions a pass in `assist` mode stored +pass, how many repeated questions that pass gave each code and what the curator still +needs there; the opinions a pass in `assist` mode stored on the pending proposals; and the namespace's daily cost cap with the curator's share of it. The operation stores nothing and calls no model.""" @@ -168,11 +169,13 @@ class CuratorSetup(BaseModel): # `deployment_on`, `fleet_ready`, `mode` or `restricted_serve`, which a scheduled # pass needs; `provider`, `model_on`, `under_cap` or `guide`, which the model's - # opinions need as well. + # opinions need as well; `gaps_on`, `capture_on`, `shared_documents` or + # `no_mirrored_source`, without which a pass counts no repeated question as + # `draftable`. code: str # What holds when it is met, the same words on every surface. title: str - # `pass` or `opinions`. + # `pass`, `opinions` or `drafts`. needed_for: str # Whether it holds now. met: bool @@ -198,6 +201,20 @@ class CuratorBudget(BaseModel): unavailable: str = "" +class CuratorQuestionCount(BaseModel): + """How many of the questions people keep asking a pass decided one way.""" + + # `draftable` for a question a shared document could answer, else why not: + # `gaps_off`, `capture_off` or `mirrored_source`, which hold for every question of + # the pass; `gap_ineligible`, `erasure`, `definition_draft_exists`, + # `already_drafted`, `drafted_other_wording`, `no_evidence` or `sensitive_passage`. + code: str + # The code in words, the same on every surface. + title: str + # The questions the pass decided so. + count: int + + class CuratorLastPass(BaseModel): """The namespace's newest scheduled pass, from its row of the run ledger.""" @@ -227,6 +244,13 @@ class CuratorLastPass(BaseModel): llm_calls: int = 0 # What those calls cost, in USD. spend_usd: float = 0.0 + # What a pass in `assist` mode decided of the namespace's 20 most asked knowledge + # gaps, the questions people keep asking: `draftable` first, 0 when none is, then a + # count for each other code that holds a question. No question's text is served. + # Empty for a pass that did not decide them: every pass outside `assist` mode, and + # one made while the org's model calls were off or the curator's share of the daily + # cost cap was spent. + questions: list[CuratorQuestionCount] = Field(default_factory=list) class CuratorStatusOutput(BaseModel): diff --git a/server/memory/app/curator_gates.py b/server/memory/app/curator_gates.py index f6cd82abc5..db8bb9888a 100644 --- a/server/memory/app/curator_gates.py +++ b/server/memory/app/curator_gates.py @@ -3,11 +3,13 @@ A scheduled pass needs the deployment's switch, a fleet on the mode's migration, a mode on the namespace and a classification the deployment's workers may read. The model step of an `assist` pass needs a model provider, the org's model calls, an unspent share of -the namespace's daily cost cap and a guide. The worker's tick and pass, the model step -and `curator.status` read each through the function here, so the `setup` list of the -answer says what the worker reads. Each takes the namespace it is asked about, and one -that reads the deployment alone ignores it. A prerequisite that cannot be read is not met -(docs/architecture/curator.md). +the namespace's daily cost cap and a guide. A repeated question of such a pass is +counted as `draftable` only where knowledge gaps are on, the namespace keeps query text, +holds a document written for no one user and mirrors no document source. The worker's +tick and pass, the model step, the question walk and `curator.status` read each through +the function here, so the `setup` list of the answer says what the worker reads. Each +takes the namespace it is asked about, and one that reads the deployment alone ignores +it. A prerequisite that cannot be read is not met (docs/architecture/curator.md). """ from __future__ import annotations @@ -22,12 +24,13 @@ from server.identity.api.models_namespace_guide import NamespaceGuideGetOutput from server.identity.app import namespace_classification from server.identity.app.namespace_guide import current_guide +from server.knowledge.app import document_reads, source_access from server.llm import customer from server.memory.api.models_curator import CuratorSetup from server.memory.app.decision_extract import no_model_error from server.memory.domain import curator as codes from server.memory.store import curator as store -from server.observability import degradations +from server.observability import capture_consent, degradations from server.observability.budget import namespace_over_cap from server.settings import settings from server.workers.registry import enabled_worker_names @@ -105,6 +108,27 @@ async def guide(org: str, namespace: str) -> NamespaceGuideGetOutput | None: return found if found.found else None +async def gaps_on(org: str = "", namespace: str = "") -> bool: + """The deployment records the questions its searches could not answer.""" + return bool(settings.knowledge_gaps_enabled) + + +async def capture_on(org: str, namespace: str) -> bool: + """The namespace's capture level is not `off`, read past the cache as the gap + draft reads it. A consent that cannot be read raises.""" + return await capture_consent.level_uncached(org, namespace) != "off" + + +async def shared_documents(org: str, namespace: str) -> bool: + """The namespace holds a current document written for no one user.""" + return await document_reads.has_shared_document(org, namespace) + + +async def no_mirrored_source(org: str, namespace: str) -> bool: + """No active document source of the namespace is mirrored.""" + return not await source_access.has_active_mirrored_sources(org, namespace) + + # The read of each prerequisite `codes.SETUP` lists: what it answers is true for one that # is met. GATES: dict[str, Callable[[str, str], Awaitable[object]]] = { @@ -116,6 +140,10 @@ async def guide(org: str, namespace: str) -> NamespaceGuideGetOutput | None: "model_on": model_on, "under_cap": under_cap, "guide": guide, + "gaps_on": gaps_on, + "capture_on": capture_on, + "shared_documents": shared_documents, + "no_mirrored_source": no_mirrored_source, } diff --git a/server/memory/app/curator_questions.py b/server/memory/app/curator_questions.py new file mode 100644 index 0000000000..ed594350f6 --- /dev/null +++ b/server/memory/app/curator_questions.py @@ -0,0 +1,233 @@ +"""The question walk of an `assist` pass: which of the questions people keep asking a +shared document could answer. + +After the model step, the pass takes the most asked gaps of the namespace's latest gap +build and decides each by code alone. The steps run in one order, and the first that +ends a question gives it its code: + +1. the gap may still be drafted from, by the check `knowledge.gaps.draft` makes + (`gap_drafts.eligibility`); +2. no definition draft claims it; +3. no drafted answer claims it, under this wording or another of the gap, and no fact + is stored under its draft key; +4. the namespace's shared documents hold a passage that answers it, by the rule that + keeps a search from being recorded as a gap, and one that does not read as `high`. + +A question no step ended is `draftable`. With knowledge gaps off, a namespace that +keeps no query text or one that mirrors a document source, no step runs and every +question is counted under that reason. A prerequisite that cannot be read is not met. + +The walk writes no fact and asks no chat model. Its search embeds the question, as the +gap build did: a call made for the org and recorded as the namespace's spend, one cost +event a search. The walk therefore reads the org's model switch and the curator's share +of the namespace's daily cost cap once, before its first question, and decides none +while the calls are off or the share is spent. + +The pass row holds a count per code and, of each question, a keyed hash and its code: +no question, no key and no passage (docs/architecture/curator.md). +""" + +from __future__ import annotations + +import hashlib +import hmac +import time +from collections.abc import Awaitable +from dataclasses import dataclass, field +from typing import Any + +import server.memory.store as memory_repo +from server.core.ch import set_query_tag +from server.identity.domain.read_scope import WHOLE_NAMESPACE +from server.knowledge.app import gap_drafts, knowledge_search +from server.knowledge.app.gap_drafts import BuiltGap +from server.knowledge.domain.gaps import gap_id as gap_id_of +from server.llm import customer +from server.memory.app import curator_gates as gates +from server.memory.app import definition_drafts +from server.memory.domain import curator as codes +from server.memory.domain.sensitivity import without_high +from server.memory.store import curator as store +from server.observability import cost_accumulator +from server.settings import settings +from server.tasks.domain.session_runs import PASS_AGENT +from server.workers import pass_context +from server.workers.cost_event import emit_worker_cost_event_for + +# The source kind of the candidate `knowledge.gaps.draft` claims a gap with. +_DEFINITION_KIND = "knowledge_gap" + + +@dataclass(slots=True) +class Walk: + """What the walk of one pass decided, as the pass row stores it.""" + + # Each question as (the keyed hash the row holds of it, its code), most asked first. + decided: list[tuple[str, str]] = field(default_factory=list) + # How a walk that did not reach its last question ended: `time_bound` or + # `mode_changed`; '' for one that decided every question. + ended: str = "" + + def metadata(self) -> dict[str, Any]: + """The key the walk adds to its pass row's metadata: a count per code that + holds a question, `draftable` always, and each question's code by its hash.""" + counts = {codes.QUESTION_DRAFTABLE: 0} + for _, code in self.decided: + counts[code] = counts.get(code, 0) + 1 + return {"questions": {"counts": counts, "by_hash": dict(self.decided)}} + + +def _keyed(label: bytes, value: str) -> str: + """A hash of `value` keyed with the root secret under `label`: a reader without + the key cannot test a guessed question against it, as against an unkeyed one.""" + key = hmac.new(settings.jwt_secret.encode(), label, hashlib.sha256).digest() + return hmac.new(key, value.encode(), hashlib.sha256).hexdigest() + + +def draft_key(gap_id: str) -> str: + """The gap's draft key. A gap's id is derived from its question, and a key must + not reveal the question: the key holds 12 hex digits of a hash of the id, keyed + under its own label.""" + return codes.DRAFT_KEY_PREFIX + _keyed(b"curator-draft-key", gap_id)[:12] + + +def question_hash(gap_id: str) -> str: + """What a pass row holds of a question: 12 hex digits of a hash of its gap's id, + keyed under a label of its own, so the row names neither the question nor its + draft key.""" + return _keyed(b"curator-question", gap_id)[:12] + + +async def _holds(read: Awaitable[object]) -> bool: + """Whether a prerequisite's read answers that it is met; one that raises is not.""" + try: + return bool(await read) + except Exception as e: # noqa: BLE001 — a prerequisite that cannot be read is not met + pass_context.note_failure(e, "prerequisite") + return False + + +async def _stopped(org: str, namespace: str) -> str: + """The reason no question of the namespace is decided, the first that holds; '' + when the walk may decide them.""" + if not await _holds(gates.gaps_on(org, namespace)): + return codes.QUESTION_GAPS_OFF + if not await _holds(gates.capture_on(org, namespace)): + return codes.QUESTION_CAPTURE_OFF + if not await _holds(gates.no_mirrored_source(org, namespace)): + return codes.QUESTION_MIRRORED_SOURCE + return "" + + +async def _eligibility(org: str, namespace: str, gap: BuiltGap, built_s: int) -> str: + """Step 1: '' for a gap a draft may rest on, else its code. A consent that cannot + be read ends the question as ineligible, as an unreadable erasure ledger ends it as + erased.""" + minimum = int(settings.knowledge_gaps_min_askers) + try: + code, _ = await gap_drafts.eligibility(org, namespace, gap.gap_id, built_s, minimum) + except Exception as e: # noqa: BLE001 — a rule that cannot be read is not met + pass_context.note_failure(e, "eligibility") + return codes.QUESTION_GAP_INELIGIBLE + if not code: + return "" + return codes.QUESTION_ERASURE if code == gap_drafts.ERASURE else codes.QUESTION_GAP_INELIGIBLE + + +async def _claimed(org: str, namespace: str, gap: BuiltGap) -> str: + """Steps 2 and 3: the code of the claim that keeps the question from a draft, '' + for none. A drafted answer claims its question in any status, since a decided + candidate is the record of the decision, and so does a fact under the draft key, + deleted or not: an accepted draft whose candidate was erased is not drafted again.""" + if await definition_drafts.already_claimed(org, namespace, _DEFINITION_KIND, gap.gap_id): + return codes.QUESTION_DEFINITION_DRAFT_EXISTS + kind = codes.DRAFT_SOURCE_KIND + if await definition_drafts.already_claimed(org, namespace, kind, gap.gap_id): + return codes.QUESTION_ALREADY_DRAFTED + stored = await memory_repo.get_by_key( + memory_repo.Identity(org=org, namespace=namespace, agent="-"), + draft_key(gap.gap_id), + scope=WHOLE_NAMESPACE, + fresh=True, + strong=True, + include_tombstoned=True, + ) + if stored is not None: + return codes.QUESTION_ALREADY_DRAFTED + for sample in gap.samples: + other = gap_id_of(org, namespace, sample) + if await definition_drafts.already_claimed(org, namespace, kind, other): + return codes.QUESTION_DRAFTED_OTHER_WORDING + return "" + + +async def _evidence(org: str, namespace: str, gap: BuiltGap) -> str: + """Step 4: the code of a question the namespace's shared documents do not answer, + '' for one they could. The search is a call made for the org: its model-call + switch applies to the embedding, and the spend lands in the namespace's cost + events under the curator's operation.""" + started = time.monotonic() + cost_accumulator.begin_op() + try: + with customer.for_org(org, namespace=namespace): + passages = await knowledge_search.shared_passages( + org, namespace, gap.head, codes.PASSAGES_A_QUESTION + ) + finally: + emit_worker_cost_event_for( + org=org, + namespace=namespace, + operation=gates.OPERATION, + started=started, + agent=PASS_AGENT, + ) + if not passages: + return codes.QUESTION_NO_EVIDENCE + if not without_high(passages, lambda hit: f"{hit.context}\n{hit.content}"): + return codes.QUESTION_SENSITIVE_PASSAGE + return "" + + +async def _question(org: str, namespace: str, gap: BuiltGap, built_s: int, shared: bool) -> str: + """One question's code: that of the first step that ends it, else `draftable`. + `shared` is whether the namespace holds a shared document at all; without one no + search is made.""" + code = await _eligibility(org, namespace, gap, built_s) or await _claimed(org, namespace, gap) + if code: + return code + if not shared: + return codes.QUESTION_NO_EVIDENCE + return await _evidence(org, namespace, gap) or codes.QUESTION_DRAFTABLE + + +async def walk(org: str, namespace: str, began: float) -> Walk | None: + """The walk of the pass that began at `began` (monotonic): the namespace's most + asked gaps, each decided in turn. None when no question can be decided: the org's + model calls are off or the curator's share of the cap is spent, so none could be + searched for. A walk that reaches the pass's time bound, or finds the namespace's + mode no longer `assist`, keeps the questions it decided and says how it ended.""" + set_query_tag(gates.OPERATION) + built_s, built = await gap_drafts.most_asked(org, namespace, codes.QUESTIONS_A_PASS) + walked = Walk() + if not built: + return walked + stopped = await _stopped(org, namespace) + if stopped: + walked.decided = [(question_hash(gap.gap_id), stopped) for gap in built] + return walked + if not await _holds(gates.model_on(org, namespace)): + return None + if not await _holds(gates.under_cap(org, namespace)): + return None + shared = await _holds(gates.shared_documents(org, namespace)) + for gap in built: + pass_context.check_stop() + if time.monotonic() - began >= codes.PASS_SECONDS: + walked.ended = codes.OUTCOME_TIME_BOUND + break + if await store.pass_mode(org, namespace) != codes.MODE_ASSIST: + walked.ended = codes.OUTCOME_MODE_CHANGED + break + code = await _question(org, namespace, gap, built_s, shared) + walked.decided.append((question_hash(gap.gap_id), code)) + return walked diff --git a/server/memory/app/curator_status.py b/server/memory/app/curator_status.py index ae28eec1a5..e684a8aea3 100644 --- a/server/memory/app/curator_status.py +++ b/server/memory/app/curator_status.py @@ -7,8 +7,9 @@ served day after day (`memory.pin`) and the pins nobody labels as used (`memory.unpin`). The sections are read side by side, then one read cites the live revision of every fact they list. Every answer also says whether the curator's -scheduled pass runs in the namespace, when its next pass is due and how its newest pass -ended, from the namespace's registry row and its newest pass row, and lists what the +scheduled pass runs in the namespace, when its next pass is due, how its newest pass +ended and how many repeated questions it gave each code, from the namespace's registry +row and its newest pass row, and lists what the curator needs there with whether each is met, read through the functions the worker reads them by (`curator_gates`). For a namespace in `assist` mode the `opinions` section lists what the model answered about each pending proposal, read back from the pass rows @@ -39,6 +40,7 @@ CuratorOpinions, CuratorPrimer, CuratorProposals, + CuratorQuestionCount, CuratorSetup, CuratorStatusInput, CuratorStatusOutput, @@ -231,8 +233,8 @@ async def _budget(org: str, ns: str) -> CuratorBudget: def _last_pass(row: Any) -> CuratorLastPass: """A pass row as the answer shows it: the row's own columns, and of its metadata the - mode, the outcome, the counts and what its model work did. A metadata that is no - JSON object reads as empty.""" + mode, the outcome, the counts, what its model work did and the repeated questions + it counted by code. A metadata that is no JSON object reads as empty.""" metadata = run.pass_metadata(row) mode, outcome, counts = codes.pass_facts(metadata) model, llm_calls, spend_usd = codes.model_facts(metadata) @@ -247,6 +249,10 @@ def _last_pass(row: Any) -> CuratorLastPass: model=model, llm_calls=llm_calls, spend_usd=spend_usd, + questions=[ + CuratorQuestionCount(code=code, title=codes.QUESTION_TITLES[code], count=count) + for code, count in codes.question_facts(metadata).items() + ], ) diff --git a/server/memory/domain/curator.py b/server/memory/domain/curator.py index 593623a757..844c76f461 100644 --- a/server/memory/domain/curator.py +++ b/server/memory/domain/curator.py @@ -3,8 +3,9 @@ answers when it cannot be computed, the thresholds of the pin findings and the startup budgets the primer is measured against. A surface prints the title it is sent, so every surface says the same words. The modes, the bounds and outcomes of the scheduled pass, -the codes and bounds of its model step, and the state that says whether the curator runs -in a namespace follow, then what the curator needs before it runs.""" +the codes and bounds of its model step and of its question walk, and the state that says +whether the curator runs in a namespace follow, then what the curator needs before it +runs.""" from __future__ import annotations @@ -224,6 +225,65 @@ def stored_mode(raw: object) -> str: OPINION_FAILURES_STOP = 3 # not a setting: the rule of the `unavailable` code +# ---- the question walk of an `assist` pass (`server/memory/app/curator_questions.py`) -- + +# What the walk found of one repeated question. `draftable` is what is left when no +# other holds; of the others the first that holds, in this order. The first three end +# the walk, and every question is counted under the one that did. +QUESTION_DRAFTABLE = "draftable" +QUESTION_GAPS_OFF = "gaps_off" +QUESTION_CAPTURE_OFF = "capture_off" +QUESTION_MIRRORED_SOURCE = "mirrored_source" +# The gap is no longer one a draft may rest on, as `knowledge.gaps.draft` decides it, +# or an erasure reached the namespace's questions after they were grouped. +QUESTION_GAP_INELIGIBLE = "gap_ineligible" +QUESTION_ERASURE = "erasure" +QUESTION_DEFINITION_DRAFT_EXISTS = "definition_draft_exists" +QUESTION_ALREADY_DRAFTED = "already_drafted" +QUESTION_DRAFTED_OTHER_WORDING = "drafted_other_wording" +QUESTION_NO_EVIDENCE = "no_evidence" +QUESTION_SENSITIVE_PASSAGE = "sensitive_passage" + +QUESTION_TITLES: dict[str, str] = { + QUESTION_DRAFTABLE: "A shared document could answer it", + QUESTION_GAPS_OFF: "Knowledge gaps are off for this deployment", + QUESTION_CAPTURE_OFF: "The namespace keeps no query text", + QUESTION_MIRRORED_SOURCE: "The namespace mirrors a document source", + QUESTION_GAP_INELIGIBLE: "No longer asked by enough people", + QUESTION_ERASURE: "An erasure reached the questions after they were grouped", + QUESTION_DEFINITION_DRAFT_EXISTS: "A definition draft answers it", + QUESTION_ALREADY_DRAFTED: "Drafted before", + QUESTION_DRAFTED_OTHER_WORDING: "Drafted before under another wording", + QUESTION_NO_EVIDENCE: "No shared document answers it", + QUESTION_SENSITIVE_PASSAGE: "Every passage that answers it reads as sensitive", +} + +# The bounds of the walk, the same for every namespace. +# not a setting: with PASS_METADATA_MAX it bounds the row; a test checks the largest +QUESTIONS_A_PASS = 20 +# not a setting: the passages one question is decided on +PASSAGES_A_QUESTION = 4 +# The source kind of a review candidate that holds a drafted answer to a gap. The walk +# reads whether one claims a question. +DRAFT_SOURCE_KIND = "curator_draft" +# A gap's draft key: this prefix, then a keyed hash of the gap's id +# (`curator_questions.draft_key`). +DRAFT_KEY_PREFIX = "curator/gap/" + + +def question_facts(metadata: Mapping[str, object]) -> dict[str, int]: + """The repeated questions a pass row's metadata counts, by code, in the order of + `QUESTION_TITLES`. A row without them counted none: a `findings` pass's, and an + `assist` pass's whose walk did not run. A code this build does not know and a value + that is no count read as not there.""" + questions = metadata.get("questions") + counts = questions.get("counts") if isinstance(questions, Mapping) else None + if not isinstance(counts, Mapping): + return {} + # A bool is an int to isinstance, and no count. + return {code: counts[code] for code in QUESTION_TITLES if type(counts.get(code)) is int} + + # ---- whether the curator runs in a namespace (`curator.status`) ----------------------- # What `curator.status` answers in `state`, the first that holds: @@ -293,10 +353,12 @@ def pass_facts(metadata: Mapping[str, object]) -> tuple[str, str, dict[str, int] # ---- what the curator needs before it runs (`setup` of `curator.status`) --------------- -# What a prerequisite is needed for: a scheduled pass, or the model's opinions of a pass -# in `assist` mode, which needs those of a pass as well. +# What a prerequisite is needed for: a scheduled pass; the model's opinions of a pass in +# `assist` mode, which need those of a pass as well; or a repeated question such a pass +# counts as `draftable`. NEEDED_PASS = "pass" NEEDED_OPINIONS = "opinions" +NEEDED_DRAFTS = "drafts" # Who can change a prerequisite: a role, never a person. BY_OPERATOR = "operator" BY_ORG_ADMIN = "org_admin" @@ -345,6 +407,27 @@ class Prerequisite: BY_NAMESPACE_ADMIN, ), Prerequisite("guide", "The namespace has a guide", NEEDED_OPINIONS, BY_NAMESPACE_ADMIN), + Prerequisite( + "gaps_on", "Knowledge gaps are turned on for this deployment", NEEDED_DRAFTS, BY_OPERATOR + ), + Prerequisite( + "capture_on", + "The namespace keeps the text of its queries", + NEEDED_DRAFTS, + BY_NAMESPACE_ADMIN, + ), + Prerequisite( + "shared_documents", + "The namespace holds a document written for no one user", + NEEDED_DRAFTS, + BY_NAMESPACE_ADMIN, + ), + Prerequisite( + "no_mirrored_source", + "The namespace mirrors no document source", + NEEDED_DRAFTS, + BY_NAMESPACE_ADMIN, + ), ) diff --git a/server/memory/workers/curator.py b/server/memory/workers/curator.py index 3a62ed7a18..b7964b549c 100644 --- a/server/memory/workers/curator.py +++ b/server/memory/workers/curator.py @@ -1,10 +1,12 @@ """The curator's scheduled pass: once a cadence, in each namespace whose mode is not `off`, count what `curator.status` reports and record the pass as one run ledger row; in `assist` mode, also ask a model whether each pending proposal fits the namespace's -guide. +guide, then decide which of the questions people keep asking a shared document could +answer. The row says when the pass ran, how it ended and what it counted. A pass changes no -fact. In `assist` mode its row also holds the model's answers (`curator_opinions`); in +fact. In `assist` mode its row also holds the model's answers (`curator_opinions`) and +a count of the repeated questions by what was found of each (`curator_questions`); in any other mode it calls no model. A tick does nothing until every live replica has the migration that adds the mode. It then takes the namespaces whose newest pass started more than the cadence ago, and those set to `assist` whose newest pass ran in another @@ -25,7 +27,7 @@ from server.identity.app import restricted_access from server.knowledge.app import gaps from server.memory.app import curator_gates as gates -from server.memory.app import curator_opinions, curator_status +from server.memory.app import curator_opinions, curator_questions, curator_status from server.memory.domain import curator as codes from server.memory.store import curator as store from server.settings import settings @@ -210,25 +212,31 @@ async def _pass(due: _Due) -> bool: async def _recorded_pass(org: str, namespace: str, mode: str, started_s: int) -> None: """Open the pass row, count the sections and close the row with how the pass ended. - An `assist` pass that counted every section then runs the model step, and its row - says what that step did. A pass stopped by the supervisor or by a lost lease writes - nothing more: its row stays `active` and a later tick closes it as abandoned.""" + An `assist` pass that counted every section then runs the model step and, when that + left the mode as it was, the question walk; its row says what each did. A pass + stopped by the supervisor or by a lost lease writes nothing more: its row stays + `active` and a later tick closes it as abandoned.""" began = time.monotonic() row = await run.open_pass(org, namespace, started_s, _metadata("", {}, {}, None, mode=mode)) counts: dict[str, int] = {} unavailable: dict[str, str] = {} # None for a pass with no model step. work = curator_opinions.ModelWork() if mode == codes.MODE_ASSIST else None + # None for a pass that decided no repeated question. + walked: curator_questions.Walk | None = None try: outcome = await _count(org, namespace, began, counts, unavailable) if work is not None and outcome == codes.OUTCOME_OK: work = await curator_opinions.run_step(org, namespace, began) if work.mode_changed: outcome = codes.OUTCOME_MODE_CHANGED - # An erasure that reaches the namespace may have deleted what was counted, or - # a proposal the model step names. + if work is not None and outcome == codes.OUTCOME_OK: + walked = await _walk(org, namespace, began) + outcome = (walked.ended if walked else "") or outcome + # An erasure that reaches the namespace may have deleted what was counted, a + # proposal the model step names, or a question the walk decided. if await gaps.erasure_since(org, namespace, started_s, set()): - outcome, counts, unavailable = codes.OUTCOME_ERASURE, {}, {} + outcome, counts, unavailable, walked = codes.OUTCOME_ERASURE, {}, {}, None if work is not None: work.opinions, work.unanswered = [], [] except Exception: @@ -237,7 +245,20 @@ async def _recorded_pass(org: str, namespace: str, mode: str, started_s: int) -> ) raise stored = _metadata(outcome, counts, unavailable, began, mode=mode) - await run.close_pass(row, failed=False, metadata=stored | (work.metadata() if work else {})) + stored |= (work.metadata() if work else {}) | (walked.metadata() if walked else {}) + await run.close_pass(row, failed=False, metadata=stored) + + +async def _walk(org: str, namespace: str, began: float) -> curator_questions.Walk | None: + """The question walk of an `assist` pass that counted every section and finished + its model step. None for a walk that did not run or raised: the failure is noted, + the pass keeps its counts and opinions, and its row counts no question.""" + try: + return await curator_questions.walk(org, namespace, began) + except Exception as e: # noqa: BLE001 — a failed walk must not lose the counts and opinions + log.warning("curator: question walk failed in %s/%s: %s", org, namespace, type(e).__name__) + pass_context.note_failure(e, "questions") + return None async def _count( diff --git a/tests/analyzer/cases/planes.py b/tests/analyzer/cases/planes.py index 402799b81c..3dfa8baf95 100644 --- a/tests/analyzer/cases/planes.py +++ b/tests/analyzer/cases/planes.py @@ -27,7 +27,7 @@ read_filters_bound, scope_and, ) -from tests.analyzer.cases._common import AGENT, NS, ORG, SMALL_VEC, rows_by_substring +from tests.analyzer.cases._common import AGENT, MODEL, NS, ORG, SMALL_VEC, rows_by_substring from tests.analyzer.corpus import Case, RecordingCH, is_drive_defect # An org admin's scope as `resolve_org_scope` builds it: a hidden restricted namespace, no @@ -1342,6 +1342,37 @@ async def _definition_draft_reads(ch: RecordingCH, c: dict[str, Any]) -> None: await learnings.delete_candidate_through(ORG, NS, _UUID, 1) +async def _curator_question_reads(ch: RecordingCH, c: dict[str, Any]) -> None: + """What the curator's question walk reads beside the gap draft's statements: the + latest gap build, whether the namespace holds a shared document, and the three + search legs over the chunks written for no one user.""" + from server.knowledge.app.search import ( + HybridSearchQuery, + hybrid_search, + keys_search, + lexical_search, + ) + from server.knowledge.store import documents, gaps + + await gaps.latest_gaps(ORG, NS, limit=20, ch=ch) + await documents.shared_document_exists(ORG, NS, ch=ch) + query = HybridSearchQuery( + org=ORG, + namespaces=(NS,), + embedding_model=MODEL, + query_vec=SMALL_VEC, + top_k=4, + tokens=["refund"], + idfs=[1.0], + avgdl=10.0, + keys=["refund"], + shared_only=True, + ) + await hybrid_search(query, ch=ch) + await lexical_search(query, ch=ch) + await keys_search(query, ch=ch) + + async def _regression_suites(ch: RecordingCH, c: dict[str, Any]) -> None: """The reads of a namespace's regression suites (every head, one head, one revision) and the read that says which origin runs still exist.""" @@ -1425,6 +1456,14 @@ def cases() -> list[Case]: {}, ) ) + out.append( + Case( + "curator_question_reads", + "server.knowledge.store.documents", + _curator_question_reads, + {}, + ) + ) out.append(Case("session_runs.ledger", "server.tasks.store.runs", _session_runs, {})) out.append( Case( diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 6ab1d02024..15b27b37d1 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -428,6 +428,7 @@ 2f3cdbb9cf2d 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 2f476975ad71 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 2f51d642cd7b SELECT pr_number, title, author, labels, merged_at, files, assignees, body_excerpt, linked_issues, additions, deletions, merge_commit_sha, -- mirrors code/domain/index/pr_signals.is_revert_pr (match(t +2f7163612891 SELECT ? AS found FROM loom.documents FINAL WHERE org = {org:String} AND namespace = {ns:String} AND superseded_at IS NULL AND user_id = ? LIMIT ? 2f87519d6c67 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 2fa5c1f4e23c 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 2fab97e447f4 SELECT count() AS n FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL @@ -557,6 +558,7 @@ 3c2d10a13b08 WITH if(JSONType(value, ?) = ?, JSONExtractString(value, ?), ?) AS written_term, JSONExtractRaw(value, ?) AS written_aliases, sensitivity = ? OR length(written_term) + length(written_aliases) > {names 3c31742569aa SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns 3c62c4400be7 ALTER TABLE loom.knowledge_suite_drafts DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_syn +3c6db40c25f6 SELECT gap_id, head, samples, askers, asks, last_at, built_at FROM loom.knowledge_gaps WHERE org = {org:String} AND namespace = {ns:String} AND build = ( SELECT max(build) FROM loom.knowledge_gaps WHE 3c8afdaaf887 SELECT count() AS n FROM loom.agent_runs WHERE org = {org:String} AND namespace IN {ns:Array(String)} 3c8cfca665bb SELECT count() AS n FROM loom.entity_communities WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 3c9ff5ef2dc2 SELECT namespace, source_uri, chunk_idx, doc_version, JSONExtractUInt(chunk_metadata, ?) AS revision, cosineDistance(embedding, {q:Array(Float32)}) AS distance, ? AS lexical, [] AS matched FROM loom.c @@ -1708,6 +1710,7 @@ af399844e950 ALTER TABLE loom.memory_record_fields DELETE WHERE (org = {org:Stri af8aae57db93 SELECT count() AS n FROM loom.memory_chunk_sources FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} afdcda2bf23a SELECT count() AS n FROM loom.memory_ask_precedents WHERE org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), arrayConcat((SELECT groupUniqArray(memory_key) FROM loom.memory WHERE org aff1e632ca9c 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, e.agent AS agent, e.user_id AS user_id, e.session_id AS +b0033bc84c2f WITH arrayConcat(splitByNonAlpha(context_lc), splitByNonAlpha(content_lc)) AS words SELECT namespace, source_uri, chunk_idx, doc_version, content, context, tags, chunk_metadata, ingested_at, agent, se b0198f2a1337 SELECT uniqExact(path) AS n FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND tombstoned_at IS NULL AND startsWith(path, {prefix b062ee2ddb58 SELECT toString(r.record_id) AS record_id FROM loom.memory_records AS r FINAL WHERE r.org = {org:String} AND r.namespace = {ns:String} AND r.schema_name = {schema:String} AND r.status = ? AND r.tombst b07bc2344da4 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND status = ? @@ -1913,6 +1916,7 @@ c464d4b1053c SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:St c466198a7fda WITH (SELECT toFloat64(count()) FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL) AS n_keys, (SELECT mapFromArrays(groupArray(s), groupA c4831b86cc45 SELECT now64(?) AS now, groupArray((token, started_at, finished)) AS keys FROM loom.graph_projections WHERE token IN {tokens:Array(String)} c48726998045 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create +c4a7e1d68614 SELECT namespace, source_uri, chunk_idx, doc_version, content, context, tags, chunk_metadata, ingested_at, agent, session_id, toString(source_class) AS source_class, cosineDistance(embedding, {q:Array c4b0dbe8c3f4 SELECT namespace, agent, user_id, session_id, memory_key, toString(memory_id) AS mid, value, tags, files, toString(content_sha256) AS sha, version FROM loom.memory FINAL WHERE org = {org:String} AND n c4cee4797736 SELECT count() AS sources, countIf(j.has_document = ? AND NOT j.replaced) AS without_document, countIf(j.replaced) AS replaced, sum(j.pending) AS pending, sum(j.processing) AS processing, sum(j.ready) c4d11f8d928a SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} @@ -2278,6 +2282,7 @@ e39d8f5737df SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. e3a91311885a 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 e3ac6b4d5b37 SELECT count() AS n FROM loom.conversations WHERE org = {org:String} AND namespace IN {ns:Array(String)} e3b4b40993e4 SELECT DISTINCT org, code_namespace FROM loom.memory_code_links WHERE tombstoned_at IS NULL ORDER BY org, code_namespace +e3c4cdb76753 SELECT namespace, source_uri, chunk_idx, doc_version, content, context, tags, chunk_metadata, ingested_at, agent, session_id, toString(source_class) AS source_class, cosineDistance(embedding, {q:Array e42328436802 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 e437129a1eed SELECT path, lang, index_error, indexed_commit, created_at FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND index_error != ? ORDER BY creat e43d0c378314 SELECT org, namespace, consumer, query AS pattern, path_prefix, count() AS calls FROM loom.code_search_trace WHERE ts > now() - INTERVAL {hours:UInt32} HOUR AND op = ? AND abstain = ? AND route IN (?, diff --git a/tests/integration/test_curator_pass.py b/tests/integration/test_curator_pass.py index 72c236c089..cbfc60bb00 100644 --- a/tests/integration/test_curator_pass.py +++ b/tests/integration/test_curator_pass.py @@ -8,7 +8,10 @@ while the proposal's content is the one the model read, and the calls are recorded as the namespace's spend, which `curator.status` shows against the curator's share of the namespace's daily cost cap. A namespace in `assist` mode without a guide gets no call, -and the `setup` list of `curator.status` says the guide is what it lacks. +and the `setup` list of `curator.status` says the guide is what it lacks. An `assist` +pass also decides each question people keep asking: one a shared document answers is +counted as `draftable`, one that only a user's own document answers is not, and one a +definition draft claims is left to it; no pass writes a fact for any of them. The tick runs in-process, as the supervisor would call it, on the store the server under test writes to. It reads every namespace of the store that set a mode, so each @@ -35,8 +38,17 @@ import httpx import pytest +from server.knowledge.app import gaps as gaps_app +from server.knowledge.domain.gaps import gap_id, normalize_query +from server.knowledge.workers import knowledge_gaps from server.memory.api.models_curator import CuratorStatusInput -from server.memory.app import curator_gates, curator_opinions, curator_status +from server.memory.app import ( + curator_gates, + curator_opinions, + curator_questions, + curator_status, + definition_drafts, +) from server.memory.domain import curator as codes from server.memory.workers import curator as worker from server.observability import cost_accumulator @@ -54,8 +66,9 @@ pytestmark = pytest.mark.asyncio OWNER = "owner@example.com" -# What `last_pass` says of the model work of a pass that called no model. -NO_MODEL_WORK = {"model": "not_called", "llm_calls": 0, "spend_usd": 0.0} +# What `last_pass` says of the model work and the repeated questions of a pass that +# called no model and decided no question. +NO_MODEL_WORK = {"model": "not_called", "llm_calls": 0, "spend_usd": 0.0, "questions": []} class _Org: @@ -634,3 +647,152 @@ async def test_setup_says_why_no_opinion_was_given( after = await org.call("curator.status", namespace=team, sections=["proposals"]) assert {entry["code"]: entry["met"] for entry in after["setup"]}["guide"] is True assert after["budget"] is None + + +QUESTION = "what is the refund window for annual plans" +ANSWERS = ( + "What is the refund window for annual plans? The refund window for annual plans is " + "thirty days from the day of purchase." +) +OTHER = "The office kitchen is cleaned on Fridays and the dishwasher runs overnight." + + +async def _asked(org: _Org, namespace: str, monkeypatch: pytest.MonkeyPatch) -> str: + """Three people asked `QUESTION` in the namespace and found nothing, on a + deployment that records knowledge gaps and keeps query text, and the gap build + grouped them. Returns the gap's id.""" + from server.core.ch import get_client + + monkeypatch.setattr(settings, "knowledge_gaps_enabled", True) + monkeypatch.setattr(settings, "langfuse_capture_io_level", "query") + monkeypatch.setattr(gaps_app, "every_replica_erases_gaps", lambda: True) + head = normalize_query(QUESTION) + await get_client().insert( + "loom.search_misses", + [ + {"org": org.org, "namespace": namespace, "asker": user, "normalized": head} + for user in ("u1", "u2", "u3") + ], + ) + assert await knowledge_gaps.build_namespace(org.org, namespace) == 1 + return gap_id(org.org, namespace, head) + + +async def _document( + org: _Org, namespace: str, uri: str, content: str, mint_test_token: Any = None, user: str = "" +) -> None: + """Add a document to the namespace: one written for no one user, or with `user` + one written for that user.""" + token = ( + mint_test_token(org=org.org, namespaces=["*"], roles=["writer"], read_user_id=user) + if user + else org.token + ) + r = await org.client.post( + "/v1/knowledge.add", + json={"org": org.org, "namespace": namespace, "source_uri": uri, "content": content}, + headers={"Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 200 and r.json()["chunks_created"] >= 1, r.text[:400] + + +async def _walked(org: _Org, namespace: str, gap: str) -> dict[str, Any]: + """Run one tick and return the questions its pass row holds for the namespace: + the one question, by the keyed hash the row names it with.""" + assert (await worker.run_pass())["failed"] == 0 + (row,) = await org.passes(namespace) + questions = row["metadata"]["questions"] + assert list(questions["by_hash"]) == [curator_questions.question_hash(gap)] + # The row holds counts, hashes and codes: no question, no gap id and no draft key. + stored = str(row["metadata"]) + assert "refund" not in stored and gap not in stored + assert curator_questions.draft_key(gap) not in stored + return questions + + +def _written(ch_client: Any, org: _Org, namespace: str) -> tuple[int, int]: + """How many memory rows the namespace holds, in any status, and how many + candidates wait in its review queue.""" + scope = {"org": org.org, "ns": namespace} + where = "WHERE org = {org:String} AND namespace = {ns:String}" + memory = ch_client.query(f"SELECT count() FROM loom.memory {where}", parameters=scope) + queued = ch_client.query(f"SELECT count() FROM loom.learnings_queue {where}", parameters=scope) + return int(memory.result_rows[0][0]), int(queued.result_rows[0][0]) + + +async def test_a_repeated_question_with_a_shared_document_is_draftable( + org: _Org, ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a question a shared document answers is not counted as `draftable`, + when the count is not 1, or when the pass writes a fact for it.""" + team = await org.namespace("assist") + await _document(org, team, "kb://refunds.md", ANSWERS) + gap = await _asked(org, team, monkeypatch) + + questions = await _walked(org, team, gap) + assert questions["counts"] == {"draftable": 1} + assert list(questions["by_hash"].values()) == ["draftable"] + assert _written(ch_client, org, team) == (0, 0) + stored = await curator_questions.memory_repo.get_by_key( + curator_questions.memory_repo.Identity(org=org.org, namespace=team, agent="-"), + curator_questions.draft_key(gap), + scope=curator_questions.WHOLE_NAMESPACE, + strong=True, + include_tombstoned=True, + ) + assert stored is None + # `curator.status` serves the count with the code's title, and every prerequisite + # of a draftable question as met. + served = await org.call("curator.status", namespace=team, sections=["proposals"]) + assert served["last_pass"]["questions"] == [ + {"code": "draftable", "title": "A shared document could answer it", "count": 1} + ] + setup = {entry["code"]: entry for entry in served["setup"]} + assert setup["shared_documents"] == { + "code": "shared_documents", + "title": "The namespace holds a document written for no one user", + "needed_for": "drafts", + "met": True, + "changed_by": "namespace_admin", + } + assert setup["no_mirrored_source"]["met"] is True + + +async def test_a_question_answered_only_by_a_users_own_document_has_no_evidence( + org: _Org, mint_test_token: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a passage of a document written for one user counts as one of a + shared document: the namespace's shared document says nothing on the question.""" + team = await org.namespace("assist") + await _document(org, team, "kb://kitchen.md", OTHER) + await _document(org, team, "kb://my-notes.md", ANSWERS, mint_test_token, user="alice") + gap = await _asked(org, team, monkeypatch) + + questions = await _walked(org, team, gap) + assert questions["counts"] == {"draftable": 0, "no_evidence": 1} + served = await org.call("curator.status", namespace=team, sections=["proposals"]) + assert served["last_pass"]["questions"] == [ + {"code": "draftable", "title": "A shared document could answer it", "count": 0}, + {"code": "no_evidence", "title": "No shared document answers it", "count": 1}, + ] + + +async def test_a_question_with_a_definition_draft_is_left_to_it( + org: _Org, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when a question whose gap a definition draft claims is counted as + `draftable`: two drafts would then answer one question.""" + from server.knowledge.api.models_gaps import KnowledgeGapsDraftInput + from server.knowledge.app.gap_drafts import handle_gap_draft + from server.llm import client + from server.llm.fake import FakeLLMClient + + monkeypatch.setattr(client, "get_llm_client", FakeLLMClient) + team = await org.namespace("assist") + await _document(org, team, "kb://refunds.md", ANSWERS) + gap = await _asked(org, team, monkeypatch) + await handle_gap_draft(KnowledgeGapsDraftInput(org=org.org, namespace=team, gap_id=gap)) + assert await definition_drafts.already_claimed(org.org, team, "knowledge_gap", gap) + + questions = await _walked(org, team, gap) + assert questions["counts"] == {"draftable": 0, "definition_draft_exists": 1} diff --git a/tests/integration/test_curator_status.py b/tests/integration/test_curator_status.py index 039b5b6fd0..4e3782a377 100644 --- a/tests/integration/test_curator_status.py +++ b/tests/integration/test_curator_status.py @@ -585,10 +585,21 @@ async def test_an_empty_namespace_answers_zeros(space: _Namespace) -> None: "model_on", "under_cap", "guide", + "gaps_on", + "capture_on", + "shared_documents", + "no_mirrored_source", ] assert [setup[code]["met"] for code in ("mode", "guide", "under_cap")] == [False, False, True] + # The namespace holds no document and mirrors no source. + assert [setup[code]["met"] for code in ("shared_documents", "no_mirrored_source")] == [ + False, + True, + ] assert all( - entry["title"] and entry["needed_for"] in ("pass", "opinions") and entry["changed_by"] + entry["title"] + and entry["needed_for"] in ("pass", "opinions", "drafts") + and entry["changed_by"] for entry in setup.values() ) # Nothing was spent, and the curator's cap is within the namespace's. diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 1f4a49ee29..4bec4a1f15 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -282,6 +282,8 @@ server/memory/app/coverage_sweep_gate.py::_load::1 server/memory/app/curation.py::quotes_a_redacted_key::1 cache_fallback server/memory/app/curator_opinions.py::run_step::1 logged_only_nonanswer # the curator pass's model step: the proposal gets no opinion, and the pass row's `model` says how the calls ended server/memory/app/curator_opinions.py::run_step::timeout::1 logged_only_nonanswer # the curator pass's model step: the proposal gets no opinion, and the pass row's `model` says how the calls ended +server/memory/app/curator_questions.py::_eligibility::1 fail_closed # the curator pass's question walk: a rule that cannot be read is not met, and the pass row's code for the question says so +server/memory/app/curator_questions.py::_holds::1 fail_closed # the curator pass's question walk: a rule that cannot be read is not met, and the pass row's code for the question says so server/memory/app/decision.py::_write_decision::1 write server/memory/app/decision.py::handle_decision_outcome::1 write server/memory/app/decision.py::handle_decision_record::1 write diff --git a/tests/unit/test_cli_curator.py b/tests/unit/test_cli_curator.py index 3fd08c1661..ccbab83409 100644 --- a/tests/unit/test_cli_curator.py +++ b/tests/unit/test_cli_curator.py @@ -357,6 +357,52 @@ def test_opinions_that_were_not_computed_say_why_and_a_later_model_code_is_print assert lines[4] == "opinions: not computed (too_large)" +QUESTIONS = [ + {"code": "draftable", "title": "A shared document could answer it", "count": 1}, + {"code": "no_evidence", "title": "No shared document has a passage on it", "count": 2}, + # A code a later server names, sent without a title, is printed alone. + {"code": "held", "count": 4}, +] + + +def test_a_pass_that_decided_questions_prints_them_with_the_servers_titles( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when the report leaves out how many repeated questions a shared document + could answer, prints a count without the server's words for its code, or prints a + line for a pass that decided no question.""" + asked = {**ASSIST, "last_pass": {**ASSIST["last_pass"], "questions": QUESTIONS}} + _wired(monkeypatch, tmp_path, _Wire({**ANSWER, **asked})) + code, out, _ = _status(capsys, prog="python -m loom") + assert code == 0 + assert out.splitlines()[2:4] == [ + "model: over_cap; the curator's share of the namespace's daily cost cap is spent; " + "2 calls, $0.0013", + "questions: 1 draftable (A shared document could answer it), " + "2 no_evidence (No shared document has a passage on it), 4 held", + ] + assert out.splitlines()[4:] == REPORT + + +@pytest.mark.parametrize( + "last", + [ + # A pass that decided no question, and a server that sends no such counts. + {**ASSIST["last_pass"], "questions": []}, + ASSIST["last_pass"], + ], +) +def test_no_questions_line_for_a_pass_that_decided_none( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + last: dict[str, Any], +) -> None: + _wired(monkeypatch, tmp_path, _Wire({**ANSWER, **ASSIST, "last_pass": last})) + _, out, _ = _status(capsys, prog="python -m loom") + assert "questions:" not in out and out.splitlines()[3:] == REPORT + + def _need(code: str, needed_for: str, changed_by: str, met: bool) -> dict[str, Any]: return { "code": code, @@ -372,8 +418,9 @@ def _need(code: str, needed_for: str, changed_by: str, met: bool) -> dict[str, A _need("mode", "pass", "namespace_admin", True), _need("model_on", "opinions", "org_admin", False), _need("guide", "opinions", "namespace_admin", False), + _need("capture_on", "drafts", "namespace_admin", False), # A prerequisite and a role a later server names are printed by their codes. - _need("drafts_on", "drafts", "reviewer", False), + _need("digest_on", "digest", "reviewer", False), ] BUDGET = { "cap_usd": 5.0, @@ -393,22 +440,24 @@ def test_status_prints_what_is_not_met_after_the_state_and_the_budget_after_the_ _wired(monkeypatch, tmp_path, _Wire(answer)) code, out, _ = _status(capsys, prog="python -m loom") assert code == 0 - assert out.splitlines()[:7] == [ + assert out.splitlines()[:8] == [ "curator: ok, mode assist; the next pass is due 2027-01-16T07:59:00.000Z", "not met: Title of deployment_on (needed for a pass; an operator can change it)", "not met: Title of model_on (needed for model opinions; an org admin can change it)", "not met: Title of guide (needed for model opinions; a namespace admin can change it)", - "not met: Title of drafts_on (needed for drafts; reviewer can change it)", + "not met: Title of capture_on (needed for a draftable question; " + "a namespace admin can change it)", + "not met: Title of digest_on (needed for digest; reviewer can change it)", "last pass: cur-1799999940, started 2027-01-15T07:59:00.000Z, completed (ok), 1500 ms; " "counted proposals 3, flagged 2", "model: over_cap; the curator's share of the namespace's daily cost cap is spent; " "2 calls, $0.0013", ] - assert out.splitlines()[7] == ( + assert out.splitlines()[8] == ( "budget: the curator spent $0.0013 of its $1.2500 share in 24 hours; " "the namespace $0.7500 of its $5.0000 daily cost cap" ) - assert out.splitlines()[8:] == REPORT + assert out.splitlines()[9:] == REPORT @pytest.mark.parametrize( diff --git a/tests/unit/test_curator_questions.py b/tests/unit/test_curator_questions.py new file mode 100644 index 0000000000..fe1d93039f --- /dev/null +++ b/tests/unit/test_curator_questions.py @@ -0,0 +1,572 @@ +"""The question walk of an `assist` pass: the order its steps run in and the code each +ends a question with, what stops the walk for every question, the key a drafted answer +would be stored under, and what the pass row and `curator.status` hold of the walk. + +A tick runs over the worker test's world (a run ledger kept in a list, the registry, +the lease and the clock answered by the test). The gap build, the eligibility check, +the claims, the stored fact and the search are answered by the test, and each read is +logged in the order it was made. +""" + +from __future__ import annotations + +import hashlib +import itertools +import json +import re +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.knowledge.app import gap_drafts +from server.knowledge.app.gap_drafts import BuiltGap +from server.knowledge.domain.gaps import gap_id +from server.memory.app import curator_gates as gates +from server.memory.app import curator_opinions, curator_questions, curator_status +from server.memory.domain import curator as codes +from server.memory.domain import curator_prompts as prompts +from server.memory.workers import curator as worker +from server.settings import settings +from server.tasks.app import run +from server.tasks.domain.session_runs import PASS_AGENT +from server.workers import pass_context +from tests.unit import test_curator_worker as _worker_tests +from tests.unit.switch_state import switch_off, switch_stale + +# The walk itself: the worker test's world answers it with no walk. +_WALK = curator_questions.walk + +world = _worker_tests.world +ORG, NOW, DAY, COUNTS = ( + _worker_tests.ORG, + _worker_tests.NOW, + _worker_tests.DAY, + _worker_tests.COUNTS, +) +NS = "team" +# The steps a question's reads belong to, in the order the walk makes them. +STEPS = ("eligibility", "definition", "draft", "stored", "other_wording", "search") +# The codes that end the walk: every question of a pass is counted under the one. +_ENDS_THE_WALK = ("gaps_off", "capture_off", "mirrored_source") + + +def _gap(n: int, *samples: str) -> BuiltGap: + """The gap of a question nobody else in these tests asks.""" + head = f"QUESTION-MARK-{n} how do we deploy" + return BuiltGap(gap_id(ORG, NS, head), head, samples) + + +def _passage(text: str) -> SimpleNamespace: + return SimpleNamespace(context="Runbook", content=text) + + +class _Questions: + """What the walk reads besides the worker's world, set by the test.""" + + def __init__(self, world: Any) -> None: + self.world = world + self.gaps: list[BuiltGap] = [] + # The epoch second the latest gap build was written at. + self.built_s = NOW - 3600 + # The capture level, or what its read raises. + self.capture: str | Exception = "query" + # Whether a source of the namespace is mirrored, or what the read raises. + self.mirrored: bool | Exception = False + self.shared: bool | Exception = True + self.over_cap = False + # gap id -> the code `gap_drafts.eligibility` answers, or what it raises. + self.ineligible: dict[str, str | Exception] = {} + # (source kind, resource id) of each review candidate. + self.claims: set[tuple[str, str]] = set() + # The keys a fact is stored under, deleted or not. + self.stored: set[str] = set() + # head -> the passages the shared search answers, or what it raises. + self.passages: dict[str, list[Any] | Exception] = {} + # In order: (step, the gap id, key or head it read). + self.reads: list[tuple[str, str]] = [] + self.cost_events: list[dict[str, Any]] = [] + self.failures: list[tuple[str, str]] = [] + # Called before each question's first read with its gap id. + self.before: Any = lambda gap: None + + def steps(self) -> list[str]: + """The steps that read, in order, each once.""" + return list(dict.fromkeys(step for step, _ in self.reads)) + + async def tick(self) -> dict[str, Any]: + """One tick a cadence later than the last, and the row of its pass.""" + self.world.clock.advance(DAY + 1) + assert (await worker.run_pass())["passes"] == 1 + return self.world.ledger.passes(NS)[-1] + + +@pytest.fixture +def asked(world: Any, monkeypatch: pytest.MonkeyPatch) -> _Questions: + q = _Questions(world) + world.modes = {NS: "assist"} + switch_off() + + async def run_step(org: str, namespace: str, began: float) -> Any: + return curator_opinions.ModelWork() + + async def most_asked(org: str, namespace: str, limit: int) -> tuple[int, list[BuiltGap]]: + assert (org, namespace, limit) == (ORG, NS, 20) + return (q.built_s, q.gaps[:limit]) + + async def eligibility( + org: str, namespace: str, gap: str, since_s: int, minimum: int + ) -> tuple[str, list[str]]: + # No erasure since the build, and the asker floor as the deployment sets it. + assert (org, namespace, since_s, minimum) == (ORG, NS, q.built_s, 3) + q.before(gap) + q.reads.append(("eligibility", gap)) + code = q.ineligible.get(gap, "") + if isinstance(code, Exception): + raise code + return code, ([] if code else ["a question"]) + + async def already_claimed(org: str, namespace: str, kind: str, resource_id: str) -> bool: + assert (org, namespace) == (ORG, NS) + mine = {gap.gap_id for gap in q.gaps} + step = ( + "definition" + if kind == "knowledge_gap" + else "draft" + if resource_id in mine + else "other_wording" + ) + q.reads.append((step, resource_id)) + return (kind, resource_id) in q.claims + + async def get_by_key(identity: Any, key: str, **kw: Any) -> Any: + # The namespace's shared identity, read where the last write is, a deleted + # fact included. + assert (identity.org, identity.namespace, identity.agent) == (ORG, NS, "-") + assert (identity.user_id, identity.session_id) == ("-", "-") + assert kw == { + "scope": curator_questions.WHOLE_NAMESPACE, + "fresh": True, + "strong": True, + "include_tombstoned": True, + } + q.reads.append(("stored", key)) + return object() if key in q.stored else None + + async def shared_passages(org: str, namespace: str, query: str, top_k: int) -> list[Any]: + assert (org, namespace, top_k) == (ORG, NS, 4) + # The search is a call made for the org, under the namespace it reads. + billed = curator_questions.customer._attribution.get() + assert billed is not None and (billed.org, billed.namespace) == (ORG, NS) + q.reads.append(("search", query)) + found = q.passages.get(query, []) + if isinstance(found, Exception): + raise found + return found + + async def level_uncached(org: str, namespace: str) -> str: + if isinstance(q.capture, Exception): + raise q.capture + return q.capture + + async def mirrored(org: str, namespace: str) -> bool: + if isinstance(q.mirrored, Exception): + raise q.mirrored + return q.mirrored + + async def has_shared_document(org: str, namespace: str) -> bool: + if isinstance(q.shared, Exception): + raise q.shared + return q.shared + + async def namespace_over_cap(org: str, namespace: str, **kw: Any) -> bool: + return q.over_cap + + monkeypatch.setattr(curator_questions, "walk", _WALK) + monkeypatch.setattr(curator_questions, "time", world.clock) + monkeypatch.setattr(curator_opinions, "run_step", run_step) + monkeypatch.setattr(gap_drafts, "most_asked", most_asked) + monkeypatch.setattr(gap_drafts, "eligibility", eligibility) + monkeypatch.setattr(curator_questions.definition_drafts, "already_claimed", already_claimed) + monkeypatch.setattr(curator_questions.memory_repo, "get_by_key", get_by_key) + monkeypatch.setattr(curator_questions.knowledge_search, "shared_passages", shared_passages) + monkeypatch.setattr(gates.capture_consent, "level_uncached", level_uncached) + monkeypatch.setattr(gates.source_access, "has_active_mirrored_sources", mirrored) + monkeypatch.setattr(gates.document_reads, "has_shared_document", has_shared_document) + monkeypatch.setattr(gates, "namespace_over_cap", namespace_over_cap) + monkeypatch.setattr( + curator_questions, "emit_worker_cost_event_for", lambda **kw: q.cost_events.append(kw) + ) + monkeypatch.setattr( + pass_context, "note_failure", lambda e, what="": q.failures.append((what, str(e))) + ) + monkeypatch.setattr(settings, "knowledge_gaps_enabled", True) + monkeypatch.setattr(settings, "knowledge_gaps_min_askers", 3) + monkeypatch.setattr(settings, "curator_cap_share", 0.25) + return q + + +def _questions(row: dict[str, Any]) -> dict[str, Any]: + return row["metadata"]["questions"] + + +def _codes(row: dict[str, Any]) -> list[str]: + """The code of each question the row holds, most asked first.""" + return list(_questions(row)["by_hash"].values()) + + +# ---------------------------------------------------------------- the order of the steps + +# Each code with the step whose read ends the question under it, and how the test makes +# that step end it. Every later step would end the question too, were it reached. +_ENDS: dict[str, tuple[str, Any]] = { + "gap_ineligible": ( + "eligibility", + lambda q, g: q.ineligible.update({g.gap_id: gap_drafts.INELIGIBLE}), + ), + "erasure": ("eligibility", lambda q, g: q.ineligible.update({g.gap_id: gap_drafts.ERASURE})), + "definition_draft_exists": ( + "definition", + lambda q, g: q.claims.add(("knowledge_gap", g.gap_id)), + ), + "already_drafted": ("draft", lambda q, g: q.claims.add(("curator_draft", g.gap_id))), + "drafted_other_wording": ( + "other_wording", + lambda q, g: q.claims.add(("curator_draft", gap_id(ORG, NS, g.samples[1]))), + ), + "no_evidence": ("search", lambda q, g: q.passages.update({g.head: []})), + "sensitive_passage": ( + "search", + lambda q, g: q.passages.update({g.head: [_passage("the deploy password=hunter2xyzzy42")]}), + ), + "draftable": ("search", lambda q, g: None), +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", list(_ENDS)) +async def test_the_steps_run_in_order_and_the_first_to_end_wins( + asked: _Questions, code: str +) -> None: + """A step that ran after an earlier one ended the question would read what the + question no longer needs, and the search would embed a question nobody may draft + for; a wrong code would tell the admin to fix the wrong thing.""" + gap = _gap(1, "how do we ship", "deploy steps") + asked.gaps = [gap] + asked.passages = {gap.head: [_passage("Deploys go out on Tuesdays.")]} + step, end = _ENDS[code] + # Every step after the one under test would end the question as well. + later = [c for c, (s, _) in _ENDS.items() if STEPS.index(s) > STEPS.index(step)] + for other in later: + if other != "draftable": + _ENDS[other][1](asked, gap) + end(asked, gap) + + row = await asked.tick() + assert _codes(row) == [code] + assert _questions(row)["counts"] == {"draftable": int(code == "draftable"), code: 1} + # The reads stop at the step that ended the question, and come in the walk's order. + assert asked.steps() == list(STEPS[: STEPS.index(step) + 1]) + assert (row["status"], row["metadata"]["outcome"]) == ("completed", "ok") + + +@pytest.mark.asyncio +async def test_a_fact_under_the_draft_key_counts_as_drafted(asked: _Questions) -> None: + """An accepted draft whose candidate was erased leaves the fact as the only record: + without this read the question would be drafted a second time.""" + first, second = _gap(1, "how do we ship"), _gap(2) + asked.gaps = [first, second] + asked.passages = {g.head: [_passage("Deploys go out on Tuesdays.")] for g in asked.gaps} + asked.stored = {curator_questions.draft_key(first.gap_id)} + row = await asked.tick() + assert _codes(row) == ["already_drafted", "draftable"] + assert _questions(row)["counts"] == {"draftable": 1, "already_drafted": 1} + # The first question ended at the stored fact: no other wording was read, no search. + assert [step for step, _ in asked.reads[:4]] == ["eligibility", "definition", "draft", "stored"] + assert [head for step, head in asked.reads if step == "search"] == [second.head] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("code", "stop"), + [ + ("gaps_off", lambda q, mp: mp.setattr(settings, "knowledge_gaps_enabled", False)), + ("capture_off", lambda q, mp: setattr(q, "capture", "off")), + ("mirrored_source", lambda q, mp: setattr(q, "mirrored", True)), + ], +) +async def test_a_mirrored_source_stops_the_walk( + asked: _Questions, monkeypatch: pytest.MonkeyPatch, code: str, stop: Any +) -> None: + """Gaps off, a namespace that keeps no query text and one that mirrors a document + source decide every question at once: a search made there would read a mirror's + copies for a question nobody may keep, or embed text the namespace refused.""" + asked.gaps = [_gap(n) for n in (1, 2, 3)] + asked.passages = {g.head: [_passage("Deploys go out on Tuesdays.")] for g in asked.gaps} + stop(asked, monkeypatch) + row = await asked.tick() + assert _codes(row) == [code] * 3 + assert _questions(row)["counts"] == {"draftable": 0, code: 3} + # No question was read: no eligibility check, no claim, no fact and no search. + assert asked.reads == [] + assert (row["status"], row["metadata"]["outcome"]) == ("completed", "ok") + + +@pytest.mark.asyncio +async def test_a_check_that_cannot_be_read_is_not_met(asked: _Questions) -> None: + """A consent, a mirror registration or an eligibility rule that could not be read + and counted as met would let the walk search for a question it may not keep.""" + gap = _gap(1) + asked.gaps = [gap] + asked.passages = {gap.head: [_passage("Deploys go out on Tuesdays.")]} + unread = ConnectionError("no answer") + for field, code in (("capture", "capture_off"), ("mirrored", "mirrored_source")): + setattr(asked, field, unread) + row = await asked.tick() + assert (_codes(row), asked.reads) == ([code], []), field + setattr(asked, field, {"capture": "query", "mirrored": False}[field]) + # The eligibility check raises for a consent it cannot read: the question ends there. + asked.ineligible = {gap.gap_id: unread} + row = await asked.tick() + assert (_codes(row), asked.steps()) == (["gap_ineligible"], ["eligibility"]) + asked.ineligible, asked.reads = {}, [] + # A namespace whose shared documents cannot be read has none: no search is made. + asked.shared = unread + row = await asked.tick() + assert _codes(row) == ["no_evidence"] and "search" not in asked.steps() + assert [what for what, _ in asked.failures] == [ + "prerequisite", + "prerequisite", + "eligibility", + "prerequisite", + ] + + +@pytest.mark.asyncio +async def test_a_namespace_without_a_shared_document_makes_no_search(asked: _Questions) -> None: + """The entry `shared_documents` of the setup list is this read: every question a + search would decide has no evidence, and none is embedded.""" + asked.gaps = [_gap(1), _gap(2)] + asked.shared = False + row = await asked.tick() + assert _codes(row) == ["no_evidence", "no_evidence"] + assert "search" not in asked.steps() and asked.cost_events == [] + + +@pytest.mark.asyncio +async def test_no_walk_without_the_orgs_model_calls_or_the_curators_share( + asked: _Questions, +) -> None: + """The search embeds the question: made for an org that switched its model calls + off, or past the curator's share of the cap, it would send and spend what the + switch and the cap forbid.""" + gap = _gap(1) + asked.gaps = [gap] + asked.passages = {gap.head: [_passage("Deploys go out on Tuesdays.")]} + for close in (lambda: switch_off(ORG), switch_stale, lambda: setattr(asked, "over_cap", True)): + switch_off() + asked.over_cap = False + close() + row = await asked.tick() + assert "questions" not in row["metadata"] and asked.reads == [] + assert (row["status"], row["metadata"]["outcome"]) == ("completed", "ok") + assert row["metadata"]["counts"] == COUNTS + # What stops every question is said whatever the switch and the cap are. + asked.mirrored = True + row = await asked.tick() + assert _codes(row) == ["mirrored_source"] + asked.mirrored, asked.over_cap = False, False + switch_off() + row = await asked.tick() + assert _codes(row) == ["draftable"] + # The search's spend is the namespace's, under the curator's operation. + (event,) = asked.cost_events + assert {k: v for k, v in event.items() if k != "started"} == { + "org": ORG, + "namespace": NS, + "operation": "worker.curator", + "agent": PASS_AGENT, + } + + +# ---------------------------------------------------------------- the draft key + + +def test_the_draft_key_is_keyed_and_stable(monkeypatch: pytest.MonkeyPatch) -> None: + """A gap's id is a hash of its question: a key that held it, or an unkeyed hash of + it, would let any reader of a key test a guessed question against it.""" + first, second = _gap(1).gap_id, _gap(2).gap_id + key = curator_questions.draft_key(first) + assert re.fullmatch(r"curator/gap/[0-9a-f]{12}", key) + assert key == curator_questions.draft_key(first) + assert key != curator_questions.draft_key(second) + digits = key.removeprefix("curator/gap/") + assert digits not in first and first[:12] != digits + assert digits != hashlib.sha256(first.encode()).hexdigest()[:12] + # The pass row's hash of the question is keyed under another label: it is no key. + row_hash = curator_questions.question_hash(first) + assert re.fullmatch(r"[0-9a-f]{12}", row_hash) and row_hash != digits + assert row_hash not in first + # Both follow the deployment's secret. + monkeypatch.setattr(settings, "jwt_secret", settings.jwt_secret + "-another") + assert curator_questions.draft_key(first) != key + assert curator_questions.question_hash(first) != row_hash + + +# ---------------------------------------------------------------- the pass row + + +@pytest.mark.asyncio +async def test_no_question_text_reaches_the_pass_row(asked: _Questions) -> None: + """Every viewer of the namespace reads the row, and it outlives the questions: a + head, a sample, a passage, a gap's id or a draft key in it would show a question to + people `knowledge.gaps.list` refuses, and keep it after its erasure.""" + asked.gaps = [_gap(n, f"SAMPLE-MARK-{n} shipping") for n in range(1, 31)] + asked.passages = {g.head: [_passage(f"PASSAGE-MARK on {g.head}")] for g in asked.gaps} + # The longest code, twenty times. + longest = max(codes.QUESTION_TITLES, key=len) + assert longest == "definition_draft_exists" + asked.claims = {("knowledge_gap", g.gap_id) for g in asked.gaps} + row = await asked.tick() + stored = _questions(row) + assert len(stored["by_hash"]) == codes.QUESTIONS_A_PASS == 20 + assert stored["counts"] == {"draftable": 0, longest: 20} + assert set(stored) == {"counts", "by_hash"} + assert list(stored["by_hash"]) == [ + curator_questions.question_hash(g.gap_id) for g in asked.gaps[:20] + ] + assert all(re.fullmatch(r"[0-9a-f]{12}", prefix) for prefix in stored["by_hash"]) + text = json.dumps(row["metadata"]) + assert "MARK" not in text and "curator/gap" not in text + for gap in asked.gaps: + assert gap.gap_id not in text + assert curator_questions.draft_key(gap.gap_id).removeprefix("curator/gap/") not in text + # Each code a question ends under adds a count, so the largest the walk stores is a + # mix: one question under each of some codes, and the longest code for the rest. + alone = [c for c in codes.QUESTION_TITLES if c not in (longest, *_ENDS_THE_WALK)] + mixes = [ + curator_questions.Walk( + decided=[ + (f"{n:012x}", code) + for n, code in enumerate([*some, *[longest] * (codes.QUESTIONS_A_PASS - len(some))]) + ] + ).metadata() + for size in range(len(alone) + 1) + for some in itertools.combinations(alone, size) + ] + mixed = max(mixes, key=lambda questions: len(run._dumps(questions))) + assert len(mixed["questions"]["counts"]) > 2 + assert 1000 > len(run._dumps(mixed)) > len(run._dumps({"questions": stored})) + # With the largest model step beside it, the row stays under its bound. + opinion = { + "memory_id": "00000000-0000-0000-0000-000000000001", + "hash_prefix": "0" * 16, + "verdict": max(prompts.VERDICT_TITLES, key=len), + "reason": max(prompts.REASON_TITLES, key=len), + "guide_revision": 2**31, + } + largest = { + **row["metadata"], + **mixed, + "unavailable": dict.fromkeys(codes.SECTIONS, "no_usage_labels"), + "opinions": [opinion] * codes.OPINIONS_A_PASS, + } + assert len(run._dumps(largest)) < codes.PASS_METADATA_MAX + + +@pytest.mark.asyncio +async def test_a_namespace_with_no_gap_counts_zero_and_a_findings_pass_does_not_walk( + asked: _Questions, +) -> None: + """`draftable: 0` says the pass looked and found none; a row without the key says + it did not look. Read alike, a namespace nobody asks in would wait for a draft.""" + row = await asked.tick() + assert _questions(row) == {"counts": {"draftable": 0}, "by_hash": {}} + asked.gaps = [_gap(1)] + asked.world.modes = {NS: "findings"} + row = await asked.tick() + assert set(row["metadata"]) == {"mode", "outcome", "counts", "unavailable", "duration_ms"} + assert asked.reads == [] + + +@pytest.mark.asyncio +async def test_the_time_bound_and_a_changed_mode_end_the_walk(asked: _Questions) -> None: + """A walk that went on past the pass's time bound would outlive its lease, and one + that went on after the mode was turned off would read a namespace that withdrew.""" + asked.gaps = [_gap(n) for n in (1, 2, 3)] + asked.passages = {g.head: [_passage("Deploys go out on Tuesdays.")] for g in asked.gaps} + second = asked.gaps[1].gap_id + asked.before = lambda gap: gap == second and asked.world.clock.advance(codes.PASS_SECONDS) + row = await asked.tick() + assert (_codes(row), row["metadata"]["outcome"]) == (["draftable"] * 2, "time_bound") + assert row["status"] == "completed" and row["metadata"]["counts"] == COUNTS + + asked.before = lambda gap: gap == second and asked.world.modes.update({NS: "findings"}) + row = await asked.tick() + assert (_codes(row), row["metadata"]["outcome"]) == (["draftable"] * 2, "mode_changed") + + +@pytest.mark.asyncio +async def test_a_walk_that_fails_keeps_the_pass_and_counts_no_question( + asked: _Questions, +) -> None: + """The counts and the opinions are done when the walk starts: a search that raised + and failed the pass would lose them, and a question counted before the failure + would read as the whole walk.""" + asked.gaps = [_gap(1), _gap(2)] + asked.passages = { + asked.gaps[0].head: [_passage("Deploys go out on Tuesdays.")], + asked.gaps[1].head: RuntimeError("the embedder is down"), + } + row = await asked.tick() + assert (row["status"], row["metadata"]["outcome"]) == ("completed", "ok") + assert row["metadata"]["counts"] == COUNTS and "questions" not in row["metadata"] + assert asked.failures == [("questions", "the embedder is down")] + # The failed search's spend, if any, is still recorded. + assert len(asked.cost_events) == 2 + + +@pytest.mark.asyncio +async def test_an_erasure_during_the_pass_stores_no_question(asked: _Questions) -> None: + """A question's hash kept after an erasure that reached the namespace during the + pass would name a question the erasure deleted.""" + asked.gaps = [_gap(1)] + asked.passages = {asked.gaps[0].head: [_passage("Deploys go out on Tuesdays.")]} + asked.world.erasing = {NS} + row = await asked.tick() + assert row["metadata"]["outcome"] == "erasure" and "questions" not in row["metadata"] + + +# ---------------------------------------------------------------- what the status serves + + +def test_status_serves_the_counts_with_their_titles() -> None: + """A surface prints the title it is sent: a count without one, or under a code the + walk does not answer, would be printed as a bare word nobody can act on.""" + walked = curator_questions.Walk( + decided=[("a" * 12, "no_evidence"), ("b" * 12, "draftable"), ("c" * 12, "no_evidence")] + ) + row = { + "run_id": "cur-1800000000", + "started_at": run.UNIX_EPOCH, + "status": "completed", + "metadata": run._dumps({"mode": "assist", "outcome": "ok", **walked.metadata()}), + } + served = curator_status._last_pass(row).model_dump()["questions"] + assert served == [ + {"code": "draftable", "title": "A shared document could answer it", "count": 1}, + {"code": "no_evidence", "title": "No shared document answers it", "count": 2}, + ] + # A row without the walk, one from a build before it, and counts of another shape. + for metadata in ( + {"mode": "findings"}, + {"questions": "none"}, + {"questions": {"counts": {"draftable": True, "later_code": 3, "erasure": "2"}}}, + ): + row["metadata"] = run._dumps(metadata) + assert curator_status._last_pass(row).questions == [] + # Every code the walk answers has its words, each its own. + answered = {v for k, v in vars(codes).items() if k.startswith("QUESTION_") and type(v) is str} + assert answered == set(codes.QUESTION_TITLES) + assert len(set(codes.QUESTION_TITLES.values())) == len(codes.QUESTION_TITLES) + assert (gap_drafts.INELIGIBLE, gap_drafts.ERASURE) == ("gap_ineligible", "erasure") diff --git a/tests/unit/test_curator_status.py b/tests/unit/test_curator_status.py index c4d3caf694..71d22b5c1f 100644 --- a/tests/unit/test_curator_status.py +++ b/tests/unit/test_curator_status.py @@ -9,7 +9,8 @@ time the next pass is due and the newest pass, from the mode, the deployment's switch, the fleet, the newest pass row and the clock the test sets. It lists what the curator needs there, each read through the function the worker reads it by, and the `budget` -section gives the curator's share of the namespace's daily cost cap. +section gives the curator's share of the namespace's daily cost cap. The newest pass +also says how many repeated questions it gave each code. """ from __future__ import annotations @@ -35,7 +36,12 @@ CuratorStatusOutput, ) from server.memory.app import curator_gates as gates -from server.memory.app import curator_opinions, curator_status, finding_evidence +from server.memory.app import ( + curator_opinions, + curator_questions, + curator_status, + finding_evidence, +) from server.memory.domain import context_layout from server.memory.domain import curator as codes from server.memory.store import curator as store @@ -61,9 +67,10 @@ RUNNING = ("mode", "state", "next_due_at", "last_pass", "setup") # A guide as the namespace's registry serves it. GUIDE = NamespaceGuideGetOutput(found=True, revision=1, content="What the team keeps.") -# What `last_pass` says of the model work of a pass that made none: every pass outside -# `assist` mode, and a row whose metadata does not say. -NO_MODEL_WORK = {"model": "not_called", "llm_calls": 0, "spend_usd": 0.0} +# What `last_pass` says of the model work and the repeated questions of a pass that +# made no call and decided no question: every pass outside `assist` mode, and a row +# whose metadata does not say. +NO_MODEL_WORK = {"model": "not_called", "llm_calls": 0, "spend_usd": 0.0, "questions": []} def _id(n: int) -> str: @@ -120,15 +127,31 @@ def _gates( over_cap: bool = False, guide: NamespaceGuideGetOutput | None = None, spend: budget.BudgetSnapshot | Exception | None = None, + gaps: bool = True, + capture: str | Exception = "query", + shared: bool | Exception = True, + mirrored: bool | Exception = False, ) -> list[dict[str, Any]]: """Answer the reads behind the prerequisites and the budget, so no test reaches a server: `fleet` as whether every replica has the mode's migration, `restricted` as the namespace's classification or what its read raises, `no_model` as why the deployment has no model provider, `over_cap` as whether the curator's share is spent, `guide` as the namespace's, `spend` as the budget read's answer or what it - raises. The org's model calls are on. Returns the arguments of each budget read.""" + raises, `gaps` as the deployment's knowledge-gap switch, `capture` as the + namespace's capture level, `shared` as whether it holds a shared document and + `mirrored` as whether it mirrors a document source, each of the last three also as + what its read raises. The org's model calls are on. Returns the arguments of each + budget read.""" asked: list[dict[str, Any]] = [] + def answering(answer: Any) -> Any: + async def read(org: str, ns: str) -> Any: + if isinstance(answer, Exception): + raise answer + return answer + + return read + async def fleet_at(ch: Any, migration: int) -> bool: assert migration == codes.CURATOR_MODE_MIGRATION return fleet @@ -161,6 +184,10 @@ async def budget_snapshot(org: str, ns: str, **kw: Any) -> budget.BudgetSnapshot monkeypatch.setattr(gates, "no_model_error", lambda: no_model) monkeypatch.setattr(gates, "namespace_over_cap", namespace_over_cap) monkeypatch.setattr(gates, "current_guide", current_guide) + monkeypatch.setattr(settings, "knowledge_gaps_enabled", gaps) + monkeypatch.setattr(gates.capture_consent, "level_uncached", answering(capture)) + monkeypatch.setattr(gates.document_reads, "has_shared_document", answering(shared)) + monkeypatch.setattr(gates.source_access, "has_active_mirrored_sources", answering(mirrored)) monkeypatch.setattr(curator_status, "budget_snapshot", budget_snapshot) switch_off() return asked @@ -477,6 +504,30 @@ async def test_an_empty_namespace_answers_zeros_and_empty_lists( "needed_for": "opinions", "changed_by": "namespace_admin", }, + { + "code": "gaps_on", + "title": "Knowledge gaps are turned on for this deployment", + "needed_for": "drafts", + "changed_by": "operator", + }, + { + "code": "capture_on", + "title": "The namespace keeps the text of its queries", + "needed_for": "drafts", + "changed_by": "namespace_admin", + }, + { + "code": "shared_documents", + "title": "The namespace holds a document written for no one user", + "needed_for": "drafts", + "changed_by": "namespace_admin", + }, + { + "code": "no_mirrored_source", + "title": "The namespace mirrors no document source", + "needed_for": "drafts", + "changed_by": "namespace_admin", + }, ] @@ -515,13 +566,17 @@ async def test_every_prerequisite_is_listed_once_with_who_changes_it( for p in codes.SETUP ] assert len({entry["title"] for entry in _SETUP_WORDS}) == len(_SETUP_WORDS) - # One read an entry, and each read is one the worker's tick and pass or the model - # step calls. The deployment's switch is the exception: the supervisor starts the - # worker by its registry row, and the entry is whether that row is enabled. + # One read an entry, and each read is one the worker's tick and pass, the model + # step or the question walk calls. The deployment's switch is the exception: the + # supervisor starts the worker by its registry row, and the entry is whether that + # row is enabled. assert list(gates.GATES) == [p.code for p in codes.SETUP] reads = {read.__name__ for read in gates.GATES.values()} assert len(reads) == len(gates.GATES) - assert _gates_called(worker) | _gates_called(curator_opinions) == reads - {"deployment_on"} + called = ( + _gates_called(worker) | _gates_called(curator_opinions) | _gates_called(curator_questions) + ) + assert called == reads - {"deployment_on"} (row,) = [w for w in registry._WORKERS if w.name == worker.WORKER] assert row.module == worker.__name__ for switch in (False, True): @@ -532,15 +587,18 @@ async def test_every_prerequisite_is_listed_once_with_who_changes_it( for second in (True, False): monkeypatch.setattr(settings, "restricted_serve", second) assert await gates.deployment_on() is second - # Neither holds a read of its own beside the one the list reports. + # None holds a read of its own beside the one the list reports. for name in ( "fleet_at", "namespace_classification", "no_model_error", "namespace_over_cap", "current_guide", + "document_reads", + "source_access", ): - assert not hasattr(worker, name) and not hasattr(curator_opinions, name), name + for module in (worker, curator_opinions, curator_questions): + assert not hasattr(module, name), (module.__name__, name) async def test_each_prerequisite_follows_its_own_read(monkeypatch: pytest.MonkeyPatch) -> None: @@ -554,6 +612,10 @@ async def test_each_prerequisite_follows_its_own_read(monkeypatch: pytest.Monkey "model_on": {"off": True}, "under_cap": {"over_cap": True}, "guide": {"guide": None}, + "gaps_on": {"gaps": False}, + "capture_on": {"capture": "off"}, + "shared_documents": {"shared": False}, + "no_mirrored_source": {"mirrored": True}, } assert list(closed) == [p.code for p in codes.SETUP] for code, how in closed.items(): @@ -565,6 +627,10 @@ async def test_each_prerequisite_follows_its_own_read(monkeypatch: pytest.Monkey no_model=how.get("no_model", ""), over_cap=how.get("over_cap", False), guide=how.get("guide", GUIDE), + gaps=how.get("gaps", True), + capture=how.get("capture", "query"), + shared=how.get("shared", True), + mirrored=how.get("mirrored", False), ) monkeypatch.setattr(settings, "restricted_serve", how.get("serve", True)) if how.get("off"): @@ -609,6 +675,13 @@ def spend() -> None: "model_on": switch_stale, "under_cap": spend, "guide": lambda: monkeypatch.setattr(gates, "current_guide", failing), + "capture_on": lambda: monkeypatch.setattr(gates.capture_consent, "level_uncached", failing), + "shared_documents": lambda: monkeypatch.setattr( + gates.document_reads, "has_shared_document", failing + ), + "no_mirrored_source": lambda: monkeypatch.setattr( + gates.source_access, "has_active_mirrored_sources", failing + ), } noted: dict[str, list[str]] = {} for code, fail in unread.items(): @@ -618,13 +691,20 @@ def spend() -> None: degradations.begin() assert [s.code for s in await gates.setup(ORG, NS) if not s.met] == [code] noted[code] = degradations.current() - # The two left read a setting of this process, which is always there. - assert set(unread) == {p.code for p in codes.SETUP} - {"deployment_on", "provider"} + # The three left read a setting of this process, which is always there. + assert set(unread) == {p.code for p in codes.SETUP} - { + "deployment_on", + "provider", + "gaps_on", + } # A read that raised is noted for `degraded`, which tells it from a prerequisite # read as unmet; the others end in their own gate, as the worker's do. assert {code: notes for code, notes in noted.items() if notes} == { "mode": ["curator.status: prerequisite_unread (mode)"], "guide": ["curator.status: prerequisite_unread (guide)"], + "capture_on": ["curator.status: prerequisite_unread (capture_on)"], + "shared_documents": ["curator.status: prerequisite_unread (shared_documents)"], + "no_mirrored_source": ["curator.status: prerequisite_unread (no_mirrored_source)"], } # The guide's note reaches the answer of a call whose sections do not read the guide # themselves. One that asks for the primer reads it again and fails, and so does any diff --git a/tests/unit/test_curator_worker.py b/tests/unit/test_curator_worker.py index accb6dd4f1..2ea5edea0e 100644 --- a/tests/unit/test_curator_worker.py +++ b/tests/unit/test_curator_worker.py @@ -188,8 +188,14 @@ async def count_sections( s: (0, w.unavailable[s]) if s in w.unavailable else (COUNTS[s], "") for s in sections } + async def no_walk(org: str, namespace: str, began: float) -> None: + # The question walk of an `assist` pass has its own tests + # (tests/unit/test_curator_questions.py), which put it back. + return None + from server.observability import audit + monkeypatch.setattr(worker.curator_questions, "walk", no_walk) monkeypatch.setattr(worker, "time", w.clock) monkeypatch.setattr(gates, "get_client", lambda: None) monkeypatch.setattr(run, "get_client", lambda: None) diff --git a/tests/unit/test_knowledge_gaps.py b/tests/unit/test_knowledge_gaps.py index 0597024abe..4055198ac6 100644 --- a/tests/unit/test_knowledge_gaps.py +++ b/tests/unit/test_knowledge_gaps.py @@ -1275,3 +1275,83 @@ async def open_erasure(*a: Any, **kw: Any) -> list[dict[str, Any]]: monkeypatch.setattr("server.auth.aliases.spellings", broken) monkeypatch.setattr("server.erasure.app.ledger_reads.unfinished_reaching", open_erasure) assert await gaps_app.erasure_since("o", "ns", 0, {"alice"}) is True + + +@pytest.mark.parametrize( + ("closed", "walk_code"), + [ + ("switch", "gap_ineligible"), + ("floor", "gap_ineligible"), + ("capture", "gap_ineligible"), + ("erasure", "erasure"), + ("left_the_build", "gap_ineligible"), + ("under_the_floor", "gap_ineligible"), + ("", ""), + ], +) +async def test_both_callers_share_one_eligibility_function( + monkeypatch: pytest.MonkeyPatch, closed: str, walk_code: str +) -> None: + """`knowledge.gaps.draft` and the curator's question walk decide whether a gap may + be drafted from through one function: a rule that held for one caller alone would + let the other draft from questions an erasure reached, or from a gap too few people + still ask.""" + from fastapi import HTTPException + + from server.knowledge.api.models_gaps import KnowledgeGapsDraftInput + from server.knowledge.app import gap_drafts + from server.memory.app import curator_questions + + question = "what is the refund window" + + async def level(org: str, namespace: str) -> str: + return "off" if closed == "capture" else "query" + + async def erasure_since(org: str, namespace: str, since_s: int, until: Any) -> bool: + return closed == "erasure" + + async def gap_for_draft(org: str, namespace: str, gid: str) -> dict[str, Any] | None: + return None if closed == "left_the_build" else {"head": question, "samples": []} + + async def draft_queries(org: str, namespace: str, queries: list[str], minimum: int) -> Any: + return [] if closed == "under_the_floor" else queries + + drafted: list[dict[str, Any]] = [] + + async def draft(org: str, namespace: str, **kw: Any) -> str: + drafted.append(kw["evidence"]) + return "c1" + + monkeypatch.setattr(settings, "knowledge_gaps_enabled", closed != "switch") + monkeypatch.setattr(settings, "knowledge_gaps_min_askers", 3) + monkeypatch.setattr(gap_drafts.capture_consent, "level_uncached", level) + monkeypatch.setattr(gap_drafts.gaps, "erasure_since", erasure_since) + monkeypatch.setattr(gap_drafts.repo, "gap_for_draft", gap_for_draft) + monkeypatch.setattr(gap_drafts.repo, "draft_queries", draft_queries) + monkeypatch.setattr(gap_drafts, "draft", draft) + shared = gap_drafts.eligibility + asked: list[tuple[str, int]] = [] + + async def eligibility(org: str, namespace: str, gid: str, since_s: int, minimum: int) -> Any: + # A floor that changed between the caller's read and the check. + asked.append((gid, minimum)) + return await shared(org, namespace, gid, since_s, minimum + (closed == "floor")) + + monkeypatch.setattr(gap_drafts, "eligibility", eligibility) + + gid = gap_id("o", "ns", question) + request = KnowledgeGapsDraftInput(org="o", namespace="ns", gap_id=gid) + if closed: + with pytest.raises(HTTPException) as refused: + await gap_drafts.handle_gap_draft(request) + assert refused.value.status_code == 404 and not drafted + else: + assert (await gap_drafts.handle_gap_draft(request)).candidate_id == "c1" + assert drafted == [{"queries": [question]}] + gap = gap_drafts.BuiltGap(gid, question, ()) + assert await curator_questions._eligibility("o", "ns", gap, 100) == walk_code + # Each caller asked the one function, with the floor it read. + assert asked == [(gid, 3), (gid, 3)] + # The walk holds no read of the rules beside it. + for name in ("capture_consent", "gaps", "repo"): + assert not hasattr(curator_questions, name), name diff --git a/tests/unit/test_knowledge_search_service.py b/tests/unit/test_knowledge_search_service.py index 9e01c53936..2fb4fc967b 100644 --- a/tests/unit/test_knowledge_search_service.py +++ b/tests/unit/test_knowledge_search_service.py @@ -6,7 +6,14 @@ import pytest -from server.knowledge.app.search import ChunkHit, HybridSearchQuery, hybrid_search +from server.knowledge.app import knowledge_search, pg_serving, search_legs +from server.knowledge.app.search import ( + ChunkHit, + HybridSearchQuery, + hybrid_search, + keys_search, + lexical_search, +) class StubCH: @@ -137,3 +144,64 @@ async def test_no_uri_prefix_means_no_scope_clause() -> None: await hybrid_search(_q(), ch=ch) sql, _ = ch.query_all_calls[0] assert "startsWith(source_uri" not in sql + + +@pytest.mark.asyncio +async def test_shared_only_reads_no_user_document(monkeypatch: pytest.MonkeyPatch) -> None: + """A read made for the namespace and not for a caller takes only chunks written for + no one user, on every leg: a passage of a document written for one user would + otherwise count as one of a shared document.""" + for search in (hybrid_search, lexical_search, keys_search): + for shared_only in (True, False): + ch = StubCH() + query = _q( + shared_only=shared_only, + tokens=["refund"], + idfs=[1.0], + avgdl=10.0, + keys=["refund"], + ) + await search(query, ch=ch) + asked_sql = [sql for sql, _ in ch.query_all_calls] + assert asked_sql, search.__name__ + for sql in asked_sql: + assert ("user_id = '-'" in sql) is shared_only, (search.__name__, shared_only) + # No operation's wire model can ask for it. + assert "shared_only" not in knowledge_search.KnowledgeSearchInput.model_fields + + # The namespace's own read asks every leg for shared chunks alone, and keeps the + # passages that answer the question: a close one, or an exact-key match. + asked: list[HybridSearchQuery] = [] + close = knowledge_search._close() + ranked = [ + ChunkHit("ns", "kb://a.md", 0, "close", [], distance=1.0 - close), + ChunkHit("ns", "kb://b.md", 0, "far", [], distance=1.0 - close + 0.01), + ChunkHit("ns", "kb://c.md", 0, "key", [], distance=0.9, keys_matched=("refund",)), + ChunkHit("ns", "kb://d.md", 0, "past the width", [], distance=0.0), + ] + + class Pools: + def ranked(self) -> list[ChunkHit]: + return ranked + + async def collect(query: HybridSearchQuery, mode: str, **kw: Any) -> Pools: + assert mode == "hybrid" + asked.append(query) + return Pools() + + async def served_search(org: str, fetch: Any, k: int) -> tuple[list[Any], int]: + return await fetch(k), 0 + + class Embedder: + model_name = "fake" + + async def embed(self, text: str) -> list[float]: + return [0.5] + + monkeypatch.setattr(search_legs, "collect", collect) + monkeypatch.setattr(pg_serving, "served_search", served_search) + monkeypatch.setattr(knowledge_search, "get_embedder", Embedder) + hits = await knowledge_search.shared_passages("o", "ns", "what is the refund window", 3) + assert [h.content for h in hits] == ["close", "key"] + (query,) = asked + assert query.shared_only and (query.org, query.namespaces, query.top_k) == ("o", ("ns",), 3)