From dba6573c43d3401906a0b70bd3a7498eb717c3f4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 18:34:42 +0000 Subject: [PATCH 01/18] Owner-only snapshot and selected-refresh worker sources keep a private copy in the mirror With knowledge_source_worker_copies_enabled on, a collection writer can register an owner-only snapshot or selected_refresh worker source (the latter with a new interval_seconds field). The sync worker keeps its copy in the collection's mirror: each turn copies a resource that has no copy or whose refresh interval passed through a new copy share of the worker channel, checks the rest with check-access once their confirmation is half the ACL stale window old, retires a copy the worker denies, and records the listing at the oldest confirmation of the stored copies, so an unconfirmed copy stops being served within the stale window. The mirror read gate admits a worker source's copies to its owner alone while the registration, the approval and the owner's worker account are current. knowledge.source.remove, namespace retirement and owner erasure now queue a worker source's copies for the retirement worker, which no longer skips an inactive worker row. The setting is off by default and is turned on only once every replica runs this build. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/document-sources.md | 21 +- .../mcp-source-worker-boundary.md | 64 ++- docs/architecture/rolling-upgrades.md | 15 + docs/features/knowledge.md | 5 +- docs/reference/configuration.md | 1 + docs/reference/operations.md | 4 +- docs/reference/operations/knowledge.md | 12 +- docs/reference/status.md | 3 +- loom.example.yaml | 5 + schemas/loom-settings.schema.json | 5 + sdk/go/wire/models.gen.go | 44 +- sdk/python/loom/ops.py | 12 +- sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 8 +- sdk/rust/src/wire_models.rs | 30 + sdk/typescript/src/generated/ops.ts | 8 +- server/knowledge/api/models_sources.py | 15 +- server/knowledge/api/models_worker_setup.py | 19 +- server/knowledge/api/ops_worker_setup.py | 2 +- server/knowledge/app/connected_accounts.py | 7 +- server/knowledge/app/mcp_worker_read.py | 26 +- .../knowledge/app/mcp_worker_setup_preview.py | 13 +- .../app/mcp_worker_setup_register.py | 2 +- .../knowledge/app/mcp_worker_setup_source.py | 21 +- server/knowledge/app/source_access.py | 66 ++- server/knowledge/app/source_retirements.py | 9 +- server/knowledge/app/source_sync.py | 52 +- server/knowledge/app/source_sync_worker.py | 419 ++++++++++++++ server/knowledge/app/sources.py | 18 +- server/knowledge/domain/mcp_worker_source.py | 13 + server/knowledge/store/source_access.py | 8 +- server/knowledge/store/sources.py | 29 + server/settings/catalog.py | 3 + .../test_mcp_worker_source_history_ch.py | 14 + tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_assistant_mirror_boundary.py | 6 +- tests/unit/test_connected_account_cleanup.py | 16 + .../unit/test_knowledge_source_retirements.py | 70 ++- tests/unit/test_mcp_worker_read.py | 40 ++ tests/unit/test_mcp_worker_setup_register.py | 52 +- tests/unit/test_source_access_plan.py | 10 +- tests/unit/test_worker_source_copies.py | 536 ++++++++++++++++++ 41 files changed, 1538 insertions(+), 166 deletions(-) create mode 100644 server/knowledge/app/source_sync_worker.py create mode 100644 tests/unit/test_worker_source_copies.py diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 44ef9177b5f..0f9fd919ef6 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 f519a61eeaa..692219d678c 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -13,17 +13,18 @@ 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 +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 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 that +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. @@ -311,9 +312,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 @@ -368,5 +371,44 @@ 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 owner's standing first: an active directory account, no revocation +since the registration, and a writer grant in the collection. It then needs the +collection's current approval of the registration's mode and the owner's worker account +at the registered generation. Each worker request resolves that authority again as a +live read does (`CurrentRead` with the `stored` purpose), with the owner as requester, +before the request and after the reply. A resource with no copy, or a selected-refresh +one whose interval has passed, is read through the worker's live path in a share of two +requests per worker that live reads never wait on; a reply with the stored digest writes +nothing. 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. The oldest confirmation goes first. Copies count against the +pass's mirror document bound; checks count against its time alone. + +A worker `denied` retires that resource's copy. `reconnect`, `overloaded` and +`unavailable` end the turn and keep every copy; `timeout` and `unsupported` keep that +resource's copy and let the turn go on. 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. Nothing confirms a copy while +the owner's standing, the approval or the worker account fails, so they fail closed +together. + +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. + +`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 fa2cefea598..51fb94c77d4 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1138,6 +1138,21 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `tests/unit/test_mcp_worker_setup_register.py` checks N's writer, and the mixed-version gate does not check this rule. +75. **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 and retirement worker queue and delete no worker copy. So the operator + turns the setting on only once every replica runs N; it is off by default, and with it + off N behaves as N-1 for these rows, so the rollout itself writes no copy. 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. 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 d64538fb313..2c58f51d0a8 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -326,9 +326,8 @@ 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 +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 diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 266815d77d9..70a28993cec 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 afcfd662669..00f1235c5a7 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 eccaf021558..ecaec0210fc 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` reads a resource when asked and keeps no copy; `snapshot` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every `interval_seconds`. | +| `interval_seconds` | `int \| None` | `None` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | | `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` reads a resource when asked and keeps no copy; `snapshot` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every `interval_seconds`. | +| `interval_seconds` | `int \| None` | `None` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | | `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 760593c1673..2c165f5b1aa 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 ffb7b922b6d..59089b5d059 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 483984c3f5b..32afbd4b534 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 6868f00309f..8edaca0f59e 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: 89731d59fda7a96ab4476c4e23f20a5d4cb501cc1de5a67c5960b8ad4bbadc43 +// Registry model schema SHA-256: 7e596d0d638d21dce1fc5b90a2b4defaf8ae6df2ebe11c6c637a5b95108ed687 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -13237,15 +13237,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. @@ -13304,17 +13305,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 8b0c6c6e7ac..c1dddbfed6a 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 08e7c12d35d..c3d8f5ed575 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 bbe9ff73ebe..737693dd7a2 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 2a902220d20..2582269b291 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` reads a resource when asked and keeps no copy; `snapshot` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every ` */ mode: "live" | "snapshot" | "selected_refresh"; + /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ + 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` reads a resource when asked and keeps no copy; `snapshot` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every ` */ mode: "live" | "snapshot" | "selected_refresh"; + /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ + 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/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 76d3a40bef0..3d9f78bf13f 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 fe512a6433f..9996a04c672 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,15 @@ 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` reads a resource when asked and keeps no copy; `snapshot` keeps" + " one copy of each resource for the owner alone, and `selected_refresh` replaces it" + " every `interval_seconds`. Both 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="Seconds between a `selected_refresh` source's copies, 300 to 86400;" + " required for that mode and refused for the others.", ) team_access: bool = Field( default=False, @@ -204,11 +211,13 @@ 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 alone") 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 3cfd26cfd55..d853e116db9 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 02eac6ac5b6..6b9ad8511bd 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -637,12 +637,17 @@ 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) diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py index a3c7ea553ad..92bd9f9ceed 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 reads a stored copy's content one resource at a time per source; its own share +# keeps those reads from taking a live read's slot. +_COPY_SLOTS = 2 # not a setting: copies in flight per worker across a process's sync turns # 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. @@ -239,6 +242,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 +255,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, ), @@ -324,6 +332,20 @@ 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. `require_current` + checks `scope` before the request and after the reply.""" + return await self._exchange( + scope, + "live", + "copy", + require_current, + lambda payload, issued: _validate_reading(payload, scope, issued), + check_first=True, + ) + 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 8c159cfa896..87b33208670 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, @@ -33,12 +33,21 @@ from server.knowledge.domain.mcp_worker_setup import WorkerSetupRejected, plan_worker_setup 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 account still reads it." + ), + "selected_refresh": ( + "Loom reads each resource through the owner's account and replaces its copy every" + " interval; the copy is indexed and shown to the owner alone, while 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 70f9dbf988f..5a3e08726c4 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 a662681882b..6cb25e7b588 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 3de93c496f1..4f152e8b04b 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -87,6 +87,7 @@ 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) @property def discovery_sources(self) -> dict[tuple[str, str], str]: @@ -144,12 +145,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 +266,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 +293,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 +331,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 +395,47 @@ async def _eligible_sources( return eligible, crawl_generations +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 connected_accounts, 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 + 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"]) + owner_org, subject = await connected_accounts.own_subject(auth) + if (owner_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 40fe1a2159e..09c730c33fd 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 4c0ed98514b..9801f8d6ea0 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), @@ -423,11 +425,11 @@ def synced_at(src: KnowledgeSource) -> str: 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 +465,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 +489,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 +498,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 +506,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 +527,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 +553,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 +1437,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_worker.py b/server/knowledge/app/source_sync_worker.py new file mode 100644 index 00000000000..7c587bfc7f2 --- /dev/null +++ b/server/knowledge/app/source_sync_worker.py @@ -0,0 +1,419 @@ +"""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). The oldest confirmation goes first, and only copies +spend the pass's document bound. + +A worker `denied` retires that resource's copy. A `timeout` or `unsupported` answer keeps +that resource's copy and the turn goes on; any other refusal keeps every copy, ends the +turn and records no listing. 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, whatever stopped its check. + +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`.""" + +from __future__ import annotations + +import dataclasses +import functools +from datetime import UTC, datetime, timedelta +from typing import Any +from uuid import UUID + +from server.auth import aliases, authz +from server.core.ch import own_write_reads, 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.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, + WorkerReadChannel, + WorkerReading, + WorkerReadRefused, + WorkerReadScope, +) +from server.knowledge.app.mcp_worker_runtime import current_directory +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.operations.base import Role +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; 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 _writer(src: KnowledgeSource) -> bool: + # The alias cache is read fresh, so a departed alias's grant no longer counts. + await aliases.verified_spellings(src.org, src.owner_subject) + aliases.invalidate(src.org, [src.owner_subject]) + with own_write_reads(): + role = await authz.grant_role_for(src.org, src.namespace, src.owner_subject) + return role is not None and role >= Role.WRITER + + +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 _writer(src) + + +async def account_current(src: KnowledgeSource, directory: LiveSourceDirectory) -> bool: + """The collection's approval of the registration's mode and the owner's worker account + at the registered generation, as `CurrentRead` checks them for each request.""" + try: + config, _ = decode_worker_source(src) + except WorkerSourceRefused: + return False + approval = await directory.worker_approval( + src.org, src.namespace, config.worker_id, config.profile_digest, config.mode, False + ) + if approval != config.approval_generation: + return False + record = await directory.connection( + src.org, src.namespace, src.owner_subject, config.worker_id, config.owner_connection_id + ) + return ( + record is not None + and record.active + and record.binding.connection_generation == config.owner_connection_generation + and record.binding.profile_digest == config.profile_digest + ) + + +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: + return True + 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: + verified = _at(self.entry.get("verified_at")) + half = timedelta(seconds=settings.knowledge_source_acl_stale_seconds / 2) + return verified is None or now - verified >= half + + +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, self.selected = decode_worker_source(src) + + async def _standing(self, _: RequestedResource) -> ReaderStanding | None: + return ReaderStanding(self.src.owner_subject) if await _writer(self.src) else None + + async def _exchange( + self, item: ResourceIdentity, *, content: bool + ) -> WorkerReading | WorkerAccess: + 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") + return await self._send(channel, scope, current, content=content) + + async def _send( + self, + channel: WorkerReadChannel, + scope: WorkerReadScope, + current: CurrentRead, + *, + content: bool, + ) -> WorkerReading | WorkerAccess: + 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 + copy.stored = True + copy.entry["sha"] = reading.content_sha256 + + async def visit(self, copy: _Copy, now: datetime) -> bool: + """Copy or check one resource; False once the turn must stop.""" + content = copy.copy_due(self.config.interval_seconds, now) and self.run.left > 0 + if not content and not copy.stored: + # Out of the document bound: a stored copy can still have its access checked. + self.result.mark(sync.TurnMark.PASS_BOUND) + 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.reason) + if isinstance(answer, WorkerReading): + self.run.left -= 1 + await self._write(copy, answer) + if copy.stored: + copy.entry["copied_at"] = asked.isoformat() + if copy.stored: + copy.entry["verified_at"] = asked.isoformat() + return True + + async def _refused(self, copy: _Copy, reason: str) -> bool: + if reason == "denied": + # The owner's account no longer reads it: its copy goes. + if copy.stored and await sync.retire(self.src, copy.uri): + self.result.removed += 1 + copy.stored = False + copy.entry.clear() + return True + # Every other refusal keeps the copy, unconfirmed. One resource's timeout or + # unsupported answer lets the others go on; the worker at capacity, the owner's + # account to link again or the worker unavailable ends the turn. + if reason in ("timeout", "unsupported"): + self.result.complete = False + self.result.note = reason + return True + self.result.fail(reason, reason) + return False + + +async def _known_copies( + src: KnowledgeSource, selected: tuple[ResourceIdentity, ...], recorded: dict[str, Any] +) -> tuple[list[_Copy], set[str]]: + """Each selected resource's copy, and the stored addresses no resource selects.""" + with sequential_reads(): + docs = await source_store.source_documents( + src.org, src.mirror, source_id_tag(src.source_id) + ) + stored = {str(d["source_uri"]) for d in docs} + copies = [] + for item in selected: + uri = resource_uri(src.source_id, item.id) + raw = recorded.get(resource_digest(item.id)) + entry = dict(raw) if isinstance(raw, dict) and uri in stored else {} + copies.append(_Copy(item, uri, uri in stored, entry)) + return copies, stored - {c.uri for c in 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, unselected = 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) + for uri in sorted(unselected): + if await sync.retire(src, uri): + result.removed += 1 + 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 + if not await owner_standing(src) or not await account_current(src, directory): + result.fail("owner_unavailable", "owner_unavailable") + return + await _visit_due(_Turn(src, directory, run, result), due, now) + _keep(result, copies) + await _vouch(src, directory, copies, run, result) + + +async def _visit_due(work: _Turn, due: list[_Copy], now: datetime) -> None: + # The oldest confirmation first, so a turn the bound cuts leaves the newest 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.stored and 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] + or run.budget.exhausted() + or 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() + async with sync.publication_guard(src): + 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 aab19122e98..3d4abbc3786 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)) diff --git a/server/knowledge/domain/mcp_worker_source.py b/server/knowledge/domain/mcp_worker_source.py index 2d7388731db..76badc76ba8 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 c5265cba248..b7e74c1919e 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -43,15 +43,19 @@ class ReadHead(NamedTuple): 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`, worker rows too, which the caller + decodes before it trusts one.""" if not namespaces: return [] + native = f"NOT {WORKER_HISTORY}" + rows = f"({native} OR credential_mode = '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 " "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 e413bf33841..ba9f8887d65 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: diff --git a/server/settings/catalog.py b/server/settings/catalog.py index f5314b83450..287947a9ec1 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2618,6 +2618,9 @@ class KnowledgeSettings(BaseModel): # Seconds one response frame may spend acquiring authority locks and sending. At most # 1, the default; the remaining publication deadline can shorten it further. knowledge_source_worker_frame_timeout_s: float = Field(default=1.0, gt=0, le=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. + knowledge_source_worker_copies_enabled: bool = False # Mirrored reads require a complete listing and group observation within this # many seconds; missing or older evidence admits nobody. knowledge_source_acl_stale_seconds: int = Field(default=3600, ge=1) diff --git a/tests/integration/test_mcp_worker_source_history_ch.py b/tests/integration/test_mcp_worker_source_history_ch.py index 07967aa71bc..8f771a3d667 100644 --- a/tests/integration/test_mcp_worker_source_history_ch.py +++ b/tests/integration/test_mcp_worker_source_history_ch.py @@ -260,6 +260,20 @@ async def test_native_mirror_inventory_excludes_legacy_worker_history(registry: ] +async def test_worker_copy_inventory_adds_worker_rows_alone(registry: Registry) -> None: + set_query_tag("test.mcp-worker-source-history.worker-mirrors") + await registry.seed("damaged", worker=True, legacy_only=True, active=True, shared=True) + native_id, _, _ = await registry.seed("native", worker=False, active=True, shared=True) + worker_id, _, _ = await registry.seed("worker", worker=True, active=True) + found = await source_access.active_sources( + registry.org, [NAMESPACE], workers=True, ch=registry.ch + ) + assert [(row["name"], row["credential_mode"], row["source_id"]) for row in found] == [ + ("native", "shared", native_id), + ("worker", "worker", worker_id), + ] + + async def test_worker_history_is_found_by_owner_in_any_namespace(registry: Registry) -> None: set_query_tag("test.mcp-worker-source-history.owners") await registry.seed("elsewhere", worker=True, namespace="other-namespace") diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 6a9bed59121..657d708dbff 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 3137b661136..bd1136c0745 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_connected_account_cleanup.py b/tests/unit/test_connected_account_cleanup.py index a6fb4533421..73d4006936c 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 5511e9f3db4..57d1d461fa3 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 e9a361e5dd2..149ee75967e 100644 --- a/tests/unit/test_mcp_worker_read.py +++ b/tests/unit/test_mcp_worker_read.py @@ -486,6 +486,46 @@ 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) + + held = [asyncio.create_task(copy()) for _ in range(2)] + await self._until(arrived, paths, 2) + 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, 3) + 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"] * 3) + + async def test_a_copy_checks_its_scope_before_it_sends(self) -> None: + sent: list[str] = [] + + def answer(request: httpx.Request) -> httpx.Response: + sent.append(request.url.path) + return httpx.Response(500) + + async def changed() -> WorkerReadScope: + return replace(self.scope, approval_generation=5) + + channel = self._channel(httpx.MockTransport(answer)) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await channel.copy(self.scope, require_current=changed) + self.assertEqual(sent, []) + 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 89f4b9b1a85..a54f3bc47e8 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", } diff --git a/tests/unit/test_source_access_plan.py b/tests/unit/test_source_access_plan.py index 3c162fc41b7..883a5057e13 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_source_copies.py b/tests/unit/test_worker_source_copies.py new file mode 100644 index 00000000000..308db871177 --- /dev/null +++ b/tests/unit/test_worker_source_copies.py @@ -0,0 +1,536 @@ +"""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 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.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) + + +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} + self.refusals: dict[str, str] = {} + 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: + raise WorkerReadRefused(self.refusals[scope.resource_id]) + 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.directory: LiveSourceDirectory | None = LiveSourceDirectory( + source=self._get_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.source_store, "get_source", self._get_source) + monkeypatch.setattr(w.source_store, "source_documents", self._documents) + monkeypatch.setattr(w.connected_accounts, "_standing", AsyncMock()) + monkeypatch.setattr(w.aliases, "verified_spellings", AsyncMock(return_value=["alice"])) + monkeypatch.setattr(w.aliases, "invalidate", lambda *_: None) + monkeypatch.setattr(w.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 _documents(self, org: str, namespace: str, tag: str) -> list[dict[str, Any]]: + assert (org, namespace, tag) == ("org", _MIRROR, f"source-id:{_SOURCE}") + return [{"source_uri": uri} for uri in sorted(self.stored)] + + 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_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 + assert set(result.kind_state[source_sync_worker._COPIES]) == {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_an_unselected_copy_is_retired(world) -> None: + stray = resource_uri(str(_SOURCE), "doc:gone") + world.stored = {_uri(i) for i in _IDS} | {stray} + recent = datetime.now(UTC) - timedelta(seconds=60) + await world.turn(_detail(recent, listed=recent.isoformat())) + assert world.retired == [stray] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("lost", ["directory", "writer", "approval", "account"]) +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 + elif lost == "approval": + world.approval = 8 + else: + world.account_active = False + result, _ = await world.turn(_detail(old)) + assert result.status in ("unavailable", "owner_unavailable") and not result.complete + assert not world.worker.calls and not world.retired and not world.listings + + +@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) + monkeypatch.setattr(connected_accounts, "own_subject", lambda _auth: _subject(state.subject)) + from server.knowledge.store import sources as source_store + + async def latest(org: str, namespace: str, name: str) -> Any: + 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)} + + +@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_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")] From bb02ac0fc6b902530eb9d618427673041fe95fd7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 19:06:38 +0000 Subject: [PATCH 02/18] Worker copies sync in the workers process and retire only on the worker's own denial The workers child and `loom knowledge sync` open the source worker directory, so their sync turns reach the provisioned workers. A turn reads exactly the selected copies' addresses instead of the newest page of documents, and a page of unselected leftovers apart. A copy is retired only on the worker's own 403, once the registration and the owner's authority are read again and hold; a denial Loom's own checks answer ends the turn with every copy kept. A resource left without a copy waits its refresh interval or half the stale window before it is read again. An approval or worker account that no longer matches the registration ends it under the sources lease: the row goes inactive, its copies are queued for retirement and its state reads owner_inactive. A copy request resolves its authority before it is sent and after the reply, no longer three times. The mirror read gate's registration read returns only worker rows whose stored registration names an owner-only copy mode. The setup `mode` description fits the generated references whole, and the docs say what removal does with the setting off. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 44 ++- docs/architecture/rolling-upgrades.md | 33 ++- docs/features/knowledge.md | 6 +- docs/reference/operations/knowledge.md | 4 +- sdk/go/wire/models.gen.go | 2 +- sdk/typescript/src/generated/ops.ts | 4 +- server/cli/knowledge.py | 16 +- server/knowledge/api/models_worker_setup.py | 6 +- server/knowledge/app/mcp_worker_read.py | 13 +- server/knowledge/app/source_sync_worker.py | 182 +++++++++---- server/knowledge/store/source_access.py | 17 +- server/knowledge/store/sources.py | 49 ++++ server/worker_main.py | 31 ++- .../test_mcp_worker_source_history_ch.py | 14 - tests/unit/test_mcp_worker_read.py | 32 ++- tests/unit/test_mcp_worker_setup_register.py | 13 + tests/unit/test_worker_cell_observation.py | 52 ++++ tests/unit/test_worker_copy_store_sql.py | 124 +++++++++ tests/unit/test_worker_source_copies.py | 250 +++++++++++++++++- 19 files changed, 739 insertions(+), 153 deletions(-) create mode 100644 tests/unit/test_worker_copy_store_sql.py diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 692219d678c..e19ca39940c 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -14,9 +14,10 @@ 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, 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. +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 @@ -383,8 +384,9 @@ A turn reads the owner's standing first: an active directory account, no revocat since the registration, and a writer grant in the collection. It then needs the collection's current approval of the registration's mode and the owner's worker account at the registered generation. Each worker request resolves that authority again as a -live read does (`CurrentRead` with the `stored` purpose), with the owner as requester, -before the request and after the reply. A resource with no copy, or a selected-refresh +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 in a share of two requests per worker that live reads never wait on; a reply with the stored digest writes nothing. Every other copy whose access was last confirmed more than half of @@ -392,23 +394,41 @@ nothing. Every other copy whose access was last confirmed more than half of returns the digest only. The oldest confirmation goes first. Copies count against the pass's mirror document bound; checks count against its time alone. -A worker `denied` retires that resource's copy. `reconnect`, `overloaded` and +A denial the worker itself answers (its 403) retires that resource's copy, once the +registration, the owner's standing, the approval and the worker account are read again +and still hold. Any other `denied` is Loom's own: authority that changed during the +turn, or a reply that failed validation (a malformed body, another content type, a time +outside the grant). It ends the turn with every copy kept. `reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; `timeout` and `unsupported` keep that -resource's copy and let the turn go on. The mirror read gate needs a listing no older +resource's copy and let the turn go on. A resource left without a copy, denied or +unsupported, is read again only after its refresh interval or, for a snapshot, 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. 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. +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 +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 51fb94c77d4..3f6850edd2e 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1138,20 +1138,25 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `tests/unit/test_mcp_worker_setup_register.py` checks N's writer, and the mixed-version gate does not check this rule. -75. **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 and retirement worker queue and delete no worker copy. So the operator - turns the setting on only once every replica runs N; it is off by default, and with it - off N behaves as N-1 for these rows, so the rollout itself writes no copy. 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. 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. +75. **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 and retirement worker queue and delete 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. 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 diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 2c58f51d0a8..24559a3021d 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -327,9 +327,9 @@ document is counted yet (a sync turn running at that moment may still write one) 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 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 +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/operations/knowledge.md b/docs/reference/operations/knowledge.md index ecaec0210fc..0a60550b7cc 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -971,7 +971,7 @@ Preview a 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` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every `interval_seconds`. | +| `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` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | | `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. | @@ -1020,7 +1020,7 @@ Register the worker source a preview showed, with its fingerprint and evidence. | `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` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every `interval_seconds`. | +| `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` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | | `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. | diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 8edaca0f59e..7d0caafd720 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: 7e596d0d638d21dce1fc5b90a2b4defaf8ae6df2ebe11c6c637a5b95108ed687 +// Registry model schema SHA-256: cc51a5b844ba005bbc7e2606a98771db9c73c819fcab5cfd97689d91b4b05df7 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 2582269b291..7efd5596bb1 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4933,7 +4933,7 @@ 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` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every ` */ + /** `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"; /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ interval_seconds?: number | null; @@ -5025,7 +5025,7 @@ 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` keeps one copy of each resource for the owner alone, and `selected_refresh` replaces it every ` */ + /** `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"; /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ interval_seconds?: number | null; diff --git a/server/cli/knowledge.py b/server/cli/knowledge.py index d582f62e063..d77c7747ef1 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/knowledge/api/models_worker_setup.py b/server/knowledge/api/models_worker_setup.py index 9996a04c672..1b3df62ab47 100644 --- a/server/knowledge/api/models_worker_setup.py +++ b/server/knowledge/api/models_worker_setup.py @@ -186,10 +186,8 @@ 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` keeps" - " one copy of each resource for the owner alone, and `selected_refresh` replaces it" - " every `interval_seconds`. Both answer `unavailable` while the deployment keeps no" - " worker copies." + 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, diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py index 92bd9f9ceed..f0fac875ff7 100644 --- a/server/knowledge/app/mcp_worker_read.py +++ b/server/knowledge/app/mcp_worker_read.py @@ -64,9 +64,11 @@ def live_grant_seconds(live_timeout_s: float) -> int: class WorkerReadRefused(Exception): - def __init__(self, reason: WorkerFailure) -> None: + def __init__(self, reason: WorkerFailure, *, status: int | None = None) -> None: super().__init__(reason) self.reason = reason + # The worker's own HTTP status when it answered the refusal; None when Loom refused. + self.status = status @dataclass(frozen=True, repr=False) @@ -281,7 +283,9 @@ async def _post( 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" - raise WorkerReadRefused(_STATUSES.get(response.status_code, other)) + raise WorkerReadRefused( + _STATUSES.get(response.status_code, other), status=response.status_code + ) if ( response.headers.get("content-encoding", "identity") != "identity" or response.headers.get("content-type", "").partition(";")[0] != "application/json" @@ -335,15 +339,14 @@ async def run( async def copy( self, scope: WorkerReadScope, *, require_current: Callable[[], Awaitable[WorkerReadScope]] ) -> WorkerReading: - """Read `scope`'s resource for its stored copy, in the copy share. `require_current` - checks `scope` before the request and after the reply.""" + """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), - check_first=True, ) async def check_access( diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 7c587bfc7f2..a18bbda6b7a 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -9,30 +9,38 @@ access checked (a digest, no content). The oldest confirmation goes first, and only copies spend the pass's document bound. -A worker `denied` retires that resource's copy. A `timeout` or `unsupported` answer keeps -that resource's copy and the turn goes on; any other refusal keeps every copy, ends the -turn and records no listing. The listing the mirror read gate needs records the oldest +A denial the worker itself answers (its 403) retires that resource's copy, once the +registration and the owner's authority are read again and still hold; any other denial +is Loom's own check or a reply that failed validation, and ends the turn with every copy +kept. A `timeout` or `unsupported` answer keeps that resource's copy and the turn goes on; +any other refusal keeps every copy, ends the turn and records no listing. A resource left +without a copy is tried again after a wait: its refresh interval, or half the stale +window. 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, whatever stopped its check. 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`.""" +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 +from typing import Any, Literal from uuid import UUID from server.auth import aliases, authz from server.core.ch import own_write_reads, sequential_reads from server.core.errors import ValidationError -from server.knowledge.app import connected_accounts, mirrors, private_sync +from server.knowledge.app import connected_accounts, mirrors, private_sync, source_push 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, @@ -41,12 +49,10 @@ from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory from server.knowledge.app.mcp_worker_read import ( WorkerAccess, - WorkerReadChannel, WorkerReading, WorkerReadRefused, - WorkerReadScope, ) -from server.knowledge.app.mcp_worker_runtime import current_directory +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 ( @@ -68,8 +74,8 @@ 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; and the -# confirmation time the last recorded listing carries. +# 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" @@ -116,27 +122,69 @@ async def owner_standing(src: KnowledgeSource) -> bool: return await _writer(src) -async def account_current(src: KnowledgeSource, directory: LiveSourceDirectory) -> bool: - """The collection's approval of the registration's mode and the owner's worker account - at the registered generation, as `CurrentRead` checks them for each request.""" +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 False + 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 ) - if approval != config.approval_generation: - return False record = await directory.connection( src.org, src.namespace, src.owner_subject, config.worker_id, config.owner_connection_id ) - return ( - record is not None - and record.active - and record.binding.connection_generation == config.owner_connection_generation - and record.binding.profile_digest == config.profile_digest - ) + 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) -> None: + """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)) + pending = await source_ops._queue_retirement(current) + await source_push.retire(current) + await source_store.insert_source( + dataclasses.replace( + current, active=False, pending_delete=pending or current.pending_delete + ) + ) + await source_store.write_state( + current.org, + current.namespace, + current.name, + state_value="", + detail={"status": "owner_inactive"}, + ) + raise sync.SourceGone(sync._cursor_of(src)) def _at(raw: Any) -> datetime | None: @@ -158,7 +206,8 @@ class _Copy: def copy_due(self, interval: int | None, now: datetime) -> bool: if not self.stored: - return True + 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) @@ -193,12 +242,19 @@ def __init__( self.result = result self.config, self.selected = decode_worker_source(src) + 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: return ReaderStanding(self.src.owner_subject) if await _writer(self.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), @@ -215,16 +271,6 @@ async def _exchange( channel = directory.worker(scope.worker_id) if channel is None: raise WorkerReadRefused("unavailable") - return await self._send(channel, scope, current, content=content) - - async def _send( - self, - channel: WorkerReadChannel, - scope: WorkerReadScope, - current: CurrentRead, - *, - content: bool, - ) -> WorkerReading | WorkerAccess: if content: return await channel.copy(scope, require_current=current.resolve) return await channel.check_access(scope, require_current=current.resolve) @@ -260,6 +306,8 @@ async def _write(self, copy: _Copy, reading: WorkerReading) -> None: 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 @@ -274,51 +322,72 @@ async def visit(self, copy: _Copy, now: datetime) -> bool: try: answer = await self._exchange(copy.item, content=content) except WorkerReadRefused as refusal: - return await self._refused(copy, refusal.reason) + 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: + copy.entry["retry_at"] = (asked + self._wait()).isoformat() if copy.stored: copy.entry["verified_at"] = asked.isoformat() return True - async def _refused(self, copy: _Copy, reason: str) -> bool: + 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 _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetime) -> bool: + reason, result = refusal.reason, self.result if reason == "denied": - # The owner's account no longer reads it: its copy goes. + # Only the worker's own denial, under authority read again just now, says the + # owner's account no longer reads the resource. Loom's own refusal (authority + # that changed meanwhile, a reply that failed validation) keeps every copy. + if refusal.status != 403 or not await self._authority_holds(): + result.fail("denied", "denied") + return False if copy.stored and await sync.retire(self.src, copy.uri): - self.result.removed += 1 + result.removed += 1 copy.stored = False copy.entry.clear() + copy.entry["retry_at"] = (asked + self._wait()).isoformat() + return True + if reason == "unsupported" and not copy.stored: + # Nothing to keep: the resource waits before it is read again. + copy.entry["retry_at"] = (asked + self._wait()).isoformat() + result.note = reason return True # Every other refusal keeps the copy, unconfirmed. One resource's timeout or # unsupported answer lets the others go on; the worker at capacity, the owner's # account to link again or the worker unavailable ends the turn. if reason in ("timeout", "unsupported"): - self.result.complete = False - self.result.note = reason + result.complete = False + result.note = reason return True - self.result.fail(reason, reason) + result.fail(reason, reason) return False async def _known_copies( src: KnowledgeSource, selected: tuple[ResourceIdentity, ...], recorded: dict[str, Any] -) -> tuple[list[_Copy], set[str]]: - """Each selected resource's copy, and the stored addresses no resource selects.""" +) -> tuple[list[_Copy], list[str]]: + """Each selected resource's copy, and up to a page of stored addresses no resource + selects.""" + uris = [resource_uri(src.source_id, item.id) for item in selected] + tag = source_id_tag(src.source_id) with sequential_reads(): - docs = await source_store.source_documents( - src.org, src.mirror, source_id_tag(src.source_id) - ) - stored = {str(d["source_uri"]) for d in docs} + stored = await source_store.copies_at(src.org, src.mirror, tag, uris) + unselected = await source_store.copies_besides(src.org, src.mirror, tag, uris) copies = [] - for item in selected: - uri = resource_uri(src.source_id, item.id) + for item, uri in zip(selected, uris, strict=True): raw = recorded.get(resource_digest(item.id)) - entry = dict(raw) if isinstance(raw, dict) and uri in stored else {} + raw = raw if isinstance(raw, dict) else {} + entry = dict(raw) if uri in stored else {k: raw[k] for k in ("retry_at",) if k in raw} copies.append(_Copy(item, uri, uri in stored, entry)) - return copies, stored - {c.uri for c in copies} + return copies, unselected async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: @@ -347,7 +416,7 @@ async def _sync_copies( listed = str(detail.get(_LISTED) or "") result.kind_state[_LISTED] = listed _keep(result, copies) - for uri in sorted(unselected): + for uri in unselected: if await sync.retire(src, uri): result.removed += 1 now = datetime.now(UTC) @@ -363,7 +432,10 @@ async def _sync_copies( if directory is None: result.fail("unavailable", "unavailable") return - if not await owner_standing(src) or not await account_current(src, directory): + held = await authority(src, directory) + if held == "gone": + await _end_registration(src, directory) + if held != "current" or not await owner_standing(src): result.fail("owner_unavailable", "owner_unavailable") return await _visit_due(_Turn(src, directory, run, result), due, now) @@ -386,9 +458,7 @@ async def _visit_due(work: _Turn, due: list[_Copy], now: datetime) -> None: 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.stored and c.entry - } + result.kind_state[_COPIES] = {resource_digest(c.item.id): c.entry for c in copies if c.entry} async def _vouch( diff --git a/server/knowledge/store/source_access.py b/server/knowledge/store/source_access.py index b7e74c1919e..f005b29e669 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -37,6 +37,16 @@ ) +# 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 @@ -45,12 +55,13 @@ class ReadHead(NamedTuple): async def active_sources( org: str, namespaces: list[str], *, workers: bool = False, ch: _CHClient | None = None ) -> list[dict[str, Any]]: - """The active mirrored registrations; with `workers`, worker rows too, which the caller - decodes before it trusts one.""" + """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 credential_mode = 'worker')" if workers else native + 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 " diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index ba9f8887d65..46b4ebc6759 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -645,6 +645,53 @@ 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} + + +async def copies_besides( + org: str, namespace: str, tag: str, uris: list[str], *, ch: _CHClient | None = None +) -> list[str]: + """Up to DOCUMENTS_LIMIT live documents the sync wrote under `tag` at an address + outside `uris`, by address.""" + 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 NOT IN {uris:Array(String)} AND has(tags, {tag:String}) " + "AND actor = {actor:String} AND superseded_at IS NULL " + f"ORDER BY source_uri LIMIT {DOCUMENTS_LIMIT}", + params={ + "org": org, + "ns": namespace, + "uris": sorted(set(uris)), + "tag": tag, + "actor": SYNC_WORKER_ACTOR, + }, + ) + 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/tests/integration/test_mcp_worker_source_history_ch.py b/tests/integration/test_mcp_worker_source_history_ch.py index 8f771a3d667..07967aa71bc 100644 --- a/tests/integration/test_mcp_worker_source_history_ch.py +++ b/tests/integration/test_mcp_worker_source_history_ch.py @@ -260,20 +260,6 @@ async def test_native_mirror_inventory_excludes_legacy_worker_history(registry: ] -async def test_worker_copy_inventory_adds_worker_rows_alone(registry: Registry) -> None: - set_query_tag("test.mcp-worker-source-history.worker-mirrors") - await registry.seed("damaged", worker=True, legacy_only=True, active=True, shared=True) - native_id, _, _ = await registry.seed("native", worker=False, active=True, shared=True) - worker_id, _, _ = await registry.seed("worker", worker=True, active=True) - found = await source_access.active_sources( - registry.org, [NAMESPACE], workers=True, ch=registry.ch - ) - assert [(row["name"], row["credential_mode"], row["source_id"]) for row in found] == [ - ("native", "shared", native_id), - ("worker", "worker", worker_id), - ] - - async def test_worker_history_is_found_by_owner_in_any_namespace(registry: Registry) -> None: set_query_tag("test.mcp-worker-source-history.owners") await registry.seed("elsewhere", worker=True, namespace="other-namespace") diff --git a/tests/unit/test_mcp_worker_read.py b/tests/unit/test_mcp_worker_read.py index 149ee75967e..668d391e6a5 100644 --- a/tests/unit/test_mcp_worker_read.py +++ b/tests/unit/test_mcp_worker_read.py @@ -511,20 +511,36 @@ def copy(): await asyncio.gather(*held, return_exceptions=True) self.assertEqual(paths, ["/v1/live"] * 3) - async def test_a_copy_checks_its_scope_before_it_sends(self) -> None: - sent: list[str] = [] - - def answer(request: httpx.Request) -> httpx.Response: - sent.append(request.url.path) - return httpx.Response(500) + 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) - channel = self._channel(httpx.MockTransport(answer)) + 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) - self.assertEqual(sent, []) + sent.assert_called_once() + self.assertEqual(checks, 1) + + async def test_a_refusal_names_the_workers_status_or_none(self) -> None: + channel = self._channel(httpx.MockTransport(lambda request: httpx.Response(403))) + with self.assertRaises(WorkerReadRefused) as answered: + await channel.copy(self.scope, require_current=self._authorized) + self.assertEqual((answered.exception.reason, answered.exception.status), ("denied", 403)) + + def wrong_type(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, headers={"Content-Type": "text/html"}, content=b"{}") + + channel = self._channel(httpx.MockTransport(wrong_type)) + with self.assertRaises(WorkerReadRefused) as refused: + await channel.copy(self.scope, require_current=self._authorized) + self.assertEqual((refused.exception.reason, refused.exception.status), ("denied", None)) async def test_a_failed_check_frees_its_slot(self) -> None: for status, reason in ((503, "unavailable"), (403, "denied")): diff --git a/tests/unit/test_mcp_worker_setup_register.py b/tests/unit/test_mcp_worker_setup_register.py index a54f3bc47e8..cdfcb1239bd 100644 --- a/tests/unit/test_mcp_worker_setup_register.py +++ b/tests/unit/test_mcp_worker_setup_register.py @@ -1084,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_worker_cell_observation.py b/tests/unit/test_worker_cell_observation.py index 9c37f211f5e..e1c26cd1cc9 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 00000000000..87afabcf4f4 --- /dev/null +++ b/tests/unit/test_worker_copy_store_sql.py @@ -0,0 +1,124 @@ +"""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, the leftovers beside +them, 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:]) + besides = asyncio.run(store.copies_besides("org", _MIRROR, _TAG, uris[1:], ch=ch)) + assert besides == [uris[0]] + 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 index 308db871177..b90fbe45194 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import dataclasses import hashlib import time @@ -118,7 +119,9 @@ class _Worker: 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] = {} + self.statuses: dict[str, int | None] = {} self.calls: list[tuple[str, str]] = [] async def _answer(self, op: str, scope: Any, require_current: Any) -> str: @@ -126,7 +129,9 @@ async def _answer(self, op: str, scope: Any, require_current: Any) -> str: assert (scope.requester, scope.source_id) == ("alice", _SOURCE) self.calls.append((op, scope.resource_id)) if scope.resource_id in self.refusals: - raise WorkerReadRefused(self.refusals[scope.resource_id]) + reason = self.refusals[scope.resource_id] + status = self.statuses.get(scope.resource_id, 403 if reason == "denied" else None) + raise WorkerReadRefused(reason, status=status) return self.texts[scope.resource_id] async def copy(self, scope: Any, *, require_current: Any) -> WorkerReading: @@ -169,8 +174,11 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: 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._get_source, + source=self._directory_source, connection=self._connection, enrollment=AsyncMock(return_value=None), worker=lambda worker: self.worker if worker == _WORKER else None, @@ -179,8 +187,10 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: ) 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, "source_documents", self._documents) + monkeypatch.setattr(w.source_store, "copies_at", self._copies_at) + monkeypatch.setattr(w.source_store, "copies_besides", self._copies_besides) monkeypatch.setattr(w.connected_accounts, "_standing", AsyncMock()) monkeypatch.setattr(w.aliases, "verified_spellings", AsyncMock(return_value=["alice"])) monkeypatch.setattr(w.aliases, "invalidate", lambda *_: None) @@ -193,9 +203,21 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: 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 _documents(self, org: str, namespace: str, tag: str) -> list[dict[str, Any]]: + 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 _copies_besides(self, org, namespace, tag, uris) -> list[str]: assert (org, namespace, tag) == ("org", _MIRROR, f"source-id:{_SOURCE}") - return [{"source_uri": uri} for uri in sorted(self.stored)] + return sorted(self.stored - set(uris)) async def _grant(self, org: str, namespace: str, subject: str) -> Role | None: return self.role @@ -311,7 +333,9 @@ async def test_a_denied_resource_loses_its_copy_and_the_rest_are_vouched(world) world.worker.refusals["doc:one"] = "denied" result, _ = await world.turn(_detail(old)) assert world.retired == [_uri("doc:one")] and result.removed == 1 - assert set(result.kind_state[source_sync_worker._COPIES]) == {resource_digest("doc:two")} + 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 @@ -361,7 +385,7 @@ async def test_an_unselected_copy_is_retired(world) -> None: @pytest.mark.asyncio -@pytest.mark.parametrize("lost", ["directory", "writer", "approval", "account"]) +@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) @@ -369,15 +393,92 @@ async def test_without_the_owners_authority_nothing_is_read_or_retired(world, lo world.directory = None elif lost == "writer": world.role = Role.VIEWER - elif lost == "approval": - world.approval = 8 else: - world.account_active = False + world.permitted = False # this process's routes file does not provision the profile result, _ = await world.turn(_detail(old)) assert result.status in ("unavailable", "owner_unavailable") and not result.complete assert not world.worker.calls and not world.retired and not world.listings +@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) + monkeypatch.setattr(w.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: @@ -534,3 +635,132 @@ async def erase(org, namespace, owner, *, before): 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.statuses["doc:one"] = None # 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"] From 7437654ef373f5c92fe19c53cd0b527f2cef6001 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 19:51:46 +0000 Subject: [PATCH 03/18] A worker copy is retired only on the worker's named upstream denial The source worker answers the upstream's own HTTP 403 to a read with {"status": "denied", "reason": "upstream_access"}; every refusal it makes itself (a grant that fails to verify, a binding or record that no longer matches, a document naming another resource, a redirect, a refused closing DELETE) stays a plain denied. Loom reads that body bounded and strictly, and its sync retires a copy only on it, after the registration and the owner's authority are read again; a plain 403 ends the turn with every copy kept. A worker build without the reason never causes a retirement. The mirror read gate skips a worker row its reader does not own before any registry read, using the row's owner and the reader's own subject read once per plan. A registration whose authority is gone ends through the same helper a connected source uses, and the leftover-copy retirement stops at the pass budget. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 31 +++--- docs/architecture/rolling-upgrades.md | 10 +- server/knowledge/app/mcp_worker_read.py | 46 ++++++-- server/knowledge/app/source_access.py | 25 ++++- server/knowledge/app/source_sync_connected.py | 21 +--- server/knowledge/app/source_sync_worker.py | 49 ++++----- server/knowledge/app/sources.py | 13 +++ server/knowledge/store/source_access.py | 4 +- source_worker/README.md | 15 ++- .../loom_source_worker/direct_backend.py | 2 + .../loom_source_worker/http_service.py | 11 +- .../loom_source_worker/mcp_client.py | 17 +-- .../loom_source_worker/read_service.py | 5 +- source_worker/tests/test_mcp_client.py | 14 ++- source_worker/tests/test_protocol_servers.py | 15 ++- source_worker/tests/test_read_service.py | 50 +++++++++ .../test_mcp_worker_source_history_ch.py | 1 + tests/unit/test_mcp_worker_read.py | 39 ++++--- tests/unit/test_worker_source_copies.py | 100 ++++++++++++++++-- 19 files changed, 360 insertions(+), 108 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index e19ca39940c..f381c72576d 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -394,20 +394,25 @@ nothing. Every other copy whose access was last confirmed more than half of returns the digest only. The oldest confirmation goes first. Copies count against the pass's mirror document bound; checks count against its time alone. -A denial the worker itself answers (its 403) retires that resource's copy, once the +Only the worker's report that the upstream refused the account retires a copy: 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 +read ([source worker responses](../../source_worker/README.md#responses)). Even then the registration, the owner's standing, the approval and the worker account are read again -and still hold. Any other `denied` is Loom's own: authority that changed during the -turn, or a reply that failed validation (a malformed body, another content type, a time -outside the grant). It ends the turn with every copy kept. `reconnect`, `overloaded` and -`unavailable` end the turn and keep every copy; `timeout` and `unsupported` keep that -resource's copy and let the turn go on. A resource left without a copy, denied or -unsupported, is read again only after its refresh interval or, for a snapshot, 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. Nothing confirms a copy while -the owner's standing, the approval or the worker account fails, so they fail closed -together. +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; its +copies stop being served once their access goes unconfirmed past the stale window. +`reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; +`timeout` and `unsupported` keep that resource's copy and let the turn go on. A resource +left without a copy, denied or unsupported, is read again only after its refresh +interval or, for a snapshot, 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. 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 diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 3f6850edd2e..a4669575b39 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1154,9 +1154,13 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline 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. 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. + 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 + answer, 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. 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 diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py index f0fac875ff7..db20a465cdc 100644 --- a/server/knowledge/app/mcp_worker_read.py +++ b/server/knowledge/app/mcp_worker_read.py @@ -64,11 +64,25 @@ def live_grant_seconds(live_timeout_s: float) -> int: class WorkerReadRefused(Exception): - def __init__(self, reason: WorkerFailure, *, status: int | None = None) -> None: + def __init__(self, reason: WorkerFailure, *, upstream_access: bool = False) -> None: super().__init__(reason) self.reason = reason - # The worker's own HTTP status when it answered the refusal; None when Loom refused. - self.status = status + # 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 and reason == "denied" + + +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) @@ -174,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 @@ -280,12 +314,12 @@ 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" - raise WorkerReadRefused( - _STATUSES.get(response.status_code, other), status=response.status_code - ) + raise WorkerReadRefused(_STATUSES.get(response.status_code, other)) if ( response.headers.get("content-encoding", "identity") != "identity" or response.headers.get("content-type", "").partition(";")[0] != "application/json" diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 4f152e8b04b..853852decab 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -88,6 +88,9 @@ 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, read once per plan for its worker rows; "" 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]: @@ -395,11 +398,24 @@ 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 per 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 connected_accounts, source_sync_worker + 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 @@ -411,6 +427,10 @@ async def _worker_copy_eligible(plan: ReadPlan, row: dict[str, Any]) -> bool: 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 @@ -422,8 +442,7 @@ async def _worker_copy_eligible(plan: ReadPlan, row: dict[str, Any]) -> bool: ): return False await check_authorized(auth, Role.VIEWER, plan.org, row["namespace"]) - owner_org, subject = await connected_accounts.own_subject(auth) - if (owner_org, subject) != (source.org, source.owner_subject): + if (plan.org, subject) != (source.org, source.owner_subject): return False if not await source_sync_worker.account_current(source, directory): return False diff --git a/server/knowledge/app/source_sync_connected.py b/server/knowledge/app/source_sync_connected.py index 56857965aa2..76c01d21c1b 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 index a18bbda6b7a..423f5c37d3c 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -9,15 +9,16 @@ access checked (a digest, no content). The oldest confirmation goes first, and only copies spend the pass's document bound. -A denial the worker itself answers (its 403) retires that resource's copy, once the -registration and the owner's authority are read again and still hold; any other denial -is Loom's own check or a reply that failed validation, and ends the turn with every copy -kept. A `timeout` or `unsupported` answer keeps that resource's copy and the turn goes on; -any other refusal keeps every copy, ends the turn and records no listing. A resource left -without a copy is tried again after a wait: its refresh interval, or half the stale -window. 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, whatever stopped its check. +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; any other refusal +keeps every copy, ends the turn and records no listing. A resource left without a copy +is tried again after a wait: its refresh interval, or half the stale window. 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, whatever stopped its check. 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 @@ -38,7 +39,7 @@ from server.auth import aliases, authz from server.core.ch import own_write_reads, sequential_reads from server.core.errors import ValidationError -from server.knowledge.app import connected_accounts, mirrors, private_sync, source_push +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 ( @@ -170,20 +171,7 @@ async def _end_registration(src: KnowledgeSource, directory: LiveSourceDirectory current = await registered(src) if current is None or await authority(current, directory) != "gone": raise sync.SourceGone(sync._cursor_of(src)) - pending = await source_ops._queue_retirement(current) - await source_push.retire(current) - await source_store.insert_source( - dataclasses.replace( - current, active=False, 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)) @@ -343,10 +331,11 @@ async def _authority_holds(self) -> bool: async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetime) -> bool: reason, result = refusal.reason, self.result if reason == "denied": - # Only the worker's own denial, under authority read again just now, says the - # owner's account no longer reads the resource. Loom's own refusal (authority - # that changed meanwhile, a reply that failed validation) keeps every copy. - if refusal.status != 403 or not await self._authority_holds(): + # 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(): result.fail("denied", "denied") return False if copy.stored and await sync.retire(self.src, copy.uri): @@ -417,6 +406,10 @@ async def _sync_copies( result.kind_state[_LISTED] = listed _keep(result, copies) for uri in unselected: + if run.budget.exhausted(): + result.mark(sync.TurnMark.PASS_BOUND) + return + pass_context.check_stop() if await sync.retire(src, uri): result.removed += 1 now = datetime.now(UTC) diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 3d4abbc3786..e758bc75909 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -1309,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/store/source_access.py b/server/knowledge/store/source_access.py index f005b29e669..72256242f83 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -63,8 +63,8 @@ async def active_sources( 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 {rows} ORDER BY namespace, name", params={"org": org, "names": sorted(set(namespaces))}, diff --git a/source_worker/README.md b/source_worker/README.md index 77aa4c40e62..75b6ad4c03a 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -362,7 +362,20 @@ 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 read itself with HTTP 403, the worker answers `403` with +`{"status": "denied", "reason": "upstream_access"}`, the upstream's word that the +account cannot read the resource. Loom retires a stored copy only on that body. 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) stays a plain `denied`, and so +does an upstream 403 to the closing session `DELETE`. A worker build without the reason +never sends it, so Loom never retires a copy on its answer; the copy stops being served +once its access goes unconfirmed past Loom's stale window. + +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 63d609737f0..5ed6f65518c 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 092cf3f5439..14f34e815f4 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 50c72922b43..bb49d09918d 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,10 @@ 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 a session request is `forbidden`, its +# verdict that the account cannot read, apart from every `denied` 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 +85,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,9 +103,9 @@ 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"}) +_AUTHORITY_REFUSALS: frozenset[ErrorCode] = frozenset({"denied", "forbidden", "reconnect"}) def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = True) -> None: @@ -120,8 +123,10 @@ def _check_response( status = response.status_code if status == 401: raise MCPSourceError("reconnect") - if response.is_redirect or status == 403: + if response.is_redirect or (status == 403 and method == "DELETE"): raise MCPSourceError("denied") + if status == 403: + raise MCPSourceError("forbidden") # A throttled or timed-out upstream is temporary, like a server error. if status in {408, 429} or 500 <= status < 600: raise MCPSourceError("unavailable") diff --git a/source_worker/loom_source_worker/read_service.py b/source_worker/loom_source_worker/read_service.py index 4fecd9d209e..3a73318201c 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 and code == "denied" @dataclass(frozen=True, repr=False) diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index f04d9d5a77c..1c0d13ac8be 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -256,7 +256,7 @@ def _client(source: _Source, **config: Any) -> MCPSourceClient: @pytest.mark.asyncio @pytest.mark.parametrize( ("status", "code"), - [(401, "reconnect"), (403, "denied"), (408, "unavailable"), (429, "unavailable")], + [(401, "reconnect"), (403, "forbidden"), (408, "unavailable"), (429, "unavailable")], ) async def test_maps_the_upstream_http_refusal(status: int, code: str, pin: list[str]) -> None: def refuse(request: httpx.Request) -> httpx.Response: @@ -1304,3 +1304,15 @@ 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", "code"), [("POST", "forbidden"), ("GET", "forbidden"), ("DELETE", "denied")] +) +def test_only_a_session_requests_403_is_the_upstreams_access_refusal( + method: str, code: str +) -> None: + # A refused 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) diff --git a/source_worker/tests/test_protocol_servers.py b/source_worker/tests/test_protocol_servers.py index cb02c47e0f4..aec296883f0 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -287,7 +287,7 @@ def grant(target: ReadBinding, operation: str) -> str: ("tool", "discover"), ], ) -@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "denied")]) +@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "forbidden")]) async def test_upstream_http_refusal_at_sdk_boundary( mode: str, phase: str, status: int, code: mcp_client.ErrorCode, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -404,8 +404,11 @@ 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 account names its reason. + ("upstream-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,7 +466,12 @@ 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, + "upstream-403": 403, + "missing-endpoint": 404, + } if method == "initialize" and faulted and upstream_fault in upstream: assert session is None refused = upstream[upstream_fault] @@ -545,7 +553,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 7292549b35f..594579f16dd 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -254,6 +254,56 @@ 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"}) + # Any other code never carries the reason. + self.assertFalse(ReadFailure("unsupported", upstream_access=True).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 07967aa71bc..0bbdd3d9a3f 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/test_mcp_worker_read.py b/tests/unit/test_mcp_worker_read.py index 668d391e6a5..90d57cc4629 100644 --- a/tests/unit/test_mcp_worker_read.py +++ b/tests/unit/test_mcp_worker_read.py @@ -528,19 +528,32 @@ async def changed() -> WorkerReadScope: sent.assert_called_once() self.assertEqual(checks, 1) - async def test_a_refusal_names_the_workers_status_or_none(self) -> None: - channel = self._channel(httpx.MockTransport(lambda request: httpx.Response(403))) - with self.assertRaises(WorkerReadRefused) as answered: - await channel.copy(self.scope, require_current=self._authorized) - self.assertEqual((answered.exception.reason, answered.exception.status), ("denied", 403)) - - def wrong_type(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, headers={"Content-Type": "text/html"}, content=b"{}") - - channel = self._channel(httpx.MockTransport(wrong_type)) - with self.assertRaises(WorkerReadRefused) as refused: - await channel.copy(self.scope, require_current=self._authorized) - self.assertEqual((refused.exception.reason, refused.exception.status), ("denied", None)) + 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")): diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index b90fbe45194..ab90fcf727c 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -121,7 +121,8 @@ 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] = {} - self.statuses: dict[str, int | None] = {} + # 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: @@ -130,8 +131,8 @@ async def _answer(self, op: str, scope: Any, require_current: Any) -> str: self.calls.append((op, scope.resource_id)) if scope.resource_id in self.refusals: reason = self.refusals[scope.resource_id] - status = self.statuses.get(scope.resource_id, 403 if reason == "denied" else None) - raise WorkerReadRefused(reason, status=status) + 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: @@ -425,7 +426,9 @@ async def state(org, namespace, name, *, state_value, detail) -> None: monkeypatch.setattr(w.source_ops, "sources_lease", lease) monkeypatch.setattr(w.source_ops, "_queue_retirement", queue) - monkeypatch.setattr(w.source_push, "retire", AsyncMock()) + 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 @@ -516,10 +519,18 @@ def gate(monkeypatch: pytest.MonkeyPatch, world: _World) -> Any: 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) - monkeypatch.setattr(connected_accounts, "own_subject", lambda _auth: _subject(state.subject)) + 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) @@ -536,7 +547,12 @@ def _plan(state: Any) -> source_access.ReadPlan: return plan -_ROW = {"namespace": "team", "name": "handbook", "source_id": str(_SOURCE)} +_ROW = { + "namespace": "team", + "name": "handbook", + "source_id": str(_SOURCE), + "owner_subject": "alice", +} @pytest.mark.asyncio @@ -554,6 +570,27 @@ async def test_another_reader_is_refused_the_copies(gate) -> None: 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) @@ -652,7 +689,7 @@ async def test_a_denial_loom_answers_keeps_every_copy(world, ending, cause) -> N async def check(scope, *, require_current): if cause == "malformed": - world.worker.statuses["doc:one"] = None # a reply that failed validation + world.worker.upstream["doc:one"] = False # a reply that failed validation try: return await original(scope, require_current=require_current) except WorkerReadRefused: @@ -764,3 +801,52 @@ async def run_sync(**_kw: Any) -> Any: 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_unselected_copies_wait_once_the_pass_is_spent(world) -> None: + stray = resource_uri(str(_SOURCE), "doc:gone") + world.stored = {_uri(i) for i in _IDS} | {stray} + started = time.monotonic() + run = source_sync.Pass(PassBudget(started, started), 40) + result = source_sync.TurnResult(mirror=_MIRROR) + await source_sync_worker._sync_copies(world.src, {}, run, result) + assert world.retired == [] and source_sync.TurnMark.PASS_BOUND in result.marks + assert not world.worker.calls From 068feb6ad237d7cdd1069c8e507063cccdea3632 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 20:07:47 +0000 Subject: [PATCH 04/18] Only the upstream's 403 to the read itself names an upstream access denial The source worker answers `upstream_access` only for an upstream 403 to the resources/read, or the mapped read's tools/call, inside an opened session. A 403 to initialize, tool discovery, the GET stream or the closing DELETE may come from a network policy in front of the upstream, so it stays a plain denied. A plain denial of a resource with no copy now sets its wait before the turn ends, so the next turn reaches the other resources. A process sends at most one copy at a time, so the channel's copy share holds one slot. The boundary page says a copy and a live read share the worker's own read slots. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 22 +++++--- server/knowledge/app/mcp_worker_read.py | 8 +-- server/knowledge/app/source_sync_worker.py | 4 ++ source_worker/README.md | 21 ++++---- .../loom_source_worker/mcp_client.py | 50 ++++++++++++++----- .../loom_source_worker/read_service.py | 2 +- source_worker/qualification/test_real_tls.py | 31 ++++++++++++ source_worker/tests/test_mcp_client.py | 21 +++++--- source_worker/tests/test_protocol_servers.py | 16 ++++-- source_worker/tests/test_read_service.py | 2 - tests/unit/test_mcp_worker_read.py | 9 ++-- tests/unit/test_worker_source_copies.py | 15 ++++++ 12 files changed, 150 insertions(+), 51 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index f381c72576d..e4b795107d4 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -386,18 +386,24 @@ collection's current approval of the registration's mode and the owner's worker at the registered generation. 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 in a share of two -requests per worker that live reads never wait on; a reply with the stored digest writes -nothing. 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. The oldest confirmation goes first. Copies count against the -pass's mirror document bound; checks count against its time alone. +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. The oldest confirmation goes +first. Copies count against the pass's mirror document bound; checks count against its +time alone. Only the worker's report that the upstream refused the account retires a copy: 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 -read ([source worker responses](../../source_worker/README.md#responses)). Even then 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 diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py index db20a465cdc..5f8d79ddb89 100644 --- a/server/knowledge/app/mcp_worker_read.py +++ b/server/knowledge/app/mcp_worker_read.py @@ -33,9 +33,9 @@ # 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 reads a stored copy's content one resource at a time per source; its own share -# keeps those reads from taking a live read's slot. -_COPY_SLOTS = 2 # not a setting: copies in flight per worker across a process's sync turns +# 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", "copy", "enroll"] # not a setting: the fixed check-access answer (ids, a digest, a time), with margin @@ -69,7 +69,7 @@ def __init__(self, reason: WorkerFailure, *, upstream_access: bool = False) -> N 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 and reason == "denied" + self.upstream_access = upstream_access class _UpstreamDenial(BaseModel): diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 423f5c37d3c..4b471b2f439 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -336,6 +336,10 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # 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(): + if not copy.stored: + # Nothing to retire, but the resource waits, so the next turn reaches + # the others before it. + copy.entry["retry_at"] = (asked + self._wait()).isoformat() result.fail("denied", "denied") return False if copy.stored and await sync.retire(self.src, copy.uri): diff --git a/source_worker/README.md b/source_worker/README.md index 75b6ad4c03a..d18d3bbe632 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -365,15 +365,18 @@ inside the failed read. The handler refuses a body or query with `400` and `invalid`. A refusal body is `{"status": ""}`. One read refusal adds a reason: when the -upstream answers the read itself with HTTP 403, the worker answers `403` with -`{"status": "denied", "reason": "upstream_access"}`, the upstream's word that the -account cannot read the resource. Loom retires a stored copy only on that body. 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) stays a plain `denied`, and so -does an upstream 403 to the closing session `DELETE`. A worker build without the reason -never sends it, so Loom never retires a copy on its answer; the copy stops being served -once its access goes unconfirmed past Loom's stale window. +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. Loom retires a stored copy only on that body. 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 answer; the copy stops being served once its access goes unconfirmed past +Loom's stale window. 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 diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index bb49d09918d..1e6f7420328 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -62,8 +62,11 @@ 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 upstream's own 403 to a session request is `forbidden`, its -# verdict that the account cannot read, apart from every `denied` this worker decides. +# `_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: @@ -117,16 +120,26 @@ 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 response.is_redirect or (status == 403 and method == "DELETE"): - raise MCPSourceError("denied") - if status == 403: + if status == 403 and reads and method == "POST": 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. if status in {408, 429} or 500 <= status < 600: raise MCPSourceError("unavailable") @@ -705,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"") @@ -813,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 3a73318201c..0c5ea47c55c 100644 --- a/source_worker/loom_source_worker/read_service.py +++ b/source_worker/loom_source_worker/read_service.py @@ -29,7 +29,7 @@ def __init__(self, code: FailureCode, *, upstream_access: bool = False) -> None: 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 and code == "denied" + 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 30076d7a720..3b21b6a074d 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 1c0d13ac8be..8026c5339b0 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -256,7 +256,7 @@ def _client(source: _Source, **config: Any) -> MCPSourceClient: @pytest.mark.asyncio @pytest.mark.parametrize( ("status", "code"), - [(401, "reconnect"), (403, "forbidden"), (408, "unavailable"), (429, "unavailable")], + [(401, "reconnect"), (403, "denied"), (408, "unavailable"), (429, "unavailable")], ) async def test_maps_the_upstream_http_refusal(status: int, code: str, pin: list[str]) -> None: def refuse(request: httpx.Request) -> httpx.Response: @@ -1307,12 +1307,21 @@ async def test_resource_read_titles_the_document_with_its_uri(pin: list[str]) -> @pytest.mark.parametrize( - ("method", "code"), [("POST", "forbidden"), ("GET", "forbidden"), ("DELETE", "denied")] + ("method", "reads", "code"), + [ + ("POST", True, "forbidden"), + ("POST", False, "denied"), + ("GET", True, "denied"), + ("DELETE", True, "denied"), + ], ) -def test_only_a_session_requests_403_is_the_upstreams_access_refusal( - method: str, code: str +def test_only_the_reads_403_is_the_upstreams_access_refusal( + method: str, reads: bool, code: str ) -> None: - # A refused closing DELETE says nothing of the account's access to the resource. + # 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) + 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 aec296883f0..20953ba703f 100644 --- a/source_worker/tests/test_protocol_servers.py +++ b/source_worker/tests/test_protocol_servers.py @@ -287,10 +287,14 @@ def grant(target: ReadBinding, operation: str) -> str: ("tool", "discover"), ], ) -@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "forbidden")]) +@pytest.mark.parametrize(("status", "code"), [(401, "reconnect"), (403, "denied")]) 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,10 @@ 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 account names its reason. + # 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"), @@ -469,7 +475,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: upstream = { "upstream-503": 503, "upstream-429": 429, - "upstream-403": 403, + "initialize-403": 403, "missing-endpoint": 404, } if method == "initialize" and faulted and upstream_fault in upstream: @@ -477,7 +483,9 @@ async def app(scope: Scope, receive: Receive, send: Send) -> 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: diff --git a/source_worker/tests/test_read_service.py b/source_worker/tests/test_read_service.py index 594579f16dd..c171c13a9e5 100644 --- a/source_worker/tests/test_read_service.py +++ b/source_worker/tests/test_read_service.py @@ -301,8 +301,6 @@ async def refused(*_args: object, **_kwargs: object) -> Document: reply = await client.post("/v1/live", headers=auth) self.assertEqual(reply.status_code, 403) self.assertEqual(reply.json(), {"status": "denied", "reason": "upstream_access"}) - # Any other code never carries the reason. - self.assertFalse(ReadFailure("unsupported", upstream_access=True).upstream_access) async def test_http_body_backpressure_holds_the_org_slot(self) -> None: app = create_app(self._service(timeout=3)) diff --git a/tests/unit/test_mcp_worker_read.py b/tests/unit/test_mcp_worker_read.py index 90d57cc4629..c87cce75726 100644 --- a/tests/unit/test_mcp_worker_read.py +++ b/tests/unit/test_mcp_worker_read.py @@ -495,21 +495,22 @@ async def test_a_copy_reads_live_content_in_its_own_share(self) -> None: def copy(): return channel.copy(self.scope, require_current=self._authorized) - held = [asyncio.create_task(copy()) for _ in range(2)] - await self._until(arrived, paths, 2) + # 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, 3) + 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"] * 3) + 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 diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index ab90fcf727c..bccf1167588 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -850,3 +850,18 @@ async def test_unselected_copies_wait_once_the_pass_is_spent(world) -> None: await source_sync_worker._sync_copies(world.src, {}, run, result) assert world.retired == [] and source_sync.TurnMark.PASS_BOUND in result.marks assert not world.worker.calls + + +@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 From 7a38e9cd03100941560aa6881c4575eb2e5510c6 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 20:23:20 +0000 Subject: [PATCH 05/18] State that an access check confirms access only, and simplify two checks The boundary page said a stored-copy confirmation compares digests; it confirms the owner's access only, and a test now pins that. The upstream-403 check drops a method test the read flag already implies, and a one-key comprehension becomes a plain lookup. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/mcp-source-worker-boundary.md | 7 ++++--- server/knowledge/app/source_sync_worker.py | 5 ++++- source_worker/loom_source_worker/mcp_client.py | 2 +- source_worker/tests/test_mcp_client.py | 4 ++-- tests/unit/test_worker_source_copies.py | 13 +++++++++++++ 5 files changed, 24 insertions(+), 7 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index e4b795107d4..f8a26137332 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -54,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 diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 4b471b2f439..398db5e068a 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -378,7 +378,10 @@ async def _known_copies( for item, uri in zip(selected, uris, strict=True): raw = recorded.get(resource_digest(item.id)) raw = raw if isinstance(raw, dict) else {} - entry = dict(raw) if uri in stored else {k: raw[k] for k in ("retry_at",) if k in raw} + 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, unselected diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 1e6f7420328..2815ccb1e84 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -136,7 +136,7 @@ def _check_response( status = response.status_code if status == 401: raise MCPSourceError("reconnect") - if status == 403 and reads and method == "POST": + if status == 403 and reads: raise MCPSourceError("forbidden") if response.is_redirect or status == 403: raise MCPSourceError("denied") diff --git a/source_worker/tests/test_mcp_client.py b/source_worker/tests/test_mcp_client.py index 8026c5339b0..bfe02ca099d 100644 --- a/source_worker/tests/test_mcp_client.py +++ b/source_worker/tests/test_mcp_client.py @@ -1311,8 +1311,8 @@ async def test_resource_read_titles_the_document_with_its_uri(pin: list[str]) -> [ ("POST", True, "forbidden"), ("POST", False, "denied"), - ("GET", True, "denied"), - ("DELETE", True, "denied"), + ("GET", False, "denied"), + ("DELETE", False, "denied"), ], ) def test_only_the_reads_403_is_the_upstreams_access_refusal( diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index bccf1167588..82cff297d57 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -318,6 +318,19 @@ async def test_a_snapshot_copy_has_its_access_checked_without_its_content(world) 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} From 4b219f44c42287f56731aca6ff4e1f83190604fe Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 20:46:45 +0000 Subject: [PATCH 06/18] A worker copy unconfirmed for the whole stale window is retired A stored copy whose access check keeps answering timeout or unsupported no longer pins the listing of every other copy: once its last confirmation is older than knowledge_source_acl_stale_seconds it is served no more, so it is retired, waits, and is copied again once readable. The state notes copy_unconfirmable. The unselected-copy sweep goes: a copy's address is fixed by its source ID and resource, and a registration's selection never changes. The owner's writer-grant check is one helper, connected_accounts.owner_writes, for the worker turn and both connected checks. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 27 +++-- server/knowledge/app/connected_accounts.py | 25 +++-- .../knowledge/app/mcp_worker_setup_preview.py | 7 +- server/knowledge/app/source_sync_worker.py | 80 +++++++------- server/knowledge/store/sources.py | 23 ---- tests/unit/test_worker_copy_store_sql.py | 6 +- tests/unit/test_worker_source_copies.py | 100 +++++++++++++----- 7 files changed, 147 insertions(+), 121 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index f8a26137332..f83f3bd2e77 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -395,9 +395,11 @@ share guards only Loom's own channel slots: on the worker, a copy and a live rea 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. The oldest confirmation goes -first. Copies count against the pass's mirror document bound; checks count against its -time alone. +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. 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. Only the worker's report that the upstream refused the account retires a copy: a `403` whose body is exactly `{"status": "denied", "reason": "upstream_access"}`, read whole @@ -412,14 +414,17 @@ lifetime), Loom's own check of authority that changed during the turn, or a repl failed validation. A worker build that names no reason never causes a retirement; its copies stop being served once their access goes unconfirmed past the stale window. `reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; -`timeout` and `unsupported` keep that resource's copy and let the turn go on. A resource -left without a copy, denied or unsupported, is read again only after its refresh -interval or, for a snapshot, 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. Nothing confirms a copy while the owner's standing, the approval or the worker -account fails, so they fail closed together. +`timeout` and `unsupported` keep that resource's copy and let the turn go on, until the +copy's last confirmation is older than the whole `knowledge_source_acl_stale_seconds`: +such a copy is served no more and would hold back the listing of the others, so it is +retired (its state notes `copy_unconfirmable`) and read again after the wait below. A +resource left without a copy, denied or unsupported, is read again only after its +refresh interval or, for a snapshot, 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 diff --git a/server/knowledge/app/connected_accounts.py b/server/knowledge/app/connected_accounts.py index 6b9ad8511bd..9a059240967 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -652,6 +652,17 @@ async def _erase_worker_sources(org: str, owner: str, before: int | None) -> Non 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 @@ -683,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 @@ -753,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_setup_preview.py b/server/knowledge/app/mcp_worker_setup_preview.py index 80cbe95fc69..c4e563d91f9 100644 --- a/server/knowledge/app/mcp_worker_setup_preview.py +++ b/server/knowledge/app/mcp_worker_setup_preview.py @@ -45,12 +45,13 @@ ), "snapshot": ( "Loom reads each resource once through the owner's account and keeps that copy," - " indexed and shown to the owner alone, while the account still reads it." + " 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 every" - " interval; the copy is indexed and shown to the owner alone, while the account" - " still reads it." + " 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] = { diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 398db5e068a..e262b246c32 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -6,19 +6,21 @@ 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). The oldest confirmation goes first, and only copies -spend the pass's document bound. +access checked (a digest, no content). Resources without a copy go first, then the stored +copies by oldest confirmation, and 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; any other refusal -keeps every copy, ends the turn and records no listing. A resource left without a copy -is tried again after a wait: its refresh interval, or half the stale window. 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, whatever stopped its check. +`unsupported` answer keeps that resource's copy and the turn goes on, until the copy has +gone unconfirmed for the whole stale window: it is then retired, so the others are +vouched for again. Any other refusal keeps every copy, ends the turn and records no +listing. A resource left without a copy is tried again after a wait: its refresh +interval, or half the stale window. 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 @@ -36,8 +38,7 @@ from typing import Any, Literal from uuid import UUID -from server.auth import aliases, authz -from server.core.ch import own_write_reads, sequential_reads +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 @@ -70,7 +71,6 @@ 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.operations.base import Role from server.settings import settings from server.workers import pass_context from server.workers.status import set_worker_identity @@ -103,15 +103,6 @@ async def require_current(src: KnowledgeSource) -> None: raise sync.SourceGone(sync._cursor_of(src)) -async def _writer(src: KnowledgeSource) -> bool: - # The alias cache is read fresh, so a departed alias's grant no longer counts. - await aliases.verified_spellings(src.org, src.owner_subject) - aliases.invalidate(src.org, [src.owner_subject]) - with own_write_reads(): - role = await authz.grant_role_for(src.org, src.namespace, src.owner_subject) - return role is not None and role >= Role.WRITER - - 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) @@ -120,7 +111,7 @@ async def owner_standing(src: KnowledgeSource) -> bool: 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 _writer(src) + return await connected_accounts.owner_writes(src.org, src.namespace, src.owner_subject) type Authority = Literal["current", "gone", "unserved"] @@ -175,6 +166,10 @@ async def _end_registration(src: KnowledgeSource, directory: LiveSourceDirectory raise sync.SourceGone(sync._cursor_of(src)) +def _stale() -> timedelta: + return timedelta(seconds=settings.knowledge_source_acl_stale_seconds) + + def _at(raw: Any) -> datetime | None: try: value = datetime.fromisoformat(str(raw)) @@ -202,9 +197,11 @@ def copy_due(self, interval: int | None, now: datetime) -> bool: ) 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")) - half = timedelta(seconds=settings.knowledge_source_acl_stale_seconds / 2) - return verified is None or now - verified >= half + return verified is not None and now - verified < window def _oldest_confirmation(copies: list[_Copy]) -> datetime | None: @@ -236,7 +233,9 @@ def _wait(self) -> timedelta: return timedelta(seconds=interval or settings.knowledge_source_acl_stale_seconds / 2) async def _standing(self, _: RequestedResource) -> ReaderStanding | None: - return ReaderStanding(self.src.owner_subject) if await _writer(self.src) else None + src = self.src + writes = await connected_accounts.owner_writes(src.org, src.namespace, src.owner_subject) + return ReaderStanding(src.owner_subject) if writes else None async def _exchange( self, item: ResourceIdentity, *, content: bool @@ -357,6 +356,16 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # unsupported answer lets the others go on; the worker at capacity, the owner's # account to link again or the worker unavailable ends the turn. if reason in ("timeout", "unsupported"): + if copy.stored and not copy.confirmed_within(_stale(), asked): + # Unconfirmed for the whole stale window, it is served no more and would + # hold back the listing of every other copy: it goes, and waits. + if await sync.retire(self.src, copy.uri): + result.removed += 1 + copy.stored = False + copy.entry.clear() + copy.entry["retry_at"] = (asked + self._wait()).isoformat() + result.note = "copy_unconfirmable" + return True result.complete = False result.note = reason return True @@ -366,14 +375,13 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim async def _known_copies( src: KnowledgeSource, selected: tuple[ResourceIdentity, ...], recorded: dict[str, Any] -) -> tuple[list[_Copy], list[str]]: - """Each selected resource's copy, and up to a page of stored addresses no resource - selects.""" +) -> 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) - unselected = await source_store.copies_besides(src.org, src.mirror, tag, uris) copies = [] for item, uri in zip(selected, uris, strict=True): raw = recorded.get(resource_digest(item.id)) @@ -383,7 +391,7 @@ async def _known_copies( else: entry = {"retry_at": raw["retry_at"]} if "retry_at" in raw else {} copies.append(_Copy(item, uri, uri in stored, entry)) - return copies, unselected + return copies async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: @@ -406,19 +414,10 @@ async def _sync_copies( ) -> None: config, selected = decode_worker_source(src) recorded = detail.get(_COPIES) - copies, unselected = await _known_copies( - src, selected, recorded if isinstance(recorded, dict) else {} - ) + 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) - for uri in unselected: - if run.budget.exhausted(): - result.mark(sync.TurnMark.PASS_BOUND) - return - pass_context.check_stop() - if await sync.retire(src, uri): - result.removed += 1 now = datetime.now(UTC) due = [ c @@ -444,7 +443,8 @@ async def _sync_copies( async def _visit_due(work: _Turn, due: list[_Copy], now: datetime) -> None: - # The oldest confirmation first, so a turn the bound cuts leaves the newest for later. + # 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: diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 46b4ebc6759..3364722ef5d 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -670,28 +670,6 @@ async def copies_at( return {str(r["source_uri"]) for r in rows} -async def copies_besides( - org: str, namespace: str, tag: str, uris: list[str], *, ch: _CHClient | None = None -) -> list[str]: - """Up to DOCUMENTS_LIMIT live documents the sync wrote under `tag` at an address - outside `uris`, by address.""" - 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 NOT IN {uris:Array(String)} AND has(tags, {tag:String}) " - "AND actor = {actor:String} AND superseded_at IS NULL " - f"ORDER BY source_uri LIMIT {DOCUMENTS_LIMIT}", - params={ - "org": org, - "ns": namespace, - "uris": sorted(set(uris)), - "tag": tag, - "actor": SYNC_WORKER_ACTOR, - }, - ) - 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: 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.source_store, "copies_besides", self._copies_besides) monkeypatch.setattr(w.connected_accounts, "_standing", AsyncMock()) - monkeypatch.setattr(w.aliases, "verified_spellings", AsyncMock(return_value=["alice"])) - monkeypatch.setattr(w.aliases, "invalidate", lambda *_: None) - monkeypatch.setattr(w.authz, "grant_role_for", self._grant) + 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="")) @@ -216,10 +217,6 @@ 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 _copies_besides(self, org, namespace, tag, uris) -> list[str]: - assert (org, namespace, tag) == ("org", _MIRROR, f"source-id:{_SOURCE}") - return sorted(self.stored - set(uris)) - async def _grant(self, org: str, namespace: str, subject: str) -> Role | None: return self.role @@ -389,15 +386,6 @@ async def test_the_document_bound_stops_copies_but_not_checks(world) -> None: assert source_sync.TurnMark.PASS_BOUND in result.marks -@pytest.mark.asyncio -async def test_an_unselected_copy_is_retired(world) -> None: - stray = resource_uri(str(_SOURCE), "doc:gone") - world.stored = {_uri(i) for i in _IDS} | {stray} - recent = datetime.now(UTC) - timedelta(seconds=60) - await world.turn(_detail(recent, listed=recent.isoformat())) - assert world.retired == [stray] - - @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: @@ -853,18 +841,6 @@ async def retire(src) -> None: assert ended == [str(_SOURCE)] -@pytest.mark.asyncio -async def test_unselected_copies_wait_once_the_pass_is_spent(world) -> None: - stray = resource_uri(str(_SOURCE), "doc:gone") - world.stored = {_uri(i) for i in _IDS} | {stray} - started = time.monotonic() - run = source_sync.Pass(PassBudget(started, started), 40) - result = source_sync.TurnResult(mirror=_MIRROR) - await source_sync_worker._sync_copies(world.src, {}, run, result) - assert world.retired == [] and source_sync.TurnMark.PASS_BOUND in result.marks - assert not world.worker.calls - - @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 @@ -878,3 +854,69 @@ async def test_a_plain_denial_of_a_resource_without_a_copy_waits_its_turn(world) 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) + + +@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"] From d6320c3ede32fa665f9919d3bcc0d3d2652d8f52 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 20:58:36 +0000 Subject: [PATCH 07/18] Retire an unconfirmable worker copy before its confirmation lapses A copy that kept answering timeout or unsupported was retired only after the listing it held back had expired, leaving the source's other copies unserved until the next pass. It now goes once its confirmation would lapse before the next pass, and only while the owner's authority, read again, still holds. The listing write drops a publication guard that does nothing for a worker source, and the docs say which retirements there are. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 13 +++-- server/knowledge/app/source_sync_worker.py | 33 ++++++++----- source_worker/README.md | 3 +- tests/unit/test_worker_source_copies.py | 47 +++++++++++++++++++ 4 files changed, 80 insertions(+), 16 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index f83f3bd2e77..30b9b742a25 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -401,7 +401,8 @@ mirror document bound; checks count against its time alone. A copy's address is its source ID and its resource, and a registration's selection never changes, so every stored copy belongs to a selected resource. -Only the worker's report that the upstream refused the account retires a copy: a `403` +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 @@ -415,9 +416,13 @@ failed validation. A worker build that names no reason never causes a retirement copies stop being served once their access goes unconfirmed past the stale window. `reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; `timeout` and `unsupported` keep that resource's copy and let the turn go on, until the -copy's last confirmation is older than the whole `knowledge_source_acl_stale_seconds`: -such a copy is served no more and would hold back the listing of the others, so it is -retired (its state notes `copy_unconfirmable`) and read again after the wait below. A +copy's confirmation would lapse before the next pass: older than +`knowledge_source_acl_stale_seconds` less `knowledge_source_sync_interval_seconds`, and +no sooner than half the stale window. With the registration and the owner's authority +read again and still holding, it is then retired (its state notes `copy_unconfirmable`) +before it can hold back the listing of the others, and read again after the wait below. +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 or unsupported, is read again only after its refresh interval or, for a snapshot, half of `knowledge_source_acl_stale_seconds`. The mirror read gate needs a listing no older than `knowledge_source_acl_stale_seconds`, and diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index e262b246c32..ef3d8861ab7 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -13,9 +13,10 @@ 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, until the copy has -gone unconfirmed for the whole stale window: it is then retired, so the others are -vouched for again. Any other refusal keeps every copy, ends the turn and records no +`unsupported` answer keeps that resource's copy and the turn goes on, until the copy's +confirmation would lapse before the next pass (and no sooner than half the stale +window): with the owner's authority read again and still holding, it is then retired, so +the others stay vouched for. Any other refusal keeps every copy, ends the turn and records no listing. A resource left without a copy is tried again after a wait: its refresh interval, or half the stale window. The listing the mirror read gate needs records the oldest confirmation of every stored copy, so a copy whose access was not confirmed @@ -170,6 +171,14 @@ 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, and no sooner than half the stale window, when its check + falls due.""" + interval = timedelta(seconds=settings.knowledge_source_sync_interval_seconds) + return max(_stale() / 2, _stale() - interval) + + def _at(raw: Any) -> datetime | None: try: value = datetime.fromisoformat(str(raw)) @@ -352,13 +361,16 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim copy.entry["retry_at"] = (asked + self._wait()).isoformat() result.note = reason return True - # Every other refusal keeps the copy, unconfirmed. One resource's timeout or - # unsupported answer lets the others go on; the worker at capacity, the owner's - # account to link again or the worker unavailable ends the turn. + # A timeout or unsupported answer keeps that copy unconfirmed and the others go on, + # until its confirmation is about to lapse; any other refusal ends the turn. if reason in ("timeout", "unsupported"): - if copy.stored and not copy.confirmed_within(_stale(), asked): - # Unconfirmed for the whole stale window, it is served no more and would - # hold back the listing of every other copy: it goes, and waits. + if ( + copy.stored + and not copy.confirmed_within(_lapsing(), asked) + and await self._authority_holds() + ): + # Its confirmation lapses before the next pass, and with it the listing of + # every other copy: it goes before that, and waits. if await sync.retire(self.src, copy.uri): result.removed += 1 copy.stored = False @@ -484,6 +496,5 @@ async def _vouch( result.fail("owner_unavailable", "owner_unavailable") return pass_context.check_stop() - async with sync.publication_guard(src): - await mirror_store.record_listing(src.org, src.mirror, src.source_id, src.name, oldest) + await mirror_store.record_listing(src.org, src.mirror, src.source_id, src.name, oldest) result.kind_state[_LISTED] = oldest.isoformat() diff --git a/source_worker/README.md b/source_worker/README.md index d18d3bbe632..020199cf534 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -368,7 +368,8 @@ A refusal body is `{"status": ""}`. One read refusal adds a reason: when t 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. Loom retires a stored copy only on that body. An +account cannot read the resource. Of the worker's answers, only that body retires a +stored copy. 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 diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index f8b38b656e0..641e1af34ad 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -874,6 +874,53 @@ async def test_a_copy_unconfirmed_for_the_whole_stale_window_is_retired(world) - 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_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"] = "timeout" + 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_resources_without_a_copy_go_before_the_oldest_confirmation(world) -> None: world.stored = {_uri("doc:two")} From 09c75e61bf568a33d2f232e9548cfb31b0364568 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 21:19:48 +0000 Subject: [PATCH 08/18] A timeout never retires a worker copy; an unsupported one needs a confirmed peer A stalled upstream answers every request with a timeout, and retiring the copies that lapsed then cost a full re-copy and a wait of up to the refresh interval for nothing. A timeout now keeps the copy. A copy answering unsupported as its confirmation is about to lapse goes only when another copy was confirmed after its own check fell due, which shows the failure is the resource's. A resource without a copy that times out waits half the stale window, so it no longer comes first on every pass. The lapsing age drops a floor no check could reach. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 34 ++++--- server/knowledge/app/source_sync_worker.py | 91 +++++++++++++------ source_worker/README.md | 7 +- tests/unit/test_worker_source_copies.py | 67 +++++++++++++- 4 files changed, 149 insertions(+), 50 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 30b9b742a25..9fc55432ff6 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -402,12 +402,13 @@ its source ID and its resource, and a registration's selection never changes, so stored copy belongs to a selected resource. 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 +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 @@ -415,16 +416,19 @@ lifetime), Loom's own check of authority that changed during the turn, or a repl failed validation. A worker build that names no reason never causes a retirement; its copies stop being served once their access goes unconfirmed past the stale window. `reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; -`timeout` and `unsupported` keep that resource's copy and let the turn go on, until the -copy's confirmation would lapse before the next pass: older than -`knowledge_source_acl_stale_seconds` less `knowledge_source_sync_interval_seconds`, and -no sooner than half the stale window. With the registration and the owner's authority -read again and still holding, it is then retired (its state notes `copy_unconfirmable`) -before it can hold back the listing of the others, and read again after the wait below. -Removal, namespace retirement, owner erasure and the end of a registration (below) also -retire every copy of the source. A +`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`; it is checked only from half the window on) 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. 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 or unsupported, is read again only after its -refresh interval or, for a snapshot, half of `knowledge_source_acl_stale_seconds`. The +refresh interval or, for a snapshot, half of `knowledge_source_acl_stale_seconds`; one +that timed out, 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 diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index ef3d8861ab7..7a6d823c41f 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -13,15 +13,15 @@ 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, until the copy's -confirmation would lapse before the next pass (and no sooner than half the stale -window): with the owner's authority read again and still holding, it is then retired, so -the others stay vouched for. Any other refusal keeps every copy, ends the turn and records no -listing. A resource left without a copy is tried again after a wait: its refresh -interval, or half the stale window. 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. +`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 resource left +without a copy is tried again after a wait: its refresh interval, or half the stale +window. 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 @@ -173,10 +173,9 @@ def _stale() -> timedelta: def _lapsing() -> timedelta: """The age at which an unconfirmable copy goes: its confirmation would lapse before the - next pass could confirm it, and no sooner than half the stale window, when its check - falls due.""" - interval = timedelta(seconds=settings.knowledge_source_sync_interval_seconds) - return max(_stale() / 2, _stale() - interval) + next pass could confirm it. A copy is checked only from half the stale window on, so + none goes sooner.""" + return _stale() - timedelta(seconds=settings.knowledge_source_sync_interval_seconds) def _at(raw: Any) -> datetime | None: @@ -213,6 +212,21 @@ def confirmed_within(self, window: timedelta, now: datetime) -> bool: 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.""" @@ -235,6 +249,9 @@ def __init__( self.run = run self.result = result self.config, self.selected = 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.""" @@ -336,6 +353,26 @@ async def _authority_holds(self) -> bool: 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.""" + failing = [c for c in self.lapsing if _confirmed_since_due(c, copies)] + if not failing or self.run.budget.exhausted() 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() + copy.entry["retry_at"] = (asked + self._wait()).isoformat() + 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": @@ -361,25 +398,17 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim copy.entry["retry_at"] = (asked + self._wait()).isoformat() result.note = reason return True - # A timeout or unsupported answer keeps that copy unconfirmed and the others go on, - # until its confirmation is about to lapse; any other refusal ends the turn. + # 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"): - if ( - copy.stored - and not copy.confirmed_within(_lapsing(), asked) - and await self._authority_holds() - ): - # Its confirmation lapses before the next pass, and with it the listing of - # every other copy: it goes before that, and waits. - if await sync.retire(self.src, copy.uri): - result.removed += 1 - copy.stored = False - copy.entry.clear() - copy.entry["retry_at"] = (asked + self._wait()).isoformat() - result.note = "copy_unconfirmable" - return True result.complete = False result.note = reason + if not copy.stored: + # Nothing to keep, and it must not come first on every pass. + copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() + elif reason == "unsupported" and not copy.confirmed_within(_lapsing(), asked): + self.lapsing.append(copy) return True result.fail(reason, reason) return False @@ -449,7 +478,9 @@ async def _sync_copies( if held != "current" or not await owner_standing(src): result.fail("owner_unavailable", "owner_unavailable") return - await _visit_due(_Turn(src, directory, run, result), due, now) + 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) diff --git a/source_worker/README.md b/source_worker/README.md index 020199cf534..cd3d52839f0 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -369,10 +369,9 @@ upstream answers the resource request itself with HTTP 403 (the `resources/read` 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. 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 +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 diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index 641e1af34ad..7d3eaeec4a3 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -92,6 +92,7 @@ def _sha(text: str) -> str: 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: @@ -906,7 +907,7 @@ async def test_a_lapsed_copy_is_kept_by_a_refusal_that_ends_the_turn(world, reas @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"] = "timeout" + world.worker.refusals["doc:one"] = "unsupported" original = world.worker.check_access async def check(scope, *, require_current): @@ -921,6 +922,70 @@ async def check(scope, *, require_current): 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")} From 8a90bc6bcf681970368f68c01091f20de7ba6b05 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 21:41:59 +0000 Subject: [PATCH 09/18] A worker turn a refusal ended retires no lapsing copy Retiring a lapsing copy in a turn that a later refusal ended gained nothing, since that turn records no listing, and broke the documented rule that such a refusal keeps every copy. The lapsing age's docstring and the boundary page now give the real reason no copy goes before half the stale window, and two paragraphs are reflowed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 52 +++++++++---------- server/knowledge/app/source_sync_worker.py | 6 ++- source_worker/README.md | 18 +++---- tests/unit/test_worker_source_copies.py | 10 ++++ 4 files changed, 49 insertions(+), 37 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 9fc55432ff6..01613cfb750 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -408,32 +408,32 @@ the worker sends only for the upstream's own HTTP 403 to the resource request it 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; its -copies stop being served once their access goes unconfirmed past the stale window. -`reconnect`, `overloaded` and `unavailable` end the turn and keep every copy; -`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`; it is checked only from half the window on) 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. 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 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, 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. +`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; its copies stop being served once their access goes unconfirmed +past the stale window. `reconnect`, `overloaded` and `unavailable` end the turn and keep +every copy; `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 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, 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 diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 7a6d823c41f..dc5b27fefd7 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -173,8 +173,8 @@ def _stale() -> timedelta: def _lapsing() -> timedelta: """The age at which an unconfirmable copy goes: its confirmation would lapse before the - next pass could confirm it. A copy is checked only from half the stale window on, so - none goes sooner.""" + next pass could confirm it. None goes 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) @@ -360,6 +360,8 @@ async def retire_lapsing(self, copies: list[_Copy]) -> None: 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 not failing or self.run.budget.exhausted() or not await self._authority_holds(): return diff --git a/source_worker/README.md b/source_worker/README.md index cd3d52839f0..b42e728f290 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -365,18 +365,18 @@ inside the failed read. The handler refuses a body or query with `400` and `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 +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 answer; the copy stops being served once its access goes unconfirmed past -Loom's stale window. +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 answer; the copy stops being served once its access +goes unconfirmed past Loom's stale window. 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 diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index 7d3eaeec4a3..cd770dbae11 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -904,6 +904,16 @@ async def test_a_lapsed_copy_is_kept_by_a_refusal_that_ends_the_turn(world, reas 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_lapsed_copy_is_kept_when_the_owners_authority_is_gone(world) -> None: world.stored = {_uri(i) for i in _IDS} From 9efd67fd3b63078232fca43e322c616e9c740b39 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 21:59:28 +0000 Subject: [PATCH 10/18] Say an older worker never causes a retirement on a denial, and order the turn's checks The boundary page and the source worker README said an older worker never causes a retirement; a copy answering unsupported still follows the lapsing rule with either build. The boundary page lists the turn's authority checks in the order the code runs them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 52 ++++++++++--------- source_worker/README.md | 5 +- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 01613cfb750..45c9ffdf185 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -381,25 +381,26 @@ as a connected source's turn. A copy is a document at the resource's address tag and a permission list naming the owner alone; its metadata carries the worker's `content_sha256` and revision. -A turn reads the owner's standing first: an active directory account, no revocation -since the registration, and a writer grant in the collection. It then needs the -collection's current approval of the registration's mode and the owner's worker account -at the registered generation. 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. 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. +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. 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. 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 @@ -413,12 +414,13 @@ account are read again and must still hold. Any other `denied` ends the turn wit 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; its copies stop being served once their access goes unconfirmed -past the stale window. `reconnect`, `overloaded` and `unavailable` end the turn and keep -every copy; `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 +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; `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 diff --git a/source_worker/README.md b/source_worker/README.md index b42e728f290..809cde8fd7b 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -375,8 +375,9 @@ the upstream, so it stays a plain `denied`, as does every refusal the worker mak 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 answer; the copy stops being served once its access -goes unconfirmed past Loom's stale window. +Loom never retires a copy on its denial; the copy stops being served once its 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 From 7c4e18b75b09237811e7853f68ac48d713bdb28a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 22:11:49 +0000 Subject: [PATCH 11/18] A resource whose refusal ends a worker turn goes last, and copy checks pass the bound A copy whose request ended a turn (unavailable, overloaded, reconnect, a plain denial) came first again on every pass, so one failing resource kept every other copy of its source unconfirmed. It now sorts after the others for half the stale window, and a resource without a copy waits that long. A worker source's turn also starts once other mirrored sources have used up the document bound, since its checks spend only time. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 23 +++++----- server/knowledge/app/source_access.py | 8 ++-- server/knowledge/app/source_sync.py | 6 ++- server/knowledge/app/source_sync_worker.py | 17 +++++++- tests/unit/test_worker_source_copies.py | 43 +++++++++++++++++++ 5 files changed, 81 insertions(+), 16 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 45c9ffdf185..45143392a04 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -397,10 +397,12 @@ slots: on the worker, a copy and a live read take the same `read_limits.concurre 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. 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. +oldest confirmation; a stored copy whose refusal ended a turn in the last half stale +window goes after the rest. 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. 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 @@ -430,12 +432,13 @@ holding, in a turn no other refusal ended. Removal, namespace retirement, owner and the end of a registration (below) also retire every copy of the source. A resource left without a copy, denied 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, 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. +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 diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 853852decab..9b633069ccf 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -88,8 +88,8 @@ 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, read once per plan for its worker rows; "" when the - # reader has none, so it owns no worker source. + # 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 @@ -399,7 +399,7 @@ async def _eligible_sources( async def _reader_own_subject(plan: ReadPlan, auth: AuthInfo) -> str: - """The reader's own sign-in subject in the plan's org, read once per plan.""" + """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: @@ -442,6 +442,8 @@ async def _worker_copy_eligible(plan: ReadPlan, row: dict[str, Any]) -> bool: ): 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): diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 9801f8d6ea0..6c6568aaa61 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -418,8 +418,12 @@ 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) diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index dc5b27fefd7..db75b3cb649 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -345,6 +345,7 @@ async def visit(self, copy: _Copy, now: datetime) -> bool: copy.entry["retry_at"] = (asked + self._wait()).isoformat() if copy.stored: copy.entry["verified_at"] = asked.isoformat() + copy.entry.pop("ended_at", None) return True async def _authority_holds(self) -> bool: @@ -412,6 +413,13 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim elif reason == "unsupported" and not copy.confirmed_within(_lapsing(), asked): self.lapsing.append(copy) return True + # Any other refusal ends the turn. It may be this resource's alone (an upstream that + # keeps failing one document), so the resource goes last next time: one without a + # copy waits, and a stored copy sorts after the others while the mark is fresh. + if copy.stored: + copy.entry["ended_at"] = asked.isoformat() + else: + copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() result.fail(reason, reason) return False @@ -489,8 +497,13 @@ async def _sync_copies( 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 ""))) + # so a turn the bound cuts leaves the newest confirmations for later; a copy whose + # refusal ended a turn in the last half stale window goes after the rest. + def ended_lately(c: _Copy) -> bool: + ended = _at(c.entry.get("ended_at")) + return ended is not None and now - ended < _stale() / 2 + + due.sort(key=lambda c: (c.stored, ended_lately(c), str(c.entry.get("verified_at") or ""))) result = work.result for copy in due: if work.run.budget.exhausted(): diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index cd770dbae11..ee527b8af5f 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -914,6 +914,49 @@ async def test_a_lapsing_copy_is_kept_when_a_later_refusal_ends_the_turn(world) assert not world.retired and result.status == "reconnect" +@pytest.mark.asyncio +async def test_a_copy_whose_refusal_ended_a_turn_goes_last_next_time(world) -> None: + # doc:one always fails upstream; the next turn reaches doc:two first and vouches. + world.stored = {_uri(i) for i in _IDS} + world.worker.refusals["doc:one"] = "unavailable" + old = datetime.now(UTC) - timedelta(seconds=3000) + detail = _detail(old) + detail[source_sync_worker._COPIES][resource_digest("doc:one")]["verified_at"] = ( + old - timedelta(seconds=100) + ).isoformat() + first, _ = await world.turn(detail) + assert first.status == "unavailable" and world.worker.calls == [("check", "doc:one")] + again = {source_sync_worker._COPIES: first.kind_state[source_sync_worker._COPIES]} + await world.turn(again) + assert world.worker.calls[1:] == [("check", "doc:two"), ("check", "doc:one")] + + +@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} From 998ff756b27b21c8266829bc25e1ebbfd8044859 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 22:20:52 +0000 Subject: [PATCH 12/18] A plain worker denial also sends its copy last next time A stored copy refused with a plain denied (a reply naming another resource) ended every turn first, as the other turn-ending refusals did before. It now gets the same mark and sorts after the rest. The module docstring states the order and each wait. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/knowledge/app/source_sync_worker.py | 30 +++++++++++++--------- tests/unit/test_worker_source_copies.py | 11 +++++--- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index db75b3cb649..3f77233e0aa 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -7,21 +7,24 @@ 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, and only copies spend the pass's document bound. +copies by oldest confirmation, and a copy whose refusal ended a turn in the last half stale +window goes after the rest. 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 resource left -without a copy is tried again after a wait: its refresh interval, or half the stale -window. 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. +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 resource left without a +copy is tried again after a wait: its refresh interval or, for a snapshot, half the stale +window after a 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 @@ -384,9 +387,12 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # 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(): - if not copy.stored: - # Nothing to retire, but the resource waits, so the next turn reaches - # the others before it. + # Nothing is retired, but the resource goes last next time, so the next + # turn reaches the others before it: one that may be this resource's alone + # (a reply naming another resource) must not stop the rest. + if copy.stored: + copy.entry["ended_at"] = asked.isoformat() + else: copy.entry["retry_at"] = (asked + self._wait()).isoformat() result.fail("denied", "denied") return False diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index ee527b8af5f..cb1d8c40cc5 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -915,17 +915,20 @@ async def test_a_lapsing_copy_is_kept_when_a_later_refusal_ends_the_turn(world) @pytest.mark.asyncio -async def test_a_copy_whose_refusal_ended_a_turn_goes_last_next_time(world) -> None: - # doc:one always fails upstream; the next turn reaches doc:two first and vouches. +@pytest.mark.parametrize("reason", ["unavailable", "denied"]) +async def test_a_copy_whose_refusal_ended_a_turn_goes_last_next_time(world, reason) -> None: + # doc:one always fails (a plain denial: a reply naming another resource); the next + # turn reaches doc:two first. world.stored = {_uri(i) for i in _IDS} - world.worker.refusals["doc:one"] = "unavailable" + world.worker.refusals["doc:one"] = reason + world.worker.upstream["doc:one"] = False old = datetime.now(UTC) - timedelta(seconds=3000) detail = _detail(old) detail[source_sync_worker._COPIES][resource_digest("doc:one")]["verified_at"] = ( old - timedelta(seconds=100) ).isoformat() first, _ = await world.turn(detail) - assert first.status == "unavailable" and world.worker.calls == [("check", "doc:one")] + assert first.status == reason and world.worker.calls == [("check", "doc:one")] again = {source_sync_worker._COPIES: first.kind_state[source_sync_worker._COPIES]} await world.turn(again) assert world.worker.calls[1:] == [("check", "doc:two"), ("check", "doc:one")] From 0fcf51b06e3d5cb508fd1b7c43dd8ebbceb62f10 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 22:32:55 +0000 Subject: [PATCH 13/18] Each worker copy request reads the owner's whole standing, and drop the ended mark A turn read the owner's directory standing once at its start, then only the writer grant for each request, so a SCIM deactivation or revocation mid-turn still let the turn read and write copies. Every request now reads the whole standing. The mark that sent a copy last after a turn-ending refusal changed nothing a reader sees, since that copy ends each turn it is checked in, so it is removed; the docs say such a copy keeps the source's copies unserved until it answers, which fails closed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 19 ++++--- server/knowledge/app/source_sync_worker.py | 55 ++++++++----------- source_worker/README.md | 6 +- tests/unit/test_worker_source_copies.py | 32 +++++------ 4 files changed, 51 insertions(+), 61 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 45143392a04..f10fd6d7c2a 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -397,11 +397,10 @@ slots: on the worker, a copy and a live read take the same `read_limits.concurre 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; a stored copy whose refusal ended a turn in the last half stale -window goes after the rest. 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 +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. Of the worker's answers, only its report that the upstream refused the account retires a @@ -419,10 +418,12 @@ turn, or a reply that failed validation. A worker build that names no reason nev 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; `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 +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 diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 3f77233e0aa..17ebfa6da1c 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -7,8 +7,7 @@ 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, and a copy whose refusal ended a turn in the last half stale -window goes after the rest. Only copies spend the pass's document bound. +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 @@ -18,13 +17,14 @@ 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 resource left without a -copy is tried again after a wait: its refresh interval or, for a snapshot, half the stale -window after a 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. +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 a 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 @@ -176,7 +176,7 @@ def _stale() -> timedelta: def _lapsing() -> timedelta: """The age at which an unconfirmable copy goes: its confirmation would lapse before the - next pass could confirm it. None goes before half the stale window: a copy goes only + 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) @@ -262,9 +262,10 @@ def _wait(self) -> timedelta: 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 - writes = await connected_accounts.owner_writes(src.org, src.namespace, src.owner_subject) - return ReaderStanding(src.owner_subject) if writes else None + return ReaderStanding(src.owner_subject) if await owner_standing(src) else None async def _exchange( self, item: ResourceIdentity, *, content: bool @@ -348,7 +349,6 @@ async def visit(self, copy: _Copy, now: datetime) -> bool: copy.entry["retry_at"] = (asked + self._wait()).isoformat() if copy.stored: copy.entry["verified_at"] = asked.isoformat() - copy.entry.pop("ended_at", None) return True async def _authority_holds(self) -> bool: @@ -387,12 +387,10 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # 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, but the resource goes last next time, so the next - # turn reaches the others before it: one that may be this resource's alone - # (a reply naming another resource) must not stop the rest. - if copy.stored: - copy.entry["ended_at"] = asked.isoformat() - else: + # Nothing is retired. A resource without a copy waits, so the next turn + # reaches the others; 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: copy.entry["retry_at"] = (asked + self._wait()).isoformat() result.fail("denied", "denied") return False @@ -419,12 +417,10 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim elif reason == "unsupported" and not copy.confirmed_within(_lapsing(), asked): self.lapsing.append(copy) return True - # Any other refusal ends the turn. It may be this resource's alone (an upstream that - # keeps failing one document), so the resource goes last next time: one without a - # copy waits, and a stored copy sorts after the others while the mark is fresh. - if copy.stored: - copy.entry["ended_at"] = asked.isoformat() - else: + # Any other refusal ends the turn. A resource without a copy waits, so the next turn + # reaches the others; a stored copy keeps the source's copies unserved until it + # answers, which fails closed. + if not copy.stored: copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() result.fail(reason, reason) return False @@ -503,13 +499,8 @@ async def _sync_copies( 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; a copy whose - # refusal ended a turn in the last half stale window goes after the rest. - def ended_lately(c: _Copy) -> bool: - ended = _at(c.entry.get("ended_at")) - return ended is not None and now - ended < _stale() / 2 - - due.sort(key=lambda c: (c.stored, ended_lately(c), str(c.entry.get("verified_at") or ""))) + # 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(): diff --git a/source_worker/README.md b/source_worker/README.md index 809cde8fd7b..97aac911cb4 100644 --- a/source_worker/README.md +++ b/source_worker/README.md @@ -375,9 +375,9 @@ the upstream, so it stays a plain `denied`, as does every refusal the worker mak 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; the copy stops being served once its access -goes unconfirmed past Loom's stale window. A copy answering `unsupported` follows Loom's -lapsing rule with either build. +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 diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index cb1d8c40cc5..6b7b71741a4 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -18,6 +18,7 @@ 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, @@ -915,23 +916,20 @@ async def test_a_lapsing_copy_is_kept_when_a_later_refusal_ends_the_turn(world) @pytest.mark.asyncio -@pytest.mark.parametrize("reason", ["unavailable", "denied"]) -async def test_a_copy_whose_refusal_ended_a_turn_goes_last_next_time(world, reason) -> None: - # doc:one always fails (a plain denial: a reply naming another resource); the next - # turn reaches doc:two first. - world.stored = {_uri(i) for i in _IDS} - world.worker.refusals["doc:one"] = reason - world.worker.upstream["doc:one"] = False - old = datetime.now(UTC) - timedelta(seconds=3000) - detail = _detail(old) - detail[source_sync_worker._COPIES][resource_digest("doc:one")]["verified_at"] = ( - old - timedelta(seconds=100) - ).isoformat() - first, _ = await world.turn(detail) - assert first.status == reason and world.worker.calls == [("check", "doc:one")] - again = {source_sync_worker._COPIES: first.kind_state[source_sync_worker._COPIES]} - await world.turn(again) - assert world.worker.calls[1:] == [("check", "doc:two"), ("check", "doc:one")] +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 From 68772fd7414229c686795ae81f5e6c94a597563b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 22:59:22 +0000 Subject: [PATCH 14/18] Say interval_seconds is refused outside selected_refresh, and rewrap a docstring Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- server/knowledge/api/models_worker_setup.py | 4 +++- server/knowledge/app/source_sync_worker.py | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/server/knowledge/api/models_worker_setup.py b/server/knowledge/api/models_worker_setup.py index 1b3df62ab47..f3d32124658 100644 --- a/server/knowledge/api/models_worker_setup.py +++ b/server/knowledge/api/models_worker_setup.py @@ -210,7 +210,9 @@ 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 alone") + raise ValueError( + "interval_seconds is required for selected_refresh and refused for the other modes" + ) return self diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 17ebfa6da1c..63a458e66de 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -176,8 +176,9 @@ def _stale() -> timedelta: 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`).""" + 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) From a7df63dba5f804f4d169feca59ece8301ede29d3 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 23:21:13 +0000 Subject: [PATCH 15/18] State the worker copy capacity bound, and send each refusal to its own wait Copies and checks run one at a time within the mirrored phase, so the copies one deployment keeps served are bounded by that phase's time over one check's; the boundary page says so, and that past the bound copies stop being served. A plain denial of a resource without a copy waits half the stale window, as other turn-ending refusals do, and a routes file that does not provision the profile reads unavailable rather than the owner's. interval_seconds is described as the least time between copies. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 17 ++++++++++++++--- docs/reference/operations/knowledge.md | 4 ++-- sdk/go/wire/models.gen.go | 2 +- sdk/typescript/src/generated/ops.ts | 4 ++-- server/knowledge/api/models_worker_setup.py | 5 +++-- .../knowledge/app/mcp_worker_setup_preview.py | 4 ++-- server/knowledge/app/source_sync_worker.py | 19 ++++++++++++------- tests/unit/test_worker_source_copies.py | 17 ++++++++++++++++- 8 files changed, 52 insertions(+), 20 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index f10fd6d7c2a..74e47888278 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -403,6 +403,17 @@ sources have used up the bound, and only its due copies wait for a pass with roo 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; +the source's sync state reads `pass bound reached`. 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 @@ -431,9 +442,9 @@ another copy was confirmed after its own check fell due, which shows the failure 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 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 +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 diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 0a60550b7cc..c107d1c0968 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -972,7 +972,7 @@ Preview a worker source on the caller's linked account; nothing is written. | `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` 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` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | +| `interval_seconds` | `int \| None` | `None` | The least seconds between a `selected_refresh` resource's copies, 300 to 86400; a copy is read again only in a sync pass with room in the mirror document bound. | | `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. | @@ -1021,7 +1021,7 @@ Register the worker source a preview showed, with its fingerprint and evidence. | `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` 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` | Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. | +| `interval_seconds` | `int \| None` | `None` | The least seconds between a `selected_refresh` resource's copies, 300 to 86400; a copy is read again only in a sync pass with room in the mirror document bound. | | `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/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 7d0caafd720..282812089c2 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: cc51a5b844ba005bbc7e2606a98771db9c73c819fcab5cfd97689d91b4b05df7 +// Registry model schema SHA-256: 9c96512499716754e88ce5514c87ccfbd2d7349cafbc3e05e7724eae4f3483ad // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 7efd5596bb1..72a3827ffd8 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4935,7 +4935,7 @@ export interface KnowledgeSourceWorkerPreviewInput { connection_id: string; /** `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"; - /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ + /** The least seconds between a `selected_refresh` resource's copies, 300 to 86400; a copy is read again only in a sync pass with room in the mirror document bound. */ 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; @@ -5027,7 +5027,7 @@ export interface KnowledgeSourceWorkerRegisterInput { connection_id: string; /** `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"; - /** Seconds between a `selected_refresh` source's copies, 300 to 86400; required for that mode and refused for the others. */ + /** The least seconds between a `selected_refresh` resource's copies, 300 to 86400; a copy is read again only in a sync pass with room in the mirror document bound. */ 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; diff --git a/server/knowledge/api/models_worker_setup.py b/server/knowledge/api/models_worker_setup.py index f3d32124658..9da335b9603 100644 --- a/server/knowledge/api/models_worker_setup.py +++ b/server/knowledge/api/models_worker_setup.py @@ -191,8 +191,9 @@ class WorkerSourceSetup(BaseModel): ) interval_seconds: Annotated[int, Field(ge=300, le=86_400, strict=True)] | None = Field( default=None, - description="Seconds between a `selected_refresh` source's copies, 300 to 86400;" - " required for that mode and refused for the others.", + description="The least seconds between a `selected_refresh` resource's copies, 300 to" + " 86400; a copy is read again only in a sync pass with room in the mirror document" + " bound. Required for that mode and refused for the others.", ) team_access: bool = Field( default=False, diff --git a/server/knowledge/app/mcp_worker_setup_preview.py b/server/knowledge/app/mcp_worker_setup_preview.py index c4e563d91f9..5eda2c18c2b 100644 --- a/server/knowledge/app/mcp_worker_setup_preview.py +++ b/server/knowledge/app/mcp_worker_setup_preview.py @@ -49,8 +49,8 @@ " reads it." ), "selected_refresh": ( - "Loom reads each resource through the owner's account and replaces its copy every" - " interval; the copy is indexed and shown to the owner alone, while the worker" + "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." ), } diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 63a458e66de..82675159d85 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -20,11 +20,11 @@ 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 a 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. +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 @@ -252,7 +252,7 @@ def __init__( self.directory = directory self.run = run self.result = result - self.config, self.selected = decode_worker_source(src) + self.config, _ = decode_worker_source(src) # Stored copies whose resource answered `unsupported` as their confirmation was # about to lapse. self.lapsing: list[_Copy] = [] @@ -392,7 +392,8 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # reaches the others; 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: - copy.entry["retry_at"] = (asked + self._wait()).isoformat() + # Not the resource's word, so the short wait of any turn-ending refusal. + copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() result.fail("denied", "denied") return False if copy.stored and await sync.retire(self.src, copy.uri): @@ -488,6 +489,10 @@ async def _sync_copies( 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 held != "current" or not await owner_standing(src): result.fail("owner_unavailable", "owner_unavailable") return diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index 6b7b71741a4..d7c138e772b 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -400,10 +400,25 @@ async def test_without_the_owners_authority_nothing_is_read_or_retired(world, lo else: world.permitted = False # this process's routes file does not provision the profile result, _ = await world.turn(_detail(old)) - assert result.status in ("unavailable", "owner_unavailable") and not result.complete + # 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 62055a4c28b18b39a25fd196505aba1b6feb2bc0 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Fri, 4 Dec 2026 23:47:27 +0000 Subject: [PATCH 16/18] A worker turn out of time before its listing marks pass bound reached The turn marked the bound only when it cut a visit, so a turn whose time ran out after its last visit recorded no listing with no mark. The listing and lapsing steps now mark it too. The interval_seconds description fits the generated SDK comment, and the capacity paragraph is rewrapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 9 +++++---- docs/reference/operations/knowledge.md | 4 ++-- sdk/go/wire/models.gen.go | 2 +- sdk/typescript/src/generated/ops.ts | 4 ++-- server/knowledge/api/models_worker_setup.py | 3 +-- server/knowledge/app/source_sync_worker.py | 18 ++++++++++-------- tests/unit/test_worker_source_copies.py | 19 +++++++++++++++++++ 7 files changed, 40 insertions(+), 19 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 523301bf109..50ea039d34b 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -420,10 +420,11 @@ copy needs a check every half of `knowledge_source_acl_stale_seconds`, so the co 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. +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 diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 2b1af087c0b..c53a46a052d 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -972,7 +972,7 @@ Preview a worker source on the caller's linked account; nothing is written. | `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` 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, since a copy is read again only in a sync pass with room in the mirror document bound. | +| `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. | @@ -1021,7 +1021,7 @@ Register the worker source a preview showed, with its fingerprint and evidence. | `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` 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, since a copy is read again only in a sync pass with room in the mirror document bound. | +| `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/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index a05fce7d0dc..f488aad1fff 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: b2374b0571facb1d80da6631e2e1e0631c4c06b91cfeda92536ba407b55ca3ac +// Registry model schema SHA-256: b9a3de2bc237db20413eced90e39fa90d9de52e2d881b2a15a6c860e11ca2bb3 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 83b053043cd..14e5715cd4f 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4935,7 +4935,7 @@ export interface KnowledgeSourceWorkerPreviewInput { connection_id: string; /** `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, since a copy is read again only in */ + /** 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; @@ -5027,7 +5027,7 @@ export interface KnowledgeSourceWorkerRegisterInput { connection_id: string; /** `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, since a copy is read again only in */ + /** 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; diff --git a/server/knowledge/api/models_worker_setup.py b/server/knowledge/api/models_worker_setup.py index bb19bd71f63..b9a3f1db208 100644 --- a/server/knowledge/api/models_worker_setup.py +++ b/server/knowledge/api/models_worker_setup.py @@ -192,8 +192,7 @@ class WorkerSourceSetup(BaseModel): 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, since a copy is read again only" - " in a sync pass with room in the mirror document bound.", + " seconds between a resource's copies, 300 to 86400.", ) team_access: bool = Field( default=False, diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index f6c47ea1e83..bd16d8a978e 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -368,7 +368,10 @@ async def retire_lapsing(self, copies: list[_Copy]) -> None: 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 not failing or self.run.budget.exhausted() or not await self._authority_holds(): + 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: @@ -532,13 +535,12 @@ async def _vouch( """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] - or run.budget.exhausted() - or await documents.publications_owed(src.org, src.mirror, mirror_uri_suffix(src.source_id)) - ): + 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): diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index d7c138e772b..bcce419d94f 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -388,6 +388,25 @@ async def test_the_document_bound_stops_copies_but_not_checks(world) -> None: 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 @pytest.mark.parametrize("lost", ["directory", "writer", "routes"]) async def test_without_the_owners_authority_nothing_is_read_or_retired(world, lost) -> None: From 8e02d624c624365e8ab0a0543cef80c223fcb287 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 00:03:51 +0000 Subject: [PATCH 17/18] Mark a refresh the document bound holds back, and keep one retry rule A stored selected_refresh copy due for its refresh at an exhausted document bound was only checked, with no mark, so the turn read ok while refreshes waited; it now marks pass bound reached. The retry waits come from one helper, the lapsing step's pass-bound branch has a test, and rule 76 says N-1's retirement worker leaves an entry pending while an inactive worker row of that source ID remains. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../mcp-source-worker-boundary.md | 8 ++-- docs/architecture/rolling-upgrades.md | 36 ++++++++-------- server/knowledge/app/source_sync_worker.py | 43 +++++++++++-------- tests/unit/test_worker_source_copies.py | 32 ++++++++++++++ 4 files changed, 78 insertions(+), 41 deletions(-) diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index 50ea039d34b..dae2bde286e 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -24,10 +24,10 @@ This build serves the live read, the collection approval operations described in [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 that -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. +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 diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 9831751da9e..37b6d8bef77 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1156,25 +1156,25 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline 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 and retirement worker queue and delete 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 + its removal paths queue no worker copy, and its retirement worker leaves an entry + pending while an inactive worker row of that source ID remains. 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. + 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 diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index bd16d8a978e..43c31078eaf 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -329,13 +329,23 @@ async def _write(self, copy: _Copy, reading: WorkerReading) -> None: 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.""" - content = copy.copy_due(self.config.interval_seconds, now) and self.run.left > 0 - if not content and not copy.stored: - # Out of the document bound: a stored copy can still have its access checked. + 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 can still have its access checked. self.result.mark(sync.TurnMark.PASS_BOUND) - return True + if not copy.stored: + return True asked = datetime.now(UTC) try: answer = await self._exchange(copy.item, content=content) @@ -347,7 +357,7 @@ async def visit(self, copy: _Copy, now: datetime) -> bool: if copy.stored: copy.entry["copied_at"] = asked.isoformat() else: - copy.entry["retry_at"] = (asked + self._wait()).isoformat() + self._retry_later(copy, asked, resource_word=True) if copy.stored: copy.entry["verified_at"] = asked.isoformat() return True @@ -380,7 +390,7 @@ async def retire_lapsing(self, copies: list[_Copy]) -> None: self.result.removed += 1 copy.stored = False copy.entry.clear() - copy.entry["retry_at"] = (asked + self._wait()).isoformat() + self._retry_later(copy, asked, resource_word=True) self.result.note = "copy_unconfirmable" async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetime) -> bool: @@ -391,23 +401,20 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim # 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 resource without a copy waits, so the next turn - # reaches the others; a stored copy ends each turn it is checked in, and the + # 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: - # Not the resource's word, so the short wait of any turn-ending refusal. - copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() + 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() - copy.entry["retry_at"] = (asked + self._wait()).isoformat() + self._retry_later(copy, asked, resource_word=True) return True if reason == "unsupported" and not copy.stored: - # Nothing to keep: the resource waits before it is read again. - copy.entry["retry_at"] = (asked + self._wait()).isoformat() + 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; @@ -417,16 +424,14 @@ async def _refused(self, copy: _Copy, refusal: WorkerReadRefused, asked: datetim result.complete = False result.note = reason if not copy.stored: - # Nothing to keep, and it must not come first on every pass. - copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() + 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 resource without a copy waits, so the next turn - # reaches the others; a stored copy keeps the source's copies unserved until it - # answers, which fails closed. + # 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: - copy.entry["retry_at"] = (asked + _stale() / 2).isoformat() + self._retry_later(copy, asked, resource_word=False) result.fail(reason, reason) return False diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index bcce419d94f..a4de9ecae3a 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -407,6 +407,38 @@ async def check(scope, *, require_current): 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 @pytest.mark.parametrize("lost", ["directory", "writer", "routes"]) async def test_without_the_owners_authority_nothing_is_read_or_retired(world, lost) -> None: From fb7fa2d66b6674a22b9534b2af959614cebbf553 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 00:18:53 +0000 Subject: [PATCH 18/18] A refresh the document bound holds back is checked only when its check is due The previous change sent an access check every pass for a stored copy due for refresh at an exhausted document bound, however fresh its access, which spent the mirrored phase's time the capacity bound counts on. It now marks the bound and checks only when the copy's check is due. Rule 76 states N-1's pending retirement once, and the worker drops an authority refusal the close never meets. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/architecture/rolling-upgrades.md | 31 +++++++++---------- server/knowledge/app/source_sync_worker.py | 4 +-- .../loom_source_worker/mcp_client.py | 2 +- tests/unit/test_worker_source_copies.py | 11 +++++++ 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 37b6d8bef77..c0ff2f28821 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1156,22 +1156,21 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline 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, and its retirement worker leaves an entry - pending while an inactive worker row of that source ID remains. 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 + 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. diff --git a/server/knowledge/app/source_sync_worker.py b/server/knowledge/app/source_sync_worker.py index 43c31078eaf..9d1d4373cff 100644 --- a/server/knowledge/app/source_sync_worker.py +++ b/server/knowledge/app/source_sync_worker.py @@ -342,9 +342,9 @@ async def visit(self, copy: _Copy, now: datetime) -> bool: 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 can still have its access checked. + # 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: + if not copy.stored or not copy.check_due(now): return True asked = datetime.now(UTC) try: diff --git a/source_worker/loom_source_worker/mcp_client.py b/source_worker/loom_source_worker/mcp_client.py index 2815ccb1e84..18784d34676 100644 --- a/source_worker/loom_source_worker/mcp_client.py +++ b/source_worker/loom_source_worker/mcp_client.py @@ -108,7 +108,7 @@ def _error_code(error: BaseException) -> ErrorCode: # already missed, which the close does not wait out again. _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", "forbidden", "reconnect"}) +_AUTHORITY_REFUSALS: frozenset[ErrorCode] = frozenset({"denied", "reconnect"}) def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = True) -> None: diff --git a/tests/unit/test_worker_source_copies.py b/tests/unit/test_worker_source_copies.py index a4de9ecae3a..566d70b95d9 100644 --- a/tests/unit/test_worker_source_copies.py +++ b/tests/unit/test_worker_source_copies.py @@ -439,6 +439,17 @@ async def test_a_refresh_the_document_bound_holds_back_says_so(world) -> None: 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: