diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 44ef9177b5..0f9fd919ef 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -42,18 +42,15 @@ its source lease, clearing their credentials, as `code.repo.remove` does today, source outlives its namespace with a sealed credential or writes back what an erasure took. A worker source registration goes inactive with its config and items unchanged, its credentials cleared, as are a crawl row's selected addresses, approval and -registrant, and no queued cleanup. Native mirror retirement finds a source's copies by -the sync worker's actor and the source's `source-id` tag, which a worker's copies need -not carry, so it cannot find them. A namespace erasure still purges every mirror the -namespace has had, worker copies included; after `namespace.delete`, `collection.delete` -or `code.repo.remove`, which retire sources without erasing, copies a later build wrote -for a worker source stay until a build with worker cleanup removes them. +registrant, and its copies queued for retirement like a mirrored source's: they carry +the sync worker's actor and the source's `source-id` tag, which mirror retirement finds +them by ([stored copies](mcp-source-worker-boundary.md#stored-copies-and-refresh)). A +namespace erasure purges every mirror the namespace has had, worker copies included. `knowledge.source.remove` removes a worker source as namespace retirement does: its owner, with the writer role, or the namespace's administrator writes it inactive, its -credentials cleared, its stored registration kept and nothing queued, and answers -`documents_pending` 0 even with `delete_documents`: this build writes no worker copy, -and copies a later build wrote stay until that build's cleanup removes them. +credentials cleared, its stored registration kept and its copies queued for retirement, +and answers `documents_pending` 0, as for any mirrored source. `knowledge.source.check`, `update`, `rotate`, `sync_now`, `push_configure`, `push_status` and `push_confirm` refuse a worker source with `SOURCE_WORKER_OWNED`, which does not clear on retry, and `add` refuses the name of a removed one the same way. @@ -1376,8 +1373,10 @@ statements and census keys against these, and its tests pin each one: an owner with no revocation keeps every row. A registration's `created_at` is taken before its last caller check, so a cutoff that lands after that check reaches its row. A team reader's link to an erased source is the reader's row: it names only the opaque - source id and stays until the reader's own deletion or the namespace's erasure. The - source has no sync state to erase, since no build syncs a worker source. + source id and stays until the reader's own deletion or the namespace's erasure. Before + it deletes a namespace's worker rows, owner erasure queues each registration's copies + for the mirror retirement worker, as it does for a connected source; a copied source's + sync state lives under the mirror, which the namespace's erasure takes. `knowledge.source.worker_register` creates active worker rows ([source registration](mcp-source-worker-boundary.md#source-registration)), which hold no credential; every other writer writes a worker row only inactive, clearing its diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 1f22c2aabe..dae2bde286 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -13,19 +13,21 @@ receives the result controls what it retains. The source worker owns upstream credentials, outbound MCP requests and account consent. Loom owns source configuration, access policy and the erasure of what it -stores; this build keeps no worker copies and schedules no worker refresh. Loom -stores opaque worker and connection identifiers, their generations and the approved -profile digest. The worker resolves the connection within its own credential -authority. Neither side uses the other side's credential at the upstream endpoint. +stores, an owner-only source's private copy included ([Stored copies and +refresh](#stored-copies-and-refresh)). Loom stores opaque worker and connection +identifiers, their generations and the approved profile digest. The worker resolves the +connection within its own credential authority. Neither side uses the other side's +credential at the upstream endpoint. This build serves the live read, the collection approval operations described in [Collection approvals](#collection-approvals), the account link described in -[Account enrollment](#account-enrollment) and the registration of an owner-only live -source described in [Source registration](#source-registration). No operation links a -team reader or registers a snapshot or selected-refresh source; the checks those need -ship uncalled, and this page describes what they require. A write to an approval, -account or team link row locks that row, which the frame fence locks shared, so a -revocation that commits before a frame's handoff withholds that frame. +[Account enrollment](#account-enrollment), the registration of an owner-only source +described in [Source registration](#source-registration) and, while +`LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` is on, the private copy of an owner-only +snapshot or selected-refresh source. No operation links a team reader; the checks a team +reader needs ship uncalled, and this page describes what they require. A write to an +approval, account or team link row locks that row, which the frame fence locks shared, +so a revocation that commits before a frame's handoff withholds that frame. The selection proof asks the worker's `/v1/check-access` for each selected identity through the owner's own connection; the worker answers the digest of what it read, never @@ -52,9 +54,10 @@ worker](../../source_worker/README.md#running-the-companion)). A stored-copy confirmation resolves the read with the `stored` purpose, which accepts only a snapshot or selected-refresh registration and looks up the collection approval by -that registration's mode. The worker's digest must match the stored revision, which must -not change during the check. The evidence carries Loom's own clock time, not the -worker's `fetched_at`, and expires within its bounded lifetime. +that registration's mode. It confirms the owner's access only: the worker's digest is +not compared with the stored copy's, so a changed resource keeps its copy until the copy +is due again. The evidence carries Loom's own clock time, not the worker's `fetched_at`, +and expires within its bounded lifetime. ## Worker provisioning @@ -311,9 +314,11 @@ audit row records the caller. Its owner or the namespace's administrator removes `knowledge.source.remove`, namespace retirement writes it inactive, and its owner's erasure deletes it ([document sources](document-sources.md#erasure-and-audit)). -Only `live` is registered, with the `owner_only` reader policy: a snapshot or a selected -refresh needs a stored copy and its refresh, and team access a linked team reader, -neither of which ships, so each answers `unavailable`. Both operations answer one +Every registration has the `owner_only` reader policy: team access needs a linked team +reader, which no operation makes, so it answers `unavailable`. A `snapshot` or +`selected_refresh` registration, the latter with its `interval_seconds` (300 to 86400), +answers `unavailable` too unless `LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` is on, +since only then does the sync keep its copy. Both operations answer one `status`. The caller check of [Collection approvals](#collection-approvals) at the writer role runs first; `denied` covers its refusal, an account the caller has not linked there, an erasure that may still reach the collection and a proof the worker @@ -379,5 +384,106 @@ follows that ownership: ## Stored copies and refresh -Worker copies, refresh and retirement are not built: no store this page lists accepts a -worker copy. +While `LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` is on, the sync worker keeps a +private copy of each active, unpaused, owner-only `snapshot` or `selected_refresh` +source in its collection's mirror (`source_sync_worker`), inside the same private scope +as a connected source's turn. A copy is a document at the resource's address +(`mcp_identity.resource_uri`), written by the sync actor with the source's `source-id` +tag and a permission list naming the owner alone; its metadata carries the worker's +`content_sha256` and revision. + +A turn reads the collection's current approval of the registration's mode and the +owner's worker account at the registered generation first; one that no longer matches +ends the registration (below). It then needs the owner's standing: an active directory +account, no revocation since the registration, and a writer grant in the collection. +Each worker request resolves that authority again as a live read does (`CurrentRead` +with the `stored` purpose), with the owner as requester: before a copy request and after +its reply, and for an access check also just before it is sent. A resource with no copy, +or a selected-refresh one whose interval has passed, is read through the worker's live +path; a reply with the stored digest writes nothing. A process's turns run one after +another, so it has at most one copy in flight, in a channel share of one request per +worker that Loom's live reads never wait on. That share guards only Loom's own channel +slots: on the worker, a copy and a live read take the same `read_limits.concurrent` and +`concurrent_per_org` slots, so on a small worker a copy in flight can make a live read +answer `overloaded`. Every other copy whose access was last confirmed more than half of +`knowledge_source_acl_stale_seconds` ago is checked with `/v1/check-access`, which +returns the digest only. Resources without a copy go first, then the stored copies by +oldest confirmation. Copies count against the pass's mirror document bound; checks count +against its time alone, so a worker source's turn still starts once other mirrored +sources have used up the bound, and only its due copies wait for a pass with room. A +copy's address is fixed by its source ID and its resource, and a registration's +selection never changes, so every stored copy belongs to a selected resource. + +Capacity: a process sends its copies and checks one at a time, within the mirrored phase +of each `knowledge_source_sync` pass, which native mirrored sources share. Every stored +copy needs a check every half of `knowledge_source_acl_stale_seconds`, so the copies one +deployment keeps served are bounded by the mirrored phase time in that window divided by +one check's time (Loom's authority reads and the worker's upstream session). Past that +bound the oldest listings lapse and those copies stop being served, which fails closed; +a turn the bound cuts reads `pass bound reached`, and a source the phase does not reach +keeps its last state. A `selected_refresh` copy is read again at most once a pass and +spends the mirror document bound even when its digest is unchanged, so +`interval_seconds` is the least time between copies, not a schedule. This feature is +experimental and off by default. + +Of the worker's answers, only its report that the upstream refused the account retires a +copy at once: a `403` whose body is exactly +`{"status": "denied", "reason": "upstream_access"}`, read whole within 256 bytes, which +the worker sends only for the upstream's own HTTP 403 to the resource request itself, +the `resources/read` or the mapped read's `tools/call` +([source worker responses](../../source_worker/README.md#responses)); a 403 to +`initialize`, tool discovery, the GET stream or the closing `DELETE` stays a plain +`denied`. Even then the registration, the owner's standing, the approval and the worker +account are read again and must still hold. Any other `denied` ends the turn with every +copy kept: a grant the worker refused (a rotated or mismatched grant key, a clock +outside the grant's lifetime), Loom's own check of authority that changed during the +turn, or a reply that failed validation. A worker build that names no reason never +causes a retirement on a denial; its copies stop being served once their access goes +unconfirmed past the stale window. A copy answering `unsupported` follows the lapsing +rule below with either build. `reconnect`, `overloaded` and `unavailable` end the turn +and keep every copy, and a stored copy whose request keeps ending turns keeps every copy +of the source unserved until it answers or the source is removed, which fails closed; +`timeout` and `unsupported` keep that resource's copy and let the turn go on. A +`timeout` may be the upstream's or the worker's, so it never retires a copy. A stored +copy that answers `unsupported` once its confirmation would lapse before the next pass +(older than `knowledge_source_acl_stale_seconds` less +`knowledge_source_sync_interval_seconds`; only a copy whose check fell due can have a +peer confirmed since, so none goes before half the window) is retired before it can hold +back the listing of the others, its state noting `copy_unconfirmable`, but only when +another copy was confirmed after its own check fell due, which shows the failure is the +resource's, and with the registration and the owner's authority read again and still +holding, in a turn no other refusal ended. Removal, namespace retirement, owner erasure +and the end of a registration (below) also retire every copy of the source. A resource +left without a copy, denied by the upstream or unsupported, is read again only after its +refresh interval or, for a snapshot, half of `knowledge_source_acl_stale_seconds`; one +that timed out, or whose refusal ended the turn, after half of +`knowledge_source_acl_stale_seconds`. The mirror read gate needs a listing no older than +`knowledge_source_acl_stale_seconds`, and the turn records the listing at the oldest +confirmation among the stored copies, so a copy whose access was not confirmed in that +window stops every copy of the source being served until it is confirmed or retired. +Nothing confirms a copy while the owner's standing, the approval or the worker account +fails, so they fail closed together. + +An approval or worker account read that no longer matches the registration (the +collection's approval at another generation or gone, the owner's worker account +inactive or at another generation) ends the registration, since nothing restores that +generation: under the namespace's source lease, once a read there confirms it, the row +goes inactive, its copies are queued for retirement and its sync state reads +`owner_inactive`, as for a connected source whose owner left +(`source_sync_connected.ensure_current`). A read that fails, a routes file that does not +provision the profile in that process, and a lost writer grant or directory standing +keep the registration and every copy, unserved once the stale window passes. + +The mirror read gate admits a worker source's copies to its owner alone: the latest row +of the name must be the same registration the request first read, still copied, the +reader's own sign-in subject must be its owner with the viewer role, and the approval +and the owner's worker account must be current. Any other reader, a changed registration +or a failed check admits no copy. While copies are on, the gate's registration read +returns only worker rows whose stored registration names an owner-only copy mode, so a +live worker source costs a reader nothing. + +`knowledge.source.remove`, namespace retirement and owner erasure queue the source's +copies for the `knowledge_source_retire` worker before its row goes inactive or is +deleted; that worker deletes them as it deletes a mirrored folder source's copies, and +an active row of the same source ID stops it. A namespace erasure purges the mirror with +every copy in it. diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 9960c89e6b..aa9ce62aed 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1167,6 +1167,31 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline rollout. `tests/unit/test_run_ledger.py` and `tests/unit/test_mcp_session_runs.py` check N's side, and the mixed-version gate does not check this rule. +77. **Worker copies** (`knowledge_source_worker_copies_enabled`, no migration): with the + setting on, N registers owner-only `snapshot` and `selected_refresh` worker sources, + syncs their copies into the collection's mirror, serves those copies to the owner + and queues their retirement on `knowledge.source.remove`, namespace retirement and + owner erasure. N-1 registers no such source, its sync worker and mirror reads skip + every worker row, its `knowledge.source.live` refuses a non-live registration, and + its removal paths queue no worker copy. So the operator turns the setting on only + once every replica runs N; it is off by default, so the rollout itself writes no + copy. Whatever the setting, N's `knowledge.source.remove` and namespace retirement + queue a worker source's copies and write its inactive row with `pending_delete`, + since a copy written while the setting was on outlives turning it off. With no copy + the entry finds nothing to delete: N clears it, and N-1's retirement worker leaves + it pending, since it still counts an inactive worker row as blocking. A rollback to + N-1 leaves the copies in the mirror, unserved, and an owner erased or a source + removed under N-1 queues none of them: before rolling back, remove every snapshot + and selected-refresh worker source with N and let the `knowledge_source_retire` + worker drain. A source worker build older than N's names no reason on its `403`, so + N never retires a copy on its denial, and an N-1 Loom ignores the reason N's worker + adds: a refused resource's copy is kept and its source's copies stop being served + after the stale window, until a worker that names the reason answers. A copy + answering `unsupported` follows the + [lapsing rule](mcp-source-worker-boundary.md#stored-copies-and-refresh) with either + worker build. No gate holds the rollout. `tests/unit/test_worker_source_copies.py` + checks N's side, and the mixed-version gate does not check this rule. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index ad41329c4b..884490b185 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -326,11 +326,10 @@ A removed source's row stays, inactive and with its credential cleared. With document is counted yet (a sync turn running at that moment may still write one); the worker clears it once none is left. A worker source's owner, with the writer role, or the namespace's administrator removes it the same way; it keeps its stored registration, -and `delete_documents` queues nothing and counts no documents: this build writes no -worker copy, and copies a later build wrote stay until that build's cleanup removes -them. Removing a repository (`code.repo.remove`) retires the sources registered on its -namespace the same way and names them in `sources_deactivated`; the purge of the -repository's code index that follows deletes their sync state (it lives in +and its copies are queued for retirement whatever `delete_documents` says, uncounted, as +for any mirrored source. Removing a repository (`code.repo.remove`) retires the sources +registered on its namespace the same way and names them in `sources_deactivated`; the +purge of the repository's code index that follows deletes their sync state (it lives in `loom.code_index_state`) and the namespace's documents, and leaves the inactive source rows. An `add` that probed while the repository was being removed answers `NAMESPACE_INACTIVE`, or, when it lands before the namespace is deleted, is retired with diff --git a/docs/reference/cli.md b/docs/reference/cli.md index a659440955..98d6a06495 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -266,8 +266,8 @@ python scripts/codegen/docs_reference.py | `loom knowledge source worker-profiles` | List the provisioned source worker profiles and the collection's approval of each (knowledge.source.worker_profiles; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--limit`, `--after-json` | | `loom knowledge source worker-approve` | Set or revoke the collection's approval of one worker profile (knowledge.source.worker_approve; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--worker-id`, `--profile-digest`, `--mode`, `--revoke`, `--team-access`, `--expected-generation` | | `loom knowledge source worker-enroll` | Link your own worker account to an approved profile (knowledge.source.worker_enroll; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--worker-id`, `--profile-digest`, `--connection-id`, `--connection-generation` | -| `loom knowledge source worker-preview` | Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-id`, `--profile-digest`, `--connection-id`, `--mode`, `--team-access`, `--selection-file` | -| `loom knowledge source worker-register` | Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-id`, `--profile-digest`, `--connection-id`, `--mode`, `--team-access`, `--selection-file`, `--preview-file` | +| `loom knowledge source worker-preview` | Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-id`, `--profile-digest`, `--connection-id`, `--mode`, `--interval-seconds`, `--team-access`, `--selection-file` | +| `loom knowledge source worker-register` | Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--worker-id`, `--profile-digest`, `--connection-id`, `--mode`, `--interval-seconds`, `--team-access`, `--selection-file`, `--preview-file` | | `loom knowledge migrate-originals` | Move the document originals still held in ClickHouse, that a document, upload or ingestion needs, to LOOM_DOCUMENT_S3_BUCKET: each is copied to its own object, hash-verified and switched, fenced by… | `--org`, `--namespace`, `--dry-run` | | `loom export-okf` | Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. | `--server-url`, `--token`, `--org`, `--namespace`, `--out`, `--title`, `--include-tombstoned`, `--limit`, `--dry-run`, `--no-evidence`, `--no-links`, `--include-high` | | `loom import-okf` | Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. | ``, `--server-url`, `--token`, `--org`, `--namespace`, `--agent`, `--user-id`, `--session-id`, `--keep-sessions`, `--verify`, `--dry-run`, `--no-evidence`, `--no-lint`, `--force-import`, `--no-links`, `--prune` | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 3342f383c8..17c9b4a723 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1061,6 +1061,7 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_KNOWLEDGE_SOURCE_WORKER_LIVE_TIMEOUT_S` | `float` | `8.0` | | Seconds a live read may spend on authority checks and its worker request. At most 8, the default: a value can only shorten it. | | `LOOM_KNOWLEDGE_SOURCE_WORKER_PUBLICATION_TIMEOUT_S` | `float` | `2.0` | | Seconds reserved after a live read for accounting and delivery. At most 2, the default: a value can only shorten it. | | `LOOM_KNOWLEDGE_SOURCE_WORKER_FRAME_TIMEOUT_S` | `float` | `1.0` | | Seconds one response frame may spend acquiring authority locks and sending. At most 1, the default; the remaining publication deadline can shorten it further. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` | `bool` | `False` | | Serve owner-only `snapshot` and `selected_refresh` worker sources from a private copy in the collection's mirror. Turn it on only once every replica runs a build that has it. | | `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` | `int` | `3600` | | Mirrored reads require a complete listing and group observation within this many seconds; missing or older evidence admits nobody. | | `LOOM_KNOWLEDGE_SOURCE_ACL_MAX_ENTRIES` | `int` | `10000` | | Maximum team and member rows read for one project's complete permission list. A larger list refuses publication rather than granting from a partial page. | | `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED` | `bool` | `False` | | Enable optional source push setup, callbacks and Drive renewal; false keeps polling only. | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index afcfd66266..00f1235c5a 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -461,9 +461,9 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate) | Add items to a registered document source or remove them, or change a gdrive source's file kinds. | writer | write | no | yes | | [`knowledge.source.worker_approve`](operations/knowledge.md#knowledgesourceworker_approve) | Set or revoke the collection's approval of one provisioned worker profile. | admin | write | no | yes | | [`knowledge.source.worker_enroll`](operations/knowledge.md#knowledgesourceworker_enroll) | Link the caller's own operator-provisioned worker account to an approved profile. | viewer | write | no | yes | -| [`knowledge.source.worker_preview`](operations/knowledge.md#knowledgesourceworker_preview) | Preview a live worker source on the caller's linked account; nothing is written. | writer | write | no | | +| [`knowledge.source.worker_preview`](operations/knowledge.md#knowledgesourceworker_preview) | Preview a worker source on the caller's linked account; nothing is written. | writer | write | no | | | [`knowledge.source.worker_profiles`](operations/knowledge.md#knowledgesourceworker_profiles) | List provisioned source worker profiles and their current collection approval. | admin | idempotent | no | | -| [`knowledge.source.worker_register`](operations/knowledge.md#knowledgesourceworker_register) | Register the live worker source a preview showed, with its fingerprint and evidence. | writer | write | no | yes | +| [`knowledge.source.worker_register`](operations/knowledge.md#knowledgesourceworker_register) | Register the worker source a preview showed, with its fingerprint and evidence. | writer | write | no | yes | | [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize) | Complete a task over WHOLE documents, not a search slice: every active chunk of the named documents is read in order, in windows that respect section boundaries, each window is noted once, and the… | viewer | idempotent | no | yes | | [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata) | Edit doc-level metadata (title, description, tags). | writer | idempotent | no | yes | | [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | Same fields as knowledge.add. | writer | idempotent | no | | diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index eccaf02155..c53a46a052 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -846,7 +846,7 @@ Retire a registered document source: its registry row goes inactive and its cred | Output field | Type | Meaning | | --- | --- | --- | | `name` | `str` | The source retired. | -| `documents_pending` | `int` | Live documents queued for retirement; always zero for a mirrored source because its counts are withheld, without `delete_documents` for a namespace source, or for a worker source. | +| `documents_pending` | `int` | Live documents queued for retirement; always zero for a mirrored source (a worker source included) because its counts are withheld, and without `delete_documents` for a namespace source. | ## `knowledge.source.rotate` @@ -959,7 +959,7 @@ Link the caller's own operator-provisioned worker account to an approved profile ## `knowledge.source.worker_preview` -Preview a live worker source on the caller's linked account; nothing is written. +Preview a worker source on the caller's linked account; nothing is written. `POST /v1/knowledge.source.worker_preview` · MCP `loom_knowledge_source_worker_preview` · role `writer` · write · not listed under the MCP `all` toolset @@ -971,7 +971,8 @@ Preview a live worker source on the caller's linked account; nothing is written. | `worker_id` | `UUID` | required | Worker of the approved profile. | | `profile_digest` | `str` | required | Digest of the approved profile. | | `connection_id` | `UUID` | required | Opaque ID of the caller's worker account linked in this collection. | -| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | `live` reads a resource when asked and keeps no copy; `snapshot` and `selected_refresh` answer `unavailable`. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | `live` keeps no copy; `snapshot` and `selected_refresh` keep one for the owner, and answer `unavailable` while the deployment keeps no worker copies. | +| `interval_seconds` | `int \| None` | `None` | Required for `selected_refresh` and refused for the other modes: the least seconds between a resource's copies, 300 to 86400. | | `team_access` | `bool` | `False` | Let other members read through their own accounts; `true` answers `unavailable`, since no operation links a team reader. | | `selection` | `list[ResourceIdentity]` | required | The exact resources the source reads, in order: 1 to 240 distinct ids. | @@ -1007,7 +1008,7 @@ List provisioned source worker profiles and their current collection approval. ## `knowledge.source.worker_register` -Register the live worker source a preview showed, with its fingerprint and evidence. +Register the worker source a preview showed, with its fingerprint and evidence. `POST /v1/knowledge.source.worker_register` · MCP `loom_knowledge_source_worker_register` · role `writer` · write · audited · not listed under the MCP `all` toolset @@ -1019,7 +1020,8 @@ Register the live worker source a preview showed, with its fingerprint and evide | `worker_id` | `UUID` | required | Worker of the approved profile. | | `profile_digest` | `str` | required | Digest of the approved profile. | | `connection_id` | `UUID` | required | Opaque ID of the caller's worker account linked in this collection. | -| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | `live` reads a resource when asked and keeps no copy; `snapshot` and `selected_refresh` answer `unavailable`. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | `live` keeps no copy; `snapshot` and `selected_refresh` keep one for the owner, and answer `unavailable` while the deployment keeps no worker copies. | +| `interval_seconds` | `int \| None` | `None` | Required for `selected_refresh` and refused for the other modes: the least seconds between a resource's copies, 300 to 86400. | | `team_access` | `bool` | `False` | Let other members read through their own accounts; `true` answers `unavailable`, since no operation links a team reader. | | `selection` | `list[ResourceIdentity]` | required | The exact resources the source reads, in order: 1 to 240 distinct ids. | | `fingerprint` | `str` | required | The preview's `fingerprint`. | diff --git a/docs/reference/status.md b/docs/reference/status.md index 760593c167..2c165f5b1a 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,7 +89,7 @@ default is `off`) are not listed here. -56 boolean settings load false. +57 boolean settings load false. | Setting | Meaning | | --- | --- | @@ -128,6 +128,7 @@ default is `off`) are not listed here. | `LOOM_KNOWLEDGE_QUERY_HISTORY_ENABLED` | Permit opt-in ClickHouse query-history sources to queue definition drafts. | | `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED` | Enable optional source push setup, callbacks and Drive renewal; false keeps polling only. | | `LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED` | The knowledge_source_sync worker: pulls each registered document source's changed files into its namespace's documents. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` | Serve owner-only `snapshot` and `selected_refresh` worker sources from a private copy in the collection's mirror. | | `LOOM_MCP_CODE_TOOLS` | List code.* tools on the MCP surface (core toolset union). | | `LOOM_MCP_CODE_UPLOAD_TOOLS` | Serve the compiler-tier upload ops (code.scip_ingest, code.scip_status) over MCP, which hides both when off. | | `LOOM_MEMORY_ASK_CONSISTENCY_CHECK` | After synthesis one judge call (the cheap client when the cascade is on, else the synth client) labels the answer entailed / neutral / contradicted against the memories it cites (consistency… | diff --git a/loom.example.yaml b/loom.example.yaml index e70ed7853e..4bb0965242 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -3205,6 +3205,11 @@ settings: # 1, the default; the remaining publication deadline can shorten it further. [restart] # knowledge_source_worker_frame_timeout_s: 1.0 + # Serve owner-only `snapshot` and `selected_refresh` worker sources from a private + # copy in the collection's mirror. Turn it on only once every replica runs a build + # that has it. [restart] + # knowledge_source_worker_copies_enabled: false + # Mirrored reads require a complete listing and group observation within this many # seconds; missing or older evidence admits nobody. [restart] # knowledge_source_acl_stale_seconds: 3600 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 985d0bd043..eb7b94c50e 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -3853,6 +3853,11 @@ "type": "integer", "description": "Seconds one sync pass may run before it is cancelled; it stops starting sources at three quarters of it. At least 180: 90 for the sync, then 60 of read time for one document's extraction and 30 for its writes before the deadline." }, + "knowledge_source_worker_copies_enabled": { + "default": false, + "type": "boolean", + "description": "Serve owner-only `snapshot` and `selected_refresh` worker sources from a private copy in the collection's mirror. Turn it on only once every replica runs a build that has it." + }, "knowledge_source_worker_frame_timeout_s": { "default": 1.0, "exclusiveMinimum": 0, diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 10d9fe3d7c..de8083f52a 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: 7f87ddc5fbd02902979af5035477706d52ada42f8ff0cbbf67dc49e3ef77b521 +// Registry model schema SHA-256: 3d28b5ff8c04d8ec257339bb43f11d5200b25670e5bf7dcb5dfd4e242d679a11 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -13239,15 +13239,16 @@ type WorkerMode = string // WorkerPreviewInput is a model used by Loom operations. type WorkerPreviewInput struct { - Org string `json:"org"` - Namespace string `json:"namespace"` - Name string `json:"name"` - WorkerID string `json:"worker_id"` - ProfileDigest string `json:"profile_digest"` - ConnectionID string `json:"connection_id"` - Mode string `json:"mode"` - TeamAccess *bool `json:"team_access,omitempty"` - Selection []ResourceIdentity `json:"selection"` + Org string `json:"org"` + Namespace string `json:"namespace"` + Name string `json:"name"` + WorkerID string `json:"worker_id"` + ProfileDigest string `json:"profile_digest"` + ConnectionID string `json:"connection_id"` + Mode string `json:"mode"` + IntervalSeconds Optional[int64] `json:"interval_seconds,omitempty"` + TeamAccess *bool `json:"team_access,omitempty"` + Selection []ResourceIdentity `json:"selection"` } // WorkerPreviewOutput is a model used by Loom operations. @@ -13306,17 +13307,18 @@ type WorkerProfilesOutput struct { // WorkerRegisterInput is a model used by Loom operations. type WorkerRegisterInput struct { - Org string `json:"org"` - Namespace string `json:"namespace"` - Name string `json:"name"` - WorkerID string `json:"worker_id"` - ProfileDigest string `json:"profile_digest"` - ConnectionID string `json:"connection_id"` - Mode string `json:"mode"` - TeamAccess *bool `json:"team_access,omitempty"` - Selection []ResourceIdentity `json:"selection"` - Fingerprint string `json:"fingerprint"` - Evidence string `json:"evidence"` + Org string `json:"org"` + Namespace string `json:"namespace"` + Name string `json:"name"` + WorkerID string `json:"worker_id"` + ProfileDigest string `json:"profile_digest"` + ConnectionID string `json:"connection_id"` + Mode string `json:"mode"` + IntervalSeconds Optional[int64] `json:"interval_seconds,omitempty"` + TeamAccess *bool `json:"team_access,omitempty"` + Selection []ResourceIdentity `json:"selection"` + Fingerprint string `json:"fingerprint"` + Evidence string `json:"evidence"` } // WorkerRegisterOutput is a model used by Loom operations. diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 3643c24894..9c02171f48 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -12641,7 +12641,7 @@ class KnowledgeSourceWorkerEnrollOutput(TypedDict, total=False): class KnowledgeSourceWorkerPreviewInput(TypedDict, total=False): - "Preview a live worker source on the caller's linked account; nothing is written." + "Preview a worker source on the caller's linked account; nothing is written." org: Required[str] namespace: Required[str] @@ -12650,6 +12650,7 @@ class KnowledgeSourceWorkerPreviewInput(TypedDict, total=False): profile_digest: Required[str] connection_id: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] + interval_seconds: NotRequired[Optional[int]] team_access: NotRequired[bool] selection: Required[list["ResourceIdentity"]] @@ -12660,7 +12661,7 @@ class ResourceIdentity(TypedDict, total=False): class KnowledgeSourceWorkerPreviewBody(TypedDict, total=False): - "Preview a live worker source on the caller's linked account; nothing is written." + "Preview a worker source on the caller's linked account; nothing is written." org: NotRequired[str] namespace: NotRequired[str] @@ -12669,6 +12670,7 @@ class KnowledgeSourceWorkerPreviewBody(TypedDict, total=False): profile_digest: Required[str] connection_id: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] + interval_seconds: NotRequired[Optional[int]] team_access: NotRequired[bool] selection: Required[list["ResourceIdentity"]] @@ -12731,7 +12733,7 @@ class WorkerProfileChoice(TypedDict, total=False): class KnowledgeSourceWorkerRegisterInput(TypedDict, total=False): - "Register the live worker source a preview showed, with its fingerprint and evidence." + "Register the worker source a preview showed, with its fingerprint and evidence." org: Required[str] namespace: Required[str] @@ -12740,6 +12742,7 @@ class KnowledgeSourceWorkerRegisterInput(TypedDict, total=False): profile_digest: Required[str] connection_id: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] + interval_seconds: NotRequired[Optional[int]] team_access: NotRequired[bool] selection: Required[list["ResourceIdentity"]] fingerprint: Required[str] @@ -12747,7 +12750,7 @@ class KnowledgeSourceWorkerRegisterInput(TypedDict, total=False): class KnowledgeSourceWorkerRegisterBody(TypedDict, total=False): - "Register the live worker source a preview showed, with its fingerprint and evidence." + "Register the worker source a preview showed, with its fingerprint and evidence." org: NotRequired[str] namespace: NotRequired[str] @@ -12756,6 +12759,7 @@ class KnowledgeSourceWorkerRegisterBody(TypedDict, total=False): profile_digest: Required[str] connection_id: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] + interval_seconds: NotRequired[Optional[int]] team_access: NotRequired[bool] selection: Required[list["ResourceIdentity"]] fingerprint: Required[str] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 39654d9c32..260d235de0 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -183,9 +183,9 @@ module Generated "knowledge.source.update" => OpSpec.new("knowledge.source.update", "knowledge", "source_update", false, false, "writer", "experimental", %w[org namespace name add_items add_links remove_items remove_links crawl_options include].freeze, %w[org namespace name].freeze), "knowledge.source.worker_approve" => OpSpec.new("knowledge.source.worker_approve", "knowledge", "source_worker_approve", false, false, "admin", "experimental", %w[org namespace worker_id profile_digest modes team_access expected_generation].freeze, %w[org namespace worker_id profile_digest modes expected_generation].freeze), "knowledge.source.worker_enroll" => OpSpec.new("knowledge.source.worker_enroll", "knowledge", "source_worker_enroll", false, false, "viewer", "experimental", %w[org namespace worker_id profile_digest connection_id connection_generation].freeze, %w[org namespace worker_id profile_digest connection_id connection_generation].freeze), - "knowledge.source.worker_preview" => OpSpec.new("knowledge.source.worker_preview", "knowledge", "source_worker_preview", false, false, "writer", "experimental", %w[org namespace name worker_id profile_digest connection_id mode team_access selection].freeze, %w[org namespace name worker_id profile_digest connection_id mode selection].freeze), + "knowledge.source.worker_preview" => OpSpec.new("knowledge.source.worker_preview", "knowledge", "source_worker_preview", false, false, "writer", "experimental", %w[org namespace name worker_id profile_digest connection_id mode interval_seconds team_access selection].freeze, %w[org namespace name worker_id profile_digest connection_id mode selection].freeze), "knowledge.source.worker_profiles" => OpSpec.new("knowledge.source.worker_profiles", "knowledge", "source_worker_profiles", true, false, "admin", "experimental", %w[org namespace limit after].freeze, %w[org namespace].freeze), - "knowledge.source.worker_register" => OpSpec.new("knowledge.source.worker_register", "knowledge", "source_worker_register", false, false, "writer", "experimental", %w[org namespace name worker_id profile_digest connection_id mode team_access selection fingerprint evidence].freeze, %w[org namespace name worker_id profile_digest connection_id mode selection fingerprint evidence].freeze), + "knowledge.source.worker_register" => OpSpec.new("knowledge.source.worker_register", "knowledge", "source_worker_register", false, false, "writer", "experimental", %w[org namespace name worker_id profile_digest connection_id mode interval_seconds team_access selection fingerprint evidence].freeze, %w[org namespace name worker_id profile_digest connection_id mode selection fingerprint evidence].freeze), "knowledge.synthesize" => OpSpec.new("knowledge.synthesize", "knowledge", "synthesize", true, false, "viewer", "experimental", %w[org namespace user_id source_uris datasets task window_chars max_answer_chars max_windows].freeze, %w[org namespace task].freeze), "knowledge.update_metadata" => OpSpec.new("knowledge.update_metadata", "knowledge", "update_metadata", true, false, "writer", "experimental", %w[org namespace source_uri title description tags reindex].freeze, %w[org namespace source_uri].freeze), "knowledge.upsert" => OpSpec.new("knowledge.upsert", "knowledge", "upsert", true, false, "writer", "experimental", %w[org namespace source_uri content title description tags metadata original_bytes_b64 original_filename blob_content_type agent session_id source_class].freeze, %w[org namespace source_uri content].freeze), @@ -1569,7 +1569,7 @@ def source_worker_enroll(body = nil, request_options: nil, **fields) end # `knowledge.source.worker_preview` (writer, writes, experimental). - # Preview a live worker source on the caller's linked account; nothing is written. + # Preview a worker source on the caller's linked account; nothing is written. # Required: org, namespace, name, worker_id, profile_digest, connection_id, mode, selection. def source_worker_preview(body = nil, request_options: nil, **fields) call_op("knowledge.source.worker_preview", body, fields, request_options) @@ -1583,7 +1583,7 @@ def source_worker_profiles(body = nil, request_options: nil, **fields) end # `knowledge.source.worker_register` (writer, writes, experimental). - # Register the live worker source a preview showed, with its fingerprint and evidence. + # Register the worker source a preview showed, with its fingerprint and evidence. # Required: org, namespace, name, worker_id, profile_digest, connection_id, mode, selection, fingerprint, evidence. def source_worker_register(body = nil, request_options: nil, **fields) call_op("knowledge.source.worker_register", body, fields, request_options) diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index aacace973c..6cdc749749 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -28676,6 +28676,12 @@ pub struct WorkerPreviewInput { pub profile_digest: String, pub connection_id: String, pub mode: WorkerPreviewInputMode, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub interval_seconds: Option>, #[serde( default, skip_serializing_if = "Option::is_none", @@ -28701,6 +28707,7 @@ impl WorkerPreviewInput { profile_digest: profile_digest.into(), connection_id: connection_id.into(), mode, + interval_seconds: None, team_access: None, selection, } @@ -28713,6 +28720,14 @@ impl WorkerPreviewInput { self.namespace = Some(namespace.into()); self } + pub fn interval_seconds(mut self, interval_seconds: impl Into) -> Self { + self.interval_seconds = Some(Some(interval_seconds.into())); + self + } + pub fn interval_seconds_null(mut self) -> Self { + self.interval_seconds = Some(None); + self + } pub fn team_access(mut self, team_access: bool) -> Self { self.team_access = Some(team_access); self @@ -28940,6 +28955,12 @@ pub struct WorkerRegisterInput { pub profile_digest: String, pub connection_id: String, pub mode: WorkerRegisterInputMode, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub interval_seconds: Option>, #[serde( default, skip_serializing_if = "Option::is_none", @@ -28960,6 +28981,7 @@ impl WorkerRegisterInput { profile_digest: required.profile_digest, connection_id: required.connection_id, mode: required.mode, + interval_seconds: None, team_access: None, selection: required.selection, fingerprint: required.fingerprint, @@ -28974,6 +28996,14 @@ impl WorkerRegisterInput { self.namespace = Some(namespace.into()); self } + pub fn interval_seconds(mut self, interval_seconds: impl Into) -> Self { + self.interval_seconds = Some(Some(interval_seconds.into())); + self + } + pub fn interval_seconds_null(mut self) -> Self { + self.interval_seconds = Some(None); + self + } pub fn team_access(mut self, team_access: bool) -> Self { self.team_access = Some(team_access); self diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 6542cbb2f1..22156720cd 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4933,8 +4933,10 @@ export interface KnowledgeSourceWorkerPreviewInput { profile_digest: string; /** Opaque ID of the caller's worker account linked in this collection. */ connection_id: string; - /** `live` reads a resource when asked and keeps no copy; `snapshot` and `selected_refresh` answer `unavailable`. */ + /** `live` keeps no copy; `snapshot` and `selected_refresh` keep one for the owner, and answer `unavailable` while the deployment keeps no worker copies. */ mode: "live" | "snapshot" | "selected_refresh"; + /** Required for `selected_refresh` and refused for the other modes: the least seconds between a resource's copies, 300 to 86400. */ + interval_seconds?: number | null; /** Let other members read through their own accounts; `true` answers `unavailable`, since no operation links a team reader. */ team_access?: boolean; /** The exact resources the source reads, in order: 1 to 240 distinct ids. */ @@ -5023,8 +5025,10 @@ export interface KnowledgeSourceWorkerRegisterInput { profile_digest: string; /** Opaque ID of the caller's worker account linked in this collection. */ connection_id: string; - /** `live` reads a resource when asked and keeps no copy; `snapshot` and `selected_refresh` answer `unavailable`. */ + /** `live` keeps no copy; `snapshot` and `selected_refresh` keep one for the owner, and answer `unavailable` while the deployment keeps no worker copies. */ mode: "live" | "snapshot" | "selected_refresh"; + /** Required for `selected_refresh` and refused for the other modes: the least seconds between a resource's copies, 300 to 86400. */ + interval_seconds?: number | null; /** Let other members read through their own accounts; `true` answers `unavailable`, since no operation links a team reader. */ team_access?: boolean; /** The exact resources the source reads, in order: 1 to 240 distinct ids. */ diff --git a/server/cli/knowledge.py b/server/cli/knowledge.py index d582f62e06..d77c7747ef 100644 --- a/server/cli/knowledge.py +++ b/server/cli/knowledge.py @@ -67,17 +67,21 @@ def register_knowledge_cli(sub: Any) -> None: def _cmd_sync(args: argparse.Namespace) -> int: + from server.knowledge.app.mcp_worker_runtime import source_worker_runtime from server.knowledge.app.source_sync import run_sync from server.knowledge.domain.sources import normalize_name + from server.settings import settings async def _run(_ch: Any) -> int: started = time.monotonic() - result = await run_sync( - org=args.org, - namespace=args.namespace, - only=normalize_name(args.source), - full=bool(args.full), - ) + # A worker source's copy reads through the provisioned source workers. + async with source_worker_runtime(settings.knowledge_source_worker_routes_file): + result = await run_sync( + org=args.org, + namespace=args.namespace, + only=normalize_name(args.source), + full=bool(args.full), + ) print( f"{args.namespace}: {result.synced} of {result.sources} source(s) synced, " f"{result.changed} written, {result.removed + result.retired} retired, " diff --git a/server/cli/knowledge_source.py b/server/cli/knowledge_source.py index 2a547248b3..f41b903f89 100644 --- a/server/cli/knowledge_source.py +++ b/server/cli/knowledge_source.py @@ -192,7 +192,14 @@ def _worker_source(p: argparse.ArgumentParser) -> None: p.add_argument( "--mode", required=True, - help="live, snapshot or selected_refresh; the last two answer unavailable", + help="live, snapshot or selected_refresh; the last two answer unavailable unless the " + "server keeps worker copies", + ) + p.add_argument( + "--interval-seconds", + type=int, + default=None, + help="selected_refresh: the least seconds between a resource's copies, 300-86400", ) p.add_argument( "--team-access", @@ -384,6 +391,7 @@ def _worker_source_body(args: argparse.Namespace) -> dict[str, Any] | None: "mode": args.mode, "team_access": args.team_access, "selection": selection, + **({} if args.interval_seconds is None else {"interval_seconds": args.interval_seconds}), } diff --git a/server/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 76d3a40bef..3d9f78bf13 100644 --- a/server/knowledge/api/models_sources.py +++ b/server/knowledge/api/models_sources.py @@ -555,11 +555,10 @@ class KnowledgeSourceRemoveInput(BaseModel): those documents can still go; without it such a source answers SOURCE_NOT_FOUND. A namespace admin may, a connected or worker source's owner with writer, and for a crawl source only an admin who also holds the org-wide role; `confirm` must equal - the name. A worker source keeps its stored registration and queues nothing, - answering `documents_pending` 0 even with `delete_documents`. A mirrored source - always queues retirement of its own copies, regardless of `delete_documents`, and - answers no document count. A crawl source an offline restore retired answers - CREDENTIAL_REFUSED: the restore already queued its copies.""" + the name. A worker source keeps its stored registration. A mirrored source, a + worker source included, always queues retirement of its own copies, regardless of + `delete_documents`, and answers no document count. A crawl source an offline restore + retired answers CREDENTIAL_REFUSED: the restore already queued its copies.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -576,9 +575,9 @@ class KnowledgeSourceRemoveInput(BaseModel): class KnowledgeSourceRemoveOutput(BaseModel): # The source retired. name: str - # Live documents queued for retirement; always zero for a mirrored source because its - # counts are withheld, without `delete_documents` for a namespace source, or for a - # worker source. + # Live documents queued for retirement; always zero for a mirrored source (a worker + # source included) because its counts are withheld, and without `delete_documents` + # for a namespace source. documents_pending: int = 0 diff --git a/server/knowledge/api/models_worker_setup.py b/server/knowledge/api/models_worker_setup.py index fe512a6433..b9a3f1db20 100644 --- a/server/knowledge/api/models_worker_setup.py +++ b/server/knowledge/api/models_worker_setup.py @@ -170,7 +170,7 @@ class WorkerEnrollOutput(BaseModel): class WorkerSourceSetup(BaseModel): - """A live worker source to set up on the caller's own linked worker account.""" + """A worker source to set up on the caller's own linked worker account.""" model_config = ConfigDict(hide_input_in_errors=True) @@ -186,8 +186,13 @@ class WorkerSourceSetup(BaseModel): ) # `WorkerMode`'s values spelled out, so the reference and the generated SDKs list them. mode: Literal["live", "snapshot", "selected_refresh"] = Field( - description="`live` reads a resource when asked and keeps no copy; `snapshot` and" - " `selected_refresh` answer `unavailable`." + description="`live` keeps no copy; `snapshot` and `selected_refresh` keep one for the" + " owner, and answer `unavailable` while the deployment keeps no worker copies." + ) + interval_seconds: Annotated[int, Field(ge=300, le=86_400, strict=True)] | None = Field( + default=None, + description="Required for `selected_refresh` and refused for the other modes: the least" + " seconds between a resource's copies, 300 to 86400.", ) team_access: bool = Field( default=False, @@ -204,11 +209,15 @@ class WorkerSourceSetup(BaseModel): def _check_selection(self) -> Self: # Raises WorkerSetupRejected, a ValueError, which the model answers as invalid input. checked_worker_selection(tuple(self.selection), self.mode) + if (self.interval_seconds is None) == (self.mode == "selected_refresh"): + raise ValueError( + "interval_seconds is required for selected_refresh and refused for the other modes" + ) return self class WorkerPreviewInput(WorkerSourceSetup): - """Preview a live worker source on the caller's linked account; nothing is written.""" + """Preview a worker source on the caller's linked account; nothing is written.""" WorkerPreviewStatus = Literal["ok", "denied", "name_taken", "overloaded", "timeout", "unavailable"] @@ -243,7 +252,7 @@ class WorkerPreviewOutput(BaseModel): class WorkerRegisterInput(WorkerSourceSetup): - """Register the live worker source a preview showed, with its fingerprint and evidence.""" + """Register the worker source a preview showed, with its fingerprint and evidence.""" fingerprint: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] = Field( description="The preview's `fingerprint`." diff --git a/server/knowledge/api/ops_worker_setup.py b/server/knowledge/api/ops_worker_setup.py index 3cfd26cfd5..d853e116db 100644 --- a/server/knowledge/api/ops_worker_setup.py +++ b/server/knowledge/api/ops_worker_setup.py @@ -1,6 +1,6 @@ """Operations a collection sets up source workers with: an administrator's profile list and approval, a member's link of their own worker account, and a writer's preview and -registration of a live worker source on that account.""" +registration of a worker source on that account.""" from server.knowledge.api.models_worker_setup import ( WorkerApproveInput, diff --git a/server/knowledge/app/connected_accounts.py b/server/knowledge/app/connected_accounts.py index 02eac6ac5b..9a05924096 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -637,16 +637,32 @@ async def _erase_worker_owners( async def _erase_worker_sources(org: str, owner: str, before: int | None) -> None: """Delete the owner's worker source rows, active or not, in every namespace, each - under its namespace's source lease, then verify none is left anywhere.""" + under its namespace's source lease after their copies are queued for retirement, then + verify none is left anywhere.""" from server.erasure.app.connected_accounts import require_worker_sources_erased from server.knowledge.app import sources as source_ops for namespace in await source_store.worker_owner_namespaces(org, owner, before=before): async with source_ops.sources_lease(org, namespace): + for source in await source_store.worker_owner_sources( + org, namespace, owner, before=before + ): + await source_ops._queue_retirement(source) await source_store.erase_worker_owner(org, namespace, owner, before=before) await require_worker_sources_erased(org, owner, before=before) +async def owner_writes(org: str, namespace: str, subject: str) -> bool: + """Whether `subject` holds a writer grant in the namespace, read uncached. The alias + cache is invalidated after an uncached verified tie read, so the grant contract reads + this person's current spellings rather than a departed alias.""" + await aliases.verified_spellings(org, subject) + aliases.invalidate(org, [subject]) + with own_write_reads(): + role = await authz.grant_role_for(org, namespace, subject) + return role is not None and role >= Role.WRITER + + async def _source_standing(source: KnowledgeSource, account: ConnectedAccount) -> None: from server.knowledge.app import sources as source_ops @@ -678,14 +694,10 @@ async def _source_standing(source: KnowledgeSource, account: ConnectedAccount) - await _require_source_fence(account) since = int(account.connected_at.timestamp()) if account.connected_at else 0 await _standing(source.org, source.owner_subject, since) - # Invalidate the alias cache after an uncached verified tie read; the existing grant - # contract then reads this person's current spellings rather than a departed alias. - await aliases.verified_spellings(source.org, source.owner_subject) - aliases.invalidate(source.org, [source.owner_subject]) + writes = await owner_writes(source.org, source.namespace, source.owner_subject) with own_write_reads(): - role = await authz.grant_role_for(source.org, source.namespace, source.owner_subject) current = await source_store.latest_source(source.org, source.namespace, source.name) - if role is None or role < Role.WRITER: + if not writes: raise OwnerUnavailable() if ( current is None @@ -748,11 +760,7 @@ async def _draft_standing(source: KnowledgeSource, account: ConnectedAccount) -> or not await authz.row_in_scope(org, source.namespace, Role.WRITER) ): raise unavailable() - await aliases.verified_spellings(org, subject) - aliases.invalidate(org, [subject]) - with own_write_reads(): - role = await authz.grant_role_for(org, source.namespace, subject) - if role is None or role < Role.WRITER: + if not await owner_writes(org, source.namespace, subject): raise unavailable() await source_ops._require_source_namespace(org, source.namespace) await source_ops._require_no_erasure(org, source.namespace) diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py index a3c7ea553a..5f8d79ddb8 100644 --- a/server/knowledge/app/mcp_worker_read.py +++ b/server/knowledge/app/mcp_worker_read.py @@ -33,8 +33,11 @@ # selection proof reserves its share for its whole run, and stored-copy checks have theirs. _PROOF_SLOTS = SELECTION_PARALLELISM # not a setting: the checks one proof runs at once _STORED_CHECK_SLOTS = SELECTION_PARALLELISM # not a setting: a share proofs never take +# The sync's turns and their resources run one after another, so a process has at most one +# copy in flight; its own share keeps it from taking a live read's channel slot. +_COPY_SLOTS = 1 # not a setting: the one copy a process's sequential sync turns send # The request slots each share holds on one channel. -type _Share = Literal["live", "proof", "stored", "enroll"] +type _Share = Literal["live", "proof", "stored", "copy", "enroll"] # not a setting: the fixed check-access answer (ids, a digest, a time), with margin _MAX_CHECK_BODY = 1024 # not a setting: worker and Loom clocks count whole seconds and may differ by one. @@ -61,9 +64,25 @@ def live_grant_seconds(live_timeout_s: float) -> int: class WorkerReadRefused(Exception): - def __init__(self, reason: WorkerFailure) -> None: + def __init__(self, reason: WorkerFailure, *, upstream_access: bool = False) -> None: super().__init__(reason) self.reason = reason + # The worker said the upstream refused the account's access to the resource; any + # other `denied`, the worker's refusal of the grant or Loom's own, says nothing of it. + self.upstream_access = upstream_access + + +class _UpstreamDenial(BaseModel): + """The worker's 403 body when the upstream refused the account's access.""" + + model_config = ConfigDict(extra="forbid", strict=True, frozen=True) + + status: Literal["denied"] + reason: Literal["upstream_access"] + + +# not a setting: the worker's fixed upstream-denial body, with margin +_MAX_DENIAL_BODY = 256 @dataclass(frozen=True, repr=False) @@ -169,6 +188,26 @@ async def __call__( ) -> WorkerAccess: ... +async def _upstream_denial(response: httpx.Response) -> bool: + """Whether a 403 carries the worker's upstream-denial body, read whole and bounded; a + worker that sends none, or anything else, answers a plain denial.""" + if ( + response.headers.get("content-encoding", "identity") != "identity" + or response.headers.get("content-type", "").partition(";")[0] != "application/json" + ): + return False + data = bytearray() + async for chunk in response.aiter_raw(): + if len(data) + len(chunk) > _MAX_DENIAL_BODY: + return False + data.extend(chunk) + try: + _UpstreamDenial.model_validate_json(data) + except ValidationError: + return False + return True + + def _answers(reading: WorkerReading | WorkerAccess, issued: _Issued) -> None: if reading.request_id != issued.request_id or not ( issued.issued_at - _CLOCK_SKEW_S <= reading.fetched_at < issued.expires_at @@ -239,6 +278,7 @@ def __init__( "live": max_inflight, "proof": _PROOF_SLOTS, "stored": _STORED_CHECK_SLOTS, + "copy": _COPY_SLOTS, "enroll": _ENROLLMENT_CAPACITY, } self._busy: dict[_Share, int] = dict.fromkeys(self._slots, 0) @@ -251,7 +291,11 @@ def __init__( verify=tls or True, limits=httpx.Limits( max_connections=( - max_inflight + _PROOF_SLOTS + _STORED_CHECK_SLOTS + _ENROLLMENT_CAPACITY + max_inflight + + _PROOF_SLOTS + + _STORED_CHECK_SLOTS + + _COPY_SLOTS + + _ENROLLMENT_CAPACITY ), max_keepalive_connections=max_inflight, ), @@ -270,6 +314,8 @@ async def _post( headers["Content-Type"] = "application/json" data = bytearray() async with self._client.stream("POST", url, headers=headers, content=body) as response: + if response.status_code == 403: + raise WorkerReadRefused("denied", upstream_access=await _upstream_denial(response)) if response.status_code != 200: # A server error is the worker or its proxy failing, not a refusal. other: WorkerFailure = "unavailable" if response.status_code >= 500 else "denied" @@ -324,6 +370,19 @@ async def run( lambda payload, issued: _validate_reading(payload, scope, issued), ) + async def copy( + self, scope: WorkerReadScope, *, require_current: Callable[[], Awaitable[WorkerReadScope]] + ) -> WorkerReading: + """Read `scope`'s resource for its stored copy, in the copy share. The caller resolved + `scope` just before this call; `require_current` checks it again after the reply.""" + return await self._exchange( + scope, + "live", + "copy", + require_current, + lambda payload, issued: _validate_reading(payload, scope, issued), + ) + async def check_access( self, scope: WorkerReadScope, *, require_current: Callable[[], Awaitable[WorkerReadScope]] ) -> WorkerAccess: diff --git a/server/knowledge/app/mcp_worker_setup_preview.py b/server/knowledge/app/mcp_worker_setup_preview.py index 498d0a5f8f..5eda2c18c2 100644 --- a/server/knowledge/app/mcp_worker_setup_preview.py +++ b/server/knowledge/app/mcp_worker_setup_preview.py @@ -1,4 +1,4 @@ -"""Preview a live worker source: prove its selection through the caller's own linked +"""Preview a worker source: prove its selection through the caller's own linked account and say what the source will read and keep, writing nothing. The caller check comes first, so only a collection writer learns that the deployment, @@ -37,12 +37,22 @@ ) from server.knowledge.domain.mcp_worker_source import WorkerFailure -# What each mode reads and keeps, as the preview states it; only `live` is served. +# What each mode reads and keeps, as the preview states it. _DISCLOSURES = { "live": ( "Each read asks the worker for the current resource through the owner's account;" " Loom stores no copy and does not index it." ), + "snapshot": ( + "Loom reads each resource once through the owner's account and keeps that copy," + " indexed and shown to the owner alone, while the worker confirms the account still" + " reads it." + ), + "selected_refresh": ( + "Loom reads each resource through the owner's account and replaces its copy at most" + " every interval; the copy is indexed and shown to the owner alone, while the worker" + " confirms the account still reads it." + ), } _PROOF_STATUS: dict[WorkerFailure, WorkerPreviewStatus] = { "denied": "denied", diff --git a/server/knowledge/app/mcp_worker_setup_register.py b/server/knowledge/app/mcp_worker_setup_register.py index 295d69381a..705db6e7f2 100644 --- a/server/knowledge/app/mcp_worker_setup_register.py +++ b/server/knowledge/app/mcp_worker_setup_register.py @@ -1,4 +1,4 @@ -"""Register the live worker source a preview showed, on the caller's own linked account. +"""Register the worker source a preview showed, on the caller's own linked account. The caller check comes first, as for the preview. Under the namespace's source lease, which serializes every write of its sources, the registration checks the collection, the diff --git a/server/knowledge/app/mcp_worker_setup_source.py b/server/knowledge/app/mcp_worker_setup_source.py index a662681882..6cb25e7b58 100644 --- a/server/knowledge/app/mcp_worker_setup_source.py +++ b/server/knowledge/app/mcp_worker_setup_source.py @@ -45,6 +45,7 @@ from server.knowledge.store import pg_mcp_worker_enrollment as accounts from server.knowledge.store import pg_worker_row_lock as row_lock from server.knowledge.store.pg_worker_row_lock import WorkerRowBusy +from server.settings import settings if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -89,13 +90,21 @@ def destination_id(org: str, namespace: str) -> UUID: def intent_of(setup: WorkerSourceSetup) -> SetupIntent: - return SetupIntent(tuple(setup.selection), setup.mode, share_with_team=setup.team_access) + return SetupIntent( + tuple(setup.selection), + setup.mode, + interval_seconds=setup.interval_seconds, + share_with_team=setup.team_access, + ) def servable(setup: WorkerSourceSetup) -> bool: - """Only a live registration is served. A snapshot or selected refresh needs a stored - copy and its refresh, and team access a linked team reader, none of which ships.""" - return setup.mode == "live" and not setup.team_access + """A live registration, or an owner-only snapshot or selected refresh while the + deployment keeps worker copies. Team access needs a linked team reader, which no + operation makes.""" + if setup.team_access: + return False + return setup.mode == "live" or settings.knowledge_source_worker_copies_enabled @dataclass(frozen=True, repr=False) @@ -145,6 +154,10 @@ def state( _FIRST_SELECTION, _UNVERSIONED, now, + # The sync keeps a copy in the mirror, whose retirement queue and erasure + # remove it, only while copies are on. + store_qualified=settings.knowledge_source_worker_copies_enabled, + erasure_qualified=settings.knowledge_source_worker_copies_enabled, ) diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 3de93c496f..9b633069cc 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -87,6 +87,10 @@ class ReadPlan: ) _crawl_pins: dict[tuple[str, str], KnowledgeSource] = field(default_factory=dict, repr=False) + _worker_pins: dict[tuple[str, str], KnowledgeSource] = field(default_factory=dict, repr=False) + # The reader's own sign-in subject for its worker rows, read once by `prepare` and once + # by each `check` batch's plan; "" when the reader has none, so it owns no worker source. + _own_subject: str | None = field(default=None, repr=False) @property def discovery_sources(self) -> dict[tuple[str, str], str]: @@ -144,12 +148,15 @@ async def check( async def _refresh_scope(self) -> None: """Refresh conditional evidence without adding a discovery leg to this request.""" initial = self.discovery_sources - sources = await store.active_sources(self.org, sorted(set(initial.values()))) + sources = await store.active_sources( + self.org, sorted(set(initial.values())), workers=_worker_copies() + ) snapshot = ReadPlan(self.org) snapshot._auth = self._auth snapshot._scope_frozen = True snapshot._connected_pins = self._connected_pins snapshot._crawl_pins = self._crawl_pins + snapshot._worker_pins = self._worker_pins await _prepare(snapshot, sources, self._reader_subject) self.sources = { key: original @@ -262,9 +269,14 @@ def _head_serves(head: store.ReadHead, candidate: dict[str, Any], chunks: bool) ) +def _worker_copies() -> bool: + """Whether worker rows join the mirror's registrations: only while copies are on.""" + return settings.knowledge_source_worker_copies_enabled + + async def has_active_mirrored_sources(org: str, namespace: str) -> bool: """Read public registration presence after the caller authorizes the namespace.""" - return bool(await store.active_sources(org, [namespace])) + return bool(await store.active_sources(org, [namespace], workers=_worker_copies())) async def prepare(org: str, namespaces: list[str]) -> ReadPlan: @@ -284,7 +296,7 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: with sequential_reads(): for namespace in sorted(set(namespaces)): await check_authorized(auth, Role.VIEWER, org, namespace) - sources = await store.active_sources(org, namespaces) + sources = await store.active_sources(org, namespaces, workers=_worker_copies()) if not sources: return plan if not request_work.mark_mirrored(): @@ -322,7 +334,15 @@ async def _eligible_sources( key = row["namespace"], row["source_id"] mode = row.get("credential_mode", "shared") if mode == "shared": - if key not in plan._connected_pins and key not in plan._crawl_pins: + if ( + key not in plan._connected_pins + and key not in plan._crawl_pins + and key not in plan._worker_pins + ): + eligible.append(row) + continue + if mode == "worker": + if await _worker_copy_eligible(plan, row): eligible.append(row) continue if mode == "crawl": @@ -378,6 +398,65 @@ async def _eligible_sources( return eligible, crawl_generations +async def _reader_own_subject(plan: ReadPlan, auth: AuthInfo) -> str: + """The reader's own sign-in subject in the plan's org, read once for this plan.""" + from server.knowledge.app import connected_accounts + + if plan._own_subject is None: + try: + owner_org, subject = await connected_accounts.own_subject(auth) + except Exception: # noqa: BLE001 — a reader without standing owns no worker source + owner_org, subject = "", "" + plan._own_subject = subject if owner_org == plan.org else "" + return plan._own_subject + + +async def _worker_copy_eligible(plan: ReadPlan, row: dict[str, Any]) -> bool: + """A worker row's copies are read only by their owner, while the registration this + request first read stays the latest, keeps copies, and its approval and the owner's + worker account are current.""" + from server.knowledge.app import source_sync_worker + from server.knowledge.app.mcp_worker_runtime import current_directory + from server.knowledge.domain.mcp_worker_source import worker_copied + from server.knowledge.store import sources as source_store + + key = row["namespace"], row["source_id"] + if plan._scope_frozen and key not in plan._worker_pins: + return False + try: + auth, directory = plan._auth, current_directory() + if auth is None or current_auth() is not auth or directory is None: + return False + # A row the reader does not own costs no registry read. + subject = await _reader_own_subject(plan, auth) + if not subject or row.get("owner_subject") != subject: + return False + source = await source_store.latest_source(plan.org, row["namespace"], row["name"]) + if source is None or source.source_id != row["source_id"] or not worker_copied(source): + return False + pinned = plan._worker_pins.get(key) + if pinned is not None and ( + source.connection_id != pinned.connection_id + or source.owner_subject != pinned.owner_subject + or source.worker_history != pinned.worker_history + ): + return False + await check_authorized(auth, Role.VIEWER, plan.org, row["namespace"]) + # The pre-filter read the listed row; the registration read since must name the + # same owner, so a listed row that disagrees with it admits nothing. + if (plan.org, subject) != (source.org, source.owner_subject): + return False + if not await source_sync_worker.account_current(source, directory): + return False + if current_auth() is not auth: + return False + if not plan._scope_frozen: + plan._worker_pins[key] = copy.deepcopy(source) + return True + except Exception: # noqa: BLE001 — unverifiable worker authority admits no mirror leg + return False + + async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) -> None: sources, crawl_generations = await _eligible_sources(plan, sources) names = sorted({s["namespace"] for s in sources}) diff --git a/server/knowledge/app/source_retirements.py b/server/knowledge/app/source_retirements.py index 40fe1a2159..09c730c33f 100644 --- a/server/knowledge/app/source_retirements.py +++ b/server/knowledge/app/source_retirements.py @@ -15,7 +15,6 @@ SYNC_WORKER_ACTOR, KnowledgeSource, home, - is_worker_source, mirror_uri_suffix, turn_lease_name, ) @@ -88,12 +87,8 @@ async def _run_once() -> None: def _blocks_retirement(item: queue.Retirement, current: KnowledgeSource | None) -> bool: - # A queue entry can precede inactivation or outlive its native registration. - return ( - current is not None - and current.source_id == item.source_id - and (current.active or is_worker_source(current)) - ) + # A queue entry can precede inactivation or outlive its registration. + return current is not None and current.source_id == item.source_id and current.active async def _retire(item: queue.Retirement, run: source_sync.Pass) -> None: diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 4c0ed98514..6c6568aaa6 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -2,10 +2,11 @@ mirrored folder source into the namespace's mirror: one pass over every active source, run by the `knowledge_source_sync` worker and by `loom knowledge sync`. The shared-folder turn, over its items (`source_gdrive_items`), is below; each other kind, -and a mirrored folder source, has its own turn module (`source_sync_linear`, -`source_sync_notion`, `source_sync_recording`, `source_sync_mirror`), chosen by -`_turn_of`, which builds on the public helpers here (`__all__`). A kind's own -bookkeeping goes in `TurnResult.kind_state`, which the sync state keeps. +a mirrored folder source and an owner's worker copy have their own turn module +(`source_sync_linear`, `source_sync_notion`, `source_sync_recording`, `source_sync_mirror`, +`source_sync_worker`), chosen by `_turn_of`, which builds on the public helpers here +(`__all__`). A kind's own bookkeeping goes in `TurnResult.kind_state`, which the sync +state keeps. A pass reads the active sources and drops those whose namespace is inactive. The mirrored sources go first, starting work during the first quarter of the pass under @@ -116,6 +117,7 @@ from server.knowledge.app import source_gdrive_items as gdrive_items from server.knowledge.app import sources as source_ops from server.knowledge.domain import access_list, convert, transcripts +from server.knowledge.domain.mcp_worker_source import worker_copied from server.knowledge.domain.sources import ( GDRIVE_MIME_TYPES, SYNC_WORKER_ACTOR, @@ -361,12 +363,12 @@ async def run_sync( for src in usable: await source_ops.request_full_sync(src) states = await _states(usable) - mirrored = [s for s in usable if mirror_synced(s)] + mirrored = [s for s in usable if _mirrored(s)] if mirrored: # Until a third of the pass's start window; the namespace sources then have the # rest of the pass's own budget, and their document bound is their own. await _sync_mirrored(mirrored, states, run.budget, result) - usable = [s for s in usable if not mirror_synced(s)] + usable = [s for s in usable if not _mirrored(s)] asked = sorted( (s for s in usable if _requested(states, s)), key=lambda s: _requested(states, s), @@ -416,18 +418,22 @@ def synced_at(src: KnowledgeSource) -> str: return str(detail.get("last_synced_at") or "") for src in sorted(mirrored, key=synced_at): - if run.spent(): + if run.budget.exhausted(): return + # A worker copy's access checks spend only time, so its turn starts past the + # document bound; its copies wait for a pass with room. + if run.left <= 0 and not worker_copied(src): + continue await _sync_one(src, states.get(_cursor_of(src), {}), run, result) async def _usable(found: list[KnowledgeSource]) -> list[KnowledgeSource]: """The sources a pass syncs: those whose namespace is active, of the sources this - build serves and the mirrored ones its worker writes, the latter only while auth is - on.""" + build serves and the mirrored ones its worker writes (worker copies among them), the + latter only while auth is on.""" # With auth off there is no reader a mirror's lists could be checked against. mirrors_on = settings.auth_actually_required() - syncable = [s for s in found if served(s) or (mirror_synced(s) and mirrors_on)] + syncable = [s for s in found if served(s) or (_mirrored(s) and mirrors_on)] inactive = await store.inactive_namespaces(sorted({(s.org, s.namespace) for s in syncable})) return [s for s in syncable if (s.org, s.namespace) not in inactive] @@ -463,7 +469,7 @@ async def _source_turn(src: KnowledgeSource) -> AsyncIterator[leases.Lease]: async def _sync_one( src: KnowledgeSource, state: dict[str, str], run: Pass, result: PassResult ) -> TurnResult | None: - if not mirror_synced(src): + if not _mirrored(src): return await _sync_turn(src, state, run, result) result.private_work = True with private_sync.scope(): @@ -487,7 +493,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s was removed during its turn", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — recorded as the source's failed turn - if not mirror_synced(src): + if not _mirrored(src): log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) turn = TurnResult() turn.fail("failed", type(e).__name__) @@ -496,7 +502,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others - if mirror_synced(src): + if _mirrored(src): _mirror_failure(src, result) return None result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") @@ -504,7 +510,7 @@ async def _sync_turn( log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) pass_context.note_failure(e, _cursor_of(src)) return None - if mirror_synced(src): + if _mirrored(src): if turn.status != "ok": _mirror_failure(src, result) return turn @@ -525,6 +531,22 @@ async def _sync_turn( return turn +def _mirrored(src: KnowledgeSource) -> bool: + """Whether the sync writes `src` into its namespace's mirror: a mirrored native source, + or a worker source whose owner's copy it keeps.""" + return mirror_synced(src) or worker_copied(src) + + +async def _registered(src: KnowledgeSource) -> KnowledgeSource | None: + """The active registration a turn read `src` from, or None once it was removed or + replaced.""" + if worker_copied(src): + from server.knowledge.app import source_sync_worker + + return await source_sync_worker.registered(src) + return await source_ops.current_native_source(src) + + def _mirror_failure(src: KnowledgeSource, result: PassResult) -> None: """Report the same code for every cause without exporting turn details.""" result.errors.append(f"{_cursor_of(src)}: SYNC_FAILED") @@ -535,6 +557,10 @@ def _turn_of(src: KnowledgeSource) -> Callable[..., Awaitable[TurnResult]]: """The turn function of a source; this module's `_turn` reads a folder, and a mirrored folder source writes into its namespace's mirror.""" # Imported here: a kind's module builds on this one's helpers. + if worker_copied(src): + from server.knowledge.app import source_sync_worker + + return source_sync_worker.turn if src.credential_mode == "crawl" and src.kind == "gdrive" and mirror_synced(src): from server.knowledge.app import source_sync_crawl @@ -1415,12 +1441,12 @@ async def _write_state(src: KnowledgeSource, read: dict[str, str], turn: TurnRes derived from the mirror's documents, so it goes under the mirror (`mirror_state`).""" async with source_ops.sources_lease(src.org, src.namespace): with sequential_reads(): - if await source_ops.current_native_source(src) is None: + if await _registered(src) is None: return states = await store.read_states(src.org, src.namespace, [src.name]) mirror_row = await mirror_state(src, turn.mirror) if turn.mirror else {} current = states.get(src.name) or {} - if mirror_synced(src): + if _mirrored(src): await _write_mirrored_state(src, read, turn, current, mirror_row) return detail = json_object(current.get("detail", "")) diff --git a/server/knowledge/app/source_sync_connected.py b/server/knowledge/app/source_sync_connected.py index 56857965aa..76c01d21c1 100644 --- a/server/knowledge/app/source_sync_connected.py +++ b/server/knowledge/app/source_sync_connected.py @@ -55,26 +55,7 @@ async def ensure_current(src: KnowledgeSource) -> None: return except connected_accounts.OwnerUnavailable: pass - pending = await source_ops._queue_retirement(current) - from server.knowledge.app.source_push import retire - - await retire(current) - await source_store.insert_source( - dataclasses.replace( - current, - active=False, - credential_enc="", - secret_enc="", - pending_delete=pending or current.pending_delete, - ) - ) - await source_store.write_state( - current.org, - current.namespace, - current.name, - state_value="", - detail={"status": "owner_inactive"}, - ) + await source_ops.retire_owner_inactive(current) raise sync.SourceGone(sync._cursor_of(src)) diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py new file mode 100644 index 0000000000..9d1d4373cf --- /dev/null +++ b/server/knowledge/app/source_sync_worker.py @@ -0,0 +1,556 @@ +"""An owner-only `snapshot` or `selected_refresh` worker source's private copy, kept in its +namespace's mirror by the sync worker. + +Each turn reads the copy's state under the mirror: per selected resource, when its copy was +last written and when the owner's access to it was last confirmed. A resource with no copy, +or a `selected_refresh` one whose interval has passed, is read through the worker as the +owner and written with an access list naming the owner alone; an unchanged digest writes +nothing. Every other copy older than half of `knowledge_source_acl_stale_seconds` has its +access checked (a digest, no content). Resources without a copy go first, then the stored +copies by oldest confirmation. Only copies spend the pass's document bound. + +A denial the worker reports as the upstream's (its 403 with reason `upstream_access`) +retires that resource's copy, once the registration and the owner's authority are read +again and still hold; any other denial (a grant the worker refused, Loom's own check, a +reply that failed validation) ends the turn with every copy kept. A `timeout` or +`unsupported` answer keeps that resource's copy and the turn goes on. A timeout never +retires a copy; a copy answering `unsupported` as its confirmation would lapse before the +next pass is retired when another copy was confirmed after its own check fell due and the +owner's authority, read again, still holds, so the others stay vouched for. Any other +refusal keeps every copy, ends the turn and records no listing; a stored copy whose request +keeps ending turns keeps every copy of the source unserved until it answers or the source +is removed, which fails closed. A resource left without a copy is tried again after a wait: +its refresh interval or, for a snapshot, half the stale window after the upstream's denial +or an `unsupported` answer, and half the stale window after a timeout or any other refusal +that ended the turn. The listing the mirror read gate needs records the oldest confirmation +of every stored copy, so a copy whose access was not confirmed within the stale window +stops every copy of the source being served until it is confirmed or retired. + +A turn needs the owner's standing (an active directory account, no revocation since the +registration, a writer grant in the namespace), the collection's current approval of the +registration's mode and the owner's worker account at the registered generation; each +worker request resolves them again through `CurrentRead`. An approval or worker account +read that no longer matches the registration ends it for good: under the namespace's +source lease the row goes inactive, its copies are queued for retirement and its state +reads `owner_inactive`, as for a connected source whose owner left.""" + +from __future__ import annotations + +import dataclasses +import functools +from datetime import UTC, datetime, timedelta +from typing import Any, Literal, NoReturn +from uuid import UUID + +from server.core.ch import sequential_reads +from server.core.errors import ValidationError +from server.knowledge.app import connected_accounts, mirrors, private_sync +from server.knowledge.app import source_sync as sync +from server.knowledge.app import sources as source_ops +from server.knowledge.app.mcp_worker_authority import ( + CurrentRead, + ReaderStanding, + RequestedResource, +) +from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory +from server.knowledge.app.mcp_worker_read import ( + WorkerAccess, + WorkerReading, + WorkerReadRefused, +) +from server.knowledge.app.mcp_worker_runtime import current_directory, current_routes +from server.knowledge.domain import access_list +from server.knowledge.domain.mcp_identity import ResourceIdentity, resource_digest, resource_uri +from server.knowledge.domain.mcp_worker_source import ( + WorkerSourceRefused, + decode_worker_source, + worker_copied, +) +from server.knowledge.domain.sources import ( + KnowledgeSource, + json_object, + mirror_uri_suffix, + source_id_tag, +) +from server.knowledge.store import documents +from server.knowledge.store import mirrors as mirror_store +from server.knowledge.store import sources as source_store +from server.settings import settings +from server.workers import pass_context +from server.workers.status import set_worker_identity + +# The mirror sync state keys: per resource digest, the copy's digest and times (or, with no +# copy, when to try again); and the confirmation time the last recorded listing carries. +_COPIES = "worker_copies" +_LISTED = "worker_listed_at" + + +async def registered(src: KnowledgeSource) -> KnowledgeSource | None: + """The active row of `src`'s registration, unchanged and still copied, or None.""" + fresh = await source_store.get_source(src.org, src.namespace, src.name) + if ( + fresh is None + or fresh.source_id != src.source_id + or fresh.owner_subject != src.owner_subject + or fresh.connection_id != src.connection_id + or fresh.worker_history != src.worker_history + or not worker_copied(fresh) + ): + return None + return fresh + + +async def require_current(src: KnowledgeSource) -> None: + """Raise SourceGone when the registration was removed or replaced.""" + with sequential_reads(): + if await registered(src) is None: + raise sync.SourceGone(sync._cursor_of(src)) + + +async def owner_standing(src: KnowledgeSource) -> bool: + """The owner's directory standing since the registration, and a writer grant.""" + created = src.created_at or datetime.fromtimestamp(0, UTC) + since = int(created.replace(tzinfo=created.tzinfo or UTC).timestamp()) + try: + await connected_accounts._standing(src.org, src.owner_subject, since) + except ValidationError: # a lost standing, or auth off: no owner to copy for + return False + return await connected_accounts.owner_writes(src.org, src.namespace, src.owner_subject) + + +type Authority = Literal["current", "gone", "unserved"] + + +async def authority(src: KnowledgeSource, directory: LiveSourceDirectory) -> Authority: + """`current` while the collection approves the registration's mode at its generation and + the owner's worker account is active at the registered generation, as `CurrentRead` + checks them for each request; `gone` when a read no longer matches, which no later read + undoes for this registration; `unserved` when this process's routes file does not + provision the profile. A read that fails raises.""" + try: + config, _ = decode_worker_source(src) + except WorkerSourceRefused: + return "gone" + routes = current_routes() + if routes is None or not routes.permits( + config.worker_id, src.org, config.profile_digest, config.mode, False + ): + return "unserved" + approval = await directory.worker_approval( + src.org, src.namespace, config.worker_id, config.profile_digest, config.mode, False + ) + record = await directory.connection( + src.org, src.namespace, src.owner_subject, config.worker_id, config.owner_connection_id + ) + if ( + approval != config.approval_generation + or record is None + or not record.active + or record.binding.connection_generation != config.owner_connection_generation + or record.binding.profile_digest != config.profile_digest + ): + return "gone" + return "current" + + +async def account_current(src: KnowledgeSource, directory: LiveSourceDirectory) -> bool: + return await authority(src, directory) == "current" + + +async def _end_registration(src: KnowledgeSource, directory: LiveSourceDirectory) -> NoReturn: + """The registration's approval or worker account is gone: write it inactive with its + copies queued for retirement, under the sources lease, unless a read there finds it + changed or its authority back. Raises SourceGone either way the turn cannot go on.""" + async with source_ops.sources_lease(src.org, src.namespace): + with sequential_reads(): + current = await registered(src) + if current is None or await authority(current, directory) != "gone": + raise sync.SourceGone(sync._cursor_of(src)) + await source_ops.retire_owner_inactive(current) + raise sync.SourceGone(sync._cursor_of(src)) + + +def _stale() -> timedelta: + return timedelta(seconds=settings.knowledge_source_acl_stale_seconds) + + +def _lapsing() -> timedelta: + """The age at which an unconfirmable copy goes: its confirmation would lapse before the + next pass could confirm it. No copy is retired before half the stale window: a copy + goes only when a peer was confirmed after its own check fell due + (`_confirmed_since_due`).""" + return _stale() - timedelta(seconds=settings.knowledge_source_sync_interval_seconds) + + +def _at(raw: Any) -> datetime | None: + try: + value = datetime.fromisoformat(str(raw)) + except ValueError: + return None + return value if value.tzinfo is not None else None + + +@dataclasses.dataclass +class _Copy: + """What the turn knows of one selected resource.""" + + item: ResourceIdentity + uri: str + stored: bool + entry: dict[str, Any] + + def copy_due(self, interval: int | None, now: datetime) -> bool: + if not self.stored: + retry = _at(self.entry.get("retry_at")) + return retry is None or now >= retry + copied = _at(self.entry.get("copied_at")) + return interval is not None and ( + copied is None or now - copied >= timedelta(seconds=interval) + ) + + def check_due(self, now: datetime) -> bool: + return not self.confirmed_within(_stale() / 2, now) + + def confirmed_within(self, window: timedelta, now: datetime) -> bool: + verified = _at(self.entry.get("verified_at")) + return verified is not None and now - verified < window + + +def _confirmed_since_due(copy: _Copy, copies: list[_Copy]) -> bool: + """Whether another stored copy was confirmed after `copy`'s own check fell due.""" + verified = _at(copy.entry.get("verified_at")) + if verified is None: + return False + due = verified + _stale() / 2 + return any( + other is not copy + and other.stored + and (at := _at(other.entry.get("verified_at"))) + and at > due + for other in copies + ) + + +def _oldest_confirmation(copies: list[_Copy]) -> datetime | None: + """The oldest confirmation among the stored copies; None when one has none or no copy + is stored, so no listing vouches for them.""" + times = [_at(c.entry.get("verified_at")) for c in copies if c.stored] + if not times or any(t is None for t in times): + return None + return min(t for t in times if t is not None) + + +class _Turn: + def __init__( + self, + src: KnowledgeSource, + directory: LiveSourceDirectory, + run: sync.Pass, + result: sync.TurnResult, + ) -> None: + self.src = src + self.directory = directory + self.run = run + self.result = result + self.config, _ = decode_worker_source(src) + # Stored copies whose resource answered `unsupported` as their confirmation was + # about to lapse. + self.lapsing: list[_Copy] = [] + + def _wait(self) -> timedelta: + """How long a resource left without a copy waits before it is tried again.""" + interval = self.config.interval_seconds + return timedelta(seconds=interval or settings.knowledge_source_acl_stale_seconds / 2) + + async def _standing(self, _: RequestedResource) -> ReaderStanding | None: + # The owner's whole standing, read for every request: a SCIM deactivation or a + # revocation mid-turn stops the next read and write, not only the listing. + src = self.src + return ReaderStanding(src.owner_subject) if await owner_standing(src) else None + + async def _exchange( + self, item: ResourceIdentity, *, content: bool + ) -> WorkerReading | WorkerAccess: + """One worker request for `item`, its authority resolved here and again after the + reply (and, for a check, before it is sent too).""" + src, directory = self.src, self.directory + current = CurrentRead( + RequestedResource(src.org, src.namespace, src.name, item.id), + self._standing, + directory.source, + directory.connection, + directory.enrollment, + directory.worker_approval, + purpose="stored", + ) + scope = await current.resolve() + if scope.source_id != UUID(src.source_id) or scope.requester != src.owner_subject: + raise sync.SourceGone(sync._cursor_of(src)) + channel = directory.worker(scope.worker_id) + if channel is None: + raise WorkerReadRefused("unavailable") + if content: + return await channel.copy(scope, require_current=current.resolve) + return await channel.check_access(scope, require_current=current.resolve) + + async def _write(self, copy: _Copy, reading: WorkerReading) -> None: + src, document = self.src, reading.document + if copy.stored and copy.entry.get("sha") == reading.content_sha256: + return # the stored text is the worker's: nothing to write or embed again + await require_current(src) + item = { + "id": resource_digest(copy.item.id), + "name": document.title, + "modifiedTime": document.revision or "", + } + try: + written = await sync.write_document( + src, + item, + copy.uri, + document.text, + ingested_format="worker", + extra_metadata={ + "content_sha256": reading.content_sha256, + "mime_type": document.mime_type, + }, + permissions=access_list.AccessList(owner=src.owner_subject), + ) + except ValidationError as e: + # The store refuses this text: an older copy stays, its access confirmed. + self.result.unconverted_for(f"write_refused:{e.to_detail().get('code') or 'invalid'}") + return + if not written: + self.result.skipped += 1 + return + self.result.changed += 1 + if not copy.stored: + copy.entry.clear() + copy.stored = True + copy.entry["sha"] = reading.content_sha256 + + def _retry_later(self, copy: _Copy, asked: datetime, *, resource_word: bool) -> None: + """A resource without a copy waits before it is read again, so the next turn reaches + the others: its refresh interval after the resource's own answer (the upstream's + denial, `unsupported`), half the stale window after any other refusal.""" + wait = self._wait() if resource_word else _stale() / 2 + copy.entry["retry_at"] = (asked + wait).isoformat() + + async def visit(self, copy: _Copy, now: datetime) -> bool: + """Copy or check one resource; False once the turn must stop.""" + due = copy.copy_due(self.config.interval_seconds, now) + content = due and self.run.left > 0 + if due and not content: + # Out of the document bound: the copy waits for a pass with room, which the + # turn says; a stored copy still has its access checked when that is due. + self.result.mark(sync.TurnMark.PASS_BOUND) + if not copy.stored or not copy.check_due(now): + return True + asked = datetime.now(UTC) + try: + answer = await self._exchange(copy.item, content=content) + except WorkerReadRefused as refusal: + return await self._refused(copy, refusal, asked) + if isinstance(answer, WorkerReading): + self.run.left -= 1 + await self._write(copy, answer) + if copy.stored: + copy.entry["copied_at"] = asked.isoformat() + else: + self._retry_later(copy, asked, resource_word=True) + if copy.stored: + copy.entry["verified_at"] = asked.isoformat() + return True + + async def _authority_holds(self) -> bool: + with sequential_reads(): + if await registered(self.src) is None: + return False + return await owner_standing(self.src) and await account_current(self.src, self.directory) + + async def retire_lapsing(self, copies: list[_Copy]) -> None: + """Retire the copies whose resource the worker could not serve as their confirmation + was about to lapse, so they do not hold back the listing of the others, while the + owner's authority, read again, still holds. A copy goes only when another copy was + confirmed after its own check fell due: it has failed every check since, so the + failure is the resource's, not the upstream's or the worker's. The retired copy + waits as a resource without a copy does.""" + if self.result.status != "ok": + return # a turn a refusal ended retires nothing and records no listing + failing = [c for c in self.lapsing if _confirmed_since_due(c, copies)] + if failing and self.run.budget.exhausted(): + self.result.mark(sync.TurnMark.PASS_BOUND) + return + if not failing or not await self._authority_holds(): + return + asked = datetime.now(UTC) + for copy in failing: + pass_context.check_stop() + if await sync.retire(self.src, copy.uri): + self.result.removed += 1 + copy.stored = False + copy.entry.clear() + self._retry_later(copy, asked, resource_word=True) + self.result.note = "copy_unconfirmable" + + async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetime) -> bool: + reason, result = refusal.reason, self.result + if reason == "denied": + # Only the worker's report of the upstream's denial, under authority read again + # just now, says the owner's account no longer reads the resource. A grant the + # worker refused, Loom's own refusal (authority that changed meanwhile, a reply + # that failed validation) and a worker that names no reason keep every copy. + if not refusal.upstream_access or not await self._authority_holds(): + # Nothing is retired. A stored copy ends each turn it is checked in, and the + # source's copies stay unserved until it answers or the source is removed. + if not copy.stored: + self._retry_later(copy, asked, resource_word=False) + result.fail("denied", "denied") + return False + if copy.stored and await sync.retire(self.src, copy.uri): + result.removed += 1 + copy.stored = False + copy.entry.clear() + self._retry_later(copy, asked, resource_word=True) + return True + if reason == "unsupported" and not copy.stored: + self._retry_later(copy, asked, resource_word=True) + result.note = reason + return True + # A timeout or unsupported answer keeps that copy unconfirmed and the others go on; + # any other refusal ends the turn. A timeout may be the upstream's or the worker's, + # not the resource's, so it never retires a copy. + if reason in ("timeout", "unsupported"): + result.complete = False + result.note = reason + if not copy.stored: + self._retry_later(copy, asked, resource_word=False) + elif reason == "unsupported" and not copy.confirmed_within(_lapsing(), asked): + self.lapsing.append(copy) + return True + # Any other refusal ends the turn; a stored copy keeps the source's copies unserved + # until it answers, which fails closed. + if not copy.stored: + self._retry_later(copy, asked, resource_word=False) + result.fail(reason, reason) + return False + + +async def _known_copies( + src: KnowledgeSource, selected: tuple[ResourceIdentity, ...], recorded: dict[str, Any] +) -> list[_Copy]: + """Each selected resource's copy. A copy's address is its source ID's and its resource's, + and a registration's selection never changes, so every stored copy is a selected one.""" + uris = [resource_uri(src.source_id, item.id) for item in selected] + tag = source_id_tag(src.source_id) + with sequential_reads(): + stored = await source_store.copies_at(src.org, src.mirror, tag, uris) + copies = [] + for item, uri in zip(selected, uris, strict=True): + raw = recorded.get(resource_digest(item.id)) + raw = raw if isinstance(raw, dict) else {} + if uri in stored: + entry = dict(raw) + else: + entry = {"retry_at": raw["retry_at"]} if "retry_at" in raw else {} + copies.append(_Copy(item, uri, uri in stored, entry)) + return copies + + +async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: + """Copy or check the resources that are due, then vouch for the stored copies.""" + await require_current(src) + mirror = await mirrors.ensure_mirror( + src.org, src.namespace, still_current=functools.partial(require_current, src) + ) + src = dataclasses.replace(src, mirror=mirror) + result = sync.TurnResult(mirror=mirror, full=True) + detail = json_object((await sync.mirror_state(src, mirror)).get("detail", "")) + async with private_sync.mirror_costs(src.org, mirror, sync.WORKER): + set_worker_identity(sync.WORKER, org=src.org, namespace=mirror) + await _sync_copies(src, detail, run, result) + return result + + +async def _sync_copies( + src: KnowledgeSource, detail: dict[str, Any], run: sync.Pass, result: sync.TurnResult +) -> None: + config, selected = decode_worker_source(src) + recorded = detail.get(_COPIES) + copies = await _known_copies(src, selected, recorded if isinstance(recorded, dict) else {}) + listed = str(detail.get(_LISTED) or "") + result.kind_state[_LISTED] = listed + _keep(result, copies) + now = datetime.now(UTC) + due = [ + c + for c in copies + if c.copy_due(config.interval_seconds, now) or (c.stored and c.check_due(now)) + ] + oldest = _oldest_confirmation(copies) + if not due and oldest is not None and oldest.isoformat() == listed: + return # every copy was confirmed lately, and the listing says so + directory = current_directory() + if directory is None: + result.fail("unavailable", "unavailable") + return + held = await authority(src, directory) + if held == "gone": + await _end_registration(src, directory) + if held == "unserved": + # This process's routes file does not provision the profile: an operator's matter. + result.fail("unavailable", "unavailable") + return + if not await owner_standing(src): + result.fail("owner_unavailable", "owner_unavailable") + return + work = _Turn(src, directory, run, result) + await _visit_due(work, due, now) + await work.retire_lapsing(copies) + _keep(result, copies) + await _vouch(src, directory, copies, run, result) + + +async def _visit_due(work: _Turn, due: list[_Copy], now: datetime) -> None: + # Every resource without a copy first, then the stored copies by oldest confirmation, + # so a turn the bound cuts leaves the newest confirmations for later. + due.sort(key=lambda c: (c.stored, str(c.entry.get("verified_at") or ""))) + result = work.result + for copy in due: + if work.run.budget.exhausted(): + result.mark(sync.TurnMark.PASS_BOUND) + return + pass_context.check_stop() + result.documents_seen += 1 + if not await work.visit(copy, now): + return + + +def _keep(result: sync.TurnResult, copies: list[_Copy]) -> None: + result.kind_state[_COPIES] = {resource_digest(c.item.id): c.entry for c in copies if c.entry} + + +async def _vouch( + src: KnowledgeSource, + directory: LiveSourceDirectory, + copies: list[_Copy], + run: sync.Pass, + result: sync.TurnResult, +) -> None: + """Record the listing at the oldest confirmation of the stored copies, once each is + written and the owner's authority still holds. A turn that failed records nothing.""" + oldest = _oldest_confirmation(copies) + if oldest is None or result.status != "ok" or oldest.isoformat() == result.kind_state[_LISTED]: + return + if run.budget.exhausted(): + result.mark(sync.TurnMark.PASS_BOUND) # out of time before the listing: say so + return + if await documents.publications_owed(src.org, src.mirror, mirror_uri_suffix(src.source_id)): + return + await require_current(src) + if not await owner_standing(src) or not await account_current(src, directory): + result.fail("owner_unavailable", "owner_unavailable") + return + pass_context.check_stop() + await mirror_store.record_listing(src.org, src.mirror, src.source_id, src.name, oldest) + result.kind_state[_LISTED] = oldest.isoformat() diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index aab19122e9..e758bc7590 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -1167,12 +1167,8 @@ async def handle_knowledge_source_remove( # turn running meanwhile may still write one, and the worker clears the # request once none is left. pending_delete = input.delete_documents - if worker: - # This build writes no worker copy, and native retirement cannot find one - # a later build wrote, so nothing is queued; a request already on the row - # stays for that build, as namespace retirement keeps it. - pending_delete = src.pending_delete - elif src.access == domain.MIRRORED_ACCESS: + if src.access == domain.MIRRORED_ACCESS: + # A mirrored source's copies, an owner's worker copies among them, always go. pending_delete = await _queue_retirement(src) retired = _retired(src, pending_delete) from server.knowledge.app.source_push import retire @@ -1285,17 +1281,15 @@ async def deactivate_namespace_sources(org: str, namespace: str) -> list[str]: """Retire every active source of a namespace that is going away (its repository removed, the namespace deleted or erased): an inactive row with the credential cleared, so nothing reads or opens it again. A worker source goes inactive with its - config and items unchanged, its credentials cleared (and a crawl row's selected - addresses, approval and registrant), and nothing queued, since this build has no - worker cleanup. The caller holds `sources_lease`. The names retired.""" + config and items unchanged and its credentials cleared (and a crawl row's selected + addresses, approval and registrant); a mirrored one, worker sources included, has its + copies queued for retirement. The caller holds `sources_lease`. The names retired.""" with sequential_reads(): found = await store.list_sources(org, namespace) from server.knowledge.app.source_push import retire for src in found: - # A worker row queues no mirror cleanup; its push setup, which holds no worker - # payload, is retired like any other. - mirrored = src.access == domain.MIRRORED_ACCESS and not domain.is_worker_source(src) + mirrored = src.access == domain.MIRRORED_ACCESS pending = await _queue_retirement(src) if mirrored else False await retire(src) await store.insert_source(_retired(src, pending or src.pending_delete)) @@ -1315,6 +1309,19 @@ def _retired(src: KnowledgeSource, pending_delete: bool) -> KnowledgeSource: return retired +async def retire_owner_inactive(src: KnowledgeSource) -> None: + """Retire a source whose owner's authority is gone for good, as a removal does, its + state reading `owner_inactive`. The caller holds `sources_lease` and read `src` under it.""" + pending = await _queue_retirement(src) + from server.knowledge.app.source_push import retire + + await retire(src) + await store.insert_source(_retired(src, pending or src.pending_delete)) + await store.write_state( + src.org, src.namespace, src.name, state_value="", detail={"status": "owner_inactive"} + ) + + async def _queue_retirement(src: KnowledgeSource) -> bool: """Called under the sources lease, before inactivation; never creates a mirror.""" from server.knowledge.app.mirrors import live_mirror diff --git a/server/knowledge/domain/mcp_worker_source.py b/server/knowledge/domain/mcp_worker_source.py index 2d7388731d..76badc76ba 100644 --- a/server/knowledge/domain/mcp_worker_source.py +++ b/server/knowledge/domain/mcp_worker_source.py @@ -17,6 +17,7 @@ json_object, stored_items, ) +from server.settings import settings WORKER_SOURCE_VERSION = 1 WORKER_REGISTRATION = "worker_registration" @@ -146,6 +147,18 @@ def decode_worker_source( raise WorkerSourceRefused("worker source unavailable") from None +def worker_copied(source: KnowledgeSource) -> bool: + """Whether the sync keeps the owner's private copy of `source`: an active, unpaused, + owner-only `snapshot` or `selected_refresh` registration, while copies are on.""" + if not settings.knowledge_source_worker_copies_enabled: + return False + try: + config, _ = decode_worker_source(source) + except WorkerSourceRefused: + return False + return config.mode != "live" and not config.paused and config.reader_policy == "owner_only" + + def encode_worker_source( *, org: str, diff --git a/server/knowledge/store/source_access.py b/server/knowledge/store/source_access.py index c5265cba24..72256242f8 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -37,21 +37,36 @@ ) +# A worker row whose raw registration (`mcp_worker_source.encode_worker_source`) asks for an +# owner-only copy; `decode_worker_source` still decides. +_REGISTRATION = "JSONExtractString(config_json, 'worker_registration')" +_COPIED_WORKER = ( + f"(credential_mode = 'worker' AND JSONExtractString({_REGISTRATION}, 'mode') " + f"IN ('snapshot', 'selected_refresh') " + f"AND JSONExtractString({_REGISTRATION}, 'reader_policy') = 'owner_only')" +) + + class ReadHead(NamedTuple): row: dict[str, Any] serving: Serving async def active_sources( - org: str, namespaces: list[str], *, ch: _CHClient | None = None + org: str, namespaces: list[str], *, workers: bool = False, ch: _CHClient | None = None ) -> list[dict[str, Any]]: + """The active mirrored registrations; with `workers`, the worker rows whose stored + registration names an owner-only copy mode too, which the caller decodes before it + trusts one. A live worker row has no copy, so it is left out here.""" if not namespaces: return [] + native = f"NOT {WORKER_HISTORY}" + rows = f"({native} OR {_COPIED_WORKER})" if workers else native return await (ch or _default_client()).query_all( - "SELECT namespace, name, credential_mode, toString(source_id) AS source_id " - "FROM loom.knowledge_sources FINAL " + "SELECT namespace, name, credential_mode, toString(source_id) AS source_id, " + "owner_subject FROM loom.knowledge_sources FINAL " "WHERE org = {org:String} AND namespace IN {names:Array(String)} " - f"AND active AND access = 'mirrored' AND NOT {WORKER_HISTORY} ORDER BY namespace, name", + f"AND active AND access = 'mirrored' AND {rows} ORDER BY namespace, name", params={"org": org, "names": sorted(set(namespaces))}, ) diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index e413bf3384..3364722ef5 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -40,6 +40,7 @@ ) from server.knowledge.domain.source_crawl import Options from server.knowledge.domain.sources import ( + MIRRORED_ACCESS, NAMESPACE_ACCESS, SYNC_WORKER_ACTOR, KnowledgeSource, @@ -448,6 +449,34 @@ async def worker_owner_namespaces( return [str(row["namespace"]) for row in rows] +async def worker_owner_sources( + org: str, namespace: str, subject: str, *, before: int | None, ch: _CHClient | None = None +) -> list[KnowledgeSource]: + """Each distinct registration, by name and id, among the namespace's raw worker rows + `worker_owner_rows(before)` matches: what retirement needs to find its copies.""" + with sequential_reads(): + rows = await (ch or _default_client()).query_all( + "SELECT DISTINCT name, toString(source_id) AS source_id " + f"FROM {TABLE} WHERE namespace = {{ns:String}} AND {worker_owner_rows(before)} " + "ORDER BY name, source_id", + params={"org": org, "ns": namespace, "owner": subject, "before": before}, + ) + return [ + KnowledgeSource( + org=org, + namespace=namespace, + name=str(row["name"]), + kind="mcp", + source_id=str(row["source_id"]), + access=MIRRORED_ACCESS, + credential_mode="worker", + owner_subject=subject, + active=False, + ) + for row in rows + ] + + async def erase_worker_owner( org: str, namespace: str, subject: str, *, before: int | None, ch: _CHClient | None = None ) -> None: @@ -616,6 +645,31 @@ async def source_documents( return [dict(r) for r in rows] +async def copies_at( + org: str, namespace: str, tag: str, uris: list[str], *, ch: _CHClient | None = None +) -> set[str]: + """Which of `uris` hold a live document the sync wrote under `tag`: every one asked + for, however many the namespace holds.""" + if not uris: + return set() + rows = await (ch or _default_client()).query_all( + "SELECT source_uri FROM loom.documents FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND source_uri IN {uris:Array(String)} AND has(tags, {tag:String}) " + "AND actor = {actor:String} AND superseded_at IS NULL " + "LIMIT {limit:UInt32}", + params={ + "org": org, + "ns": namespace, + "uris": sorted(set(uris)), + "tag": tag, + "actor": SYNC_WORKER_ACTOR, + "limit": len(set(uris)), + }, + ) + return {str(r["source_uri"]) for r in rows} + + # A reference definition whose destination is a picture's bytes, as a native # document's raw export holds it (`convert.exported_markdown` removes them). _INLINE_PICTURE = r"(?m)^ {0,3}\[[^\]\n]+\]:[ \t]* None: services.append(retirement.get_gate().track(await instances.start_cell_heartbeat(ch))) services += await _start_services(ch) supervisor = get_supervisor() - supervisor.start_all() - await stop.wait() - log.info("workers child %s stopping", os.getpid()) - retirement.get_gate().close() - embedder_calibration.stop_refresh_loop() - for task in services: - task.cancel() - await asyncio.gather(*services, return_exceptions=True) - await supervisor.stop_all(drain_timeout_s=leader.drain_timeout_s()) + # The source sync's worker copies read through the provisioned source workers; their + # channels close once the supervised work has stopped. + async with source_worker_runtime(settings.knowledge_source_worker_routes_file): + supervisor.start_all() + await stop.wait() + log.info("workers child %s stopping", os.getpid()) + retirement.get_gate().close() + embedder_calibration.stop_refresh_loop() + for task in services: + task.cancel() + await asyncio.gather(*services, return_exceptions=True) + await supervisor.stop_all(drain_timeout_s=leader.drain_timeout_s()) await _drain() retirement.get_gate().stopped() except BaseException as error: diff --git a/source_worker/README.md b/source_worker/README.md index 77aa4c40e6..97aac911cb 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -362,7 +362,24 @@ mismatched record `denied`. DNS timeouts and a credential lookup past as does an endpoint name that does not resolve or resolves to no address. Any retry needs current authority and a new session; the worker does not retry inside the failed read. The handler refuses a body or query with `400` and -`invalid`. The enrollment handler answers the same statuses for a refused grant +`invalid`. + +A refusal body is `{"status": ""}`. One read refusal adds a reason: when the +upstream answers the resource request itself with HTTP 403 (the `resources/read`, or the +mapped read's `tools/call`, inside an opened session), the worker answers `403` with +`{"status": "denied", "reason": "upstream_access"}`, the upstream's word that the +account cannot read the resource. Of the worker's answers, only that body retires a +stored copy at once. An upstream 403 to `initialize`, to tool discovery (`tools/list`), +to the GET stream or to the closing `DELETE` may come from a network policy in front of +the upstream, so it stays a plain `denied`, as does every refusal the worker makes +itself (a grant that fails to verify, an issuer, lifetime or operation it refuses, a +missing bearer, a record or binding that no longer matches, a document naming another +resource, an upstream redirect). A worker build without the reason never sends it, so +Loom never retires a copy on its denial; its source's copies stop being served once that +copy's access goes unconfirmed past Loom's stale window. A copy answering `unsupported` +follows Loom's lapsing rule with either build. + +The enrollment handler answers the same statuses for a refused grant or record, `429 overloaded` when its slots are full, and `400 invalid` for a query string, a body other than `{}`, another content type, a content or transfer encoding, or a body not sent within 5 seconds. With `enrollment` off, diff --git a/source_worker/loom_source_worker/direct_backend.py b/source_worker/loom_source_worker/direct_backend.py index 63d609737f..5ed6f65518 100644 --- a/source_worker/loom_source_worker/direct_backend.py +++ b/source_worker/loom_source_worker/direct_backend.py @@ -121,6 +121,8 @@ async def require_current() -> None: ) as client: item = await client.read(resource_id) except MCPSourceError as error: + if error.code == "forbidden": + raise ReadFailure("denied", upstream_access=True) from None raise ReadFailure(_FAILURES.get(error.code, "unsupported")) from None returned = (item.text, item.title, item.uri, item.mime_type, item.revision or "") if bearer is not None and any(bearer.token in value for value in returned): diff --git a/source_worker/loom_source_worker/http_service.py b/source_worker/loom_source_worker/http_service.py index 092cf3f543..14f34e815f 100644 --- a/source_worker/loom_source_worker/http_service.py +++ b/source_worker/loom_source_worker/http_service.py @@ -38,6 +38,15 @@ def _error(code: str, status: int) -> JSONResponse: return JSONResponse({"status": code}, status, headers=_CACHE_HEADERS) +def _read_error(error: ReadFailure) -> JSONResponse: + """A read's refusal; the upstream's own access denial names its reason, so Loom can tell + it from a refusal of the grant or the binding.""" + if error.upstream_access: + body = {"status": "denied", "reason": "upstream_access"} + return JSONResponse(body, _STATUSES["denied"], headers=_CACHE_HEADERS) + return _error(error.code, _STATUSES[error.code]) + + class _ReadRoute: def __init__(self, service: ReadService, operation: Literal["live", "check_access"]) -> None: self.service = service @@ -92,7 +101,7 @@ async def emit(message: Message) -> None: await response(scope, receive, emit) except ReadFailure as error: if not started: - await _error(error.code, _STATUSES[error.code])(scope, receive, send) + await _read_error(error)(scope, receive, send) except Exception: # noqa: BLE001 — adapter failure text can expose credential or document data if not started: await _error("unavailable", 503)(scope, receive, send) diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 50c72922b4..18784d3467 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -34,6 +34,7 @@ "config", "unsupported", "denied", + "forbidden", "reconnect", "session_ended", "unavailable", @@ -61,9 +62,13 @@ def __init__(self, code: ErrorCode) -> None: # result, a mapped read's returned id that differs, or a reply that breaks Streamable # HTTP or JSON-RPC framing is `protocol`; a reply the HTTP layer cannot frame, such as # an interrupted one, is `unavailable`. An upstream HTTP status maps in -# `_check_response`. The worker answers `schema`, `limit`, `unsupported` and `protocol` -# all as `unsupported`. A profile refused at startup is one StartupError, whatever its -# code. +# `_check_response`: the upstream's own 403 to the resource request itself (a +# `resources/read`, or the mapped read's `tools/call`) is `forbidden`, its verdict that the +# account cannot read that resource. A 403 to `initialize`, tool discovery, the GET +# stream or the closing DELETE may be a network policy in front of the upstream, so it is +# `denied`, like every refusal this worker decides. +# The worker answers `schema`, `limit`, `unsupported` and `protocol` all as +# `unsupported`. A profile refused at startup is one StartupError, whatever its code. def _error_code(error: BaseException) -> ErrorCode: if isinstance(error, (AddressResolutionError, MCPSourceError)): return error.code @@ -83,6 +88,7 @@ def _error_code(error: BaseException) -> ErrorCode: codes = {_error_code(child) for child in error.exceptions} priorities: tuple[ErrorCode, ...] = ( "denied", + "forbidden", "reconnect", "limit", "timeout", @@ -100,7 +106,7 @@ def _error_code(error: BaseException) -> ErrorCode: # Failures that also stop the closing DELETE: lost authority, or a deadline the read # already missed, which the close does not wait out again. -_CLOSE_REFUSALS: frozenset[ErrorCode] = frozenset({"denied", "reconnect", "timeout"}) +_CLOSE_REFUSALS: frozenset[ErrorCode] = frozenset({"denied", "forbidden", "reconnect", "timeout"}) # Failures of the closing DELETE that still replace a completed read's result. _AUTHORITY_REFUSALS: frozenset[ErrorCode] = frozenset({"denied", "reconnect"}) @@ -114,12 +120,24 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") +# The JSON-RPC methods that read the selected resource; only their 403 is the upstream's +# word on the account's access to it. +_READ_METHODS = frozenset({"resources/read", "tools/call"}) + + def _check_response( - method: str, response: httpx.Response, *, has_session: bool, expects_post_reply: bool + method: str, + response: httpx.Response, + *, + has_session: bool, + expects_post_reply: bool, + reads: bool = False, ) -> None: status = response.status_code if status == 401: raise MCPSourceError("reconnect") + if status == 403 and reads: + raise MCPSourceError("forbidden") if response.is_redirect or status == 403: raise MCPSourceError("denied") # A throttled or timed-out upstream is temporary, like a server error. @@ -700,24 +718,32 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials raise MCPSourceError(self.record_failure(error)) from None - def _expects_post_reply(self, method: str, body: bytes) -> bool: + def _post_request(self, method: str, body: bytes) -> str | None: + """The JSON-RPC request method a POST carries, which expects a reply; None for any + other request.""" if method != "POST": - return False + return None message = types.JSONRPCMessage.model_validate_json(body).root if not isinstance(message, types.JSONRPCRequest): - return False + return None if message.method == "tools/call" and self.guard_tool_dispatch is not None: self.guard_tool_dispatch() - return True + return message.method async def _validate_response( - self, request: httpx.Request, response: httpx.Response, *, expects_post_reply: bool + self, + request: httpx.Request, + response: httpx.Response, + *, + expects_post_reply: bool, + reads: bool, ) -> httpx.Response: _check_response( request.method, response, has_session="mcp-session-id" in request.headers, expects_post_reply=expects_post_reply, + reads=reads, ) if request.method == "DELETE": return httpx.Response(response.status_code, content=b"") @@ -808,11 +834,14 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: # A failure recorded since the check, or the deadline, stops the send. self._check_state() # A stale tool catalog refuses a tools/call here. - expects_post_reply = self._expects_post_reply(request.method, body) + rpc_method = self._post_request(request.method, body) response = await self.inner.handle_async_request(outgoing) self._check_state() validated = await self._validate_response( - outgoing, response, expects_post_reply=expects_post_reply + outgoing, + response, + expects_post_reply=rpc_method is not None, + reads=rpc_method in _READ_METHODS, ) handed_off = validated is response return validated diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index 4fecd9d209..0c5ea47c55 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -24,9 +24,12 @@ class ReadFailure(Exception): - def __init__(self, code: FailureCode) -> None: + def __init__(self, code: FailureCode, *, upstream_access: bool = False) -> None: super().__init__(code) self.code = code + # A `denied` that is the upstream's verdict on the account's access, never this + # worker's own refusal of a grant, a binding or a reply. + self.upstream_access = upstream_access @dataclass(frozen=True, repr=False) diff --git a/source_worker/qualification/test_real_tls.py b/source_worker/qualification/test_real_tls.py index 30076d7a72..3b21b6a074 100644 --- a/source_worker/qualification/test_real_tls.py +++ b/source_worker/qualification/test_real_tls.py @@ -69,6 +69,8 @@ async def _admitted( _LOOPBACK = "127.0.0.1" _ACCOUNTS = ("alice", "bob") _REFUSALS = {"expired": 401, "forbidden": 403} +# An account whose session opens as alice's and whose read the upstream refuses with 403. +_READ_REFUSED = "readrefused" def _schema(*fields: str) -> dict[str, Any]: @@ -265,6 +267,23 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: fixture.refusals.append((account, status)) await Response(status_code=status)(scope, receive, send) return + if account == _READ_REFUSED: + body = await request.body() + if request.method == "POST" and json.loads(body)["method"] == "resources/read": + fixture.refusals.append((account, 403)) + await Response(status_code=403)(scope, receive, send) + return + replayed = False + + async def replay() -> Message: + nonlocal replayed + if replayed: + return await receive() + replayed = True + return {"type": "http.request", "body": body, "more_body": False} + + await managers["alice"].handle_request(scope, replay, send) + return if account == "stall": assert request.method == "POST" assert json.loads(await request.body())["method"] == "initialize" @@ -477,6 +496,18 @@ async def test_tls_http_refusal( assert not fixture.sessions +async def test_tls_read_refusal_is_the_upstreams_word_on_access( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The session opens; the upstream's 403 to the read itself is its access refusal. + async with _service(tmp_path, monkeypatch) as fixture: + with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): + async with _client(fixture.endpoint(), _READ_REFUSED) as client: + with pytest.raises(MCPSourceError, match="^MCP source forbidden$"): + await client.read(_identity("alice")) + assert fixture.refusals == [(_READ_REFUSED, 403)] + + async def test_deadline_closes_tls_socket(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: async with _service(tmp_path, monkeypatch) as fixture: with _trust_fixture_ca(tmp_path, fixture.root, monkeypatch): diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index f04d9d5a77..bfe02ca099 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -1304,3 +1304,24 @@ async def test_resource_read_titles_the_document_with_its_uri(pin: list[str]) -> async with _client(_Source()) as client: item = await client.read(_DOCUMENT) assert item.title == item.uri == _DOCUMENT + + +@pytest.mark.parametrize( + ("method", "reads", "code"), + [ + ("POST", True, "forbidden"), + ("POST", False, "denied"), + ("GET", False, "denied"), + ("DELETE", False, "denied"), + ], +) +def test_only_the_reads_403_is_the_upstreams_access_refusal( + method: str, reads: bool, code: str +) -> None: + # A refused initialize, discovery, stream or closing DELETE says nothing of the + # account's access to the resource. + response = httpx.Response(403, request=httpx.Request(method, _ENDPOINT)) + with pytest.raises(MCPSourceError, match=f"^MCP source {code}$"): + mcp_client._check_response( + method, response, has_session=True, expects_post_reply=True, reads=reads + ) diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index cb02c47e0f..20953ba703 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -291,6 +291,10 @@ def grant(target: ReadBinding, operation: str) -> str: async def test_upstream_http_refusal_at_sdk_boundary( mode: str, phase: str, status: int, code: mcp_client.ErrorCode, monkeypatch: pytest.MonkeyPatch ) -> None: + # Only a 403 to the read itself is the upstream's word on the account's access; one to + # initialize or discovery may be a network policy in front of it. + if status == 403 and phase == "read": + code = "forbidden" reads = 0 def on_read() -> None: @@ -404,8 +408,13 @@ def client_for(token: str) -> mcp_client.MCPSourceClient: ("dns-unavailable", 503, "unavailable"), ("dns-timeout", 504, "timeout"), ("dns-prohibited", 403, "denied"), + # The upstream's own refusal of the read names its reason; one at session opening + # does not. + ("upstream-403", 403, "denied"), + ("initialize-403", 403, "denied"), # Revoked while the upstream fails: the current refusal outranks the failure. ("revoked-at-upstream-503", 403, "denied"), + ("revoked-at-upstream-403", 403, "denied"), ("revoked-at-expired-session", 403, "denied"), # One credential lookup fails during the read, the next succeeds. ("backend-blip", 503, "unavailable"), @@ -463,13 +472,20 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: if method == "initialize" and faulted and fault == "network": raise httpx.ConnectError("synthetic private network detail") refused = None - upstream = {"upstream-503": 503, "upstream-429": 429, "missing-endpoint": 404} + upstream = { + "upstream-503": 503, + "upstream-429": 429, + "initialize-403": 403, + "missing-endpoint": 404, + } if method == "initialize" and faulted and upstream_fault in upstream: assert session is None refused = upstream[upstream_fault] elif method == "resources/read": assert session - if faulted and upstream_fault == "expired-session": + if faulted and upstream_fault == "upstream-403": + refused = 403 + elif faulted and upstream_fault == "expired-session": stale_session = session refused = 404 else: @@ -545,7 +561,8 @@ def headers() -> dict[str, str]: ): failed = await worker.post(f"/v1/{route}", headers=headers()) assert failed.status_code == status - assert failed.json() == {"status": code} + named = {"reason": "upstream_access"} if fault == "upstream-403" else {} + assert failed.json() == {"status": code, **named} assert failed.headers["Cache-Control"] == "no-store" assert not successful_sessions assert sorted(queries) == ["A", "AAAA"] diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index 7292549b35..c171c13a9e 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -254,6 +254,54 @@ async def test_http_query_or_body_is_invalid_not_denied(self) -> None: self.assertEqual(reply.status_code, 400) self.assertEqual(reply.json(), {"status": "invalid"}) + async def test_http_grant_and_binding_refusals_name_no_upstream_reason(self) -> None: + # Only the upstream's own refusal names `upstream_access`: Loom retires a stored + # copy on it, never on a grant this worker cannot verify. + app = create_app(self._service(timeout=3)) + other = Ed25519PrivateKey.generate() + tokens = { + "signature": issue_read_grant( + self._live(), issuer="loom", key=other, lifetime_seconds=10 + ), + "issuer": issue_read_grant( + self._live(), issuer="other", key=self.key, lifetime_seconds=10 + ), + "operation": self._token( + ReadGrant(request_id=uuid4(), operation="check_access", binding=self.binding) + ), + } + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://worker.test" + ) as client: + replies = [ + await client.post("/v1/live", headers={"authorization": "Bearer " + token}) + for token in tokens.values() + ] + replies.append(await client.post("/v1/live")) + self.backend.return_identity = "urn:resource:other" + replies.append( + await client.post( + "/v1/live", headers={"authorization": "Bearer " + self._token(self._live())} + ) + ) + for reply in replies: + self.assertEqual(reply.status_code, 403) + self.assertEqual(reply.json(), {"status": "denied"}) + + async def test_http_upstream_denial_names_its_reason(self) -> None: + async def refused(*_args: object, **_kwargs: object) -> Document: + raise ReadFailure("denied", upstream_access=True) + + self.backend.read_exact = refused # type: ignore[method-assign] + app = create_app(self._service(timeout=3)) + auth = {"authorization": "Bearer " + self._token(self._live())} + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://worker.test" + ) as client: + reply = await client.post("/v1/live", headers=auth) + self.assertEqual(reply.status_code, 403) + self.assertEqual(reply.json(), {"status": "denied", "reason": "upstream_access"}) + async def test_http_body_backpressure_holds_the_org_slot(self) -> None: app = create_app(self._service(timeout=3)) sending = asyncio.Event() diff --git a/tests/integration/test_mcp_worker_source_history_ch.py b/tests/integration/test_mcp_worker_source_history_ch.py index 07967aa71b..0bbdd3d9a3 100644 --- a/tests/integration/test_mcp_worker_source_history_ch.py +++ b/tests/integration/test_mcp_worker_source_history_ch.py @@ -256,6 +256,7 @@ async def test_native_mirror_inventory_excludes_legacy_worker_history(registry: "name": "native", "credential_mode": "shared", "source_id": native_id, + "owner_subject": OWNER, } ] diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index 4fc1c672ff..f378a3ecbf 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -168,14 +168,14 @@ "options: -h, --help show this help message and exit --namespace NAMESPACE The collection (namespace) --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --worker-id WORKER_ID The profile's worker ID --profile-digest PROFILE_DIGEST The profile's digest --connection-id CONNECTION_ID Your worker account's ID --connection-generation CONNECTION_GENERATION That account's generation" ], "loom knowledge source worker-preview": [ - "usage: loom knowledge source worker-preview [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-id WORKER_ID --profile-digest PROFILE_DIGEST --connection-id CONNECTION_ID --mode MODE [--team-access] --selection-file SELECTION_FILE", + "usage: loom knowledge source worker-preview [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-id WORKER_ID --profile-digest PROFILE_DIGEST --connection-id CONNECTION_ID --mode MODE [--interval-seconds INTERVAL_SECONDS] [--team-access] --selection-file SELECTION_FILE", "Check a worker source's selection through your linked account; nothing is written (knowledge.source.worker_preview; experimental, answered denied until the CLI declares session protection).", - "options: -h, --help show this help message and exit --namespace NAMESPACE The collection (namespace) --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-id WORKER_ID The profile's worker ID --profile-digest PROFILE_DIGEST The profile's digest --connection-id CONNECTION_ID Your linked worker account's ID --mode MODE live, snapshot or selected_refresh; the last two answer unavailable --team-access Let other members read; answers unavailable, since no operation links a team reader --selection-file SELECTION_FILE A JSON list of the resources to read, such as [{\"type\": \"resource\", \"id\": \"...\"}]; - reads it from stdin" + "options: -h, --help show this help message and exit --namespace NAMESPACE The collection (namespace) --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-id WORKER_ID The profile's worker ID --profile-digest PROFILE_DIGEST The profile's digest --connection-id CONNECTION_ID Your linked worker account's ID --mode MODE live, snapshot or selected_refresh; the last two answer unavailable unless the server keeps worker copies --interval-seconds INTERVAL_SECONDS selected_refresh: the least seconds between a resource's copies, 300-86400 --team-access Let other members read; answers unavailable, since no operation links a team reader --selection-file SELECTION_FILE A JSON list of the resources to read, such as [{\"type\": \"resource\", \"id\": \"...\"}]; - reads it from stdin" ], "loom knowledge source worker-register": [ - "usage: loom knowledge source worker-register [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-id WORKER_ID --profile-digest PROFILE_DIGEST --connection-id CONNECTION_ID --mode MODE [--team-access] --selection-file SELECTION_FILE --preview-file PREVIEW_FILE", + "usage: loom knowledge source worker-register [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --worker-id WORKER_ID --profile-digest PROFILE_DIGEST --connection-id CONNECTION_ID --mode MODE [--interval-seconds INTERVAL_SECONDS] [--team-access] --selection-file SELECTION_FILE --preview-file PREVIEW_FILE", "Register the worker source a preview showed (knowledge.source.worker_register; experimental, answered denied until the CLI declares session protection).", - "options: -h, --help show this help message and exit --namespace NAMESPACE The collection (namespace) --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-id WORKER_ID The profile's worker ID --profile-digest PROFILE_DIGEST The profile's digest --connection-id CONNECTION_ID Your linked worker account's ID --mode MODE live, snapshot or selected_refresh; the last two answer unavailable --team-access Let other members read; answers unavailable, since no operation links a team reader --selection-file SELECTION_FILE A JSON list of the resources to read, such as [{\"type\": \"resource\", \"id\": \"...\"}]; - reads it from stdin --preview-file PREVIEW_FILE The file holding worker-preview's answer; - reads it from stdin" + "options: -h, --help show this help message and exit --namespace NAMESPACE The collection (namespace) --org ORG Default: the token's org --server-url SERVER_URL Server URL (default: $LOOM_BASE_URL, ~/.loom/config.json url, http://localhost:7777) --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME The source's name in the namespace --worker-id WORKER_ID The profile's worker ID --profile-digest PROFILE_DIGEST The profile's digest --connection-id CONNECTION_ID Your linked worker account's ID --mode MODE live, snapshot or selected_refresh; the last two answer unavailable unless the server keeps worker copies --interval-seconds INTERVAL_SECONDS selected_refresh: the least seconds between a resource's copies, 300-86400 --team-access Let other members read; answers unavailable, since no operation links a team reader --selection-file SELECTION_FILE A JSON list of the resources to read, such as [{\"type\": \"resource\", \"id\": \"...\"}]; - reads it from stdin --preview-file PREVIEW_FILE The file holding worker-preview's answer; - reads it from stdin" ], "loom knowledge migrate-originals": [ "usage: loom knowledge migrate-originals [-h] [--org ORG] [--namespace NAMESPACE] [--dry-run]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 870843e6e4..f3edf95e22 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -4996,6 +4996,7 @@ "profile_digest", "connection_id", "mode", + "interval_seconds", "team_access", "selection_file" ] @@ -5151,7 +5152,22 @@ "nargs": null, "type": null, "required": true, - "help": "live, snapshot or selected_refresh; the last two answer unavailable", + "help": "live, snapshot or selected_refresh; the last two answer unavailable unless the server keeps worker copies", + "metavar": null + }, + { + "option_strings": [ + "--interval-seconds" + ], + "dest": "interval_seconds", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": "builtins:int", + "required": false, + "help": "selected_refresh: the least seconds between a resource's copies, 300-86400", "metavar": null }, { @@ -5217,6 +5233,7 @@ "profile_digest", "connection_id", "mode", + "interval_seconds", "team_access", "selection_file", "preview_file" @@ -5373,7 +5390,22 @@ "nargs": null, "type": null, "required": true, - "help": "live, snapshot or selected_refresh; the last two answer unavailable", + "help": "live, snapshot or selected_refresh; the last two answer unavailable unless the server keeps worker copies", + "metavar": null + }, + { + "option_strings": [ + "--interval-seconds" + ], + "dest": "interval_seconds", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": "builtins:int", + "required": false, + "help": "selected_refresh: the least seconds between a resource's copies, 300-86400", "metavar": null }, { diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 3584d7bf41..81347c5cbb 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -679,6 +679,7 @@ "knowledge_source_sync_interval_seconds": 900, "knowledge_source_sync_max_file_bytes": 67108864, "knowledge_source_sync_max_pass_seconds": 600, + "knowledge_source_worker_copies_enabled": false, "knowledge_source_worker_frame_timeout_s": 1.0, "knowledge_source_worker_live_timeout_s": 8.0, "knowledge_source_worker_publication_timeout_s": 2.0, diff --git a/tests/unit/test_assistant_mirror_boundary.py b/tests/unit/test_assistant_mirror_boundary.py index 3137b66113..bd1136c074 100644 --- a/tests/unit/test_assistant_mirror_boundary.py +++ b/tests/unit/test_assistant_mirror_boundary.py @@ -52,7 +52,7 @@ async def test_an_answer_without_admission_never_discovers_a_mirror( async def authorized(*args: Any) -> None: seen.append("authorized") - async def active(*args: Any) -> list[dict[str, Any]]: + async def active(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: seen.append("discovered") return [{"namespace": "notes", "source_id": "source"}] @@ -92,7 +92,7 @@ def test_answer_admission_survives_signature_verification(admitted: bool) -> Non async def test_positive_admission_still_requires_the_fixed_caller_promise( monkeypatch: pytest.MonkeyPatch, ) -> None: - async def unexpected(*args: Any) -> Any: + async def unexpected(*args: Any, **kwargs: Any) -> Any: pytest.fail("an undeclared answer queried mirrored registrations") monkeypatch.setattr(settings, "auth_required", True) @@ -127,7 +127,7 @@ async def test_an_admitted_protected_answer_keeps_the_checked_mirror_path( async def authorized(*args: Any) -> None: seen.append("authorized") - async def active(*args: Any) -> list[dict[str, str]]: + async def active(*args: Any, **kwargs: Any) -> list[dict[str, str]]: seen.append("discovered") return [{"namespace": "notes", "source_id": "source"}] diff --git a/tests/unit/test_cli_knowledge_source_worker.py b/tests/unit/test_cli_knowledge_source_worker.py index ff39c1da57..e5819974e9 100644 --- a/tests/unit/test_cli_knowledge_source_worker.py +++ b/tests/unit/test_cli_knowledge_source_worker.py @@ -157,6 +157,19 @@ def _source_argv(command: str, selection: str) -> list[str]: ] +def test_a_selected_refresh_preview_sends_its_interval(tmp_path: Path, posted: Server) -> None: + argv = _source_argv("worker-preview", _selection(tmp_path)) + argv[argv.index("live")] = "selected_refresh" + assert _run([*argv, "--interval-seconds", "3600"]) == 0 + body = posted[0]["body"] + assert body["mode"] == "selected_refresh" and body["interval_seconds"] == 3600 + + +def test_no_interval_is_sent_unless_given(tmp_path: Path, posted: Server) -> None: + assert _run(_source_argv("worker-preview", _selection(tmp_path))) == 0 + assert "interval_seconds" not in posted[0]["body"] + + def test_preview_sends_the_selection_and_waits_out_the_proof( tmp_path: Path, posted: Server ) -> None: diff --git a/tests/unit/test_connected_account_cleanup.py b/tests/unit/test_connected_account_cleanup.py index a6fb453342..73d4006936 100644 --- a/tests/unit/test_connected_account_cleanup.py +++ b/tests/unit/test_connected_account_cleanup.py @@ -214,6 +214,7 @@ def __init__(self, monkeypatch, world: _World, rows: list[tuple[str, str, str, i monkeypatch.setattr(connections.source_store, "connected_owner_namespaces", self.none) monkeypatch.setattr(connections.source_store, "worker_owner_namespaces", self.namespaces) monkeypatch.setattr(connections.source_store, "erase_worker_owner", self.erase) + monkeypatch.setattr(connections.source_store, "worker_owner_sources", self.sources) monkeypatch.setattr(erasure_accounts, "worker_source_residue", self.residue) monkeypatch.setattr(connections.aliases, "verified_spellings", self.own_spelling) monkeypatch.setattr(connections.revocation, "cutoffs", self.outright) @@ -238,6 +239,16 @@ async def namespaces(self, org, owner, *, before): self.late = [] return found + async def sources(self, org, namespace, owner, *, before): + # One registration per matching row, named after its creation stamp. + return [ + KnowledgeSource( + org=org, namespace=namespace, name=f"w{r[3]}", kind="mcp", source_id=str(r[3]) + ) + for r in self._matching(org, owner, before) + if r[1] == namespace + ] + async def erase(self, org, namespace, owner, *, before): assert self.world.depth > 0, "a worker row was erased outside its source lease" gone = [r for r in self._matching(org, owner, before) if r[1] == namespace] @@ -273,6 +284,11 @@ async def test_owner_erasure_erases_worker_rows_after_the_revocations(monkeypatc first_worker = world.events.index(("worker", "elsewhere")) last_erase = max(i for i, event in enumerate(world.events) if event == ("erase", "gdrive")) assert provider < first_worker < last_erase + # Each erased registration's copies are queued for retirement before its rows go. + for namespace, stamp in (("elsewhere", 2), ("shared-space", 1)): + queued = world.events.index(("retire", str(stamp))) + assert queued < world.events.index(("worker", namespace)) + assert ("retire", "3") not in world.events @pytest.mark.asyncio diff --git a/tests/unit/test_knowledge_source_retirements.py b/tests/unit/test_knowledge_source_retirements.py index 5511e9f3db..57d1d461fa 100644 --- a/tests/unit/test_knowledge_source_retirements.py +++ b/tests/unit/test_knowledge_source_retirements.py @@ -98,17 +98,26 @@ def _seed_worker_row(fake: Any, legacy_only: bool) -> tuple[Any, Any]: return native_key, worker_key +def _record_queue(fake: Any, monkeypatch: pytest.MonkeyPatch) -> list[str]: + """`_queue_retirement` as a recorder that sees the row still active and queues it.""" + queued: list[str] = [] + + async def enqueue(src: Any) -> bool: + assert fake.rows[(src.org, src.namespace, src.name)].active + queued.append(src.source_id) + return True + + monkeypatch.setattr(sources, "_queue_retirement", enqueue) + return queued + + @pytest.mark.parametrize("legacy_only", [False, True]) def test_namespace_retirement_retires_a_worker_row_in_place( fake: Any, monkeypatch: pytest.MonkeyPatch, legacy_only: bool ) -> None: native_key, worker_key = _seed_worker_row(fake, legacy_only) before = fake.rows.copy() - - async def forbidden(*args: Any, **kwargs: Any) -> bool: - raise AssertionError("native retirement cannot queue worker cleanup") - - monkeypatch.setattr(sources, "_queue_retirement", forbidden) + queued = _record_queue(fake, monkeypatch) push_retired: list[str] = [] async def retire_push(src: Any) -> None: @@ -125,6 +134,8 @@ async def retire_push(src: Any) -> None: assert not worker.credential_enc and not worker.secret_enc assert before[worker_key].credential_enc assert worker.worker_history == before[worker_key].worker_history + # Its copies in the mirror are queued for retirement; the namespace source has none. + assert queued == [worker.source_id] and worker.pending_delete def test_namespace_retirement_clears_a_crawl_approval_on_a_worker_marked_row( @@ -137,11 +148,7 @@ def test_namespace_retirement_clears_a_crawl_approval_on_a_worker_marked_row( approval_enc="sealed-approval", registrant_subject="admin", ) - - async def forbidden(*args: Any, **kwargs: Any) -> bool: - raise AssertionError("native retirement cannot queue worker cleanup") - - monkeypatch.setattr(sources, "_queue_retirement", forbidden) + _record_queue(fake, monkeypatch) asyncio.run(sources.deactivate_namespace_sources(ORG, NS)) worker = fake.rows[worker_key] assert not worker.active and not worker.approval_enc and not worker.registrant_subject @@ -163,7 +170,7 @@ async def role(_org: str, _namespace: str, wanted: Role) -> bool: return admin or wanted == Role.WRITER async def forbidden(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("a worker source queues no cleanup and counts no documents") + raise AssertionError("a worker source counts no documents") caller_auth = object() monkeypatch.setattr(sources.authz, "row_in_scope", role) @@ -171,7 +178,6 @@ async def forbidden(*args: Any, **kwargs: Any) -> Any: monkeypatch.setattr(connected_sources, "current_auth", lambda: caller_auth) monkeypatch.setattr(connected_sources.request_work, "mark_mirrored", lambda: True) monkeypatch.setattr(connected_accounts, "own_subject", AsyncMock(return_value=(ORG, caller))) - monkeypatch.setattr(sources, "_queue_retirement", forbidden) monkeypatch.setattr(store, "count_documents", forbidden) return worker_key, before @@ -182,6 +188,7 @@ def test_remove_retires_a_worker_row_in_place( fake: Any, monkeypatch: pytest.MonkeyPatch, legacy_only: bool, admin: bool, caller: str ) -> None: worker_key, before = _remove_worker(fake, monkeypatch, legacy_only, admin=admin, caller=caller) + queued = _record_queue(fake, monkeypatch) name = worker_key[2] out = asyncio.run( sources.handle_knowledge_source_remove( @@ -190,22 +197,26 @@ def test_remove_retires_a_worker_row_in_place( ) ) ) + # The copies are queued, uncounted: the delete request is the queue's answer. assert out.documents_pending == 0 worker = fake.rows[worker_key] - assert not worker.active and not worker.pending_delete + assert queued == [worker.source_id] + assert not worker.active and worker.pending_delete assert not worker.credential_enc and not worker.secret_enc assert worker.worker_history == before[worker_key].worker_history -def test_removing_a_retired_worker_row_keeps_a_delete_request_already_on_it( - fake: Any, monkeypatch: pytest.MonkeyPatch +@pytest.mark.parametrize("mirror", [True, False], ids=["queued", "no-mirror"]) +def test_removing_a_retired_worker_row_answers_the_queue( + fake: Any, monkeypatch: pytest.MonkeyPatch, mirror: bool ) -> None: - # A later build's cleanup request on the row stays; this build queues none. + # A retired row's copies are queued again; with no mirror there is nothing to retire. worker_key, _ = _remove_worker(fake, monkeypatch, False, admin=True, caller="admin") name = worker_key[2] fake.rows[worker_key] = dataclasses.replace( fake.rows[worker_key], active=False, pending_delete=True ) + monkeypatch.setattr(sources, "_queue_retirement", AsyncMock(return_value=mirror)) out = asyncio.run( sources.handle_knowledge_source_remove( KnowledgeSourceRemoveInput( @@ -214,7 +225,7 @@ def test_removing_a_retired_worker_row_keeps_a_delete_request_already_on_it( ) ) assert out.documents_pending == 0 - assert fake.rows[worker_key].pending_delete and not fake.rows[worker_key].active + assert fake.rows[worker_key].pending_delete is mirror and not fake.rows[worker_key].active @pytest.mark.parametrize("standing", ["expired", "lost"]) @@ -391,18 +402,23 @@ def test_replacement_preserves_old_cleanup_and_new_documents(work: Any) -> None: assert work.identities == [((cleanup.WORKER,), {"org": old.org, "namespace": old.mirror})] -@pytest.mark.parametrize("marked_at", ["never", "start", "finish"]) -def test_pending_mirror_retirement_rechecks_worker_history( - work: Any, monkeypatch: pytest.MonkeyPatch, marked_at: str +@pytest.mark.parametrize("active_at", ["never", "start", "finish"]) +def test_pending_mirror_retirement_rechecks_an_active_worker_row( + work: Any, monkeypatch: pytest.MonkeyPatch, active_at: str ) -> None: + # A retired worker row's copies go like a native row's; an active registration of the + # same id stops the retirement wherever it is found. item = _item() _put(work, item, "private-address") - native = dataclasses.replace(item.source(), active=False, pending_delete=True) - worker = dataclasses.replace( - native, worker_history=WorkerSourceHistory("mcp", "gdrive", "{}", "[]", "{}") + retired = dataclasses.replace( + item.source(), + active=False, + pending_delete=True, + worker_history=WorkerSourceHistory("mcp", "gdrive", "{}", "[]", "{}"), ) + active = dataclasses.replace(retired, active=True) rereads = iter( - [worker if marked_at == "start" else native, worker if marked_at == "finish" else native] + [active if active_at == "start" else retired, active if active_at == "finish" else retired] ) key = (item.org, item.namespace, item.name) @@ -414,9 +430,9 @@ async def latest(*_args: Any) -> Any: monkeypatch.setattr(cleanup.store, "latest_source", latest) asyncio.run(cleanup.run_once()) - assert len(work.retired) == (0 if marked_at == "start" else 1) - assert work.pending == ({item.source_id} if marked_at != "never" else set()) - assert work.current[key].pending_delete is (marked_at != "never") + assert len(work.retired) == (0 if active_at == "start" else 1) + assert work.pending == ({item.source_id} if active_at != "never" else set()) + assert work.current[key].pending_delete is (active_at != "never") def test_crash_before_inactivation_never_deletes_active_source(work: Any) -> None: diff --git a/tests/unit/test_mcp_worker_read.py b/tests/unit/test_mcp_worker_read.py index e9a361e5dd..c87cce7572 100644 --- a/tests/unit/test_mcp_worker_read.py +++ b/tests/unit/test_mcp_worker_read.py @@ -486,6 +486,76 @@ def stored(): task.cancel() await asyncio.gather(*again, return_exceptions=True) + async def test_a_copy_reads_live_content_in_its_own_share(self) -> None: + reading = await self._channel().copy(self.scope, require_current=self._authorized) + self.assertEqual(reading.document.text, "alpha") + transport, arrived, paths = self._blocking() + channel = self._channel(transport, max_inflight=1) + + def copy(): + return channel.copy(self.scope, require_current=self._authorized) + + # One copy in flight fills the share: the sync sends no second. + held = [asyncio.create_task(copy())] + await self._until(arrived, paths, 1) + try: + with self.assertRaisesRegex(WorkerReadRefused, "^overloaded$"): + await copy() + # Copies never take a live read's slot. + live = asyncio.create_task(channel.run(self.scope, require_current=self._authorized)) + await self._until(arrived, paths, 2) + live.cancel() + await asyncio.gather(live, return_exceptions=True) + finally: + for task in held: + task.cancel() + await asyncio.gather(*held, return_exceptions=True) + self.assertEqual(paths, ["/v1/live"] * 2) + + async def test_a_copy_checks_its_scope_once_after_the_reply(self) -> None: + # The caller resolved the scope just before; the channel checks it again only + # after the worker's reply. + checks = 0 + + async def changed() -> WorkerReadScope: + nonlocal checks + checks += 1 + return replace(self.scope, approval_generation=5) + + sent = Mock(side_effect=self._wire_fixture) + channel = self._channel(httpx.MockTransport(sent)) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await channel.copy(self.scope, require_current=changed) + sent.assert_called_once() + self.assertEqual(checks, 1) + + async def test_only_the_workers_named_upstream_denial_is_marked(self) -> None: + marker = {"status": "denied", "reason": "upstream_access"} + as_json = {"Content-Type": "application/json"} + cases = [ + (403, as_json, marker, True), + (403, as_json, {"status": "denied"}, False), + (403, {}, None, False), + (403, as_json, marker | {"extra": 1}, False), + (403, as_json, marker | {"reason": "x" * 300}, False), + (403, {"Content-Type": "text/plain"}, marker, False), + (200, {"Content-Type": "text/html"}, {}, False), + ] + for status, headers, body, named in cases: + with self.subTest(status=status, body=body, named=named): + + def answer( + request: httpx.Request, status=status, headers=headers, body=body + ) -> httpx.Response: + content = b"" if body is None else json.dumps(body).encode() + return httpx.Response(status, headers=headers, stream=httpx.ByteStream(content)) + + channel = self._channel(httpx.MockTransport(answer)) + with self.assertRaises(WorkerReadRefused) as refused: + await channel.copy(self.scope, require_current=self._authorized) + self.assertEqual(refused.exception.reason, "denied") + self.assertIs(refused.exception.upstream_access, named) + async def test_a_failed_check_frees_its_slot(self) -> None: for status, reason in ((503, "unavailable"), (403, "denied")): with self.subTest(reason=reason): diff --git a/tests/unit/test_mcp_worker_setup_register.py b/tests/unit/test_mcp_worker_setup_register.py index 89f4b9b1a8..cdfcb1239b 100644 --- a/tests/unit/test_mcp_worker_setup_register.py +++ b/tests/unit/test_mcp_worker_setup_register.py @@ -56,7 +56,12 @@ ) from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, KnowledgeSource from server.knowledge.store import sources as source_store -from server.knowledge.store.pg_mcp_worker_approvals import LIVE, SNAPSHOT, WorkerApproval +from server.knowledge.store.pg_mcp_worker_approvals import ( + LIVE, + REFRESH, + SNAPSHOT, + WorkerApproval, +) from server.knowledge.store.pg_mcp_worker_enrollment import AccountState from server.knowledge.store.pg_worker_row_lock import WorkerRowBusy from server.operations.base import Role @@ -366,13 +371,19 @@ async def test_a_refused_caller_is_denied_before_anything_else_is_read(setup, op ) +_STORED_MODES = [ + {"mode": "snapshot"}, + {"mode": "selected_refresh", "interval_seconds": 3600}, +] + + @pytest.mark.asyncio @pytest.mark.parametrize( - "fields", - [{"mode": "snapshot"}, {"mode": "selected_refresh"}, {"team_access": True}], - ids=["snapshot", "selected_refresh", "team"], + "fields", [*_STORED_MODES, {"team_access": True}], ids=["snapshot", "selected_refresh", "team"] ) -async def test_only_an_owner_only_live_source_is_served(setup, fields) -> None: +async def test_without_worker_copies_only_an_owner_only_live_source_is_served( + setup, fields +) -> None: previewed = await setup.preview() setup.channel.checked.clear() assert (await setup.preview(**fields)).status == "unavailable" @@ -380,6 +391,36 @@ async def test_only_an_owner_only_live_source_is_served(setup, fields) -> None: assert setup.caller_checks and not setup.channel.checked and not setup.inserted +@pytest.mark.asyncio +@pytest.mark.parametrize("fields", _STORED_MODES, ids=["snapshot", "selected_refresh"]) +async def test_with_worker_copies_an_owner_only_stored_source_registers( + setup, monkeypatch, fields +) -> None: + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", True) + setup.routes.permits.side_effect = lambda worker, org, digest, mode, team: not team + setup.approval = WorkerApproval(7, LIVE | SNAPSHOT | REFRESH, False, True) + previewed = await setup.preview(**fields) + assert previewed.status == "ok" + assert (previewed.reader_policy, previewed.stores_copy) == ("owner_only", True) + assert "owner alone" in previewed.disclosure + assert (await setup.register(previewed, **fields)).status == "ok" + config, _ = decode_worker_source(source_store._source(setup.inserted[0])) + assert (config.mode, config.reader_policy) == (fields["mode"], "owner_only") + assert config.interval_seconds == fields.get("interval_seconds") + # Team access stays unserved. + assert (await setup.preview(team_access=True, **fields)).status == "unavailable" + + +@pytest.mark.parametrize( + "fields", + [{"mode": "selected_refresh"}, {"mode": "snapshot", "interval_seconds": 3600}], + ids=["refresh-without", "snapshot-with"], +) +def test_an_interval_comes_with_selected_refresh_alone(fields) -> None: + with pytest.raises(pydantic.ValidationError): + WorkerPreviewInput(**_body(**fields)) + + @pytest.mark.asyncio async def test_without_routes_a_writer_hears_unavailable(setup) -> None: previewed = await setup.preview() @@ -649,6 +690,7 @@ def test_no_wire_field_names_the_owner_or_the_source_id() -> None: "profile_digest", "connection_id", "mode", + "interval_seconds", "team_access", "selection", } @@ -1042,3 +1084,16 @@ def test_the_preview_client_timeout_outlasts_the_largest_proof() -> None: # A full selection's proof runs inline, so an SDK must wait for all of it. op = OPERATIONS_BY_NAME["knowledge.source.worker_preview"] assert op.client_timeout_s >= proof_seconds(MAX_SETUP_RESOURCES) + + +def test_the_generated_references_carry_the_whole_mode_description() -> None: + from pathlib import Path + + root = Path(__file__).resolve().parents[2] + described = WorkerPreviewInput.model_fields["mode"].description + assert described and "unavailable" in described + for generated in ( + "sdk/typescript/src/generated/ops.ts", + "docs/reference/operations/knowledge.md", + ): + assert described in (root / generated).read_text(), generated diff --git a/tests/unit/test_source_access_plan.py b/tests/unit/test_source_access_plan.py index 3c162fc41b..883a5057e1 100644 --- a/tests/unit/test_source_access_plan.py +++ b/tests/unit/test_source_access_plan.py @@ -105,7 +105,9 @@ async def answer(statement, *, params): async def test_a_source_marked_before_discovery_is_never_admitted(world, monkeypatch): ch = _registry({"now": True}) - monkeypatch.setattr(app.store, "active_sources", lambda org, ns: active_sources(org, ns, ch=ch)) + monkeypatch.setattr( + app.store, "active_sources", lambda org, ns, **kw: active_sources(org, ns, ch=ch, **kw) + ) plan = await app.prepare("acme", ["docs"]) assert await plan.check([candidate()], chunks=True) == [] assert not plan.marked @@ -114,7 +116,9 @@ async def test_a_source_marked_before_discovery_is_never_admitted(world, monkeyp async def test_a_source_marked_after_discovery_is_refused_at_the_next_check(world, monkeypatch): marked = {"now": False} ch = _registry(marked) - monkeypatch.setattr(app.store, "active_sources", lambda org, ns: active_sources(org, ns, ch=ch)) + monkeypatch.setattr( + app.store, "active_sources", lambda org, ns, **kw: active_sources(org, ns, ch=ch, **kw) + ) plan = await app.prepare("acme", ["docs"]) assert len(await plan.check([candidate()], chunks=True)) == 1 marked["now"] = True @@ -563,7 +567,7 @@ async def test_overlapping_checks_cannot_restore_a_source_after_observing_its_re started, release = asyncio.Event(), asyncio.Event() calls = 0 - async def active_sources(*_args): + async def active_sources(*_args, **_kwargs): nonlocal calls calls += 1 if calls == 1: diff --git a/tests/unit/test_worker_cell_observation.py b/tests/unit/test_worker_cell_observation.py index 9c37f211f5..e1c26cd1cc 100644 --- a/tests/unit/test_worker_cell_observation.py +++ b/tests/unit/test_worker_cell_observation.py @@ -229,3 +229,55 @@ async def test_worker_cleanup_preserves_first_failure_and_attempts_both_closings for task in value.tasks + value.producers: task.cancel() await asyncio.gather(*value.tasks, *value.producers, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_worker_child_opens_the_source_worker_directory_around_its_work( + worker_boot, monkeypatch +): + from contextlib import asynccontextmanager + + from server.knowledge.app import mcp_worker_runtime + + value = worker_boot + routes = SimpleNamespace() + + @asynccontextmanager + async def opened(loaded): + assert loaded == ("route",) + value.events.append("routes opened") + try: + yield routes + finally: + value.events.append("routes closed") + + monkeypatch.setattr(settings, "cell", "") + monkeypatch.setattr(settings, "knowledge_source_worker_routes_file", "/routes.json") + monkeypatch.setattr(mcp_worker_runtime.pg, "enabled", lambda: True) + monkeypatch.setattr(mcp_worker_runtime, "load_worker_routes", lambda path: ("route",)) + monkeypatch.setattr(mcp_worker_runtime, "open_worker_routes", opened) + monkeypatch.setattr(mcp_worker_runtime, "live_directory", lambda r: ("directory", r)) + seen = [] + start = worker_main.get_supervisor().start_all + + class Supervisor: + def start_all(self): + seen.append(mcp_worker_runtime.current_directory()) + start() + + async def stop_all(self, **_kwargs): + value.events.append("supervisor stopped") + + monkeypatch.setattr(worker_main, "get_supervisor", Supervisor) + try: + async with asyncio.timeout(1.0): + await worker_main._serve(-1, -1) + # The sync's turns see the directory; its channels close after the work stops. + assert seen == [("directory", routes)] + assert value.events.index("routes opened") < value.events.index("supervisor") + assert value.events.index("supervisor stopped") < value.events.index("routes closed") + assert mcp_worker_runtime.current_directory() is None + finally: + for task in value.tasks + value.producers: + task.cancel() + await asyncio.gather(*value.tasks, *value.producers, return_exceptions=True) diff --git a/tests/unit/test_worker_copy_store_sql.py b/tests/unit/test_worker_copy_store_sql.py new file mode 100644 index 0000000000..18c65210ce --- /dev/null +++ b/tests/unit/test_worker_copy_store_sql.py @@ -0,0 +1,122 @@ +"""The registry and document reads a worker source's copy needs, run on clickhouse-local +against schema.sql: every selected copy past a page of documents, and only copy-mode +worker rows in the mirror read gate's registration read.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from uuid import UUID + +import pytest + +from server.knowledge.domain.mcp_identity import ResourceIdentity +from server.knowledge.domain.mcp_worker_source import WorkerSourceConfig, encode_worker_source +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR +from server.knowledge.store import source_access +from server.knowledge.store import sources as store +from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl + +pytestmark = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse not installed") + +_MIRROR = "acl-" + "1" * 24 +_TAG = "source-id:" + str(UUID(int=5)) + + +def _seed_documents(ch: KeptCH, count: int) -> list[str]: + """`count` live copies under the tag, then one another writer holds and one superseded.""" + asyncio.run( + ch.execute( + "INSERT INTO loom.documents (org, namespace, source_uri, content, tags, version, " + "actor) SELECT 'org', {mirror:String}, concat('copy-', leftPad(toString(number), " + "4, '0')), 'text', [{tag:String}], 1, {actor:String} FROM numbers({n:UInt32})", + {"mirror": _MIRROR, "tag": _TAG, "actor": SYNC_WORKER_ACTOR, "n": count}, + ) + ) + asyncio.run( + ch.execute( + "INSERT INTO loom.documents (org, namespace, source_uri, content, tags, version, " + "actor, superseded_at) VALUES ('org', {mirror:String}, 'other', 't', " + "[{tag:String}], 1, 'someone', NULL), ('org', {mirror:String}, 'gone', 't', " + "[{tag:String}], 1, {actor:String}, now())", + {"mirror": _MIRROR, "tag": _TAG, "actor": SYNC_WORKER_ACTOR}, + ) + ) + return [f"copy-{n:04d}" for n in range(count)] + + +def test_every_selected_copy_is_found_past_a_page_of_documents(tmp_path: Path) -> None: + ch = KeptCH(tmp_path, ddl("documents")) + uris = _seed_documents(ch, store.DOCUMENTS_LIMIT + 41) + asked = [*uris[1:], "never-written", "other", "gone"] + found = asyncio.run(store.copies_at("org", _MIRROR, _TAG, asked, ch=ch)) + assert found == set(uris[1:]) + assert asyncio.run(store.copies_at("org", _MIRROR, _TAG, [], ch=ch)) == set() + + +def _worker_row(name: str, source_id: int, **fields: object) -> dict[str, object]: + values: dict[str, object] = { + "version": 1, + "worker_id": UUID(int=3), + "profile_digest": "b" * 64, + "approval_generation": 7, + "owner_connection_id": UUID(int=4), + "owner_connection_generation": 9, + "selection_generation": 1, + "mode": "snapshot", + "reader_policy": "owner_only", + } + row = encode_worker_source( + org="org", + namespace="team", + name=name, + source_id=UUID(int=source_id), + owner="alice", + config=WorkerSourceConfig(**(values | fields)), + selection=(ResourceIdentity(type="resource", id="doc:one"),), + ) + history = row.worker_history + assert history is not None + return { + "org": "org", + "namespace": "team", + "name": name, + "source_id": row.source_id, + "kind": "", + "source_kind": "mcp", + "credential_mode": "worker", + "access": "mirrored", + "owner_subject": "alice", + "connection_id": row.connection_id, + "config_json": history.config_json, + "items_json": history.items_json, + } + + +def test_the_gate_reads_only_owner_only_copy_mode_worker_rows(tmp_path: Path) -> None: + ch = KeptCH(tmp_path, ddl("knowledge_sources")) + rows = [ + _worker_row("live", 11, mode="live"), + _worker_row("snap", 12), + _worker_row("refresh", 13, mode="selected_refresh", interval_seconds=600), + _worker_row("team", 14, reader_policy="current_team_access"), + {**_worker_row("damaged", 15), "config_json": json.dumps({"unknown": 1})}, + { + "org": "org", + "namespace": "team", + "name": "native", + "source_id": str(UUID(int=16)), + "kind": "gdrive", + "access": "mirrored", + }, + ] + asyncio.run(ch.insert("loom.knowledge_sources", rows)) + names = [r["name"] for r in asyncio.run(source_access.active_sources("org", ["team"], ch=ch))] + assert names == ["native"] + found = asyncio.run(source_access.active_sources("org", ["team"], workers=True, ch=ch)) + assert [(r["name"], r["credential_mode"]) for r in found] == [ + ("native", "shared"), + ("refresh", "worker"), + ("snap", "worker"), + ] diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py new file mode 100644 index 0000000000..566d70b95d --- /dev/null +++ b/tests/unit/test_worker_source_copies.py @@ -0,0 +1,1165 @@ +"""An owner-only worker source's private copy: the sync turn that copies and checks each +selected resource, the mirror read gate that serves the copies to their owner alone, and +the retirement every removal path queues.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import hashlib +import time +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock +from uuid import UUID, uuid4 + +import pytest + +from server.auth.jwt import AuthInfo +from server.code.app.index.pass_budget import PassBudget +from server.core.errors import ValidationError +from server.knowledge.app import ( + connected_accounts, + mcp_worker_runtime, + source_access, + source_sync, + source_sync_worker, +) +from server.knowledge.app.mcp_worker_authority import CurrentConnection +from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory +from server.knowledge.app.mcp_worker_read import ( + WorkerAccess, + WorkerDocument, + WorkerReading, + WorkerReadRefused, +) +from server.knowledge.domain.access_list import AccessList +from server.knowledge.domain.mcp_identity import ResourceIdentity, resource_digest, resource_uri +from server.knowledge.domain.mcp_worker_source import ( + ReaderConnection, + WorkerSourceConfig, + encode_worker_source, + worker_copied, +) +from server.operations.base import Role +from server.settings import settings + +_WORKER = UUID(int=3) +_CONNECTION = UUID(int=4) +_SOURCE = UUID(int=5) +_DIGEST = "b" * 64 +_MIRROR = "acl-" + "1" * 24 +_IDS = ("doc:one", "doc:two") + + +def _config(**fields: Any) -> WorkerSourceConfig: + values: dict[str, Any] = { + "version": 1, + "worker_id": _WORKER, + "profile_digest": _DIGEST, + "approval_generation": 7, + "owner_connection_id": _CONNECTION, + "owner_connection_generation": 9, + "selection_generation": 1, + "mode": "snapshot", + "reader_policy": "owner_only", + } + return WorkerSourceConfig(**(values | fields)) + + +def _source(**fields: Any) -> Any: + row = encode_worker_source( + org="org", + namespace="team", + name="handbook", + source_id=_SOURCE, + owner="alice", + config=_config(**fields), + selection=tuple(ResourceIdentity(type="resource", id=i) for i in _IDS), + ) + return dataclasses.replace(row, mirror=_MIRROR) + + +def _uri(resource: str) -> str: + return resource_uri(str(_SOURCE), resource) + + +def _sha(text: str) -> str: + return hashlib.sha256(text.encode()).hexdigest() + + +@pytest.fixture(autouse=True) +def _copies_on(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", True) + monkeypatch.setattr(settings, "knowledge_source_acl_stale_seconds", 3600) + monkeypatch.setattr(settings, "knowledge_source_sync_interval_seconds", 900) + + +def test_only_an_active_owner_only_stored_registration_is_copied(monkeypatch) -> None: + assert worker_copied(_source()) + assert worker_copied(_source(mode="selected_refresh", interval_seconds=600)) + assert not worker_copied(_source(mode="live")) + assert not worker_copied(_source(paused=True)) + assert not worker_copied(_source(reader_policy="current_team_access")) + assert not worker_copied(dataclasses.replace(_source(), active=False)) + assert not worker_copied(dataclasses.replace(_source(), pending_delete=True)) + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", False) + assert not worker_copied(_source()) + + +def test_the_sync_routes_a_copied_worker_source_to_its_mirror_turn(monkeypatch) -> None: + src = _source() + assert source_sync._mirrored(src) + assert source_sync._turn_of(src) is source_sync_worker.turn + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", False) + assert not source_sync._mirrored(src) + + +class _Worker: + """A worker channel: each resource's text, or the refusal it answers.""" + + def __init__(self) -> None: + self.texts = {i: f"text of {i}" for i in _IDS} + # Each resource's refusal and the worker's HTTP status for it (None: Loom's own). + self.refusals: dict[str, str] = {} + # Whether a `denied` carries the worker's upstream-denial reason (by default it does). + self.upstream: dict[str, bool] = {} + self.calls: list[tuple[str, str]] = [] + + async def _answer(self, op: str, scope: Any, require_current: Any) -> str: + assert await require_current() == scope + assert (scope.requester, scope.source_id) == ("alice", _SOURCE) + self.calls.append((op, scope.resource_id)) + if scope.resource_id in self.refusals: + reason = self.refusals[scope.resource_id] + named = self.upstream.get(scope.resource_id, True) + raise WorkerReadRefused(reason, upstream_access=named) + return self.texts[scope.resource_id] + + async def copy(self, scope: Any, *, require_current: Any) -> WorkerReading: + text = await self._answer("copy", scope, require_current) + document = WorkerDocument( + resource_id=scope.resource_id, + title=f"title {scope.resource_id}", + text=text, + revision="r1", + source_link=None, + mime_type="text/plain", + ) + return WorkerReading( + status="ok", + request_id=uuid4(), + fetched_at=int(time.time()), + content_sha256=_sha(text), + document=document, + ) + + async def check_access(self, scope: Any, *, require_current: Any) -> WorkerAccess: + text = await self._answer("check", scope, require_current) + return WorkerAccess( + status="ok", + request_id=uuid4(), + fetched_at=int(time.time()), + content_sha256=_sha(text), + document=None, + ) + + +class _World: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.src = _source() + self.worker = _Worker() + self.stored: set[str] = set() + self.written: list[dict[str, Any]] = [] + self.retired: list[str] = [] + self.listings: list[datetime] = [] + self.role: Role | None = Role.WRITER + self.approval: int | None = 7 + self.account_active = True + self.permitted = True + self.ended: list[Any] = [] + self.source_reads = 0 + self.directory: LiveSourceDirectory | None = LiveSourceDirectory( + source=self._directory_source, + connection=self._connection, + enrollment=AsyncMock(return_value=None), + worker=lambda worker: self.worker if worker == _WORKER else None, + worker_approval=self._approval, + fence_delivery=AsyncMock(), + ) + w = source_sync_worker + monkeypatch.setattr(w, "current_directory", lambda: self.directory) + monkeypatch.setattr(w, "current_routes", lambda: SimpleNamespace(permits=self._permits)) + monkeypatch.setattr(w.source_store, "get_source", self._get_source) + monkeypatch.setattr(w.source_store, "copies_at", self._copies_at) + monkeypatch.setattr(w.connected_accounts, "_standing", AsyncMock()) + monkeypatch.setattr( + w.connected_accounts.aliases, "verified_spellings", AsyncMock(return_value=["alice"]) + ) + monkeypatch.setattr(w.connected_accounts.aliases, "invalidate", lambda *_: None) + monkeypatch.setattr(w.connected_accounts.authz, "grant_role_for", self._grant) + monkeypatch.setattr(w.sync, "write_document", self._write) + monkeypatch.setattr(w.sync, "retire", self._retire) + monkeypatch.setattr(w.documents, "publications_owed", AsyncMock(return_value="")) + monkeypatch.setattr(w.mirror_store, "record_listing", self._listing) + + async def _get_source(self, org: str, namespace: str, name: str) -> Any: + return self.src if (org, namespace, name) == ("org", "team", "handbook") else None + + async def _directory_source(self, org: str, namespace: str, name: str) -> Any: + self.source_reads += 1 + return await self._get_source(org, namespace, name) + + def _permits(self, worker, org, digest, mode, team) -> bool: + assert (worker, org, digest, team) == (_WORKER, "org", _DIGEST, False) + return self.permitted + + async def _copies_at(self, org, namespace, tag, uris) -> set[str]: + assert (org, namespace, tag) == ("org", _MIRROR, f"source-id:{_SOURCE}") + return self.stored & set(uris) + + async def _grant(self, org: str, namespace: str, subject: str) -> Role | None: + return self.role + + async def _approval(self, org, namespace, worker, digest, mode, team) -> int | None: + assert (worker, digest, team) == (_WORKER, _DIGEST, False) + return self.approval + + async def _connection(self, org, namespace, owner, worker, connection) -> Any: + binding = ReaderConnection(owner, worker, connection, 9, _DIGEST) + return CurrentConnection(binding, self.account_active) + + async def _write(self, src, item, uri, text, **kw: Any) -> bool: + self.written.append({"item": item, "uri": uri, "text": text, **kw}) + self.stored.add(uri) + return True + + async def _retire(self, src, uri: str) -> bool: + self.retired.append(uri) + self.stored.discard(uri) + return True + + async def _listing(self, org, mirror, source_id, name, started) -> None: + assert (org, mirror, source_id, name) == ("org", _MIRROR, str(_SOURCE), "handbook") + self.listings.append(started) + + async def turn( + self, detail: dict[str, Any] | None = None, *, left: int = 40 + ) -> tuple[source_sync.TurnResult, source_sync.Pass]: + started = time.monotonic() + run = source_sync.Pass(PassBudget(started, started + 60), left) + result = source_sync.TurnResult(mirror=_MIRROR) + await source_sync_worker._sync_copies(self.src, detail or {}, run, result) + return result, run + + +def _detail(verified: datetime, *, copied: datetime | None = None, listed: str = "") -> dict: + entries = { + resource_digest(i): { + "sha": _sha(f"text of {i}"), + "copied_at": (copied or verified).isoformat(), + "verified_at": verified.isoformat(), + } + for i in _IDS + } + return {source_sync_worker._COPIES: entries, source_sync_worker._LISTED: listed} + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> _World: + return _World(monkeypatch) + + +@pytest.mark.asyncio +async def test_a_first_turn_copies_every_resource_for_the_owner_alone(world) -> None: + before = datetime.now(UTC) + result, run = await world.turn() + assert world.worker.calls == [("copy", "doc:one"), ("copy", "doc:two")] + assert [w["uri"] for w in world.written] == [_uri("doc:one"), _uri("doc:two")] + first = world.written[0] + assert first["permissions"] == AccessList(owner="alice") + assert first["extra_metadata"]["content_sha256"] == _sha("text of doc:one") + assert first["item"] == { + "id": resource_digest("doc:one"), + "name": "title doc:one", + "modifiedTime": "r1", + } + assert (result.status, result.changed, run.left) == ("ok", 2, 38) + # The listing vouches for the oldest confirmation, which came after the turn began. + [listed] = world.listings + assert listed >= before + assert result.kind_state[source_sync_worker._LISTED] == listed.isoformat() + copies = result.kind_state[source_sync_worker._COPIES] + assert set(copies) == {resource_digest(i) for i in _IDS} + + +@pytest.mark.asyncio +async def test_a_refresh_with_an_unchanged_digest_writes_nothing(world) -> None: + world.src = _source(mode="selected_refresh", interval_seconds=600) + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=900) + world.worker.texts["doc:two"] = "new text" + result, _ = await world.turn(_detail(old)) + assert world.worker.calls == [("copy", "doc:one"), ("copy", "doc:two")] + assert [w["uri"] for w in world.written] == [_uri("doc:two")] + assert result.changed == 1 and len(world.listings) == 1 + + +@pytest.mark.asyncio +async def test_a_snapshot_copy_has_its_access_checked_without_its_content(world) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + result, run = await world.turn(_detail(old)) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.written and run.left == 40 + [listed] = world.listings + assert listed > old + + +@pytest.mark.asyncio +async def test_an_access_check_confirms_access_whatever_the_digest(world) -> None: + # A check confirms the owner's access only; a changed resource keeps its copy until + # the copy is due again. + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.texts["doc:one"] = "changed upstream" + result, _ = await world.turn(_detail(old)) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.written and not world.retired + assert result.status == "ok" and len(world.listings) == 1 + + +@pytest.mark.asyncio +async def test_recently_confirmed_copies_skip_the_turn(world) -> None: + world.stored = {_uri(i) for i in _IDS} + recent = datetime.now(UTC) - timedelta(seconds=60) + world.role = None # nothing is read, the standing included + result, _ = await world.turn(_detail(recent, listed=recent.isoformat())) + assert result.status == "ok" and not world.worker.calls and not world.listings + + +@pytest.mark.asyncio +async def test_a_denied_resource_loses_its_copy_and_the_rest_are_vouched(world) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.refusals["doc:one"] = "denied" + result, _ = await world.turn(_detail(old)) + assert world.retired == [_uri("doc:one")] and result.removed == 1 + entries = result.kind_state[source_sync_worker._COPIES] + assert set(entries[resource_digest("doc:one")]) == {"retry_at"} + assert "verified_at" in entries[resource_digest("doc:two")] + [listed] = world.listings + assert listed > old + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reason", ["reconnect", "unavailable", "overloaded"]) +async def test_a_turn_wide_refusal_keeps_the_copies_and_vouches_for_none(world, reason) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.refusals = dict.fromkeys(_IDS, reason) + result, _ = await world.turn(_detail(old)) + assert world.worker.calls == [("check", "doc:one")] + assert not world.retired and not world.listings and not result.complete + entries = result.kind_state[source_sync_worker._COPIES] + assert {e["verified_at"] for e in entries.values()} == {old.isoformat()} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reason", ["timeout", "unsupported"]) +async def test_one_resources_failure_keeps_its_copy_unconfirmed(world, reason) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.refusals["doc:one"] = reason + result, _ = await world.turn(_detail(old, listed=old.isoformat())) + # The other resource is still checked, but the unconfirmed copy holds the listing back. + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.retired and not world.listings and not result.complete + + +@pytest.mark.asyncio +async def test_the_document_bound_stops_copies_but_not_checks(world) -> None: + world.stored = {_uri("doc:two")} + old = datetime.now(UTC) - timedelta(seconds=2000) + result, run = await world.turn(_detail(old), left=0) + assert world.worker.calls == [("check", "doc:two")] + assert not world.written and run.left == 0 + assert source_sync.TurnMark.PASS_BOUND in result.marks + + +@pytest.mark.asyncio +async def test_a_turn_out_of_time_before_its_listing_says_so(world, monkeypatch) -> None: + # The phase's time runs out during the last check: no listing, and the mark says why. + world.stored = {_uri(i) for i in _IDS} + spent = {"now": False} + original = world.worker.check_access + + async def check(scope, *, require_current): + answer = await original(scope, require_current=require_current) + spent["now"] = scope.resource_id == "doc:two" + return answer + + world.worker.check_access = check + monkeypatch.setattr(PassBudget, "exhausted", lambda self: spent["now"]) + result, _ = await world.turn(_detail(datetime.now(UTC) - timedelta(seconds=2000))) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.listings and source_sync.TurnMark.PASS_BOUND in result.marks + + +@pytest.mark.asyncio +async def test_a_lapsing_copy_is_kept_when_time_runs_out_first(world, monkeypatch) -> None: + # doc:one lapses and doc:two is confirmed, but the time is gone before the retirement. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unsupported" + spent = {"now": False} + original = world.worker.check_access + + async def check(scope, *, require_current): + try: + return await original(scope, require_current=require_current) + finally: + spent["now"] = scope.resource_id == "doc:two" + + world.worker.check_access = check + monkeypatch.setattr(PassBudget, "exhausted", lambda self: spent["now"]) + result, _ = await world.turn(_lapsed_detail(4000)) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.retired and source_sync.TurnMark.PASS_BOUND in result.marks + + +@pytest.mark.asyncio +async def test_a_refresh_the_document_bound_holds_back_says_so(world) -> None: + # A stored selected_refresh copy due for its refresh is only checked, and the turn says why. + world.src = _source(mode="selected_refresh", interval_seconds=600) + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + result, _ = await world.turn(_detail(old), left=0) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.written and source_sync.TurnMark.PASS_BOUND in result.marks + + +@pytest.mark.asyncio +async def test_a_held_back_refresh_with_fresh_access_sends_nothing(world) -> None: + # Due for its refresh but confirmed lately: the turn waits for room without a check. + world.src = _source(mode="selected_refresh", interval_seconds=600) + world.stored = {_uri(i) for i in _IDS} + now = datetime.now(UTC) + detail = _detail(now - timedelta(seconds=60), copied=now - timedelta(seconds=2000)) + result, _ = await world.turn(detail, left=0) + assert world.worker.calls == [] and source_sync.TurnMark.PASS_BOUND in result.marks + + +@pytest.mark.asyncio +@pytest.mark.parametrize("lost", ["directory", "writer", "routes"]) +async def test_without_the_owners_authority_nothing_is_read_or_retired(world, lost) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + if lost == "directory": + world.directory = None + elif lost == "writer": + world.role = Role.VIEWER + else: + world.permitted = False # this process's routes file does not provision the profile + result, _ = await world.turn(_detail(old)) + # A missing directory or an unprovisioned profile is the operator's; a lost grant the owner's. + expected = "owner_unavailable" if lost == "writer" else "unavailable" + assert result.status == expected and not result.complete + assert not world.worker.calls and not world.retired and not world.listings + + +@pytest.mark.asyncio +async def test_a_plain_denial_of_an_uncopied_resource_waits_half_the_window(world) -> None: + # A refused grant or a skewed clock is not the resource's word: a short wait, even for a + # day-long refresh interval. + world.src = _source(mode="selected_refresh", interval_seconds=86400) + world.worker.refusals["doc:one"] = "denied" + world.worker.upstream["doc:one"] = False + result, _ = await world.turn() + entry = result.kind_state[source_sync_worker._COPIES][resource_digest("doc:one")] + retry = datetime.fromisoformat(entry["retry_at"]) - datetime.now(UTC) + assert timedelta(seconds=1700) < retry <= timedelta(seconds=1800) + + +@pytest.fixture +def ending(world: _World, monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """The registration's end: its lease, queue, push retirement, row and state writes.""" + from contextlib import asynccontextmanager + + w = source_sync_worker + events: list[Any] = [] + + @asynccontextmanager + async def lease(org: str, namespace: str): + events.append(("lease", namespace)) + yield + + async def queue(src) -> bool: + events.append(("queue", src.source_id)) + return True + + async def insert(src) -> None: + events.append(("row", src.active, src.pending_delete, src.worker_history)) + + async def state(org, namespace, name, *, state_value, detail) -> None: + events.append(("state", name, detail)) + + monkeypatch.setattr(w.source_ops, "sources_lease", lease) + monkeypatch.setattr(w.source_ops, "_queue_retirement", queue) + from server.knowledge.app import source_push + + monkeypatch.setattr(source_push, "retire", AsyncMock()) + monkeypatch.setattr(w.source_store, "insert_source", insert) + monkeypatch.setattr(w.source_store, "write_state", state) + return events + + +@pytest.mark.asyncio +@pytest.mark.parametrize("lost", ["approval", "account", "generation"]) +async def test_a_gone_approval_or_account_ends_the_registration(world, ending, lost) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + if lost == "approval": + world.approval = 8 + elif lost == "account": + world.account_active = False + else: + world.approval = None + with pytest.raises(source_sync.SourceGone): + await world.turn(_detail(old)) + history = world.src.worker_history + assert ending == [ + ("lease", "team"), + ("queue", str(_SOURCE)), + ("row", False, True, history), + ("state", "handbook", {"status": "owner_inactive"}), + ] + assert not world.worker.calls and not world.retired + + +@pytest.mark.asyncio +async def test_an_unreadable_approval_ends_nothing(world, ending) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + + async def failing(*_args: Any) -> Any: + raise RuntimeError("approval read failed") + + world.directory = dataclasses.replace(world.directory, worker_approval=failing) + with pytest.raises(RuntimeError): + await world.turn(_detail(old)) + assert ending == [] and not world.retired + + +@pytest.mark.asyncio +async def test_authority_back_under_the_lease_ends_nothing(world, ending, monkeypatch) -> None: + async def authority(src, directory) -> str: + return "current" # the read under the lease finds the approval back + + monkeypatch.setattr(source_sync_worker, "authority", authority) + with pytest.raises(source_sync.SourceGone): + await source_sync_worker._end_registration(world.src, world.directory) + assert ending == [("lease", "team")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["replaced", "rewritten", "paused", "removed"]) +async def test_a_changed_registration_stops_the_turn(world, change) -> None: + read = world.src + if change == "replaced": + world.src = dataclasses.replace(read, source_id=str(UUID(int=6))) + elif change == "rewritten": + world.src = _source(approval_generation=8) + elif change == "paused": + world.src = _source(paused=True) + else: + world.src = None + with pytest.raises(source_sync.SourceGone): + await source_sync_worker.require_current(read) + + +# The read gate. + + +def _auth() -> AuthInfo: + return AuthInfo( + subject="alice", + org="org", + namespaces=("team",), + roles=(Role.VIEWER,), + is_service_account=False, + session_id="session", + ) + + +@pytest.fixture +def gate(monkeypatch: pytest.MonkeyPatch, world: _World) -> Any: + auth = _auth() + state = SimpleNamespace(auth=auth, subject="alice", latest=world.src, world=world) + monkeypatch.setattr(source_access, "current_auth", lambda: state.auth) + monkeypatch.setattr(source_access, "check_authorized", AsyncMock()) + monkeypatch.setattr(mcp_worker_runtime, "current_directory", lambda: world.directory) + state.subject_reads = 0 + state.latest_reads = 0 + + async def own_subject(_auth: Any) -> tuple[str, str]: + state.subject_reads += 1 + return await _subject(state.subject) + + monkeypatch.setattr(connected_accounts, "own_subject", own_subject) + from server.knowledge.store import sources as source_store + + async def latest(org: str, namespace: str, name: str) -> Any: + state.latest_reads += 1 + return state.latest + + monkeypatch.setattr(source_store, "latest_source", latest) + return state + + +async def _subject(subject: str) -> tuple[str, str]: + return "org", subject + + +def _plan(state: Any) -> source_access.ReadPlan: + plan = source_access.ReadPlan("org") + plan._auth = state.auth + return plan + + +_ROW = { + "namespace": "team", + "name": "handbook", + "source_id": str(_SOURCE), + "owner_subject": "alice", +} + + +@pytest.mark.asyncio +async def test_the_owner_is_admitted_to_the_copies_and_pinned(gate) -> None: + plan = _plan(gate) + rows = [dict(_ROW, credential_mode="worker")] + eligible, _ = await source_access._eligible_sources(plan, rows) + assert eligible == rows + assert plan._worker_pins[("team", str(_SOURCE))] == gate.latest + + +@pytest.mark.asyncio +async def test_another_reader_is_refused_the_copies(gate) -> None: + gate.subject = "bob" + assert not await source_access._worker_copy_eligible(_plan(gate), _ROW) + + +@pytest.mark.asyncio +async def test_a_readers_plan_reads_no_registry_row_of_a_source_it_does_not_own(gate) -> None: + gate.subject = "bob" + plan = _plan(gate) + rows = [ + dict(_ROW, credential_mode="worker"), + dict(_ROW, name="other", source_id=str(UUID(int=6)), credential_mode="worker"), + ] + eligible, _ = await source_access._eligible_sources(plan, rows) + assert eligible == [] and gate.latest_reads == 0 + # The reader's own subject is read once for the plan, not once per row. + assert gate.subject_reads == 1 + + +@pytest.mark.asyncio +async def test_a_row_naming_another_owner_than_its_registration_is_refused(gate) -> None: + # The row's owner admits the reader to the registry read; the registration decides. + gate.latest = dataclasses.replace(gate.latest, owner_subject="bob") + assert not await source_access._worker_copy_eligible(_plan(gate), _ROW) + + +@pytest.mark.asyncio +async def test_with_copies_off_no_worker_row_is_admitted(gate, monkeypatch) -> None: + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", False) + assert not await source_access._worker_copy_eligible(_plan(gate), _ROW) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["live", "approval", "account", "replaced", "directory"]) +async def test_a_changed_registration_or_authority_is_refused(gate, change) -> None: + world = gate.world + if change == "live": + gate.latest = _source(mode="live") + elif change == "approval": + world.approval = 8 + elif change == "account": + world.account_active = False + elif change == "replaced": + gate.latest = dataclasses.replace(gate.latest, source_id=str(UUID(int=6))) + else: + world.directory = None + assert not await source_access._worker_copy_eligible(_plan(gate), _ROW) + + +@pytest.mark.asyncio +async def test_a_frozen_plan_refuses_a_registration_changed_since_it_was_pinned(gate) -> None: + plan = _plan(gate) + assert await source_access._worker_copy_eligible(plan, _ROW) + frozen = _plan(gate) + frozen._scope_frozen = True + frozen._worker_pins = plan._worker_pins + assert await source_access._worker_copy_eligible(frozen, _ROW) + gate.latest = _source(approval_generation=8) + gate.world.approval = 8 + assert not await source_access._worker_copy_eligible(frozen, _ROW) + # A row the request never pinned is not added to a frozen plan. + assert not await source_access._worker_copy_eligible( + frozen, dict(_ROW, source_id=str(UUID(int=6))) + ) + + +# Owner erasure. + + +@pytest.mark.asyncio +async def test_owner_erasure_queues_the_copies_before_the_rows_go(monkeypatch) -> None: + from contextlib import asynccontextmanager + + from server.knowledge.app import sources as source_ops + + events: list[tuple[str, ...]] = [] + store = connected_accounts.source_store + + @asynccontextmanager + async def lease(org: str, namespace: str): + events.append(("lease", namespace)) + yield + + async def namespaces(org, owner, *, before): + return ["team"] + + async def owned(org, namespace, owner, *, before): + assert (org, namespace, owner, before) == ("org", "team", "alice", 100) + return [dataclasses.replace(_source(), active=False)] + + async def queue(src) -> bool: + events.append(("queue", src.source_id)) + return True + + async def erase(org, namespace, owner, *, before): + events.append(("erase", namespace)) + + monkeypatch.setattr(source_ops, "sources_lease", lease) + monkeypatch.setattr(source_ops, "_queue_retirement", queue) + monkeypatch.setattr(store, "worker_owner_namespaces", namespaces) + monkeypatch.setattr(store, "worker_owner_sources", owned) + monkeypatch.setattr(store, "erase_worker_owner", erase) + from server.erasure.app import connected_accounts as erasure_accounts + + monkeypatch.setattr(erasure_accounts, "require_worker_sources_erased", AsyncMock()) + await connected_accounts._erase_worker_sources("org", "alice", 100) + assert events == [("lease", "team"), ("queue", str(_SOURCE)), ("erase", "team")] + + +# A denial retires a copy only when the worker answered it under authority that holds. + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "cause", ["grant", "approval", "malformed", "registration"], ids=lambda c: c +) +async def test_a_denial_loom_answers_keeps_every_copy(world, ending, cause) -> None: + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.refusals["doc:one"] = "denied" + original = world.worker.check_access + + async def check(scope, *, require_current): + if cause == "malformed": + world.worker.upstream["doc:one"] = False # a reply that failed validation + try: + return await original(scope, require_current=require_current) + except WorkerReadRefused: + # What changes after the worker's 403, before the copy would be retired. + if cause == "grant": + world.role = None + elif cause == "approval": + world.approval = 8 + elif cause == "registration": + world.src = _source(approval_generation=9) + raise + + world.worker.check_access = check + result, _ = await world.turn(_detail(old)) + assert not world.retired and not world.listings + assert result.status == "denied" and world.worker.calls == [("check", "doc:one")] + entries = result.kind_state[source_sync_worker._COPIES] + assert set(entries) == {resource_digest(i) for i in _IDS} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reason", ["denied", "unsupported"]) +async def test_a_resource_left_without_a_copy_waits_before_it_is_tried_again(world, reason) -> None: + world.worker.refusals["doc:one"] = reason + result, _ = await world.turn() + assert world.worker.calls == [("copy", "doc:one"), ("copy", "doc:two")] + entry = result.kind_state[source_sync_worker._COPIES][resource_digest("doc:one")] + assert set(entry) == {"retry_at"} + # The next turn reads only what is due: the stored copy was just confirmed. + world.worker.calls.clear() + detail = { + source_sync_worker._COPIES: result.kind_state[source_sync_worker._COPIES], + source_sync_worker._LISTED: result.kind_state[source_sync_worker._LISTED], + } + await world.turn(detail) + assert world.worker.calls == [] + # Past the wait it is read again. + entry["retry_at"] = (datetime.now(UTC) - timedelta(seconds=1)).isoformat() + await world.turn(detail) + assert world.worker.calls == [("copy", "doc:one")] + + +@pytest.mark.asyncio +async def test_a_copy_resolves_its_authority_once_before_and_once_after(world) -> None: + await world.turn() + # Two resources, each resolved by the turn and once more by the channel after the reply. + assert world.source_reads == 4 + + +_MANY = tuple(f"doc:{n:03d}" for n in range(241)) + + +@pytest.mark.asyncio +async def test_every_selected_copy_counts_past_a_page_of_documents(world) -> None: + world.src = dataclasses.replace( + encode_worker_source( + org="org", + namespace="team", + name="handbook", + source_id=_SOURCE, + owner="alice", + config=_config(), + selection=tuple(ResourceIdentity(type="resource", id=i) for i in _MANY), + ), + mirror=_MIRROR, + ) + world.worker.texts = {i: f"text of {i}" for i in _MANY} + world.stored = {_uri(i) for i in _MANY} + recent = datetime.now(UTC) - timedelta(seconds=60) + old = datetime.now(UTC) - timedelta(seconds=2000) + entries = { + resource_digest(i): {"sha": _sha(f"text of {i}"), "verified_at": recent.isoformat()} + for i in _MANY + } + # The oldest confirmation is the last resource's, past any page of 200. + entries[resource_digest(_MANY[-1])]["verified_at"] = old.isoformat() + world.worker.refusals[_MANY[-1]] = "denied" + result, _ = await world.turn({source_sync_worker._COPIES: entries}) + assert world.worker.calls == [("check", _MANY[-1])] + assert world.retired == [_uri(_MANY[-1])] + [listed] = world.listings + assert listed == recent + + +def test_the_sync_command_opens_the_source_worker_directory(monkeypatch) -> None: + import argparse + from contextlib import asynccontextmanager + + from server.cli import knowledge as cli + from server.knowledge.app import mcp_worker_runtime + + seen: list[Any] = [] + + @asynccontextmanager + async def runtime(path: str): + seen.append(("open", path)) + yield + seen.append("closed") + + async def run_sync(**_kw: Any) -> Any: + seen.append("sync") + return source_sync.PassResult() + + monkeypatch.setattr(settings, "knowledge_source_worker_routes_file", "/routes.json") + monkeypatch.setattr(mcp_worker_runtime, "source_worker_runtime", runtime) + monkeypatch.setattr(source_sync, "run_sync", run_sync) + monkeypatch.setattr(cli, "_record", AsyncMock()) + monkeypatch.setattr(cli, "run_connected", lambda run, **_kw: asyncio.run(run(None))) + args = argparse.Namespace(org="org", namespace="team", source="", full=False) + assert cli._cmd_sync(args) == 0 + assert seen == [("open", "/routes.json"), "sync", "closed"] + + +@pytest.mark.asyncio +async def test_a_worker_denial_without_the_upstream_reason_retires_nothing(world) -> None: + # A grant the worker could not verify (a rotated key, a skewed clock) answers a plain + # 403 for every request; authority on Loom's side is intact. + world.stored = {_uri(i) for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=2000) + world.worker.refusals = dict.fromkeys(_IDS, "denied") + world.worker.upstream = dict.fromkeys(_IDS, False) + result, _ = await world.turn(_detail(old)) + assert result.status == "denied" and not result.complete + assert world.worker.calls == [("check", "doc:one")] + assert not world.retired and not world.listings + + +@pytest.mark.asyncio +async def test_a_registration_ends_through_the_shared_retirement(world, monkeypatch) -> None: + from contextlib import asynccontextmanager + + from server.knowledge.app import sources as source_ops + + ended: list[Any] = [] + + @asynccontextmanager + async def lease(org: str, namespace: str): + yield + + async def retire(src) -> None: + ended.append(src.source_id) + + monkeypatch.setattr(source_ops, "sources_lease", lease) + monkeypatch.setattr(source_ops, "retire_owner_inactive", retire) + world.approval = 8 + with pytest.raises(source_sync.SourceGone): + await source_sync_worker._end_registration(world.src, world.directory) + assert ended == [str(_SOURCE)] + + +@pytest.mark.asyncio +async def test_a_plain_denial_of_a_resource_without_a_copy_waits_its_turn(world) -> None: + # An older worker names no reason: the turn ends, nothing is retired, and the refused + # resource waits so the next turn reaches the others. + world.worker.refusals["doc:one"] = "denied" + world.worker.upstream["doc:one"] = False + result, _ = await world.turn() + assert result.status == "denied" and world.worker.calls == [("copy", "doc:one")] + entries = result.kind_state[source_sync_worker._COPIES] + assert set(entries[resource_digest("doc:one")]) == {"retry_at"} + world.worker.calls.clear() + await world.turn({source_sync_worker._COPIES: entries}) + assert world.worker.calls == [("copy", "doc:two")] and not world.retired + + +@pytest.mark.asyncio +async def test_a_copy_unconfirmed_for_the_whole_stale_window_is_retired(world) -> None: + world.stored = {_uri(i) for i in _IDS} + detail = _detail(datetime.now(UTC) - timedelta(seconds=2000)) + lapsed = datetime.now(UTC) - timedelta(seconds=4000) + detail[source_sync_worker._COPIES][resource_digest("doc:one")]["verified_at"] = ( + lapsed.isoformat() + ) + world.worker.refusals["doc:one"] = "unsupported" + result, _ = await world.turn(detail) + # Served no more, it would hold back every other copy's listing: it goes and waits. + assert world.retired == [_uri("doc:one")] and result.note == "copy_unconfirmable" + entries = result.kind_state[source_sync_worker._COPIES] + assert set(entries[resource_digest("doc:one")]) == {"retry_at"} + [listed] = world.listings + assert listed > lapsed + timedelta(seconds=3000) + + +def _lapsed_detail(age_s: int) -> dict: + detail = _detail(datetime.now(UTC) - timedelta(seconds=2000)) + lapsed = datetime.now(UTC) - timedelta(seconds=age_s) + detail[source_sync_worker._COPIES][resource_digest("doc:one")]["verified_at"] = ( + lapsed.isoformat() + ) + return detail + + +@pytest.mark.asyncio +async def test_a_copy_goes_before_its_confirmation_lapses(world) -> None: + # 2800 s of a 3600 s window with a 900 s pass: the next pass would come too late. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unsupported" + result, _ = await world.turn(_lapsed_detail(2800)) + assert world.retired == [_uri("doc:one")] and result.note == "copy_unconfirmable" + assert len(world.listings) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reason", ["reconnect", "overloaded", "unavailable", "denied"]) +async def test_a_lapsed_copy_is_kept_by_a_refusal_that_ends_the_turn(world, reason) -> None: + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = reason + world.worker.upstream["doc:one"] = False + result, _ = await world.turn(_lapsed_detail(4000)) + assert not world.retired and not world.listings and result.status == reason + + +@pytest.mark.asyncio +async def test_a_lapsing_copy_is_kept_when_a_later_refusal_ends_the_turn(world) -> None: + # doc:two was confirmed after doc:one's check fell due, but its own check now ends the turn. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals = {"doc:one": "unsupported", "doc:two": "reconnect"} + result, _ = await world.turn(_lapsed_detail(4000)) + assert world.worker.calls == [("check", "doc:one"), ("check", "doc:two")] + assert not world.retired and result.status == "reconnect" + + +@pytest.mark.asyncio +async def test_a_deactivation_mid_turn_stops_the_next_read(world, monkeypatch) -> None: + # The owner's whole standing is read for every request, not only at the turn's start. + world.stored = set() + calls = {"n": 0} + + async def standing(org, subject, since): + calls["n"] += 1 + if calls["n"] > 1: + raise ValidationError("owner deactivated", code="CONNECTION_UNAVAILABLE") + + monkeypatch.setattr(source_sync_worker.connected_accounts, "_standing", standing) + result, _ = await world.turn() + assert world.worker.calls == [] and not world.written + assert result.status == "denied" + + +@pytest.mark.asyncio +async def test_a_resource_without_a_copy_that_ends_the_turn_waits(world) -> None: + world.worker.refusals["doc:one"] = "overloaded" + result, _ = await world.turn() + entry = result.kind_state[source_sync_worker._COPIES][resource_digest("doc:one")] + assert result.status == "overloaded" and "retry_at" in entry + + +@pytest.mark.asyncio +async def test_worker_copies_take_their_turn_past_the_document_bound(monkeypatch) -> None: + native = _source() + copied = dataclasses.replace(native, source_id=str(uuid4())) + turned: list[str] = [] + + async def one(src, state, run, result): + turned.append(src.source_id) + + monkeypatch.setattr(source_sync, "_sync_one", one) + monkeypatch.setattr(source_sync, "worker_copied", lambda src: src is copied) + monkeypatch.setattr(settings, "knowledge_source_mirror_documents_per_pass", 0) + started = time.monotonic() + whole = PassBudget(started, started + 60) + await source_sync._sync_mirrored([native, copied], {}, whole, source_sync.PassResult()) + assert turned == [copied.source_id] + + +@pytest.mark.asyncio +async def test_a_lapsed_copy_is_kept_when_the_owners_authority_is_gone(world) -> None: + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unsupported" + original = world.worker.check_access + + async def check(scope, *, require_current): + try: + return await original(scope, require_current=require_current) + except WorkerReadRefused: + world.role = None # the owner's writer grant goes during the request + raise + + world.worker.check_access = check + await world.turn(_lapsed_detail(4000)) + assert not world.retired and not world.listings + + +@pytest.mark.asyncio +async def test_a_pass_longer_than_half_the_window_retires_at_the_first_due_check( + world, monkeypatch +) -> None: + # The copy is checked, and so retired, only once its check is due. + monkeypatch.setattr(settings, "knowledge_source_sync_interval_seconds", 3000) + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unsupported" + await world.turn(_lapsed_detail(1700)) + assert not world.retired + await world.turn(_lapsed_detail(1900)) + assert world.retired == [_uri("doc:one")] + + +@pytest.mark.asyncio +async def test_a_timeout_never_retires_a_copy(world) -> None: + # A stalled upstream answers every request with a timeout: nothing is the resource's. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals = {i: "timeout" for i in _IDS} + old = datetime.now(UTC) - timedelta(seconds=4000) + result, _ = await world.turn(_detail(old)) + # Any listing still names the old confirmation, which the read gate refuses as stale. + assert not world.retired and all(listed <= old for listed in world.listings) + entries = result.kind_state[source_sync_worker._COPIES] + assert all("retry_at" not in entries[resource_digest(i)] for i in _IDS) + + +@pytest.mark.asyncio +async def test_a_lapsing_copy_stays_while_no_other_copy_was_confirmed_since(world) -> None: + # Every resource unsupported, as after a protocol change upstream: none is retired. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals = {i: "unsupported" for i in _IDS} + await world.turn(_detail(datetime.now(UTC) - timedelta(seconds=3000))) + assert not world.retired + + +@pytest.mark.asyncio +async def test_a_lapsing_copy_goes_when_another_was_confirmed_since_its_check_fell_due( + world, +) -> None: + # The other copy is not due this turn, but was confirmed after doc:one's check fell due. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unsupported" + detail = _lapsed_detail(3000) + recent = datetime.now(UTC) - timedelta(seconds=60) + detail[source_sync_worker._COPIES][resource_digest("doc:two")]["verified_at"] = ( + recent.isoformat() + ) + await world.turn(detail) + assert world.worker.calls == [("check", "doc:one")] + assert world.retired == [_uri("doc:one")] + + +@pytest.mark.asyncio +async def test_a_resource_without_a_copy_that_times_out_waits(world) -> None: + world.worker.refusals["doc:one"] = "timeout" + result, _ = await world.turn() + entry = result.kind_state[source_sync_worker._COPIES][resource_digest("doc:one")] + retry = datetime.fromisoformat(entry["retry_at"]) - datetime.now(UTC) + assert timedelta(seconds=1700) < retry <= timedelta(seconds=1800) + result, _ = await world.turn({source_sync_worker._COPIES: {resource_digest("doc:one"): entry}}) + assert ("copy", "doc:one") not in world.worker.calls[2:] + + +@pytest.mark.asyncio +async def test_resources_without_a_copy_go_before_the_oldest_confirmation(world) -> None: + world.stored = {_uri("doc:two")} + old = datetime.now(UTC) - timedelta(seconds=3000) + await world.turn(_detail(old)) + assert world.worker.calls == [("copy", "doc:one"), ("check", "doc:two")] + + +@pytest.mark.asyncio +async def test_the_turn_reads_the_owners_writer_grant_through_the_shared_check( + world, monkeypatch +) -> None: + asked: list[tuple[str, str, str]] = [] + + async def owner_writes(org: str, namespace: str, subject: str) -> bool: + asked.append((org, namespace, subject)) + return False + + monkeypatch.setattr(connected_accounts, "owner_writes", owner_writes) + result, _ = await world.turn() + assert result.status == "owner_unavailable" and not world.worker.calls + assert asked == [("org", "team", "alice")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("role", "writes"), [(Role.WRITER, True), (Role.VIEWER, False), (None, False)] +) +async def test_owner_writes_reads_the_grant_after_the_aliases_refresh( + monkeypatch, role, writes +) -> None: + events: list[str] = [] + + async def spellings(org: str, subject: str) -> list[str]: + events.append("spellings") + return [subject] + + async def grant(org: str, namespace: str, subject: str) -> Role | None: + events.append("grant") + return role + + monkeypatch.setattr(connected_accounts.aliases, "verified_spellings", spellings) + monkeypatch.setattr(connected_accounts.aliases, "invalidate", lambda *_: events.append("drop")) + monkeypatch.setattr(connected_accounts.authz, "grant_role_for", grant) + assert await connected_accounts.owner_writes("org", "team", "alice") is writes + assert events == ["spellings", "drop", "grant"]