diff --git a/.github/workflows/crawl-native-privacy.yml b/.github/workflows/crawl-native-privacy.yml new file mode 100644 index 00000000000..951b2529665 --- /dev/null +++ b/.github/workflows/crawl-native-privacy.yml @@ -0,0 +1,98 @@ +name: Crawl native privacy + +on: + pull_request: + paths: + - "server/**" + - "schemas/migrations/**" + - "pyproject.toml" + - "uv.lock" + - "tests/integration/crawl_native_privacy.py" + - ".github/workflows/crawl-native-privacy.yml" + push: + branches: [main] + paths: + - "server/**" + - "schemas/migrations/**" + - "pyproject.toml" + - "uv.lock" + - "tests/integration/crawl_native_privacy.py" + - ".github/workflows/crawl-native-privacy.yml" + +permissions: + contents: read + +jobs: + crawl-native-privacy: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + LOOM_ENV_FILE: "" + LOOM_CH_CONTAINER: docsrc-crawl-${{ github.run_id }}-${{ github.run_attempt }} + LOOM_CH_HOST: 127.0.0.1 + LOOM_CH_PORT: "18123" + LOOM_CH_HOST_PORT: "18123" + LOOM_CH_NATIVE_HOST_PORT: "19000" + LOOM_CH_USER: loom + LOOM_CH_PASSWORD: loomdev + LOOM_CH_DATABASE: loom + LOOM_DEPLOYMENT: "1" + LOOM_INSTANCE_LABEL: ci-crawl-${{ github.run_id }}-${{ github.run_attempt }} + LOOM_BUILD_COMMIT: ${{ github.sha }} + LOOM_AUTH_REQUIRED: "true" + LOOM_STORAGE_AUTHORITY: clickhouse + LOOM_WORKERS_PROCESS: inline + LOOM_BACKGROUND_WORKERS: auto + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + LOOM_LLM_PROVIDER: fake + LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS: "60" + LOOM_KNOWLEDGE_SOURCE_SYNC_IDLE_INTERVAL_SECONDS: "60" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + - name: Install locked dependencies and build dashboard assets + run: | + uv sync --locked --python 3.12 --extra dev --extra code + npm --prefix frontend ci + npm --prefix frontend run build + - name: Configure the test signer + run: | + crawl_signer_material="$(openssl rand -hex 32)" + printf '::add-mask::%s\n' "$crawl_signer_material" + printf 'LOOM_JWT_SECRET=%s\n' "$crawl_signer_material" >> "$GITHUB_ENV" + - name: Start the owned backend + id: clickhouse + run: | + if docker container inspect "$LOOM_CH_CONTAINER" >/dev/null 2>&1; then + echo "refusing an existing backend container" >&2 + exit 1 + fi + LOOM_CLICKHOUSE_IMAGE="$(bash dev/clickhouse_release.sh)" + export LOOM_CLICKHOUSE_IMAGE + echo "admitted=true" >> "$GITHUB_OUTPUT" + bash dev/ci_start_clickhouse.sh + - name: Run the native privacy witness + run: >- + .venv/bin/python -m pytest tests/integration/crawl_native_privacy.py + -q --tb=short --junitxml=crawl-native-privacy.xml + - name: Preserve backend diagnostics + if: always() && steps.clickhouse.outputs.admitted == 'true' + run: docker logs "$LOOM_CH_CONTAINER" > crawl-native-clickhouse.log 2>&1 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() + with: + name: crawl-native-privacy + path: | + crawl-native-privacy.xml + crawl-native-clickhouse.log + if-no-files-found: ignore + - name: Remove the owned backend + if: always() && steps.clickhouse.outputs.admitted == 'true' + run: docker rm -f "$LOOM_CH_CONTAINER" diff --git a/dev/restore_connected_accounts.py b/dev/restore_connected_accounts.py index c7fb13b1fca..dc4e7f621b3 100644 --- a/dev/restore_connected_accounts.py +++ b/dev/restore_connected_accounts.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""End connected-account authority after restoring the configured deployment. +"""End connected-account and crawl-source authority after restoring the configured +deployment. Stop all serving processes and workers first. This command does not erase mirror contents; complete the deployment's mirror cleanup before serving again. @@ -17,32 +18,40 @@ from server.cli._apply import add_apply_flags from server.cli._ch import reads, run_connected, writes from server.knowledge.app.connected_restore import restore_all +from server.knowledge.app.crawl_restore import restore_all as restore_crawls def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) - add_apply_flags(parser, writes="stop and purge this deployment's connected accounts") + add_apply_flags( + parser, writes="stop and purge this deployment's connected accounts and crawl sources" + ) args = parser.parse_args(argv) async def run(ch: Any) -> int: await restore_all(apply=not args.dry_run, ch=ch) + await restore_crawls(apply=not args.dry_run, ch=ch) print( - "connected-account restore cleanup completed; connections must be established again" + ( + "connected-account and crawl restore cleanup completed; connections and " + "crawl sources must be registered again" + ) if not args.dry_run - else "dry run: no connection authority was changed" + else "dry run: no connection or crawl authority was changed" ) return 0 gate = ( - reads("plans this deployment's connection restore cleanup") + reads("plans this deployment's connection and crawl restore cleanup") if args.dry_run - else writes("purges this deployment's restored connection authority") + else writes("purges this deployment's restored connection and crawl authority") ) try: return run_connected(run, org_free=gate) except Exception: # noqa: BLE001 — maintenance errors must not print credentials or stored metadata print( - "connected-account restore cleanup failed; keep the deployment stopped", file=sys.stderr + "connected-account or crawl restore cleanup failed; keep the deployment stopped", + file=sys.stderr, ) return 1 diff --git a/docs/architecture/clickhouse.md b/docs/architecture/clickhouse.md index bdf2604ce2e..53a5ac28b4b 100644 --- a/docs/architecture/clickhouse.md +++ b/docs/architecture/clickhouse.md @@ -710,6 +710,19 @@ with `purge=true`, stale vector caches, runner state, and the supersession rows refused because an erasure removed the document it was built from deletes the chunk rows it inserted (lightweight `DELETE FROM loom.chunks` by source and version, `chunks.delete_versions`), so its text and author do not outlive the erasure. +- **Crawl approval resealing** conditionally updates only the matching old + `approval_enc` for an exact org, namespace and source id, under the source lease. It + rewrites raw versions and checks for old-ciphertext residue before the previous root + is retired. +- **Crawl restore invalidation** clears `active`, `approval_enc` and `crawl_generation` + on every raw crawl version of an org after an offline restore, then checks for + residue, so no restored version reactivates delegated source authority. +- **Source registry publishers** bound every INSERT under the source lease by its + claim's receiver deadline. An unanswered send retains its Keeper key until expiry; the + receiver's latest possible completion precedes that expiry. Nested claims retain the + earliest deadline and every unanswered send, so a later holder cannot rewrite raw + history while an older send may still append to it. An insufficient claim window + refuses before publishing. - **Remaining `ALTER … UPDATE/DELETE` call sites** are listed in `tests/unit/test_clickhouse_mutation_inventory.py`, which fails on a new one until it is classified there. diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index cac5bb4b72d..9d60a001819 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -162,11 +162,11 @@ and writes the source at its next version under the namespace's source lease. It row, and `add`'s, names the namespace, the name and the items added and removed, with a crawl's `subjects` and every field of a mirrored source's items as keyed hashes (below). Removing every item is refused (`BAD_CONFIG`); `remove` ends a source. Changing `access` -is a new source. For a `crawl`, `update` also takes `subjects` (the new list, probed -like added items) and `directory_subject`. Every `update` and `rotate` of a crawl needs -the same roles as `add`, since its credential reads every listed person's drive: a -namespace admin without an org-wide role cannot change whose drives it reads, what it -reads of them (items, `include`) or the key it reads with. +is a new source. For a `crawl`, `update` also takes `crawl_options` (its new `subjects`, +probed like added items, and `directory_subject`). Every `update` and `rotate` of a +crawl needs the same roles as `add`, since its credential reads every listed person's +drive: a namespace admin without an org-wide role cannot change whose drives it reads, +what it reads of them (items, `include`) or the key it reads with. ### One document, one owner @@ -227,14 +227,15 @@ A source has a `credential_mode`: | `crawl` | A service account with domain-wide delegation that reads, as each listed person, what that person can read | an `admin` of the namespace who also holds `org_admin` or `platform_admin` | the namespace's mirror | The gate of `add`, `update`, `check`, `sync_now` and `remove` drops from `admin` to -`writer`. The handler then requires `admin` for a `shared` or `crawl` source. On a -`connected` source only its owner adds items or changes `include`, since the items read -with the owner's account; its owner or an admin of the namespace may `check`, `sync_now` -and `remove` it, and only its owner, who sees them, removes its items. `rotate` stays -`admin` (for a crawl, also an org-wide role) and is refused for a `connected` source, -whose credential is its owner's connection. Owners are compared as canonical subjects -(`server/auth/aliases.py` `canonical_subject`), so a person's other spellings are the -same owner. +`writer`. The handler then requires `admin` for a `shared` source, and for a `crawl` +source `admin` of the namespace with `org_admin` or `platform_admin` on every one of +those ops. On a `connected` source only its owner adds items or changes `include`, since +the items read with the owner's account; its owner or an admin of the namespace may +`check`, `sync_now` and `remove` it, and only its owner, who sees them, removes its +items. `rotate` stays `admin` (for a crawl, also the org-wide role) and is refused for a +`connected` source, whose credential is its owner's connection. Owners are compared as +canonical subjects (`server/auth/aliases.py` `canonical_subject`), so a person's other +spellings are the same owner. `LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE` (default 8) bounds a namespace's `shared` and `crawl` sources, as today. `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_PERSON` (default 8) @@ -373,27 +374,60 @@ directory, so it expands no group ([below](#who-may-read)). A `crawl` source's credential is a service-account key whose client id the org's workspace administrator granted domain-wide delegation for `drive.readonly`, -`admin.directory.group.member.readonly` and `admin.directory.user.readonly`. Its config -holds `directory_subject` (a workspace administrator the directory reads impersonate) -and `subjects`: people (emails) and groups (group emails), whose members the directory -read lists at each turn, at most 2000 people (not a setting). For each person the sync -exchanges the key for a token that impersonates them (the JWT bearer grant with `sub`) -and lists the source's items as them. A typical config is one `meet_recordings` item and -a `filter` with `kinds: [docs]`, over a group: every member's meeting notes, without -anyone connecting. Every list and members row the sync writes, a crawl's expansion -included, leaves out the people an erasure excluded ([erasure](#erasure-and-audit)). +`admin.directory.group.member.readonly` and `admin.directory.user.readonly`. Its +`crawl_options` field holds `directory_subject` (a workspace administrator the directory +reads impersonate) and `subjects`: people (emails) and groups (group emails), whose +members the directory read lists at each turn, at most 2000 people (not a setting). For +each person the sync exchanges the key for a token that impersonates them (the JWT +bearer grant with `sub`) and lists the source's items as them. A typical config is one +`meet_recordings` item and a `filter` with `kinds: [docs]`, over a group: every member's +meeting notes, without anyone connecting. Each turn's expansion leaves out every person +SCIM has deactivated or deleted ([erasure](#erasure-and-audit)). The probe checks that the delegation grants no write on what the crawl reads: it asks for each of the three scopes, which must be granted, and for -`https://www.googleapis.com/auth/drive`, `admin.directory.user` and -`admin.directory.group`, which the store must refuse; a credential the store grants any -of them is refused (`CREDENTIAL_REFUSED`). It cannot prove the delegation grants nothing -else (a mail scope, say), and the page says so to the admin who registers it. The audit -rows of `add`, `update` and `rotate` record the configured subjects as keyed hashes (an -HMAC under the root secret, as SCIM's audit rows hash a subject, so a list of the org's -addresses does not reverse them). Audit rows also record the scopes granted and the -number of members resolved: the audit trail outlives erasure and keeps no crawled -person's address. +`https://www.googleapis.com/auth/drive`, `admin.directory.user`, `admin.directory.group` +and the distinct `admin.directory.group.member` write scope, which the store must +refuse; a credential the store grants any of them is refused (`CREDENTIAL_REFUSED`). A +network failure, a rate limit, a 5xx or the registration's deadline answers +`BACKEND_UNAVAILABLE` instead, since the store refused nothing: retryable from `check`, +while `add`, `update` and `rotate` report `retryable: false` as non-idempotent ops, +although a failure before the commit wrote nothing. It cannot prove the delegation +grants nothing else (a mail scope, say), and the page says so to the admin who registers +it. The audit rows of `add`, `update` and `rotate` record the configured subjects as +keyed hashes (an HMAC under the root secret, as SCIM's audit rows hash a subject, so a +list of the org's addresses does not reverse them). Audit rows also record the scopes +granted and the number of members resolved: the audit trail outlives erasure and keeps +no crawled person's address. + +Registration, update and rotation require a current org administrator who also +administers the source namespace. Each approval binds the signing-key lifecycle, +canonical registrant, exact selectors, items, credential hash, verified Workspace +customer and source generation. Workers recheck that authority after provider and +model waits and under the source lease. An indexed read uses the same local approval +without opening a credential or contacting Google. Only a complete union listing stamped +with the source generation admits copies; updating a registration cannot reuse its old +listing. A check reports delegation standing without document titles or counts. + +An approval lasts as long as the credential that registered it: it ends when that +token expires, when its session or subject is revoked, or when its signing key +retires. The crawl then stops and its copies stop answering reads. While the +approval holds, any `knowledge.source.update` reapproves the source under the +caller's credential. Once it has ended, an administrator renews it with +`knowledge.source.rotate`, giving the service-account key again. Register with a +long-lived administrator token, not a sign-in session's access token, for a crawl +that must keep running. + +A person SCIM has deactivated or deleted is left out of the expansion: each person's +Workspace addresses (primary and aliases) are checked against `scim_users` in one read, +since a SCIM id is the uuid5 of the email. The same read runs at every checkout of that +person's Drive grant, so a deactivation during a turn stops that person's reads and the +publication that would follow them. A reactivated person is expanded again on the next +turn. A selected person or group member the Workspace has suspended, archived or moved +to another customer is left out the same way; a selection whose every person is out +still registers, with no members. A selected address the Directory does not know +refuses each turn until an admin updates the selection, so a typo is not read as a +departure. ## Access follows the source @@ -997,13 +1031,21 @@ pass, and until it completes the source's listing row keeps its older start, so source needs a stale bound longer than the time to list it all. `inspect` and `loom doctor` report each source's oldest listing start, a mirrored source's to a platform admin only (its connected owner sees fresh or stale). A stopped sync hides every -mirrored document once the stale bound passes. The implementing pull request measures -the writes of a crawl over 2000 people and puts the figures here. - -How lists from several accounts of one source, a person a crawl stops reading, a stopped -source's rows, and restores of either store are handled is the implementing pull -request's to specify against these four parts; each must leave no list or row that -admits someone the store no longer names. +mirrored document once the stale bound passes. + +A crawl lists each eligible person's files with that person's access and publishes only +when every listing is complete: each copy keeps the file's own permission list, and a +copy retires only once every eligible presenter's complete listing no longer reaches it. +Each presenter asked spends one unit of the pass budget, and with no eligible presenter +left a copy nobody reaches retires. A removed or retired source queues its copies for +retirement under its mirror and source id, and its row keeps no credential, selection or +approval. An offline restore retires every crawl source the same way and clears every +stored approval, so no restored row admits a reader until an administrator registers the +source again. Every published file is checked against the source row, the registrant's +cached approval and each presenter's standing before and after its write, under the +namespace's sources lease, which the file's write takes twice; a turn at +`knowledge_crawl_max_files` therefore makes on the order of a million local reads and +competes with that namespace's other source writes for the lease. ### Threat model @@ -1017,7 +1059,7 @@ admits someone the store no longer names. | A person leaves a group and keeps reading through it (group churn) | Groups are read with every complete listing into a members row with its `read_at`; a stale or unread group admits nobody. | the access check | | Auth is switched off after mirrors exist | The `acl-` refusal runs before the auth-off return; mirror legs answer nothing and the sync skips mirrored sources while auth is off. | `check_authorized`; the mirror legs | | A person leaves the org and their connected sources keep syncing | SCIM deactivation and disconnect stop the sources and clear the credential, then revoke it at the store; each turn's owner check skips a source whose owner is revoked, deactivated or no longer a writer. | `server/auth/scim.py`; the sync's turn | -| A crawl reads more than its registrant meant, or can write | An org-wide role to register, update or rotate; the probe requires the store to refuse a write scope; subjects and scopes in the audit row. | the crawl probe; `loom.audit_log` | +| A crawl reads more than its registrant meant, or can write | An org-wide role to register, update, rotate, check, sync or remove; the probe requires the store to refuse a write scope; subjects and scopes in the audit row. | the crawl probe; `loom.audit_log` | | An id-addressed read confirms a mirrored document exists | `get`, `outline`, `download` and the inspects answer `found=false` or leave out an address the reader may not see. | the mirror legs | | A viewer or admin learns what a mirror holds from an op that is not a checked leg | A source's probe, status and `remove`, and an erasure's receipt, answer codes for a mirror; its counts go to a platform admin only. | the source ops; the erasure handlers | | A new read path shows mirrored documents to everyone | Mirrored documents live in a namespace no grant opens and no listing names; a path that does not read the mirror shows none, and no org-wide scope names an `acl-` namespace. | `check_authorized` (`acl-[0-9a-f]{24}`); the scope helpers ([the mirror](#the-mirror)) | @@ -1235,11 +1277,10 @@ statements and census keys against these, and its tests pin each one: failure reveals no special code or failed stage. Full internal evidence remains available for recovery and authorized platform-admin status reads. -- A person's connected accounts, the sources they own with every mirrored copy those - wrote, and their entries in every crawl are erased when an org admin asks; afterwards - no source row, list or members row names them, and a crawl reads them again only once - an org admin readmits them. The pull request that builds connected accounts and crawls - designs that erasure. +- A person's connected accounts and the sources they own, with every mirrored copy those + wrote, are erased when an org admin asks; afterwards no source row names them. + Canonical-person deletion runs from the required SCIM lifecycle; it never infers that a + memory `user_id` names a sign-in subject. - Private canonical-owner cleanup uses the exact `(org, subject, kind)` key independently of namespace and end-user erasure. Disconnect and deactivation fence the generation, clear the current credential, queue every owned source for retirement, then physically @@ -1250,6 +1291,17 @@ statements and census keys against these, and its tests pin each one: mean an end-user principal and never guesses a sign-in subject from an id or email. Source retirement remains queued until the existing mirror retirement worker finishes; account cleanup alone does not certify that every source copy or crawl entry is erased. +- A person SCIM deactivates or deletes is left out of every later crawl turn and cannot + authenticate as a mirrored reader. The copies only they presented drop out of the + union, so the next complete turn writes an empty permission list for them and they stop + answering reads within one sync interval: the same bound the crawl accepts for any + permission change. They retire once the people still selected confirm the files are + gone. Three records can still name the person by address: a source's selection names a + selected person until an admin updates it; the group membership rows name them until + the next complete turn rewrites them; and a copy other people still present keeps the + permission list Drive reports, which drops them when Drive does. None of these admits + them, since they cannot sign in; erasing them is the namespace's or the source's + erasure. - `erasure.request` refuses an `acl-` scope for every caller but a platform admin with auth on, and `erasure.export` refuses one for every caller (an export would read the mirror's chunks with no permission check); with auth off both refuse it for everyone. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index d7c2add7413..449ffee9ed7 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1035,6 +1035,12 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_KNOWLEDGE_CONNECTED_LEASE_WAIT_S` | `float` | `5.0` | | Seconds a connection change waits for another holder's account-generation lease. | | `LOOM_KNOWLEDGE_CONNECTED_REGISTRY_SCAN_LIMIT` | `int` | `4096` | | Maximum complete owner scan; exceeding it refuses instead of stopping a subset. | | `LOOM_KNOWLEDGE_CONNECTED_REGISTRY_PAGE_SIZE` | `int` | `256` | | Registrations per page during root-secret resealing. | +| `LOOM_KNOWLEDGE_CRAWL_DIRECTORY_MAX_RESPONSE_BYTES` | `int` | `1048576` | | Bytes read from one delegated Directory or OAuth response; larger responses refuse. | +| `LOOM_KNOWLEDGE_CRAWL_DIRECTORY_MAX_PAGES` | `int` | `256` | | Directory membership pages across the entire expansion, including nested groups. | +| `LOOM_KNOWLEDGE_CRAWL_MAX_GROUPS` | `int` | `2000` | | Groups across one complete crawl expansion; the total-person ceiling stays fixed. | +| `LOOM_KNOWLEDGE_CRAWL_MAX_FILES` | `int` | `10000` | | Distinct files across every person's complete listing; a larger union publishes nothing. | +| `LOOM_KNOWLEDGE_CRAWL_REGISTRY_SCAN_LIMIT` | `int` | `4096` | | Crawl registry rows one reseal or restore reads: the orgs, each org's raw source versions, the source names a reseal pages through in all, and each name's approvals. A larger set refuses instead of doing partial work. | +| `LOOM_KNOWLEDGE_CRAWL_REGISTRY_PAGE_SIZE` | `int` | `256` | | Crawl sources per root-secret reseal page. | | `LOOM_KNOWLEDGE_CONNECTED_OAUTH_TIMEOUT_S` | `float` | `30.0` | | Seconds one connected-account OAuth request may take, including its response. The caller's remaining deadline can shorten this bound. | | `LOOM_KNOWLEDGE_CONNECTED_OAUTH_RESPONSE_MAX_BYTES` | `int` | `65536` | | Bytes read from a connected-account token or identity response; larger metadata replies are refused before parsing. | | `LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE` | `int` | `8` | live | Active document sources (knowledge.source.add) one namespace may register; an add past it is refused with SOURCE_QUOTA. | diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 54a6f0c7785..56e4a383cbf 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -446,7 +446,7 @@ Raised in `server/tracker/app/sources.py`. #### `CREDENTIAL_REFUSED` -Raised in `server/knowledge/app/connected_sources.py`, `server/knowledge/app/sources.py`. +Raised in `server/knowledge/app/connected_sources.py`, `server/knowledge/app/crawl_sources.py`, `server/knowledge/app/sources.py`. #### `CROSS_SITE_REQUEST` diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 1a4f72d5f16..be9a4c5c300 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -624,12 +624,14 @@ Register a document source on a namespace: a kind, what it reads (items and link | `links` | `list[str] \| None` | `None` | Links to folders, files, documents, slides, pages, databases or projects, read as items (`knowledge.source.parse_links`); an unreadable link refuses the call (BAD_LINK). | | `config` | `dict[str, Any] \| None` | `None` | What the source reads in the form that names ids per kind, instead of items or links; gdrive: {folder_ids: [1-20 folder ids], include: [docs, slides, pdf, pptx, docx] (default all but docx)}; linear: {project_ids: [1-20 project ids… | | `include` | `list[str] \| None` | `None` | gdrive with items or links: the file kinds read, of docs, slides, pdf, pptx, docx (default all but docx). | -| `credential_mode` | `Literal['shared', 'connected']` | `'shared'` | Use the supplied shared credential, or your own mirrored connected account. | +| `credential_mode` | `Literal['shared', 'connected', 'crawl']` | `'shared'` | Use shared credentials, your connected account, or approved Workspace delegation. | +| `crawl_options` | `KnowledgeSourceCrawlOptions \| None` | `None` | Crawl only: delegation identity and explicit people or groups; default none. | | `credential` | `str` | `''` | The source's read-only credential (gdrive: a service account's JSON key, with the folders shared to the account read-only; linear: a read-only API key of an account that sees the projects; notion: an integration token with read content… | | `dry_run` | `bool` | `False` | Probe and write nothing. | | Output field | Type | Meaning | | --- | --- | --- | +| `crawl_proof` | `KnowledgeSourceCrawlProof \| None` | Crawl only: checked scope and keyed-subject proof; None for another credential mode. | | `name` | `str` | The registered source's name, normalised. | | `kind` | `str` | The source kind, normalised. | | `namespace` | `str` | The namespace the source was registered on. | @@ -681,6 +683,7 @@ One registered document source: its items, its sync state and the documents it w | `kind` | `str` | The source's kind. | | `credential_mode` | `str` | The registration's credential class; never the credential or account identity. | | `access` | `str` | Namespace-wide or checked mirrored document access. | +| `crawl_options` | `dict[str, Any]` | Crawl selectors, only for a current org and namespace administrator. | | `owner_subject` | `str` | Canonical connected owner, only in the owner's permitted detail projection. | | `items` | `list[dict[str, Any]]` | The things the source reads; [] for a recording source. | | `include` | `list[str]` | The file kinds a gdrive source reads; [] for another kind. | @@ -841,6 +844,7 @@ Replace a registered document source's credential. | Output field | Type | Meaning | | --- | --- | --- | +| `crawl_proof` | `KnowledgeSourceCrawlProof \| None` | Crawl only: checked scope and keyed-subject proof; None for another credential mode. | | `name` | `str` | The source whose credential was replaced. | | `probe` | `KnowledgeSourceProbe` | What the probe with the new credential found. | | `rotated_at` | `str` | When the credential was replaced, ISO UTC. | @@ -878,10 +882,12 @@ Add items to a registered document source or remove them, or change a gdrive sou | `add_links` | `list[str]` | *(computed)* | Links to add, read as items; a link to something the source holds names it as held (a recursive folder, a drive at its root), and an add_items entry for the same thing wins. | | `remove_items` | `list[dict[str, Any]]` | *(computed)* | Items to remove, matched by type and id (a filter by its fields); a folder entry also removes a shared drive of the same id the source holds. | | `remove_links` | `list[str]` | *(computed)* | Links to remove, read as items; a folder link also removes a shared drive of the same id the source holds. | +| `crawl_options` | `KnowledgeSourceCrawlOptions \| None` | `None` | Crawl only: replace the explicit delegation selectors; default unchanged. | | `include` | `list[str] \| None` | `None` | gdrive only: the new file kinds read, of docs, slides, pdf, pptx, docx; default unchanged. | | Output field | Type | Meaning | | --- | --- | --- | +| `crawl_proof` | `KnowledgeSourceCrawlProof \| None` | Crawl only: checked scope and keyed-subject proof; None for another credential mode. | | `name` | `str` | The source updated. | | `items` | `list[dict[str, Any]]` | The source's items as now stored. | | `include` | `list[str]` | The file kinds a gdrive source reads; [] for another kind. | diff --git a/loom.example.yaml b/loom.example.yaml index ab052503454..355790df12e 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -3077,6 +3077,30 @@ settings: # Registrations per page during root-secret resealing. [restart] # knowledge_connected_registry_page_size: 256 + # Bytes read from one delegated Directory or OAuth response; larger responses refuse. + # [restart] + # knowledge_crawl_directory_max_response_bytes: 1048576 + + # Directory membership pages across the entire expansion, including nested groups. + # [restart] + # knowledge_crawl_directory_max_pages: 256 + + # Groups across one complete crawl expansion; the total-person ceiling stays fixed. + # [restart] + # knowledge_crawl_max_groups: 2000 + + # Distinct files across every person's complete listing; a larger union publishes + # nothing. [restart] + # knowledge_crawl_max_files: 10000 + + # Crawl registry rows one reseal or restore reads: the orgs, each org's raw source + # versions, the source names a reseal pages through in all, and each name's approvals. + # A larger set refuses instead of doing partial work. [restart] + # knowledge_crawl_registry_scan_limit: 4096 + + # Crawl sources per root-secret reseal page. [restart] + # knowledge_crawl_registry_page_size: 256 + # Seconds one connected-account OAuth request may take, including its response. The # caller's remaining deadline can shorten this bound. [restart] # knowledge_connected_oauth_timeout_s: 30.0 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index bef78fe9d2f..64c1a982623 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -3345,6 +3345,43 @@ "type": "number", "description": "Seconds for local connection stops, including their source retirement writes." }, + "knowledge_crawl_directory_max_pages": { + "default": 256, + "minimum": 1, + "type": "integer", + "description": "Directory membership pages across the entire expansion, including nested groups." + }, + "knowledge_crawl_directory_max_response_bytes": { + "default": 1048576, + "minimum": 1024, + "type": "integer", + "description": "Bytes read from one delegated Directory or OAuth response; larger responses refuse." + }, + "knowledge_crawl_max_files": { + "default": 10000, + "minimum": 1, + "type": "integer", + "description": "Distinct files across every person's complete listing; a larger union publishes nothing." + }, + "knowledge_crawl_max_groups": { + "default": 2000, + "minimum": 1, + "type": "integer", + "description": "Groups across one complete crawl expansion; the total-person ceiling stays fixed." + }, + "knowledge_crawl_registry_page_size": { + "default": 256, + "maximum": 4096, + "minimum": 1, + "type": "integer", + "description": "Crawl sources per root-secret reseal page." + }, + "knowledge_crawl_registry_scan_limit": { + "default": 4096, + "minimum": 1, + "type": "integer", + "description": "Crawl registry rows one reseal or restore reads: the orgs, each org's raw source versions, the source names a reseal pages through in all, and each name's approvals. A larger set refuses instead of doing partial work." + }, "knowledge_gaps_enabled": { "default": false, "type": "boolean", diff --git a/schemas/migrations/119_workspace_crawl.sql b/schemas/migrations/119_workspace_crawl.sql new file mode 100644 index 00000000000..4f4d53dc0cc --- /dev/null +++ b/schemas/migrations/119_workspace_crawl.sql @@ -0,0 +1,10 @@ +-- Crawl admission stays closed until every process validates its registration authority. +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS options_json String DEFAULT '{}'; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS registrant_subject String DEFAULT ''; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS approval_enc String DEFAULT ''; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS crawl_generation String DEFAULT ''; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS crawl_customer_id String DEFAULT ''; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS crawl_credential_hash String DEFAULT ''; + +-- Only a complete listing of this exact registration generation admits its copies. +ALTER TABLE loom.knowledge_source_listings ADD COLUMN IF NOT EXISTS crawl_generation String DEFAULT ''; diff --git a/schemas/schema.sql b/schemas/schema.sql index 34d893c8c77..e21facf7b62 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -2266,7 +2266,8 @@ CREATE TABLE IF NOT EXISTS loom.knowledge_source_listings `source_id` String, `name` String, `started_at` DateTime64(3), - `version` UInt64 DEFAULT toUInt64(toUnixTimestamp64Nano(now64(9))) + `version` UInt64 DEFAULT toUInt64(toUnixTimestamp64Nano(now64(9))), + `crawl_generation` String DEFAULT '' ) ENGINE = ReplacingMergeTree(version) ORDER BY (org, namespace, source_id) @@ -2319,7 +2320,13 @@ CREATE TABLE IF NOT EXISTS loom.knowledge_sources `access` LowCardinality(String) DEFAULT 'namespace', `credential_mode` LowCardinality(String) DEFAULT 'shared', `owner_subject` String DEFAULT '', - `connection_id` String DEFAULT '' + `connection_id` String DEFAULT '', + `options_json` String DEFAULT '{}', + `registrant_subject` String DEFAULT '', + `approval_enc` String DEFAULT '', + `crawl_generation` String DEFAULT '', + `crawl_customer_id` String DEFAULT '', + `crawl_credential_hash` String DEFAULT '' ) ENGINE = ReplacingMergeTree(version) ORDER BY (org, namespace, name) diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index a43305bf158..eacf7b3ebfc 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -1397,6 +1397,15 @@ type KnowledgeSourceCheckInput = wire.KnowledgeSourceCheckInput // KnowledgeSourceCheckOutput is the response from knowledge.source.check. type KnowledgeSourceCheckOutput = wire.KnowledgeSourceCheckOutput +// KnowledgeSourceCrawlOptions is a model used by Loom operations. +type KnowledgeSourceCrawlOptions = wire.KnowledgeSourceCrawlOptions + +// KnowledgeSourceCrawlProof is a model used by Loom operations. +type KnowledgeSourceCrawlProof = wire.KnowledgeSourceCrawlProof + +// KnowledgeSourceCrawlSubject is a model used by Loom operations. +type KnowledgeSourceCrawlSubject = wire.KnowledgeSourceCrawlSubject + // KnowledgeSourceDocument is a model used by Loom operations. type KnowledgeSourceDocument = wire.KnowledgeSourceDocument diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 7eefc5fd6fb..08159ca9c17 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: 2bbacf08033ddb0d38cc26fa5fdf514d3d49a9659f9bdd5c0452ffeffa751179 +// Registry model schema SHA-256: d5a1c9cfcaca089ca9aa9915834fb786c033ae9ed778ce7340291371184a2601 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -5536,23 +5536,25 @@ type KnowledgeSourceAddInput struct { Config Optional[map[string]json.RawMessage] `json:"config,omitempty"` Include Optional[[]string] `json:"include,omitempty"` CredentialMode *string `json:"credential_mode,omitempty"` + CrawlOptions Optional[KnowledgeSourceCrawlOptions] `json:"crawl_options,omitempty"` Credential *string `json:"credential,omitempty"` DryRun *bool `json:"dry_run,omitempty"` } // KnowledgeSourceAddOutput is the response from knowledge.source.add. type KnowledgeSourceAddOutput struct { - IgnoredArgs *[]string `json:"ignored_args,omitempty"` - DidYouMean *map[string]string `json:"did_you_mean,omitempty"` - Mirrored *bool `json:"mirrored,omitempty"` - Name string `json:"name"` - Kind string `json:"kind"` - Namespace string `json:"namespace"` - Items *[]map[string]json.RawMessage `json:"items,omitempty"` - Include *[]string `json:"include,omitempty"` - Config *map[string]json.RawMessage `json:"config,omitempty"` - Probe *KnowledgeSourceProbe `json:"probe,omitempty"` - DryRun *bool `json:"dry_run,omitempty"` + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` + Name string `json:"name"` + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Items *[]map[string]json.RawMessage `json:"items,omitempty"` + Include *[]string `json:"include,omitempty"` + Config *map[string]json.RawMessage `json:"config,omitempty"` + Probe *KnowledgeSourceProbe `json:"probe,omitempty"` + DryRun *bool `json:"dry_run,omitempty"` } // KnowledgeSourceCheckInput is the request to knowledge.source.check. @@ -5578,6 +5580,26 @@ type KnowledgeSourceCheckOutput struct { CheckedAt *string `json:"checked_at,omitempty"` } +// KnowledgeSourceCrawlOptions is a model used by Loom operations. +type KnowledgeSourceCrawlOptions struct { + DirectorySubject string `json:"directory_subject"` + Subjects []KnowledgeSourceCrawlSubject `json:"subjects"` +} + +// KnowledgeSourceCrawlProof is a model used by Loom operations. +type KnowledgeSourceCrawlProof struct { + SubjectHashes []string `json:"subject_hashes"` + ReadScopes []string `json:"read_scopes"` + WriteDenials []string `json:"write_denials"` + Members int64 `json:"members"` +} + +// KnowledgeSourceCrawlSubject is a model used by Loom operations. +type KnowledgeSourceCrawlSubject struct { + Type string `json:"type"` + Email string `json:"email"` +} + // KnowledgeSourceDocument is a model used by Loom operations. type KnowledgeSourceDocument struct { SourceURI string `json:"source_uri"` @@ -5592,6 +5614,7 @@ type KnowledgeSourceEntry struct { Kind string `json:"kind"` CredentialMode *string `json:"credential_mode,omitempty"` Access *string `json:"access,omitempty"` + CrawlOptions *map[string]json.RawMessage `json:"crawl_options,omitempty"` OwnerSubject *string `json:"owner_subject,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` Include *[]string `json:"include,omitempty"` @@ -5617,6 +5640,7 @@ type KnowledgeSourceInspectOutput struct { Kind string `json:"kind"` CredentialMode *string `json:"credential_mode,omitempty"` Access *string `json:"access,omitempty"` + CrawlOptions *map[string]json.RawMessage `json:"crawl_options,omitempty"` OwnerSubject *string `json:"owner_subject,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` Include *[]string `json:"include,omitempty"` @@ -5722,12 +5746,13 @@ type KnowledgeSourceRotateInput struct { // KnowledgeSourceRotateOutput is the response from knowledge.source.rotate. type KnowledgeSourceRotateOutput struct { - IgnoredArgs *[]string `json:"ignored_args,omitempty"` - DidYouMean *map[string]string `json:"did_you_mean,omitempty"` - Mirrored *bool `json:"mirrored,omitempty"` - Name string `json:"name"` - Probe *KnowledgeSourceProbe `json:"probe,omitempty"` - RotatedAt *string `json:"rotated_at,omitempty"` + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` + Name string `json:"name"` + Probe *KnowledgeSourceProbe `json:"probe,omitempty"` + RotatedAt *string `json:"rotated_at,omitempty"` } // KnowledgeSourceSync is a model used by Loom operations. @@ -5769,28 +5794,30 @@ type KnowledgeSourceSyncNowOutput struct { // KnowledgeSourceUpdateInput is the request to knowledge.source.update. type KnowledgeSourceUpdateInput struct { - Org string `json:"org"` - Namespace string `json:"namespace"` - Name string `json:"name"` - AddItems *[]map[string]json.RawMessage `json:"add_items,omitempty"` - AddLinks *[]string `json:"add_links,omitempty"` - RemoveItems *[]map[string]json.RawMessage `json:"remove_items,omitempty"` - RemoveLinks *[]string `json:"remove_links,omitempty"` - Include Optional[[]string] `json:"include,omitempty"` + Org string `json:"org"` + Namespace string `json:"namespace"` + Name string `json:"name"` + AddItems *[]map[string]json.RawMessage `json:"add_items,omitempty"` + AddLinks *[]string `json:"add_links,omitempty"` + RemoveItems *[]map[string]json.RawMessage `json:"remove_items,omitempty"` + RemoveLinks *[]string `json:"remove_links,omitempty"` + CrawlOptions Optional[KnowledgeSourceCrawlOptions] `json:"crawl_options,omitempty"` + Include Optional[[]string] `json:"include,omitempty"` } // KnowledgeSourceUpdateOutput is the response from knowledge.source.update. type KnowledgeSourceUpdateOutput struct { - IgnoredArgs *[]string `json:"ignored_args,omitempty"` - DidYouMean *map[string]string `json:"did_you_mean,omitempty"` - Mirrored *bool `json:"mirrored,omitempty"` - Name string `json:"name"` - Items *[]map[string]json.RawMessage `json:"items,omitempty"` - Include *[]string `json:"include,omitempty"` - Config *map[string]json.RawMessage `json:"config,omitempty"` - Added *[]map[string]json.RawMessage `json:"added,omitempty"` - Removed *[]map[string]json.RawMessage `json:"removed,omitempty"` - Probe *KnowledgeSourceProbe `json:"probe,omitempty"` + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` + Name string `json:"name"` + Items *[]map[string]json.RawMessage `json:"items,omitempty"` + Include *[]string `json:"include,omitempty"` + Config *map[string]json.RawMessage `json:"config,omitempty"` + Added *[]map[string]json.RawMessage `json:"added,omitempty"` + Removed *[]map[string]json.RawMessage `json:"removed,omitempty"` + Probe *KnowledgeSourceProbe `json:"probe,omitempty"` } // KnowledgeSynthesizeInput is the request to knowledge.synthesize. diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 9eda95c644e..c5b1cb0fcb5 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -11996,11 +11996,26 @@ class KnowledgeSourceAddInput(TypedDict, total=False): links: NotRequired[Optional[list[str]]] config: NotRequired[Optional[dict[str, Any]]] include: NotRequired[Optional[list[str]]] - credential_mode: NotRequired[Literal["shared", "connected"]] + credential_mode: NotRequired[Literal["shared", "connected", "crawl"]] + crawl_options: NotRequired[Optional["KnowledgeSourceCrawlOptions"]] credential: NotRequired[str] dry_run: NotRequired[bool] +class KnowledgeSourceCrawlOptions(TypedDict, total=False): + "Delegation identity and the complete bounded union of selected people." + + directory_subject: Required[str] + subjects: Required[list["KnowledgeSourceCrawlSubject"]] + + +class KnowledgeSourceCrawlSubject(TypedDict, total=False): + "An explicitly selected Workspace person or group, resolved through Directory." + + type: Required[Literal["person", "group"]] + email: Required[str] + + class KnowledgeSourceAddBody(TypedDict, total=False): "Register a document source on a namespace: a kind, what it reads (items" @@ -12012,12 +12027,14 @@ class KnowledgeSourceAddBody(TypedDict, total=False): links: NotRequired[Optional[list[str]]] config: NotRequired[Optional[dict[str, Any]]] include: NotRequired[Optional[list[str]]] - credential_mode: NotRequired[Literal["shared", "connected"]] + credential_mode: NotRequired[Literal["shared", "connected", "crawl"]] + crawl_options: NotRequired[Optional["KnowledgeSourceCrawlOptions"]] credential: NotRequired[str] dry_run: NotRequired[bool] class KnowledgeSourceAddOutput(TypedDict, total=False): + crawl_proof: NotRequired[Optional["KnowledgeSourceCrawlProof"]] name: Required[str] kind: Required[str] namespace: Required[str] @@ -12028,6 +12045,15 @@ class KnowledgeSourceAddOutput(TypedDict, total=False): dry_run: NotRequired[bool] +class KnowledgeSourceCrawlProof(TypedDict, total=False): + "The read-only delegation proof, without person addresses or credentials." + + subject_hashes: Required[list[str]] + read_scopes: Required[list[str]] + write_denials: Required[list[str]] + members: Required[int] + + class KnowledgeSourceProbe(TypedDict, total=False): "What a probe that succeeded found; a probe that fails refuses the call." @@ -12087,6 +12113,7 @@ class KnowledgeSourceInspectOutput(TypedDict, total=False): kind: Required[str] credential_mode: NotRequired[str] access: NotRequired[str] + crawl_options: NotRequired[dict[str, Any]] owner_subject: NotRequired[str] items: NotRequired[list[dict[str, Any]]] include: NotRequired[list[str]] @@ -12151,6 +12178,7 @@ class KnowledgeSourceEntry(TypedDict, total=False): kind: Required[str] credential_mode: NotRequired[str] access: NotRequired[str] + crawl_options: NotRequired[dict[str, Any]] owner_subject: NotRequired[str] items: NotRequired[list[dict[str, Any]]] include: NotRequired[list[str]] @@ -12308,6 +12336,7 @@ class KnowledgeSourceRotateBody(TypedDict, total=False): class KnowledgeSourceRotateOutput(TypedDict, total=False): + crawl_proof: NotRequired[Optional["KnowledgeSourceCrawlProof"]] name: Required[str] probe: NotRequired["KnowledgeSourceProbe"] rotated_at: NotRequired[str] @@ -12346,6 +12375,7 @@ class KnowledgeSourceUpdateInput(TypedDict, total=False): add_links: NotRequired[list[str]] remove_items: NotRequired[list[dict[str, Any]]] remove_links: NotRequired[list[str]] + crawl_options: NotRequired[Optional["KnowledgeSourceCrawlOptions"]] include: NotRequired[Optional[list[str]]] @@ -12359,10 +12389,12 @@ class KnowledgeSourceUpdateBody(TypedDict, total=False): add_links: NotRequired[list[str]] remove_items: NotRequired[list[dict[str, Any]]] remove_links: NotRequired[list[str]] + crawl_options: NotRequired[Optional["KnowledgeSourceCrawlOptions"]] include: NotRequired[Optional[list[str]]] class KnowledgeSourceUpdateOutput(TypedDict, total=False): + crawl_proof: NotRequired[Optional["KnowledgeSourceCrawlProof"]] name: Required[str] items: NotRequired[list[dict[str, Any]]] include: NotRequired[list[str]] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 83f7e54ad53..db19a0a62a7 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -168,7 +168,7 @@ module Generated "knowledge.reads" => OpSpec.new("knowledge.reads", "knowledge", "reads", true, true, "viewer", "experimental", %w[org namespace days source_uris].freeze, %w[org namespace].freeze), "knowledge.restore" => OpSpec.new("knowledge.restore", "knowledge", "restore", true, false, "writer", "experimental", %w[org namespace source_uri if_revision].freeze, %w[org namespace source_uri].freeze), "knowledge.search" => OpSpec.new("knowledge.search", "knowledge", "search", true, true, "viewer", "stable", %w[org namespace query tags since_seconds top_k namespace_scope namespaces search_mode lexical_weight narrow_spans collapse_sections uri_prefix session_ids source_classes formats block_types rerank].freeze, %w[org namespace query].freeze), - "knowledge.source.add" => OpSpec.new("knowledge.source.add", "knowledge", "source_add", false, false, "writer", "experimental", %w[org namespace name kind items links config include credential_mode credential dry_run].freeze, %w[org namespace name kind].freeze), + "knowledge.source.add" => OpSpec.new("knowledge.source.add", "knowledge", "source_add", false, false, "writer", "experimental", %w[org namespace name kind items links config include credential_mode crawl_options credential dry_run].freeze, %w[org namespace name kind].freeze), "knowledge.source.check" => OpSpec.new("knowledge.source.check", "knowledge", "source_check", true, false, "writer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.source.inspect" => OpSpec.new("knowledge.source.inspect", "knowledge", "source_inspect", true, true, "viewer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.source.list" => OpSpec.new("knowledge.source.list", "knowledge", "source_list", true, true, "viewer", "experimental", %w[org namespace].freeze, %w[org namespace].freeze), @@ -179,7 +179,7 @@ module Generated "knowledge.source.remove" => OpSpec.new("knowledge.source.remove", "knowledge", "source_remove", false, false, "writer", "experimental", %w[org namespace name confirm delete_documents].freeze, %w[org namespace name confirm].freeze), "knowledge.source.rotate" => OpSpec.new("knowledge.source.rotate", "knowledge", "source_rotate", false, false, "admin", "experimental", %w[org namespace name credential].freeze, %w[org namespace name credential].freeze), "knowledge.source.sync_now" => OpSpec.new("knowledge.source.sync_now", "knowledge", "source_sync_now", true, false, "writer", "experimental", %w[org namespace name full].freeze, %w[org namespace name].freeze), - "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 include].freeze, %w[org namespace name].freeze), + "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.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), diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index ec19f20e824..7681a5654a9 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -26936,36 +26936,47 @@ impl KnowledgeRestoreInput { } } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceCrawlProof { + pub subject_hashes: Vec, + pub read_scopes: Vec, + pub write_denials: Vec, + pub members: Integer, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceProbe { - #[serde(default = "default_1205")] - pub documents: Integer, #[serde(default = "default_1206")] - pub more: bool, + pub documents: Integer, #[serde(default = "default_1207")] - pub sample: Vec, + pub more: bool, #[serde(default = "default_1208")] - pub checked: Integer, + pub sample: Vec, #[serde(default = "default_1209")] + pub checked: Integer, + #[serde(default = "default_1210")] pub sampled: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceAddOutput { + #[serde(default = "default_1202")] + pub crawl_proof: Option, pub name: String, pub kind: String, pub namespace: String, - #[serde(default = "default_1202")] - pub items: Vec>, #[serde(default = "default_1203")] - pub include: Vec, + pub items: Vec>, #[serde(default = "default_1204")] + pub include: Vec, + #[serde(default = "default_1205")] pub config: std::collections::HashMap, - #[serde(default = "default_1210")] - pub probe: KnowledgeSourceProbe, #[serde(default = "default_1211")] + pub probe: KnowledgeSourceProbe, + #[serde(default = "default_1212")] pub dry_run: bool, } @@ -26976,6 +26987,51 @@ pub enum KnowledgeSourceAddInputCredentialMode { Shared, #[serde(rename = "connected")] Connected, + #[serde(rename = "crawl")] + Crawl, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeSourceCrawlSubjectType { + #[serde(rename = "person")] + Person, + #[serde(rename = "group")] + Group, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceCrawlSubject { + #[serde(rename = "type")] + pub r#type: KnowledgeSourceCrawlSubjectType, + pub email: String, +} +impl KnowledgeSourceCrawlSubject { + pub fn new(r#type: KnowledgeSourceCrawlSubjectType, email: impl Into) -> Self { + Self { + r#type, + email: email.into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceCrawlOptions { + pub directory_subject: String, + pub subjects: Vec, +} +impl KnowledgeSourceCrawlOptions { + pub fn new( + directory_subject: impl Into, + subjects: Vec, + ) -> Self { + Self { + directory_subject: directory_subject.into(), + subjects, + } + } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -27025,6 +27081,12 @@ pub struct KnowledgeSourceAddInput { deserialize_with = "present_value" )] pub credential_mode: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] + pub crawl_options: Option>, #[serde( default, skip_serializing_if = "Option::is_none", @@ -27050,6 +27112,7 @@ impl KnowledgeSourceAddInput { config: None, include: None, credential_mode: None, + crawl_options: None, credential: None, dry_run: None, } @@ -27101,6 +27164,14 @@ impl KnowledgeSourceAddInput { self.credential_mode = Some(credential_mode); self } + pub fn crawl_options(mut self, crawl_options: KnowledgeSourceCrawlOptions) -> Self { + self.crawl_options = Some(Some(crawl_options)); + self + } + pub fn crawl_options_null(mut self) -> Self { + self.crawl_options = Some(None); + self + } pub fn credential(mut self, credential: impl Into) -> Self { self.credential = Some(credential.into()); self @@ -27122,21 +27193,21 @@ impl KnowledgeSourceAddInput { #[non_exhaustive] pub struct KnowledgeSourceCheckOutput { pub name: String, - #[serde(default = "default_1212")] - pub reachable: bool, #[serde(default = "default_1213")] - pub documents: Integer, + pub reachable: bool, #[serde(default = "default_1214")] - pub more: bool, + pub documents: Integer, #[serde(default = "default_1215")] - pub sample: Vec, + pub more: bool, #[serde(default = "default_1216")] - pub checked: Integer, + pub sample: Vec, #[serde(default = "default_1217")] - pub sampled: bool, + pub checked: Integer, #[serde(default = "default_1218")] - pub summary: String, + pub sampled: bool, #[serde(default = "default_1219")] + pub summary: String, + #[serde(default = "default_1220")] pub checked_at: String, } @@ -27185,37 +27256,37 @@ impl KnowledgeSourceCheckInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceSync { - #[serde(default = "default_1228")] + #[serde(default = "default_1230")] pub requested_at: String, - #[serde(default = "default_1229")] + #[serde(default = "default_1231")] pub last_synced_at: String, - #[serde(default = "default_1230")] + #[serde(default = "default_1232")] pub status: String, - #[serde(default = "default_1231")] + #[serde(default = "default_1233")] pub documents_seen: Integer, - #[serde(default = "default_1232")] + #[serde(default = "default_1234")] pub changed: Integer, - #[serde(default = "default_1233")] + #[serde(default = "default_1235")] pub removed: Integer, - #[serde(default = "default_1234")] + #[serde(default = "default_1236")] pub unconverted: Integer, - #[serde(default = "default_1235")] + #[serde(default = "default_1237")] pub unconverted_reasons: std::collections::HashMap, - #[serde(default = "default_1236")] + #[serde(default = "default_1238")] pub skipped: Integer, - #[serde(default = "default_1237")] + #[serde(default = "default_1239")] pub error: String, - #[serde(default = "default_1238")] + #[serde(default = "default_1240")] pub pending_extract: Integer, - #[serde(default = "default_1239")] + #[serde(default = "default_1241")] pub last_extracted_at: String, - #[serde(default = "default_1240")] + #[serde(default = "default_1242")] pub extracted: Integer, - #[serde(default = "default_1241")] + #[serde(default = "default_1243")] pub flagged_pinned: Integer, - #[serde(default = "default_1242")] + #[serde(default = "default_1244")] pub unextracted: Integer, - #[serde(default = "default_1243")] + #[serde(default = "default_1245")] pub extract_error: String, } @@ -27223,11 +27294,11 @@ pub struct KnowledgeSourceSync { #[non_exhaustive] pub struct KnowledgeSourceDocument { pub source_uri: String, - #[serde(default = "default_1245")] + #[serde(default = "default_1247")] pub title: String, - #[serde(default = "default_1246")] + #[serde(default = "default_1248")] pub source_revision: String, - #[serde(default = "default_1247")] + #[serde(default = "default_1249")] pub ingested_at: String, } @@ -27236,25 +27307,27 @@ pub struct KnowledgeSourceDocument { pub struct KnowledgeSourceInspectOutput { pub name: String, pub kind: String, - #[serde(default = "default_1220")] - pub credential_mode: String, #[serde(default = "default_1221")] - pub access: String, + pub credential_mode: String, #[serde(default = "default_1222")] - pub owner_subject: String, + pub access: String, #[serde(default = "default_1223")] - pub items: Vec>, + pub crawl_options: std::collections::HashMap, #[serde(default = "default_1224")] - pub include: Vec, + pub owner_subject: String, #[serde(default = "default_1225")] - pub config: std::collections::HashMap, + pub items: Vec>, #[serde(default = "default_1226")] - pub created_by: String, + pub include: Vec, #[serde(default = "default_1227")] + pub config: std::collections::HashMap, + #[serde(default = "default_1228")] + pub created_by: String, + #[serde(default = "default_1229")] pub created_at: String, - #[serde(default = "default_1244")] + #[serde(default = "default_1246")] pub sync: KnowledgeSourceSync, - #[serde(default = "default_1248")] + #[serde(default = "default_1250")] pub documents: Vec, } @@ -27307,36 +27380,38 @@ impl KnowledgeSourceInspectInput { pub struct KnowledgeSourceEntry { pub name: String, pub kind: String, - #[serde(default = "default_1249")] + #[serde(default = "default_1251")] pub credential_mode: String, - #[serde(default = "default_1250")] + #[serde(default = "default_1252")] pub access: String, - #[serde(default = "default_1251")] + #[serde(default = "default_1253")] + pub crawl_options: std::collections::HashMap, + #[serde(default = "default_1254")] pub owner_subject: String, - #[serde(default = "default_1252")] + #[serde(default = "default_1255")] pub items: Vec>, - #[serde(default = "default_1253")] + #[serde(default = "default_1256")] pub include: Vec, - #[serde(default = "default_1254")] + #[serde(default = "default_1257")] pub config: std::collections::HashMap, - #[serde(default = "default_1255")] + #[serde(default = "default_1258")] pub created_by: String, - #[serde(default = "default_1256")] + #[serde(default = "default_1259")] pub created_at: String, - #[serde(default = "default_1257")] + #[serde(default = "default_1260")] pub sync: KnowledgeSourceSync, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceListOutput { - #[serde(default = "default_1258")] + #[serde(default = "default_1261")] pub sources: Vec, - #[serde(default = "default_1259")] + #[serde(default = "default_1262")] pub enabled: bool, - #[serde(default = "default_1260")] + #[serde(default = "default_1263")] pub accepts_sources: bool, - #[serde(default = "default_1261")] + #[serde(default = "default_1264")] pub self_service: bool, } @@ -27389,18 +27464,18 @@ impl KnowledgeSourceListInput { #[non_exhaustive] pub struct KnowledgeSourceParsedLink { pub link: String, - #[serde(default = "default_1262")] + #[serde(default = "default_1265")] pub kind: String, - #[serde(default = "default_1263")] + #[serde(default = "default_1266")] pub item: std::collections::HashMap, - #[serde(default = "default_1264")] + #[serde(default = "default_1267")] pub unreadable: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceParseLinksOutput { - #[serde(default = "default_1265")] + #[serde(default = "default_1268")] pub links: Vec, } @@ -27451,25 +27526,25 @@ impl KnowledgeSourceParseLinksInput { #[derive(Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct PushStatusOutput { - #[serde(default = "default_1266")] + #[serde(default = "default_1269")] pub enabled: bool, - #[serde(default = "default_1267")] + #[serde(default = "default_1270")] pub status: String, - #[serde(default = "default_1268")] + #[serde(default = "default_1271")] pub provider: String, - #[serde(default = "default_1269")] + #[serde(default = "default_1272")] pub generation: String, - #[serde(default = "default_1270")] + #[serde(default = "default_1273")] pub callback_url: String, - #[serde(default = "default_1271")] + #[serde(default = "default_1274")] pub provider_id: String, - #[serde(default = "default_1272")] + #[serde(default = "default_1275")] pub challenge_fingerprint: String, - #[serde(default = "default_1273")] + #[serde(default = "default_1276")] pub verification_token: String, - #[serde(default = "default_1274")] + #[serde(default = "default_1277")] pub channels: Integer, - #[serde(default = "default_1275")] + #[serde(default = "default_1278")] pub expires_at: f64, } impl std::fmt::Debug for PushStatusOutput { @@ -27714,7 +27789,7 @@ impl PushStatusInput { #[non_exhaustive] pub struct KnowledgeSourceRemoveOutput { pub name: String, - #[serde(default = "default_1276")] + #[serde(default = "default_1279")] pub documents_pending: Integer, } @@ -27776,10 +27851,12 @@ impl KnowledgeSourceRemoveInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceRotateOutput { + #[serde(default = "default_1280")] + pub crawl_proof: Option, pub name: String, - #[serde(default = "default_1277")] + #[serde(default = "default_1281")] pub probe: KnowledgeSourceProbe, - #[serde(default = "default_1278")] + #[serde(default = "default_1282")] pub rotated_at: String, } @@ -27831,7 +27908,7 @@ impl KnowledgeSourceRotateInput { #[non_exhaustive] pub struct KnowledgeSourceSyncNowOutput { pub name: String, - #[serde(default = "default_1279")] + #[serde(default = "default_1283")] pub enabled: bool, } @@ -27893,18 +27970,20 @@ impl KnowledgeSourceSyncNowInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceUpdateOutput { + #[serde(default = "default_1284")] + pub crawl_proof: Option, pub name: String, - #[serde(default = "default_1280")] + #[serde(default = "default_1285")] pub items: Vec>, - #[serde(default = "default_1281")] + #[serde(default = "default_1286")] pub include: Vec, - #[serde(default = "default_1282")] + #[serde(default = "default_1287")] pub config: std::collections::HashMap, - #[serde(default = "default_1283")] + #[serde(default = "default_1288")] pub added: Vec>, - #[serde(default = "default_1284")] + #[serde(default = "default_1289")] pub removed: Vec>, - #[serde(default = "default_1285")] + #[serde(default = "default_1290")] pub probe: KnowledgeSourceProbe, } @@ -27953,6 +28032,12 @@ pub struct KnowledgeSourceUpdateInput { skip_serializing_if = "Option::is_none", deserialize_with = "present_nullable" )] + pub crawl_options: Option>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_nullable" + )] pub include: Option>>, } impl KnowledgeSourceUpdateInput { @@ -27965,6 +28050,7 @@ impl KnowledgeSourceUpdateInput { add_links: None, remove_items: None, remove_links: None, + crawl_options: None, include: None, } } @@ -27998,6 +28084,14 @@ impl KnowledgeSourceUpdateInput { self.remove_links = Some(remove_links.into_iter().map(Into::into).collect()); self } + pub fn crawl_options(mut self, crawl_options: KnowledgeSourceCrawlOptions) -> Self { + self.crawl_options = Some(Some(crawl_options)); + self + } + pub fn crawl_options_null(mut self) -> Self { + self.crawl_options = Some(None); + self + } pub fn include(mut self, include: impl IntoIterator>) -> Self { self.include = Some(Some(include.into_iter().map(Into::into).collect())); self @@ -28020,9 +28114,9 @@ impl KnowledgeSourceUpdateInput { pub struct CitedChunk { pub source_uri: String, pub chunk_idx: Integer, - #[serde(default = "default_1287")] + #[serde(default = "default_1292")] pub revision: Integer, - #[serde(default = "default_1288")] + #[serde(default = "default_1293")] pub locator: Option>, } @@ -28031,12 +28125,12 @@ pub struct CitedChunk { pub struct SynthesizeCalculation { pub columns: Vec, pub rows: Vec>, - #[serde(default = "default_1295")] + #[serde(default = "default_1300")] pub row_ids: Vec>, - #[serde(default = "default_1296")] + #[serde(default = "default_1301")] pub truncated: bool, pub complete: bool, - #[serde(default = "default_1297")] + #[serde(default = "default_1302")] pub incomplete: Vec, pub receipt: QueryReceipt, pub citation: String, @@ -28050,23 +28144,23 @@ pub struct KnowledgeSynthesizeOutput { pub chunks_read: Integer, pub documents: Integer, pub reduce_rounds: Integer, - #[serde(default = "default_1286")] + #[serde(default = "default_1291")] pub citations: Vec, - #[serde(default = "default_1289")] + #[serde(default = "default_1294")] pub cited_chunks: Vec, - #[serde(default = "default_1290")] + #[serde(default = "default_1295")] pub unsupported_citations: Vec, - #[serde(default = "default_1291")] + #[serde(default = "default_1296")] pub truncated: bool, - #[serde(default = "default_1292")] + #[serde(default = "default_1297")] pub abstain: bool, - #[serde(default = "default_1293")] + #[serde(default = "default_1298")] pub abstain_reason: String, - #[serde(default = "default_1294")] + #[serde(default = "default_1299")] pub clarification: String, - #[serde(default = "default_1298")] + #[serde(default = "default_1303")] pub calculations: Vec, - #[serde(default = "default_1299")] + #[serde(default = "default_1304")] pub model: String, } @@ -28182,13 +28276,13 @@ impl KnowledgeSynthesizeInput { #[non_exhaustive] pub struct KnowledgeUpdateMetadataOutput { pub updated: bool, - #[serde(default = "default_1300")] + #[serde(default = "default_1305")] pub title: String, - #[serde(default = "default_1301")] + #[serde(default = "default_1306")] pub description: String, - #[serde(default = "default_1302")] + #[serde(default = "default_1307")] pub tags: Vec, - #[serde(default = "default_1303")] + #[serde(default = "default_1308")] pub chunks_reindexed: Integer, } @@ -28300,13 +28394,13 @@ pub struct KnowledgeUpsertOutput { pub chunks_superseded: Integer, pub embedding_model: String, pub embedding_dim: Integer, - #[serde(default = "default_1304")] + #[serde(default = "default_1309")] pub duplicate_of_uri: String, - #[serde(default = "default_1305")] + #[serde(default = "default_1310")] pub duplicate_chunk_count: Integer, - #[serde(default = "default_1306")] + #[serde(default = "default_1311")] pub namespace: String, - #[serde(default = "default_1307")] + #[serde(default = "default_1312")] pub source_uri: String, } @@ -28491,26 +28585,26 @@ pub struct LearningEntry { pub memory_type: String, pub proposed_value: Value, pub supporter_count: Integer, - #[serde(default = "default_1308")] + #[serde(default = "default_1313")] pub supporter_sessions: Integer, - #[serde(default = "default_1309")] + #[serde(default = "default_1314")] pub supporter_writers: Integer, pub confidence_avg: f64, pub supporters: Vec, pub rationale: String, - #[serde(default = "default_1310")] + #[serde(default = "default_1315")] pub source_kind: String, - #[serde(default = "default_1311")] + #[serde(default = "default_1316")] pub source_resource_id: String, - #[serde(default = "default_1312")] + #[serde(default = "default_1317")] pub agent: String, pub status: LearningEntryStatus, pub proposed_at: String, - #[serde(default = "default_1313")] + #[serde(default = "default_1318")] pub decided_at: Option, - #[serde(default = "default_1314")] + #[serde(default = "default_1319")] pub decided_by: String, - #[serde(default = "default_1315")] + #[serde(default = "default_1320")] pub decision_reason: String, } @@ -28713,11 +28807,11 @@ pub enum LearningsReviewOutputNewStatus { pub struct LearningsReviewOutput { pub candidate_id: String, pub new_status: LearningsReviewOutputNewStatus, - #[serde(default = "default_1316")] + #[serde(default = "default_1321")] pub promoted_to_shared: bool, - #[serde(default = "default_1317")] + #[serde(default = "default_1322")] pub promoted_to_knowledge: bool, - #[serde(default = "default_1318")] + #[serde(default = "default_1323")] pub knowledge_source_uri: String, pub decided_at: String, } @@ -28921,7 +29015,7 @@ impl MemoryAgentsListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct AggregateRow { - #[serde(default = "default_1319")] + #[serde(default = "default_1324")] pub group: std::collections::HashMap, pub metric: f64, } @@ -28929,9 +29023,9 @@ pub struct AggregateRow { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAggregateOutput { - #[serde(default = "default_1320")] + #[serde(default = "default_1325")] pub rows: Vec, - #[serde(default = "default_1321")] + #[serde(default = "default_1326")] pub sql_executed: String, } @@ -29099,15 +29193,15 @@ impl MemoryAggregateInput { pub struct BulkSetResult { pub memory_key: String, pub version: Integer, - #[serde(default = "default_1322")] + #[serde(default = "default_1327")] pub memory_id: String, - #[serde(default = "default_1323")] + #[serde(default = "default_1328")] pub conflict_verdict: String, - #[serde(default = "default_1324")] + #[serde(default = "default_1329")] pub peers: Vec, - #[serde(default = "default_1325")] + #[serde(default = "default_1330")] pub next: String, - #[serde(default = "default_1326")] + #[serde(default = "default_1331")] pub pinned_blocker_id: String, } @@ -29115,29 +29209,29 @@ pub struct BulkSetResult { #[non_exhaustive] pub struct MemoryBulkSetOutput { pub written: Vec, - #[serde(default = "default_1327")] + #[serde(default = "default_1332")] pub skipped_pinned: Vec, - #[serde(default = "default_1328")] + #[serde(default = "default_1333")] pub skipped_locked: Vec, - #[serde(default = "default_1329")] + #[serde(default = "default_1334")] pub skipped_blacklisted: Vec, - #[serde(default = "default_1330")] + #[serde(default = "default_1335")] pub merged: Vec, - #[serde(default = "default_1331")] + #[serde(default = "default_1336")] pub value_updates_linked: Integer, - #[serde(default = "default_1332")] + #[serde(default = "default_1337")] pub rejected_pinned: Vec, - #[serde(default = "default_1333")] + #[serde(default = "default_1338")] pub duplicates: Vec, - #[serde(default = "default_1334")] + #[serde(default = "default_1339")] pub conflicted: Vec, - #[serde(default = "default_1335")] + #[serde(default = "default_1340")] pub unchecked: Integer, - #[serde(default = "default_1336")] + #[serde(default = "default_1341")] pub retyped: Vec, - #[serde(default = "default_1337")] + #[serde(default = "default_1342")] pub identity_duplicates: std::collections::HashMap, - #[serde(default = "default_1338")] + #[serde(default = "default_1343")] pub stage_ms: std::collections::HashMap, } @@ -29287,18 +29381,18 @@ pub enum ApplyRowStatus { #[non_exhaustive] pub struct ApplyRow { pub memory_key: String, - #[serde(default = "default_1346")] + #[serde(default = "default_1351")] pub memory_id: String, - #[serde(default = "default_1347")] + #[serde(default = "default_1352")] pub agent: String, - #[serde(default = "default_1348")] + #[serde(default = "default_1353")] pub user_id: String, - #[serde(default = "default_1349")] + #[serde(default = "default_1354")] pub session_id: String, pub status: ApplyRowStatus, - #[serde(default = "default_1350")] + #[serde(default = "default_1355")] pub version: Option, - #[serde(default = "default_1351")] + #[serde(default = "default_1356")] pub detail: String, } @@ -29308,21 +29402,21 @@ pub struct MemoryApplyOutput { pub action: String, pub dry_run: bool, pub target: String, - #[serde(default = "default_1339")] + #[serde(default = "default_1344")] pub matched: Integer, - #[serde(default = "default_1340")] + #[serde(default = "default_1345")] pub applied: Integer, - #[serde(default = "default_1341")] + #[serde(default = "default_1346")] pub would_apply: Integer, - #[serde(default = "default_1342")] + #[serde(default = "default_1347")] pub refused: Integer, - #[serde(default = "default_1343")] + #[serde(default = "default_1348")] pub noop: Integer, - #[serde(default = "default_1344")] + #[serde(default = "default_1349")] pub failed: Integer, - #[serde(default = "default_1345")] + #[serde(default = "default_1350")] pub truncated: bool, - #[serde(default = "default_1352")] + #[serde(default = "default_1357")] pub rows: Vec, } @@ -30056,137 +30150,137 @@ pub enum MemoryAskOutputDeepFirst { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAskOutput { - #[serde(default = "default_1353")] + #[serde(default = "default_1358")] pub answer: String, - #[serde(default = "default_1354")] + #[serde(default = "default_1359")] pub source: MemoryAskOutputSource, - #[serde(default = "default_1355")] + #[serde(default = "default_1360")] pub abstain: bool, - #[serde(default = "default_1356")] + #[serde(default = "default_1361")] pub abstain_reason: String, - #[serde(default = "default_1357")] + #[serde(default = "default_1362")] pub memory_keys: Vec, - #[serde(default = "default_1358")] + #[serde(default = "default_1363")] pub results: Vec, - #[serde(default = "default_1359")] + #[serde(default = "default_1364")] pub cited_sessions: Vec, - #[serde(default = "default_1360")] + #[serde(default = "default_1365")] pub next: String, - #[serde(default = "default_1361")] + #[serde(default = "default_1366")] pub synth_model: String, - #[serde(default = "default_1362")] + #[serde(default = "default_1367")] pub route_tier: MemoryAskOutputRouteTier, - #[serde(default = "default_1363")] + #[serde(default = "default_1368")] pub route_reason: String, - #[serde(default = "default_1364")] + #[serde(default = "default_1369")] pub llm_cache_hits: Integer, - #[serde(default = "default_1365")] + #[serde(default = "default_1370")] pub llm_cache_misses: Integer, - #[serde(default = "default_1366")] + #[serde(default = "default_1371")] pub llm_cache: bool, - #[serde(default = "default_1367")] + #[serde(default = "default_1372")] pub llm_cache_saved_usd: f64, - #[serde(default = "default_1368")] + #[serde(default = "default_1373")] pub temporal_consistency: Option, - #[serde(default = "default_1369")] + #[serde(default = "default_1374")] pub citation_concentration: Option, - #[serde(default = "default_1370")] + #[serde(default = "default_1375")] pub escalated: bool, - #[serde(default = "default_1371")] + #[serde(default = "default_1376")] pub gate_mode: String, - #[serde(default = "default_1372")] + #[serde(default = "default_1377")] pub gate_kept: Integer, - #[serde(default = "default_1373")] + #[serde(default = "default_1378")] pub gate_dropped: Integer, - #[serde(default = "default_1374")] + #[serde(default = "default_1379")] pub pending_extraction: Integer, - #[serde(default = "default_1375")] + #[serde(default = "default_1380")] pub pending_evidence: Integer, - #[serde(default = "default_1376")] + #[serde(default = "default_1381")] pub retrieval_query: String, - #[serde(default = "default_1377")] + #[serde(default = "default_1382")] pub facets: Vec, - #[serde(default = "default_1378")] + #[serde(default = "default_1383")] pub facet_memories_added: Integer, - #[serde(default = "default_1379")] + #[serde(default = "default_1384")] pub consistency: MemoryAskOutputConsistency, - #[serde(default = "default_1380")] + #[serde(default = "default_1385")] pub consistency_score: f64, - #[serde(default = "default_1381")] + #[serde(default = "default_1386")] pub consistency_note: String, - #[serde(default = "default_1382")] + #[serde(default = "default_1387")] pub identifier_chase_hops: Integer, - #[serde(default = "default_1383")] + #[serde(default = "default_1388")] pub identifier_chase_added: Integer, - #[serde(default = "default_1384")] + #[serde(default = "default_1389")] pub premise_conflict: String, - #[serde(default = "default_1385")] + #[serde(default = "default_1390")] pub premise_note: String, - #[serde(default = "default_1386")] + #[serde(default = "default_1391")] pub premise_verdict: String, - #[serde(default = "default_1387")] + #[serde(default = "default_1392")] pub attribution_note: String, - #[serde(default = "default_1388")] + #[serde(default = "default_1393")] pub depth: MemoryAskOutputDepth, - #[serde(default = "default_1389")] + #[serde(default = "default_1394")] pub deep_fired: bool, - #[serde(default = "default_1390")] + #[serde(default = "default_1395")] pub decomposed: Vec, - #[serde(default = "default_1391")] + #[serde(default = "default_1396")] pub decomposed_parts: Integer, - #[serde(default = "default_1392")] + #[serde(default = "default_1397")] pub superseded_dropped: Integer, - #[serde(default = "default_1393")] + #[serde(default = "default_1398")] pub stale_sentences_masked: Integer, - #[serde(default = "default_1394")] + #[serde(default = "default_1399")] pub entity_followed: Vec, - #[serde(default = "default_1395")] + #[serde(default = "default_1400")] pub when_evidence_turns: Integer, - #[serde(default = "default_1396")] + #[serde(default = "default_1401")] pub decompose_failed: Integer, - #[serde(default = "default_1397")] + #[serde(default = "default_1402")] pub pool_k: Integer, - #[serde(default = "default_1398")] + #[serde(default = "default_1403")] pub grounding: MemoryAskOutputGrounding, - #[serde(default = "default_1399")] + #[serde(default = "default_1404")] pub deep_reason: String, - #[serde(default = "default_1400")] + #[serde(default = "default_1405")] pub deep_keys: Vec, - #[serde(default = "default_1401")] + #[serde(default = "default_1406")] pub deep_chars: Integer, - #[serde(default = "default_1402")] + #[serde(default = "default_1407")] pub code_hits: Integer, - #[serde(default = "default_1403")] + #[serde(default = "default_1408")] pub pool_facts: Integer, - #[serde(default = "default_1404")] + #[serde(default = "default_1409")] pub pool_chunks: Integer, - #[serde(default = "default_1405")] + #[serde(default = "default_1410")] pub prompt_blocks: std::collections::HashMap, - #[serde(default = "default_1406")] + #[serde(default = "default_1411")] pub deep_selector: MemoryAskOutputDeepSelector, - #[serde(default = "default_1407")] + #[serde(default = "default_1412")] pub deep_first: MemoryAskOutputDeepFirst, - #[serde(default = "default_1408")] + #[serde(default = "default_1413")] pub synth_calls: Integer, - #[serde(default = "default_1409")] + #[serde(default = "default_1414")] pub synth_input_tokens: Integer, - #[serde(default = "default_1410")] + #[serde(default = "default_1415")] pub synth_cached_input_tokens: Integer, - #[serde(default = "default_1411")] + #[serde(default = "default_1416")] pub synth_cache_write_tokens: Integer, - #[serde(default = "default_1412")] + #[serde(default = "default_1417")] pub synth_cost_usd: f64, - #[serde(default = "default_1413")] + #[serde(default = "default_1418")] pub context_tokens_est: Integer, - #[serde(default = "default_1414")] + #[serde(default = "default_1419")] pub context_trimmed: Integer, - #[serde(default = "default_1415")] + #[serde(default = "default_1420")] pub summary_hits: Integer, - #[serde(default = "default_1416")] + #[serde(default = "default_1421")] pub knowledge_hits: Integer, - #[serde(default = "default_1417")] + #[serde(default = "default_1422")] pub timeline_rows: Integer, - #[serde(default = "default_1418")] + #[serde(default = "default_1423")] pub count_recomputed: bool, } @@ -31141,36 +31235,36 @@ pub struct MemoryAutoRetirement { pub reason: String, pub memory_id: String, pub memory_key: String, - #[serde(default = "default_1419")] + #[serde(default = "default_1424")] pub agent: String, - #[serde(default = "default_1420")] + #[serde(default = "default_1425")] pub user_id: String, - #[serde(default = "default_1421")] + #[serde(default = "default_1426")] pub session_id: String, - #[serde(default = "default_1422")] + #[serde(default = "default_1427")] pub superseded_by: String, - #[serde(default = "default_1423")] + #[serde(default = "default_1428")] pub superseded_by_key: String, - #[serde(default = "default_1424")] + #[serde(default = "default_1429")] pub label: String, - #[serde(default = "default_1425")] + #[serde(default = "default_1430")] pub unconfirmed: bool, - #[serde(default = "default_1426")] + #[serde(default = "default_1431")] pub judge_verdict: String, - #[serde(default = "default_1427")] + #[serde(default = "default_1432")] pub judge_confidence: Option, - #[serde(default = "default_1428")] + #[serde(default = "default_1433")] pub judge_model: String, - #[serde(default = "default_1429")] + #[serde(default = "default_1434")] pub judge_prompt_version: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAutoRetirementsOutput { - #[serde(default = "default_1430")] + #[serde(default = "default_1435")] pub rows: Vec, - #[serde(default = "default_1431")] + #[serde(default = "default_1436")] pub next_cursor: Option, } @@ -31264,9 +31358,9 @@ impl MemoryAutoRetirementsInput { #[non_exhaustive] pub struct BacklinkVersion { pub version: Integer, - #[serde(default = "default_1433")] + #[serde(default = "default_1438")] pub status: String, - #[serde(default = "default_1434")] + #[serde(default = "default_1439")] pub created_at: String, } @@ -31274,7 +31368,7 @@ pub struct BacklinkVersion { #[non_exhaustive] pub struct BacklinkDigest { pub session_id: String, - #[serde(default = "default_1436")] + #[serde(default = "default_1441")] pub date: String, } @@ -31282,9 +31376,9 @@ pub struct BacklinkDigest { #[non_exhaustive] pub struct BacklinkEdge { pub memory_key: String, - #[serde(default = "default_1438")] + #[serde(default = "default_1443")] pub relation: String, - #[serde(default = "default_1439")] + #[serde(default = "default_1444")] pub created_at: String, } @@ -31292,7 +31386,7 @@ pub struct BacklinkEdge { #[non_exhaustive] pub struct BacklinkRelated { pub memory_key: String, - #[serde(default = "default_1443")] + #[serde(default = "default_1448")] pub shared_entities: Vec, } @@ -31300,19 +31394,19 @@ pub struct BacklinkRelated { #[non_exhaustive] pub struct MemoryBacklinksOutput { pub memory_key: String, - #[serde(default = "default_1432")] + #[serde(default = "default_1437")] pub found: bool, - #[serde(default = "default_1435")] + #[serde(default = "default_1440")] pub versions: Vec, - #[serde(default = "default_1437")] + #[serde(default = "default_1442")] pub digests: Vec, - #[serde(default = "default_1440")] + #[serde(default = "default_1445")] pub links_in: Vec, - #[serde(default = "default_1441")] + #[serde(default = "default_1446")] pub links_out: Vec, - #[serde(default = "default_1442")] + #[serde(default = "default_1447")] pub evidence_count: Integer, - #[serde(default = "default_1444")] + #[serde(default = "default_1449")] pub related: Vec, } @@ -31417,36 +31511,36 @@ impl MemoryBacklinksInput { #[non_exhaustive] pub struct BriefEvidence { pub memory_key: String, - #[serde(default = "default_1449")] + #[serde(default = "default_1454")] pub source: String, - #[serde(default = "default_1450")] + #[serde(default = "default_1455")] pub source_class: String, - #[serde(default = "default_1451")] + #[serde(default = "default_1456")] pub verified: bool, - #[serde(default = "default_1452")] + #[serde(default = "default_1457")] pub when: String, - #[serde(default = "default_1453")] + #[serde(default = "default_1458")] pub session_id: String, - #[serde(default = "default_1454")] + #[serde(default = "default_1459")] pub excerpt: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryBriefOutput { - #[serde(default = "default_1445")] + #[serde(default = "default_1450")] pub query: String, - #[serde(default = "default_1446")] + #[serde(default = "default_1451")] pub answer: String, - #[serde(default = "default_1447")] + #[serde(default = "default_1452")] pub abstained: bool, - #[serde(default = "default_1448")] + #[serde(default = "default_1453")] pub grounding: String, - #[serde(default = "default_1455")] + #[serde(default = "default_1460")] pub evidence: Vec, - #[serde(default = "default_1456")] + #[serde(default = "default_1461")] pub unknowns: Vec, - #[serde(default = "default_1457")] + #[serde(default = "default_1462")] pub next_reads: Vec, } @@ -31860,9 +31954,9 @@ pub struct MemoryBulkGetOutputMemoryGetOutput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryBulkGetOutput { - #[serde(default = "default_1458")] + #[serde(default = "default_1463")] pub results: std::collections::HashMap, - #[serde(default = "default_1459")] + #[serde(default = "default_1464")] pub missing: Vec, } @@ -32375,7 +32469,7 @@ pub struct MemoryClearOutput { pub cleared_at: String, pub rows_affected: std::collections::HashMap, pub total: Integer, - #[serde(default = "default_1460")] + #[serde(default = "default_1465")] pub locked_skipped: Integer, } @@ -32463,21 +32557,21 @@ pub struct MemoryConsolidateResult { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryConsolidateOutput { - #[serde(default = "default_1461")] + #[serde(default = "default_1466")] pub consolidated: Vec, - #[serde(default = "default_1462")] + #[serde(default = "default_1467")] pub examined: Integer, - #[serde(default = "default_1463")] + #[serde(default = "default_1468")] pub clusters_found: Integer, - #[serde(default = "default_1464")] + #[serde(default = "default_1469")] pub clusters_failed: Integer, - #[serde(default = "default_1465")] + #[serde(default = "default_1470")] pub clusters_refused_lossy: Integer, - #[serde(default = "default_1466")] + #[serde(default = "default_1471")] pub skipped_in_flight: Integer, - #[serde(default = "default_1467")] + #[serde(default = "default_1472")] pub tokens_in: Integer, - #[serde(default = "default_1468")] + #[serde(default = "default_1473")] pub tokens_out: Integer, } @@ -32618,7 +32712,7 @@ impl MemoryConsolidateInput { #[non_exhaustive] pub struct MemoryCopyToOutput { pub copied: bool, - #[serde(default = "default_1469")] + #[serde(default = "default_1474")] pub target_memory_id: String, pub target_namespace: String, pub target_key: String, @@ -32729,11 +32823,11 @@ impl MemoryCopyToInput { #[non_exhaustive] pub struct MemoryCrossPromoteOutput { pub promoted: bool, - #[serde(default = "default_1470")] + #[serde(default = "default_1475")] pub target_memory_id: String, pub target_namespace: String, pub target_key: String, - #[serde(default = "default_1471")] + #[serde(default = "default_1476")] pub cross_promoted_from_memory_id: String, } @@ -32816,23 +32910,23 @@ pub struct DedupCollapsePair { #[non_exhaustive] pub struct MemoryDedupCollapseOutput { pub namespace: String, - #[serde(default = "default_1472")] + #[serde(default = "default_1477")] pub prefix: String, - #[serde(default = "default_1473")] + #[serde(default = "default_1478")] pub dry_run: bool, - #[serde(default = "default_1474")] + #[serde(default = "default_1479")] pub pairs: Integer, - #[serde(default = "default_1475")] + #[serde(default = "default_1480")] pub canonical_live: Integer, - #[serde(default = "default_1476")] + #[serde(default = "default_1481")] pub orphans: Integer, - #[serde(default = "default_1477")] + #[serde(default = "default_1482")] pub mirror_stale: Integer, - #[serde(default = "default_1478")] + #[serde(default = "default_1483")] pub restamped: Integer, - #[serde(default = "default_1479")] + #[serde(default = "default_1484")] pub truncated: bool, - #[serde(default = "default_1480")] + #[serde(default = "default_1485")] pub sample: Vec, } @@ -32931,7 +33025,7 @@ pub struct DedupDuplicate { pub memory_id: String, pub memory_key: String, pub agent: String, - #[serde(default = "default_1483")] + #[serde(default = "default_1488")] pub created_at: Option, } @@ -32939,12 +33033,12 @@ pub struct DedupDuplicate { #[non_exhaustive] pub struct DedupCluster { pub canonical_id: String, - #[serde(default = "default_1481")] + #[serde(default = "default_1486")] pub canonical_key: String, - #[serde(default = "default_1482")] + #[serde(default = "default_1487")] pub canonical_agent: String, pub dup_count: Integer, - #[serde(default = "default_1484")] + #[serde(default = "default_1489")] pub duplicates: Vec, } @@ -33016,11 +33110,11 @@ pub struct MemoryDedupResolveOutput { pub canonical_key: String, pub duplicate_key: String, pub decision: String, - #[serde(default = "default_1485")] + #[serde(default = "default_1490")] pub canonical_tombstoned: bool, - #[serde(default = "default_1486")] + #[serde(default = "default_1491")] pub duplicate_tombstoned: bool, - #[serde(default = "default_1487")] + #[serde(default = "default_1492")] pub ignored_args: Vec, } @@ -33158,17 +33252,17 @@ pub struct LostName { pub struct DefinitionEntry { pub memory_key: String, pub promoted_at: String, - #[serde(default = "default_1488")] + #[serde(default = "default_1493")] pub capped: bool, - #[serde(default = "default_1489")] + #[serde(default = "default_1494")] pub term: Option, - #[serde(default = "default_1490")] + #[serde(default = "default_1495")] pub aliases: Vec, - #[serde(default = "default_1491")] + #[serde(default = "default_1496")] pub verdict: Option, - #[serde(default = "default_1492")] + #[serde(default = "default_1497")] pub lapse_reason: Option, - #[serde(default = "default_1493")] + #[serde(default = "default_1498")] pub lost: Vec, } @@ -33229,15 +33323,15 @@ impl MemoryDefinitionsListInput { #[non_exhaustive] pub struct MemoryDeleteVersionOutput { pub tombstoned: bool, - #[serde(default = "default_1494")] + #[serde(default = "default_1499")] pub version: Integer, - #[serde(default = "default_1495")] + #[serde(default = "default_1500")] pub found: bool, - #[serde(default = "default_1496")] + #[serde(default = "default_1501")] pub reason: String, - #[serde(default = "default_1497")] + #[serde(default = "default_1502")] pub dependents_tombstoned: Integer, - #[serde(default = "default_1498")] + #[serde(default = "default_1503")] pub dependents_downgraded: Integer, } @@ -33364,21 +33458,21 @@ pub struct DemonstrationRow { pub struct MemoryDemonstrateOutput { pub query: String, pub demonstrations: Vec, - #[serde(default = "default_1499")] + #[serde(default = "default_1504")] pub votes: std::collections::HashMap, - #[serde(default = "default_1500")] + #[serde(default = "default_1505")] pub predicted_label: String, - #[serde(default = "default_1501")] + #[serde(default = "default_1506")] pub margin: f64, - #[serde(default = "default_1502")] + #[serde(default = "default_1507")] pub abstain: bool, - #[serde(default = "default_1503")] + #[serde(default = "default_1508")] pub abstain_reason: String, - #[serde(default = "default_1504")] + #[serde(default = "default_1509")] pub few_shot_block: String, - #[serde(default = "default_1505")] + #[serde(default = "default_1510")] pub examined: Integer, - #[serde(default = "default_1506")] + #[serde(default = "default_1511")] pub labelled: Integer, } @@ -33518,7 +33612,7 @@ impl MemoryDemonstrateInput { pub struct MemoryDemoteOutput { pub demoted: bool, pub was_reversible: bool, - #[serde(default = "default_1507")] + #[serde(default = "default_1512")] pub tombstoned_at: Option, } @@ -33580,15 +33674,15 @@ impl MemoryDemoteInput { pub struct DigestRow { pub session_id: String, pub summary_text: String, - #[serde(default = "default_1508")] + #[serde(default = "default_1513")] pub key_facts: Vec, - #[serde(default = "default_1509")] + #[serde(default = "default_1514")] pub derived_from: Vec, - #[serde(default = "default_1510")] + #[serde(default = "default_1515")] pub valid_at: Option, - #[serde(default = "default_1511")] + #[serde(default = "default_1516")] pub created_at: Option, - #[serde(default = "default_1512")] + #[serde(default = "default_1517")] pub version: Integer, } @@ -33596,7 +33690,7 @@ pub struct DigestRow { #[non_exhaustive] pub struct MemoryDigestsOutput { pub rows: Vec, - #[serde(default = "default_1513")] + #[serde(default = "default_1518")] pub truncated: bool, } @@ -33721,17 +33815,17 @@ pub struct MemoryEvidenceItem { pub evidence_id: String, pub support_type: String, pub scope: MemoryEvidenceItemScope, - #[serde(default = "default_1517")] + #[serde(default = "default_1522")] pub role: String, - #[serde(default = "default_1518")] + #[serde(default = "default_1523")] pub observed_at: Option, - #[serde(default = "default_1519")] + #[serde(default = "default_1524")] pub content: String, - #[serde(default = "default_1520")] + #[serde(default = "default_1525")] pub char_start: Integer, - #[serde(default = "default_1521")] + #[serde(default = "default_1526")] pub char_end: Integer, - #[serde(default = "default_1522")] + #[serde(default = "default_1527")] pub span: String, } @@ -33739,23 +33833,23 @@ pub struct MemoryEvidenceItem { #[non_exhaustive] pub struct MemoryEvidenceOutput { pub found: bool, - #[serde(default = "default_1514")] + #[serde(default = "default_1519")] pub memory_key: String, - #[serde(default = "default_1515")] + #[serde(default = "default_1520")] pub memory_id: String, - #[serde(default = "default_1516")] + #[serde(default = "default_1521")] pub value: String, - #[serde(default = "default_1523")] + #[serde(default = "default_1528")] pub items: Vec, - #[serde(default = "default_1524")] + #[serde(default = "default_1529")] pub truncated: bool, - #[serde(default = "default_1525")] + #[serde(default = "default_1530")] pub cited: Integer, - #[serde(default = "default_1526")] + #[serde(default = "default_1531")] pub lexical: Integer, - #[serde(default = "default_1527")] + #[serde(default = "default_1532")] pub window: Integer, - #[serde(default = "default_1528")] + #[serde(default = "default_1533")] pub derived: Integer, } @@ -33860,26 +33954,26 @@ impl MemoryEvidenceInput { #[non_exhaustive] pub struct EvidenceChunk { pub session_id: String, - #[serde(default = "default_1529")] + #[serde(default = "default_1534")] pub chunk_index: Integer, pub content: String, - #[serde(default = "default_1530")] + #[serde(default = "default_1535")] pub content_sha256: String, - #[serde(default = "default_1531")] + #[serde(default = "default_1536")] pub agent: String, - #[serde(default = "default_1532")] + #[serde(default = "default_1537")] pub user_id: String, - #[serde(default = "default_1533")] + #[serde(default = "default_1538")] pub parent_memory_key: String, - #[serde(default = "default_1534")] + #[serde(default = "default_1539")] pub memory_keys: Vec, - #[serde(default = "default_1535")] + #[serde(default = "default_1540")] pub line_start: Integer, - #[serde(default = "default_1536")] + #[serde(default = "default_1541")] pub line_end: Integer, - #[serde(default = "default_1537")] + #[serde(default = "default_1542")] pub created_at: String, - #[serde(default = "default_1538")] + #[serde(default = "default_1543")] pub source_url: String, } @@ -33888,17 +33982,17 @@ pub struct EvidenceChunk { pub struct EvidenceDigest { pub session_id: String, pub summary_text: String, - #[serde(default = "default_1540")] + #[serde(default = "default_1545")] pub agent: String, - #[serde(default = "default_1541")] + #[serde(default = "default_1546")] pub user_id: String, - #[serde(default = "default_1542")] + #[serde(default = "default_1547")] pub key_facts: Vec, - #[serde(default = "default_1543")] + #[serde(default = "default_1548")] pub derived_from: Vec, - #[serde(default = "default_1544")] + #[serde(default = "default_1549")] pub valid_at: String, - #[serde(default = "default_1545")] + #[serde(default = "default_1550")] pub created_at: String, } @@ -33908,28 +34002,28 @@ pub struct EvidenceEdge { pub from_key: String, pub to_key: String, pub relation: String, - #[serde(default = "default_1547")] + #[serde(default = "default_1552")] pub confidence: f64, - #[serde(default = "default_1548")] + #[serde(default = "default_1553")] pub explanation: String, - #[serde(default = "default_1549")] + #[serde(default = "default_1554")] pub created_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExportEvidenceOutput { - #[serde(default = "default_1539")] + #[serde(default = "default_1544")] pub chunks: Vec, - #[serde(default = "default_1546")] + #[serde(default = "default_1551")] pub digests: Vec, - #[serde(default = "default_1550")] + #[serde(default = "default_1555")] pub edges: Vec, - #[serde(default = "default_1551")] + #[serde(default = "default_1556")] pub has_more: bool, - #[serde(default = "default_1552")] + #[serde(default = "default_1557")] pub next_cursor: String, - #[serde(default = "default_1553")] + #[serde(default = "default_1558")] pub held_high: Integer, } @@ -34122,15 +34216,15 @@ impl ExposureSummaryInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionRetryMineOutput { - #[serde(default = "default_1554")] + #[serde(default = "default_1559")] pub requeued: Vec, - #[serde(default = "default_1555")] + #[serde(default = "default_1560")] pub not_failed: Vec, - #[serde(default = "default_1556")] + #[serde(default = "default_1561")] pub model_calls_off: Vec, - #[serde(default = "default_1557")] + #[serde(default = "default_1562")] pub expired: Vec, - #[serde(default = "default_1558")] + #[serde(default = "default_1563")] pub unknown: Vec, } @@ -34191,20 +34285,20 @@ pub struct ExtractionQueueRow { pub content_chars: Integer, pub written: Integer, pub last_error: String, - #[serde(default = "default_1559")] + #[serde(default = "default_1564")] pub enqueued_at: Option, - #[serde(default = "default_1560")] + #[serde(default = "default_1565")] pub updated_at: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionStatusOutput { - #[serde(default = "default_1561")] + #[serde(default = "default_1566")] pub batches: Vec, - #[serde(default = "default_1562")] + #[serde(default = "default_1567")] pub pending: Integer, - #[serde(default = "default_1563")] + #[serde(default = "default_1568")] pub failed: Integer, } @@ -34352,13 +34446,13 @@ impl MemoryExtractionStatusInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionStatusMineOutput { - #[serde(default = "default_1564")] + #[serde(default = "default_1569")] pub batches: Vec, - #[serde(default = "default_1565")] + #[serde(default = "default_1570")] pub unknown: Vec, - #[serde(default = "default_1566")] + #[serde(default = "default_1571")] pub pending: Integer, - #[serde(default = "default_1567")] + #[serde(default = "default_1572")] pub failed: Integer, } @@ -34479,39 +34573,39 @@ pub struct MemoryForFileHit { pub memory_key: String, pub memory_type: String, pub value: String, - #[serde(default = "default_1568")] + #[serde(default = "default_1573")] pub value_truncated: bool, - #[serde(default = "default_1569")] + #[serde(default = "default_1574")] pub tags: Vec, - #[serde(default = "default_1570")] + #[serde(default = "default_1575")] pub confidence: f64, - #[serde(default = "default_1571")] + #[serde(default = "default_1576")] pub pinned: bool, - #[serde(default = "default_1572")] + #[serde(default = "default_1577")] pub status: String, - #[serde(default = "default_1573")] + #[serde(default = "default_1578")] pub agent: String, - #[serde(default = "default_1574")] + #[serde(default = "default_1579")] pub updated_at: Option, - #[serde(default = "default_1575")] + #[serde(default = "default_1580")] pub namespace: String, - #[serde(default = "default_1576")] + #[serde(default = "default_1581")] pub actor: String, - #[serde(default = "default_1577")] + #[serde(default = "default_1582")] pub supersedes_key: String, - #[serde(default = "default_1578")] + #[serde(default = "default_1583")] pub supersedes: String, - #[serde(default = "default_1579")] + #[serde(default = "default_1584")] pub supersedes_kind: MemoryForFileHitSupersedesKind, - #[serde(default = "default_1580")] + #[serde(default = "default_1585")] pub matched_files: Vec, - #[serde(default = "default_1581")] + #[serde(default = "default_1586")] pub source_resource_id: String, - #[serde(default = "default_1582")] + #[serde(default = "default_1587")] pub verification: MemoryForFileHitVerification, - #[serde(default = "default_1583")] + #[serde(default = "default_1588")] pub code_state: MemoryForFileHitCodeState, - #[serde(default = "default_1584")] + #[serde(default = "default_1589")] pub code_moved: Vec, } @@ -34521,11 +34615,11 @@ pub struct MemoryForFileOutput { pub path: String, pub total: Integer, pub hits: Vec, - #[serde(default = "default_1585")] + #[serde(default = "default_1590")] pub rendered: String, - #[serde(default = "default_1586")] + #[serde(default = "default_1591")] pub tokens_estimate: Integer, - #[serde(default = "default_1587")] + #[serde(default = "default_1592")] pub truncated: bool, } @@ -34633,61 +34727,61 @@ impl MemoryForFileInput { #[non_exhaustive] pub struct MemoryGetByIdOutput { pub found: bool, - #[serde(default = "default_1588")] + #[serde(default = "default_1593")] pub memory_id: String, - #[serde(default = "default_1589")] + #[serde(default = "default_1594")] pub namespace: String, - #[serde(default = "default_1590")] + #[serde(default = "default_1595")] pub agent: String, - #[serde(default = "default_1591")] + #[serde(default = "default_1596")] pub user_id: String, - #[serde(default = "default_1592")] + #[serde(default = "default_1597")] pub session_id: String, - #[serde(default = "default_1593")] + #[serde(default = "default_1598")] pub memory_key: String, - #[serde(default = "default_1594")] + #[serde(default = "default_1599")] pub memory_type: Option, - #[serde(default = "default_1595")] + #[serde(default = "default_1600")] pub value: Value, - #[serde(default = "default_1596")] + #[serde(default = "default_1601")] pub confidence: Option, - #[serde(default = "default_1597")] + #[serde(default = "default_1602")] pub version: Option, - #[serde(default = "default_1598")] + #[serde(default = "default_1603")] pub created_at: Option, - #[serde(default = "default_1599")] + #[serde(default = "default_1604")] pub expires_at: Option, - #[serde(default = "default_1600")] + #[serde(default = "default_1605")] pub valid_at: Option, - #[serde(default = "default_1601")] + #[serde(default = "default_1606")] pub valid_to: Option, - #[serde(default = "default_1602")] + #[serde(default = "default_1607")] pub pinned: bool, - #[serde(default = "default_1603")] + #[serde(default = "default_1608")] pub content_sha256: String, - #[serde(default = "default_1604")] + #[serde(default = "default_1609")] pub verified_by: String, - #[serde(default = "default_1605")] + #[serde(default = "default_1610")] pub verified_at: Option, - #[serde(default = "default_1606")] + #[serde(default = "default_1611")] pub verification: String, - #[serde(default = "default_1607")] + #[serde(default = "default_1612")] pub sensitivity: String, - #[serde(default = "default_1608")] + #[serde(default = "default_1613")] pub actor: String, - #[serde(default = "default_1609")] + #[serde(default = "default_1614")] pub source_class: String, - #[serde(default = "default_1610")] + #[serde(default = "default_1615")] pub lock_mode: String, - #[serde(default = "default_1611")] + #[serde(default = "default_1616")] pub lock_reason: String, - #[serde(default = "default_1612")] + #[serde(default = "default_1617")] pub lock_until: Option, - #[serde(default = "default_1613")] + #[serde(default = "default_1618")] pub locked_by: String, - #[serde(default = "default_1614")] + #[serde(default = "default_1619")] pub on_expire: String, - #[serde(default = "default_1615")] + #[serde(default = "default_1620")] pub expire_reason: String, } @@ -34763,41 +34857,41 @@ pub struct MemoryHealthTopRow { pub memory_type: String, pub recall_count: Integer, pub used_count: Integer, - #[serde(default = "default_1618")] + #[serde(default = "default_1623")] pub harm_count: Integer, - #[serde(default = "default_1619")] + #[serde(default = "default_1624")] pub last_recalled_at: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryHealthStaleness { - #[serde(default = "default_1621")] + #[serde(default = "default_1626")] pub by_age: std::collections::HashMap, - #[serde(default = "default_1622")] + #[serde(default = "default_1627")] pub with_validity_end: Integer, - #[serde(default = "default_1623")] + #[serde(default = "default_1628")] pub with_validity_end_share: f64, - #[serde(default = "default_1624")] + #[serde(default = "default_1629")] pub with_expiry: Integer, - #[serde(default = "default_1625")] + #[serde(default = "default_1630")] pub expiring_7d: Integer, - #[serde(default = "default_1626")] + #[serde(default = "default_1631")] pub pinned: Integer, - #[serde(default = "default_1627")] + #[serde(default = "default_1632")] pub days_since_reinforced_p50: Integer, - #[serde(default = "default_1628")] + #[serde(default = "default_1633")] pub days_since_reinforced_p90: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryHealthFootprint { - #[serde(default = "default_1630")] + #[serde(default = "default_1635")] pub value_chars: Integer, - #[serde(default = "default_1631")] + #[serde(default = "default_1636")] pub value_tokens_est: Integer, - #[serde(default = "default_1632")] + #[serde(default = "default_1637")] pub tokens_per_row_est: f64, } @@ -34807,19 +34901,19 @@ pub struct MemoryHealthOutput { pub live: Integer, pub recalled_ever: Integer, pub used_ever: Integer, - #[serde(default = "default_1616")] + #[serde(default = "default_1621")] pub harmed_ever: Integer, pub silent: Integer, pub silent_older: Integer, pub silent_share: f64, pub silent_after_days: Integer, - #[serde(default = "default_1617")] + #[serde(default = "default_1622")] pub by_type: Vec, - #[serde(default = "default_1620")] + #[serde(default = "default_1625")] pub top_recalled: Vec, - #[serde(default = "default_1629")] + #[serde(default = "default_1634")] pub staleness: MemoryHealthStaleness, - #[serde(default = "default_1633")] + #[serde(default = "default_1638")] pub footprint: MemoryHealthFootprint, } @@ -34939,51 +35033,51 @@ impl MemoryHealthInput { pub struct MemoryHistoryRow { pub memory_id: String, pub version: Integer, - #[serde(default = "default_1634")] + #[serde(default = "default_1639")] pub version_text: String, - #[serde(default = "default_1635")] + #[serde(default = "default_1640")] pub value: Value, pub confidence: f64, - #[serde(default = "default_1636")] + #[serde(default = "default_1641")] pub source_trace: String, - #[serde(default = "default_1637")] + #[serde(default = "default_1642")] pub pinned: bool, pub created_at: String, - #[serde(default = "default_1638")] + #[serde(default = "default_1643")] pub expires_at: Option, - #[serde(default = "default_1639")] + #[serde(default = "default_1644")] pub tombstoned_at: Option, - #[serde(default = "default_1640")] + #[serde(default = "default_1645")] pub redacted_at: Option, - #[serde(default = "default_1641")] + #[serde(default = "default_1646")] pub redaction_reason: String, - #[serde(default = "default_1642")] + #[serde(default = "default_1647")] pub content_sha256: String, - #[serde(default = "default_1643")] + #[serde(default = "default_1648")] pub actor: String, - #[serde(default = "default_1644")] + #[serde(default = "default_1649")] pub source_class: String, - #[serde(default = "default_1645")] + #[serde(default = "default_1650")] pub agent: String, - #[serde(default = "default_1646")] + #[serde(default = "default_1651")] pub written_at: Option, - #[serde(default = "default_1647")] + #[serde(default = "default_1652")] pub status: String, - #[serde(default = "default_1648")] + #[serde(default = "default_1653")] pub conflict_with: Vec, - #[serde(default = "default_1649")] + #[serde(default = "default_1654")] pub tags: Vec, - #[serde(default = "default_1650")] + #[serde(default = "default_1655")] pub verified_at: Option, - #[serde(default = "default_1651")] + #[serde(default = "default_1656")] pub verified_by: String, - #[serde(default = "default_1652")] + #[serde(default = "default_1657")] pub verified_sha256: String, - #[serde(default = "default_1653")] + #[serde(default = "default_1658")] pub lock_mode: String, - #[serde(default = "default_1654")] + #[serde(default = "default_1659")] pub lock_reason: String, - #[serde(default = "default_1655")] + #[serde(default = "default_1660")] pub lock_until: Option, } @@ -35093,13 +35187,13 @@ impl MemoryHistoryInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryImportTotals { - #[serde(default = "default_1656")] + #[serde(default = "default_1661")] pub written: Integer, - #[serde(default = "default_1657")] + #[serde(default = "default_1662")] pub held: Integer, - #[serde(default = "default_1658")] + #[serde(default = "default_1663")] pub skipped: Integer, - #[serde(default = "default_1659")] + #[serde(default = "default_1664")] pub refused: Integer, } @@ -35182,11 +35276,11 @@ pub struct MemoryImportResult { pub index: Integer, pub key: String, pub outcome: MemoryImportResultOutcome, - #[serde(default = "default_1660")] + #[serde(default = "default_1665")] pub reason: MemoryImportResultReason, - #[serde(default = "default_1661")] + #[serde(default = "default_1666")] pub held_by: String, - #[serde(default = "default_1662")] + #[serde(default = "default_1667")] pub note: MemoryImportResultNote, } @@ -35195,7 +35289,7 @@ pub struct MemoryImportResult { pub struct MemoryImportOutput { pub totals: MemoryImportTotals, pub results: Vec, - #[serde(default = "default_1663")] + #[serde(default = "default_1668")] pub dry_run: bool, } @@ -35388,9 +35482,9 @@ pub struct MemoryImportCuratedRow { pub section_heading: String, pub bytes_written: Integer, pub verdict: String, - #[serde(default = "default_1664")] + #[serde(default = "default_1669")] pub rejection_reason: String, - #[serde(default = "default_1665")] + #[serde(default = "default_1670")] pub pinned_blocker_id: Option, } @@ -35482,21 +35576,21 @@ impl MemoryImportCuratedInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryImportEvidenceOutput { - #[serde(default = "default_1666")] + #[serde(default = "default_1671")] pub chunks_written: Integer, - #[serde(default = "default_1667")] + #[serde(default = "default_1672")] pub links_written: Integer, - #[serde(default = "default_1668")] + #[serde(default = "default_1673")] pub digests_written: Integer, - #[serde(default = "default_1669")] + #[serde(default = "default_1674")] pub embedding_model: String, - #[serde(default = "default_1670")] + #[serde(default = "default_1675")] pub embedding_dim: Integer, - #[serde(default = "default_1671")] + #[serde(default = "default_1676")] pub edited: Vec, - #[serde(default = "default_1672")] + #[serde(default = "default_1677")] pub skipped: Integer, - #[serde(default = "default_1673")] + #[serde(default = "default_1678")] pub unchecked: Integer, } @@ -35833,7 +35927,7 @@ pub struct InspectRow { pub memory_key: String, pub memory_id: String, pub version: Integer, - #[serde(default = "default_1683")] + #[serde(default = "default_1688")] pub content_sha256: String, pub memory_type: String, pub status: String, @@ -35844,9 +35938,9 @@ pub struct InspectRow { pub actor: String, pub updated_at: String, pub sensitivity: String, - #[serde(default = "default_1684")] + #[serde(default = "default_1689")] pub versions: Integer, - #[serde(default = "default_1685")] + #[serde(default = "default_1690")] pub excerpt: String, } @@ -35854,27 +35948,27 @@ pub struct InspectRow { #[non_exhaustive] pub struct InspectView { pub definition: String, - #[serde(default = "default_1674")] + #[serde(default = "default_1679")] pub refs: Vec, - #[serde(default = "default_1675")] + #[serde(default = "default_1680")] pub live_rows: Integer, - #[serde(default = "default_1676")] + #[serde(default = "default_1681")] pub by_type: Vec, - #[serde(default = "default_1677")] + #[serde(default = "default_1682")] pub by_status: Vec, - #[serde(default = "default_1678")] + #[serde(default = "default_1683")] pub by_source_class: Vec, - #[serde(default = "default_1679")] + #[serde(default = "default_1684")] pub top_tags: Vec, - #[serde(default = "default_1680")] + #[serde(default = "default_1685")] pub categories: Vec, - #[serde(default = "default_1681")] + #[serde(default = "default_1686")] pub first_updated_at: Option, - #[serde(default = "default_1682")] + #[serde(default = "default_1687")] pub last_updated_at: Option, - #[serde(default = "default_1686")] + #[serde(default = "default_1691")] pub newest: Vec, - #[serde(default = "default_1687")] + #[serde(default = "default_1692")] pub complete: bool, } @@ -35890,32 +35984,32 @@ pub struct InspectCall { #[non_exhaustive] pub struct InspectActivity { pub window_seconds: Integer, - #[serde(default = "default_1688")] + #[serde(default = "default_1693")] pub calls: Vec, - #[serde(default = "default_1689")] + #[serde(default = "default_1694")] pub first_at: Option, - #[serde(default = "default_1690")] + #[serde(default = "default_1695")] pub last_at: Option, - #[serde(default = "default_1691")] + #[serde(default = "default_1696")] pub gap: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct InspectSettings { - #[serde(default = "default_1692")] + #[serde(default = "default_1697")] pub guide_revision: Integer, - #[serde(default = "default_1693")] + #[serde(default = "default_1698")] pub guide_summary: String, - #[serde(default = "default_1694")] + #[serde(default = "default_1699")] pub categories_registered: Integer, - #[serde(default = "default_1695")] + #[serde(default = "default_1700")] pub extraction_policy: Option, - #[serde(default = "default_1696")] + #[serde(default = "default_1701")] pub extraction_policy_unavailable: String, - #[serde(default = "default_1697")] + #[serde(default = "default_1702")] pub extraction_instructions: String, - #[serde(default = "default_1698")] + #[serde(default = "default_1703")] pub extraction_instructions_refs: Vec, } @@ -35931,7 +36025,7 @@ pub struct MemoryInspectOutput { pub others: InspectView, pub activity: InspectActivity, pub settings: InspectSettings, - #[serde(default = "default_1699")] + #[serde(default = "default_1704")] pub skipped: Vec, } @@ -36025,7 +36119,7 @@ pub struct MemoryKeyRef { #[non_exhaustive] pub struct MemoryKeysOutput { pub keys: Vec, - #[serde(default = "default_1700")] + #[serde(default = "default_1705")] pub truncated: bool, } @@ -36128,9 +36222,9 @@ pub struct LineageCandidate { pub decided_at: String, pub decided_by: String, pub match_confidence: LineageCandidateMatchConfidence, - #[serde(default = "default_1709")] + #[serde(default = "default_1714")] pub seeded_from_thread_id: String, - #[serde(default = "default_1710")] + #[serde(default = "default_1715")] pub seeded_from_msg_id: String, } @@ -36148,25 +36242,25 @@ pub struct LineageAuditEvent { pub struct MemoryLineageOutput { pub found: bool, pub memory_key: String, - #[serde(default = "default_1701")] + #[serde(default = "default_1706")] pub promotion_event: String, - #[serde(default = "default_1702")] + #[serde(default = "default_1707")] pub promoted_by: String, - #[serde(default = "default_1703")] + #[serde(default = "default_1708")] pub promoted_at: Option, - #[serde(default = "default_1704")] + #[serde(default = "default_1709")] pub rationale: String, - #[serde(default = "default_1705")] + #[serde(default = "default_1710")] pub source_trace: String, - #[serde(default = "default_1706")] + #[serde(default = "default_1711")] pub source_resource_id: String, - #[serde(default = "default_1707")] + #[serde(default = "default_1712")] pub mechanism: MemoryLineageOutputMechanism, - #[serde(default = "default_1708")] + #[serde(default = "default_1713")] pub supporters: Vec, - #[serde(default = "default_1711")] + #[serde(default = "default_1716")] pub candidate: Option, - #[serde(default = "default_1712")] + #[serde(default = "default_1717")] pub audit_chain: Vec, } @@ -36295,11 +36389,11 @@ pub struct MemoryLinkOutput { pub from_key: String, pub to_key: String, pub relation: String, - #[serde(default = "default_1713")] + #[serde(default = "default_1718")] pub confidence: f64, - #[serde(default = "default_1714")] + #[serde(default = "default_1719")] pub conflict_opened: bool, - #[serde(default = "default_1715")] + #[serde(default = "default_1720")] pub relation_defaulted: bool, } @@ -36613,17 +36707,17 @@ pub struct MemoryListEntry { pub struct MemoryListOutput { pub entries: Vec, pub truncated: bool, - #[serde(default = "default_1716")] + #[serde(default = "default_1721")] pub total: Integer, - #[serde(default = "default_1717")] + #[serde(default = "default_1722")] pub today: Integer, - #[serde(default = "default_1718")] + #[serde(default = "default_1723")] pub namespace_version: String, - #[serde(default = "default_1719")] + #[serde(default = "default_1724")] pub unchanged: bool, - #[serde(default = "default_1720")] + #[serde(default = "default_1725")] pub hidden: Integer, - #[serde(default = "default_1721")] + #[serde(default = "default_1726")] pub hidden_hint: String, } @@ -37009,19 +37103,19 @@ impl MemoryListInput { #[non_exhaustive] pub struct MemoryLockOutput { pub locked: bool, - #[serde(default = "default_1722")] + #[serde(default = "default_1727")] pub reason: String, - #[serde(default = "default_1723")] + #[serde(default = "default_1728")] pub memory_id: String, - #[serde(default = "default_1724")] + #[serde(default = "default_1729")] pub version: Option, - #[serde(default = "default_1725")] + #[serde(default = "default_1730")] pub lock_mode: String, - #[serde(default = "default_1726")] + #[serde(default = "default_1731")] pub lock_until: Option, - #[serde(default = "default_1727")] + #[serde(default = "default_1732")] pub locked_by: String, - #[serde(default = "default_1728")] + #[serde(default = "default_1733")] pub previous_mode: String, } @@ -37180,21 +37274,21 @@ pub struct MemoryMoveOutput { pub from_key: String, pub to_key: String, pub redirected: bool, - #[serde(default = "default_1729")] + #[serde(default = "default_1734")] pub memory_id: String, - #[serde(default = "default_1730")] + #[serde(default = "default_1735")] pub version: Integer, - #[serde(default = "default_1731")] + #[serde(default = "default_1736")] pub content_sha256: String, - #[serde(default = "default_1732")] + #[serde(default = "default_1737")] pub advisories: Vec, - #[serde(default = "default_1733")] + #[serde(default = "default_1738")] pub dry_run: bool, - #[serde(default = "default_1734")] + #[serde(default = "default_1739")] pub memory_type: String, - #[serde(default = "default_1735")] + #[serde(default = "default_1740")] pub value_preview: String, - #[serde(default = "default_1736")] + #[serde(default = "default_1741")] pub sensitivity: String, } @@ -37406,7 +37500,7 @@ impl MemoryMoveInput { pub struct MemoryOutcomeOutput { pub recorded: bool, pub evidence_count_after: Integer, - #[serde(default = "default_1737")] + #[serde(default = "default_1742")] pub quarantined: bool, } @@ -37649,13 +37743,13 @@ impl MemoryOutcomeRunInput { #[non_exhaustive] pub struct OutlineSession { pub session_id: String, - #[serde(default = "default_1739")] + #[serde(default = "default_1744")] pub date: String, - #[serde(default = "default_1740")] + #[serde(default = "default_1745")] pub headline: String, - #[serde(default = "default_1741")] + #[serde(default = "default_1746")] pub key_facts: Integer, - #[serde(default = "default_1742")] + #[serde(default = "default_1747")] pub rows: Integer, } @@ -37663,7 +37757,7 @@ pub struct OutlineSession { #[non_exhaustive] pub struct OutlineHub { pub entity: String, - #[serde(default = "default_1745")] + #[serde(default = "default_1750")] pub degree: Integer, } @@ -37671,28 +37765,28 @@ pub struct OutlineHub { #[non_exhaustive] pub struct OutlineCommunity { pub community_id: Integer, - #[serde(default = "default_1747")] + #[serde(default = "default_1752")] pub label: String, - #[serde(default = "default_1748")] + #[serde(default = "default_1753")] pub size: Integer, - #[serde(default = "default_1749")] + #[serde(default = "default_1754")] pub computed_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryOutlineOutput { - #[serde(default = "default_1738")] - pub rows_by_type: std::collections::HashMap, #[serde(default = "default_1743")] + pub rows_by_type: std::collections::HashMap, + #[serde(default = "default_1748")] pub sessions: Vec, - #[serde(default = "default_1744")] + #[serde(default = "default_1749")] pub sessions_total: Integer, - #[serde(default = "default_1746")] + #[serde(default = "default_1751")] pub hubs: Vec, - #[serde(default = "default_1750")] + #[serde(default = "default_1755")] pub communities: Vec, - #[serde(default = "default_1751")] + #[serde(default = "default_1756")] pub profile_chars: Integer, } @@ -37844,7 +37938,7 @@ pub struct OwnerUsageRow { pub recalls: Integer, pub used: Integer, pub harm: Integer, - #[serde(default = "default_1752")] + #[serde(default = "default_1757")] pub last_recalled: Option, } @@ -38331,7 +38425,7 @@ pub struct MemoryPromoteOutput { pub shared_memory_key: String, pub promotion_event: String, pub reversible_until: String, - #[serde(default = "default_1753")] + #[serde(default = "default_1758")] pub ignored_args: Vec, } @@ -38500,18 +38594,18 @@ impl MemoryPromoteInput { pub struct MemoryProposalDecision { pub memory_key: String, pub decided: bool, - #[serde(default = "default_1755")] + #[serde(default = "default_1760")] pub status: String, - #[serde(default = "default_1756")] + #[serde(default = "default_1761")] pub reason: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryProposalDecideOutput { - #[serde(default = "default_1754")] + #[serde(default = "default_1759")] pub decided: Integer, - #[serde(default = "default_1757")] + #[serde(default = "default_1762")] pub results: Vec, } @@ -38612,33 +38706,33 @@ pub enum MemoryProposalReady { pub struct MemoryProposal { pub memory_key: String, pub memory_id: String, - #[serde(default = "default_1758")] + #[serde(default = "default_1763")] pub content_sha256: String, - #[serde(default = "default_1759")] + #[serde(default = "default_1764")] pub agent: String, - #[serde(default = "default_1760")] + #[serde(default = "default_1765")] pub memory_type: String, - #[serde(default = "default_1761")] + #[serde(default = "default_1766")] pub value_preview: String, - #[serde(default = "default_1762")] + #[serde(default = "default_1767")] pub sensitivity: String, - #[serde(default = "default_1763")] + #[serde(default = "default_1768")] pub tags: Vec, - #[serde(default = "default_1764")] + #[serde(default = "default_1769")] pub created_at: String, - #[serde(default = "default_1765")] + #[serde(default = "default_1770")] pub graded_passes: Integer, - #[serde(default = "default_1766")] + #[serde(default = "default_1771")] pub graded_fails: Integer, - #[serde(default = "default_1767")] + #[serde(default = "default_1772")] pub last_graded_at: String, - #[serde(default = "default_1768")] + #[serde(default = "default_1773")] pub used_count: Integer, - #[serde(default = "default_1769")] + #[serde(default = "default_1774")] pub harm_count: Integer, - #[serde(default = "default_1770")] + #[serde(default = "default_1775")] pub ready: MemoryProposalReady, - #[serde(default = "default_1771")] + #[serde(default = "default_1776")] pub conflict_with: Vec, } @@ -38654,24 +38748,24 @@ pub enum ProposalPolicyMode { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProposalPolicy { - #[serde(default = "default_1774")] + #[serde(default = "default_1779")] pub mode: ProposalPolicyMode, - #[serde(default = "default_1775")] + #[serde(default = "default_1780")] pub min_passes: Integer, - #[serde(default = "default_1776")] + #[serde(default = "default_1781")] pub max_fails: Integer, - #[serde(default = "default_1777")] + #[serde(default = "default_1782")] pub reject_after_fails: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryProposalsOutput { - #[serde(default = "default_1772")] + #[serde(default = "default_1777")] pub proposals: Vec, - #[serde(default = "default_1773")] - pub total: Integer, #[serde(default = "default_1778")] + pub total: Integer, + #[serde(default = "default_1783")] pub policy: ProposalPolicy, } @@ -38789,19 +38883,19 @@ impl MemoryProposalsInput { pub struct MemoryProvenanceLink { pub direction: String, pub memory_key: String, - #[serde(default = "default_1792")] + #[serde(default = "default_1797")] pub relation: String, - #[serde(default = "default_1793")] + #[serde(default = "default_1798")] pub label: String, - #[serde(default = "default_1794")] + #[serde(default = "default_1799")] pub explanation: String, - #[serde(default = "default_1795")] + #[serde(default = "default_1800")] pub evidence: Vec, - #[serde(default = "default_1796")] + #[serde(default = "default_1801")] pub confidence: f64, - #[serde(default = "default_1797")] + #[serde(default = "default_1802")] pub author: String, - #[serde(default = "default_1798")] + #[serde(default = "default_1803")] pub run_id: String, } @@ -38809,33 +38903,33 @@ pub struct MemoryProvenanceLink { #[non_exhaustive] pub struct MemoryProvenanceOutput { pub found: bool, - #[serde(default = "default_1779")] + #[serde(default = "default_1784")] pub source_trace: String, - #[serde(default = "default_1780")] + #[serde(default = "default_1785")] pub source_kind: String, - #[serde(default = "default_1781")] + #[serde(default = "default_1786")] pub actor: String, - #[serde(default = "default_1782")] + #[serde(default = "default_1787")] pub source_class: String, - #[serde(default = "default_1783")] + #[serde(default = "default_1788")] pub source_label: String, - #[serde(default = "default_1784")] + #[serde(default = "default_1789")] pub thread_id: String, - #[serde(default = "default_1785")] + #[serde(default = "default_1790")] pub thread_exists: bool, - #[serde(default = "default_1786")] + #[serde(default = "default_1791")] pub thread_title: String, - #[serde(default = "default_1787")] + #[serde(default = "default_1792")] pub agent: String, - #[serde(default = "default_1788")] + #[serde(default = "default_1793")] pub session_id: String, - #[serde(default = "default_1789")] + #[serde(default = "default_1794")] pub run_id: String, - #[serde(default = "default_1790")] + #[serde(default = "default_1795")] pub written_at: String, - #[serde(default = "default_1791")] + #[serde(default = "default_1796")] pub source_resource_id: String, - #[serde(default = "default_1799")] + #[serde(default = "default_1804")] pub links: Vec, } @@ -38930,17 +39024,17 @@ impl MemoryProvenanceInput { pub struct RecallTurn { pub evidence_id: String, pub session_id: String, - #[serde(default = "default_1800")] + #[serde(default = "default_1805")] pub role: String, - #[serde(default = "default_1801")] + #[serde(default = "default_1806")] pub actor: String, - #[serde(default = "default_1802")] + #[serde(default = "default_1807")] pub observed_at: String, - #[serde(default = "default_1803")] + #[serde(default = "default_1808")] pub content: String, - #[serde(default = "default_1804")] + #[serde(default = "default_1809")] pub truncated: bool, - #[serde(default = "default_1805")] + #[serde(default = "default_1810")] pub matched_tokens: Integer, } @@ -38957,21 +39051,21 @@ pub enum MemoryRecallOutputOrder { #[non_exhaustive] pub struct MemoryRecallOutput { pub turns: Vec, - #[serde(default = "default_1806")] + #[serde(default = "default_1811")] pub total_matched: Integer, - #[serde(default = "default_1807")] + #[serde(default = "default_1812")] pub returned: Integer, - #[serde(default = "default_1808")] + #[serde(default = "default_1813")] pub has_more: bool, - #[serde(default = "default_1809")] + #[serde(default = "default_1814")] pub next_cursor: String, - #[serde(default = "default_1810")] + #[serde(default = "default_1815")] pub next_offset: Integer, - #[serde(default = "default_1811")] + #[serde(default = "default_1816")] pub order: MemoryRecallOutputOrder, - #[serde(default = "default_1812")] + #[serde(default = "default_1817")] pub query_tokens: Vec, - #[serde(default = "default_1813")] + #[serde(default = "default_1818")] pub tokens_returned: Integer, } @@ -39253,19 +39347,19 @@ pub struct MemoryRecordConflictRow { pub schema_name: String, pub memory_key: String, pub field_name: String, - #[serde(default = "default_1814")] + #[serde(default = "default_1819")] pub prior_value: Value, - #[serde(default = "default_1815")] + #[serde(default = "default_1820")] pub incoming_value: Value, pub prior_record_id: String, pub incoming_record_id: String, - #[serde(default = "default_1816")] + #[serde(default = "default_1821")] pub prior_memory_id: String, - #[serde(default = "default_1817")] + #[serde(default = "default_1822")] pub incoming_memory_id: String, - #[serde(default = "default_1818")] + #[serde(default = "default_1823")] pub detected_at: Option, - #[serde(default = "default_1819")] + #[serde(default = "default_1824")] pub resolved_at: Option, } @@ -39273,7 +39367,7 @@ pub struct MemoryRecordConflictRow { #[non_exhaustive] pub struct MemoryRecordConflictsOutput { pub rows: Vec, - #[serde(default = "default_1820")] + #[serde(default = "default_1825")] pub truncated: bool, } @@ -39383,19 +39477,19 @@ pub enum MemoryRecordRowStatus { #[non_exhaustive] pub struct MemoryRecordRow { pub record_id: String, - #[serde(default = "default_1821")] + #[serde(default = "default_1826")] pub memory_key: String, - #[serde(default = "default_1822")] + #[serde(default = "default_1827")] pub memory_id: String, - #[serde(default = "default_1823")] + #[serde(default = "default_1828")] pub record: std::collections::HashMap, - #[serde(default = "default_1824")] + #[serde(default = "default_1829")] pub field_states: std::collections::HashMap, - #[serde(default = "default_1825")] + #[serde(default = "default_1830")] pub status: MemoryRecordRowStatus, - #[serde(default = "default_1826")] + #[serde(default = "default_1831")] pub valid_at: Option, - #[serde(default = "default_1827")] + #[serde(default = "default_1832")] pub valid_to: Option, } @@ -39462,7 +39556,7 @@ impl MemoryRecordHistoryInput { #[non_exhaustive] pub struct MemoryRecordQueryOutput { pub rows: Vec, - #[serde(default = "default_1828")] + #[serde(default = "default_1833")] pub truncated: bool, } @@ -39686,15 +39780,15 @@ pub enum MemoryRecordWriteOutputKeySource { pub struct MemoryRecordWriteOutput { pub record_id: String, pub field_count: Integer, - #[serde(default = "default_1829")] + #[serde(default = "default_1834")] pub memory_key: String, - #[serde(default = "default_1830")] + #[serde(default = "default_1835")] pub key_source: MemoryRecordWriteOutputKeySource, - #[serde(default = "default_1831")] + #[serde(default = "default_1836")] pub fold: std::collections::HashMap, - #[serde(default = "default_1832")] + #[serde(default = "default_1837")] pub superseded_record_id: String, - #[serde(default = "default_1833")] + #[serde(default = "default_1838")] pub conflicts: Integer, } @@ -39937,13 +40031,13 @@ impl MemoryRecordWriteInput { #[non_exhaustive] pub struct MemoryRedactOutput { pub redacted: bool, - #[serde(default = "default_1834")] + #[serde(default = "default_1839")] pub refused_head: bool, - #[serde(default = "default_1835")] + #[serde(default = "default_1840")] pub redacted_at: Option, - #[serde(default = "default_1836")] + #[serde(default = "default_1841")] pub cache_rows_deleted: Integer, - #[serde(default = "default_1837")] + #[serde(default = "default_1842")] pub precedent_rows_deleted: Integer, } @@ -40103,7 +40197,7 @@ impl MemoryReindexInput { #[non_exhaustive] pub struct MemoryRejectOutput { pub rejected: bool, - #[serde(default = "default_1838")] + #[serde(default = "default_1843")] pub rejected_at: Option, } @@ -40219,7 +40313,7 @@ pub struct MemoryRelatedHit { pub struct MemoryRelatedOutput { pub results: Vec, pub source_entities: Vec, - #[serde(default = "default_1839")] + #[serde(default = "default_1844")] pub reason: String, } @@ -40334,13 +40428,13 @@ impl MemoryRelatedInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryResolveOrphanDuplicatesOutput { - #[serde(default = "default_1840")] + #[serde(default = "default_1845")] pub candidates: Integer, - #[serde(default = "default_1841")] + #[serde(default = "default_1846")] pub reactivated: Integer, - #[serde(default = "default_1842")] + #[serde(default = "default_1847")] pub dry_run: bool, - #[serde(default = "default_1843")] + #[serde(default = "default_1848")] pub memory_ids: Vec, } @@ -40417,15 +40511,15 @@ impl MemoryResolveOrphanDuplicatesInput { #[non_exhaustive] pub struct MemoryRestoreOutput { pub restored: bool, - #[serde(default = "default_1844")] + #[serde(default = "default_1849")] pub memory_id: Option, - #[serde(default = "default_1845")] + #[serde(default = "default_1850")] pub version: Option, - #[serde(default = "default_1846")] + #[serde(default = "default_1851")] pub expired: bool, - #[serde(default = "default_1847")] + #[serde(default = "default_1852")] pub redacted: bool, - #[serde(default = "default_1848")] + #[serde(default = "default_1853")] pub from_status: String, } @@ -40545,13 +40639,13 @@ pub struct SearchTraceHit { pub content_excerpt: String, pub distance: f64, pub similarity: f64, - #[serde(default = "default_1849")] + #[serde(default = "default_1854")] pub entity_boost: f64, pub rank_score: f64, pub rank: Integer, - #[serde(default = "default_1850")] + #[serde(default = "default_1855")] pub source: String, - #[serde(default = "default_1851")] + #[serde(default = "default_1856")] pub parent_memory_key: String, } @@ -40561,11 +40655,11 @@ pub struct MemorySearchTraceOutput { pub results: Vec, pub embedding_model: String, pub entity_filter: Vec, - #[serde(default = "default_1852")] + #[serde(default = "default_1857")] pub query_spellings: std::collections::HashMap, - #[serde(default = "default_1853")] + #[serde(default = "default_1858")] pub query_spellings_skipped: bool, - #[serde(default = "default_1854")] + #[serde(default = "default_1859")] pub stale_dropped: Integer, } @@ -41746,7 +41840,7 @@ pub struct SearchTraceLogRow { pub embedding_model: String, pub latency_ms: Integer, pub run_id: String, - #[serde(default = "default_1855")] + #[serde(default = "default_1860")] pub operation: String, } @@ -41855,71 +41949,71 @@ pub struct RefusedFact { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemorySetFromMessagesOutput { - #[serde(default = "default_1856")] + #[serde(default = "default_1861")] pub written: Vec, - #[serde(default = "default_1857")] + #[serde(default = "default_1862")] pub refused: Vec, - #[serde(default = "default_1858")] + #[serde(default = "default_1863")] pub tokens_in: Integer, - #[serde(default = "default_1859")] + #[serde(default = "default_1864")] pub tokens_out: Integer, - #[serde(default = "default_1860")] + #[serde(default = "default_1865")] pub llm_provider: String, - #[serde(default = "default_1861")] + #[serde(default = "default_1866")] pub llm_model: String, - #[serde(default = "default_1862")] + #[serde(default = "default_1867")] pub segments: Integer, - #[serde(default = "default_1863")] + #[serde(default = "default_1868")] pub foresight: Integer, - #[serde(default = "default_1864")] + #[serde(default = "default_1869")] pub forgotten: Integer, - #[serde(default = "default_1865")] + #[serde(default = "default_1870")] pub forgotten_keys: Vec, - #[serde(default = "default_1866")] + #[serde(default = "default_1871")] pub forget_requests: Integer, - #[serde(default = "default_1867")] + #[serde(default = "default_1872")] pub about_other: Integer, - #[serde(default = "default_1868")] + #[serde(default = "default_1873")] pub premise_facts: Integer, - #[serde(default = "default_1869")] + #[serde(default = "default_1874")] pub learning_candidates: Integer, - #[serde(default = "default_1870")] + #[serde(default = "default_1875")] pub ignored_args: Vec, - #[serde(default = "default_1871")] + #[serde(default = "default_1876")] pub segmenter: String, - #[serde(default = "default_1872")] + #[serde(default = "default_1877")] pub cached_tokens_in: Integer, - #[serde(default = "default_1873")] + #[serde(default = "default_1878")] pub ontology_warnings: Vec, - #[serde(default = "default_1874")] + #[serde(default = "default_1879")] pub evidence_ids: Vec, - #[serde(default = "default_1875")] + #[serde(default = "default_1880")] pub belief_source_links: Integer, - #[serde(default = "default_1876")] + #[serde(default = "default_1881")] pub pipeline_errors: Vec, - #[serde(default = "default_1877")] + #[serde(default = "default_1882")] pub value_updates_linked: Integer, - #[serde(default = "default_1878")] + #[serde(default = "default_1883")] pub stubbed_fields: Vec, - #[serde(default = "default_1879")] + #[serde(default = "default_1884")] pub degraded: Vec, - #[serde(default = "default_1880")] + #[serde(default = "default_1885")] pub deferred: bool, - #[serde(default = "default_1881")] + #[serde(default = "default_1886")] pub queue_id: String, - #[serde(default = "default_1882")] + #[serde(default = "default_1887")] pub deferred_by: String, - #[serde(default = "default_1883")] + #[serde(default = "default_1888")] pub stage_ms: std::collections::HashMap, - #[serde(default = "default_1884")] + #[serde(default = "default_1889")] pub observation_date_source: String, - #[serde(default = "default_1885")] + #[serde(default = "default_1890")] pub under_operator_policy: bool, - #[serde(default = "default_1886")] + #[serde(default = "default_1891")] pub extract_prompt_keys: Vec, - #[serde(default = "default_1887")] + #[serde(default = "default_1892")] pub llm_cache_hits: Integer, - #[serde(default = "default_1888")] + #[serde(default = "default_1893")] pub llm_cache_misses: Integer, } @@ -42374,22 +42468,22 @@ pub enum StackEntrySection { #[non_exhaustive] pub struct StackEntry { pub section: StackEntrySection, - #[serde(default = "default_1889")] + #[serde(default = "default_1894")] pub memory_key: String, - #[serde(default = "default_1890")] + #[serde(default = "default_1895")] pub memory_type: String, - #[serde(default = "default_1891")] + #[serde(default = "default_1896")] pub value: String, pub tokens: Integer, - #[serde(default = "default_1892")] + #[serde(default = "default_1897")] pub pinned: bool, - #[serde(default = "default_1893")] + #[serde(default = "default_1898")] pub recall_count: Integer, - #[serde(default = "default_1894")] + #[serde(default = "default_1899")] pub last_recalled_at: Option, - #[serde(default = "default_1895")] + #[serde(default = "default_1900")] pub actor: String, - #[serde(default = "default_1896")] + #[serde(default = "default_1901")] pub namespace: String, } @@ -42574,14 +42668,14 @@ impl MemoryStackInput { pub struct MemoryStatus { pub memory_id: String, pub status: String, - #[serde(default = "default_1897")] + #[serde(default = "default_1902")] pub superseded_by: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryStatusesOutput { - #[serde(default = "default_1898")] + #[serde(default = "default_1903")] pub rows: Vec, } @@ -42630,23 +42724,23 @@ impl MemoryStatusesInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemorySweepExpiredOutput { - #[serde(default = "default_1899")] + #[serde(default = "default_1904")] pub scanned: Integer, - #[serde(default = "default_1900")] + #[serde(default = "default_1905")] pub tombstoned: Integer, - #[serde(default = "default_1901")] + #[serde(default = "default_1906")] pub demoted: Integer, - #[serde(default = "default_1902")] + #[serde(default = "default_1907")] pub anonymized: Integer, - #[serde(default = "default_1903")] + #[serde(default = "default_1908")] pub locked_skipped: Integer, - #[serde(default = "default_1904")] + #[serde(default = "default_1909")] pub moved_skipped: Integer, - #[serde(default = "default_1905")] + #[serde(default = "default_1910")] pub dry_run: bool, - #[serde(default = "default_1906")] + #[serde(default = "default_1911")] pub sample: Vec>, - #[serde(default = "default_1907")] + #[serde(default = "default_1912")] pub failures: Vec, } @@ -42723,10 +42817,10 @@ pub struct MemoryTimelineEntry { pub memory_key: String, pub memory_type: String, pub content_excerpt: String, - #[serde(default = "default_1908")] + #[serde(default = "default_1913")] pub valid_at: Option, pub created_at: String, - #[serde(default = "default_1909")] + #[serde(default = "default_1914")] pub namespace: String, } @@ -42734,7 +42828,7 @@ pub struct MemoryTimelineEntry { #[non_exhaustive] pub struct MemoryTimelineOutput { pub events: Vec, - #[serde(default = "default_1910")] + #[serde(default = "default_1915")] pub total_matching: Integer, } @@ -42926,9 +43020,9 @@ impl MemoryTimelineInput { pub struct MemoryTouchResult { pub memory_key: String, pub touched: bool, - #[serde(default = "default_1913")] + #[serde(default = "default_1918")] pub version: Option, - #[serde(default = "default_1914")] + #[serde(default = "default_1919")] pub expires_at: Option, } @@ -42936,13 +43030,13 @@ pub struct MemoryTouchResult { #[non_exhaustive] pub struct MemoryTouchOutput { pub touched: bool, - #[serde(default = "default_1911")] + #[serde(default = "default_1916")] pub version: Option, - #[serde(default = "default_1912")] + #[serde(default = "default_1917")] pub expires_at: Option, - #[serde(default = "default_1915")] + #[serde(default = "default_1920")] pub results: Vec, - #[serde(default = "default_1916")] + #[serde(default = "default_1921")] pub touched_count: Integer, } @@ -43122,15 +43216,15 @@ impl MemoryTouchInput { #[non_exhaustive] pub struct MemoryUnlockOutput { pub unlocked: bool, - #[serde(default = "default_1917")] + #[serde(default = "default_1922")] pub reason: String, - #[serde(default = "default_1918")] + #[serde(default = "default_1923")] pub memory_id: String, - #[serde(default = "default_1919")] + #[serde(default = "default_1924")] pub version: Option, - #[serde(default = "default_1920")] + #[serde(default = "default_1925")] pub previous_mode: String, - #[serde(default = "default_1921")] + #[serde(default = "default_1926")] pub unlocked_by: String, } @@ -43235,11 +43329,11 @@ impl MemoryUnlockInput { #[non_exhaustive] pub struct MemoryUnpinOutput { pub unpinned: bool, - #[serde(default = "default_1922")] + #[serde(default = "default_1927")] pub reason: String, - #[serde(default = "default_1923")] + #[serde(default = "default_1928")] pub memory_id: String, - #[serde(default = "default_1924")] + #[serde(default = "default_1929")] pub version: Option, } @@ -43333,15 +43427,15 @@ impl MemoryUnpinInput { #[non_exhaustive] pub struct MemoryUpdateCandidate { pub memory_id: String, - #[serde(default = "default_1930")] + #[serde(default = "default_1935")] pub agent: String, - #[serde(default = "default_1931")] + #[serde(default = "default_1936")] pub user_id: String, - #[serde(default = "default_1932")] + #[serde(default = "default_1937")] pub session_id: String, - #[serde(default = "default_1933")] + #[serde(default = "default_1938")] pub version: Integer, - #[serde(default = "default_1934")] + #[serde(default = "default_1939")] pub status: String, } @@ -43349,23 +43443,23 @@ pub struct MemoryUpdateCandidate { #[non_exhaustive] pub struct MemoryUpdateOutput { pub updated: bool, - #[serde(default = "default_1925")] + #[serde(default = "default_1930")] pub memory_id: String, - #[serde(default = "default_1926")] + #[serde(default = "default_1931")] pub memory_key: String, - #[serde(default = "default_1927")] + #[serde(default = "default_1932")] pub new_version: Integer, - #[serde(default = "default_1928")] + #[serde(default = "default_1933")] pub content_sha256: String, - #[serde(default = "default_1929")] + #[serde(default = "default_1934")] pub reason: String, - #[serde(default = "default_1935")] + #[serde(default = "default_1940")] pub candidates: Vec, - #[serde(default = "default_1936")] + #[serde(default = "default_1941")] pub conflict_verdict: String, - #[serde(default = "default_1937")] + #[serde(default = "default_1942")] pub conflict_peers: Integer, - #[serde(default = "default_1938")] + #[serde(default = "default_1943")] pub duplicate_of: String, } @@ -43574,15 +43668,15 @@ impl MemoryUpdateInput { #[non_exhaustive] pub struct MemoryUpdateByIdOutput { pub updated: bool, - #[serde(default = "default_1939")] + #[serde(default = "default_1944")] pub new_version: Integer, - #[serde(default = "default_1940")] + #[serde(default = "default_1945")] pub content_sha256: String, - #[serde(default = "default_1941")] + #[serde(default = "default_1946")] pub conflict_verdict: String, - #[serde(default = "default_1942")] + #[serde(default = "default_1947")] pub conflict_peers: Integer, - #[serde(default = "default_1943")] + #[serde(default = "default_1948")] pub duplicate_of: String, } @@ -43710,23 +43804,23 @@ impl MemoryUpdateByIdInput { #[non_exhaustive] pub struct MemoryVerifyOutput { pub found: bool, - #[serde(default = "default_1944")] + #[serde(default = "default_1949")] pub changed: bool, - #[serde(default = "default_1945")] + #[serde(default = "default_1950")] pub memory_id: String, - #[serde(default = "default_1946")] + #[serde(default = "default_1951")] pub memory_key: String, - #[serde(default = "default_1947")] + #[serde(default = "default_1952")] pub namespace: String, - #[serde(default = "default_1948")] + #[serde(default = "default_1953")] pub verified_by: String, - #[serde(default = "default_1949")] + #[serde(default = "default_1954")] pub verified_at: Option, - #[serde(default = "default_1950")] + #[serde(default = "default_1955")] pub verification: String, - #[serde(default = "default_1951")] + #[serde(default = "default_1956")] pub version: Integer, - #[serde(default = "default_1952")] + #[serde(default = "default_1957")] pub content_sha256: String, } @@ -43931,13 +44025,13 @@ pub struct SchemaFieldOutput { #[serde(rename = "type")] pub r#type: String, pub required: bool, - #[serde(default = "default_1955")] + #[serde(default = "default_1960")] pub identity: bool, - #[serde(default = "default_1956")] + #[serde(default = "default_1961")] pub enum_values: Vec, - #[serde(default = "default_1957")] + #[serde(default = "default_1962")] pub constraints: std::collections::HashMap, - #[serde(default = "default_1958")] + #[serde(default = "default_1963")] pub description: String, } @@ -43946,11 +44040,11 @@ pub struct SchemaFieldOutput { pub struct MemorySchemaSummary { pub schema_id: String, pub name: String, - #[serde(default = "default_1953")] + #[serde(default = "default_1958")] pub description: String, - #[serde(default = "default_1954")] - pub status: String, #[serde(default = "default_1959")] + pub status: String, + #[serde(default = "default_1964")] pub fields: Vec, } @@ -44365,13 +44459,13 @@ impl MemorySchemaRegisterInput { #[non_exhaustive] pub struct MentorPlane { pub plane: String, - #[serde(default = "default_1961")] + #[serde(default = "default_1966")] pub calls: Integer, - #[serde(default = "default_1962")] + #[serde(default = "default_1967")] pub available: Option, - #[serde(default = "default_1963")] + #[serde(default = "default_1968")] pub when: String, - #[serde(default = "default_1964")] + #[serde(default = "default_1969")] pub mentored: bool, } @@ -44381,11 +44475,11 @@ pub struct MentorHint { pub code: String, pub severity: String, pub text: String, - #[serde(default = "default_1966")] + #[serde(default = "default_1971")] pub ops: Vec, - #[serde(default = "default_1967")] + #[serde(default = "default_1972")] pub evidence: std::collections::HashMap, - #[serde(default = "default_1968")] + #[serde(default = "default_1973")] pub plane: Option, } @@ -44393,9 +44487,9 @@ pub struct MentorHint { #[non_exhaustive] pub struct MentorAdoption { pub code: String, - #[serde(default = "default_1970")] + #[serde(default = "default_1975")] pub shown_sessions: Integer, - #[serde(default = "default_1971")] + #[serde(default = "default_1976")] pub followed_sessions: Integer, } @@ -44431,7 +44525,7 @@ pub enum UsageRungSource { #[non_exhaustive] pub struct UsageRung { pub rung: UsageRungRung, - #[serde(default = "default_1973")] + #[serde(default = "default_1978")] pub count: Option, pub source: UsageRungSource, pub meaning: String, @@ -44446,27 +44540,27 @@ pub struct MentorBriefOutput { pub window_seconds: Integer, pub computed_at: String, pub sessions: Integer, - #[serde(default = "default_1960")] - pub usage: std::collections::HashMap, #[serde(default = "default_1965")] + pub usage: std::collections::HashMap, + #[serde(default = "default_1970")] pub planes: Vec, - #[serde(default = "default_1969")] + #[serde(default = "default_1974")] pub hints: Vec, - #[serde(default = "default_1972")] + #[serde(default = "default_1977")] pub adoption: Vec, - #[serde(default = "default_1974")] + #[serde(default = "default_1979")] pub usage_evidence: Vec, - #[serde(default = "default_1975")] + #[serde(default = "default_1980")] pub ledger_from: Option, - #[serde(default = "default_1976")] + #[serde(default = "default_1981")] pub ledger_retention_days: Option, - #[serde(default = "default_1977")] + #[serde(default = "default_1982")] pub agents: Vec, - #[serde(default = "default_1978")] + #[serde(default = "default_1983")] pub agent_defaulted: bool, - #[serde(default = "default_1979")] + #[serde(default = "default_1984")] pub skipped: Vec, - #[serde(default = "default_1980")] + #[serde(default = "default_1985")] pub healthy: bool, } @@ -44615,33 +44709,33 @@ impl MentorGuideInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct NamespaceAuditSummary { - #[serde(default = "default_1981")] + #[serde(default = "default_1986")] pub live_rows: Integer, - #[serde(default = "default_1982")] + #[serde(default = "default_1987")] pub live_bytes: Integer, - #[serde(default = "default_1983")] + #[serde(default = "default_1988")] pub excerpt_bytes: Integer, - #[serde(default = "default_1984")] + #[serde(default = "default_1989")] pub version_rows: Integer, - #[serde(default = "default_1985")] + #[serde(default = "default_1990")] pub version_bytes: Integer, - #[serde(default = "default_1986")] + #[serde(default = "default_1991")] pub unembedded_rows: Integer, - #[serde(default = "default_1987")] + #[serde(default = "default_1992")] pub gets: Integer, - #[serde(default = "default_1988")] + #[serde(default = "default_1993")] pub searches: Integer, - #[serde(default = "default_1989")] + #[serde(default = "default_1994")] pub sets: Integer, - #[serde(default = "default_1990")] + #[serde(default = "default_1995")] pub get_search_ratio: f64, - #[serde(default = "default_1991")] + #[serde(default = "default_1996")] pub inspector_calls: Integer, - #[serde(default = "default_1992")] + #[serde(default = "default_1997")] pub typed_gets: Integer, - #[serde(default = "default_1993")] + #[serde(default = "default_1998")] pub written_in_window: Integer, - #[serde(default = "default_1994")] + #[serde(default = "default_1999")] pub ledger_calls: Integer, } @@ -44673,25 +44767,25 @@ pub struct NamespaceAuditFinding { pub kind: NamespaceAuditFindingKind, pub rule_version: Integer, pub source_op: String, - #[serde(default = "default_1995")] + #[serde(default = "default_2000")] pub window_seconds: Option, - #[serde(default = "default_1996")] + #[serde(default = "default_2001")] pub population: Option, pub sample_limit: Integer, pub samples_complete: bool, - #[serde(default = "default_1997")] + #[serde(default = "default_2002")] pub evidence: Vec, - #[serde(default = "default_1998")] + #[serde(default = "default_2003")] pub exceptions: String, - #[serde(default = "default_1999")] + #[serde(default = "default_2004")] pub uncertainty: String, pub code: String, pub severity: NamespaceAuditFindingSeverity, pub count: Integer, pub share: f64, - #[serde(default = "default_2000")] + #[serde(default = "default_2005")] pub bytes: Integer, - #[serde(default = "default_2001")] + #[serde(default = "default_2006")] pub samples: Vec>, pub detail: String, pub remedy: String, @@ -44706,7 +44800,7 @@ pub struct NamespaceAuditOutput { pub window_seconds: Integer, pub summary: NamespaceAuditSummary, pub findings: Vec, - #[serde(default = "default_2002")] + #[serde(default = "default_2007")] pub skipped: Vec, pub coverage: ReportCoverage, pub healthy: bool, @@ -44797,29 +44891,29 @@ pub enum BrowseEntryMyStatus { #[non_exhaustive] pub struct BrowseEntry { pub namespace: String, - #[serde(default = "default_2003")] + #[serde(default = "default_2008")] pub kind: String, pub description: String, pub owner_email: String, pub member_count: Integer, - #[serde(default = "default_2004")] + #[serde(default = "default_2009")] pub requires_approval: bool, pub created_at: String, - #[serde(default = "default_2005")] + #[serde(default = "default_2010")] pub join_policy: String, - #[serde(default = "default_2006")] + #[serde(default = "default_2011")] pub visibility: String, - #[serde(default = "default_2007")] + #[serde(default = "default_2012")] pub my_status: BrowseEntryMyStatus, - #[serde(default = "default_2008")] + #[serde(default = "default_2013")] pub my_role: String, - #[serde(default = "default_2009")] + #[serde(default = "default_2014")] pub repo: String, - #[serde(default = "default_2010")] + #[serde(default = "default_2015")] pub branch: String, - #[serde(default = "default_2011")] + #[serde(default = "default_2016")] pub guide_revision: Integer, - #[serde(default = "default_2012")] + #[serde(default = "default_2017")] pub guide_summary: String, } @@ -44923,9 +45017,9 @@ pub enum NamespaceCancelRequestOutputClearedRole { pub struct NamespaceCancelRequestOutput { pub cancelled: bool, pub namespace: String, - #[serde(default = "default_2013")] + #[serde(default = "default_2018")] pub cleared_role: Option, - #[serde(default = "default_2014")] + #[serde(default = "default_2019")] pub cancelled_at: Option, } @@ -44997,7 +45091,7 @@ pub struct NamespaceDeleteOutput { pub deleted: bool, pub namespace: String, pub updated_at: String, - #[serde(default = "default_2015")] + #[serde(default = "default_2020")] pub sources_retired: Vec, } @@ -45066,67 +45160,67 @@ pub enum NamespaceGetOutputClassification { pub struct NamespaceGetOutput { pub found: bool, pub namespace: String, - #[serde(default = "default_2016")] + #[serde(default = "default_2021")] pub kind: Option, - #[serde(default = "default_2017")] + #[serde(default = "default_2022")] pub owner_email: Option, - #[serde(default = "default_2018")] + #[serde(default = "default_2023")] pub description: Option, - #[serde(default = "default_2019")] + #[serde(default = "default_2024")] pub tags: Option>, - #[serde(default = "default_2020")] + #[serde(default = "default_2025")] pub active: Option, - #[serde(default = "default_2021")] + #[serde(default = "default_2026")] pub conversation_logging_enabled: Option, - #[serde(default = "default_2022")] + #[serde(default = "default_2027")] pub capture_generation_io: Option, - #[serde(default = "default_2023")] + #[serde(default = "default_2028")] pub coverage_sweep: Option, - #[serde(default = "default_2024")] + #[serde(default = "default_2029")] pub consolidation_enabled: Option, - #[serde(default = "default_2025")] + #[serde(default = "default_2030")] pub daily_cost_cap_usd: Option, - #[serde(default = "default_2026")] + #[serde(default = "default_2031")] pub daily_user_cost_cap_usd: Option, - #[serde(default = "default_2027")] + #[serde(default = "default_2032")] pub budget_alert_inbox: Option, - #[serde(default = "default_2028")] + #[serde(default = "default_2033")] pub conflict_threshold: Option, - #[serde(default = "default_2029")] + #[serde(default = "default_2034")] pub retention_days: Option, - #[serde(default = "default_2030")] + #[serde(default = "default_2035")] pub warm_days: Option, - #[serde(default = "default_2031")] + #[serde(default = "default_2036")] pub visibility: Option, - #[serde(default = "default_2032")] + #[serde(default = "default_2037")] pub requires_approval: Option, - #[serde(default = "default_2033")] + #[serde(default = "default_2038")] pub join_policy: Option, - #[serde(default = "default_2034")] + #[serde(default = "default_2039")] pub effective_join_policy: Option, - #[serde(default = "default_2035")] + #[serde(default = "default_2040")] pub retrieval_defaults: Option>, - #[serde(default = "default_2036")] + #[serde(default = "default_2041")] pub rerank_endpoint: Option, - #[serde(default = "default_2037")] + #[serde(default = "default_2042")] pub classify_endpoint: Option, - #[serde(default = "default_2038")] + #[serde(default = "default_2043")] pub default_conflict_policy: Option, - #[serde(default = "default_2039")] + #[serde(default = "default_2044")] pub proposal_policy: Option, - #[serde(default = "default_2040")] + #[serde(default = "default_2045")] pub code_change_policy: Option, - #[serde(default = "default_2041")] + #[serde(default = "default_2046")] pub tag_registry: Option>>, - #[serde(default = "default_2042")] + #[serde(default = "default_2047")] pub classification: Option, - #[serde(default = "default_2043")] + #[serde(default = "default_2048")] pub guide_revision: Option, - #[serde(default = "default_2044")] + #[serde(default = "default_2049")] pub guide_summary: Option, - #[serde(default = "default_2045")] + #[serde(default = "default_2050")] pub created_at: Option, - #[serde(default = "default_2046")] + #[serde(default = "default_2051")] pub updated_at: Option, } @@ -45179,17 +45273,17 @@ impl NamespaceGetInput { #[non_exhaustive] pub struct NamespaceGuideGetOutput { pub found: bool, - #[serde(default = "default_2047")] + #[serde(default = "default_2052")] pub revision: Integer, - #[serde(default = "default_2048")] + #[serde(default = "default_2053")] pub content: String, - #[serde(default = "default_2049")] + #[serde(default = "default_2054")] pub summary: String, - #[serde(default = "default_2050")] + #[serde(default = "default_2055")] pub note: String, - #[serde(default = "default_2051")] + #[serde(default = "default_2056")] pub updated_by: String, - #[serde(default = "default_2052")] + #[serde(default = "default_2057")] pub updated_at: Option, } @@ -45326,17 +45420,17 @@ impl NamespaceGuideHistoryInput { #[non_exhaustive] pub struct NamespaceGuideSetOutputNamespaceGuideGetOutput { pub found: bool, - #[serde(default = "default_2054")] + #[serde(default = "default_2059")] pub revision: Integer, - #[serde(default = "default_2055")] + #[serde(default = "default_2060")] pub content: String, - #[serde(default = "default_2056")] + #[serde(default = "default_2061")] pub summary: String, - #[serde(default = "default_2057")] + #[serde(default = "default_2062")] pub note: String, - #[serde(default = "default_2058")] + #[serde(default = "default_2063")] pub updated_by: String, - #[serde(default = "default_2059")] + #[serde(default = "default_2064")] pub updated_at: Option, } @@ -45344,10 +45438,10 @@ pub struct NamespaceGuideSetOutputNamespaceGuideGetOutput { #[non_exhaustive] pub struct NamespaceGuideSetOutput { pub written: bool, - #[serde(default = "default_2053")] + #[serde(default = "default_2058")] pub conflict: bool, pub revision: Integer, - #[serde(default = "default_2060")] + #[serde(default = "default_2065")] pub current: Option, } @@ -45468,7 +45562,7 @@ pub struct InventorySection { #[serde(deserialize_with = "required_nullable")] pub latest_at: Option, pub complete: bool, - #[serde(default = "default_2061")] + #[serde(default = "default_2066")] pub reason: String, } @@ -45498,10 +45592,10 @@ pub struct InventoryPopulation { pub population: InventoryPopulationPopulation, #[serde(deserialize_with = "required_nullable")] pub total: Option, - #[serde(default = "default_2062")] + #[serde(default = "default_2067")] pub top: Vec, pub complete: bool, - #[serde(default = "default_2063")] + #[serde(default = "default_2068")] pub reason: String, } @@ -45667,11 +45761,11 @@ pub struct NamespaceJoinOutput { pub joined: bool, pub namespace: String, pub role: NamespaceJoinOutputRole, - #[serde(default = "default_2064")] + #[serde(default = "default_2069")] pub status: String, - #[serde(default = "default_2065")] + #[serde(default = "default_2070")] pub requested_role: Option, - #[serde(default = "default_2066")] + #[serde(default = "default_2071")] pub pending_admins: Vec, pub joined_at: String, } @@ -45763,7 +45857,7 @@ impl NamespaceJoinInput { pub struct NamespaceLeaveOutput { pub left: bool, pub namespace: String, - #[serde(default = "default_2067")] + #[serde(default = "default_2072")] pub left_at: Option, } @@ -45840,27 +45934,27 @@ pub enum NamespaceEntryVisibility { #[non_exhaustive] pub struct NamespaceEntry { pub namespace: String, - #[serde(default = "default_2068")] + #[serde(default = "default_2073")] pub kind: String, pub owner_email: String, pub description: String, pub tags: Vec, pub active: bool, - #[serde(default = "default_2069")] + #[serde(default = "default_2074")] pub consolidation_enabled: bool, - #[serde(default = "default_2070")] + #[serde(default = "default_2075")] pub daily_cost_cap_usd: f64, - #[serde(default = "default_2071")] + #[serde(default = "default_2076")] pub daily_user_cost_cap_usd: f64, - #[serde(default = "default_2072")] + #[serde(default = "default_2077")] pub budget_alert_inbox: String, - #[serde(default = "default_2073")] + #[serde(default = "default_2078")] pub conflict_threshold: Option, - #[serde(default = "default_2074")] + #[serde(default = "default_2079")] pub retention_days: Integer, - #[serde(default = "default_2075")] + #[serde(default = "default_2080")] pub warm_days: Integer, - #[serde(default = "default_2076")] + #[serde(default = "default_2081")] pub visibility: NamespaceEntryVisibility, pub created_at: String, pub updated_at: String, @@ -46015,27 +46109,27 @@ pub enum MineEntryVisibility { pub struct MineEntry { pub namespace: String, pub role: String, - #[serde(default = "default_2077")] + #[serde(default = "default_2082")] pub status: String, - #[serde(default = "default_2078")] + #[serde(default = "default_2083")] pub pending_role: Option, - #[serde(default = "default_2079")] + #[serde(default = "default_2084")] pub pending_since: Option, - #[serde(default = "default_2080")] + #[serde(default = "default_2085")] pub pending_admins: Vec, - #[serde(default = "default_2081")] + #[serde(default = "default_2086")] pub visibility: MineEntryVisibility, - #[serde(default = "default_2082")] + #[serde(default = "default_2087")] pub kind: String, - #[serde(default = "default_2083")] + #[serde(default = "default_2088")] pub title: String, - #[serde(default = "default_2084")] + #[serde(default = "default_2089")] pub description: String, - #[serde(default = "default_2085")] + #[serde(default = "default_2090")] pub joined_at: Option, - #[serde(default = "default_2086")] + #[serde(default = "default_2091")] pub is_new: bool, - #[serde(default = "default_2087")] + #[serde(default = "default_2092")] pub inherited: bool, } @@ -46101,7 +46195,7 @@ pub struct OntologyEntry { pub name: String, pub status: String, pub description: String, - #[serde(default = "default_2088")] + #[serde(default = "default_2093")] pub cardinality: String, pub created_by: String, pub updated_at: String, @@ -46294,7 +46388,7 @@ pub struct NamespaceRegisterOutput { pub registered: bool, pub namespace: String, pub updated_at: String, - #[serde(default = "default_2089")] + #[serde(default = "default_2094")] pub visibility: NamespaceRegisterOutputVisibility, } @@ -47374,7 +47468,7 @@ impl NamespaceRegisterOntologyInput { #[non_exhaustive] pub struct NamespaceRestoreOutput { pub restored: bool, - #[serde(default = "default_2090")] + #[serde(default = "default_2095")] pub publication_pending: bool, pub target_namespace: String, pub snapshot_id: String, @@ -48261,15 +48355,15 @@ pub struct NamespaceRollbackOutput { pub version_at: Integer, pub reinstate: Integer, pub remove: Integer, - #[serde(default = "default_2091")] + #[serde(default = "default_2096")] pub skipped_no_head: Integer, - #[serde(default = "default_2092")] + #[serde(default = "default_2097")] pub skipped_already_gone: Integer, - #[serde(default = "default_2093")] + #[serde(default = "default_2098")] pub truncated: bool, - #[serde(default = "default_2094")] + #[serde(default = "default_2099")] pub sample: Vec>, - #[serde(default = "default_2095")] + #[serde(default = "default_2100")] pub applied_at: Option, } @@ -48448,101 +48542,101 @@ pub struct NamespaceSnapshotOutputSnapshotMemoryRow { pub confidence: f64, pub source_trace: String, pub pinned: bool, - #[serde(default = "default_2096")] + #[serde(default = "default_2101")] pub expires_at: Option, - #[serde(default = "default_2097")] + #[serde(default = "default_2102")] pub entities: Vec, - #[serde(default = "default_2098")] + #[serde(default = "default_2103")] pub version: Integer, - #[serde(default = "default_2099")] + #[serde(default = "default_2104")] pub content_sha256: String, - #[serde(default = "default_2100")] + #[serde(default = "default_2105")] pub actor: String, - #[serde(default = "default_2101")] + #[serde(default = "default_2106")] pub source_class: String, - #[serde(default = "default_2102")] + #[serde(default = "default_2107")] pub source_resource_id: String, - #[serde(default = "default_2103")] + #[serde(default = "default_2108")] pub verified_by: String, - #[serde(default = "default_2104")] + #[serde(default = "default_2109")] pub verified_at: Option, - #[serde(default = "default_2105")] + #[serde(default = "default_2110")] pub verified_sha256: String, - #[serde(default = "default_2106")] + #[serde(default = "default_2111")] pub grounding: String, - #[serde(default = "default_2107")] + #[serde(default = "default_2112")] pub evidence: String, - #[serde(default = "default_2108")] + #[serde(default = "default_2113")] pub tags: Vec, - #[serde(default = "default_2109")] + #[serde(default = "default_2114")] pub valid_at: Option, - #[serde(default = "default_2110")] + #[serde(default = "default_2115")] pub valid_to: Option, - #[serde(default = "default_2111")] + #[serde(default = "default_2116")] pub created_at: Option, - #[serde(default = "default_2112")] + #[serde(default = "default_2117")] pub updated_at: Option, - #[serde(default = "default_2113")] + #[serde(default = "default_2118")] pub value_json: String, - #[serde(default = "default_2114")] + #[serde(default = "default_2119")] pub status: NamespaceSnapshotOutputSnapshotMemoryRowStatus, - #[serde(default = "default_2115")] + #[serde(default = "default_2120")] pub requires_review: Option, - #[serde(default = "default_2116")] + #[serde(default = "default_2121")] pub conflict_with: Vec, - #[serde(default = "default_2117")] + #[serde(default = "default_2122")] pub duplicate_of: String, - #[serde(default = "default_2118")] + #[serde(default = "default_2123")] pub evidence_count: Integer, - #[serde(default = "default_2119")] + #[serde(default = "default_2124")] pub recall_count: Integer, - #[serde(default = "default_2120")] + #[serde(default = "default_2125")] pub last_recalled_at: Option, - #[serde(default = "default_2121")] + #[serde(default = "default_2126")] pub cross_promoted_from_memory_id: String, - #[serde(default = "default_2122")] + #[serde(default = "default_2127")] pub cross_promoted_from_namespace: String, - #[serde(default = "default_2123")] + #[serde(default = "default_2128")] pub superseded_by: String, - #[serde(default = "default_2124")] + #[serde(default = "default_2129")] pub rejection_reason: String, - #[serde(default = "default_2125")] + #[serde(default = "default_2130")] pub temporal_anchor: Option, - #[serde(default = "default_2126")] + #[serde(default = "default_2131")] pub temporal_confidence: f64, - #[serde(default = "default_2127")] + #[serde(default = "default_2132")] pub invalid_at: Option, - #[serde(default = "default_2128")] + #[serde(default = "default_2133")] pub char_limit: Option, - #[serde(default = "default_2129")] + #[serde(default = "default_2134")] pub reinforcement_count: Integer, - #[serde(default = "default_2130")] + #[serde(default = "default_2135")] pub last_reinforced_at: Option, - #[serde(default = "default_2131")] + #[serde(default = "default_2136")] pub mentioned_at: Option, - #[serde(default = "default_2132")] + #[serde(default = "default_2137")] pub sensitivity: String, - #[serde(default = "default_2133")] + #[serde(default = "default_2138")] pub redacted_at: Option, - #[serde(default = "default_2134")] + #[serde(default = "default_2139")] pub redaction_reason: String, - #[serde(default = "default_2135")] + #[serde(default = "default_2140")] pub lock_mode: String, - #[serde(default = "default_2136")] + #[serde(default = "default_2141")] pub lock_reason: String, - #[serde(default = "default_2137")] + #[serde(default = "default_2142")] pub lock_until: Option, - #[serde(default = "default_2138")] + #[serde(default = "default_2143")] pub locked_by: String, - #[serde(default = "default_2139")] + #[serde(default = "default_2144")] pub locked_at: Option, - #[serde(default = "default_2140")] + #[serde(default = "default_2145")] pub on_expire: String, - #[serde(default = "default_2141")] + #[serde(default = "default_2146")] pub expire_reason: String, - #[serde(default = "default_2142")] + #[serde(default = "default_2147")] pub files: Vec, - #[serde(default = "default_2143")] + #[serde(default = "default_2148")] pub concepts: Vec, } @@ -48551,11 +48645,11 @@ pub struct NamespaceSnapshotOutputSnapshotMemoryRow { pub struct NamespaceSnapshotOutputSnapshotTypeRow { pub memory_type: String, pub retention_days: Integer, - #[serde(default = "default_2144")] + #[serde(default = "default_2149")] pub dedup_threshold: Option, - #[serde(default = "default_2145")] + #[serde(default = "default_2150")] pub hot_quota: Integer, - #[serde(default = "default_2146")] + #[serde(default = "default_2151")] pub conflict_policy: String, } @@ -48770,7 +48864,7 @@ pub struct TaxonomyCommunity { pub community_id: Integer, pub label: String, pub size: Integer, - #[serde(default = "default_2147")] + #[serde(default = "default_2152")] pub top_entities: Vec, } @@ -48781,9 +48875,9 @@ pub struct NamespaceTaxonomyOutput { pub entities: Vec, pub memory_count: Integer, pub memory_types: Vec, - #[serde(default = "default_2148")] + #[serde(default = "default_2153")] pub communities: Vec, - #[serde(default = "default_2149")] + #[serde(default = "default_2154")] pub communities_computed_at: String, } @@ -48883,15 +48977,15 @@ pub enum TuneProposalTarget { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TuneEvidence { - #[serde(default = "default_2151")] + #[serde(default = "default_2156")] pub finding_codes: Vec, - #[serde(default = "default_2152")] + #[serde(default = "default_2157")] pub supporting_count: Integer, - #[serde(default = "default_2153")] + #[serde(default = "default_2158")] pub supporting: Vec, - #[serde(default = "default_2154")] + #[serde(default = "default_2159")] pub counter_count: Option, - #[serde(default = "default_2155")] + #[serde(default = "default_2160")] pub documents: Vec, } @@ -48917,10 +49011,10 @@ pub enum TuneApplyVia { #[non_exhaustive] pub struct TuneApply { pub op: String, - #[serde(default = "default_2159")] + #[serde(default = "default_2164")] pub via: TuneApplyVia, pub args: std::collections::HashMap, - #[serde(default = "default_2160")] + #[serde(default = "default_2165")] pub args_complete: bool, pub required_role: String, pub guard: String, @@ -48939,7 +49033,7 @@ pub struct ChunkStats { pub sections: Integer, pub sections_cut: Integer, pub max_input_tokens: Integer, - #[serde(default = "default_2162")] + #[serde(default = "default_2167")] pub over_input_limit: Option, } @@ -48959,25 +49053,25 @@ pub struct TuneProposal { pub title: String, pub rationale: String, pub current: String, - #[serde(default = "default_2150")] + #[serde(default = "default_2155")] pub current_revision: Option, pub proposed: String, pub evidence: TuneEvidence, - #[serde(default = "default_2156")] + #[serde(default = "default_2161")] pub affected_agents: Vec, - #[serde(default = "default_2157")] + #[serde(default = "default_2162")] pub affected_agents_total: Option, - #[serde(default = "default_2158")] + #[serde(default = "default_2163")] pub effect: TuneProposalEffect, pub historical: String, pub apply: TuneApply, - #[serde(default = "default_2161")] + #[serde(default = "default_2166")] pub apply_also: Vec, - #[serde(default = "default_2163")] + #[serde(default = "default_2168")] pub preview: Option, - #[serde(default = "default_2164")] + #[serde(default = "default_2169")] pub limits: String, - #[serde(default = "default_2165")] + #[serde(default = "default_2170")] pub refs: Vec, } @@ -48985,13 +49079,13 @@ pub struct TuneProposal { #[non_exhaustive] pub struct ChunkingSample { pub cap: Integer, - #[serde(default = "default_2171")] + #[serde(default = "default_2176")] pub population: Option, pub documents: Integer, pub unread: Integer, pub load_cap: Integer, pub embedder_model: String, - #[serde(default = "default_2172")] + #[serde(default = "default_2177")] pub input_token_limit: Option, pub current: ChunkStats, } @@ -49002,21 +49096,21 @@ pub struct NamespaceTuneOutput { pub org: String, pub namespace: String, pub computed_at: String, - #[serde(default = "default_2166")] + #[serde(default = "default_2171")] pub proposals: Vec, - #[serde(default = "default_2167")] + #[serde(default = "default_2172")] pub guide_revision: Option, - #[serde(default = "default_2168")] + #[serde(default = "default_2173")] pub categories_registered: Option, - #[serde(default = "default_2169")] + #[serde(default = "default_2174")] pub extraction_policy: Option, - #[serde(default = "default_2170")] + #[serde(default = "default_2175")] pub extraction_policy_unavailable: String, - #[serde(default = "default_2173")] + #[serde(default = "default_2178")] pub chunking: Option, - #[serde(default = "default_2174")] + #[serde(default = "default_2179")] pub skipped: Vec, - #[serde(default = "default_2175")] + #[serde(default = "default_2180")] pub model_used: bool, } @@ -49137,25 +49231,25 @@ pub struct NamespaceValidateFinding { pub kind: NamespaceValidateFindingKind, pub rule_version: Integer, pub source_op: String, - #[serde(default = "default_2176")] + #[serde(default = "default_2181")] pub window_seconds: Option, - #[serde(default = "default_2177")] + #[serde(default = "default_2182")] pub population: Option, pub sample_limit: Integer, pub samples_complete: bool, - #[serde(default = "default_2178")] + #[serde(default = "default_2183")] pub evidence: Vec, - #[serde(default = "default_2179")] + #[serde(default = "default_2184")] pub exceptions: String, - #[serde(default = "default_2180")] + #[serde(default = "default_2185")] pub uncertainty: String, pub check: String, pub severity: NamespaceValidateFindingSeverity, pub count: Integer, - #[serde(default = "default_2181")] + #[serde(default = "default_2186")] pub samples: Vec>, pub detail: String, - #[serde(default = "default_2182")] + #[serde(default = "default_2187")] pub totals: std::collections::HashMap, } @@ -49169,9 +49263,9 @@ pub struct NamespaceValidateOutput { pub warnings: Integer, pub infos: Integer, pub findings: Vec, - #[serde(default = "default_2183")] + #[serde(default = "default_2188")] pub skipped: Vec, - #[serde(default = "default_2184")] + #[serde(default = "default_2189")] pub keys_scoped: Integer, pub coverage: ReportCoverage, pub checked_at: String, @@ -49291,9 +49385,9 @@ impl NamespaceValidateInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ObserveCrystallizeOutput { - #[serde(default = "default_2185")] + #[serde(default = "default_2190")] pub enqueued: Integer, - #[serde(default = "default_2186")] + #[serde(default = "default_2191")] pub session_id: String, } @@ -49390,23 +49484,23 @@ impl ObserveCrystallizeInput { #[non_exhaustive] pub struct ObserveRecordOutput { pub memory_key: String, - #[serde(default = "default_2187")] + #[serde(default = "default_2192")] pub memory_id: String, - #[serde(default = "default_2188")] + #[serde(default = "default_2193")] pub kind: String, - #[serde(default = "default_2189")] + #[serde(default = "default_2194")] pub tags: Vec, - #[serde(default = "default_2190")] + #[serde(default = "default_2195")] pub file_paths: Vec, - #[serde(default = "default_2191")] + #[serde(default = "default_2196")] pub content_sha256: String, - #[serde(default = "default_2192")] + #[serde(default = "default_2197")] pub tool_name: String, - #[serde(default = "default_2193")] + #[serde(default = "default_2198")] pub has_error: bool, - #[serde(default = "default_2194")] + #[serde(default = "default_2199")] pub narrative_chars: Integer, - #[serde(default = "default_2195")] + #[serde(default = "default_2200")] pub skipped_reason: String, } @@ -49605,26 +49699,26 @@ pub struct ProjectionFailureRow { pub failure_id: String, pub org: String, pub namespace: String, - #[serde(default = "default_2196")] + #[serde(default = "default_2201")] pub agent: String, pub projection: String, - #[serde(default = "default_2197")] + #[serde(default = "default_2202")] pub source_operation: String, - #[serde(default = "default_2198")] + #[serde(default = "default_2203")] pub source_resource_id: String, - #[serde(default = "default_2199")] + #[serde(default = "default_2204")] pub memory_keys: Vec, - #[serde(default = "default_2200")] + #[serde(default = "default_2205")] pub error_type: String, - #[serde(default = "default_2201")] + #[serde(default = "default_2206")] pub error_message: String, - #[serde(default = "default_2202")] + #[serde(default = "default_2207")] pub payload: std::collections::HashMap, - #[serde(default = "default_2203")] + #[serde(default = "default_2208")] pub status: String, - #[serde(default = "default_2204")] + #[serde(default = "default_2209")] pub created_at: Option, - #[serde(default = "default_2205")] + #[serde(default = "default_2210")] pub resolved_at: Option, } @@ -49778,22 +49872,22 @@ pub struct ProjectionFailureRetryRow { pub projection: String, pub retried: bool, pub resolved: bool, - #[serde(default = "default_2206")] + #[serde(default = "default_2211")] pub abandoned: bool, - #[serde(default = "default_2207")] + #[serde(default = "default_2212")] pub reason: String, - #[serde(default = "default_2208")] + #[serde(default = "default_2213")] pub error: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProjectionFailureRetryOutput { - #[serde(default = "default_2209")] + #[serde(default = "default_2214")] pub results: Vec, pub retried: Integer, pub resolved: Integer, - #[serde(default = "default_2210")] + #[serde(default = "default_2215")] pub abandoned: Integer, } @@ -49875,15 +49969,15 @@ impl ProjectionFailureRetryInput { pub struct OrgModelCallsOutput { pub org: String, pub enabled: bool, - #[serde(default = "default_2211")] + #[serde(default = "default_2216")] pub reason: String, - #[serde(default = "default_2212")] + #[serde(default = "default_2217")] pub updated_by: String, - #[serde(default = "default_2213")] + #[serde(default = "default_2218")] pub updated_at: Option, - #[serde(default = "default_2214")] + #[serde(default = "default_2219")] pub locked: bool, - #[serde(default = "default_2215")] + #[serde(default = "default_2220")] pub locked_by: String, } @@ -50222,7 +50316,7 @@ impl PolicyDecisionsInput { #[non_exhaustive] pub struct PolicyDeleteOutput { pub removed: bool, - #[serde(default = "default_2216")] + #[serde(default = "default_2221")] pub widening: bool, } @@ -50288,12 +50382,12 @@ pub struct PolicyRuleOut { pub condition: std::collections::HashMap, pub description: String, pub enabled: bool, - #[serde(default = "default_2217")] + #[serde(default = "default_2222")] pub mode: String, pub created_by: String, - #[serde(default = "default_2218")] + #[serde(default = "default_2223")] pub created_at: Option, - #[serde(default = "default_2219")] + #[serde(default = "default_2224")] pub updated_at: Option, } @@ -50365,9 +50459,9 @@ impl PolicyListInput { pub struct PolicySetOutput { pub rule: PolicyRuleOut, pub leaf_count: Integer, - #[serde(default = "default_2220")] + #[serde(default = "default_2225")] pub widening: bool, - #[serde(default = "default_2221")] + #[serde(default = "default_2226")] pub change: Vec, } @@ -50637,37 +50731,37 @@ pub struct ProcedureEvolveOutput { pub revision: Integer, pub changed: bool, pub template: bool, - #[serde(default = "default_2222")] + #[serde(default = "default_2227")] pub folded_runs: Integer, - #[serde(default = "default_2223")] + #[serde(default = "default_2228")] pub gate: ProcedureEvolveOutputGate, - #[serde(default = "default_2224")] + #[serde(default = "default_2229")] pub gate_mode: String, - #[serde(default = "default_2225")] + #[serde(default = "default_2230")] pub gate_llr: f64, - #[serde(default = "default_2226")] + #[serde(default = "default_2231")] pub gate_before: std::collections::HashMap, - #[serde(default = "default_2227")] + #[serde(default = "default_2232")] pub gate_after: std::collections::HashMap, - #[serde(default = "default_2228")] + #[serde(default = "default_2233")] pub gate_cost_before: std::collections::HashMap, - #[serde(default = "default_2229")] + #[serde(default = "default_2234")] pub gate_cost_after: std::collections::HashMap, - #[serde(default = "default_2230")] + #[serde(default = "default_2235")] pub gate_reason: String, - #[serde(default = "default_2231")] + #[serde(default = "default_2236")] pub dead_end_steps: Vec, - #[serde(default = "default_2232")] + #[serde(default = "default_2237")] pub fail_prone_steps: Vec, - #[serde(default = "default_2233")] + #[serde(default = "default_2238")] pub fail_prone_transitions: Vec, - #[serde(default = "default_2234")] + #[serde(default = "default_2239")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2235")] + #[serde(default = "default_2240")] pub strikes: Integer, - #[serde(default = "default_2236")] + #[serde(default = "default_2241")] pub quarantined: bool, - #[serde(default = "default_2237")] + #[serde(default = "default_2242")] pub retention: std::collections::HashMap, } @@ -50890,9 +50984,9 @@ pub struct ProcedureForkOutput { pub memory_key: String, pub version: Integer, pub name: String, - #[serde(default = "default_2238")] + #[serde(default = "default_2243")] pub steps: Vec, - #[serde(default = "default_2239")] + #[serde(default = "default_2244")] pub forked_from: std::collections::HashMap, } @@ -51152,32 +51246,32 @@ pub enum ProcedureLocateOutputStatus { #[non_exhaustive] pub struct ProcedureLocateOutput { pub memory_key: String, - #[serde(default = "default_2240")] + #[serde(default = "default_2245")] pub name: String, - #[serde(default = "default_2241")] + #[serde(default = "default_2246")] pub status: ProcedureLocateOutputStatus, pub matched: bool, - #[serde(default = "default_2242")] + #[serde(default = "default_2247")] pub active: Option>, - #[serde(default = "default_2243")] + #[serde(default = "default_2248")] pub hops: Vec>>, - #[serde(default = "default_2244")] + #[serde(default = "default_2249")] pub entry_nodes: Vec, - #[serde(default = "default_2245")] + #[serde(default = "default_2250")] pub dominant_next: Vec, - #[serde(default = "default_2246")] + #[serde(default = "default_2251")] pub revisits: std::collections::HashMap, - #[serde(default = "default_2247")] + #[serde(default = "default_2252")] pub looping: bool, - #[serde(default = "default_2248")] + #[serde(default = "default_2253")] pub exits: Vec, - #[serde(default = "default_2249")] + #[serde(default = "default_2254")] pub failure_notes: Vec>, - #[serde(default = "default_2250")] + #[serde(default = "default_2255")] pub rendered: String, - #[serde(default = "default_2251")] + #[serde(default = "default_2256")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2252")] + #[serde(default = "default_2257")] pub for_agent: std::collections::HashMap, } @@ -51332,43 +51426,43 @@ pub struct ProcedureMatch { pub name: String, pub situation: String, pub steps: Vec, - #[serde(default = "default_2253")] + #[serde(default = "default_2258")] pub tags: Vec, - #[serde(default = "default_2254")] + #[serde(default = "default_2259")] pub metadata: std::collections::HashMap, pub similarity: f64, pub memory_key: String, pub namespace: String, - #[serde(default = "default_2255")] + #[serde(default = "default_2260")] pub graph: Option>, - #[serde(default = "default_2256")] + #[serde(default = "default_2261")] pub template: bool, - #[serde(default = "default_2257")] + #[serde(default = "default_2262")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2258")] + #[serde(default = "default_2263")] pub status: ProcedureMatchStatus, - #[serde(default = "default_2259")] + #[serde(default = "default_2264")] pub quarantined: Option>, - #[serde(default = "default_2260")] + #[serde(default = "default_2265")] pub fail_prone_steps: Vec, - #[serde(default = "default_2261")] + #[serde(default = "default_2266")] pub revision: Integer, - #[serde(default = "default_2262")] + #[serde(default = "default_2267")] pub rejected_revisions: Vec>, - #[serde(default = "default_2263")] + #[serde(default = "default_2268")] pub tool_overlap: f64, - #[serde(default = "default_2264")] + #[serde(default = "default_2269")] pub score: f64, - #[serde(default = "default_2265")] + #[serde(default = "default_2270")] pub utility: f64, - #[serde(default = "default_2266")] + #[serde(default = "default_2271")] pub goal_similarity: Option, - #[serde(default = "default_2267")] + #[serde(default = "default_2272")] pub for_agent: std::collections::HashMap, - #[serde(default = "default_2268")] + #[serde(default = "default_2273")] pub run_stats_by_agent: std::collections::HashMap>, - #[serde(default = "default_2269")] + #[serde(default = "default_2274")] pub actor: String, } @@ -51376,11 +51470,11 @@ pub struct ProcedureMatch { #[non_exhaustive] pub struct ProcedureMatchOutput { pub matches: Vec, - #[serde(default = "default_2270")] + #[serde(default = "default_2275")] pub matched: Integer, - #[serde(default = "default_2271")] + #[serde(default = "default_2276")] pub procedure_key: String, - #[serde(default = "default_2272")] + #[serde(default = "default_2277")] pub score: f64, } @@ -51772,9 +51866,9 @@ pub struct ProcedureReviseOutput { pub revision: Integer, pub prior_revision: Integer, pub digest: String, - #[serde(default = "default_2273")] + #[serde(default = "default_2278")] pub steps: Vec, - #[serde(default = "default_2274")] + #[serde(default = "default_2279")] pub outcome: ProcedureReviseOutputOutcome, } @@ -51886,14 +51980,14 @@ pub struct ProfileActivityEntry { pub agent: String, pub last_activated_at: String, pub event_count: Integer, - #[serde(default = "default_2275")] + #[serde(default = "default_2280")] pub operations: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProfileActivityOutput { - #[serde(default = "default_2276")] + #[serde(default = "default_2281")] pub entries: Vec, } @@ -52001,17 +52095,17 @@ impl ProfileActivityInput { #[non_exhaustive] pub struct ProfileMutationOutput { pub version: Integer, - #[serde(default = "default_2277")] + #[serde(default = "default_2282")] pub memory_id: String, - #[serde(default = "default_2278")] + #[serde(default = "default_2283")] pub content_sha256: String, - #[serde(default = "default_2279")] + #[serde(default = "default_2284")] pub namespace: String, - #[serde(default = "default_2280")] + #[serde(default = "default_2285")] pub label: String, - #[serde(default = "default_2281")] + #[serde(default = "default_2286")] pub char_limit: Option, - #[serde(default = "default_2282")] + #[serde(default = "default_2287")] pub value_length: Integer, } @@ -52120,7 +52214,7 @@ pub struct ProfileRenderOutput { pub rendered: String, pub section_count: Integer, pub total_chars: Integer, - #[serde(default = "default_2283")] + #[serde(default = "default_2288")] pub labels: Vec, } @@ -52505,17 +52599,17 @@ pub enum ProfileStructuredOutputStatus { #[non_exhaustive] pub struct ProfileStructuredOutput { pub status: ProfileStructuredOutputStatus, - #[serde(default = "default_2284")] + #[serde(default = "default_2289")] pub profile: std::collections::HashMap, - #[serde(default = "default_2285")] + #[serde(default = "default_2290")] pub built_at: Option, - #[serde(default = "default_2286")] + #[serde(default = "default_2291")] pub memory_id: String, - #[serde(default = "default_2287")] + #[serde(default = "default_2292")] pub version: Integer, - #[serde(default = "default_2288")] + #[serde(default = "default_2293")] pub version_text: String, - #[serde(default = "default_2289")] + #[serde(default = "default_2294")] pub schema_sha256: String, } @@ -52632,13 +52726,13 @@ impl ProfileStructuredInput { #[non_exhaustive] pub struct ProfileSchemaOutput { pub found: bool, - #[serde(default = "default_2290")] + #[serde(default = "default_2295")] pub json_schema: std::collections::HashMap, - #[serde(default = "default_2291")] + #[serde(default = "default_2296")] pub schema_sha256: String, - #[serde(default = "default_2292")] + #[serde(default = "default_2297")] pub updated_by: String, - #[serde(default = "default_2293")] + #[serde(default = "default_2298")] pub updated_at: Option, } @@ -52791,10 +52885,10 @@ pub enum RunBeginOutputStatus { #[non_exhaustive] pub struct RunBeginOutput { pub run_id: String, - #[serde(default = "default_2294")] + #[serde(default = "default_2299")] pub status: RunBeginOutputStatus, pub started_at: String, - #[serde(default = "default_2295")] + #[serde(default = "default_2300")] pub next: String, } @@ -53002,29 +53096,29 @@ pub struct RunCompleteOutput { pub run_id: String, pub status: RunCompleteOutputStatus, pub duration_ms: Integer, - #[serde(default = "default_2296")] + #[serde(default = "default_2301")] pub used_applied: Integer, - #[serde(default = "default_2297")] + #[serde(default = "default_2302")] pub evidence_applied: Integer, - #[serde(default = "default_2298")] + #[serde(default = "default_2303")] pub harm_applied: Integer, - #[serde(default = "default_2299")] + #[serde(default = "default_2304")] pub memories_written: Vec, - #[serde(default = "default_2300")] + #[serde(default = "default_2305")] pub recalled: Integer, - #[serde(default = "default_2301")] + #[serde(default = "default_2306")] pub observations: Integer, - #[serde(default = "default_2302")] + #[serde(default = "default_2307")] pub procedure_runs_recorded: Integer, - #[serde(default = "default_2303")] + #[serde(default = "default_2308")] pub reflection_key: String, - #[serde(default = "default_2304")] + #[serde(default = "default_2309")] pub retain: String, - #[serde(default = "default_2305")] + #[serde(default = "default_2310")] pub retained: Integer, - #[serde(default = "default_2306")] + #[serde(default = "default_2311")] pub demoted: Integer, - #[serde(default = "default_2307")] + #[serde(default = "default_2312")] pub expiring: Integer, } @@ -53545,25 +53639,25 @@ pub enum RunGetOutputOverBudgetItem { #[non_exhaustive] pub struct RunGetOutput { pub found: bool, - #[serde(default = "default_2308")] + #[serde(default = "default_2313")] pub run: Option, - #[serde(default = "default_2309")] + #[serde(default = "default_2314")] pub recalled: Integer, - #[serde(default = "default_2310")] + #[serde(default = "default_2315")] pub recalled_keys: Vec, - #[serde(default = "default_2311")] + #[serde(default = "default_2316")] pub memories_written: Vec, - #[serde(default = "default_2312")] + #[serde(default = "default_2317")] pub observations: Integer, - #[serde(default = "default_2313")] + #[serde(default = "default_2318")] pub turns: Integer, - #[serde(default = "default_2314")] + #[serde(default = "default_2319")] pub unpriced_turns: Integer, - #[serde(default = "default_2315")] + #[serde(default = "default_2320")] pub cost_usd: f64, - #[serde(default = "default_2316")] + #[serde(default = "default_2321")] pub elapsed_seconds: Integer, - #[serde(default = "default_2317")] + #[serde(default = "default_2322")] pub over_budget: Vec, } @@ -53630,17 +53724,17 @@ pub struct RunGradeProposal { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct RunGradeOutput { - #[serde(default = "default_2318")] + #[serde(default = "default_2323")] pub graded: Integer, - #[serde(default = "default_2319")] + #[serde(default = "default_2324")] pub run_ids: Vec, - #[serde(default = "default_2320")] + #[serde(default = "default_2325")] pub skipped_active: Integer, - #[serde(default = "default_2321")] + #[serde(default = "default_2326")] pub unchanged: Integer, - #[serde(default = "default_2322")] + #[serde(default = "default_2327")] pub memories_counted: Integer, - #[serde(default = "default_2323")] + #[serde(default = "default_2328")] pub proposals_decided: Vec, } @@ -53755,7 +53849,7 @@ impl RunGradeInput { #[non_exhaustive] pub struct RunListOutput { pub runs: Vec, - #[serde(default = "default_2324")] + #[serde(default = "default_2329")] pub total: Option, } @@ -54032,39 +54126,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2327")] + #[serde(default = "default_2332")] pub content: String, - #[serde(default = "default_2328")] + #[serde(default = "default_2333")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2326")] + #[serde(default = "default_2331")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2329")] + #[serde(default = "default_2334")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2325")] - pub tracker: Option>, #[serde(default = "default_2330")] + pub tracker: Option>, + #[serde(default = "default_2335")] pub live: Option, - #[serde(default = "default_2331")] + #[serde(default = "default_2336")] pub memory: std::collections::HashMap, - #[serde(default = "default_2332")] + #[serde(default = "default_2337")] pub knowledge: std::collections::HashMap, - #[serde(default = "default_2333")] + #[serde(default = "default_2338")] pub profile: std::collections::HashMap, - #[serde(default = "default_2334")] + #[serde(default = "default_2339")] pub conversations: std::collections::HashMap, - #[serde(default = "default_2335")] + #[serde(default = "default_2340")] pub withheld: Option>, - #[serde(default = "default_2336")] + #[serde(default = "default_2341")] pub namespaces_skipped: Vec, } @@ -54257,7 +54351,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2337")] + #[serde(default = "default_2342")] pub revision: Integer, } @@ -54350,67 +54444,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2346")] + #[serde(default = "default_2351")] pub what: String, - #[serde(default = "default_2347")] + #[serde(default = "default_2352")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2349")] + #[serde(default = "default_2354")] pub tried: String, - #[serde(default = "default_2350")] + #[serde(default = "default_2355")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2352")] + #[serde(default = "default_2357")] pub what: String, - #[serde(rename = "ref", default = "default_2353")] + #[serde(rename = "ref", default = "default_2358")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2357")] + #[serde(default = "default_2362")] pub path: String, - #[serde(default = "default_2358")] + #[serde(default = "default_2363")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2343")] + #[serde(default = "default_2348")] pub goal: String, - #[serde(default = "default_2344")] + #[serde(default = "default_2349")] pub status: String, - #[serde(default = "default_2345")] + #[serde(default = "default_2350")] pub verification: String, - #[serde(default = "default_2348")] + #[serde(default = "default_2353")] pub decisions: Vec, - #[serde(default = "default_2351")] + #[serde(default = "default_2356")] pub dead_ends: Vec, - #[serde(default = "default_2354")] + #[serde(default = "default_2359")] pub done: Vec, - #[serde(default = "default_2355")] + #[serde(default = "default_2360")] pub open_questions: Vec, - #[serde(default = "default_2356")] + #[serde(default = "default_2361")] pub next_steps: Vec, - #[serde(default = "default_2359")] + #[serde(default = "default_2364")] pub files: Vec, - #[serde(default = "default_2360")] + #[serde(default = "default_2365")] pub constraints: Vec, - #[serde(default = "default_2361")] + #[serde(default = "default_2366")] pub pointers: Vec, - #[serde(default = "default_2362")] + #[serde(default = "default_2367")] pub client_summary: String, - #[serde(default = "default_2363")] + #[serde(default = "default_2368")] pub client_summary_at: String, } @@ -54418,45 +54512,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2338")] + #[serde(default = "default_2343")] pub brief_key: String, - #[serde(default = "default_2339")] + #[serde(default = "default_2344")] pub revision: Integer, - #[serde(default = "default_2340")] + #[serde(default = "default_2345")] pub snapshot_id: String, - #[serde(default = "default_2341")] + #[serde(default = "default_2346")] pub snapshot_key: String, - #[serde(default = "default_2342")] + #[serde(default = "default_2347")] pub rendered: String, - #[serde(default = "default_2364")] + #[serde(default = "default_2369")] pub sections: Option, - #[serde(default = "default_2365")] + #[serde(default = "default_2370")] pub project: String, - #[serde(default = "default_2366")] + #[serde(default = "default_2371")] pub branch: String, - #[serde(default = "default_2367")] + #[serde(default = "default_2372")] pub head_sha: String, - #[serde(default = "default_2368")] + #[serde(default = "default_2373")] pub author: String, - #[serde(default = "default_2369")] + #[serde(default = "default_2374")] pub trigger: String, - #[serde(default = "default_2370")] + #[serde(default = "default_2375")] pub actor: String, - #[serde(default = "default_2371")] + #[serde(default = "default_2376")] pub source_sessions: Vec, - #[serde(default = "default_2372")] + #[serde(default = "default_2377")] pub updated_at: Option, - #[serde(default = "default_2373")] + #[serde(default = "default_2378")] pub age_seconds: Integer, - #[serde(default = "default_2374")] + #[serde(default = "default_2379")] pub revisions: Integer, - #[serde(default = "default_2375")] + #[serde(default = "default_2380")] pub events_total: Integer, - #[serde(default = "default_2376")] + #[serde(default = "default_2381")] pub source_chars: Integer, - #[serde(default = "default_2377")] + #[serde(default = "default_2382")] pub brief_chars: Integer, - #[serde(default = "default_2378")] + #[serde(default = "default_2383")] pub deleted: bool, } @@ -54631,34 +54725,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2379")] + #[serde(default = "default_2384")] pub project: String, - #[serde(default = "default_2380")] + #[serde(default = "default_2385")] pub branch: String, - #[serde(default = "default_2381")] + #[serde(default = "default_2386")] pub agent: String, - #[serde(default = "default_2382")] + #[serde(default = "default_2387")] pub goal: String, - #[serde(default = "default_2383")] + #[serde(default = "default_2388")] pub status: String, - #[serde(default = "default_2384")] + #[serde(default = "default_2389")] pub author: String, - #[serde(default = "default_2385")] + #[serde(default = "default_2390")] pub actor: String, - #[serde(default = "default_2386")] + #[serde(default = "default_2391")] pub updated_at: Option, - #[serde(default = "default_2387")] + #[serde(default = "default_2392")] pub age_seconds: Integer, - #[serde(default = "default_2388")] + #[serde(default = "default_2393")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2389")] + #[serde(default = "default_2394")] pub briefs: Vec, - #[serde(default = "default_2390")] + #[serde(default = "default_2395")] pub rendered: String, } @@ -54798,25 +54892,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2394")] + #[serde(default = "default_2399")] pub events_in: Integer, - #[serde(default = "default_2395")] + #[serde(default = "default_2400")] pub windows: Integer, - #[serde(default = "default_2396")] + #[serde(default = "default_2401")] pub events_total: Integer, - #[serde(default = "default_2397")] + #[serde(default = "default_2402")] pub source_chars: Integer, - #[serde(default = "default_2398")] + #[serde(default = "default_2403")] pub brief_chars: Integer, - #[serde(default = "default_2399")] + #[serde(default = "default_2404")] pub compression_ratio: f64, - #[serde(default = "default_2400")] + #[serde(default = "default_2405")] pub dropped_ungrounded: Integer, - #[serde(default = "default_2401")] + #[serde(default = "default_2406")] pub tokens_in: Integer, - #[serde(default = "default_2402")] + #[serde(default = "default_2407")] pub tokens_out: Integer, - #[serde(default = "default_2403")] + #[serde(default = "default_2408")] pub llm_model: String, } @@ -54826,13 +54920,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2391")] + #[serde(default = "default_2396")] pub author: String, - #[serde(default = "default_2392")] + #[serde(default = "default_2397")] pub reason: String, - #[serde(default = "default_2393")] + #[serde(default = "default_2398")] pub rendered: String, - #[serde(default = "default_2404")] + #[serde(default = "default_2409")] pub stats: SessionBriefStats, } @@ -55577,39 +55671,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2405")] + #[serde(default = "default_2410")] pub reason: String, - #[serde(default = "default_2406")] + #[serde(default = "default_2411")] pub blocked_on: String, - #[serde(default = "default_2407")] + #[serde(default = "default_2412")] pub not_before: Option, - #[serde(default = "default_2408")] + #[serde(default = "default_2413")] pub resume_at: Option, - #[serde(default = "default_2409")] + #[serde(default = "default_2414")] pub deadline: Option, - #[serde(default = "default_2410")] + #[serde(default = "default_2415")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2411")] + #[serde(default = "default_2416")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2412")] + #[serde(default = "default_2417")] pub from_subject: String, - #[serde(default = "default_2413")] + #[serde(default = "default_2418")] pub origin: String, - #[serde(default = "default_2414")] + #[serde(default = "default_2419")] pub parent_task_id: Option, - #[serde(default = "default_2415")] + #[serde(default = "default_2420")] pub owner: String, - #[serde(default = "default_2416")] + #[serde(default = "default_2421")] pub attempt: Integer, - #[serde(default = "default_2417")] + #[serde(default = "default_2422")] pub fence: Integer, - #[serde(default = "default_2418")] + #[serde(default = "default_2423")] pub lease_until: Option, - #[serde(default = "default_2419")] + #[serde(default = "default_2424")] pub outcome: std::collections::HashMap, - #[serde(default = "default_2420")] + #[serde(default = "default_2425")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -55620,7 +55714,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2421")] + #[serde(default = "default_2426")] pub seq: Integer, } @@ -56021,10 +56115,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2422")] + #[serde(default = "default_2427")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2423")] + #[serde(default = "default_2428")] pub oldest: Option, } @@ -56111,7 +56205,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2424")] + #[serde(default = "default_2429")] pub next: String, } @@ -56450,7 +56544,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2425")] + #[serde(default = "default_2430")] pub task: Option, } @@ -56584,23 +56678,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2426")] + #[serde(default = "default_2431")] pub from_status: String, - #[serde(default = "default_2427")] + #[serde(default = "default_2432")] pub to_status: String, - #[serde(default = "default_2428")] + #[serde(default = "default_2433")] pub actor: String, - #[serde(default = "default_2429")] + #[serde(default = "default_2434")] pub agent: String, - #[serde(default = "default_2430")] + #[serde(default = "default_2435")] pub fence: Integer, - #[serde(default = "default_2431")] + #[serde(default = "default_2436")] pub version: Integer, - #[serde(default = "default_2432")] + #[serde(default = "default_2437")] pub reason: String, - #[serde(default = "default_2433")] + #[serde(default = "default_2438")] pub patch: std::collections::HashMap, - #[serde(default = "default_2434")] + #[serde(default = "default_2439")] pub note: String, pub ts: String, } @@ -56940,7 +57034,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2435")] + #[serde(default = "default_2440")] pub note: String, } @@ -57336,7 +57430,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2436")] + #[serde(default = "default_2441")] pub conflict: bool, } @@ -57699,19 +57793,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2437")] + #[serde(default = "default_2442")] pub intent: String, - #[serde(default = "default_2438")] + #[serde(default = "default_2443")] pub anchors: std::collections::HashMap, - #[serde(default = "default_2439")] + #[serde(default = "default_2444")] pub sections: Vec>, - #[serde(default = "default_2440")] + #[serde(default = "default_2445")] pub searched: Vec, - #[serde(default = "default_2441")] + #[serde(default = "default_2446")] pub lines: Vec, - #[serde(default = "default_2442")] + #[serde(default = "default_2447")] pub restricted: bool, - #[serde(default = "default_2443")] + #[serde(default = "default_2448")] pub verdict: String, } @@ -57807,17 +57901,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2444")] + #[serde(default = "default_2449")] pub tracker_namespace: String, - #[serde(default = "default_2445")] + #[serde(default = "default_2450")] pub tracker_namespaces: Vec, - #[serde(default = "default_2446")] + #[serde(default = "default_2451")] pub restricted: bool, - #[serde(default = "default_2447")] + #[serde(default = "default_2452")] pub kind: String, - #[serde(default = "default_2448")] + #[serde(default = "default_2453")] pub authorized: bool, - #[serde(default = "default_2449")] + #[serde(default = "default_2454")] pub templates: Vec, } @@ -57870,13 +57964,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2450")] + #[serde(default = "default_2455")] pub risk: std::collections::HashMap, - #[serde(default = "default_2451")] + #[serde(default = "default_2456")] pub open_issues: Vec>, - #[serde(default = "default_2452")] + #[serde(default = "default_2457")] pub known: bool, - #[serde(default = "default_2453")] + #[serde(default = "default_2458")] pub tracker_unavailable: bool, } @@ -57937,9 +58031,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2454")] + #[serde(default = "default_2459")] pub tables: Vec>, - #[serde(default = "default_2455")] + #[serde(default = "default_2460")] pub templates: std::collections::HashMap, } @@ -57992,66 +58086,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2466")] + #[serde(default = "default_2471")] pub status: String, - #[serde(default = "default_2467")] + #[serde(default = "default_2472")] pub reason: String, - #[serde(default = "default_2468")] + #[serde(default = "default_2473")] pub message: String, - #[serde(default = "default_2469")] + #[serde(default = "default_2474")] pub retried: bool, - #[serde(default = "default_2470")] + #[serde(default = "default_2475")] pub ms: Integer, - #[serde(default = "default_2471")] + #[serde(default = "default_2476")] pub cause: String, - #[serde(default = "default_2472")] + #[serde(default = "default_2477")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2456")] + #[serde(default = "default_2461")] pub verdict: String, - #[serde(default = "default_2457")] + #[serde(default = "default_2462")] pub items: Vec>, - #[serde(default = "default_2458")] + #[serde(default = "default_2463")] pub undecided: bool, - #[serde(default = "default_2459")] + #[serde(default = "default_2464")] pub epistemic: String, - #[serde(default = "default_2460")] + #[serde(default = "default_2465")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2461")] + #[serde(default = "default_2466")] pub judge: std::collections::HashMap, - #[serde(default = "default_2462")] + #[serde(default = "default_2467")] pub fit_at: String, - #[serde(default = "default_2463")] + #[serde(default = "default_2468")] pub fit: std::collections::HashMap, - #[serde(default = "default_2464")] + #[serde(default = "default_2469")] pub query: std::collections::HashMap, - #[serde(default = "default_2465")] + #[serde(default = "default_2470")] pub legs: std::collections::HashMap, - #[serde(default = "default_2473")] + #[serde(default = "default_2478")] pub leg_status: Vec, - #[serde(default = "default_2474")] + #[serde(default = "default_2479")] pub tracker_unavailable: bool, - #[serde(default = "default_2475")] + #[serde(default = "default_2480")] pub namespaces: Vec, - #[serde(default = "default_2476")] + #[serde(default = "default_2481")] pub by_namespace: std::collections::HashMap>, - #[serde(default = "default_2477")] + #[serde(default = "default_2482")] pub closest: Vec>, - #[serde(default = "default_2478")] + #[serde(default = "default_2483")] pub needs: Vec>, - #[serde(default = "default_2479")] + #[serde(default = "default_2484")] pub closest_note: String, - #[serde(default = "default_2480")] + #[serde(default = "default_2485")] pub nearest: Vec>, - #[serde(default = "default_2481")] + #[serde(default = "default_2486")] pub rerank: std::collections::HashMap, - #[serde(default = "default_2482")] + #[serde(default = "default_2487")] pub answer: String, - #[serde(default = "default_2483")] + #[serde(default = "default_2488")] pub related_prs: Vec>, } @@ -58258,17 +58352,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2484")] + #[serde(default = "default_2489")] pub known_flaky: bool, - #[serde(default = "default_2485")] + #[serde(default = "default_2490")] pub open_issues: Integer, - #[serde(default = "default_2486")] + #[serde(default = "default_2491")] pub issues: Vec>, - #[serde(default = "default_2487")] + #[serde(default = "default_2492")] pub verdict: String, - #[serde(default = "default_2488")] + #[serde(default = "default_2493")] pub tracker_unavailable: bool, - #[serde(default = "default_2489")] + #[serde(default = "default_2494")] pub signal: Option>, } @@ -58351,9 +58445,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2490")] + #[serde(default = "default_2495")] pub unknown: Vec, - #[serde(default = "default_2491")] + #[serde(default = "default_2496")] pub tracker_unavailable: bool, } @@ -58402,19 +58496,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2492")] + #[serde(default = "default_2497")] pub subject: std::collections::HashMap, - #[serde(default = "default_2493")] + #[serde(default = "default_2498")] pub verdict: String, - #[serde(default = "default_2494")] + #[serde(default = "default_2499")] pub items: Vec>, - #[serde(default = "default_2495")] + #[serde(default = "default_2500")] pub epistemic: String, - #[serde(default = "default_2496")] + #[serde(default = "default_2501")] pub record: std::collections::HashMap, - #[serde(default = "default_2497")] + #[serde(default = "default_2502")] pub computed_at: String, - #[serde(default = "default_2498")] + #[serde(default = "default_2503")] pub tracker_unavailable: bool, } @@ -58512,11 +58606,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2499")] + #[serde(default = "default_2504")] pub active_blockers: Integer, - #[serde(default = "default_2500")] + #[serde(default = "default_2505")] pub health: std::collections::HashMap, - #[serde(default = "default_2501")] + #[serde(default = "default_2506")] pub tracker_unavailable: bool, } @@ -58565,17 +58659,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2502")] + #[serde(default = "default_2507")] pub items: Vec>, - #[serde(default = "default_2503")] + #[serde(default = "default_2508")] pub query: std::collections::HashMap, - #[serde(default = "default_2504")] + #[serde(default = "default_2509")] pub legs: std::collections::HashMap, - #[serde(default = "default_2505")] + #[serde(default = "default_2510")] pub epistemic: String, - #[serde(default = "default_2506")] + #[serde(default = "default_2511")] pub tracker_unavailable: bool, - #[serde(default = "default_2507")] + #[serde(default = "default_2512")] pub namespaces: Vec, } @@ -58696,19 +58790,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2508")] + #[serde(default = "default_2513")] pub namespaces: Vec>, - #[serde(default = "default_2509")] + #[serde(default = "default_2514")] pub contract: std::collections::HashMap, - #[serde(default = "default_2510")] + #[serde(default = "default_2515")] pub roles: Vec, - #[serde(default = "default_2511")] + #[serde(default = "default_2516")] pub my_role: String, - #[serde(default = "default_2512")] + #[serde(default = "default_2517")] pub dry_run: bool, - #[serde(default = "default_2513")] + #[serde(default = "default_2518")] pub written: bool, - #[serde(default = "default_2514")] + #[serde(default = "default_2519")] pub view_templates: std::collections::HashMap, } @@ -58871,13 +58965,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2515")] + #[serde(default = "default_2520")] pub database: String, - #[serde(default = "default_2516")] + #[serde(default = "default_2521")] pub reachable: bool, - #[serde(default = "default_2517")] + #[serde(default = "default_2522")] pub contract: std::collections::HashMap, - #[serde(default = "default_2518")] + #[serde(default = "default_2523")] pub view_templates: std::collections::HashMap, } @@ -58917,11 +59011,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2519")] + #[serde(default = "default_2524")] pub tables: Vec>, - #[serde(default = "default_2520")] + #[serde(default = "default_2525")] pub roles: Vec, - #[serde(default = "default_2521")] + #[serde(default = "default_2526")] pub proposal: std::collections::HashMap, } @@ -59050,9 +59144,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2522")] + #[serde(default = "default_2527")] pub sources: Vec>, - #[serde(default = "default_2523")] + #[serde(default = "default_2528")] pub self_service: bool, } @@ -59105,9 +59199,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2524")] + #[serde(default = "default_2529")] pub deactivated: bool, - #[serde(default = "default_2525")] + #[serde(default = "default_2530")] pub namespaces_retired: Vec, } @@ -59148,9 +59242,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2526")] + #[serde(default = "default_2531")] pub contract: std::collections::HashMap, - #[serde(default = "default_2527")] + #[serde(default = "default_2532")] pub rotated_at: String, } @@ -59197,11 +59291,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2528")] + #[serde(default = "default_2533")] pub contract: std::collections::HashMap, - #[serde(default = "default_2529")] + #[serde(default = "default_2534")] pub dry_run: bool, - #[serde(default = "default_2530")] + #[serde(default = "default_2535")] pub written: bool, } @@ -59268,45 +59362,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2531")] + #[serde(default = "default_2536")] pub verdict: String, - #[serde(default = "default_2532")] + #[serde(default = "default_2537")] pub why: Vec, - #[serde(default = "default_2533")] + #[serde(default = "default_2538")] pub lower_bound: f64, - #[serde(default = "default_2534")] + #[serde(default = "default_2539")] pub window_days: Integer, - #[serde(default = "default_2535")] + #[serde(default = "default_2540")] pub since: String, - #[serde(default = "default_2536")] + #[serde(default = "default_2541")] pub features: std::collections::HashMap, - #[serde(default = "default_2537")] + #[serde(default = "default_2542")] pub infra: std::collections::HashMap, - #[serde(default = "default_2538")] + #[serde(default = "default_2543")] pub churn: std::collections::HashMap, - #[serde(default = "default_2539")] + #[serde(default = "default_2544")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2540")] + #[serde(default = "default_2545")] pub source: String, - #[serde(default = "default_2541")] + #[serde(default = "default_2546")] pub timings_ms: std::collections::HashMap, - #[serde(default = "default_2542")] + #[serde(default = "default_2547")] pub tracker_unavailable: bool, - #[serde(default = "default_2543")] + #[serde(default = "default_2548")] pub rollup: std::collections::HashMap, - #[serde(default = "default_2544")] + #[serde(default = "default_2549")] pub streak: std::collections::HashMap, - #[serde(default = "default_2545")] + #[serde(default = "default_2550")] pub smells: std::collections::HashMap, - #[serde(default = "default_2546")] + #[serde(default = "default_2551")] pub prior: std::collections::HashMap, - #[serde(default = "default_2547")] + #[serde(default = "default_2552")] pub unavailable_reason: String, - #[serde(default = "default_2548")] + #[serde(default = "default_2553")] pub candidates: Vec>, - #[serde(default = "default_2549")] + #[serde(default = "default_2554")] pub candidate_matches: Integer, - #[serde(default = "default_2550")] + #[serde(default = "default_2555")] pub resolved_from: String, } @@ -59410,9 +59504,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2551")] + #[serde(default = "default_2556")] pub recorded: bool, - #[serde(default = "default_2552")] + #[serde(default = "default_2557")] pub route: String, } @@ -59596,7 +59690,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2553")] + #[serde(default = "default_2558")] pub deliveries: Vec, } @@ -59718,14 +59812,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2554")] + #[serde(default = "default_2559")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2555")] + #[serde(default = "default_2560")] pub webhooks: Vec, } @@ -59907,7 +60001,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2556")] + #[serde(default = "default_2561")] pub fill_ratio: f64, } @@ -60131,15 +60225,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2557")] + #[serde(default = "default_2562")] pub content: String, - #[serde(default = "default_2558")] + #[serde(default = "default_2563")] pub char_limit: Integer, - #[serde(default = "default_2559")] + #[serde(default = "default_2564")] pub version: Integer, - #[serde(default = "default_2560")] + #[serde(default = "default_2565")] pub updated_at: Option, - #[serde(default = "default_2561")] + #[serde(default = "default_2566")] pub fill_ratio: f64, } @@ -60250,7 +60344,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2562")] + #[serde(default = "default_2567")] pub updated_at: Option, } @@ -60258,7 +60352,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2563")] + #[serde(default = "default_2568")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -64233,87 +64327,87 @@ fn default_1200() -> Integer { fn default_1201() -> KnowledgeRestoreOutputOriginal { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1202() -> Vec> { +fn default_1202() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1203() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1203() -> Vec { +fn default_1204() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1204() -> std::collections::HashMap { +fn default_1205() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1205() -> Integer { +fn default_1206() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1206() -> bool { +fn default_1207() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1207() -> Vec { +fn default_1208() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1208() -> Integer { +fn default_1209() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1209() -> bool { +fn default_1210() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1210() -> KnowledgeSourceProbe { +fn default_1211() -> KnowledgeSourceProbe { serde_json::from_str( "{\"documents\":0,\"more\":false,\"sample\":[],\"checked\":0,\"sampled\":false}", ) .expect("schema default") } -fn default_1211() -> bool { +fn default_1212() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1212() -> bool { +fn default_1213() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1213() -> Integer { +fn default_1214() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1214() -> bool { +fn default_1215() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1215() -> Vec { +fn default_1216() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1216() -> Integer { +fn default_1217() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1217() -> bool { +fn default_1218() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1218() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1219() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1220() -> String { - serde_json::from_str("\"shared\"").expect("schema default") + serde_json::from_str("\"\"").expect("schema default") } fn default_1221() -> String { - serde_json::from_str("\"namespace\"").expect("schema default") + serde_json::from_str("\"shared\"").expect("schema default") } fn default_1222() -> String { + serde_json::from_str("\"namespace\"").expect("schema default") +} +fn default_1223() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_1224() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1223() -> Vec> { +fn default_1225() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1224() -> Vec { +fn default_1226() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1225() -> std::collections::HashMap { +fn default_1227() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1226() -> String { - serde_json::from_str("\"\"").expect("schema default") -} -fn default_1227() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1228() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -64323,11 +64417,11 @@ fn default_1229() -> String { fn default_1230() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1231() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1231() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1232() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1232() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_1233() -> Integer { serde_json::from_str("0").expect("schema default") @@ -64335,14 +64429,14 @@ fn default_1233() -> Integer { fn default_1234() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1235() -> std::collections::HashMap { - serde_json::from_str("{}").expect("schema default") +fn default_1235() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1236() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1237() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1237() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") } fn default_1238() -> Integer { serde_json::from_str("0").expect("schema default") @@ -64353,3983 +64447,3998 @@ fn default_1239() -> String { fn default_1240() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1241() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1241() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_1242() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1243() -> String { +fn default_1243() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1244() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1245() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1244() -> KnowledgeSourceSync { +fn default_1246() -> KnowledgeSourceSync { serde_json::from_str("{\"requested_at\":\"\",\"last_synced_at\":\"\",\"status\":\"\",\"documents_seen\":0,\"changed\":0,\"removed\":0,\"unconverted\":0,\"unconverted_reasons\":{},\"skipped\":0,\"error\":\"\",\"pending_extract\":0,\"last_extracted_at\":\"\",\"extracted\":0,\"flagged_pinned\":0,\"unextracted\":0,\"extract_error\":\"\"}").expect("schema default") } -fn default_1245() -> String { +fn default_1247() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1246() -> String { +fn default_1248() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1247() -> String { +fn default_1249() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1248() -> Vec { +fn default_1250() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1249() -> String { +fn default_1251() -> String { serde_json::from_str("\"shared\"").expect("schema default") } -fn default_1250() -> String { +fn default_1252() -> String { serde_json::from_str("\"namespace\"").expect("schema default") } -fn default_1251() -> String { +fn default_1253() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_1254() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1252() -> Vec> { +fn default_1255() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1253() -> Vec { +fn default_1256() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1254() -> std::collections::HashMap { +fn default_1257() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1255() -> String { +fn default_1258() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1256() -> String { +fn default_1259() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1257() -> KnowledgeSourceSync { +fn default_1260() -> KnowledgeSourceSync { serde_json::from_str("{\"requested_at\":\"\",\"last_synced_at\":\"\",\"status\":\"\",\"documents_seen\":0,\"changed\":0,\"removed\":0,\"unconverted\":0,\"unconverted_reasons\":{},\"skipped\":0,\"error\":\"\",\"pending_extract\":0,\"last_extracted_at\":\"\",\"extracted\":0,\"flagged_pinned\":0,\"unextracted\":0,\"extract_error\":\"\"}").expect("schema default") } -fn default_1258() -> Vec { +fn default_1261() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1259() -> bool { +fn default_1262() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1260() -> bool { +fn default_1263() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1261() -> bool { +fn default_1264() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1262() -> String { +fn default_1265() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1263() -> std::collections::HashMap { +fn default_1266() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1264() -> String { +fn default_1267() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1265() -> Vec { +fn default_1268() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1266() -> bool { +fn default_1269() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1267() -> String { +fn default_1270() -> String { serde_json::from_str("\"disabled\"").expect("schema default") } -fn default_1268() -> String { +fn default_1271() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1269() -> String { +fn default_1272() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1270() -> String { +fn default_1273() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1271() -> String { +fn default_1274() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1272() -> String { +fn default_1275() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1273() -> String { +fn default_1276() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1274() -> Integer { +fn default_1277() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1275() -> f64 { +fn default_1278() -> f64 { serde_json::from_str("0").expect("schema default") } -fn default_1276() -> Integer { +fn default_1279() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1277() -> KnowledgeSourceProbe { +fn default_1280() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1281() -> KnowledgeSourceProbe { serde_json::from_str( "{\"documents\":0,\"more\":false,\"sample\":[],\"checked\":0,\"sampled\":false}", ) .expect("schema default") } -fn default_1278() -> String { +fn default_1282() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1279() -> bool { +fn default_1283() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1280() -> Vec> { +fn default_1284() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1285() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1281() -> Vec { +fn default_1286() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1282() -> std::collections::HashMap { +fn default_1287() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1283() -> Vec> { +fn default_1288() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1284() -> Vec> { +fn default_1289() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1285() -> KnowledgeSourceProbe { +fn default_1290() -> KnowledgeSourceProbe { serde_json::from_str( "{\"documents\":0,\"more\":false,\"sample\":[],\"checked\":0,\"sampled\":false}", ) .expect("schema default") } -fn default_1286() -> Vec { +fn default_1291() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1287() -> Integer { +fn default_1292() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1288() -> Option> { +fn default_1293() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_1289() -> Vec { +fn default_1294() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1290() -> Vec { +fn default_1295() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1291() -> bool { +fn default_1296() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1292() -> bool { +fn default_1297() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1293() -> String { +fn default_1298() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1294() -> String { +fn default_1299() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1295() -> Vec> { +fn default_1300() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1296() -> bool { +fn default_1301() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1297() -> Vec { +fn default_1302() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1298() -> Vec { +fn default_1303() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1299() -> String { +fn default_1304() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1300() -> String { +fn default_1305() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1301() -> String { +fn default_1306() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1302() -> Vec { +fn default_1307() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1303() -> Integer { +fn default_1308() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1304() -> String { +fn default_1309() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1305() -> Integer { +fn default_1310() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1306() -> String { +fn default_1311() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1307() -> String { +fn default_1312() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1308() -> Integer { +fn default_1313() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1309() -> Integer { +fn default_1314() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1310() -> String { +fn default_1315() -> String { serde_json::from_str("\"memory_supporters\"").expect("schema default") } -fn default_1311() -> String { +fn default_1316() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1312() -> String { +fn default_1317() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1313() -> Option { +fn default_1318() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1314() -> String { +fn default_1319() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1315() -> String { +fn default_1320() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1316() -> bool { +fn default_1321() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1317() -> bool { +fn default_1322() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1318() -> String { +fn default_1323() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1319() -> std::collections::HashMap { +fn default_1324() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1320() -> Vec { +fn default_1325() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1321() -> String { +fn default_1326() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1322() -> String { +fn default_1327() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1323() -> String { +fn default_1328() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1324() -> Vec { +fn default_1329() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1325() -> String { +fn default_1330() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1326() -> String { +fn default_1331() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1327() -> Vec { +fn default_1332() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1328() -> Vec { +fn default_1333() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1329() -> Vec { +fn default_1334() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1330() -> Vec { +fn default_1335() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1331() -> Integer { +fn default_1336() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1332() -> Vec { +fn default_1337() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1333() -> Vec { +fn default_1338() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1334() -> Vec { +fn default_1339() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1335() -> Integer { +fn default_1340() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1336() -> Vec { +fn default_1341() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1337() -> std::collections::HashMap { +fn default_1342() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1338() -> std::collections::HashMap { +fn default_1343() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1339() -> Integer { +fn default_1344() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1340() -> Integer { +fn default_1345() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1341() -> Integer { +fn default_1346() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1342() -> Integer { +fn default_1347() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1343() -> Integer { +fn default_1348() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1344() -> Integer { +fn default_1349() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1345() -> bool { +fn default_1350() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1346() -> String { +fn default_1351() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1347() -> String { +fn default_1352() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1348() -> String { +fn default_1353() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1349() -> String { +fn default_1354() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1350() -> Option { +fn default_1355() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1351() -> String { +fn default_1356() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1352() -> Vec { +fn default_1357() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1353() -> String { +fn default_1358() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1354() -> MemoryAskOutputSource { +fn default_1359() -> MemoryAskOutputSource { serde_json::from_str("\"synthesized\"").expect("schema default") } -fn default_1355() -> bool { +fn default_1360() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1356() -> String { +fn default_1361() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1357() -> Vec { +fn default_1362() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1358() -> Vec { +fn default_1363() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1359() -> Vec { +fn default_1364() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1360() -> String { +fn default_1365() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1361() -> String { +fn default_1366() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1362() -> MemoryAskOutputRouteTier { +fn default_1367() -> MemoryAskOutputRouteTier { serde_json::from_str("\"\"").expect("schema default") } -fn default_1363() -> String { +fn default_1368() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1364() -> Integer { +fn default_1369() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1365() -> Integer { +fn default_1370() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1366() -> bool { +fn default_1371() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1367() -> f64 { +fn default_1372() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1368() -> Option { +fn default_1373() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1369() -> Option { +fn default_1374() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1370() -> bool { +fn default_1375() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1371() -> String { +fn default_1376() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1372() -> Integer { +fn default_1377() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1373() -> Integer { +fn default_1378() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1374() -> Integer { +fn default_1379() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1375() -> Integer { +fn default_1380() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1376() -> String { +fn default_1381() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1377() -> Vec { +fn default_1382() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1378() -> Integer { +fn default_1383() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1379() -> MemoryAskOutputConsistency { +fn default_1384() -> MemoryAskOutputConsistency { serde_json::from_str("\"\"").expect("schema default") } -fn default_1380() -> f64 { +fn default_1385() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1381() -> String { +fn default_1386() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1382() -> Integer { +fn default_1387() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1383() -> Integer { +fn default_1388() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1384() -> String { +fn default_1389() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1385() -> String { +fn default_1390() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1386() -> String { +fn default_1391() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1387() -> String { +fn default_1392() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1388() -> MemoryAskOutputDepth { +fn default_1393() -> MemoryAskOutputDepth { serde_json::from_str("\"\"").expect("schema default") } -fn default_1389() -> bool { +fn default_1394() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1390() -> Vec { +fn default_1395() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1391() -> Integer { +fn default_1396() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1392() -> Integer { +fn default_1397() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1393() -> Integer { +fn default_1398() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1394() -> Vec { +fn default_1399() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1395() -> Integer { +fn default_1400() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1396() -> Integer { +fn default_1401() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1397() -> Integer { +fn default_1402() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1398() -> MemoryAskOutputGrounding { +fn default_1403() -> MemoryAskOutputGrounding { serde_json::from_str("\"\"").expect("schema default") } -fn default_1399() -> String { +fn default_1404() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1400() -> Vec { +fn default_1405() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1401() -> Integer { +fn default_1406() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1402() -> Integer { +fn default_1407() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1403() -> Integer { +fn default_1408() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1404() -> Integer { +fn default_1409() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1405() -> std::collections::HashMap { +fn default_1410() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1406() -> MemoryAskOutputDeepSelector { +fn default_1411() -> MemoryAskOutputDeepSelector { serde_json::from_str("\"\"").expect("schema default") } -fn default_1407() -> MemoryAskOutputDeepFirst { +fn default_1412() -> MemoryAskOutputDeepFirst { serde_json::from_str("\"\"").expect("schema default") } -fn default_1408() -> Integer { +fn default_1413() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1409() -> Integer { +fn default_1414() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1410() -> Integer { +fn default_1415() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1411() -> Integer { +fn default_1416() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1412() -> f64 { +fn default_1417() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1413() -> Integer { +fn default_1418() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1414() -> Integer { +fn default_1419() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1415() -> Integer { +fn default_1420() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1416() -> Integer { +fn default_1421() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1417() -> Integer { +fn default_1422() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1418() -> bool { +fn default_1423() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1419() -> String { +fn default_1424() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1420() -> String { +fn default_1425() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1421() -> String { +fn default_1426() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1422() -> String { +fn default_1427() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1423() -> String { +fn default_1428() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1424() -> String { +fn default_1429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1425() -> bool { +fn default_1430() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1426() -> String { +fn default_1431() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1427() -> Option { +fn default_1432() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1428() -> String { +fn default_1433() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1429() -> String { +fn default_1434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1430() -> Vec { +fn default_1435() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1431() -> Option { +fn default_1436() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1432() -> bool { +fn default_1437() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1433() -> String { +fn default_1438() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1434() -> String { +fn default_1439() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1435() -> Vec { +fn default_1440() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1436() -> String { +fn default_1441() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1437() -> Vec { +fn default_1442() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1438() -> String { +fn default_1443() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1439() -> String { +fn default_1444() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1440() -> Vec { +fn default_1445() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1441() -> Vec { +fn default_1446() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1442() -> Integer { +fn default_1447() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1443() -> Vec { +fn default_1448() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1444() -> Vec { +fn default_1449() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1445() -> String { +fn default_1450() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1446() -> String { +fn default_1451() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1447() -> bool { +fn default_1452() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1448() -> String { +fn default_1453() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1449() -> String { +fn default_1454() -> String { serde_json::from_str("\"fact\"").expect("schema default") } -fn default_1450() -> String { +fn default_1455() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1451() -> bool { +fn default_1456() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1452() -> String { +fn default_1457() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1453() -> String { +fn default_1458() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1454() -> String { +fn default_1459() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1455() -> Vec { +fn default_1460() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1456() -> Vec { +fn default_1461() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1457() -> Vec { +fn default_1462() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1458() -> std::collections::HashMap { +fn default_1463() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1459() -> Vec { +fn default_1464() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1460() -> Integer { +fn default_1465() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1461() -> Vec { +fn default_1466() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1462() -> Integer { +fn default_1467() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1463() -> Integer { +fn default_1468() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1464() -> Integer { +fn default_1469() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1465() -> Integer { +fn default_1470() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1466() -> Integer { +fn default_1471() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1467() -> Integer { +fn default_1472() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1468() -> Integer { +fn default_1473() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1469() -> String { +fn default_1474() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1470() -> String { +fn default_1475() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1471() -> String { +fn default_1476() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1472() -> String { +fn default_1477() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1473() -> bool { +fn default_1478() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1474() -> Integer { +fn default_1479() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1475() -> Integer { +fn default_1480() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1476() -> Integer { +fn default_1481() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1477() -> Integer { +fn default_1482() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1478() -> Integer { +fn default_1483() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1479() -> bool { +fn default_1484() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1480() -> Vec { +fn default_1485() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1481() -> String { +fn default_1486() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1482() -> String { +fn default_1487() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1483() -> Option { +fn default_1488() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1484() -> Vec { +fn default_1489() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1485() -> bool { +fn default_1490() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1486() -> bool { +fn default_1491() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1487() -> Vec { +fn default_1492() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1488() -> bool { +fn default_1493() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1489() -> Option { +fn default_1494() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1490() -> Vec { +fn default_1495() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1491() -> Option { +fn default_1496() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1492() -> Option { +fn default_1497() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1493() -> Vec { +fn default_1498() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1494() -> Integer { +fn default_1499() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1495() -> bool { +fn default_1500() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1496() -> String { +fn default_1501() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1497() -> Integer { +fn default_1502() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1498() -> Integer { +fn default_1503() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1499() -> std::collections::HashMap { +fn default_1504() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1500() -> String { +fn default_1505() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1501() -> f64 { +fn default_1506() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1502() -> bool { +fn default_1507() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1503() -> String { +fn default_1508() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1504() -> String { +fn default_1509() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1505() -> Integer { +fn default_1510() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1506() -> Integer { +fn default_1511() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1507() -> Option { +fn default_1512() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1508() -> Vec { +fn default_1513() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1509() -> Vec { +fn default_1514() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1510() -> Option { +fn default_1515() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1511() -> Option { +fn default_1516() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1512() -> Integer { +fn default_1517() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1513() -> bool { +fn default_1518() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1514() -> String { +fn default_1519() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1515() -> String { +fn default_1520() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1516() -> String { +fn default_1521() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1517() -> String { +fn default_1522() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1518() -> Option { +fn default_1523() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1519() -> String { +fn default_1524() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1520() -> Integer { +fn default_1525() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1521() -> Integer { +fn default_1526() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1522() -> String { +fn default_1527() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1523() -> Vec { +fn default_1528() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1524() -> bool { +fn default_1529() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1525() -> Integer { +fn default_1530() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1526() -> Integer { +fn default_1531() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1527() -> Integer { +fn default_1532() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1528() -> Integer { +fn default_1533() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1529() -> Integer { +fn default_1534() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1530() -> String { +fn default_1535() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1531() -> String { +fn default_1536() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1532() -> String { +fn default_1537() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1533() -> String { +fn default_1538() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1534() -> Vec { +fn default_1539() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1535() -> Integer { +fn default_1540() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1536() -> Integer { +fn default_1541() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1537() -> String { +fn default_1542() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1538() -> String { +fn default_1543() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1539() -> Vec { +fn default_1544() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1540() -> String { +fn default_1545() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1541() -> String { +fn default_1546() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1542() -> Vec { +fn default_1547() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1543() -> Vec { +fn default_1548() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1544() -> String { +fn default_1549() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1545() -> String { +fn default_1550() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1546() -> Vec { +fn default_1551() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1547() -> f64 { +fn default_1552() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1548() -> String { +fn default_1553() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1549() -> String { +fn default_1554() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1550() -> Vec { +fn default_1555() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1551() -> bool { +fn default_1556() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1552() -> String { +fn default_1557() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1553() -> Integer { +fn default_1558() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1554() -> Vec { +fn default_1559() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1555() -> Vec { +fn default_1560() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1556() -> Vec { +fn default_1561() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1557() -> Vec { +fn default_1562() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1558() -> Vec { +fn default_1563() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1559() -> Option { +fn default_1564() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1560() -> Option { +fn default_1565() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1561() -> Vec { +fn default_1566() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1562() -> Integer { +fn default_1567() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1563() -> Integer { +fn default_1568() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1564() -> Vec { +fn default_1569() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1565() -> Vec { +fn default_1570() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1566() -> Integer { +fn default_1571() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1567() -> Integer { +fn default_1572() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1568() -> bool { +fn default_1573() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1569() -> Vec { +fn default_1574() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1570() -> f64 { +fn default_1575() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1571() -> bool { +fn default_1576() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1572() -> String { +fn default_1577() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1573() -> String { +fn default_1578() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1574() -> Option { +fn default_1579() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1575() -> String { +fn default_1580() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1576() -> String { +fn default_1581() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1577() -> String { +fn default_1582() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1578() -> String { +fn default_1583() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1579() -> MemoryForFileHitSupersedesKind { +fn default_1584() -> MemoryForFileHitSupersedesKind { serde_json::from_str("\"\"").expect("schema default") } -fn default_1580() -> Vec { +fn default_1585() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1581() -> String { +fn default_1586() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1582() -> MemoryForFileHitVerification { +fn default_1587() -> MemoryForFileHitVerification { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1583() -> MemoryForFileHitCodeState { +fn default_1588() -> MemoryForFileHitCodeState { serde_json::from_str("\"\"").expect("schema default") } -fn default_1584() -> Vec { +fn default_1589() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1585() -> String { +fn default_1590() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1586() -> Integer { +fn default_1591() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1587() -> bool { +fn default_1592() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1588() -> String { +fn default_1593() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1589() -> String { +fn default_1594() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1590() -> String { +fn default_1595() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1591() -> String { +fn default_1596() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1592() -> String { +fn default_1597() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1593() -> String { +fn default_1598() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1594() -> Option { +fn default_1599() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1595() -> Value { +fn default_1600() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1596() -> Option { +fn default_1601() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1597() -> Option { +fn default_1602() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1598() -> Option { +fn default_1603() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1599() -> Option { +fn default_1604() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1600() -> Option { +fn default_1605() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1601() -> Option { +fn default_1606() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1602() -> bool { +fn default_1607() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1603() -> String { +fn default_1608() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1604() -> String { +fn default_1609() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1605() -> Option { +fn default_1610() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1606() -> String { +fn default_1611() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1607() -> String { +fn default_1612() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1608() -> String { +fn default_1613() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1609() -> String { +fn default_1614() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1610() -> String { +fn default_1615() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1611() -> String { +fn default_1616() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1612() -> Option { +fn default_1617() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1613() -> String { +fn default_1618() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1614() -> String { +fn default_1619() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1615() -> String { +fn default_1620() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1616() -> Integer { +fn default_1621() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1617() -> Vec { +fn default_1622() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1618() -> Integer { +fn default_1623() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1619() -> Option { +fn default_1624() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1620() -> Vec { +fn default_1625() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1621() -> std::collections::HashMap { +fn default_1626() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1622() -> Integer { +fn default_1627() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1623() -> f64 { +fn default_1628() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1624() -> Integer { +fn default_1629() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1625() -> Integer { +fn default_1630() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1626() -> Integer { +fn default_1631() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1627() -> Integer { +fn default_1632() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1628() -> Integer { +fn default_1633() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1629() -> MemoryHealthStaleness { +fn default_1634() -> MemoryHealthStaleness { serde_json::from_str("{\"by_age\":{},\"with_validity_end\":0,\"with_validity_end_share\":0.0,\"with_expiry\":0,\"expiring_7d\":0,\"pinned\":0,\"days_since_reinforced_p50\":0,\"days_since_reinforced_p90\":0}").expect("schema default") } -fn default_1630() -> Integer { +fn default_1635() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1631() -> Integer { +fn default_1636() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1632() -> f64 { +fn default_1637() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1633() -> MemoryHealthFootprint { +fn default_1638() -> MemoryHealthFootprint { serde_json::from_str("{\"value_chars\":0,\"value_tokens_est\":0,\"tokens_per_row_est\":0.0}") .expect("schema default") } -fn default_1634() -> String { +fn default_1639() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1635() -> Value { +fn default_1640() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1636() -> String { +fn default_1641() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1637() -> bool { +fn default_1642() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1638() -> Option { +fn default_1643() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1639() -> Option { +fn default_1644() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1640() -> Option { +fn default_1645() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1641() -> String { +fn default_1646() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1642() -> String { +fn default_1647() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1643() -> String { +fn default_1648() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1644() -> String { +fn default_1649() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1645() -> String { +fn default_1650() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1646() -> Option { +fn default_1651() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1647() -> String { +fn default_1652() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1648() -> Vec { +fn default_1653() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1649() -> Vec { +fn default_1654() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1650() -> Option { +fn default_1655() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1651() -> String { +fn default_1656() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1652() -> String { +fn default_1657() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1653() -> String { +fn default_1658() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1654() -> String { +fn default_1659() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1655() -> Option { +fn default_1660() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1656() -> Integer { +fn default_1661() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1657() -> Integer { +fn default_1662() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1658() -> Integer { +fn default_1663() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1659() -> Integer { +fn default_1664() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1660() -> MemoryImportResultReason { +fn default_1665() -> MemoryImportResultReason { serde_json::from_str("\"\"").expect("schema default") } -fn default_1661() -> String { +fn default_1666() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1662() -> MemoryImportResultNote { +fn default_1667() -> MemoryImportResultNote { serde_json::from_str("\"\"").expect("schema default") } -fn default_1663() -> bool { +fn default_1668() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1664() -> String { +fn default_1669() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1665() -> Option { +fn default_1670() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1666() -> Integer { +fn default_1671() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1667() -> Integer { +fn default_1672() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1668() -> Integer { +fn default_1673() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1669() -> String { +fn default_1674() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1670() -> Integer { +fn default_1675() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1671() -> Vec { +fn default_1676() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1672() -> Integer { +fn default_1677() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1673() -> Integer { +fn default_1678() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1674() -> Vec { +fn default_1679() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1675() -> Integer { +fn default_1680() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1676() -> Vec { +fn default_1681() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1677() -> Vec { +fn default_1682() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1678() -> Vec { +fn default_1683() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1679() -> Vec { +fn default_1684() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1680() -> Vec { +fn default_1685() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1681() -> Option { +fn default_1686() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1682() -> Option { +fn default_1687() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1683() -> String { +fn default_1688() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1684() -> Integer { +fn default_1689() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1685() -> String { +fn default_1690() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1686() -> Vec { +fn default_1691() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1687() -> bool { +fn default_1692() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1688() -> Vec { +fn default_1693() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1689() -> Option { +fn default_1694() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1690() -> Option { +fn default_1695() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1691() -> String { +fn default_1696() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1692() -> Integer { +fn default_1697() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1693() -> String { +fn default_1698() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1694() -> Integer { +fn default_1699() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1695() -> Option { +fn default_1700() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1696() -> String { +fn default_1701() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1697() -> String { +fn default_1702() -> String { serde_json::from_str("\"Each request that extracts memories from messages may send extraction instructions; no user, agent or session setting stores them.\"").expect("schema default") } -fn default_1698() -> Vec { +fn default_1703() -> Vec { serde_json::from_str("[\"memory.set_from_messages\",\"extraction_instructions\"]") .expect("schema default") } -fn default_1699() -> Vec { +fn default_1704() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1700() -> bool { +fn default_1705() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1701() -> String { +fn default_1706() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1702() -> String { +fn default_1707() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1703() -> Option { +fn default_1708() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1704() -> String { +fn default_1709() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1705() -> String { +fn default_1710() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1706() -> String { +fn default_1711() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1707() -> MemoryLineageOutputMechanism { +fn default_1712() -> MemoryLineageOutputMechanism { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_1708() -> Vec { +fn default_1713() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1709() -> String { +fn default_1714() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1710() -> String { +fn default_1715() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1711() -> Option { +fn default_1716() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1712() -> Vec { +fn default_1717() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1713() -> f64 { +fn default_1718() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1714() -> bool { +fn default_1719() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1715() -> bool { +fn default_1720() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1716() -> Integer { +fn default_1721() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1717() -> Integer { +fn default_1722() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1718() -> String { +fn default_1723() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1719() -> bool { +fn default_1724() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1720() -> Integer { +fn default_1725() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1721() -> String { +fn default_1726() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1722() -> String { +fn default_1727() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1723() -> String { +fn default_1728() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1724() -> Option { +fn default_1729() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1725() -> String { +fn default_1730() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1726() -> Option { +fn default_1731() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1727() -> String { +fn default_1732() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1728() -> String { +fn default_1733() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1729() -> String { +fn default_1734() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1730() -> Integer { +fn default_1735() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1731() -> String { +fn default_1736() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1732() -> Vec { +fn default_1737() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1733() -> bool { +fn default_1738() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1734() -> String { +fn default_1739() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1735() -> String { +fn default_1740() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1736() -> String { +fn default_1741() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1737() -> bool { +fn default_1742() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1738() -> std::collections::HashMap { +fn default_1743() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1739() -> String { +fn default_1744() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1740() -> String { +fn default_1745() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1741() -> Integer { +fn default_1746() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1742() -> Integer { +fn default_1747() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1743() -> Vec { +fn default_1748() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1744() -> Integer { +fn default_1749() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1745() -> Integer { +fn default_1750() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1746() -> Vec { +fn default_1751() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1747() -> String { +fn default_1752() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1748() -> Integer { +fn default_1753() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1749() -> String { +fn default_1754() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1750() -> Vec { +fn default_1755() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1751() -> Integer { +fn default_1756() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1752() -> Option { +fn default_1757() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1753() -> Vec { +fn default_1758() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1754() -> Integer { +fn default_1759() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1755() -> String { +fn default_1760() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1756() -> String { +fn default_1761() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1757() -> Vec { +fn default_1762() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1758() -> String { +fn default_1763() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1759() -> String { +fn default_1764() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1760() -> String { +fn default_1765() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1761() -> String { +fn default_1766() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1762() -> String { +fn default_1767() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1763() -> Vec { +fn default_1768() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1764() -> String { +fn default_1769() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1765() -> Integer { +fn default_1770() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1766() -> Integer { +fn default_1771() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1767() -> String { +fn default_1772() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1768() -> Integer { +fn default_1773() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1769() -> Integer { +fn default_1774() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1770() -> MemoryProposalReady { +fn default_1775() -> MemoryProposalReady { serde_json::from_str("\"\"").expect("schema default") } -fn default_1771() -> Vec { +fn default_1776() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1772() -> Vec { +fn default_1777() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1773() -> Integer { +fn default_1778() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1774() -> ProposalPolicyMode { +fn default_1779() -> ProposalPolicyMode { serde_json::from_str("\"manual\"").expect("schema default") } -fn default_1775() -> Integer { +fn default_1780() -> Integer { serde_json::from_str("2").expect("schema default") } -fn default_1776() -> Integer { +fn default_1781() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1777() -> Integer { +fn default_1782() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1778() -> ProposalPolicy { +fn default_1783() -> ProposalPolicy { serde_json::from_str( "{\"mode\":\"manual\",\"min_passes\":2,\"max_fails\":0,\"reject_after_fails\":0}", ) .expect("schema default") } -fn default_1779() -> String { +fn default_1784() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1780() -> String { +fn default_1785() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1781() -> String { +fn default_1786() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1782() -> String { +fn default_1787() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1783() -> String { +fn default_1788() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1784() -> String { +fn default_1789() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1785() -> bool { +fn default_1790() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1786() -> String { +fn default_1791() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1787() -> String { +fn default_1792() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1788() -> String { +fn default_1793() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1789() -> String { +fn default_1794() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1790() -> String { +fn default_1795() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1791() -> String { +fn default_1796() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1792() -> String { +fn default_1797() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1793() -> String { +fn default_1798() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1794() -> String { +fn default_1799() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1795() -> Vec { +fn default_1800() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1796() -> f64 { +fn default_1801() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1797() -> String { +fn default_1802() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1798() -> String { +fn default_1803() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1799() -> Vec { +fn default_1804() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1800() -> String { +fn default_1805() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1801() -> String { +fn default_1806() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1802() -> String { +fn default_1807() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1803() -> String { +fn default_1808() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1804() -> bool { +fn default_1809() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1805() -> Integer { +fn default_1810() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1806() -> Integer { +fn default_1811() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1807() -> Integer { +fn default_1812() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1808() -> bool { +fn default_1813() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1809() -> String { +fn default_1814() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1810() -> Integer { +fn default_1815() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_1811() -> MemoryRecallOutputOrder { +fn default_1816() -> MemoryRecallOutputOrder { serde_json::from_str("\"recent\"").expect("schema default") } -fn default_1812() -> Vec { +fn default_1817() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1813() -> Integer { +fn default_1818() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1814() -> Value { +fn default_1819() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1815() -> Value { +fn default_1820() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1816() -> String { +fn default_1821() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1817() -> String { +fn default_1822() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1818() -> Option { +fn default_1823() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1819() -> Option { +fn default_1824() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1820() -> bool { +fn default_1825() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1821() -> String { +fn default_1826() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1822() -> String { +fn default_1827() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1823() -> std::collections::HashMap { +fn default_1828() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1824() -> std::collections::HashMap { +fn default_1829() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1825() -> MemoryRecordRowStatus { +fn default_1830() -> MemoryRecordRowStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1826() -> Option { +fn default_1831() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1827() -> Option { +fn default_1832() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1828() -> bool { +fn default_1833() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1829() -> String { +fn default_1834() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1830() -> MemoryRecordWriteOutputKeySource { +fn default_1835() -> MemoryRecordWriteOutputKeySource { serde_json::from_str("\"anonymous\"").expect("schema default") } -fn default_1831() -> std::collections::HashMap { +fn default_1836() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1832() -> String { +fn default_1837() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1833() -> Integer { +fn default_1838() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1834() -> bool { +fn default_1839() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1835() -> Option { +fn default_1840() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1836() -> Integer { +fn default_1841() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1837() -> Integer { +fn default_1842() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1838() -> Option { +fn default_1843() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1839() -> String { +fn default_1844() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1840() -> Integer { +fn default_1845() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1841() -> Integer { +fn default_1846() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1842() -> bool { +fn default_1847() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1843() -> Vec { +fn default_1848() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1844() -> Option { +fn default_1849() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1845() -> Option { +fn default_1850() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1846() -> bool { +fn default_1851() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1847() -> bool { +fn default_1852() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1848() -> String { +fn default_1853() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1849() -> f64 { +fn default_1854() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1850() -> String { +fn default_1855() -> String { serde_json::from_str("\"fact\"").expect("schema default") } -fn default_1851() -> String { +fn default_1856() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1852() -> std::collections::HashMap { +fn default_1857() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1853() -> bool { +fn default_1858() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1854() -> Integer { +fn default_1859() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1855() -> String { +fn default_1860() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1856() -> Vec { +fn default_1861() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1857() -> Vec { +fn default_1862() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1858() -> Integer { +fn default_1863() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1859() -> Integer { +fn default_1864() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1860() -> String { +fn default_1865() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1861() -> String { +fn default_1866() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1862() -> Integer { +fn default_1867() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_1863() -> Integer { +fn default_1868() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1864() -> Integer { +fn default_1869() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1865() -> Vec { +fn default_1870() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1866() -> Integer { +fn default_1871() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1867() -> Integer { +fn default_1872() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1868() -> Integer { +fn default_1873() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1869() -> Integer { +fn default_1874() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1870() -> Vec { +fn default_1875() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1871() -> String { +fn default_1876() -> String { serde_json::from_str("\"whole\"").expect("schema default") } -fn default_1872() -> Integer { +fn default_1877() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1873() -> Vec { +fn default_1878() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1874() -> Vec { +fn default_1879() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1875() -> Integer { +fn default_1880() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1876() -> Vec { +fn default_1881() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1877() -> Integer { +fn default_1882() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1878() -> Vec { +fn default_1883() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1879() -> Vec { +fn default_1884() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1880() -> bool { +fn default_1885() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1881() -> String { +fn default_1886() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1882() -> String { +fn default_1887() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1883() -> std::collections::HashMap { +fn default_1888() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1884() -> String { +fn default_1889() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1885() -> bool { +fn default_1890() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1886() -> Vec { +fn default_1891() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1887() -> Integer { +fn default_1892() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1888() -> Integer { +fn default_1893() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1889() -> String { +fn default_1894() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1890() -> String { +fn default_1895() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1891() -> String { +fn default_1896() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1892() -> bool { +fn default_1897() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1893() -> Integer { +fn default_1898() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1894() -> Option { +fn default_1899() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1895() -> String { +fn default_1900() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1896() -> String { +fn default_1901() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1897() -> String { +fn default_1902() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1898() -> Vec { +fn default_1903() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1899() -> Integer { +fn default_1904() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1900() -> Integer { +fn default_1905() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1901() -> Integer { +fn default_1906() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1902() -> Integer { +fn default_1907() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1903() -> Integer { +fn default_1908() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1904() -> Integer { +fn default_1909() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1905() -> bool { +fn default_1910() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1906() -> Vec> { +fn default_1911() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1907() -> Vec { +fn default_1912() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1908() -> Option { +fn default_1913() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1909() -> String { +fn default_1914() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1910() -> Integer { +fn default_1915() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1911() -> Option { +fn default_1916() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1912() -> Option { +fn default_1917() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1913() -> Option { +fn default_1918() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1914() -> Option { +fn default_1919() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1915() -> Vec { +fn default_1920() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1916() -> Integer { +fn default_1921() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1917() -> String { +fn default_1922() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1918() -> String { +fn default_1923() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1919() -> Option { +fn default_1924() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1920() -> String { +fn default_1925() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1921() -> String { +fn default_1926() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1922() -> String { +fn default_1927() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1923() -> String { +fn default_1928() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1924() -> Option { +fn default_1929() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1925() -> String { +fn default_1930() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1926() -> String { +fn default_1931() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1927() -> Integer { +fn default_1932() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1928() -> String { +fn default_1933() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1929() -> String { +fn default_1934() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1930() -> String { +fn default_1935() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1931() -> String { +fn default_1936() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1932() -> String { +fn default_1937() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1933() -> Integer { +fn default_1938() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1934() -> String { +fn default_1939() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1935() -> Vec { +fn default_1940() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1936() -> String { +fn default_1941() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1937() -> Integer { +fn default_1942() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1938() -> String { +fn default_1943() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1939() -> Integer { +fn default_1944() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1940() -> String { +fn default_1945() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1941() -> String { +fn default_1946() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1942() -> Integer { +fn default_1947() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1943() -> String { +fn default_1948() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1944() -> bool { +fn default_1949() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1945() -> String { +fn default_1950() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1946() -> String { +fn default_1951() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1947() -> String { +fn default_1952() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1948() -> String { +fn default_1953() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1949() -> Option { +fn default_1954() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1950() -> String { +fn default_1955() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1951() -> Integer { +fn default_1956() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1952() -> String { +fn default_1957() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1953() -> String { +fn default_1958() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1954() -> String { +fn default_1959() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1955() -> bool { +fn default_1960() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1956() -> Vec { +fn default_1961() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1957() -> std::collections::HashMap { +fn default_1962() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1958() -> String { +fn default_1963() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1959() -> Vec { +fn default_1964() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1960() -> std::collections::HashMap { +fn default_1965() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1961() -> Integer { +fn default_1966() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1962() -> Option { +fn default_1967() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1963() -> String { +fn default_1968() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1964() -> bool { +fn default_1969() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1965() -> Vec { +fn default_1970() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1966() -> Vec { +fn default_1971() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1967() -> std::collections::HashMap { +fn default_1972() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1968() -> Option { +fn default_1973() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1969() -> Vec { +fn default_1974() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1970() -> Integer { +fn default_1975() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1971() -> Integer { +fn default_1976() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1972() -> Vec { +fn default_1977() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1973() -> Option { +fn default_1978() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1974() -> Vec { +fn default_1979() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1975() -> Option { +fn default_1980() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1976() -> Option { +fn default_1981() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1977() -> Vec { +fn default_1982() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1978() -> bool { +fn default_1983() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1979() -> Vec { +fn default_1984() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1980() -> bool { +fn default_1985() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1981() -> Integer { +fn default_1986() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1982() -> Integer { +fn default_1987() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1983() -> Integer { +fn default_1988() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1984() -> Integer { +fn default_1989() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1985() -> Integer { +fn default_1990() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1986() -> Integer { +fn default_1991() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1987() -> Integer { +fn default_1992() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1988() -> Integer { +fn default_1993() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1989() -> Integer { +fn default_1994() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1990() -> f64 { +fn default_1995() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1991() -> Integer { +fn default_1996() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1992() -> Integer { +fn default_1997() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1993() -> Integer { +fn default_1998() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1994() -> Integer { +fn default_1999() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1995() -> Option { +fn default_2000() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1996() -> Option { +fn default_2001() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1997() -> Vec { +fn default_2002() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1998() -> String { +fn default_2003() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1999() -> String { +fn default_2004() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2000() -> Integer { +fn default_2005() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2001() -> Vec> { +fn default_2006() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2002() -> Vec { +fn default_2007() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2003() -> String { +fn default_2008() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2004() -> bool { +fn default_2009() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2005() -> String { +fn default_2010() -> String { serde_json::from_str("\"approval\"").expect("schema default") } -fn default_2006() -> String { +fn default_2011() -> String { serde_json::from_str("\"public\"").expect("schema default") } -fn default_2007() -> BrowseEntryMyStatus { +fn default_2012() -> BrowseEntryMyStatus { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2008() -> String { +fn default_2013() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2009() -> String { +fn default_2014() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2010() -> String { +fn default_2015() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2011() -> Integer { +fn default_2016() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2012() -> String { +fn default_2017() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2013() -> Option { +fn default_2018() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2014() -> Option { +fn default_2019() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2015() -> Vec { +fn default_2020() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2016() -> Option { +fn default_2021() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2017() -> Option { +fn default_2022() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2018() -> Option { +fn default_2023() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2019() -> Option> { +fn default_2024() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2020() -> Option { +fn default_2025() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2021() -> Option { +fn default_2026() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2022() -> Option { +fn default_2027() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2023() -> Option { +fn default_2028() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2024() -> Option { +fn default_2029() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2025() -> Option { +fn default_2030() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2026() -> Option { +fn default_2031() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2027() -> Option { +fn default_2032() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2028() -> Option { +fn default_2033() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2029() -> Option { +fn default_2034() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2030() -> Option { +fn default_2035() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2031() -> Option { +fn default_2036() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2032() -> Option { +fn default_2037() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2033() -> Option { +fn default_2038() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2034() -> Option { +fn default_2039() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2035() -> Option> { +fn default_2040() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2036() -> Option { +fn default_2041() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2037() -> Option { +fn default_2042() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2038() -> Option { +fn default_2043() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2039() -> Option { +fn default_2044() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2040() -> Option { +fn default_2045() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2041() -> Option>> { +fn default_2046() -> Option>> { serde_json::from_str("null").expect("schema default") } -fn default_2042() -> Option { +fn default_2047() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2043() -> Option { +fn default_2048() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2044() -> Option { +fn default_2049() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2045() -> Option { +fn default_2050() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2046() -> Option { +fn default_2051() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2047() -> Integer { +fn default_2052() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2048() -> String { +fn default_2053() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2049() -> String { +fn default_2054() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2050() -> String { +fn default_2055() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2051() -> String { +fn default_2056() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2052() -> Option { +fn default_2057() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2053() -> bool { +fn default_2058() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2054() -> Integer { +fn default_2059() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2055() -> String { +fn default_2060() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2056() -> String { +fn default_2061() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2057() -> String { +fn default_2062() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2058() -> String { +fn default_2063() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2059() -> Option { +fn default_2064() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2060() -> Option { +fn default_2065() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2061() -> String { +fn default_2066() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2062() -> Vec { +fn default_2067() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2063() -> String { +fn default_2068() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2064() -> String { +fn default_2069() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2065() -> Option { +fn default_2070() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2066() -> Vec { +fn default_2071() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2067() -> Option { +fn default_2072() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2068() -> String { +fn default_2073() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2069() -> bool { +fn default_2074() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2070() -> f64 { +fn default_2075() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2071() -> f64 { +fn default_2076() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2072() -> String { +fn default_2077() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2073() -> Option { +fn default_2078() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2074() -> Integer { +fn default_2079() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2075() -> Integer { +fn default_2080() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2076() -> NamespaceEntryVisibility { +fn default_2081() -> NamespaceEntryVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2077() -> String { +fn default_2082() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2078() -> Option { +fn default_2083() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2079() -> Option { +fn default_2084() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2080() -> Vec { +fn default_2085() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2081() -> MineEntryVisibility { +fn default_2086() -> MineEntryVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2082() -> String { +fn default_2087() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2083() -> String { +fn default_2088() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2084() -> String { +fn default_2089() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2085() -> Option { +fn default_2090() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2086() -> bool { +fn default_2091() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2087() -> bool { +fn default_2092() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2088() -> String { +fn default_2093() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2089() -> NamespaceRegisterOutputVisibility { +fn default_2094() -> NamespaceRegisterOutputVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2090() -> bool { +fn default_2095() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2091() -> Integer { +fn default_2096() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2092() -> Integer { +fn default_2097() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2093() -> bool { +fn default_2098() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2094() -> Vec> { +fn default_2099() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2095() -> Option { +fn default_2100() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2096() -> Option { +fn default_2101() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2097() -> Vec { +fn default_2102() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2098() -> Integer { +fn default_2103() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2099() -> String { +fn default_2104() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2100() -> String { +fn default_2105() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2101() -> String { +fn default_2106() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2102() -> String { +fn default_2107() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2103() -> String { +fn default_2108() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2104() -> Option { +fn default_2109() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2105() -> String { +fn default_2110() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2106() -> String { +fn default_2111() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2107() -> String { +fn default_2112() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2108() -> Vec { +fn default_2113() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2109() -> Option { +fn default_2114() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2110() -> Option { +fn default_2115() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2111() -> Option { +fn default_2116() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2112() -> Option { +fn default_2117() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2113() -> String { +fn default_2118() -> String { serde_json::from_str("\"{}\"").expect("schema default") } -fn default_2114() -> NamespaceSnapshotOutputSnapshotMemoryRowStatus { +fn default_2119() -> NamespaceSnapshotOutputSnapshotMemoryRowStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2115() -> Option { +fn default_2120() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2116() -> Vec { +fn default_2121() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2117() -> String { +fn default_2122() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2118() -> Integer { +fn default_2123() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2119() -> Integer { +fn default_2124() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2120() -> Option { +fn default_2125() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2121() -> String { +fn default_2126() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2122() -> String { +fn default_2127() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2123() -> String { +fn default_2128() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2124() -> String { +fn default_2129() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2125() -> Option { +fn default_2130() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2126() -> f64 { +fn default_2131() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2127() -> Option { +fn default_2132() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2128() -> Option { +fn default_2133() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2129() -> Integer { +fn default_2134() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2130() -> Option { +fn default_2135() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2131() -> Option { +fn default_2136() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2132() -> String { +fn default_2137() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2133() -> Option { +fn default_2138() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2134() -> String { +fn default_2139() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2135() -> String { +fn default_2140() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2136() -> String { +fn default_2141() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2137() -> Option { +fn default_2142() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2138() -> String { +fn default_2143() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2139() -> Option { +fn default_2144() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2140() -> String { +fn default_2145() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2141() -> String { +fn default_2146() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2142() -> Vec { +fn default_2147() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2143() -> Vec { +fn default_2148() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2144() -> Option { +fn default_2149() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2145() -> Integer { +fn default_2150() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2146() -> String { +fn default_2151() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2147() -> Vec { +fn default_2152() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2148() -> Vec { +fn default_2153() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2149() -> String { +fn default_2154() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2150() -> Option { +fn default_2155() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2151() -> Vec { +fn default_2156() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2152() -> Integer { +fn default_2157() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2153() -> Vec { +fn default_2158() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2154() -> Option { +fn default_2159() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2155() -> Vec { +fn default_2160() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2156() -> Vec { +fn default_2161() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2157() -> Option { +fn default_2162() -> Option { serde_json::from_str("0").expect("schema default") } -fn default_2158() -> TuneProposalEffect { +fn default_2163() -> TuneProposalEffect { serde_json::from_str("\"future\"").expect("schema default") } -fn default_2159() -> TuneApplyVia { +fn default_2164() -> TuneApplyVia { serde_json::from_str("\"op\"").expect("schema default") } -fn default_2160() -> bool { +fn default_2165() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2161() -> Vec { +fn default_2166() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2162() -> Option { +fn default_2167() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2163() -> Option { +fn default_2168() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2164() -> String { +fn default_2169() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2165() -> Vec { +fn default_2170() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2166() -> Vec { +fn default_2171() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2167() -> Option { +fn default_2172() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2168() -> Option { +fn default_2173() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2169() -> Option { +fn default_2174() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2170() -> String { +fn default_2175() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2171() -> Option { +fn default_2176() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2172() -> Option { +fn default_2177() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2173() -> Option { +fn default_2178() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2174() -> Vec { +fn default_2179() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2175() -> bool { +fn default_2180() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2176() -> Option { +fn default_2181() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2177() -> Option { +fn default_2182() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2178() -> Vec { +fn default_2183() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2179() -> String { +fn default_2184() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2180() -> String { +fn default_2185() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2181() -> Vec> { +fn default_2186() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2182() -> std::collections::HashMap { +fn default_2187() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2183() -> Vec { +fn default_2188() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2184() -> Integer { +fn default_2189() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2185() -> Integer { +fn default_2190() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2186() -> String { +fn default_2191() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2187() -> String { +fn default_2192() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2188() -> String { +fn default_2193() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2189() -> Vec { +fn default_2194() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2190() -> Vec { +fn default_2195() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2191() -> String { +fn default_2196() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2192() -> String { +fn default_2197() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2193() -> bool { +fn default_2198() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2194() -> Integer { +fn default_2199() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2195() -> String { +fn default_2200() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2196() -> String { +fn default_2201() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2197() -> String { +fn default_2202() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2198() -> String { +fn default_2203() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2199() -> Vec { +fn default_2204() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2200() -> String { +fn default_2205() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2201() -> String { +fn default_2206() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2202() -> std::collections::HashMap { +fn default_2207() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2203() -> String { +fn default_2208() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2204() -> Option { +fn default_2209() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2205() -> Option { +fn default_2210() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2206() -> bool { +fn default_2211() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2207() -> String { +fn default_2212() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2208() -> String { +fn default_2213() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2209() -> Vec { +fn default_2214() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2210() -> Integer { +fn default_2215() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2211() -> String { +fn default_2216() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2212() -> String { +fn default_2217() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2213() -> Option { +fn default_2218() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2214() -> bool { +fn default_2219() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2215() -> String { +fn default_2220() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2216() -> bool { +fn default_2221() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2217() -> String { +fn default_2222() -> String { serde_json::from_str("\"inherit\"").expect("schema default") } -fn default_2218() -> Option { +fn default_2223() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2219() -> Option { +fn default_2224() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2220() -> bool { +fn default_2225() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2221() -> Vec { +fn default_2226() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2222() -> Integer { +fn default_2227() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2223() -> ProcedureEvolveOutputGate { +fn default_2228() -> ProcedureEvolveOutputGate { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2224() -> String { +fn default_2229() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2225() -> f64 { +fn default_2230() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2226() -> std::collections::HashMap { +fn default_2231() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2227() -> std::collections::HashMap { +fn default_2232() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2228() -> std::collections::HashMap { +fn default_2233() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2229() -> std::collections::HashMap { +fn default_2234() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2230() -> String { +fn default_2235() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2231() -> Vec { +fn default_2236() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2232() -> Vec { +fn default_2237() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2233() -> Vec { +fn default_2238() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2234() -> std::collections::HashMap { +fn default_2239() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2235() -> Integer { +fn default_2240() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2236() -> bool { +fn default_2241() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2237() -> std::collections::HashMap { +fn default_2242() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2238() -> Vec { +fn default_2243() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2239() -> std::collections::HashMap { +fn default_2244() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2240() -> String { +fn default_2245() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2241() -> ProcedureLocateOutputStatus { +fn default_2246() -> ProcedureLocateOutputStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2242() -> Option> { +fn default_2247() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2243() -> Vec>> { +fn default_2248() -> Vec>> { serde_json::from_str("[]").expect("schema default") } -fn default_2244() -> Vec { +fn default_2249() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2245() -> Vec { +fn default_2250() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2246() -> std::collections::HashMap { +fn default_2251() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2247() -> bool { +fn default_2252() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2248() -> Vec { +fn default_2253() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2249() -> Vec> { +fn default_2254() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2250() -> String { +fn default_2255() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2251() -> std::collections::HashMap { +fn default_2256() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2252() -> std::collections::HashMap { +fn default_2257() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2253() -> Vec { +fn default_2258() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2254() -> std::collections::HashMap { +fn default_2259() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2255() -> Option> { +fn default_2260() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2256() -> bool { +fn default_2261() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2257() -> std::collections::HashMap { +fn default_2262() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2258() -> ProcedureMatchStatus { +fn default_2263() -> ProcedureMatchStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2259() -> Option> { +fn default_2264() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2260() -> Vec { +fn default_2265() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2261() -> Integer { +fn default_2266() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2262() -> Vec> { +fn default_2267() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2263() -> f64 { +fn default_2268() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2264() -> f64 { +fn default_2269() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2265() -> f64 { +fn default_2270() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2266() -> Option { +fn default_2271() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2267() -> std::collections::HashMap { +fn default_2272() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2268() -> std::collections::HashMap> { +fn default_2273() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2269() -> String { +fn default_2274() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2270() -> Integer { +fn default_2275() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2271() -> String { +fn default_2276() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2272() -> f64 { +fn default_2277() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2273() -> Vec { +fn default_2278() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2274() -> ProcedureReviseOutputOutcome { +fn default_2279() -> ProcedureReviseOutputOutcome { serde_json::from_str("\"opened\"").expect("schema default") } -fn default_2275() -> Vec { +fn default_2280() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2276() -> Vec { +fn default_2281() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2277() -> String { +fn default_2282() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2278() -> String { +fn default_2283() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2279() -> String { +fn default_2284() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2280() -> String { +fn default_2285() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2281() -> Option { +fn default_2286() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2282() -> Integer { +fn default_2287() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2283() -> Vec { +fn default_2288() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2284() -> std::collections::HashMap { +fn default_2289() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2285() -> Option { +fn default_2290() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2286() -> String { +fn default_2291() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2287() -> Integer { +fn default_2292() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2288() -> String { +fn default_2293() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2289() -> String { +fn default_2294() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2290() -> std::collections::HashMap { +fn default_2295() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2291() -> String { +fn default_2296() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2292() -> String { +fn default_2297() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2293() -> Option { +fn default_2298() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2294() -> RunBeginOutputStatus { +fn default_2299() -> RunBeginOutputStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2295() -> String { +fn default_2300() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2296() -> Integer { +fn default_2301() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2297() -> Integer { +fn default_2302() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2298() -> Integer { +fn default_2303() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2299() -> Vec { +fn default_2304() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2300() -> Integer { +fn default_2305() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2301() -> Integer { +fn default_2306() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2302() -> Integer { +fn default_2307() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2303() -> String { +fn default_2308() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2304() -> String { +fn default_2309() -> String { serde_json::from_str("\"keep\"").expect("schema default") } -fn default_2305() -> Integer { +fn default_2310() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2306() -> Integer { +fn default_2311() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2307() -> Integer { +fn default_2312() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2308() -> Option { +fn default_2313() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2309() -> Integer { +fn default_2314() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2310() -> Vec { +fn default_2315() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2311() -> Vec { +fn default_2316() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2312() -> Integer { +fn default_2317() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2313() -> Integer { +fn default_2318() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2314() -> Integer { +fn default_2319() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2315() -> f64 { +fn default_2320() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2316() -> Integer { +fn default_2321() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2317() -> Vec { +fn default_2322() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2318() -> Integer { +fn default_2323() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2319() -> Vec { +fn default_2324() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2320() -> Integer { +fn default_2325() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2321() -> Integer { +fn default_2326() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2322() -> Integer { +fn default_2327() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2323() -> Vec { +fn default_2328() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2324() -> Option { +fn default_2329() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2325() -> Option> { +fn default_2330() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2326() -> LiveSearchResultsLive { +fn default_2331() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2327() -> String { +fn default_2332() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2328() -> LiveSearchHitLive { +fn default_2333() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2329() -> Vec { +fn default_2334() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2330() -> Option { +fn default_2335() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2331() -> std::collections::HashMap { +fn default_2336() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2332() -> std::collections::HashMap { +fn default_2337() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2333() -> std::collections::HashMap { +fn default_2338() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2334() -> std::collections::HashMap { +fn default_2339() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2335() -> Option> { +fn default_2340() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2336() -> Vec { +fn default_2341() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2337() -> Integer { +fn default_2342() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2338() -> String { +fn default_2343() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2339() -> Integer { +fn default_2344() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2340() -> String { +fn default_2345() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2341() -> String { +fn default_2346() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2342() -> String { +fn default_2347() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2343() -> String { +fn default_2348() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2344() -> String { +fn default_2349() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2345() -> String { +fn default_2350() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2346() -> String { +fn default_2351() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2347() -> String { +fn default_2352() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2348() -> Vec { +fn default_2353() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2349() -> String { +fn default_2354() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2350() -> String { +fn default_2355() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2351() -> Vec { +fn default_2356() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2352() -> String { +fn default_2357() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2353() -> String { +fn default_2358() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2354() -> Vec { +fn default_2359() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2355() -> Vec { +fn default_2360() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2356() -> Vec { +fn default_2361() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2357() -> String { +fn default_2362() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2358() -> String { +fn default_2363() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2359() -> Vec { +fn default_2364() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2360() -> Vec { +fn default_2365() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2361() -> Vec { +fn default_2366() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2362() -> String { +fn default_2367() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2363() -> String { +fn default_2368() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2364() -> Option { +fn default_2369() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2365() -> String { +fn default_2370() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2366() -> String { +fn default_2371() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2367() -> String { +fn default_2372() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2368() -> String { +fn default_2373() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2369() -> String { +fn default_2374() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2370() -> String { +fn default_2375() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2371() -> Vec { +fn default_2376() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2372() -> Option { +fn default_2377() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2373() -> Integer { +fn default_2378() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2374() -> Integer { +fn default_2379() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2375() -> Integer { +fn default_2380() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2376() -> Integer { +fn default_2381() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2377() -> Integer { +fn default_2382() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2378() -> bool { +fn default_2383() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2379() -> String { +fn default_2384() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2380() -> String { +fn default_2385() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2381() -> String { +fn default_2386() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2382() -> String { +fn default_2387() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2383() -> String { +fn default_2388() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2384() -> String { +fn default_2389() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2385() -> String { +fn default_2390() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2386() -> Option { +fn default_2391() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2387() -> Integer { +fn default_2392() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2388() -> Integer { +fn default_2393() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2389() -> Vec { +fn default_2394() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2390() -> String { +fn default_2395() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2391() -> String { +fn default_2396() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2392() -> String { +fn default_2397() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2393() -> String { +fn default_2398() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2394() -> Integer { +fn default_2399() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2395() -> Integer { +fn default_2400() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2396() -> Integer { +fn default_2401() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2397() -> Integer { +fn default_2402() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2398() -> Integer { +fn default_2403() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2399() -> f64 { +fn default_2404() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2400() -> Integer { +fn default_2405() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2401() -> Integer { +fn default_2406() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2402() -> Integer { +fn default_2407() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2403() -> String { +fn default_2408() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2404() -> SessionBriefStats { +fn default_2409() -> SessionBriefStats { serde_json::from_str("{\"events_in\":0,\"windows\":0,\"events_total\":0,\"source_chars\":0,\"brief_chars\":0,\"compression_ratio\":0.0,\"dropped_ungrounded\":0,\"tokens_in\":0,\"tokens_out\":0,\"llm_model\":\"\"}").expect("schema default") } -fn default_2405() -> String { +fn default_2410() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2406() -> String { +fn default_2411() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2407() -> Option { +fn default_2412() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2408() -> Option { +fn default_2413() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2409() -> Option { +fn default_2414() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2410() -> Integer { +fn default_2415() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2411() -> std::collections::HashMap { +fn default_2416() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2412() -> String { +fn default_2417() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2413() -> String { +fn default_2418() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2414() -> Option { +fn default_2419() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2415() -> String { +fn default_2420() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2416() -> Integer { +fn default_2421() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2417() -> Integer { +fn default_2422() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2418() -> Option { +fn default_2423() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2419() -> std::collections::HashMap { +fn default_2424() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2420() -> String { +fn default_2425() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2421() -> Integer { +fn default_2426() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2422() -> String { +fn default_2427() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2423() -> Option { +fn default_2428() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2424() -> String { +fn default_2429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2425() -> Option { +fn default_2430() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2426() -> String { +fn default_2431() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2427() -> String { +fn default_2432() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2428() -> String { +fn default_2433() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2429() -> String { +fn default_2434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2430() -> Integer { +fn default_2435() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2431() -> Integer { +fn default_2436() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2432() -> String { +fn default_2437() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2433() -> std::collections::HashMap { +fn default_2438() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2434() -> String { +fn default_2439() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2435() -> String { +fn default_2440() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2436() -> bool { +fn default_2441() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2437() -> String { +fn default_2442() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2438() -> std::collections::HashMap { +fn default_2443() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2439() -> Vec> { +fn default_2444() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2440() -> Vec { +fn default_2445() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2441() -> Vec { +fn default_2446() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2442() -> bool { +fn default_2447() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2443() -> String { +fn default_2448() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2444() -> String { +fn default_2449() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2445() -> Vec { +fn default_2450() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2446() -> bool { +fn default_2451() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2447() -> String { +fn default_2452() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2448() -> bool { +fn default_2453() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2449() -> Vec { +fn default_2454() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2450() -> std::collections::HashMap { +fn default_2455() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2451() -> Vec> { +fn default_2456() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2452() -> bool { +fn default_2457() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2453() -> bool { +fn default_2458() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2454() -> Vec> { +fn default_2459() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2455() -> std::collections::HashMap { +fn default_2460() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2456() -> String { +fn default_2461() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2457() -> Vec> { +fn default_2462() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2458() -> bool { +fn default_2463() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2459() -> String { +fn default_2464() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2460() -> std::collections::HashMap { +fn default_2465() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2461() -> std::collections::HashMap { +fn default_2466() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2462() -> String { +fn default_2467() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2463() -> std::collections::HashMap { +fn default_2468() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2464() -> std::collections::HashMap { +fn default_2469() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2465() -> std::collections::HashMap { +fn default_2470() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2466() -> String { +fn default_2471() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2467() -> String { +fn default_2472() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2468() -> String { +fn default_2473() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2469() -> bool { +fn default_2474() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2470() -> Integer { +fn default_2475() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2471() -> String { +fn default_2476() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2472() -> String { +fn default_2477() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2473() -> Vec { +fn default_2478() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2474() -> bool { +fn default_2479() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2475() -> Vec { +fn default_2480() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2476() -> std::collections::HashMap> { +fn default_2481() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2477() -> Vec> { +fn default_2482() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2478() -> Vec> { +fn default_2483() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2479() -> String { +fn default_2484() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2480() -> Vec> { +fn default_2485() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2481() -> std::collections::HashMap { +fn default_2486() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2482() -> String { +fn default_2487() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2483() -> Vec> { +fn default_2488() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2484() -> bool { +fn default_2489() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2485() -> Integer { +fn default_2490() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2486() -> Vec> { +fn default_2491() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2487() -> String { +fn default_2492() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2488() -> bool { +fn default_2493() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2489() -> Option> { +fn default_2494() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2490() -> Vec { +fn default_2495() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2491() -> bool { +fn default_2496() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2492() -> std::collections::HashMap { +fn default_2497() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2493() -> String { +fn default_2498() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2494() -> Vec> { +fn default_2499() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2495() -> String { +fn default_2500() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2496() -> std::collections::HashMap { +fn default_2501() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2497() -> String { +fn default_2502() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2498() -> bool { +fn default_2503() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2499() -> Integer { +fn default_2504() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2500() -> std::collections::HashMap { +fn default_2505() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2501() -> bool { +fn default_2506() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2502() -> Vec> { +fn default_2507() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2503() -> std::collections::HashMap { +fn default_2508() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2504() -> std::collections::HashMap { +fn default_2509() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2505() -> String { +fn default_2510() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2506() -> bool { +fn default_2511() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2507() -> Vec { +fn default_2512() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2508() -> Vec> { +fn default_2513() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2509() -> std::collections::HashMap { +fn default_2514() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2510() -> Vec { +fn default_2515() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2511() -> String { +fn default_2516() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2512() -> bool { +fn default_2517() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2513() -> bool { +fn default_2518() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2514() -> std::collections::HashMap { +fn default_2519() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2515() -> String { +fn default_2520() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2516() -> bool { +fn default_2521() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2517() -> std::collections::HashMap { +fn default_2522() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2518() -> std::collections::HashMap { +fn default_2523() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2519() -> Vec> { +fn default_2524() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2520() -> Vec { +fn default_2525() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2521() -> std::collections::HashMap { +fn default_2526() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2522() -> Vec> { +fn default_2527() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2523() -> bool { +fn default_2528() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2524() -> bool { +fn default_2529() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2525() -> Vec { +fn default_2530() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2526() -> std::collections::HashMap { +fn default_2531() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2527() -> String { +fn default_2532() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2528() -> std::collections::HashMap { +fn default_2533() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2529() -> bool { +fn default_2534() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2530() -> bool { +fn default_2535() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2531() -> String { +fn default_2536() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2532() -> Vec { +fn default_2537() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2533() -> f64 { +fn default_2538() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2534() -> Integer { +fn default_2539() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2535() -> String { +fn default_2540() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2536() -> std::collections::HashMap { +fn default_2541() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2537() -> std::collections::HashMap { +fn default_2542() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2538() -> std::collections::HashMap { +fn default_2543() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2539() -> std::collections::HashMap { +fn default_2544() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2540() -> String { +fn default_2545() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2541() -> std::collections::HashMap { +fn default_2546() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2542() -> bool { +fn default_2547() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2543() -> std::collections::HashMap { +fn default_2548() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2544() -> std::collections::HashMap { +fn default_2549() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2545() -> std::collections::HashMap { +fn default_2550() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2546() -> std::collections::HashMap { +fn default_2551() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2547() -> String { +fn default_2552() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2548() -> Vec> { +fn default_2553() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2549() -> Integer { +fn default_2554() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2550() -> String { +fn default_2555() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2551() -> bool { +fn default_2556() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2552() -> String { +fn default_2557() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2553() -> Vec { +fn default_2558() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2554() -> bool { +fn default_2559() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2555() -> Vec { +fn default_2560() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2556() -> f64 { +fn default_2561() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2557() -> String { +fn default_2562() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2558() -> Integer { +fn default_2563() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2559() -> Integer { +fn default_2564() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2560() -> Option { +fn default_2565() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2561() -> f64 { +fn default_2566() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2562() -> Option { +fn default_2567() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2563() -> Vec { +fn default_2568() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index a973cf94d9a..6d42310b04f 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -4096,6 +4096,11 @@ fn knowledge_source_inspect() { serde_json::from_str::("\"namespace\"").unwrap(), "knowledge.source.inspect:access" ); + assert_eq!( + encoded["crawl_options"], + serde_json::from_str::("{}").unwrap(), + "knowledge.source.inspect:crawl_options" + ); assert_eq!( encoded["owner_subject"], serde_json::from_str::("\"\"").unwrap(), @@ -4146,6 +4151,11 @@ fn knowledge_source_add() { .unwrap(); let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); + assert_eq!( + encoded["crawl_proof"], + serde_json::from_str::("null").unwrap(), + "knowledge.source.add:crawl_proof" + ); assert_eq!( encoded["items"], serde_json::from_str::("[]").unwrap(), @@ -4186,6 +4196,11 @@ fn knowledge_source_update() { serde_json::from_str("{\"name\":\"sample\"}").unwrap(); let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); + assert_eq!( + encoded["crawl_proof"], + serde_json::from_str::("null").unwrap(), + "knowledge.source.update:crawl_proof" + ); assert_eq!( encoded["items"], serde_json::from_str::("[]").unwrap(), @@ -4297,6 +4312,11 @@ fn knowledge_source_rotate() { serde_json::from_str("{\"name\":\"sample\"}").unwrap(); let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); + assert_eq!( + encoded["crawl_proof"], + serde_json::from_str::("null").unwrap(), + "knowledge.source.rotate:crawl_proof" + ); assert_eq!( encoded["probe"], serde_json::from_str::( diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index c99a865a9e7..bcdef48d2ce 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4476,6 +4476,19 @@ export interface KnowledgeSearchOutput { stale_dropped?: number; } +export interface KnowledgeSourceCrawlOptions { + /** The delegated Directory reader's address. */ + directory_subject: string; + /** The people and groups to expand, at most 2000 people in total. */ + subjects: KnowledgeSourceCrawlSubject[]; +} + +export interface KnowledgeSourceCrawlSubject { + type: "person" | "group"; + /** The selected person's or group's address. */ + email: string; +} + export interface KnowledgeSourceAddInput { /** The org. */ org: string; @@ -4493,14 +4506,23 @@ export interface KnowledgeSourceAddInput { config?: Record | null; /** gdrive with items or links: the file kinds read, of docs, slides, pdf, pptx, docx (default all but docx). */ include?: string[] | null; - /** Use the supplied shared credential, or your own mirrored connected account. */ - credential_mode?: "shared" | "connected"; + /** Use shared credentials, your connected account, or approved Workspace delegation. */ + credential_mode?: "shared" | "connected" | "crawl"; + /** Crawl only: delegation identity and explicit people or groups; default none. */ + crawl_options?: KnowledgeSourceCrawlOptions | null; /** The source's read-only credential (gdrive: a service account's JSON key, with the folders shared to the account read-only; linear: a read-only API key of an acc */ credential?: string; /** Probe and write nothing. */ dry_run?: boolean; } +export interface KnowledgeSourceCrawlProof { + subject_hashes: string[]; + read_scopes: string[]; + write_denials: string[]; + members: number; +} + export interface KnowledgeSourceProbe { documents?: number; more?: boolean; @@ -4510,6 +4532,7 @@ export interface KnowledgeSourceProbe { } export interface KnowledgeSourceAddOutput { + crawl_proof?: KnowledgeSourceCrawlProof | null; name: string; kind: string; namespace: string; @@ -4581,6 +4604,7 @@ export interface KnowledgeSourceInspectOutput { kind: string; credential_mode?: string; access?: string; + crawl_options?: Record; owner_subject?: string; items?: Array>; include?: string[]; @@ -4603,6 +4627,7 @@ export interface KnowledgeSourceEntry { kind: string; credential_mode?: string; access?: string; + crawl_options?: Record; owner_subject?: string; items?: Array>; include?: string[]; @@ -4725,6 +4750,7 @@ export interface KnowledgeSourceRotateInput { } export interface KnowledgeSourceRotateOutput { + crawl_proof?: KnowledgeSourceCrawlProof | null; name: string; probe?: KnowledgeSourceProbe; rotated_at?: string; @@ -4761,11 +4787,14 @@ export interface KnowledgeSourceUpdateInput { remove_items?: Array>; /** Links to remove, read as items; a folder link also removes a shared drive of the same id the source holds. */ remove_links?: string[]; + /** Crawl only: replace the explicit delegation selectors; default unchanged. */ + crawl_options?: KnowledgeSourceCrawlOptions | null; /** gdrive only: the new file kinds read, of docs, slides, pdf, pptx, docx; default unchanged. */ include?: string[] | null; } export interface KnowledgeSourceUpdateOutput { + crawl_proof?: KnowledgeSourceCrawlProof | null; name: string; items?: Array>; include?: string[]; diff --git a/server/auth/authz.py b/server/auth/authz.py index 5b817bccb95..ea02f41e534 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -41,7 +41,7 @@ from server.operations.base import GRANT_ROLES, Role, grant_rank, rank_role if TYPE_CHECKING: - from server.auth.jwt import AuthInfo + from server.auth.jwt import AuthInfo, AuthorizationClaims from server.core.grant_cache import GrantMap from server.operations.base import Operation @@ -68,7 +68,7 @@ class _Unknown(Enum): _UNKNOWN_GRANT = _Unknown.GRANT -def is_own_platform_admin(auth: AuthInfo) -> bool: +def is_own_platform_admin(auth: AuthorizationClaims) -> bool: """Platform authority belongs to the unscoped principal itself, never a delegated token or the subject a trusted caller acts for.""" return ( @@ -80,7 +80,7 @@ def is_own_platform_admin(auth: AuthInfo) -> bool: ) -def may_act_in_org(auth: AuthInfo, org: str) -> bool: +def may_act_in_org(auth: AuthorizationClaims, org: str) -> bool: """Whether `auth` may act in `org` at all: a token of that org, an org-wide (`*`) token, or a platform admin. The one cross-org rule — the transports and every handler's same-org check ask this. Restricted @@ -98,7 +98,7 @@ class ActedForRefused(PermissionError): access to an index, so a transport adds no index reason to it.""" -async def _check_provisioning(auth: AuthInfo | None, org: str | None) -> None: +async def _check_provisioning(auth: AuthorizationClaims | None, org: str | None) -> None: from server.auth import login, scim from server.core.errors import BackendUnavailableError, LoomServerError @@ -117,7 +117,7 @@ async def _check_provisioning(auth: AuthInfo | None, org: str | None) -> None: raise ActedForRefused(_ACTED_FOR_REVOKED) -async def check_acted_for(auth: AuthInfo | None, org: str | None) -> None: +async def check_acted_for(auth: AuthorizationClaims | None, org: str | None) -> None: """Refuse a trusted caller acting for a revoked or SCIM-deactivated subject under any spelling it holds, or for an `sa:` subject that is not an active bot or one of its agents: a token's own subject, whose grants are the token's and end with it however @@ -234,6 +234,36 @@ async def check_authorized( known_grant: Role | None | _Unknown = _UNKNOWN_GRANT, grants: GrantMap | None = None, allow_repository_read: bool = True, +) -> None: + """Authorize an actual request principal with the common claim and live-grant rules.""" + from server.auth.jwt import AuthInfo + + if auth is not None and not isinstance(auth, AuthInfo): + raise PermissionError("invalid auth principal") + await _check_authorized_claims( + auth, + required_role, + org, + namespace, + deployment_scoped=deployment_scoped, + row_scoped=row_scoped, + known_grant=known_grant, + grants=grants, + allow_repository_read=allow_repository_read, + ) + + +async def _check_authorized_claims( + auth: AuthorizationClaims | None, + required_role: Role, + org: str | None = None, + namespace: str | None = None, + *, + deployment_scoped: bool = False, + row_scoped: bool = False, + known_grant: Role | None | _Unknown = _UNKNOWN_GRANT, + grants: GrantMap | None = None, + allow_repository_read: bool = True, ) -> None: """Raise PermissionError if `auth` lacks `required_role` or access to `(org, namespace)`. Consults `loom.namespace_grants` as a fallback when the JWT role alone @@ -246,7 +276,7 @@ async def check_authorized( `org` and is decided there. `known_grant` (the grant the gate would read, the creator's for a delegated token) and `grants` (the subject's cached grant map, for the restricted check): what a caller that already read them hands in.""" - from server.auth.jwt import AuthInfo # circular import sidestep + from server.auth.jwt import AuthorizationClaims # circular import sidestep # A mirror opens to no token, with auth off too: only the stores' own workers reach one. if namespace is not None and is_mirror_name(namespace): @@ -254,7 +284,7 @@ async def check_authorized( if auth is None: return - if not isinstance(auth, AuthInfo): # defensive + if not isinstance(auth, AuthorizationClaims): # defensive raise PermissionError("invalid auth principal") # A cell serves only the orgs it holds: the routes outside the op registry @@ -387,7 +417,11 @@ async def check_authorized( def _check_scoped_without_target( - auth: AuthInfo, required_role: Role, org: str | None, deployment_scoped: bool, row_scoped: bool + auth: AuthorizationClaims, + required_role: Role, + org: str | None, + deployment_scoped: bool, + row_scoped: bool, ) -> None: """A scoped token on an op that names no (org, namespace): admitted on its best role anywhere for a row- or deployment-scoped op, else 400.""" @@ -414,7 +448,11 @@ def _check_scoped_without_target( async def _grant_role( - auth: AuthInfo, org: str, namespace: str, cap: int | None, known_grant: Role | None | _Unknown + auth: AuthorizationClaims, + org: str, + namespace: str, + cap: int | None, + known_grant: Role | None | _Unknown, ) -> Role | None: """The grant the subject holds there. Where its claim is capped, the cap's read decides for the subject itself: it covers every spelling consistently, @@ -435,7 +473,7 @@ async def _grant_role( async def _check_creator( - auth: AuthInfo, required_role: Role, org: str | None, namespace: str | None + auth: AuthorizationClaims, required_role: Role, org: str | None, namespace: str | None ) -> None: """A delegated token stops when its creator's account is disabled. An op with no namespace has no grant to recheck, so a write there needs the @@ -460,7 +498,7 @@ async def _check_creator( async def _check_delegated( - auth: AuthInfo, + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str, @@ -524,7 +562,7 @@ async def may_be_restricted(org: str, namespace: str) -> bool: return True -def names_namespace(auth: AuthInfo, org: str, namespace: str) -> bool: +def names_namespace(auth: AuthorizationClaims, org: str, namespace: str) -> bool: """True when the token names `namespace` literally — in its `namespaces` claim or its `ns_roles` map. A wildcard (`*`) never counts: a restricted namespace must be asked for by name at mint time.""" @@ -536,7 +574,7 @@ def names_namespace(auth: AuthInfo, org: str, namespace: str) -> bool: def _scoped_role( - auth: AuthInfo, required_role: Role, org: str, namespace: str, *, cap: int | None + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str, *, cap: int | None ) -> Role | None: """The role a scoped token holds on (org, namespace) for this op: its own, capped at the subject's live grant where it holds one. None for a write @@ -555,7 +593,7 @@ def _scoped_role( async def _standard_code_read( - auth: AuthInfo, + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str, @@ -580,7 +618,7 @@ async def _standard_code_read( def _platform_repository_read( - auth: AuthInfo, required_role: Role, org: str, namespace: str + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str ) -> bool: """Repository read authority, independent of claims and membership. The caller checks tenancy and restricted safety guards before admitting it.""" @@ -621,7 +659,7 @@ def _capped_message(org: str, namespace: str, required_role: Role) -> str: ) -async def claim_cap(auth: AuthInfo, org: str, namespace: str) -> int | None: +async def claim_cap(auth: AuthorizationClaims, org: str, namespace: str) -> int | None: """The live grant rank this token's claim on `namespace` is capped at (0: none live), where the token names it and its subject holds a grant row there of any status. None where the subject never held one (an operator's @@ -633,7 +671,7 @@ async def claim_cap(auth: AuthInfo, org: str, namespace: str) -> int | None: return (await grant_map(org, auth.subject)).rank(namespace) -async def live_claims(auth: AuthInfo, org: str, namespaces: Iterable[str]) -> list[str]: +async def live_claims(auth: AuthorizationClaims, org: str, namespaces: Iterable[str]) -> list[str]: """The named `namespaces` (no `*`), in order, that the claim still reaches: all but those capped at a grant that is no longer live.""" return [ns for ns in namespaces if ns and ns != "*" and await claim_cap(auth, org, ns) != 0] @@ -641,7 +679,7 @@ async def live_claims(auth: AuthInfo, org: str, namespaces: Iterable[str]) -> li @marks_unverified async def _check_restricted( - auth: AuthInfo, + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str, @@ -703,7 +741,7 @@ async def _check_restricted( async def restricted_allows( - auth: AuthInfo, + auth: AuthorizationClaims, required_role: Role, org: str, namespace: str, diff --git a/server/auth/delegation.py b/server/auth/delegation.py index 036413fad99..7d1554177d7 100644 --- a/server/auth/delegation.py +++ b/server/auth/delegation.py @@ -23,7 +23,7 @@ from server.auth import jwt as jwt_mod from server.auth.authz import grant_role from server.auth.fail_closed import note_unreadable, unreadable -from server.auth.jwt import AuthInfo, TokenError +from server.auth.jwt import AuthInfo, AuthorizationClaims, TokenError from server.core.grant_sql import GRANT_RANK_SQL, LIVE_GRANT from server.observability.metrics import record_auth_refusal from server.operations.base import GRANT_ROLES, Role, grant_rank @@ -369,7 +369,9 @@ def _lower(a: Role | None, b: Role | None) -> Role | None: return min(a, b) -def ceiling_role(token: AuthInfo, org: str, namespace: str, *, write: bool = False) -> Role | None: +def ceiling_role( + token: AuthorizationClaims, org: str, namespace: str, *, write: bool = False +) -> Role | None: """The most `token` itself allows on `namespace`, at most admin. A scoped token's `ns_roles` entry; a delegated flat token's role where its claim covers the namespace (`write`: its write claim); a primary flat token's diff --git a/server/auth/gateway.py b/server/auth/gateway.py index 8ff604836db..77c7111c264 100644 --- a/server/auth/gateway.py +++ b/server/auth/gateway.py @@ -17,13 +17,13 @@ import dataclasses -from server.auth.jwt import AuthInfo +from server.auth.jwt import AuthInfo, AuthorizationClaims from server.core.principals import USER, is_reserved_subject, personal_name, principal_id __all__ = ["effective_auth", "is_end_user", "personal_namespace"] -def is_end_user(auth: AuthInfo | None) -> bool: +def is_end_user(auth: AuthorizationClaims | None) -> bool: """True when the request runs as an end user an issuer signed in.""" return auth is not None and bool(principal_id(auth.subject, USER)) diff --git a/server/auth/jwt.py b/server/auth/jwt.py index 3835ed2040b..aac4397106c 100644 --- a/server/auth/jwt.py +++ b/server/auth/jwt.py @@ -9,10 +9,11 @@ from __future__ import annotations +import hashlib import logging import secrets import time -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any import jwt @@ -93,9 +94,45 @@ class KeyringUnavailable(AuthUnavailable): `jwt_revocation_max_stale_seconds`, so a retired kid may not be known.""" +def _key_fingerprint(key: Any) -> str: + value = key.encode() if isinstance(key, str) else key + if not isinstance(value, bytes): + from cryptography.hazmat.primitives import serialization + + value = key.public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + return hashlib.sha256(value).hexdigest() + + +@dataclass(frozen=True, repr=False) +class SigningAuthority: + """The successful verifier's identity, not a bearer or a stored signing key.""" + + issuer: str + kid: str + algorithm: str + fingerprint: str + + def current(self) -> bool: + from server.auth import keyring + + return ( + keyring.loaded() + and not keyring.stale() + and self.issuer in settings.trusted_issuers() + and self.algorithm in keyring.ALGORITHMS + and bool(self.fingerprint) + and any( + secrets.compare_digest(self.fingerprint, _key_fingerprint(key)) + for key in keyring.verification_keys(self.kid, self.algorithm) + ) + ) + + @dataclass(frozen=True) -class AuthInfo: - """The authenticated principal. Passed through to handlers.""" +class AuthorizationClaims: + """Verified claim metadata, without making it an incoming request principal.""" subject: str # effective subject (post-impersonation if any) org: str @@ -181,6 +218,8 @@ class AuthInfo: issued_at: int | None = None # `exp` as unix seconds; None for a token without one. expires_at: int | None = None + # Filled only by the normal verifier after it finds the actual successful key. + signing_authority: SigningAuthority | None = field(default=None, repr=False) def has_role(self, required: Role) -> bool: return any(r.value >= required.value for r in self.roles) @@ -233,6 +272,11 @@ def can_write(self, org: str, namespace: str) -> bool: return namespace in self.write_namespaces or "*" in self.write_namespaces +@dataclass(frozen=True) +class AuthInfo(AuthorizationClaims): + """An authenticated request principal, passed through to handlers.""" + + # The `read_scope` claim's values, widest first. READ_SCOPES: tuple[str, ...] = ("namespace", "own_user", "own_session") @@ -414,7 +458,7 @@ def verify_token(token: str, *, secret: str | None = None) -> AuthInfo: trusted = settings.trusted_issuers() try: - decoded = _decode(token, candidates, algorithm) + decoded, fingerprint = _decode(token, candidates, algorithm) except jwt.ExpiredSignatureError as e: raise TokenError(f"token expired: {e}", reason="expired") from e except jwt.PyJWTError as e: # InvalidKeyError is not an InvalidTokenError @@ -480,6 +524,11 @@ def verify_token(token: str, *, secret: str | None = None) -> AuthInfo: first_party=_bool_claim(decoded, "fps"), issued_at=_iat_of(decoded), expires_at=int(exp) if exp is not None else None, + signing_authority=( + SigningAuthority(str(decoded["iss"]), token_kid, algorithm, fingerprint) + if secret is None + else None + ), ) @@ -569,7 +618,7 @@ def _verify_end_user(token: str, issuer: str, spec: EndUserIssuer, public_key: A from server.core.principals import AGENT, USER, end_user_revocation_subject, principal_id try: - decoded = _decode(token, [public_key], "RS256") + decoded, _ = _decode(token, [public_key], "RS256") except jwt.ExpiredSignatureError as e: raise TokenError(f"token expired: {e}", reason="expired") from e except jwt.PyJWTError as e: @@ -622,14 +671,14 @@ def _verify_end_user(token: str, issuer: str, spec: EndUserIssuer, public_key: A ) -def _decode(token: str, keys: list[Any], algorithm: str) -> dict[str, Any]: +def _decode(token: str, keys: list[Any], algorithm: str) -> tuple[dict[str, Any], str]: """The claims under the first of `keys` the signature matches. `issuer=` is checked by the caller (PyJWT takes one string, not a set); `exp` is not required (indefinite tokens) but enforced when present.""" error = jwt.InvalidSignatureError("no key") for key in keys: try: - return jwt.decode( + decoded = jwt.decode( token, key, algorithms=[algorithm], @@ -637,6 +686,7 @@ def _decode(token: str, keys: list[Any], algorithm: str) -> dict[str, Any]: options={"require": ["iat", "sub", "iss", "aud"]}, leeway=settings.jwt_leeway_seconds, # clock-skew tolerance ) + return decoded, _key_fingerprint(key) except jwt.InvalidSignatureError as e: error = e raise error diff --git a/server/auth/scim.py b/server/auth/scim.py index 6548c64cafe..d14ac9d1a0a 100644 --- a/server/auth/scim.py +++ b/server/auth/scim.py @@ -40,10 +40,10 @@ from server.settings import settings if TYPE_CHECKING: - from server.auth.jwt import AuthInfo + from server.auth.jwt import AuthorizationClaims -async def refuses_auth(auth: AuthInfo, *, org: str | None = None) -> bool: +async def refuses_auth(auth: AuthorizationClaims, *, org: str | None = None) -> bool: """Check the effective person and every bearer, creator and parent behind it.""" from server.auth.gateway import is_end_user from server.auth.scim_people import MAX_ITEMS @@ -93,6 +93,8 @@ async def refuses_auth(auth: AuthInfo, *, org: str | None = None) -> bool: _ID_NAMESPACE = uuid.UUID("6f1c3e0a-5b7d-4c2e-9a41-2d8f0b6e7c13") _LEASE_TTL_S = 60.0 _LEASE_WAIT_S = 10.0 +# not a setting: a statement's ids stay well inside the HTTP request bounds. +_IDS_PER_READ = 1000 class Exists(Exception): @@ -183,19 +185,30 @@ async def page( async def deactivated(email: str) -> bool: - """Whether SCIM has deactivated `email`, deleted users included, also once - SCIM is turned off: a deactivated email with no account has no revocation, - only this row, to keep it out. Raises `SignInUnavailable` when it cannot - read: a sign-in must not pass unchecked.""" - try: - with own_write_reads(): # a deactivation may have landed a moment ago elsewhere - row = await get_client().query_one( - f"SELECT 1 AS x FROM {TABLE} FINAL WHERE id = {{id:String}} AND active = 0", - params={"id": user_id(email)}, - ) - except Exception as e: # a read that failed or ran out of time: retryable - raise login.SignInUnavailable from e - return row is not None + """One address's `any_deactivated`: the sign-in check.""" + return await any_deactivated([email]) + + +async def any_deactivated(emails: list[str]) -> bool: + """Whether SCIM has deactivated any of `emails`, deleted users included, also once + SCIM is turned off: a deactivated email with no account has no revocation, only + this row, to keep it out. Reads at most `_IDS_PER_READ` ids per statement and stops + at the first hit. Raises `SignInUnavailable` when it cannot read: a sign-in must not + pass unchecked.""" + ids = sorted({user_id(email) for email in emails}) + for start in range(0, len(ids), _IDS_PER_READ): + try: + with own_write_reads(): # a deactivation may have landed a moment ago elsewhere + row = await get_client().query_one( + f"SELECT 1 AS x FROM {TABLE} FINAL WHERE id IN {{ids:Array(String)}} " + "AND active = 0 LIMIT 1", + params={"ids": ids[start : start + _IDS_PER_READ]}, + ) + except Exception as e: # a read that failed or ran out of time: retryable + raise login.SignInUnavailable from e + if row is not None: + return True + return False async def create( diff --git a/server/auth/sharing.py b/server/auth/sharing.py index 544044f5b0f..66e15c98470 100644 --- a/server/auth/sharing.py +++ b/server/auth/sharing.py @@ -37,7 +37,7 @@ from server.operations.base import Role, rank_role if TYPE_CHECKING: - from server.auth.jwt import AuthInfo + from server.auth.jwt import AuthorizationClaims log = logging.getLogger(__name__) @@ -160,7 +160,7 @@ async def _load_groups(org: str) -> dict[str, list[str]]: return out -async def principals(auth: AuthInfo, org: str) -> list[str]: +async def principals(auth: AuthorizationClaims, org: str) -> list[str]: """Every grant subject this request holds: its own, its groups', its agent's, and `everyone` (the caller checked it may act in `org`).""" out = [auth.subject, *await groups_of(org, auth.subject), EVERYONE] @@ -169,7 +169,7 @@ async def principals(auth: AuthInfo, org: str) -> list[str]: return out -def owns_personal(auth: AuthInfo, org: str, namespace: str) -> bool: +def owns_personal(auth: AuthorizationClaims, org: str, namespace: str) -> bool: """True when `namespace` is the personal collection of the end user `auth` runs as.""" return bool(principal_id(auth.subject, USER)) and namespace == personal_name(org, auth.subject) @@ -179,7 +179,9 @@ def _best(maps: list[grant_cache.GrantMap], lineage: list[str]) -> Role | None: return rank_role(max((m.rank(ns) or 0 for m in maps for ns in lineage), default=0)) -def _claim_limits(auth: AuthInfo, org: str, namespace: str) -> list[tuple[Role | None, str]]: +def _claim_limits( + auth: AuthorizationClaims, org: str, namespace: str +) -> list[tuple[Role | None, str]]: """Each limit the token's own claim sets on `namespace`, whatever its grants, with what the claim must say to lift it: `viewer` outside its `ns_write` set; for a scoped or delegated token, nothing (None) unless the claim names `namespace` (a `*` does not), and @@ -206,7 +208,7 @@ def _claim_limits(auth: AuthInfo, org: str, namespace: str) -> list[tuple[Role | return limits -def _claim_ceiling(auth: AuthInfo, org: str, namespace: str) -> Role | None: +def _claim_ceiling(auth: AuthorizationClaims, org: str, namespace: str) -> Role | None: """The most the token's own claim lets it hold on `namespace` (`_claim_limits`): None for nothing, `admin` when the claim sets no limit.""" ceilings = [limit for limit, _ in _claim_limits(auth, org, namespace)] @@ -216,7 +218,7 @@ def _claim_ceiling(auth: AuthInfo, org: str, namespace: str) -> Role | None: def _capped( - auth: AuthInfo, org: str, namespace: str, granted: Role | None, creator: Role | None + auth: AuthorizationClaims, org: str, namespace: str, granted: Role | None, creator: Role | None ) -> Role | None: """`granted`, no further than the token's own claim allows (`_claim_ceiling`), and for a delegated token no further than its creator's role there (`creator`).""" @@ -228,12 +230,14 @@ def _capped( return min(ceilings, key=lambda r: r.value) # type: ignore[union-attr] -async def role(auth: AuthInfo, org: str, namespace: str) -> Role | None: +async def role(auth: AuthorizationClaims, org: str, namespace: str) -> Role | None: """The request's role on the collection `namespace`.""" return (await roles(auth, org, [namespace]))[namespace] -async def roles(auth: AuthInfo, org: str, namespaces: list[str]) -> dict[str, Role | None]: +async def roles( + auth: AuthorizationClaims, org: str, namespaces: list[str] +) -> dict[str, Role | None]: """The request's role on each collection of `namespaces`, reading the tree, the principals and their grant maps once. A personal collection needs no read: its name says whose it is. A platform admin holds admin on every one @@ -276,7 +280,7 @@ async def _grant_maps(org: str, subjects: list[str]) -> list[grant_cache.GrantMa return maps -async def readable(auth: AuthInfo | None, org: str) -> list[str]: +async def readable(auth: AuthorizationClaims | None, org: str) -> list[str]: """Every collection of `org` the request may read, sorted; none (but the user's own) when the tree or a grant cannot be read.""" from server.auth.authz import may_act_in_org @@ -309,7 +313,9 @@ async def readable(auth: AuthInfo | None, org: str) -> list[str]: return sorted(found | shared) -def claim_cap(auth: AuthInfo, org: str, namespace: str, required_role: Role) -> str | None: +def claim_cap( + auth: AuthorizationClaims, org: str, namespace: str, required_role: Role +) -> str | None: """What the token's own claim must say when it, rather than a missing grant, keeps the token below `required_role` on `namespace` (`_claim_limits`, the limits the gate applies): every limit that does, so one re-mint lifts them all; None when none does. @@ -323,7 +329,7 @@ def claim_cap(auth: AuthInfo, org: str, namespace: str, required_role: Role) -> return ", and ".join(needs) or None -async def check(auth: AuthInfo, required_role: Role, org: str, namespace: str) -> None: +async def check(auth: AuthorizationClaims, required_role: Role, org: str, namespace: str) -> None: """The gate for a collection: PermissionError unless the request holds `required_role` there. A platform admin (an operator's erasure or export) passes.""" diff --git a/server/auth/source_registration.py b/server/auth/source_registration.py new file mode 100644 index 00000000000..6d63c86cd18 --- /dev/null +++ b/server/auth/source_registration.py @@ -0,0 +1,235 @@ +"""A source retains checked claim metadata, never a bearer or a request identity.""" + +from __future__ import annotations + +import dataclasses +import json +import time +from dataclasses import dataclass + +from pydantic import TypeAdapter, ValidationError + +from server.auth import aliases, authz, revocation, scim, tenancy +from server.auth.context import current_auth +from server.auth.jwt import AuthInfo, AuthorizationClaims, SigningAuthority, _check_not_revoked +from server.auth.reader_identity import resolve_reader +from server.core import cell, grant_cache +from server.core.ch import own_write_reads +from server.core.secrets_at_rest import seal, unseal +from server.operations.base import Role +from server.settings import settings + +PURPOSE = "knowledge_crawl.approval" +_now = time.time +_CLAIMS = TypeAdapter(AuthorizationClaims) +_CLAIM_FIELDS = frozenset(field.name for field in dataclasses.fields(AuthorizationClaims)) +_SIGNING_FIELDS = frozenset(field.name for field in dataclasses.fields(SigningAuthority)) + + +class Refused(PermissionError): + def __init__(self) -> None: + super().__init__("source registration authority unavailable") + + +@dataclass(frozen=True) +class Scope: + org: str + namespace: str + source_id: str + generation: str + resource_hash: str + + def check(self) -> None: + if any(not isinstance(v, str) or not v or "\0" in v for v in dataclasses.astuple(self)): + raise Refused() + if len(self.resource_hash) != 64 or any( + c not in "0123456789abcdef" for c in self.resource_hash + ): + raise Refused() + + +@dataclass(frozen=True, repr=False) +class AdminPermit: + """A current presenter, distinct from the source registrant's retained approval.""" + + _auth: AuthInfo + _approval: Approval + + async def validate(self, org: str, *, fresh: bool = True) -> None: + """Fresh by default, as one request's own authority check is. A check repeated + around many reads in one operation passes `fresh=False`; the crawl's own + `validate` methods default to that instead, since they are those repeats.""" + if org != self._approval.scope.org or current_auth() is not self._auth: + raise Refused() + await self._approval.validate(fresh=fresh) + if current_auth() is not self._auth: + raise Refused() + + +async def current_permit(scope: Scope, *, fresh: bool = True) -> AdminPermit: + """`fresh=False` for a read that only decides what to show: it keeps the org's grant + caches, as an indexed read does.""" + scope.check() + auth = current_auth() + if ( + not isinstance(auth, AuthInfo) + or not auth.has_role(Role.ORG_ADMIN) + or not authz.may_act_in_org(auth, scope.org) + ): + raise Refused() + registrant = await aliases.canonical_subject(scope.org, auth.subject) + metadata = _CLAIMS.validate_json(json.dumps(dataclasses.asdict(auth)), strict=True) + permit = AdminPermit(auth, Approval(scope, registrant, metadata)) + await permit.validate(scope.org, fresh=fresh) + return permit + + +async def capture(auth: AuthInfo, scope: Scope) -> tuple[str, str]: + """Seal the current caller's exact authorization for this one source generation.""" + scope.check() + if not isinstance(auth, AuthInfo) or current_auth() is not auth: + raise Refused() + if auth.signing_authority is None or not auth.signing_authority.current(): + raise Refused() + await authz.check_authorized(auth, Role.ADMIN, scope.org, scope.namespace) + if not auth.has_role(Role.ORG_ADMIN) or current_auth() is not auth: + raise Refused() + registrant = await aliases.canonical_subject(scope.org, auth.subject) + frame = { + "format": 1, + "scope": dataclasses.asdict(scope), + "registrant": registrant, + "claims": dataclasses.asdict(auth), + } + encoded = seal(PURPOSE, json.dumps(frame, sort_keys=True, separators=(",", ":"))) + approval = load(encoded, scope, registrant=registrant) + await approval.validate() + if current_auth() is not auth: + raise Refused() + return registrant, encoded + + +def load(encoded: str, scope: Scope, *, registrant: str) -> Approval: + scope.check() + try: + value = json.loads(unseal(PURPOSE, encoded, warn=False)) + if ( + not isinstance(value, dict) + or set(value) != {"format", "scope", "registrant", "claims"} + or type(value["format"]) is not int + or value["format"] != 1 + or value["scope"] != dataclasses.asdict(scope) + or not registrant + or value["registrant"] != registrant + or not isinstance(value["claims"], dict) + or set(value["claims"]) != _CLAIM_FIELDS + ): + raise Refused() + signing = value["claims"].get("signing_authority") + if signing is not None and ( + not isinstance(signing, dict) or set(signing) != _SIGNING_FIELDS + ): + raise Refused() + claims = _CLAIMS.validate_json(json.dumps(value["claims"]), strict=True) + except (ValueError, TypeError, RecursionError, ValidationError): + raise Refused() from None + if len(claims.parent_subjects) != len(claims.parent_iats): + raise Refused() + return Approval(scope, registrant, claims) + + +def check_scope(encoded: str, *, org: str, namespace: str, source_id: str) -> None: + """Refuse a sealed approval not bound to this exact source, without treating its + historical metadata as live authority.""" + try: + value = json.loads(unseal(PURPOSE, encoded, warn=False)) + if not isinstance(value, dict) or not isinstance(value.get("scope"), dict): + raise Refused() + scope = Scope(**value["scope"]) + if (scope.org, scope.namespace, scope.source_id) != (org, namespace, source_id): + raise Refused() + registrant = value["registrant"] + if not isinstance(registrant, str) or not registrant: + raise Refused() + load(encoded, scope, registrant=registrant) + except (ValueError, TypeError, KeyError, RecursionError): + raise Refused() from None + + +@dataclass(frozen=True, repr=False) +class Approval: + scope: Scope + registrant: str + claims: AuthorizationClaims + + def __repr__(self) -> str: + return "Approval()" + + async def _revocations(self) -> None: + claims = self.claims + _check_not_revoked( + { + "sub": claims.subject, + "iat": claims.issued_at, + "jti": claims.token_id, + "sid": claims.session_id, + "parents": list(claims.parents), + "creator": claims.creator, + "parent_subjects": list(claims.parent_subjects), + "parent_iats": list(claims.parent_iats), + } + ) + # The worker checks current storage, not only the request verifier's bounded snapshot. + ids = [v for v in (claims.token_id, claims.session_id, *claims.parents) if v] + oldest = ( + min([claims.issued_at, *claims.parent_iats]) if claims.issued_at is not None else None + ) + subjects = [ + (claims.subject, claims.issued_at), + *zip(claims.parent_subjects, claims.parent_iats, strict=True), + ] + if claims.creator: + subjects.append((claims.creator, oldest)) + if claims.impersonated_by: + subjects.append((claims.impersonated_by, claims.issued_at)) + cutoffs = await revocation.cutoffs([*ids, *(s for s, _ in subjects)]) + if any(key in cutoffs for key in ids) or any( + subject in cutoffs and (issued is None or revocation.kills(cutoffs[subject], issued)) + for subject, issued in subjects + ): + raise Refused() + + async def validate(self, *, fresh: bool = True) -> None: + """`fresh` re-reads the registrant's grants, groups and collections, as the worker and + registration need; an indexed read uses the cached reads every request uses.""" + scope, claims = self.scope, self.claims + scope.check() + if ( + not settings.auth_actually_required() + or cell.gate_reason() + or claims.signing_authority is None + or not claims.signing_authority.current() + or claims.issued_at is None + or claims.issued_at > _now() + settings.jwt_leeway_seconds + or not claims.has_role(Role.ORG_ADMIN) + or not authz.may_act_in_org(claims, scope.org) + or claims.expires_at is not None + and _now() > claims.expires_at + settings.jwt_leeway_seconds + or not await tenancy.is_held(scope.org) + ): + raise Refused() + await self._revocations() + identity = await resolve_reader(scope.org, claims.subject) + if identity is None or identity.subject != self.registrant: + raise Refused() + if await scim.any_deactivated(list(identity.emails)): + raise Refused() + # Same metadata and role law as a real request, with fresh target grants and lineage. + if fresh: + spellings = await aliases.verified_spellings(scope.org, claims.subject) + grant_cache.invalidate(scope.org, [*spellings, claims.creator, *claims.parent_subjects]) + grant_cache.invalidate(scope.org, kind=grant_cache.GROUPS) + grant_cache.invalidate(scope.org, kind=grant_cache.COLLECTIONS) + with own_write_reads(): + await authz.check_acted_for(claims, scope.org) + await authz._check_authorized_claims(claims, Role.ADMIN, scope.org, scope.namespace) diff --git a/server/auth/tenancy.py b/server/auth/tenancy.py index 5042cb22b56..304e08a4ae0 100644 --- a/server/auth/tenancy.py +++ b/server/auth/tenancy.py @@ -43,7 +43,7 @@ from server.settings import settings if TYPE_CHECKING: - from server.auth.jwt import AuthInfo + from server.auth.jwt import AuthorizationClaims log = logging.getLogger(__name__) @@ -106,7 +106,7 @@ async def is_held(org: str) -> bool: return held -def scoped_to(auth: AuthInfo | None, org: str) -> bool: +def scoped_to(auth: AuthorizationClaims | None, org: str) -> bool: """Whether a verified principal is scoped to `org`: its token's own org. A platform or `*`-org principal acts in orgs the cell holds and places none.""" from server.operations.base import Role @@ -116,7 +116,7 @@ def scoped_to(auth: AuthInfo | None, org: str) -> bool: return not auth.has_role(Role.PLATFORM_ADMIN) -async def ensure_held(org: str | None, auth: AuthInfo | None) -> None: +async def ensure_held(org: str | None, auth: AuthorizationClaims | None) -> None: """Pass when this cell holds `org`, recording or placing it as the mode allows. Raise `PermissionError` (403) first for a principal that may not act in the org, `WrongCellError` (409) for another cell's org, `ValidationError` (422) for a new org diff --git a/server/cli/restore.py b/server/cli/restore.py index 27b0965b85d..08b45a55cf9 100644 --- a/server/cli/restore.py +++ b/server/cli/restore.py @@ -110,6 +110,14 @@ async def _refusal(restored: str, point: datetime, *, live: bool, ch: Any) -> st return "" +async def _restore_private_sources(ch: Any, *, apply: bool) -> None: + from server.knowledge.app.connected_restore import restore_all + from server.knowledge.app.crawl_restore import restore_all as restore_crawls + + await restore_all(apply=apply, ch=ch) + await restore_crawls(apply=apply, ch=ch) + + async def reconcile( restored: str, point: datetime, *, apply: bool, live: bool = False, ch: Any ) -> int: @@ -147,9 +155,7 @@ async def reconcile( f"namespace {s['namespace']}, source_uri {s['source_uri']}" ) if not apply: - from server.knowledge.app.connected_restore import restore_all - - await restore_all(apply=False, ch=ch) + await _restore_private_sources(ch, apply=False) return 0 from server.code.app.index import repo_registry @@ -173,15 +179,13 @@ async def reconcile( # live head held here, which `loom rechunk` builds again from the stored content. for line in _rechunk_lines(await knowledge_reconcile.held_sources()): print(line) - from server.knowledge.app.connected_restore import restore_all - # Connection cleanup is fail-fast: no restored document may publish with # retained provider authority, even when an unrelated erasure replay can retry. try: - await restore_all(apply=True, ch=ch) + await _restore_private_sources(ch, apply=True) except Exception: # noqa: BLE001 — local cleanup must finish before any publication print( - "loom reconcile: connected-account cleanup failed; publication remains held", + "loom reconcile: connected-account or crawl cleanup failed; publication remains held", file=sys.stderr, ) return 1 diff --git a/server/cli/secrets.py b/server/cli/secrets.py index 93654d063ba..e738b71f45e 100644 --- a/server/cli/secrets.py +++ b/server/cli/secrets.py @@ -27,6 +27,7 @@ ("loom.qa_sources", "password_enc", (), "qa_sources.password", ""), ("loom.knowledge_sources", "credential_enc", (), "knowledge_sources.credential", ""), ("loom.knowledge_sources", "secret_enc", (), "knowledge_sources.secret", ""), + ("loom.knowledge_sources", "approval_enc", (), "knowledge_crawl.approval", ""), ("loom.knowledge_source_push", "secret_enc", (), "knowledge_source_push.secret", ""), ("loom.connected_accounts", "credential_enc", (), "connected_accounts.credential", ""), ("loom.connected_accounts", "account_email_enc", (), "connected_accounts.email", ""), @@ -156,6 +157,15 @@ async def reseal_all( counts: dict[str, int] = {} lost: dict[str, list[str]] = {} for table, column, path, purpose, where in SEALED: + if table == "loom.knowledge_sources" and column == "approval_enc": + # Every raw version, under each source's lease, bound to its exact scope. + from server.knowledge.app import crawl_reseal + + n, missing = await crawl_reseal.approvals(dry_run=dry_run, ch=ch) + counts[f"{table}.{column}"] = n + if missing: + lost[f"{table}.{column}"] = missing + continue if table == "loom.connected_accounts": from server.knowledge.app.connected_accounts import reseal_registry as reseal_accounts diff --git a/server/clients/_vendor.py b/server/clients/_vendor.py index cc4314a9d47..18a2f12da55 100644 --- a/server/clients/_vendor.py +++ b/server/clients/_vendor.py @@ -4,8 +4,9 @@ Errors carry the HTTP status, never the vendor's response body, which can name documents, people or the vendor's own hosts. A rate limit raises `RateLimited`, a refused credential `CredentialRefused`, an id the credential cannot see `NotFound`, -a body over the caller's size bound `TooLarge`, and any other failure -`VendorError`. Nothing here retries: the sync worker's next pass is the retry. +a body over the caller's size bound `TooLarge`, a request that got no answer +`Unreachable`, and any other failure `VendorError`. Nothing here retries: the sync +worker's next pass is the retry. Each helper takes the `httpx.AsyncClient` to send with, so a client module keeps its own `get_client` name and a test replaces it there. @@ -41,6 +42,10 @@ class RateLimited(VendorError): pass +class Unreachable(VendorError): + """No answer came back (a network error): a later try may pass.""" + + class CredentialRefused(VendorError): pass @@ -144,7 +149,7 @@ async def request_json( raise TooLarge(f"{what}: body exceeds the source size bound") resp = httpx.Response(resp.status_code, content=body) except httpx.RequestError as e: - raise VendorError(f"{what}: {type(e).__name__}") from e + raise Unreachable(f"{what}: {type(e).__name__}") from e raise_for_status(resp, what) if checked is not None and not resp.is_success: raise VendorError(f"{what}: http_{resp.status_code}", status=resp.status_code) @@ -175,7 +180,7 @@ async def exchange_token( try: resp = await client.post(url, **kw) except httpx.RequestError as e: - raise VendorError(f"{what}: {type(e).__name__}") from e + raise Unreachable(f"{what}: {type(e).__name__}") from e # A token endpoint answers an unknown or revoked credential with a 400 too. if resp.status_code == 400: raise CredentialRefused(f"{what}: http_400", status=400) @@ -225,7 +230,7 @@ async def get_capped( raise VendorError(f"{what}: http_{resp.status_code}", status=resp.status_code) return body except httpx.RequestError as e: - raise VendorError(f"{what}: {type(e).__name__}") from e + raise Unreachable(f"{what}: {type(e).__name__}") from e headers = {"Authorization": f"Bearer {token}"} try: async with client.stream("GET", url, headers=headers, params=params) as resp: @@ -234,7 +239,7 @@ async def get_capped( raise_for_status(resp, what) body = await read_capped(resp, max_bytes) except httpx.RequestError as e: - raise VendorError(f"{what}: {type(e).__name__}") from e + raise Unreachable(f"{what}: {type(e).__name__}") from e if body is None: raise TooLarge(f"{what}: over {max_bytes} bytes") return body diff --git a/server/clients/gdrive.py b/server/clients/gdrive.py index ff861138d07..37bf0e6c3bb 100644 --- a/server/clients/gdrive.py +++ b/server/clients/gdrive.py @@ -16,6 +16,7 @@ import re import time from dataclasses import dataclass, field +from enum import StrEnum from typing import Any from server.clients._checked_access import Credential @@ -67,6 +68,19 @@ class ServiceAccount: private_key: str = field(repr=False) +class ReadScope(StrEnum): + DRIVE = _SCOPE + DIRECTORY_USERS = "https://www.googleapis.com/auth/admin.directory.user.readonly" + DIRECTORY_MEMBERS = "https://www.googleapis.com/auth/admin.directory.group.member.readonly" + + +class WriteScope(StrEnum): + DRIVE = "https://www.googleapis.com/auth/drive" + DIRECTORY_USERS = "https://www.googleapis.com/auth/admin.directory.user" + DIRECTORY_GROUPS = "https://www.googleapis.com/auth/admin.directory.group" + DIRECTORY_MEMBERS = "https://www.googleapis.com/auth/admin.directory.group.member" + + def parse_service_account(credential: str) -> ServiceAccount: """The service account a JSON key names; CredentialRefused when it is not one.""" try: @@ -82,23 +96,41 @@ def parse_service_account(credential: str) -> ServiceAccount: return ServiceAccount(client_email=email, private_key=key) -async def access_token(account: ServiceAccount) -> str: - """A read-only access token for the service account.""" +def _signed_assertion( + account: ServiceAccount, *, scope: ReadScope | WriteScope, subject: str | None = None +) -> str: import jwt + if not isinstance(scope, (ReadScope, WriteScope)): + raise CredentialRefused("the delegated scope is not supported") + if subject is not None and ( + not isinstance(subject, str) + or len(subject) > 512 + or subject.count("@") != 1 + or not all(subject.split("@")) + or not re.fullmatch(r"[A-Za-z0-9@._+\-]+", subject) + ): + raise CredentialRefused("the delegated subject is not an email") now = int(time.time()) claims = { "iss": account.client_email, - "scope": _SCOPE, + "scope": scope.value, "aud": _TOKEN_URL, "iat": now, "exp": now + 600, } + if subject is not None: + claims["sub"] = subject try: - assertion = jwt.encode(claims, account.private_key, algorithm="RS256") + return jwt.encode(claims, account.private_key, algorithm="RS256") # A public key or a non-RSA key raises AttributeError or InvalidKeyError here. except (ValueError, TypeError, AttributeError, jwt.PyJWTError): raise CredentialRefused("the service account's private_key is not an RSA key") from None + + +async def access_token(account: ServiceAccount) -> str: + """A read-only access token for the service account.""" + assertion = _signed_assertion(account, scope=ReadScope.DRIVE) answer = await exchange_token( get_client(), _TOKEN_URL, @@ -223,16 +255,26 @@ async def list_all( modified_after: str = "", fields: str = LISTED, pace_s: float = PAGE_PACE_S, + limit: int | None = None, ) -> tuple[list[dict[str, Any]], bool]: """Every file of `mime_types` in any of `folder_ids`, oldest change first, or only those changed after `modified_after` (a `valid_stamp`), and whether the store - searched everything (`list_query`); MAX_PARENTS folders per query.""" + searched everything (`list_query`); MAX_PARENTS folders per query. With `limit`, + no folder is searched once more than `limit` files are in, and the flag does not + say so: a caller compares the count with its bound.""" files: list[dict[str, Any]] = [] whole = True for start in range(0, len(folder_ids), MAX_PARENTS): + if limit is not None and len(files) > limit: + break query = folder_query(folder_ids[start : start + MAX_PARENTS], mime_types) found, complete = await list_query( - token, query, modified_after=modified_after, fields=fields, pace_s=pace_s + token, + query, + modified_after=modified_after, + fields=fields, + pace_s=pace_s, + limit=None if limit is None else limit - len(files), ) files.extend(found) whole = whole and complete @@ -253,7 +295,8 @@ async def list_query( change first, or only those changed after `modified_after` (a `valid_stamp`), and whether the store searched everything: False when any page says `incompleteSearch`. Pages are paced; a failure on any page raises, so every page - was read. With `limit`, paging stops once more than `limit` files are in.""" + was read. With `limit`, paging stops once more than `limit` files are in; the flag + then does not say pages were left, so a caller compares the count with its bound.""" if modified_after and not valid_stamp(modified_after): raise ValueError("modified_after is not a modification stamp") if modified_after: diff --git a/server/clients/google_workspace.py b/server/clients/google_workspace.py new file mode 100644 index 00000000000..ccb150c2f29 --- /dev/null +++ b/server/clients/google_workspace.py @@ -0,0 +1,432 @@ +"""Delegated Google reads; provider identity is not Loom source or reader authority. + +The caller supplies finite I/O bounds. Crawl registration, registrant standing, +complete expansion and publication are outside this transport boundary. +No request retries or follows redirects; provider errors retain no body or URL. +""" + +from __future__ import annotations + +import asyncio +import json +import math +import re +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any, Literal, SupportsIndex, cast +from urllib.parse import quote + +import httpx + +from server.clients import gdrive +from server.clients._http import get_client +from server.clients._vendor import ( + CredentialRefused, + TooLarge, + Unreachable, + VendorError, + raise_for_status, + read_capped, +) + +_now = time.monotonic +_pace = asyncio.sleep +_TOKEN_URL = "https://oauth2.googleapis.com/token" +_DIRECTORY = "https://admin.googleapis.com/admin/directory/v1" +# not a setting: Directory members.list has a fixed documented page maximum. +_PAGE_SIZE = 200 +# not a setting: the selector wire protocol caps the total people at 2000; equal to +# server.knowledge.domain.source_crawl.MAX_PEOPLE; a platform client imports no plane. +MAX_PEOPLE = 2000 +type MemberKind = Literal["USER", "GROUP", "CUSTOMER"] + + +def _positive(value: int) -> None: + if type(value) is not int or value <= 0: + raise ValueError("a positive integer bound is required") + + +def _remaining(deadline: float) -> float: + if type(deadline) not in (int, float): + raise TimeoutError("delegated read deadline") + try: + remaining = deadline - _now() + except OverflowError: + raise TimeoutError("delegated read deadline") from None + if not math.isfinite(remaining) or remaining <= 0: + raise TimeoutError("delegated read deadline") + return remaining + + +def _text(value: Any, *, maximum: int = 8192) -> str: + if ( + not isinstance(value, str) + or not value + or len(value) > maximum + or any(not 33 <= ord(c) <= 126 for c in value) + ): + raise VendorError("invalid directory response") + return value + + +def _key(value: str) -> str: + if ( + not isinstance(value, str) + or value in {".", ".."} + or not re.fullmatch(r"[A-Za-z0-9@._+\-]{1,512}", value) + or "@" in value + and (value.count("@") != 1 or not all(value.split("@"))) + ): + raise ValueError("directory key refused") + return quote(value, safe="") + + +class DelegatedToken: + __slots__ = ("_value", "subject", "scope", "deadline") + + def __init__(self, value: str, subject: str, scope: gdrive.ReadScope, deadline: float) -> None: + self._value, self.subject, self.scope, self.deadline = value, subject, scope, deadline + + def __repr__(self) -> str: + return "DelegatedToken()" + + def __str__(self) -> str: + raise TypeError("a delegated token is not a shared credential") + + def __reduce_ex__(self, protocol: SupportsIndex) -> Any: + raise TypeError("a delegated token cannot be copied or serialized") + + +async def _directory_forbidden(response: httpx.Response, max_bytes: int, deadline: float) -> None: + """Classify bounded reasons without retaining an echoed provider error in the message.""" + raw = await read_capped(response, max_bytes) + _remaining(deadline) + if raw is None: + raise TooLarge("delegated response exceeds its byte bound", status=403) + try: + value = json.loads(raw) + except (ValueError, RecursionError): + raise VendorError("delegated read unavailable", status=403) from None + error = value.get("error") if isinstance(value, dict) else None + if not isinstance(error, dict): + raise VendorError("delegated read unavailable", status=403) + entries = error.get("errors") + reasons = ( + [ + entry["reason"] + for entry in entries + if isinstance(entry, dict) and isinstance(entry.get("reason"), str) and entry["reason"] + ] + if isinstance(entries, list) + else [] + ) + status = error.get("status") + if isinstance(status, str) and status: + reasons.append(status) + if not reasons: + # A 403 with no readable reason proves neither a rate limit nor a revoked + # credential; it refuses without naming either, as any unclassified answer does. + raise VendorError("delegated read unavailable", status=403) + classified = httpx.Response(403, json={"error": {"errors": [{"reason": r} for r in reasons]}}) + raise_for_status(classified, "delegated read") + + +async def _request( + method: Literal["GET", "POST"], + url: str, + *, + deadline: float, + max_bytes: int, + headers: dict[str, str] | None = None, + params: dict[str, Any] | None = None, + data: dict[str, str] | None = None, +) -> dict[str, Any]: + _positive(max_bytes) + remaining = _remaining(deadline) + try: + async with asyncio.timeout_at(deadline): + async with get_client().stream( + method, + url, + headers=headers, + params=params, + data=data, + timeout=remaining, + follow_redirects=False, + ) as response: + status = response.status_code + if status != 200: + if status == 403 and url.startswith(_DIRECTORY + "/"): + await _directory_forbidden(response, max_bytes, deadline) + if status == 400 and url == _TOKEN_URL: + raise CredentialRefused("delegated read refused", status=status) + raise_for_status(httpx.Response(status), "delegated read") + raise VendorError("delegated read: unexpected status", status=status) + raw = await read_capped(response, max_bytes) + except httpx.RequestError: + raise Unreachable("delegated read unavailable") from None + _remaining(deadline) + if raw is None: + raise TooLarge("delegated response exceeds its byte bound") + try: + value = json.loads(raw) + except (ValueError, RecursionError): + raise VendorError("invalid delegated response") from None + if not isinstance(value, dict) or value.get("error") or value.get("errors"): + raise VendorError("invalid delegated response") + _remaining(deadline) + return value + + +async def delegated_token( + account: gdrive.ServiceAccount, + *, + subject: str, + scope: gdrive.ReadScope, + deadline: float, + max_bytes: int, +) -> DelegatedToken: + """An exact read-scope grant; neither scope probing nor source admission.""" + _positive(max_bytes) + _remaining(deadline) + if not isinstance(subject, str): + raise CredentialRefused("the delegated subject is not an email") + assertion = gdrive._signed_assertion(account, scope=scope, subject=subject) + value = await _request( + "POST", + _TOKEN_URL, + deadline=deadline, + max_bytes=max_bytes, + data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": assertion}, + ) + token = _text(value.get("access_token")) + expires = value.get("expires_in") + token_type = value.get("token_type") + if ( + not isinstance(token_type, str) + or token_type.lower() != "bearer" + or type(expires) is not int + or expires <= 0 + or "scope" in value + and (not isinstance(value["scope"], str) or value["scope"].split() != [scope.value]) + ): + raise CredentialRefused("delegated token response refused") + remaining = _remaining(deadline) + expires_at = _now() + min(expires, remaining) + return DelegatedToken(token, subject, scope, min(deadline, expires_at)) + + +def _authorization(token: DelegatedToken, scope: gdrive.ReadScope) -> str: + if token.scope is not scope: + raise CredentialRefused("directory scope refused") + _remaining(token.deadline) + return "Bearer " + _text(token._value) + + +async def require_write_denied( + account: gdrive.ServiceAccount, + *, + subject: str, + scope: gdrive.WriteScope, + deadline: float, + max_bytes: int, +) -> None: + """Only a bounded, explicit OAuth scope denial proves this fixed grant absent.""" + _positive(max_bytes) + if not isinstance(scope, gdrive.WriteScope) or not isinstance(subject, str): + raise CredentialRefused("write-scope proof refused") + assertion = gdrive._signed_assertion(account, scope=scope, subject=subject) + try: + async with asyncio.timeout_at(deadline): + async with get_client().stream( + "POST", + _TOKEN_URL, + data={ + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": assertion, + }, + timeout=_remaining(deadline), + follow_redirects=False, + ) as response: + if response.status_code != 400: + raise_for_status(httpx.Response(response.status_code), "write-scope proof") + raise CredentialRefused("write delegation is not refused") + raw = await read_capped(response, max_bytes) + except httpx.RequestError: + raise Unreachable("write-scope proof unavailable") from None + _remaining(deadline) + if raw is None: + raise TooLarge("write-scope proof exceeds its byte bound") + try: + value = json.loads(raw) + except (ValueError, RecursionError): + raise VendorError("invalid write-scope proof response") from None + if not isinstance(value, dict) or value.get("error") not in { + "unauthorized_client", + "invalid_scope", + }: + raise CredentialRefused("write-scope proof is not an explicit scope denial") + + +@dataclass(frozen=True, repr=False) +class DirectoryUser: + id: str + email: str + aliases: tuple[str, ...] + customer_id: str + + def __repr__(self) -> str: + return "DirectoryUser()" + + +class PersonUnavailable(CredentialRefused): + """The Directory names no active person of the expected workspace for this key.""" + + +def _user(value: dict[str, Any]) -> DirectoryUser: + if ( + value.get("suspended") is not False + or value.get("archived") is not False + or "deletionTime" in value + ): + raise PersonUnavailable("directory person unavailable") + # Domain-alias addresses are the person's too: SCIM may key the person on one. + editable, domain = value.get("aliases", []), value.get("nonEditableAliases", []) + if not isinstance(editable, list) or not isinstance(domain, list): + raise VendorError("invalid directory response") + aliases = [*editable, *domain] + email = _email(value.get("primaryEmail")) + resolved_aliases = tuple(_email(alias) for alias in aliases) + return DirectoryUser( + _text(value.get("id"), maximum=256), + email, + resolved_aliases, + _text(value.get("customerId"), maximum=256), + ) + + +def _email(value: Any) -> str: + email = _text(value, maximum=512) + if email.count("@") != 1 or not all(email.split("@")): + raise VendorError("invalid directory response") + # The Directory may answer an address in any case; every comparison uses one spelling. + return email.lower() + + +async def directory_identity(token: DelegatedToken, *, max_bytes: int) -> DirectoryUser: + """Resolve the delegated directory principal, without inventing a Loom identity.""" + return await _get_user(token, token.subject, max_bytes=max_bytes) + + +async def user( + token: DelegatedToken, key: str, *, customer_id: str, max_bytes: int +) -> DirectoryUser: + """A current active directory user in the explicitly expected workspace customer.""" + expected = _text(customer_id, maximum=256) + found = await _get_user(token, key, max_bytes=max_bytes) + if found.customer_id != expected: + raise PersonUnavailable("directory person unavailable") + return found + + +async def _get_user(token: DelegatedToken, key: str, *, max_bytes: int) -> DirectoryUser: + headers = {"Authorization": _authorization(token, gdrive.ReadScope.DIRECTORY_USERS)} + value = await _request( + "GET", + f"{_DIRECTORY}/users/{_key(key)}", + headers=headers, + params={ + "fields": ( + "id,primaryEmail,aliases,nonEditableAliases,customerId,suspended,archived," + "deletionTime" + ) + }, + deadline=token.deadline, + max_bytes=max_bytes, + ) + found = _user(value) + names = {found.email, *found.aliases} + if key != found.id and key.lower() not in names: + raise VendorError("directory identity mismatch") + return found + + +@dataclass(frozen=True, repr=False) +class DirectoryMember: + id: str + kind: MemberKind + email: str | None + + def __repr__(self) -> str: + return "DirectoryMember()" + + +def _member(value: Any) -> DirectoryMember: + if not isinstance(value, dict): + raise VendorError("invalid directory response") + kind = value.get("type") + if not isinstance(kind, str) or kind not in {"USER", "GROUP", "CUSTOMER"}: + raise VendorError("invalid directory response") + email = value.get("email") + if email is not None: + email = _email(email) + return DirectoryMember(_text(value.get("id"), maximum=256), cast(MemberKind, kind), email) + + +async def group_members( + token: DelegatedToken, + key: str, + *, + max_bytes: int, + max_pages: int, + before_page: Callable[[], Awaitable[None]] | None = None, +) -> tuple[DirectoryMember, ...]: + """Complete bounded pages of metadata; USER/status is no proof of an active employee. + + GROUP and CUSTOMER are explicit results, never automatically expanded. A caller + must resolve USER identities and customer membership before using them as readers. + """ + _positive(max_pages) + headers = {"Authorization": _authorization(token, gdrive.ReadScope.DIRECTORY_MEMBERS)} + url = f"{_DIRECTORY}/groups/{_key(key)}/members" + cursor = "" + cursors: set[str] = set() + members: dict[tuple[str, str], DirectoryMember] = {} + for _ in range(max_pages): + if cursor: + async with asyncio.timeout_at(token.deadline): + await _pace(gdrive.PAGE_PACE_S) + if before_page is not None: + await before_page() + value = await _request( + "GET", + url, + deadline=token.deadline, + max_bytes=max_bytes, + headers=headers, + params={ + "maxResults": _PAGE_SIZE, + "includeDerivedMembership": "false", + "fields": "members(id,type,email),nextPageToken", + **({"pageToken": cursor} if cursor else {}), + }, + ) + rows = value.get("members", []) + if not isinstance(rows, list) or len(rows) > _PAGE_SIZE: + raise VendorError("invalid directory response") + for row in rows: + member = _member(row) + identity = member.kind, member.id + if identity in members: + raise VendorError("directory membership changed during pagination") + members[identity] = member + if len(members) > MAX_PEOPLE: + raise TooLarge("directory membership exceeds the crawl bound") + if "nextPageToken" not in value: + return tuple(members.values()) + cursor = _text(value["nextPageToken"]) + if cursor in cursors: + raise VendorError("directory pagination did not advance") + cursors.add(cursor) + raise TooLarge("directory membership exceeds its page bound") diff --git a/server/core/ch.py b/server/core/ch.py index 8e0edfc5ce4..ff56e23b90c 100644 --- a/server/core/ch.py +++ b/server/core/ch.py @@ -736,9 +736,11 @@ def _stray_columns_sql(table: str, stored: frozenset[str]) -> str: def write_limit_s() -> float: """The longest a leased write runs on the server, and a carried one sent with no longer limit of its own: the configured write timeout, or `_FENCE_MAX_S` when it sets - none.""" + none. A positive scoped statement bound can only shorten this receiver limit.""" limit = float(settings.ch_timeout_write_s) - return _setting_seconds(limit) if limit > 0 else _FENCE_MAX_S + bound = _setting_seconds(limit) if limit > 0 else _FENCE_MAX_S + scoped = statement_timeout_var.get() + return min(bound, _setting_seconds(scoped)) if scoped > 0 else bound def start_guard(deadline_ms_sql: str) -> str: diff --git a/server/core/leases.py b/server/core/leases.py index 82de1788a56..83ec265921b 100644 --- a/server/core/leases.py +++ b/server/core/leases.py @@ -402,12 +402,24 @@ class ClaimExpired(LeaseUnavailable): @asynccontextmanager async def holding( - name: str, *, ttl_s: float, wait_s: float = 0.0, ch: Any = None + name: str, + *, + ttl_s: float, + wait_s: float = 0.0, + ch: Any = None, + settle_writes: bool = False, ) -> AsyncIterator[bool]: """Claim `name` for the block, waiting up to `wait_s`: yields True when this caller has it, False when another holder keeps it. LeaseUnavailable when the store cannot answer, ClaimExpired when a held block runs past `_WORK_SHARE` of - the TTL.""" + the TTL. + + With `settle_writes`, every INSERT must end before the claim's server-side TTL, and + an unanswered fenced write keeps the key until safe expiry: a client cancellation or + lost reply cannot release it early, so the next holder cannot scrub raw history + before an older send has ended. + """ + from server.core import rmt_carry from server.core.ch import statement_timeout lease = await take(name, ttl_s=ttl_s, wait_s=wait_s, ch=ch) @@ -416,18 +428,31 @@ async def holding( return # From when the winning attempt was sent, not when its reply came: a reply held # up past the TTL must not open the block beside the claim's next holder. - left = work_left(lease, ttl_s) + end = time.monotonic() + work_left(lease, ttl_s) + if settle_writes: + with statement_timeout(statement_bound(ttl_s)): + end = min(end, lease.renewed_at + ttl_s - rmt_carry.send_bound_s()) + pending: set[str] = set() try: + left = end - time.monotonic() if left <= 0: raise TimeoutError async with asyncio.timeout(left): with statement_timeout(statement_bound(ttl_s)): - yield True + if settle_writes: + with rmt_carry.claim_writes(end) as pending: + yield True + if pending: + raise LeaseUnavailable("claim has unanswered writes", operation=name) + else: + yield True except TimeoutError as e: raise ClaimExpired( f"the work under claim {name} did not finish in time", operation=name ) from e finally: + if pending: + lease.let_expire() await release_shielded(lease) diff --git a/server/core/rmt_carry.py b/server/core/rmt_carry.py index c1996b5322e..14526163f43 100644 --- a/server/core/rmt_carry.py +++ b/server/core/rmt_carry.py @@ -116,6 +116,10 @@ class _Pin: _lease_end: contextvars.ContextVar[float | None] = contextvars.ContextVar( "rmt_carry_lease_end", default=None ) +# All enclosing claims retain unanswered sends, including sends in nested claims. +_claim_writes: contextvars.ContextVar[tuple[set[str], ...]] = contextvars.ContextVar( + "rmt_claim_writes", default=() +) _pinned: list[_Pin] = [] # How long a send may take to reach the server and start: a request still # queued past this is refused by its guard. @@ -333,6 +337,8 @@ async def writing() -> AsyncIterator[None]: def note_ended(query_id: str) -> None: """The server answered this send (its rows, or an error of its own): the query is over and holds nothing back.""" + for pending in _claim_writes.get(): + pending.discard(query_id) write = _carried.get() if write is not None: write.ended.add(query_id) @@ -341,6 +347,8 @@ def note_ended(query_id: str) -> None: def note_send(query_id: str, deadline: float = 0.0, max_s: float = 0.0) -> None: """The client sent one batch of this carried write as `query_id`, to start by `deadline` (server clock) and run for at most `max_s`.""" + for pending in _claim_writes.get(): + pending.add(query_id) write = _carried.get() if write is not None: write.query_ids.append(query_id) @@ -380,6 +388,18 @@ def under_lease(ends_at: float) -> Iterator[None]: _lease_end.reset(token) +@contextlib.contextmanager +def claim_writes(ends_at: float) -> Iterator[set[str]]: + """Track sends without server completion in every enclosing claim.""" + pending: set[str] = set() + token = _claim_writes.set((*_claim_writes.get(), pending)) + try: + with under_lease(ends_at): + yield pending + finally: + _claim_writes.reset(token) + + def sent_under_lease() -> bool: return _lease_end.get() is not None diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py index 6c757688436..a5f3323c14d 100644 --- a/server/erasure/store/census.py +++ b/server/erasure/store/census.py @@ -553,8 +553,9 @@ def owner(self, scope_type: str) -> str | None: "grants.revoke": ("loom.namespace_grants",), "groups.remove_member": ("loom.principal_groups",), "personal.retire": ("loom.namespaces",), - # Deactivates the namespace's sources and clears their credentials: configuration - # an admin wrote (ids, names, a filter's name fragment), no memory or document content. + # Deactivates the namespace's sources and clears their credentials, and a crawl's + # selected addresses, approval and registrant: configuration an admin wrote (ids, + # names, a filter's name fragment), no memory or document content. "knowledge_sources.retire": ("loom.knowledge_sources",), # Connection metadata and sealed credentials, no query text; removed so the source # cannot draft again into the erased namespace. diff --git a/server/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 6e14bdf951b..3be9bab8e48 100644 --- a/server/knowledge/api/models_sources.py +++ b/server/knowledge/api/models_sources.py @@ -5,8 +5,9 @@ from typing import Annotated, Any, Literal -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field +from server.knowledge.domain.source_crawl import MAX_PEOPLE from server.knowledge.domain.sources import ( MAX_DEPTH, MAX_ITEMS, @@ -110,6 +111,8 @@ class KnowledgeSourceEntry(BaseModel): credential_mode: str = "shared" # Namespace-wide or checked mirrored document access. access: str = "namespace" + # Crawl selectors, only for a current org and namespace administrator. + crawl_options: dict[str, Any] = Field(default_factory=dict) # Canonical connected owner, only in the owner's permitted detail projection. owner_subject: str = "" # The things the source reads (folders, files, shared drives, filters, pages, @@ -170,13 +173,49 @@ class KnowledgeSourceListOutput(BaseModel): ) +class KnowledgeSourceCrawlSubject(BaseModel): + """An explicitly selected Workspace person or group, resolved through Directory.""" + + model_config = ConfigDict(extra="forbid") + + type: Literal["person", "group"] + email: str = Field(..., max_length=512, description="The selected person's or group's address.") + + +class KnowledgeSourceCrawlOptions(BaseModel): + """Delegation identity and the complete bounded union of selected people.""" + + model_config = ConfigDict(extra="forbid") + + directory_subject: str = Field( + ..., max_length=512, description="The delegated Directory reader's address." + ) + subjects: list[KnowledgeSourceCrawlSubject] = Field( + ..., + min_length=1, + max_length=MAX_PEOPLE, + description="The people and groups to expand, at most 2000 people in total.", + ) + + +class KnowledgeSourceCrawlProof(BaseModel): + """The read-only delegation proof, without person addresses or credentials.""" + + subject_hashes: list[str] + read_scopes: list[str] + write_denials: list[str] + members: int + + class KnowledgeSourceAddInput(BaseModel): """Register a document source on a namespace: a kind, what it reads (items and links, or a config) and a read-only credential. A namespace admin may. The credential is probed (a check of every item, or of the 20 given last, and a listing) before anything is stored; a probe that fails stores nothing. A name is refused while documents the sync worker wrote for an earlier source of that name - are live. The credential is stored encrypted and never returned.""" + are live. The credential is stored encrypted and never returned. A crawl source + requires current org and namespace administration, and its probe checks the + delegation, not the items: each turn checks the items as each selected person.""" org: str = Field(..., description="The org.") namespace: str = Field( @@ -215,9 +254,15 @@ class KnowledgeSourceAddInput(BaseModel): description="gdrive with items or links: the file kinds read, of docs, slides, pdf, " "pptx, docx (default all but docx).", ) - credential_mode: Literal["shared", "connected"] = Field( + credential_mode: Literal["shared", "connected", "crawl"] = Field( "shared", - description="Use the supplied shared credential, or your own mirrored connected account.", + description=( + "Use shared credentials, your connected account, or approved Workspace delegation." + ), + ) + crawl_options: KnowledgeSourceCrawlOptions | None = Field( + None, + description="Crawl only: delegation identity and explicit people or groups; default none.", ) credential: str = Field( "", @@ -232,6 +277,8 @@ class KnowledgeSourceAddInput(BaseModel): class KnowledgeSourceAddOutput(BaseModel): + # Crawl only: checked scope and keyed-subject proof; None for another credential mode. + crawl_proof: KnowledgeSourceCrawlProof | None = None # The registered source's name, normalised. name: str # The source kind, normalised. @@ -255,7 +302,10 @@ class KnowledgeSourceUpdateInput(BaseModel): source's file kinds. A namespace admin may. The added items are probed with the stored credential (every one, or the 20 given last) before anything is stored, and a changed `include` probes the file items the source keeps; a probe that fails - stores nothing. Removing every item is refused: remove the source instead.""" + stores nothing. Removing every item is refused: remove the source instead. A + crawl update requires org and namespace administration and reapproves its + exact selectors, items and credential for a fresh generation; it probes the + delegation, not the items, which each turn checks as each selected person.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -294,6 +344,10 @@ class KnowledgeSourceUpdateInput(BaseModel): "the same id the source holds." ), ) + crawl_options: KnowledgeSourceCrawlOptions | None = Field( + None, + description="Crawl only: replace the explicit delegation selectors; default unchanged.", + ) include: list[str] | None = Field( None, description="gdrive only: the new file kinds read, of docs, slides, pdf, pptx, docx; " @@ -302,6 +356,8 @@ class KnowledgeSourceUpdateInput(BaseModel): class KnowledgeSourceUpdateOutput(BaseModel): + # Crawl only: checked scope and keyed-subject proof; None for another credential mode. + crawl_proof: KnowledgeSourceCrawlProof | None = None # The source updated. name: str # The source's items as now stored. @@ -378,6 +434,8 @@ class KnowledgeSourceInspectOutput(BaseModel): credential_mode: str = "shared" # Namespace-wide or checked mirrored document access. access: str = "namespace" + # Crawl selectors, only for a current org and namespace administrator. + crawl_options: dict[str, Any] = Field(default_factory=dict) # Canonical connected owner, only in the owner's permitted detail projection. owner_subject: str = "" # The things the source reads; [] for a recording source. @@ -401,7 +459,9 @@ class KnowledgeSourceCheckInput(BaseModel): """Probe a registered document source with its stored credential now (a check of every item, or of the 20 added last, and a listing), nothing written. A namespace admin may; a connected owner may also check their own source. An administrator - checking another person's connection receives source-level standing only.""" + checking another person's connection receives source-level standing only. A + crawl check requires org and namespace administration and proves delegated + scope standing without returning item titles or counts.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -435,7 +495,9 @@ class KnowledgeSourceCheckOutput(BaseModel): class KnowledgeSourceRotateInput(BaseModel): """Replace a registered document source's credential. A namespace admin may; - the new credential is probed first, and a probe that fails stores nothing.""" + the new credential is probed first, and a probe that fails stores nothing. A + crawl credential requires current org and namespace administration and a + fresh exact-source delegation approval.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -448,6 +510,8 @@ class KnowledgeSourceRotateInput(BaseModel): class KnowledgeSourceRotateOutput(BaseModel): + # Crawl only: checked scope and keyed-subject proof; None for another credential mode. + crawl_proof: KnowledgeSourceCrawlProof | None = None # The source whose credential was replaced. name: str # What the probe with the new credential found. @@ -463,9 +527,11 @@ class KnowledgeSourceRemoveInput(BaseModel): over its next passes. With `delete_documents` true it also takes a source already retired (removed keeping its documents, or retired with its namespace), so those documents can still go; without it such a source answers SOURCE_NOT_FOUND. A - namespace admin may; `confirm` must equal the name. A mirrored source always - queues retirement of its own copies, regardless of `delete_documents`, and - answers no document count.""" + namespace admin may, and for a crawl source only one who also holds the org-wide + role; `confirm` must equal the name. 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.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -490,7 +556,8 @@ class KnowledgeSourceRemoveOutput(BaseModel): class KnowledgeSourceSyncNowInput(BaseModel): """Record a request to sync one document source in its sync state: the sync worker starts its next pass with it. Nothing is fetched on the request. A - namespace admin may.""" + namespace admin may, and for a crawl source only one who also holds the org-wide + role.""" org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") diff --git a/server/knowledge/app/crawl_authority.py b/server/knowledge/app/crawl_authority.py new file mode 100644 index 00000000000..913be7b0739 --- /dev/null +++ b/server/knowledge/app/crawl_authority.py @@ -0,0 +1,377 @@ +"""Crawl checkouts retain the exact registration and provider identity.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import math +import secrets +import time +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import TypeVar + +from server.auth import scim, source_registration +from server.clients import gdrive +from server.clients import google_workspace as google +from server.clients._checked_access import CheckedAccess +from server.clients._vendor import CredentialRefused +from server.core.ch import own_write_reads +from server.core.secrets_at_rest import unseal +from server.knowledge.app import crawl_delegation, crawl_expansion +from server.knowledge.app import sources as source_ops +from server.knowledge.domain.source_crawl import Expansion, Options, Person +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.store import sources as store +from server.settings import settings + +_now = time.monotonic +_T = TypeVar("_T") +_CURRENT: ContextVar[Checkout | None] = ContextVar("crawl_checkout", default=None) + + +@dataclass(frozen=True) +class Bounds: + directory: crawl_expansion.Limits + + +def configured_bounds() -> Bounds: + return Bounds( + crawl_expansion.Limits( + settings.knowledge_crawl_directory_max_response_bytes, + settings.knowledge_crawl_directory_max_pages, + settings.knowledge_crawl_max_groups, + ) + ) + + +@dataclass(frozen=True) +class Checkout: + authority: Authority + people: tuple[Person, ...] + + async def validate(self) -> None: + # Local reads only: the Directory is asked at each person's Drive grant. + await self.authority.validate() + await self.authority._standing(*self.people) + + @asynccontextmanager + async def publication_guard(self, *, fresh: bool = False) -> AsyncIterator[None]: + # Provider observations happen before local leases; no network runs under them. + await self.validate() + async with self.authority.publication_guard(fresh=fresh): + yield + + +def current(source: KnowledgeSource) -> Checkout: + checkout = _CURRENT.get() + if ( + checkout is None + or checkout.authority.source.name != source.name + or scope(checkout.authority.source) != scope(source) + ): + raise CredentialRefused("crawl checkout unavailable") + return checkout + + +def scope(source: KnowledgeSource) -> source_registration.Scope: + payload = json.dumps( + { + "kind": source.kind, + "access": source.access, + "items": source.items, + "config": source.config, + "options": source.crawl_options, + "customer_id": source.crawl_customer_id, + "credential_hash": source.crawl_credential_hash, + }, + sort_keys=True, + separators=(",", ":"), + ) + return source_registration.Scope( + source.org, + source.namespace, + source.source_id, + source.crawl_generation, + hashlib.sha256(payload.encode()).hexdigest(), + ) + + +def _shape(source: KnowledgeSource) -> None: + if ( + source.credential_mode != "crawl" + or source.kind != "gdrive" + or source.access != MIRRORED_ACCESS + or not source.active + or source.pending_delete + or source.owner_subject + or source.connection_id + or source.credential_enc + or not source.secret_enc + or not source.registrant_subject + or not source.approval_enc + or not source.crawl_customer_id + or not source.crawl_generation + or len(source.crawl_credential_hash) != 64 + or any(c not in "0123456789abcdef" for c in source.crawl_credential_hash) + or not settings.knowledge_mirrored_sources_enabled + or not settings.auth_actually_required() + ): + raise CredentialRefused("crawl source unavailable") + Options.parse(source.crawl_options) + + +async def resolve( + source: KnowledgeSource, + *, + deadline: float, + bounds: Bounds, + presenter: source_registration.AdminPermit | None = None, +) -> Authority: + """A worker-only checkout; ordinary live credential selection never calls this path.""" + if type(deadline) not in (float, int) or not math.isfinite(deadline) or deadline <= _now(): + raise TimeoutError("crawl deadline elapsed") + async with asyncio.timeout_at(deadline): + _shape(source) + approval = source_registration.load( + source.approval_enc, scope(source), registrant=source.registrant_subject + ) + await approval.validate() + authority = Authority(source, approval, deadline, bounds, presenter=presenter) + await authority.validate() + # Credentials are touched only after the source and registrant proof. + plain = unseal(source_ops._SECRET_PURPOSE, source.secret_enc, warn=False) + if not plain or not secrets.compare_digest( + hashlib.sha256(plain.encode()).hexdigest(), source.crawl_credential_hash + ): + raise CredentialRefused("crawl source unavailable") + authority._account = gdrive.parse_service_account(plain) + await authority.validate() + return authority + + +async def validate_indexed(source: KnowledgeSource) -> None: + """Indexed reads require live local approval. + + No provider request or source credential is needed to check an indexed copy. + """ + _shape(source) + approval = source_registration.load( + source.approval_enc, scope(source), registrant=source.registrant_subject + ) + await approval.validate(fresh=False) + await source_ops._require_source_namespace(source.org, source.namespace) + await source_ops._require_no_erasure(source.org, source.namespace) + + +class Authority: + __slots__ = ( + "source", + "approval", + "deadline", + "bounds", + "_account", + "_expansion", + "_preparing", + "_directory_token", + "_drive_tokens", + "_presenter", + ) + + def __init__( + self, + source: KnowledgeSource, + approval: source_registration.Approval, + deadline: float, + bounds: Bounds, + *, + presenter: source_registration.AdminPermit | None = None, + ) -> None: + self.source, self.approval = source, approval + self._presenter = presenter + self.deadline, self.bounds = deadline, bounds + self._account: gdrive.ServiceAccount | None = None + self._expansion: Expansion | None = None + self._preparing = asyncio.Lock() + self._directory_token: google.DelegatedToken | None = None + self._drive_tokens: dict[str, google.DelegatedToken] = {} + + def __repr__(self) -> str: + return "Authority()" + + def _listed(self, people: tuple[Person, ...]) -> None: + if self._expansion is None or any(p not in self._expansion.people for p in people): + raise CredentialRefused("crawl person unavailable") + + @asynccontextmanager + async def using(self, people: tuple[Person, ...]) -> AsyncIterator[None]: + self._listed(people) + checkout = Checkout(self, people) + await checkout.validate() + marker = _CURRENT.set(checkout) + try: + yield + await checkout.validate() + finally: + _CURRENT.reset(marker) + + async def validate(self, *, fresh: bool = False) -> None: + """`fresh` re-reads the registrant's grants, as the turn's start and the completed + listing need; every other check uses the cached grant reads.""" + if _now() >= self.deadline: + raise TimeoutError("crawl deadline elapsed") + async with asyncio.timeout_at(self.deadline): + _shape(self.source) + await self.approval.validate(fresh=fresh) + if self._presenter is not None: + await self._presenter.validate(self.source.org, fresh=fresh) + with own_write_reads(): + current = await store.latest_source( + self.source.org, self.source.namespace, self.source.name + ) + if ( + current is None + or not current.active + or any( + getattr(current, field) != getattr(self.source, field) + for field in ( + "org", + "namespace", + "name", + "source_id", + "kind", + "credential_mode", + "access", + "items", + "config", + "crawl_options", + "registrant_subject", + "approval_enc", + "crawl_generation", + "crawl_customer_id", + "crawl_credential_hash", + "secret_enc", + "owner_subject", + "connection_id", + "credential_enc", + ) + ) + ): + raise CredentialRefused("crawl registration changed") + await source_ops._require_source_namespace(self.source.org, self.source.namespace) + await source_ops._require_no_erasure(self.source.org, self.source.namespace) + + def _service_account(self) -> gdrive.ServiceAccount: + if self._account is None: + raise CredentialRefused("crawl source unavailable") + return self._account + + async def prepare(self) -> Expansion: + async with asyncio.timeout_at(self.deadline): + async with self._preparing: + await self.validate() + if self._expansion is None: + result = await crawl_expansion.expand( + Options.parse(self.source.crawl_options), + self._service_account(), + standing=self, + limits=self.bounds.directory, + deadline=self.deadline, + ) + if result.customer != self.source.crawl_customer_id: + raise CredentialRefused("crawl workspace changed") + await crawl_delegation.require_read_only( + self._service_account(), + subject=Options.parse(self.source.crawl_options).directory_subject, + standing=self, + deadline=self.deadline, + max_bytes=self.bounds.directory.body_bytes, + ) + await self.validate() + self._expansion = result + return self._expansion + + async def _standing(self, *people: Person) -> None: + """Local standing, on every use: listed this turn and not deactivated in SCIM. + Batched: a turn-wide checkout costs one read per `scim._IDS_PER_READ` addresses, + not one per person.""" + self._listed(people) + if await scim.any_deactivated([a for p in people for a in p.addresses]): + raise CredentialRefused("crawl person unavailable") + + async def _directory(self, person: Person) -> None: + """The Directory still names this person: checked around each delegated grant, so a + rebound address never selects another person's Drive.""" + if self._directory_token is None or self._directory_token.deadline <= _now(): + self._directory_token = await google.delegated_token( + self._service_account(), + subject=Options.parse(self.source.crawl_options).directory_subject, + scope=gdrive.ReadScope.DIRECTORY_USERS, + deadline=self.deadline, + max_bytes=self.bounds.directory.body_bytes, + ) + current = await google.user( + self._directory_token, + person.id, + customer_id=person.customer, + max_bytes=self.bounds.directory.body_bytes, + ) + if ( + current.id != person.id + or current.email != person.email + or frozenset(current.aliases) != frozenset(person.aliases) + ): + raise CredentialRefused("crawl person changed") + + async def _current(self, person: Person) -> None: + await self.validate() + await self._standing(person) + + async def drive(self, person: Person) -> CheckedAccess: + """The proven provider person selects sub; no caller, audit or Loom subject does.""" + async with asyncio.timeout_at(self.deadline): + await self._current(person) + token = self._drive_tokens.get(person.id) + if token is None or token.deadline <= _now(): + await self._directory(person) + token = await google.delegated_token( + self._service_account(), + subject=person.email, + scope=gdrive.ReadScope.DRIVE, + deadline=self.deadline, + max_bytes=self.bounds.directory.body_bytes, + ) + await self._directory(person) + await self._current(person) + self._drive_tokens[person.id] = token + + async def validate() -> None: + await self._current(person) + + return CheckedAccess( + token._value, kind="gdrive", deadline=token.deadline, validate=validate + ) + + async def run(self, person: Person, callback: Callable[[CheckedAccess], Awaitable[_T]]) -> _T: + async with asyncio.timeout_at(self.deadline): + access = await self.drive(person) + result = await callback(access) + await access.check() + return result + + @asynccontextmanager + async def publication_guard(self, *, fresh: bool = False) -> AsyncIterator[None]: + """No content, ACL, membership or freshness write outlives this exact authority. + + A document's write checks the cached grant reads, the ones an indexed read checks + too, so a revoked grant reaches it within the grant cache's lifetime. Re-reading + the grants for every document would empty the org's caches each time; the + completed listing re-reads them before and after its writes: `fresh` there. The + checkout validated just before, outside the lease.""" + async with source_ops.sources_lease(self.source.org, self.source.namespace): + await self.validate(fresh=fresh) + yield + await self.validate(fresh=fresh) diff --git a/server/knowledge/app/crawl_delegation.py b/server/knowledge/app/crawl_delegation.py new file mode 100644 index 00000000000..90ed51170aa --- /dev/null +++ b/server/knowledge/app/crawl_delegation.py @@ -0,0 +1,34 @@ +"""An admitted crawl proves all fixed read grants and each distinct write denial.""" + +from __future__ import annotations + +import asyncio + +from server.clients import gdrive +from server.clients import google_workspace as google +from server.core.ch import query_tag +from server.knowledge.app.crawl_expansion import Standing + + +async def require_read_only( + account: gdrive.ServiceAccount, + *, + subject: str, + standing: Standing, + deadline: float, + max_bytes: int, +) -> None: + with query_tag("knowledge.crawl.delegation"): + async with asyncio.timeout_at(deadline): + for read in gdrive.ReadScope: + await standing.validate() + await google.delegated_token( + account, subject=subject, scope=read, deadline=deadline, max_bytes=max_bytes + ) + await standing.validate() + for write in gdrive.WriteScope: + await standing.validate() + await google.require_write_denied( + account, subject=subject, scope=write, deadline=deadline, max_bytes=max_bytes + ) + await standing.validate() diff --git a/server/knowledge/app/crawl_expansion.py b/server/knowledge/app/crawl_expansion.py new file mode 100644 index 00000000000..c2e7ce5b2e3 --- /dev/null +++ b/server/knowledge/app/crawl_expansion.py @@ -0,0 +1,195 @@ +"""Complete bounded Workspace membership; no partial expansion becomes reader evidence.""" + +from __future__ import annotations + +import asyncio +import logging +from dataclasses import dataclass +from typing import Protocol + +from server.auth import scim +from server.clients import gdrive +from server.clients import google_workspace as google +from server.clients._vendor import CredentialRefused, NotFound, TooLarge, VendorError +from server.core.ch import query_tag +from server.knowledge.domain.source_crawl import MAX_PEOPLE, Expansion, Options, Person + +log = logging.getLogger(__name__) + + +class Standing(Protocol): + async def validate(self) -> None: ... + + +@dataclass(frozen=True) +class Limits: + body_bytes: int + member_pages: int + groups: int + + def __post_init__(self) -> None: + if any( + type(v) is not int or v <= 0 for v in (self.body_bytes, self.member_pages, self.groups) + ): + raise ValueError("positive crawl bounds required") + + +async def expand( + options: Options, + account: gdrive.ServiceAccount, + *, + standing: Standing, + limits: Limits, + deadline: float, +) -> Expansion: + """Resolve all selected people/groups under one source observation.""" + with query_tag("knowledge.crawl.expand"): + async with asyncio.timeout_at(deadline): + observation = _Expansion(options, account, standing, limits, deadline) + return await observation.run() + + +class _Expansion: + def __init__( + self, + options: Options, + account: gdrive.ServiceAccount, + standing: Standing, + limits: Limits, + deadline: float, + ) -> None: + self.options, self.account = options, account + self.standing, self.limits = standing, limits + self.deadline = deadline + self.customer = "" + self.tokens: dict[gdrive.ReadScope, google.DelegatedToken] = {} + self.people: dict[str, Person] = {} + self.identities: dict[str, Person | None] = {} + self.groups: dict[str, tuple[str, ...]] = {} + self.group_names: dict[str, str] = {} + self.visiting: set[str] = set() + self.group_count = 0 + self.page_count = 0 + self.skipped = 0 + + async def guard(self) -> None: + await self.standing.validate() + + async def token(self, scope: gdrive.ReadScope) -> google.DelegatedToken: + if scope not in self.tokens: + await self.guard() + token = await google.delegated_token( + self.account, + subject=self.options.directory_subject, + scope=scope, + deadline=self.deadline, + max_bytes=self.limits.body_bytes, + ) + await self.guard() + self.tokens[scope] = token + return self.tokens[scope] + + async def run(self) -> Expansion: + await self.standing.validate() + token = await self.token(gdrive.ReadScope.DIRECTORY_USERS) + await self.guard() + principal = await google.directory_identity(token, max_bytes=self.limits.body_bytes) + await self.guard() + self.customer = principal.customer_id + for subject in self.options.subjects: + if subject.kind == "person": + try: + await self.person(subject.email) + except google.PersonUnavailable: + # A selected person the Workspace suspended, archived or moved out is + # left out, as SCIM's deactivation leaves them out; a typo still refuses. + self.skipped += 1 + else: + await self.group(subject.email, subject.email) + await self.guard() + if self.skipped: + log.info("crawl expansion left out %d unavailable people", self.skipped) + return Expansion( + self.customer, + tuple(self.people[k] for k in sorted(self.people)), + tuple(sorted(self.groups.items())), + ) + + async def person(self, key: str) -> Person | None: + if key in self.identities: + return self.identities[key] + token = await self.token(gdrive.ReadScope.DIRECTORY_USERS) + await self.guard() + found = await google.user( + token, key, customer_id=self.customer, max_bytes=self.limits.body_bytes + ) + await self.guard() + person = Person(found.customer_id, found.id, found.email, tuple(sorted(set(found.aliases)))) + old = self.people.get(person.id) + if old is not None and old != person: + raise VendorError("crawl person changed") + # A person SCIM deactivated or deleted, under any address, is left out of the turn. + denied = await scim.any_deactivated(list(person.addresses)) + await self.guard() + admitted = None if denied else person + for spelling in (person.id, *person.addresses): + if spelling in self.identities and self.identities[spelling] != admitted: + raise VendorError("crawl identity is ambiguous") + self.identities[spelling] = admitted + if admitted is not None: + self.people[person.id] = person + if len(self.people) > MAX_PEOPLE: + raise TooLarge("crawl exceeds its people bound") + return admitted + + async def before_page(self) -> None: + await self.guard() + if self.page_count >= self.limits.member_pages: + raise TooLarge("crawl exceeds its directory page bound") + self.page_count += 1 + + async def group(self, key: str, name: str) -> tuple[str, ...]: + canonical = self.group_names.get(name, key) + if canonical in self.visiting: + raise VendorError("crawl group cycle") + if name in self.groups: + return self.groups[name] + self.group_count += 1 + if self.group_count > self.limits.groups: + raise TooLarge("crawl exceeds its group bound") + self.visiting.add(canonical) + self.group_names[name] = canonical + token = await self.token(gdrive.ReadScope.DIRECTORY_MEMBERS) + await self.guard() + members = await google.group_members( + token, + key, + max_bytes=self.limits.body_bytes, + max_pages=self.limits.member_pages, + before_page=self.before_page, + ) + await self.guard() + found: set[str] = set() + for member in members: + if member.kind == "CUSTOMER": + raise CredentialRefused("customer-wide crawl membership refused") + if member.kind == "GROUP": + if member.email is None: + raise VendorError("crawl group address unavailable") + nested = await self.group(member.id, member.email) + found.update(nested) + else: + try: + person = await self.person(member.id) + except (google.PersonUnavailable, NotFound): + # A suspended, archived, deleted or external member reads as nobody: it + # grants no reader and presents no file. A selected address the Directory + # does not know still refuses. + self.skipped += 1 + continue + if person is not None: + found.add(person.email) + await self.guard() + self.visiting.remove(canonical) + self.groups[name] = tuple(sorted(found)) + return self.groups[name] diff --git a/server/knowledge/app/crawl_reseal.py b/server/knowledge/app/crawl_reseal.py new file mode 100644 index 00000000000..b21eb9bee71 --- /dev/null +++ b/server/knowledge/app/crawl_reseal.py @@ -0,0 +1,70 @@ +"""Root rotation carries crawl source approvals without changing authority.""" + +from __future__ import annotations + +from typing import Any + +from server.auth.source_registration import PURPOSE, check_scope +from server.core.ch import get_client, set_query_tag +from server.core.secrets_at_rest import resealed, unseal +from server.knowledge.app import sources as source_ops +from server.knowledge.store import sources as source_store +from server.settings import settings + + +async def approvals(*, dry_run: bool, ch: Any) -> tuple[int, list[str]]: + if ch is not get_client(): + raise RuntimeError("crawl_reseal_target_mismatch") + set_query_tag("knowledge.crawl.reseal.approvals") + count, scanned, after, lost = 0, 0, ("", "", ""), [] + while page := await source_store.crawl_approval_page( + after, maximum=settings.knowledge_crawl_registry_page_size, ch=ch + ): + scanned += len(page) + if scanned > settings.knowledge_crawl_registry_scan_limit: + raise RuntimeError("crawl_reseal_scan_bound") + for org, ns, name in page: + n, unreadable = await _approvals(org, ns, name, dry_run=dry_run, ch=ch) + count += n + if unreadable: + lost.append("/".join((org, ns, name))) + after = page[-1] + return count, lost + + +async def _approvals( + org: str, + namespace: str, + name: str, + *, + dry_run: bool, + ch: Any, +) -> tuple[int, bool]: + count = 0 + async with source_ops.sources_lease(org, namespace): + rows = await source_store.crawl_approval_values( + org, + namespace, + name, + maximum=settings.knowledge_crawl_registry_scan_limit, + ch=ch, + ) + for row in rows: + encoded = str(row["approval_enc"]) + if not unseal(PURPOSE, encoded, warn=False): + return count, True + # Validate source-bound historical metadata without requiring a live grant. + check_scope(encoded, org=org, namespace=namespace, source_id=row["source_id"]) + new = resealed(PURPOSE, encoded) + if new is not None: + count += 1 + if not dry_run: + await source_store.reseal_crawl_approval( + org, + namespace, + row["source_id"], + encoded, + new, + ch=ch, + ) + return count, False diff --git a/server/knowledge/app/crawl_restore.py b/server/knowledge/app/crawl_restore.py new file mode 100644 index 00000000000..e1975a14f0a --- /dev/null +++ b/server/knowledge/app/crawl_restore.py @@ -0,0 +1,51 @@ +"""Offline restore retires every crawl registration and invalidates its approvals.""" + +from __future__ import annotations + +import dataclasses +from typing import Any + +from server.core.ch import get_client, set_query_tag +from server.knowledge.app import sources as source_ops +from server.knowledge.app.connected_restore import offline_refusal +from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.store import sources as source_store +from server.settings import settings + + +async def _retire(source: KnowledgeSource, *, ch: Any) -> None: + async with source_ops.sources_lease(source.org, source.namespace): + pending = await source_ops._queue_retirement(source) + current = await source_store.latest_source(source.org, source.namespace, source.name, ch=ch) + if ( + current is not None + and current.credential_mode == "crawl" + and current.source_id == source.source_id + ): + retired = source_ops._retired(current, pending) + await source_store.insert_source( + dataclasses.replace(retired, crawl_generation=""), ch=ch + ) + + +async def restore_all(*, apply: bool, ch: Any) -> None: + """No restored crawl approval survives: an administrator registers the source again.""" + if ch is not get_client(): + raise RuntimeError("crawl_restore_target_mismatch") + set_query_tag("knowledge.crawl.restore") + if why := await offline_refusal(ch): + raise RuntimeError(why) + maximum = settings.knowledge_crawl_registry_scan_limit + for org in await source_store.crawl_orgs(maximum=maximum, ch=ch): + history = await source_store.crawl_history(org, maximum=maximum, ch=ch) + if not apply: + continue + if why := await offline_refusal(ch): + raise RuntimeError(why) + seen = set() + for source in history: + identity = source.namespace, source.source_id + if identity not in seen: + await _retire(source, ch=ch) + seen.add(identity) + await source_store.invalidate_crawl_approvals(org, ch=ch) diff --git a/server/knowledge/app/crawl_sources.py b/server/knowledge/app/crawl_sources.py new file mode 100644 index 00000000000..cc00cb7d18b --- /dev/null +++ b/server/knowledge/app/crawl_sources.py @@ -0,0 +1,329 @@ +"""Crawl registration binds a current administrator to an exact delegated source.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import hashlib +import hmac +import time +import uuid +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +from server.auth import login, machines, source_registration +from server.auth.context import current_auth, current_caller +from server.clients import gdrive +from server.clients._vendor import RateLimited, Unreachable, VendorError +from server.core import request_work +from server.core.ch import get_client, own_write_reads, set_query_tag +from server.core.diagnostics import private_work +from server.core.errors import BackendUnavailableError, OverloadedError, ValidationError +from server.core.secrets_at_rest import unseal +from server.knowledge.api.models_sources import ( + KnowledgeSourceAddInput, + KnowledgeSourceAddOutput, + KnowledgeSourceCheckOutput, + KnowledgeSourceCrawlProof, + KnowledgeSourceProbe, + KnowledgeSourceRotateOutput, + KnowledgeSourceUpdateInput, + KnowledgeSourceUpdateOutput, +) +from server.knowledge.app import crawl_authority, crawl_delegation, crawl_expansion +from server.knowledge.app import sources as ops +from server.knowledge.domain import sources as domain +from server.knowledge.domain.source_crawl import Options +from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.store import sources as store +from server.settings import settings + +_CRAWL_MIGRATION = 119 + + +def unavailable() -> ValidationError: + return ValidationError("crawl source authority unavailable", code="CREDENTIAL_REFUSED") + + +@asynccontextmanager +async def private() -> AsyncIterator[None]: + if not request_work.mark_mirrored(): + raise unavailable() + with private_work(): + try: + yield + except login.SignInUnavailable: + # The SCIM standing read failed: never admit; a later try may pass. + raise BackendUnavailableError( + "crawl source standing unavailable", operation="crawl" + ) from None + except (Unreachable, RateLimited, TimeoutError): + # The provider failed to answer or throttled the call; it did not refuse the + # credential. + raise BackendUnavailableError("crawl provider unavailable", operation="crawl") from None + except VendorError as e: + if e.status >= 500: + raise BackendUnavailableError( + "crawl provider unavailable", operation="crawl" + ) from None + raise unavailable() from None + except (source_registration.Refused, ValueError): + raise unavailable() from None + + +async def require_operator( + source: KnowledgeSource, *, fresh: bool = True +) -> source_registration.AdminPermit: + if source.credential_mode != "crawl" or not request_work.mark_mirrored(): + raise unavailable() + # Remove and sync_now call this outside `private()`: refuse here as it would. + try: + return await source_registration.current_permit(crawl_authority.scope(source), fresh=fresh) + except login.SignInUnavailable: + raise BackendUnavailableError( + "crawl source standing unavailable", operation="crawl" + ) from None + except (source_registration.Refused, ValueError): + raise unavailable() from None + + +@dataclasses.dataclass +class _Draft: + source: KnowledgeSource + permit: source_registration.AdminPermit + expected: KnowledgeSource | None + deadline: float + members: int = 0 + + async def validate(self, *, fresh: bool = False) -> None: + """The Directory steps call this around every read: they keep the org's grant + caches. The permit's own read and the commit under the lease are fresh.""" + source = self.source + if time.monotonic() >= self.deadline: + raise TimeoutError("crawl registration deadline") + await self.permit.validate(source.org, fresh=fresh) + if not settings.knowledge_mirrored_sources_enabled or not settings.auth_actually_required(): + raise unavailable() + await ops._require_source_namespace(source.org, source.namespace) + await ops._require_no_erasure(source.org, source.namespace) + if self.expected is None: + await ops._require_free(source.org, source.namespace, source.name) + else: + with own_write_reads(): + current = await store.latest_source(source.org, source.namespace, source.name) + if current != self.expected: + raise OverloadedError("the crawl source changed; retry", retry_after_s=1) + await self.permit.validate(source.org, fresh=False) + + +async def _draft(source: KnowledgeSource, expected: KnowledgeSource | None) -> _Draft: + permit = await source_registration.current_permit(crawl_authority.scope(source)) + draft = _Draft( + source, permit, expected, time.monotonic() + settings.knowledge_source_probe_timeout_s + ) + await draft.validate() + if not await machines.fleet_at(get_client(), _CRAWL_MIGRATION): + raise OverloadedError("not every process enforces crawl authority yet", retry_after_s=30) + await draft.validate() + return draft + + +async def _approve( + source: KnowledgeSource, + credential: str, + *, + expected: KnowledgeSource | None, +) -> tuple[KnowledgeSource, _Draft]: + draft = await _draft(source, expected) + async with asyncio.timeout_at(draft.deadline): + ops._require_sealable(credential) + account = gdrive.parse_service_account(credential) + bounds = crawl_authority.configured_bounds() + expansion = await crawl_expansion.expand( + Options.parse(source.crawl_options), + account, + standing=draft, + limits=bounds.directory, + deadline=draft.deadline, + ) + await crawl_delegation.require_read_only( + account, + subject=Options.parse(source.crawl_options).directory_subject, + standing=draft, + deadline=draft.deadline, + max_bytes=bounds.directory.body_bytes, + ) + draft.members = len(expansion.people) + await draft.validate() + source = dataclasses.replace(source, crawl_customer_id=expansion.customer) + auth = current_auth() + if auth is None: + raise unavailable() + subject, approval = await source_registration.capture(auth, crawl_authority.scope(source)) + source = dataclasses.replace( + source, + registrant_subject=subject, + approval_enc=approval, + secret_enc=ops._sealed(ops._SECRET_PURPOSE, credential), + credential_enc="", + ) + await draft.validate() + return source, draft + + +async def _commit(source: KnowledgeSource, draft: _Draft) -> None: + async with ops.sources_lease(source.org, source.namespace): + await draft.validate(fresh=True) + # Recheck the approval under the publication lease. + await crawl_authority.validate_indexed(source) + await store.write_state( + source.org, source.namespace, source.name, state_value="", detail={} + ) + await store.insert_source(source) + await draft.permit.validate(source.org, fresh=False) + await crawl_authority.validate_indexed(source) + + +def _options(value: Any) -> dict[str, Any]: + return Options.parse(value).stored() + + +def _renew(source: KnowledgeSource, credential: str) -> KnowledgeSource: + return dataclasses.replace( + source, + crawl_generation=uuid.uuid4().hex, + crawl_credential_hash=hashlib.sha256(credential.encode()).hexdigest(), + approval_enc="", + registrant_subject="", + crawl_customer_id="", + ) + + +async def add( + input: KnowledgeSourceAddInput, + *, + name: str, + kind: str, + config: dict[str, Any], + items: list[dict[str, Any]], +) -> KnowledgeSourceAddOutput: + set_query_tag("knowledge.crawl.add") + async with private(): + if kind != "gdrive" or input.crawl_options is None or not input.credential: + raise unavailable() + source = KnowledgeSource( + org=input.org, + namespace=input.namespace, + name=name, + kind=kind, + source_id=str(uuid.uuid4()), + config=config, + items=items, + access=domain.MIRRORED_ACCESS, + credential_mode="crawl", + crawl_options=_options(input.crawl_options.model_dump()), + created_by=current_caller()[0], + ) + source = _renew(source, input.credential) + source, draft = await _approve(source, input.credential, expected=None) + if not input.dry_run: + await _commit(source, draft) + return KnowledgeSourceAddOutput( + name=name, + kind=kind, + namespace=source.namespace, + items=source.items, + include=ops._answered_include(source), + probe=KnowledgeSourceProbe(), + dry_run=input.dry_run, + crawl_proof=_proof(source, draft), + ) + + +async def check(source: KnowledgeSource) -> KnowledgeSourceCheckOutput: + set_query_tag("knowledge.crawl.check") + async with private(): + permit = await require_operator(source) + deadline = time.monotonic() + settings.knowledge_source_probe_timeout_s + async with asyncio.timeout_at(deadline): + authority = await crawl_authority.resolve( + source, + deadline=deadline, + bounds=crawl_authority.configured_bounds(), + presenter=permit, + ) + await authority.prepare() + await permit.validate(source.org) + return KnowledgeSourceCheckOutput( + name=source.name, + summary="the delegated read-only authority was accepted", + checked_at=ops._now_iso(), + ) + + +async def rotate(source: KnowledgeSource, credential: str) -> KnowledgeSourceRotateOutput: + set_query_tag("knowledge.crawl.rotate") + async with private(): + # `_approve`'s draft proves the operator with a fresh permit. + changed, draft = await _approve(_renew(source, credential), credential, expected=source) + await _commit(changed, draft) + return KnowledgeSourceRotateOutput( + name=source.name, rotated_at=ops._now_iso(), crawl_proof=_proof(changed, draft) + ) + + +async def update( + source: KnowledgeSource, input: KnowledgeSourceUpdateInput +) -> KnowledgeSourceUpdateOutput: + set_query_tag("knowledge.crawl.update") + async with private(): + added = ops._items_of("gdrive", input.add_items, input.add_links, "add_", held=source) + removed = ops._as_held( + source, ops._items_of("gdrive", input.remove_items, input.remove_links, "remove_") + ) + change = ops._updated(source, added, removed, ops._include(input.include, "gdrive")) + candidate = dataclasses.replace( + change.source, + crawl_options=( + _options(input.crawl_options.model_dump()) + if input.crawl_options is not None + else source.crawl_options + ), + ) + # Credential access follows current presenter and exact source standing. + # One draft proves the operator and the stored source before the credential opens. + await _draft(source, source) + await crawl_authority.validate_indexed(source) + credential = unseal(ops._SECRET_PURPOSE, source.secret_enc, warn=False) + if ( + not credential + or hashlib.sha256(credential.encode()).hexdigest() != source.crawl_credential_hash + ): + raise unavailable() + changed, draft = await _approve(_renew(candidate, credential), credential, expected=source) + await _commit(changed, draft) + return KnowledgeSourceUpdateOutput( + name=source.name, + items=changed.items, + include=ops._answered_include(changed), + added=change.added, + removed=change.removed, + crawl_proof=_proof(changed, draft), + ) + + +def audit_hash(kind: str, address: str) -> str: + """A crawl subject in an audit row: keyed, so the row names no address.""" + key = hmac.digest(settings.jwt_secret.encode(), b"crawl-audit-subjects", "sha256") + return hmac.digest(key, (kind + ":" + address).encode(), "sha256").hex() + + +def _proof(source: KnowledgeSource, draft: _Draft) -> KnowledgeSourceCrawlProof: + options = Options.parse(source.crawl_options) + return KnowledgeSourceCrawlProof( + subject_hashes=[audit_hash(s.kind, s.email) for s in options.subjects], + read_scopes=[scope.value for scope in gdrive.ReadScope], + write_denials=[scope.value for scope in gdrive.WriteScope], + members=draft.members, + ) diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 254345e946e..be86d4e7d0a 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -85,6 +85,8 @@ class ReadPlan: default_factory=dict, repr=False ) + _crawl_pins: dict[tuple[str, str], KnowledgeSource] = field(default_factory=dict, repr=False) + @property def discovery_sources(self) -> dict[tuple[str, str], str]: """The request's fixed discovery scope, unaffected by conditional checks.""" @@ -146,6 +148,7 @@ async def _refresh_scope(self) -> None: snapshot._auth = self._auth snapshot._scope_frozen = True snapshot._connected_pins = self._connected_pins + snapshot._crawl_pins = self._crawl_pins await _prepare(snapshot, sources, self._reader_subject) self.sources = { key: original @@ -303,18 +306,52 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: return plan -async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) -> None: +async def _eligible_sources( + plan: ReadPlan, + sources: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[tuple[str, str], str]]: + from server.knowledge.app import crawl_authority from server.knowledge.app.connected_accounts import validate_indexed from server.knowledge.store import sources as source_store eligible = [] + crawl_generations: dict[tuple[str, str], str] = {} for row in sources: key = row["namespace"], row["source_id"] mode = row.get("credential_mode", "shared") if mode == "shared": - if key not in plan._connected_pins: + if key not in plan._connected_pins and key not in plan._crawl_pins: eligible.append(row) continue + if mode == "crawl": + if plan._scope_frozen and key not in plan._crawl_pins: + continue + try: + source = await source_store.latest_source(plan.org, row["namespace"], row["name"]) + if ( + source is None + or source.source_id != row["source_id"] + or plan._auth is None + or current_auth() is not plan._auth + ): + continue + pinned = plan._crawl_pins.get(key) + if pinned is not None and ( + crawl_authority.scope(source) != crawl_authority.scope(pinned) + or source.approval_enc != pinned.approval_enc + or source.registrant_subject != pinned.registrant_subject + or source.secret_enc != pinned.secret_enc + ): + continue + await check_authorized(plan._auth, Role.VIEWER, plan.org, row["namespace"]) + await crawl_authority.validate_indexed(source) + crawl_generations[key] = source.crawl_generation + eligible.append(row) + if not plan._scope_frozen: + plan._crawl_pins[key] = copy.deepcopy(source) + except Exception: # noqa: BLE001 — unverifiable crawl authority admits no mirror leg + continue + continue if mode != "connected" or (plan._scope_frozen and key not in plan._connected_pins): continue try: @@ -336,7 +373,11 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) plan._connected_pins[key] = copy.deepcopy(source) except Exception: # noqa: BLE001 — one unverifiable connection admits no private leg continue - sources = eligible + return eligible, crawl_generations + + +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}) mirrors = await mirrors_repo.mirrors_of(plan.org, names, live_only=True) by_original: dict[str, list[str]] = {} @@ -350,10 +391,18 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) } rows = await store.listings(plan.org, list(pairs)) plan.reader = await resolve_reader(plan.org, subject) if subject else None + + def admits_listing(r: dict[str, Any]) -> bool: + # A fresh listing of a paired source; a crawl's must be of its current generation. + key = (r["namespace"], r["source_id"]) + if key not in pairs or not fresh( + r["started_at"], now(), settings.knowledge_source_acl_stale_seconds + ): + return False + generation = crawl_generations.get((pairs[key], r["source_id"])) + return generation is None or r.get("crawl_generation") == generation + plan.listing_starts = { - (r["namespace"], r["source_id"]): r["started_at"] - for r in rows - if (r["namespace"], r["source_id"]) in pairs - and fresh(r["started_at"], now(), settings.knowledge_source_acl_stale_seconds) + (r["namespace"], r["source_id"]): r["started_at"] for r in rows if admits_listing(r) } plan.sources = {key: pairs[key] for key in plan.listing_starts} diff --git a/server/knowledge/app/source_gdrive_items.py b/server/knowledge/app/source_gdrive_items.py index 5d43cea2fbb..6fce1f957fe 100644 --- a/server/knowledge/app/source_gdrive_items.py +++ b/server/knowledge/app/source_gdrive_items.py @@ -134,6 +134,7 @@ async def list_items( fields: str = gdrive.LISTED, pace_s: float = gdrive.PAGE_PACE_S, out_of_time: Callable[[], bool] = lambda: False, + limit: int | None = None, ) -> Listing: """Every file the items list, each once, or only those changed after `modified_after`. A rate limit, a refused credential or a failed query raises; @@ -144,13 +145,23 @@ async def list_items( folder listing or other item starts, and the listing records that it ran out, so the turn keeps its stamp and lists again. A `file` item is one metadata read on every listing, an incremental one too. `fields`: what is read of each file - (`gdrive.LISTED_WITH_PERMISSIONS` adds its permissions).""" + (`gdrive.LISTED_WITH_PERMISSIONS` adds its permissions). With `limit`, more unique + files than it raises `gdrive.TooLarge`, and a query stopped at it leaves the listing + not whole.""" + if limit is not None and (type(limit) is not int or limit <= 0): + raise ValueError("listing file bound refused") out = Listing(mime_types=include_mime_types(include)) files: dict[str, dict[str, Any]] = {} - def add(found: list[dict[str, Any]]) -> None: + def add(found: list[dict[str, Any]], whole: bool = True) -> None: + # A bounded query stops paging once its raw rows pass the bound, and a repeated + # file can take them past it with unique files still under: then pages or + # folders were left, and the listing is not whole. + out.whole = out.whole and whole and (limit is None or len(found) <= limit) for f in found: files.setdefault(str(f.get("id") or ""), f) + if limit is not None and len(files) > limit: + raise gdrive.TooLarge("listing exceeds its file bound") roots = [i["id"] for i in items if i["type"] == "folder" and i.get("recursive")] if roots: @@ -166,9 +177,9 @@ def add(found: list[dict[str, Any]]) -> None: modified_after=modified_after, fields=fields, pace_s=pace_s, + limit=limit, ) - add(found) - out.whole = out.whole and whole + add(found, whole) for n, item in enumerate(items): # A folder item was listed above; every other type asks the store. if item["type"] != "folder" and out_of_time(): @@ -184,14 +195,14 @@ def add(found: list[dict[str, Any]]) -> None: modified_after=modified_after, fields=fields, pace_s=pace_s, + limit=limit, ) except gdrive.NotFound: # A drive the account left lists nothing, which says nothing is absent. out.notes.append(f"item {n}: http_404") out.lost_item = True continue - add(found) - out.whole = out.whole and whole + add(found, whole) elif item["type"] == "filter": # Add and update refuse a filter whose kinds share none with include. mime_types = include_mime_types(include, item.get("kinds")) @@ -202,9 +213,9 @@ def add(found: list[dict[str, Any]]) -> None: modified_after=modified_after, fields=fields, pace_s=pace_s, + limit=limit, ) - add(found) - out.whole = out.whole and whole + add(found, whole) elif item["type"] == "file": out.file_ids.add(item["id"]) meta = await _file_item(token, n, item["id"], out, fields) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index c506f801261..13ad49ea6d4 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -534,6 +534,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 src.credential_mode == "crawl" and src.kind == "gdrive" and mirror_synced(src): + from server.knowledge.app import source_sync_crawl + + return source_sync_crawl.turn if ( src.credential_mode == "connected" and src.kind in {"notion", "linear"} @@ -1273,6 +1277,10 @@ async def require_current(src: KnowledgeSource) -> None: if account is None: raise connected_accounts.unavailable() await connected_accounts._source_standing(src, account) + elif src.credential_mode == "crawl": + from server.knowledge.app import crawl_authority + + await crawl_authority.current(src).validate() @contextlib.asynccontextmanager @@ -1282,6 +1290,11 @@ async def publication_guard(src: KnowledgeSource) -> AsyncIterator[None]: async with connected_accounts.publication_guard(src): yield + elif src.credential_mode == "crawl": + from server.knowledge.app import crawl_authority + + async with crawl_authority.current(src).publication_guard(): + yield else: yield @@ -1356,7 +1369,7 @@ async def write_document( permissions=permissions, commit_guard=( functools.partial(publication_guard, src) - if src.credential_mode == "connected" + if src.credential_mode in {"connected", "crawl"} else None ), ) diff --git a/server/knowledge/app/source_sync_crawl.py b/server/knowledge/app/source_sync_crawl.py new file mode 100644 index 00000000000..5b532e04105 --- /dev/null +++ b/server/knowledge/app/source_sync_crawl.py @@ -0,0 +1,254 @@ +"""A complete Workspace union precedes every content, ACL and membership publication.""" + +from __future__ import annotations + +import dataclasses +import functools +from datetime import UTC, datetime + +from server.clients import gdrive +from server.clients._vendor import VendorError +from server.core.ch import sequential_reads, set_query_tag +from server.knowledge.app import crawl_authority, mirrors, private_sync +from server.knowledge.app import source_gdrive_items as items +from server.knowledge.app import source_sync as sync +from server.knowledge.app import source_sync_mirror as mirror_sync +from server.knowledge.domain import access_list +from server.knowledge.domain.source_crawl import Expansion, File, Union +from server.knowledge.domain.sources import ( + KnowledgeSource, + home, + json_object, + mirror_uri, + mirror_uri_suffix, +) +from server.knowledge.store import crawl_publication, documents +from server.knowledge.store import mirrors as mirror_store +from server.knowledge.store import sources as store +from server.settings import settings + + +async def observe( + authority: crawl_authority.Authority, + run: sync.Pass, + *, + maximum_files: int, + observations: dict[str, items.Listing] | None = None, + result: sync.TurnResult | None = None, +) -> tuple[Expansion, tuple[File, ...]]: + """No partial person's listing, membership or ACL reaches persistent storage.""" + source = authority.source + expansion = await authority.prepare() + union = Union(expansion, maximum_files) + for person in expansion.people: + if run.budget.exhausted(): + raise TimeoutError("crawl union exceeds the pass budget") + token = await authority.drive(person) + listing = await items.list_items( + token, + source.items, + source.config.get("include", []), + fields=gdrive.LISTED_WITH_PERMISSIONS + ",owners(me,emailAddress)", + out_of_time=run.budget.exhausted, + limit=maximum_files, + ) + await token.check() + visibility = result if result is not None else sync.TurnResult() + if ( + not await sync._items_visible(token, source.items, visibility, run.budget.exhausted) + or not visibility.complete + ): + raise VendorError("crawl selected items unavailable") + if observations is not None: + observations[person.id] = listing + for file in listing.files: + if "permissions" not in file: + file["permissions"] = await gdrive.file_permissions(token, str(file["id"])) + await token.check() + union.add( + person, + listing.files, + whole=( + listing.whole + and not listing.ran_out + and not listing.lost_item + and not listing.walk_cut + ), + ) + await authority.validate() + files = union.complete() + addresses = {sync.source_uri_of(file.metadata) for file in files} + if len(addresses) != len(files) or any(not uri.startswith("https://") for uri in addresses): + raise ValueError("crawl file address is unavailable or ambiguous") + return expansion, files + + +async def turn( + source: KnowledgeSource, + state: dict[str, str], + run: sync.Pass, + *, + bounds: crawl_authority.Bounds | None = None, + membership_bound: int | None = None, + maximum_files: int | None = None, +) -> sync.TurnResult: + """Publish only a complete observation under the exact retained registration.""" + set_query_tag("knowledge.crawl.sync") + bounds = bounds or crawl_authority.configured_bounds() + maximum_files = settings.knowledge_crawl_max_files if maximum_files is None else maximum_files + # The options are read only once `resolve` has validated them. + authority = await crawl_authority.resolve(source, deadline=run.budget.stop_after, bounds=bounds) + if membership_bound is None: + # A group can be reached by configured alias, primary address and provider id. + membership_bound = 3 * bounds.directory.groups + len(source.crawl_options["subjects"]) + asked = json_object(state.get("detail", "")) + known = await mirrors.live_mirror(source.org, source.namespace) + detail = await mirror_sync._own_state(source, known, asked) + result = sync.TurnResult(full=bool(detail.get("full")) or sync.full_due(detail)) + sync.start_waits(result, detail) + observations: dict[str, items.Listing] = {} + started = datetime.now(UTC) + try: + expansion, files = await observe( + authority, run, maximum_files=maximum_files, observations=observations, result=result + ) + except (VendorError, ValueError, TimeoutError): + result.fail("failed", "crawl observation incomplete") + return result + async with authority.using(expansion.people): + mirror = await mirrors.ensure_mirror( + source.org, + source.namespace, + still_current=functools.partial(sync.require_current, source), + ) + if mirror != known: + detail = await mirror_sync._own_state(source, "", asked) + result.full = bool(detail.get("full")) or sync.full_due(detail) + sync.start_waits(result, detail) + source = dataclasses.replace(source, mirror=mirror) + result.mirror = mirror + async with private_sync.mirror_costs(source.org, mirror, sync.WORKER): + await _publish( + source, + authority, + expansion, + files, + observations, + started, + run, + result, + membership_bound, + ) + return result + + +async def _permissions(file: File) -> access_list.AccessList: + return file.access + + +async def _publish( + source: KnowledgeSource, + authority: crawl_authority.Authority, + expansion: Expansion, + files: tuple[File, ...], + observations: dict[str, items.Listing], + started: datetime, + run: sync.Pass, + result: sync.TurnResult, + membership_bound: int, +) -> None: + result.documents_seen = len(files) + with sequential_reads(): + copies = await store.every_copy(source.org, *home(source)) + stored = sync.index_with_room(result, [c for c in copies if c["searchable"]]) + people = {person.id: person for person in expansion.people} + listed = { + mirror_uri(sync.source_uri_of(file.metadata), source.source_id): file for file in files + } + # Narrow every old ACL before fresh content or a complete-listing proof can land. + lists = {copy["source_uri"]: access_list.UNREAD for copy in copies} + for uri, file in listed.items(): + permissions = file.access + previous = next((copy for copy in copies if copy["source_uri"] == uri), None) + if previous is not None and previous["source_revision"] != str( + file.metadata.get("modifiedTime") or "" + ): + permissions = access_list.common( + access_list.from_json(previous["access_json"]), permissions + ) + lists[uri] = permissions + if not await mirror_sync._write_lists(source, lists): + result.fail("failed", "crawl permissions changed ownership") + return + for uri, file in listed.items(): + selected = tuple(people[id] for id in file.presenters) + async with authority.using(selected): + token = await authority.drive(selected[0]) + read_access = functools.partial(_permissions, file) + if not await sync.sync_file( + source, + token, + file.metadata, + uri, + stored.get(file.id), + run, + result, + read_access=read_access, + ): + break + if not result.complete or result.status != "ok" or run.budget.exhausted(): + return + if await documents.publications_owed( + source.org, source.mirror, mirror_uri_suffix(source.source_id) + ): + return + for copy in copies: + if copy["source_uri"] in listed: + continue + if run.spent(): + result.mark(sync.TurnMark.PASS_BOUND) + return + gone = await _gone(authority, expansion, observations, copy["file_id"], result, run) + if gone is None: + return + if gone: + async with sync.publication_guard(source): + if await sync.retire(source, copy["source_uri"]): + result.removed += 1 + async with crawl_authority.current(source).publication_guard(fresh=True): + await crawl_publication.groups(source, expansion, started, maximum=membership_bound) + await mirror_store.record_listing( + source.org, + source.mirror, + source.source_id, + source.name, + started, + crawl_generation=source.crawl_generation, + ) + + +async def _gone( + authority: crawl_authority.Authority, + expansion: Expansion, + observations: dict[str, items.Listing], + file_id: str, + result: sync.TurnResult, + run: sync.Pass, +) -> bool | None: + """Page movement can omit a reached file: every eligible presenter must confirm its + absence, each ask one unit of the pass budget. With no eligible presenter left, + nobody reaches it and it retires. None when the budget ran out first.""" + if not expansion.people: + run.left -= 1 + return True + for person in expansion.people: + if run.spent(): + result.mark(sync.TurnMark.PASS_BOUND) + return None + run.left -= 1 + token = await authority.drive(person) + gone = await sync.file_gone(token, file_id, observations[person.id], result) + await token.check() + if not gone: + return gone + return True diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 8fee1583e68..21e34097e80 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -415,6 +415,16 @@ def _sync(src: KnowledgeSource, state: dict[str, str] | None) -> KnowledgeSource async def _details_allowed(src: KnowledgeSource) -> bool: if src.credential_mode == "shared": return True + if src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import require_operator + + with private_work(): + try: + # Deciding what a listing shows keeps the org's grant caches. + await require_operator(src, fresh=False) + return True + except Exception: # noqa: BLE001 — unverifiable crawl selectors remain private + return False if src.credential_mode != "connected" or not request_work.mark_mirrored(): return False from server.knowledge.app import connected_accounts as accounts @@ -450,6 +460,7 @@ async def handle_knowledge_source_list( credential_mode=s.credential_mode, access=s.access, owner_subject=s.owner_subject if details else "", + crawl_options=s.crawl_options if details and s.credential_mode == "crawl" else {}, items=s.items if details else [], include=_answered_include(s) if details else [], config=(domain.id_list_config(s) or {}) if details else {}, @@ -480,6 +491,7 @@ async def handle_knowledge_source_inspect( credential_mode=src.credential_mode, access=src.access, owner_subject=src.owner_subject if details else "", + crawl_options=src.crawl_options if details and src.credential_mode == "crawl" else {}, items=src.items if details else [], include=_answered_include(src) if details else [], config=(domain.id_list_config(src) or {}) if details else {}, @@ -528,6 +540,12 @@ async def handle_knowledge_source_add(input: KnowledgeSourceAddInput) -> Knowled _require_kind(kind) sent = [f for f in ("items", "links") if getattr(input, f) is not None] config, items = _registration(input, kind, sent) + if input.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import add as add_crawl + + return await add_crawl(input, name=name, kind=kind, config=config, items=items) + if input.crawl_options is not None: + raise BadConfigError("crawl_options requires crawl credential mode") if input.credential_mode == "connected": from server.knowledge.app.connected_sources import add @@ -604,7 +622,11 @@ async def sources_lease( # The TTL outlives the few reads and inserts of one write with room to spare (a # holder that dies is taken over after it). async with leases.holding( - _sources_lease_name(org, namespace), ttl_s=60.0, wait_s=wait_s, ch=ch + _sources_lease_name(org, namespace), + ttl_s=60.0, + wait_s=wait_s, + ch=ch, + settle_writes=True, ) as held: if not held: raise OverloadedError( @@ -683,6 +705,10 @@ async def handle_knowledge_source_check( input: KnowledgeSourceCheckInput, ) -> KnowledgeSourceCheckOutput: src = await _source_or_404(input.org, input.namespace, input.name) + if src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import check + + return await check(src) if src.credential_mode == "connected": from server.knowledge.app.connected_sources import check @@ -734,6 +760,10 @@ async def handle_knowledge_source_rotate( ) -> KnowledgeSourceRotateOutput: _require_self_service() src = await _source_or_404(input.org, input.namespace, input.name) + if src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import rotate + + return await rotate(src, input.credential) _require_served(src) _require_supported_recording_provider(src) if not input.credential.strip(): @@ -773,6 +803,12 @@ async def handle_knowledge_source_update( input: KnowledgeSourceUpdateInput, ) -> KnowledgeSourceUpdateOutput: src = await _source_or_404(input.org, input.namespace, input.name) + if src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import update + + return await update(src, input) + if input.crawl_options is not None: + raise BadConfigError("crawl_options requires crawl credential mode") if src.credential_mode == "connected": from server.knowledge.app.connected_sources import update @@ -1039,6 +1075,10 @@ async def handle_knowledge_source_remove( from server.knowledge.app.connected_sources import require_operator await require_operator(src) + elif src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import require_operator as crawl_operator + + await crawl_operator(src) elif not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError( "a namespace administrator is required for a shared source" @@ -1055,13 +1095,7 @@ async def handle_knowledge_source_remove( pending_delete = input.delete_documents if src.access == domain.MIRRORED_ACCESS: pending_delete = await _queue_retirement(src) - retired = dataclasses.replace( - src, - active=False, - credential_enc="", - secret_enc="", - pending_delete=pending_delete, - ) + retired = _retired(src, pending_delete) from server.knowledge.app.source_push import retire await retire(src) @@ -1077,6 +1111,10 @@ async def handle_knowledge_source_sync_now( from server.knowledge.app.connected_sources import require_operator await require_operator(src) + elif src.credential_mode == "crawl": + from server.knowledge.app.crawl_sources import require_operator as crawl_operator + + await crawl_operator(src) else: if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError("a namespace administrator is required for a shared source") @@ -1095,6 +1133,8 @@ async def handle_knowledge_source_sync_now( ) if fresh.credential_mode == "connected": await require_operator(fresh) + elif fresh.credential_mode == "crawl": + await crawl_operator(fresh) state = await _read_state(fresh) # A full request waiting (an update's) already asks for more: a plain sync now # leaves it as it is, neither narrowed nor started over. @@ -1159,18 +1199,23 @@ async def deactivate_namespace_sources(org: str, namespace: str) -> list[str]: for src in found: pending = await _queue_retirement(src) if src.access == domain.MIRRORED_ACCESS else False await retire(src) - await store.insert_source( - dataclasses.replace( - src, - active=False, - credential_enc="", - secret_enc="", - pending_delete=pending or src.pending_delete, - ) - ) + await store.insert_source(_retired(src, pending or src.pending_delete)) return sorted(src.name for src in found) +def _retired(src: KnowledgeSource, pending_delete: bool) -> KnowledgeSource: + """The inactive row a retired source leaves. It holds no credential, and a crawl's + selected addresses, approval and registrant go with it: retirement needs none.""" + retired = dataclasses.replace( + src, active=False, credential_enc="", secret_enc="", pending_delete=pending_delete + ) + if src.credential_mode == "crawl": + retired = dataclasses.replace( + retired, crawl_options={}, approval_enc="", registrant_subject="" + ) + return retired + + 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 @@ -1229,6 +1274,16 @@ async def _wait_until_free(lease_name: str, deadline: float, busy: str) -> None: def source_add_audit_subject(input: KnowledgeSourceAddInput, response: Any) -> dict[str, Any]: """What an add's audit row records: the source as stored, never the credential. `loom.audit_log` outlives the source and must hold no secret.""" + if input.credential_mode == "crawl": + return { + "org": input.org, + "namespace": input.namespace, + "name": response["name"], + "kind": response["kind"], + "credential_mode": "crawl", + "dry_run": input.dry_run, + "delegation": response["crawl_proof"], + } if input.credential_mode == "connected": return { "org": input.org, @@ -1252,6 +1307,15 @@ def source_add_audit_subject(input: KnowledgeSourceAddInput, response: Any) -> d def source_update_audit_subject(input: KnowledgeSourceUpdateInput, response: Any) -> dict[str, Any]: """Which source changed and the items added and removed, never the credential.""" + if response.get("crawl_proof") is not None: + return { + "org": input.org, + "namespace": input.namespace, + "name": response["name"], + "delegation": response["crawl_proof"], + "items_added": len(response.get("added") or []), + "items_removed": len(response.get("removed") or []), + } if request_work.mirror_marked(): return {"org": input.org, "namespace": input.namespace, "name": response["name"]} return { @@ -1266,7 +1330,10 @@ def source_update_audit_subject(input: KnowledgeSourceUpdateInput, response: Any def source_rotate_audit_subject(input: KnowledgeSourceRotateInput, response: Any) -> dict[str, Any]: """Which source's credential was replaced, never the credential.""" - return {"org": input.org, "namespace": input.namespace, "name": response["name"]} + subject = {"org": input.org, "namespace": input.namespace, "name": response["name"]} + if response.get("crawl_proof") is not None: + subject["delegation"] = response["crawl_proof"] + return subject __all__ = [ diff --git a/server/knowledge/domain/source_crawl.py b/server/knowledge/domain/source_crawl.py new file mode 100644 index 00000000000..b5ac379c36c --- /dev/null +++ b/server/knowledge/domain/source_crawl.py @@ -0,0 +1,217 @@ +"""Workspace selectors and complete crawl observations; identities remain provider-local.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any, Literal + +from server.knowledge.domain.access_list import ( + UNREAD, + AccessList, + from_drive_permissions, +) + +# not a setting: the selector wire protocol caps the total people at 2000. +MAX_PEOPLE = 2000 +_EMAIL = re.compile(r"[A-Za-z0-9._+\-]+@[A-Za-z0-9.\-]+") +type SubjectKind = Literal["person", "group"] + + +def email(value: Any) -> str: + if not isinstance(value, str) or len(value) > 512 or not _EMAIL.fullmatch(value): + raise ValueError("crawl address refused") + return value.lower() + + +@dataclass(frozen=True, repr=False) +class Subject: + kind: SubjectKind + email: str + + def __repr__(self) -> str: + return "Subject()" + + +@dataclass(frozen=True, repr=False) +class Options: + directory_subject: str + subjects: tuple[Subject, ...] + + def __repr__(self) -> str: + return "Options()" + + @classmethod + def parse(cls, value: Any) -> Options: + if not isinstance(value, dict) or set(value) != {"directory_subject", "subjects"}: + raise ValueError("crawl options refused") + entries = value["subjects"] + if not isinstance(entries, list) or not 1 <= len(entries) <= MAX_PEOPLE: + raise ValueError("crawl subjects refused") + selected: list[Subject] = [] + for entry in entries: + if ( + not isinstance(entry, dict) + or set(entry) != {"type", "email"} + or entry["type"] not in ("person", "group") + ): + raise ValueError("crawl subject refused") + subject = Subject(entry["type"], email(entry["email"])) + if subject in selected: + raise ValueError("duplicate crawl subject") + selected.append(subject) + return cls(email(value["directory_subject"]), tuple(selected)) + + def stored(self) -> dict[str, Any]: + return { + "directory_subject": self.directory_subject, + "subjects": [{"type": s.kind, "email": s.email} for s in self.subjects], + } + + +@dataclass(frozen=True, repr=False) +class Person: + customer: str + id: str + email: str + aliases: tuple[str, ...] + + def __repr__(self) -> str: + return "Person()" + + @property + def addresses(self) -> frozenset[str]: + return frozenset((self.email, *self.aliases)) + + +@dataclass(frozen=True, repr=False) +class Expansion: + customer: str + people: tuple[Person, ...] + # Each selected or nested group has the entire eligible transitive membership. + groups: tuple[tuple[str, tuple[str, ...]], ...] + + def __repr__(self) -> str: + return "Expansion()" + + +def crawl_access(person: Person, file: dict[str, Any]) -> AccessList: + """Listing as a person grants nothing without ownership or an explicit permission.""" + raw = file.get("permissions") + if raw is not None and (not isinstance(raw, list) or any(not isinstance(p, dict) for p in raw)): + return UNREAD + parsed = from_drive_permissions(raw) + owners = file.get("owners") + owned = isinstance(owners, list) and any( + isinstance(owner, dict) + and owner.get("me") is True + and isinstance(owner.get("emailAddress"), str) + and owner["emailAddress"].lower() in person.addresses + for owner in owners + ) + explicit = not parsed.unread and bool(person.addresses.intersection(parsed.emails)) + if parsed.unread: + return AccessList(emails=(person.email,)) if owned else UNREAD + # Keep actual provider ACLs, but do not invent an entry for a link-only reader. + addresses = set(parsed.emails) + if owned or explicit: + addresses.add(person.email) + return AccessList( + emails=tuple(addresses), groups=parsed.groups, domains=parsed.domains, anyone=parsed.anyone + ) + + +def union_access(left: AccessList, right: AccessList) -> AccessList: + """Only positive observations widen a complete cycle's permission union.""" + if left.unread: + return right + if right.unread: + return left + if left.owner or right.owner: + raise ValueError("a crawl has no connected owner") + return AccessList( + emails=(*left.emails, *right.emails), + groups=(*left.groups, *right.groups), + domains=(*left.domains, *right.domains), + anyone=left.anyone or right.anyone, + ) + + +@dataclass(frozen=True, repr=False) +class File: + id: str + metadata: dict[str, Any] + access: AccessList + presenters: tuple[str, ...] + + def __repr__(self) -> str: + return "File()" + + +_REVISION_FIELDS = ("version", "modifiedTime", "md5Checksum", "mimeType", "webViewLink", "name") + + +def _revision(metadata: dict[str, Any]) -> tuple[str, int]: + """A file's revision order: Drive's modified time, then its version counter.""" + version = metadata.get("version") + counter = int(version) if isinstance(version, str) and version.isdigit() else -1 + return str(metadata.get("modifiedTime") or ""), counter + + +@dataclass(repr=False) +class Union: + """Absence is meaningful only after every admitted person's full listing finishes.""" + + expansion: Expansion + maximum_files: int + _done: set[str] = field(default_factory=set, init=False, repr=False) + _files: dict[str, File] = field(default_factory=dict, init=False, repr=False) + + def __repr__(self) -> str: + return "Union()" + + def __post_init__(self) -> None: + if type(self.maximum_files) is not int or self.maximum_files <= 0: + raise ValueError("crawl file bound refused") + + def add(self, person: Person, files: list[dict[str, Any]], *, whole: bool) -> None: + if person not in self.expansion.people or person.id in self._done or not whole: + raise ValueError("crawl listing is incomplete or changed") + observed: set[str] = set() + next_files = dict(self._files) + for file in files: + identifier = file.get("id") + if not isinstance(identifier, str) or not identifier or identifier in observed: + raise ValueError("crawl file identity is ambiguous") + if not any( + isinstance(file.get(k), str) and file[k] for k in ("version", "modifiedTime") + ): + raise ValueError("crawl file revision is unavailable") + observed.add(identifier) + access = crawl_access(person, file) + previous = next_files.get(identifier) + # A single publication must not pair one revision's text with another's ACL, so a + # file edited while the people are listed keeps only the newest revision and the + # access of those who saw it; an older revision's observation is dropped. + if previous is None or _revision(file) > _revision(previous.metadata): + next_files[identifier] = File(identifier, dict(file), access, (person.id,)) + elif _revision(file) < _revision(previous.metadata): + continue + elif any(previous.metadata.get(k) != file.get(k) for k in _REVISION_FIELDS): + raise ValueError("crawl file changed during its union") + else: + next_files[identifier] = File( + identifier, + previous.metadata, + union_access(previous.access, access), + (*previous.presenters, person.id), + ) + if len(next_files) > self.maximum_files: + raise ValueError("crawl union exceeds its file bound") + self._files = next_files + self._done.add(person.id) + + def complete(self) -> tuple[File, ...]: + if self._done != {person.id for person in self.expansion.people}: + raise ValueError("crawl union is incomplete") + return tuple(self._files[key] for key in sorted(self._files)) diff --git a/server/knowledge/domain/sources.py b/server/knowledge/domain/sources.py index 7686cb3b06f..899242dfbd4 100644 --- a/server/knowledge/domain/sources.py +++ b/server/knowledge/domain/sources.py @@ -130,6 +130,13 @@ class KnowledgeSource: # Connected authority is explicit; created_by remains audit attribution only. owner_subject: str = "" connection_id: str = "" + # Crawl authority is independent of connected ownership and audit attribution. + crawl_options: dict[str, Any] = field(default_factory=dict) + registrant_subject: str = "" + approval_enc: str = "" + crawl_generation: str = "" + crawl_customer_id: str = "" + crawl_credential_hash: str = "" created_by: str = "" active: bool = True # On an inactive row: an admin asked for the source's documents to be retired. @@ -572,7 +579,7 @@ def mirror_synced(src: KnowledgeSource) -> bool: """Whether the sync worker writes `src` into its namespace's mirror: a mirrored folder-store source or a person's connected page/project source.""" return src.access == MIRRORED_ACCESS and ( - src.kind == "gdrive" + (src.kind == "gdrive" and src.credential_mode in {"shared", "connected", "crawl"}) or (src.credential_mode == "connected" and src.kind in {"notion", "linear"}) ) diff --git a/server/knowledge/store/crawl_publication.py b/server/knowledge/store/crawl_publication.py new file mode 100644 index 00000000000..8d245acd89f --- /dev/null +++ b/server/knowledge/store/crawl_publication.py @@ -0,0 +1,63 @@ +"""Full source-scoped membership replacement, written only under crawl publication guards.""" + +from __future__ import annotations + +from datetime import datetime + +from server.core.ch import own_write_reads, query_tag +from server.core.repo_base import _CHClient, _default_client +from server.core.versions import next_version +from server.knowledge.domain.source_crawl import Expansion +from server.knowledge.domain.sources import KnowledgeSource + +GROUPS = "loom.knowledge_group_members" + + +async def groups( + source: KnowledgeSource, + expansion: Expansion, + started: datetime, + *, + maximum: int, + ch: _CHClient | None = None, +) -> None: + with query_tag("knowledge.crawl.groups"): + if type(maximum) is not int or maximum <= 0 or not source.mirror: + raise ValueError("crawl membership bounds refused") + client = ch or _default_client() + params = {"org": source.org, "ns": source.mirror, "id": source.source_id} + with own_write_reads(): + # Live groups only: a tombstone stays as written and does not count toward the bound. + prior = await client.query_all( + f"SELECT `group` FROM {GROUPS} FINAL WHERE org = {{org:String}} " + "AND namespace = {ns:String} AND source_id = {id:String} AND NOT deleted " + "LIMIT {limit:UInt32}", + params={**params, "limit": maximum + 1}, + ) + found = dict(expansion.groups) + names = set(found) | {str(row["group"]) for row in prior} + if len(prior) > maximum or len(names) > maximum: + raise ValueError("crawl membership bound exceeded") + if not names: + return + # One version past every row of this source is past each group's own newest row. + version = await next_version( + client, + GROUPS, + {"org": source.org, "namespace": source.mirror, "source_id": source.source_id}, + ) + rows = [ + { + "org": source.org, + "namespace": source.mirror, + "source_id": source.source_id, + "group": group, + "name": source.name, + "members": list(found.get(group, ())), + "read_at": started, + "deleted": group not in found, + "version": version, + } + for group in sorted(names) + ] + await client.insert(GROUPS, rows) diff --git a/server/knowledge/store/mirrors.py b/server/knowledge/store/mirrors.py index 1d9211b02f2..3bc362bcf53 100644 --- a/server/knowledge/store/mirrors.py +++ b/server/knowledge/store/mirrors.py @@ -53,6 +53,7 @@ async def record_listing( name: str, started_at: datetime, *, + crawl_generation: str = "", ch: _CHClient | None = None, ) -> None: """The start of a mirrored source's last complete listing, written once every list @@ -63,6 +64,7 @@ async def record_listing( "source_id": source_id, "name": name, "started_at": started_at, + "crawl_generation": crawl_generation, } await (ch or _default_client()).insert(LISTINGS, [row]) diff --git a/server/knowledge/store/source_access.py b/server/knowledge/store/source_access.py index 00adc82a30d..fcc0c8893d1 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -61,7 +61,8 @@ async def listings( if not pairs: return [] return await (ch or _default_client()).query_all( - "SELECT namespace, source_id, started_at FROM loom.knowledge_source_listings FINAL " + "SELECT namespace, source_id, started_at, crawl_generation " + "FROM loom.knowledge_source_listings FINAL " "WHERE org = {org:String} AND (namespace, source_id) " "IN {pairs:Array(Tuple(String, String))} " "LIMIT {limit:UInt32}", diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 3a39f327ca6..afa5258c71a 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -2,14 +2,15 @@ each source's sync state (a `loom.code_index_state` row under `knowledge_source:`). -Both tables are ReplacingMergeTree(version): every write is a full version row -and every read uses FINAL. A registry row changes only on add, update, rotate, remove -and the retirement when its namespace goes (`code.repo.remove`, `namespace.delete`, +Both tables are ReplacingMergeTree(version): every write is a full version row and every +read uses FINAL. A registry row changes only on add, update, rotate, remove and the +retirement when its namespace goes (`code.repo.remove`, `namespace.delete`, `collection.delete`, the erasure step `knowledge_sources.retire`), all under the -namespace's lease, and on `loom secrets reseal`, the one writer outside it: it +namespace's lease, and on `loom secrets reseal`, the one writer outside it. The reseal writes the row it read at version + 1, so any later write wins while the ClickHouse -servers' clocks differ by less than the time between the two writes. The sync state is -a separate row, so a sync never rewrites the row that holds the credential. +servers' clocks differ by less than the time between the two writes; a crawl approval is +resealed in place across its raw versions, under the namespace's lease. The sync state +is a separate row, so a sync never rewrites the row that holds the credential. A source a build without items can read (`id_list_config` is not None) is written as that build writes it, `kind`, `config_json` and the credential in `credential_enc`, @@ -26,9 +27,11 @@ from datetime import datetime from typing import Any, Literal, NamedTuple +from server.core.ch import own_write_reads from server.core.datetimes import naive_utc_now_seconds from server.core.repo_base import _CHClient, _default_client from server.knowledge.domain.live_chunks import has_live_chunks_sql +from server.knowledge.domain.source_crawl import Options from server.knowledge.domain.sources import ( NAMESPACE_ACCESS, SYNC_WORKER_ACTOR, @@ -53,11 +56,132 @@ _COLUMNS = ( "org, namespace, name, source_id, kind, source_kind, config_json, items_json, " "credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, " + "options_json, registrant_subject, approval_enc, crawl_generation, " + "crawl_customer_id, crawl_credential_hash, " "created_by, active, pending_delete, created_at, " "updated_at" ) +async def crawl_approval_page( + after: tuple[str, str, str], *, maximum: int, ch: _CHClient | None = None +) -> list[tuple[str, str, str]]: + if type(maximum) is not int or maximum <= 0: + raise ValueError("crawl approval page bound refused") + with own_write_reads(): + rows = await (ch or _default_client()).query_all( + f"SELECT DISTINCT org, namespace, name FROM {TABLE} " + "WHERE (org, namespace, name) > {after:Tuple(String, String, String)} " + "AND approval_enc != '' ORDER BY org, namespace, name LIMIT {limit:UInt32}", + params={"after": after, "limit": maximum}, + ) + keys = [(str(row["org"]), str(row["namespace"]), str(row["name"])) for row in rows] + if len(keys) > maximum or keys != sorted(set(keys)) or any(key <= after for key in keys): + raise RuntimeError("crawl_approval_page_unverified") + return keys + + +async def crawl_approval_values( + org: str, + namespace: str, + name: str, + *, + maximum: int, + ch: _CHClient, +) -> list[dict[str, Any]]: + rows = await ch.query_all( + f"SELECT DISTINCT toString(source_id) AS source_id, approval_enc FROM {TABLE} " + "WHERE org = {org:String} AND namespace = {ns:String} AND name = {name:String} " + "AND credential_mode = 'crawl' AND approval_enc != '' LIMIT {limit:UInt32}", + params={"org": org, "ns": namespace, "name": name, "limit": maximum + 1}, + ) + if len(rows) > maximum: + raise RuntimeError("crawl_approval_history_bound") + return rows + + +async def reseal_crawl_approval( + org: str, + namespace: str, + source_id: str, + before: str, + after: str, + *, + ch: _CHClient, +) -> None: + where = ( + "org = {org:String} AND namespace = {ns:String} AND source_id = {id:String} " + "AND credential_mode = 'crawl' AND approval_enc = {old:String}" + ) + params = {"org": org, "ns": namespace, "id": source_id, "old": before, "new": after} + await ch.execute( + f"ALTER TABLE loom.knowledge_sources UPDATE approval_enc = {{new:String}} WHERE {where}", + params=params, + settings={"mutations_sync": 2}, + ) + residue = await ch.query_one(f"SELECT count() AS n FROM {TABLE} WHERE {where}", params=params) + if residue is None or residue["n"]: + raise RuntimeError("crawl_approval_reseal_residue") + + +async def crawl_history( + org: str, *, maximum: int, ch: _CHClient | None = None +) -> list[KnowledgeSource]: + """Raw registrations include retired sources and earlier names, not only FINAL rows.""" + if not isinstance(org, str) or not org or type(maximum) is not int or maximum <= 0: + raise ValueError("crawl history scope refused") + with own_write_reads(): + rows = await (ch or _default_client()).query_all( + f"SELECT DISTINCT {_COLUMNS} FROM {TABLE} WHERE org = {{org:String}} " + "AND credential_mode = 'crawl' " + "ORDER BY namespace, name, source_id, updated_at LIMIT {limit:UInt32}", + params={"org": org, "limit": maximum + 1}, + ) + if len(rows) > maximum or any( + row["org"] != org or row["credential_mode"] != "crawl" for row in rows + ): + raise RuntimeError("crawl_history_unverified") + return [_source(row) for row in rows] + + +async def crawl_orgs(*, maximum: int, ch: _CHClient) -> list[str]: + """Every org with a crawl registration in raw history, retired ones included.""" + if maximum <= 0: + raise RuntimeError("crawl_restore_inventory_unverified") + with own_write_reads(): + rows = await ch.query_all( + f"SELECT DISTINCT org FROM {TABLE} WHERE credential_mode = 'crawl' " + "ORDER BY org LIMIT {limit:UInt32}", + params={"limit": maximum + 1}, + ) + orgs = [row["org"] for row in rows] + if ( + len(orgs) > maximum + or orgs != sorted(set(orgs)) + or any(not isinstance(org, str) or not org or "\0" in org for org in orgs) + ): + raise RuntimeError("crawl_restore_inventory_unverified") + return orgs + + +async def invalidate_crawl_approvals(org: str, *, ch: _CHClient) -> None: + """A restore never reactivates historical delegated source authority: every raw + crawl version of the org loses its approval and generation.""" + where = "org = {org:String} AND credential_mode = 'crawl'" + stale = " AND (active OR approval_enc != '' OR crawl_generation != '')" + await ch.execute( + "ALTER TABLE loom.knowledge_sources UPDATE " + f"active = 0, approval_enc = '', crawl_generation = '' WHERE {where}", + params={"org": org}, + settings={"mutations_sync": 2}, + ) + residue = await ch.query_one( + f"SELECT count() AS n FROM {TABLE} WHERE {where}{stale}", params={"org": org} + ) + if residue is None or residue["n"]: + raise RuntimeError("crawl_restore_approval_residue") + + def _items(raw: str) -> list[dict[str, Any]]: """The stored items, or [] (the source's config names them).""" try: @@ -67,6 +191,19 @@ def _items(raw: str) -> list[dict[str, Any]]: return [i for i in data if isinstance(i, dict)] if isinstance(data, list) else [] +def _crawl_options(row: dict[str, Any]) -> dict[str, Any]: + if row.get("credential_mode") != "crawl": + return {} + raw = str(row.get("options_json") or "{}") + try: + return Options.parse(json.loads(raw)).stored() + except ValueError: + # A retired row holds none (this build's retirement writes {}, as did a build + # without crawl options); crawl authority refuses a source whose options do not + # parse. + return {} + + def _source(row: dict[str, Any]) -> KnowledgeSource: created = row.get("created_at") updated = row.get("updated_at") @@ -87,6 +224,12 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: credential_mode=str(row.get("credential_mode") or "shared"), owner_subject=str(row.get("owner_subject") or ""), connection_id=str(row.get("connection_id") or ""), + crawl_options=_crawl_options(row), + registrant_subject=str(row.get("registrant_subject") or ""), + approval_enc=str(row.get("approval_enc") or ""), + crawl_generation=str(row.get("crawl_generation") or ""), + crawl_customer_id=str(row.get("crawl_customer_id") or ""), + crawl_credential_hash=str(row.get("crawl_credential_hash") or ""), created_by=str(row.get("created_by") or ""), active=bool(row.get("active")), pending_delete=bool(row.get("pending_delete")), @@ -275,6 +418,15 @@ async def insert_source(src: KnowledgeSource, *, ch: _CHClient | None = None) -> writing replica's: the lease-serialized writes stay ordered while those clocks differ by less than the lease's handoff between writes.""" now = naive_utc_now_seconds() + # A live crawl source's options are written strictly. A retired one an older build + # wrote has none, and its retirement or restore rewrites it with none. + retired_without = not src.active and not src.crawl_options + stored = ( + Options.parse(src.crawl_options).stored() + if src.credential_mode == "crawl" and not retired_without + else {} + ) + options = json.dumps(stored, sort_keys=True, separators=(",", ":")) row = { "org": src.org, "namespace": src.namespace, @@ -290,6 +442,12 @@ async def insert_source(src: KnowledgeSource, *, ch: _CHClient | None = None) -> "credential_mode": src.credential_mode, "owner_subject": src.owner_subject, "connection_id": src.connection_id, + "options_json": options, + "registrant_subject": src.registrant_subject, + "approval_enc": src.approval_enc, + "crawl_generation": src.crawl_generation, + "crawl_customer_id": src.crawl_customer_id, + "crawl_credential_hash": src.crawl_credential_hash, "created_by": src.created_by, "active": src.active, "pending_delete": src.pending_delete, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index da8d5fa3247..b66441829d8 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2519,6 +2519,20 @@ class KnowledgeSettings(BaseModel): knowledge_connected_registry_scan_limit: int = Field(default=4096, ge=1) # Registrations per page during root-secret resealing. knowledge_connected_registry_page_size: int = Field(default=256, ge=1, le=4096) + # Bytes read from one delegated Directory or OAuth response; larger responses refuse. + knowledge_crawl_directory_max_response_bytes: int = Field(default=1024 * 1024, ge=1024) + # Directory membership pages across the entire expansion, including nested groups. + knowledge_crawl_directory_max_pages: int = Field(default=256, ge=1) + # Groups across one complete crawl expansion; the total-person ceiling stays fixed. + knowledge_crawl_max_groups: int = Field(default=2000, ge=1) + # Distinct files across every person's complete listing; a larger union publishes nothing. + knowledge_crawl_max_files: int = Field(default=10000, ge=1) + # Crawl registry rows one reseal or restore reads: the orgs, each org's raw source + # versions, the source names a reseal pages through in all, and each name's + # approvals. A larger set refuses instead of doing partial work. + knowledge_crawl_registry_scan_limit: int = Field(default=4096, ge=1) + # Crawl sources per root-secret reseal page. + knowledge_crawl_registry_page_size: int = Field(default=256, ge=1, le=4096) # Seconds one connected-account OAuth request may take, including its response. # The caller's remaining deadline can shorten this bound. knowledge_connected_oauth_timeout_s: float = Field(default=30.0, gt=0) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 6acd2d29893..879b00afc36 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -650,7 +650,6 @@ 49e68b2fe0ca ALTER TABLE loom.memory_chunk_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 49f3550b2531 SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, agent, evidence FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND 4a071fdc1ffe SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: -4a39b257adff -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou 4a4a4fc0989b ALTER TABLE loom.knowledge_ingest_cancels DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s 4a536b32504b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 4aeabb5d4edf SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? @@ -1012,7 +1011,6 @@ 75554c47d6b1 SELECT count() AS n FROM loom.memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (namespace, t), tags), {pa 7578a5e11226 SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} 7584931ee488 SELECT c.category_id AS category_id, count() AS rows FROM (SELECT memory_key, category_id FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NU -7585095cfe72 SELECT ? AS x FROM loom.scim_users FINAL WHERE id = {id:String} AND active = ? 7588988984a6 ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 75cf782b44f3 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l 75d1ab9d987d SELECT memory_key, memory_type, content_excerpt, ? - cosineDistance(embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(temporal_anchor, toDateTime(?))) AS temporal_anchor, temporal_confi @@ -1069,7 +1067,6 @@ 7b240e4ee7d6 SELECT tier, edge_kind, to_symbol_id, from_symbol_id, path, line, argMax(from_qualified_name, version) AS from_qualified_name, argMax(to_qualified_name, version) AS to_qualified_name, argMax(confidenc 7b29c9cf5ab6 SELECT org, namespace, agent, user_id, thread_id, title, metadata, run_id, created_at, updated_at, tombstoned_at FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace = {scope:St 7b31f76d8d46 SELECT entity, max(degree) AS degree FROM loom.entity_degree WHERE org = {o:String} AND namespace = {n:String} GROUP BY entity ORDER BY degree DESC, entity LIMIT {lim:UInt32} -7b5336f3029c SELECT namespace, source_id, started_at FROM loom.knowledge_source_listings FINAL WHERE org = {org:String} AND (namespace, source_id) IN {pairs:Array(Tuple(String, String))} LIMIT {limit:UInt32} 7b590beeb043 SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND namespace = {ns:String} AND ? 7b6e39c58a8e SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 7b81be391890 SELECT count() AS n FROM loom.memory_versions WHERE org = {org:String} AND user_id = {uid:String} @@ -1110,7 +1107,6 @@ 7e34abf20d24 ALTER TABLE loom.memory_record_versions DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_syn 7e726e6f73c0 SELECT model, count() AS turns, uniqExact(session_id) AS sessions, sum(toUInt64(input_tokens)) AS input_tokens, sum(toUInt64(cache_read_tokens)) AS cache_read_tokens, sum(toUInt64(cache_creation_5m_to 7ebae0c83ac1 SELECT symbol_id, qualified_name, name, signature, path, start_line, end_line, tier, kind, toString(indexed_commit) AS extent_commit FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace -7eccab6dfda3 SELECT org, namespace, name, source_id, kind, source_kind, config_json, items_json, credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, created_by, active, pending_delet 7ed9e5f6ceb3 ALTER TABLE loom.memory_chunk_sources UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasu 7eea2ee7caf9 SELECT memory_key, (status != ? OR tombstoned_at IS NOT NULL OR redacted_at IS NOT NULL) AS taken_out FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:Str 7ef1d533ac81 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -1579,6 +1575,7 @@ b12d34885e03 ALTER TABLE loom.working_memory UPDATE tombstoned_at = {now:DateTim b14f5bc32c83 SELECT memory_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_id IN {ids:Array(UUID)} AND tombstoned_at IS NULL b1605e1b3322 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ b1686849396a ALTER TABLE loom.memory_record_conflicts UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND (prior_record_id IN {ids:Array(UUID)} OR incoming_record_id IN {i +b16d9d5df37e SELECT ? AS x FROM loom.scim_users FINAL WHERE id IN {ids:Array(String)} AND active = ? LIMIT ? b17835f57d67 ALTER TABLE loom.working_memory DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? b18bb1fa8a4f SELECT namespace, kind, owner_email, description, tags, active, conversation_logging_enabled, capture_generation_io, coverage_sweep, consolidation_enabled, daily_cost_cap_usd, daily_user_cost_cap_usd, b1931bf6e5a4 SELECT DISTINCT owner_email, org FROM loom.namespaces FINAL WHERE contact_email = {email:String} AND active = ? AND owner_email != ? AND (password_hash = ? OR (org, namespace) IN ( SELECT org, namespa @@ -1741,6 +1738,7 @@ c1f9002b82f4 SELECT chunk_id, path, scope, kind, start_line, end_line, content, c1fc173ac609 SELECT pr_number, title, author, merged_at, files, linked_issues, (match(title, {revert_re:String}) OR positionCaseInsensitive(body_excerpt, ?) > ? ) AS is_revert FROM loom.code_pr_history FINAL WHERE c23ce268d788 SELECT DISTINCT start_line, end_line, content, kind, scope, symbol_ids, toString(indexed_commit) AS indexed_commit FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND c23f3a6975c8 ALTER TABLE loom.memory_embeddings UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND scope = ? AND (namespace, memory_key) IN {keys:Array(Tuple(String, Stri +c25cec2435d6 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou c266319cd4ad SELECT count() AS n FROM loom.conversation_threads FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL c26ddee98bc8 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ c271f531ca3b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ @@ -2052,6 +2050,7 @@ df886269fbb5 SELECT org, namespace FROM loom.namespace_grants FINAL WHERE role = df9a592b3176 SELECT min(version) AS v FROM loom.memory_versions WHERE org = {org:String} AND namespace = {ns:String} dfab46389b75 SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND namespace = {ns:String} AND ? dfb389c3eaaa SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL +dfbb9c9e86b1 SELECT org, namespace, name, source_id, kind, source_kind, config_json, items_json, credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, options_json, registrant_subject, e01b3f138368 ALTER TABLE loom.memory_ask_precedents DELETE WHERE (org = {org:String} AND hasAny(arrayConcat(window_keys, cited_keys), {keys:Array(String)})) AND ({erasure_mutation_tag:String} = {erasure_mutation_t e026c7f5b6eb SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { e05f46166d69 SELECT org, namespace, agent, user_id, session_id, embedding_model, version, summary_text, key_facts, derived_from, at FROM (SELECT org, namespace, agent, user_id, session_id, embedding_model, version @@ -2328,6 +2327,7 @@ fe4fdc7e30f7 SELECT memory_id, org, namespace, agent, user_id, session_id, memor fe7a96c7e2d2 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ fe9b04fb1f69 SELECT count() AS n FROM loom.entity_edges WHERE org = {org:String} AND namespace IN {ns:Array(String)} fe9df4ed378d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +fec00ca7180d SELECT namespace, source_id, started_at, crawl_generation FROM loom.knowledge_source_listings FINAL WHERE org = {org:String} AND (namespace, source_id) IN {pairs:Array(Tuple(String, String))} LIMIT {l fed00127661d SELECT org, namespace, agent, user_id, thread_id, msg_id, role, content, reasoning, metadata, tokens, run_id, ts, is_saved, saved_at, tombstoned_at, length(content) + length(reasoning) + length(metada fef350e42e77 ALTER TABLE loom.learnings_queue DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? ff00b5b19dc0 SELECT count() AS n, max(tombstoned_at) AS gone FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND thread_id = {tid:String} AND msg_id = {mid:S diff --git a/tests/integration/crawl_native_privacy.py b/tests/integration/crawl_native_privacy.py new file mode 100644 index 00000000000..ab041644a70 --- /dev/null +++ b/tests/integration/crawl_native_privacy.py @@ -0,0 +1,410 @@ +"""Native crawl publication and HTTP ACL isolation on an exclusively owned backend. + +Run this module explicitly in the crawl-native-privacy workflow. The full app and +inline workers share one process; ordinary integration jobs use an external server. +Verified SSO contacts are trusted fixture inputs, not enrollment coverage. Bearers are +minted here with a session id, which a mirrored reader needs and `mint_test_token` +does not set. +""" + +from __future__ import annotations + +import json +import os +import uuid +from collections.abc import AsyncIterator, Iterator +from datetime import UTC, datetime +from typing import Any +from urllib.parse import parse_qs, unquote + +import httpx +import jwt +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from tests.integration._eventually import eventually +from tests.integration._resources import unique_org + +if not os.environ.get("LOOM_CH_HOST"): + pytest.skip("LOOM_CH_HOST not set", allow_module_level=True) + + +# This process exercises normal boot instead of the integration suite's in-process +# shortcuts for tests that do not start an app. +@pytest.fixture(autouse=True) +def _seed_test_api_key() -> Iterator[None]: + yield + + +@pytest.fixture(autouse=True) +def _code_registry_read() -> Iterator[None]: + yield + + +@pytest.fixture(autouse=True) +def _quick_intent_marks() -> Iterator[None]: + yield + + +@pytest.fixture +async def provider(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[dict[str, Any]]: + from server.clients import gdrive + from server.clients import google_workspace as google + + private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = private.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ).decode() + canary = uuid.uuid4().hex + content = f"# Quarterly renewal plan\n\nScope owners and release readiness. {canary}\n" + directory = "directory@example.test" + reader = "reader-a@example.test" + outside_reader = "reader-c@example.test" + file_id = "native-privacy-document" + metadata = { + "id": file_id, + "version": "1", + "name": "Quarterly renewal plan", + "mimeType": "application/vnd.google-apps.document", + "modifiedTime": datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"), + "webViewLink": f"https://docs.google.com/document/d/{file_id}", + "permissions": [ + {"type": "user", "role": "reader", "emailAddress": address} + for address in (reader, outside_reader) + ], + "owners": [{"me": True, "emailAddress": reader}], + } + scopes: set[str] = set() + exported: list[str] = [] + unexpected: list[str] = [] + + async def handle(request: httpx.Request) -> httpx.Response: + if request.url.host == "oauth2.googleapis.com": + assert request.method == "POST" and request.url.path == "/token" + form = parse_qs(request.content.decode()) + assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] + claims = jwt.decode( + form["assertion"][0], + private.public_key(), + algorithms=["RS256"], + audience="https://oauth2.googleapis.com/token", + ) + assert claims["iss"] == "service@example.test" + scope = claims["scope"] + scopes.add(scope) + if scope in {s.value for s in gdrive.WriteScope}: + assert claims["sub"] == directory + return httpx.Response(400, json={"error": "unauthorized_client"}) + assert scope in {s.value for s in gdrive.ReadScope} + assert claims["sub"] in {directory, reader} + drive = claims["sub"] == reader + assert not drive or scope == gdrive.ReadScope.DRIVE.value + return httpx.Response( + 200, + json={ + "access_token": "native-drive" if drive else "native-directory", + "token_type": "Bearer", + "expires_in": 3600, + "scope": scope, + }, + ) + assert request.method == "GET" + if request.url.host == "admin.googleapis.com": + assert request.headers["authorization"] == "Bearer native-directory" + assert request.url.path.startswith("/admin/directory/v1/users/") + key = unquote(request.url.path.rsplit("/", 1)[1]) + assert key in {directory, reader, "provider-person"} + is_directory = key == directory + return httpx.Response( + 200, + json={ + "id": "provider-directory" if is_directory else "provider-person", + "primaryEmail": directory if is_directory else reader, + "aliases": [], + "customerId": "native-workspace", + "suspended": False, + "archived": False, + }, + ) + assert request.url.host == "www.googleapis.com", request.url.host + assert request.headers["authorization"] == "Bearer native-drive" + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": [metadata], "incompleteSearch": False}) + if request.url.path == f"/drive/v3/files/{file_id}": + return httpx.Response(200, json=metadata) + assert request.url.path == f"/drive/v3/files/{file_id}/export", request.url.path + exported.append(file_id) + return httpx.Response(200, text=content) + + async def dispatch(request: httpx.Request) -> httpx.Response: + try: + return await handle(request) + except AssertionError: + unexpected.append(f"{request.method} {request.url.host}{request.url.path}") + raise + + async with httpx.AsyncClient(transport=httpx.MockTransport(dispatch)) as vendor: + monkeypatch.setattr(google, "get_client", lambda: vendor) + monkeypatch.setattr(gdrive, "get_client", lambda: vendor) + yield { + "canary": canary, + "content": content, + "reader": reader, + "outside_reader": outside_reader, + "directory": directory, + "scopes": scopes, + "exported": exported, + "unexpected": unexpected, + "credential": json.dumps( + { + "type": "service_account", + "client_email": "service@example.test", + "private_key": pem, + } + ), + } + assert not unexpected, unexpected + + +@pytest.fixture +async def native_app(provider: dict[str, Any]) -> AsyncIterator[httpx.AsyncClient]: + from server.main import app + + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + + async def ready() -> bool: + assert not provider["unexpected"], provider["unexpected"] + result = await client.get("/v1/health/ready") + assert result.status_code in {200, 503}, result.text + return result.status_code == 200 + + await eventually(ready, max_wait=60, description="normal app readiness") + yield client + + +def _bearer(subject: str, org: str, namespaces: list[str], role: str) -> str: + from server.auth.jwt import mint_token, verify_token + from server.auth.reader_identity import reader_subject + + bearer = mint_token( + subject, + org, + namespaces, + [role], + is_service_account=False, + session_id=uuid.uuid4().hex, + ttl_seconds=1800, + ) + verified = verify_token(bearer) + assert verified.subject == subject + assert reader_subject(verified) == subject + return bearer + + +async def _post( + client: httpx.AsyncClient, bearer: str, op: str, body: dict[str, Any] +) -> httpx.Response: + # Every reader here is a client that protects session content, so a refusal + # can only come from the document ACL or the tenant scope. + headers = {"Authorization": f"Bearer {bearer}", "X-Loom-Session-Protection": "v1"} + return await client.post(f"/v1/{op}", json=body, headers=headers) + + +@pytest.fixture +async def identities(native_app: httpx.AsyncClient, provider: dict[str, Any]) -> dict[str, Any]: + from server.auth.reader_identity import resolve_reader + from server.core.ch import get_client, set_query_tag + + set_query_tag("test.crawl_native_privacy.identities") + ch = get_client() + org, other_org = unique_org("crawl-native"), unique_org("crawl-other") + # Account login handles are distinct from gateway grant principals (user:*). + subjects = { + "admin": "registrant", + "a": "reader-a", + "b": "reader-b", + "c": "reader-c", + } + contacts = { + "admin": "registrant@example.test", + "a": provider["reader"], + "b": "reader-b@example.test", + "c": provider["outside_reader"], + } + # These actual rows represent already-verified upstream SSO contact evidence. + rows = [ + { + "org": org, + "namespace": f"identity-{name}", + "owner_email": subjects[name], + "contact_email": contact, + "password_hash": "", + "active": True, + } + for name, contact in contacts.items() + ] + rows.append( + { + "org": other_org, + "namespace": "identity-a", + "owner_email": subjects["a"], + "contact_email": contacts["a"], + "password_hash": "", + "active": True, + } + ) + await ch.insert("loom.namespaces", rows) + for row in rows: + identity = await resolve_reader(row["org"], row["owner_email"]) + assert identity is not None and identity.subject == row["owner_email"] + assert identity.emails == frozenset({row["contact_email"]}) + return {"org": org, "other_org": other_org, "subjects": subjects, "contacts": contacts} + + +@pytest.fixture +async def registered_crawl( + native_app: httpx.AsyncClient, identities: dict[str, Any], provider: dict[str, Any] +) -> None: + from server.core.ch import set_query_tag + + set_query_tag("test.crawl_native_privacy.registration") + org, subjects = identities["org"], identities["subjects"] + admin = _bearer(subjects["admin"], org, ["*"], "org_admin") + for namespace in ("col-crawl-documents", "col-other-documents"): + response = await _post( + native_app, admin, "collection.create", {"org": org, "namespace": namespace} + ) + assert response.status_code == 200, response.text + for who, namespace in ( + ("a", "col-crawl-documents"), + ("b", "col-crawl-documents"), + ("c", "col-other-documents"), + ): + response = await _post( + native_app, + admin, + "grants.create", + {"org": org, "namespace": namespace, "subject": subjects[who], "role": "viewer"}, + ) + assert response.status_code == 200, response.text + response = await _post( + native_app, + admin, + "knowledge.source.add", + { + "org": org, + "namespace": "col-crawl-documents", + "name": "private-documents", + "kind": "gdrive", + "credential_mode": "crawl", + "credential": provider["credential"], + "items": [{"type": "filter", "kinds": ["docs"]}], + "include": ["docs"], + "crawl_options": { + "directory_subject": provider["directory"], + "subjects": [{"type": "person", "email": provider["reader"]}], + }, + }, + ) + assert response.status_code == 200, response.text + response = await _post( + native_app, + admin, + "knowledge.source.sync_now", + {"org": org, "namespace": "col-crawl-documents", "name": "private-documents"}, + ) + assert response.status_code == 200, response.text + + +@pytest.fixture +async def published_crawl( + registered_crawl: None, identities: dict[str, Any], provider: dict[str, Any] +) -> None: + from server.clients import gdrive + from server.core.ch import get_client, set_query_tag + from server.knowledge.domain.sources import SYNC_WORKER_ACTOR + + set_query_tag("test.crawl_native_privacy.publication") + ch, org = get_client(), identities["org"] + + async def published() -> dict[str, Any] | None: + assert not provider["unexpected"], provider["unexpected"] + return await ch.query_one( + "SELECT namespace, content, access_json, actor FROM loom.documents FINAL " + "WHERE org = {org:String} AND actor = {actor:String} LIMIT 1", + params={"org": org, "actor": SYNC_WORKER_ACTOR}, + ) + + document = await eventually(published, max_wait=180, description="native crawl publication") + assert provider["canary"] in document["content"] + assert document["actor"] == SYNC_WORKER_ACTOR and document["namespace"].startswith("acl-") + acl = json.loads(document["access_json"]) + assert provider["reader"] in acl["emails"] + assert identities["contacts"]["b"] not in acl["emails"] + assert provider["outside_reader"] in acl["emails"] + assert provider["exported"] + assert provider["scopes"] == {s.value for s in (*gdrive.ReadScope, *gdrive.WriteScope)} + source = await ch.query_one( + "SELECT toString(source_id) AS source_id, crawl_generation " + "FROM loom.knowledge_sources FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND name = {name:String} LIMIT 1", + params={"org": org, "ns": "col-crawl-documents", "name": "private-documents"}, + ) + assert source is not None and source["crawl_generation"] + + async def complete_listing() -> dict[str, Any] | None: + assert not provider["unexpected"], provider["unexpected"] + return await ch.query_one( + "SELECT crawl_generation " + "FROM loom.knowledge_source_listings FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND source_id = {id:String} LIMIT 1", + params={"org": org, "ns": document["namespace"], "id": source["source_id"]}, + ) + + listing = await eventually(complete_listing, max_wait=30, description="complete native listing") + assert listing["crawl_generation"] == source["crawl_generation"] + + +async def test_native_crawl_canary_obeys_document_acl_and_tenant_scope( + native_app: httpx.AsyncClient, + identities: dict[str, Any], + provider: dict[str, Any], + published_crawl: None, +) -> None: + from server.core.ch import set_query_tag + + set_query_tag("test.crawl_native_privacy.reads") + org, subjects = identities["org"], identities["subjects"] + query = { + "org": org, + "namespace": "col-crawl-documents", + "query": "quarterly renewal plan scope owners release readiness", + } + allowed = _bearer(subjects["a"], org, ["col-crawl-documents"], "viewer") + + async def admitted() -> bool: + assert not provider["unexpected"], provider["unexpected"] + result = await _post(native_app, allowed, "knowledge.search", query) + assert result.status_code == 200, result.text + return provider["canary"] in result.text + + assert await eventually(admitted, max_wait=30, description="authorized HTTP canary") + denied = _bearer(subjects["b"], org, ["col-crawl-documents"], "viewer") + response = await _post(native_app, denied, "knowledge.search", query) + assert response.status_code == 200, response.text + assert provider["canary"] not in response.text + # C has a document ACL entry but only another namespace's grant. A's other-org + # identity also has a matching contact, so the document ACL alone cannot deny it. + for bearer in ( + _bearer(subjects["c"], org, ["col-other-documents"], "viewer"), + _bearer(subjects["a"], identities["other_org"], ["*"], "viewer"), + ): + response = await _post(native_app, bearer, "knowledge.search", query) + assert response.status_code in {200, 403, 404}, response.text + assert provider["canary"] not in response.text diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index e36eb72738b..6ec6ba3c4f3 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -596,6 +596,12 @@ "knowledge_connected_sources_max_per_namespace": 64, "knowledge_connected_sources_max_per_person": 8, "knowledge_connected_stop_timeout_s": 20.0, + "knowledge_crawl_directory_max_pages": 256, + "knowledge_crawl_directory_max_response_bytes": 1048576, + "knowledge_crawl_max_files": 10000, + "knowledge_crawl_max_groups": 2000, + "knowledge_crawl_registry_page_size": 256, + "knowledge_crawl_registry_scan_limit": 4096, "knowledge_gaps_enabled": false, "knowledge_gaps_interval_seconds": 86400, "knowledge_gaps_max_askers_per_group": 10000, diff --git a/tests/unit/test_claim_write_settlement.py b/tests/unit/test_claim_write_settlement.py new file mode 100644 index 00000000000..097f086fec7 --- /dev/null +++ b/tests/unit/test_claim_write_settlement.py @@ -0,0 +1,129 @@ +"""A cleanup claimant cannot pass a sent INSERT that may still append raw metadata.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.core import ch as ch_module +from server.core import leases, rmt_carry +from server.settings import settings +from tests.unit.clock_fake import ManualClock + +pytestmark = pytest.mark.asyncio + + +class Keeper: + """External claim acquisition/release and server-side expiry, not the claim protocol.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.clock = ManualClock(1000.0) + self.keys: dict[str, tuple[leases.Lease, float]] = {} + self.serial = 0 + monkeypatch.setattr(leases, "time", SimpleNamespace(monotonic=self.clock.monotonic)) + monkeypatch.setattr(rmt_carry, "time", SimpleNamespace(monotonic=self.clock.monotonic)) + monkeypatch.setattr(settings, "ch_timeout_write_s", 5) + monkeypatch.setattr(leases, "take", self.take) + + async def take(self, name: str, *, ttl_s: float, wait_s: float, ch: Any): + assert wait_s >= 0 + if name in self.keys and self.keys[name][1] >= self.clock(): + return None + self.serial += 1 + lease = leases.Lease(name, ttl_s=ttl_s, ch=self, holder=str(self.serial)) + lease._renewed = self.clock() + lease._sent = True + self.keys[name] = lease, self.clock() + ttl_s + return lease + + async def execute(self, sql: str, *, params: dict[str, Any]) -> None: + assert sql == leases.LOCK_RELEASE + name = params["name"] + current = self.keys.get(name) + if current is not None and current[0].holder == params["me"]: + del self.keys[name] + + def send(self, name: str) -> float: + deadline = rmt_carry.clock_send_deadline((self.clock(), self.clock())) + rmt_carry.note_send(name, deadline, ch_module.write_limit_s()) + return deadline + + +async def test_acknowledged_sends_release_without_waiting(monkeypatch): + keeper = Keeper(monkeypatch) + async with leases.holding("claim", ttl_s=60, settle_writes=True) as held: + assert held + keeper.send("write") + rmt_carry.note_ended("write") # A server answer, including its own error, ended it. + assert keeper.keys == {} and keeper.clock.sleeps == [] + + +async def test_cancelled_unanswered_send_keeps_keeper_key_until_its_safe_expiry(monkeypatch): + keeper = Keeper(monkeypatch) + with pytest.raises(asyncio.CancelledError): + async with leases.holding("claim", ttl_s=60, settle_writes=True): + deadline = keeper.send("write") + raise asyncio.CancelledError + async with leases.holding("claim", ttl_s=60, settle_writes=True) as held: + assert not held + assert deadline + rmt_carry.send_bound_s() - 15 <= keeper.keys["claim"][1] + keeper.clock.advance(61) + async with leases.holding("claim", ttl_s=60, settle_writes=True) as held: + assert held + assert keeper.keys == {} and keeper.clock.sleeps == [] + + +async def test_handled_lost_reply_cannot_turn_an_unsettled_claim_into_success(monkeypatch): + keeper = Keeper(monkeypatch) + with pytest.raises(leases.LeaseUnavailable, match="unanswered"): + async with leases.holding("claim", ttl_s=60, settle_writes=True): + keeper.send("lost-reply") + assert "claim" in keeper.keys + + +async def test_nested_claim_cannot_move_outer_send_deadline_or_release_its_unknown_send( + monkeypatch, +): + keeper = Keeper(monkeypatch) + with pytest.raises(asyncio.CancelledError): + async with leases.holding("outer", ttl_s=60, settle_writes=True): + outer = rmt_carry.clock_send_deadline((keeper.clock(), keeper.clock())) + keeper.clock.advance(20) + async with leases.holding("inner", ttl_s=60, settle_writes=True): + inner = keeper.send("late-write") + assert inner > outer + assert inner + 5 + 5 <= keeper.keys["outer"][1] + raise asyncio.CancelledError + assert set(keeper.keys) == {"outer", "inner"} + keeper.clock.advance(41) + async with leases.holding("outer", ttl_s=60, settle_writes=True) as held: + assert held + async with leases.holding("inner", ttl_s=60, settle_writes=True) as held: + assert not held + + +async def test_impossible_receiver_bound_refuses_before_body_without_retaining_empty_claim( + monkeypatch, +): + keeper = Keeper(monkeypatch) + with pytest.raises(leases.ClaimExpired): + async with leases.holding("claim", ttl_s=10, settle_writes=True): + pytest.fail("no work fits before the receiver's completion barrier") + assert keeper.keys == {} + + +async def test_default_write_timeout_still_leaves_a_full_claim_work_window(monkeypatch): + keeper = Keeper(monkeypatch) + monkeypatch.setattr(settings, "ch_timeout_write_s", 60) + assert ch_module.write_limit_s() == 60 and rmt_carry.send_bound_s() == 80 + async with leases.holding("claim", ttl_s=60, settle_writes=True) as held: + assert held and ch_module.write_limit_s() == 9 + assert rmt_carry.send_bound_s() == 29 + keeper.clock.advance(23) + deadline = keeper.send("near-work-end") + assert deadline + ch_module.write_limit_s() + 5 < keeper.keys["claim"][1] + rmt_carry.note_ended("near-work-end") + assert keeper.keys == {} and keeper.clock.sleeps == [] diff --git a/tests/unit/test_clickhouse_mutation_inventory.py b/tests/unit/test_clickhouse_mutation_inventory.py index d4c18a6a4a7..21044569eb3 100644 --- a/tests/unit/test_clickhouse_mutation_inventory.py +++ b/tests/unit/test_clickhouse_mutation_inventory.py @@ -19,6 +19,10 @@ # the inventory honest without trying to parse Python string concatenation. _EXPECTED_MUTATIONS = Counter( { + # An offline restore clears every raw crawl version's approval, so no restored + # history reactivates delegated source authority; a root-secret reseal rewrites + # every raw version's sealed approval, so no old part keeps the retired seal. + ("server/knowledge/store/sources.py", "knowledge_sources", "UPDATE"): 2, # The contradiction repair's edge close, end_edges, which ends a dropped fact's # edge with its triples (only when no live row keeps the pair), and the undo of # a close's own ends (reopen_closed_by). diff --git a/tests/unit/test_connected_account_callbacks.py b/tests/unit/test_connected_account_callbacks.py index 29466453dd6..61bb0c9c131 100644 --- a/tests/unit/test_connected_account_callbacks.py +++ b/tests/unit/test_connected_account_callbacks.py @@ -372,8 +372,8 @@ async def query_one(self, query: str, params: dict[str, Any]): if row["email"] in params["witnesses"]: qualified.update(row["work_addresses"] & set(params["missing"])) return {"qualified": sorted(qualified)} - row = self.people.get(params["id"]) - return {"x": 1} if row is not None and not row["active"] else None + rows = [self.people.get(uid) for uid in params["ids"]] + return {"x": 1} if any(row and not row["active"] for row in rows) else None return await super().query_one(query, params) diff --git a/tests/unit/test_connected_account_restore.py b/tests/unit/test_connected_account_restore.py index 3a498f80663..7517c6d2ab1 100644 --- a/tests/unit/test_connected_account_restore.py +++ b/tests/unit/test_connected_account_restore.py @@ -29,6 +29,9 @@ def __init__(self, monkeypatch, http): self.account_history = [self.rows[_KEY]] self.source_history = [self.source] monkeypatch.setattr(accounts.store, "_default_client", lambda: self) + from server.knowledge.app import crawl_restore + + monkeypatch.setattr(crawl_restore, "get_client", lambda: self) async def put(self, row, **kwargs): await super().put(row, **kwargs) @@ -43,6 +46,9 @@ async def erase(self, org, subjects, *, kind, **kwargs): ] async def query_all(self, query, params, **kwargs): + if query.startswith("SELECT DISTINCT org FROM loom.knowledge_sources "): + assert "WHERE credential_mode = 'crawl' " in query + return [] # This connection-only world contains no crawl source. if "FROM loom.connected_accounts" in query: assert "FINAL" not in query assert "credential_enc" not in query and "account_email_enc" not in query diff --git a/tests/unit/test_connected_source_authority.py b/tests/unit/test_connected_source_authority.py index 3da772a48d2..ee08634577d 100644 --- a/tests/unit/test_connected_source_authority.py +++ b/tests/unit/test_connected_source_authority.py @@ -115,6 +115,7 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> monkeypatch.setattr(accounts.source_store, "latest_source", self.get_source) monkeypatch.setattr(accounts.source_store, "connected_sources", self.connected_sources) monkeypatch.setattr(accounts.scim, "deactivated", self.deactivated) + monkeypatch.setattr(accounts.scim, "any_deactivated", self.any_deactivated) monkeypatch.setattr(accounts.revocation, "cutoffs", self.revoked) monkeypatch.setattr(ledger_reads.ledger, "open_namespace_erasures", self.erasures) monkeypatch.setattr(connected_oauth, "get_client", lambda: http) @@ -209,6 +210,9 @@ async def deactivated(self, email: str) -> bool: assert email == "person@example.com" return self.scim_ended + async def any_deactivated(self, emails: list[str]) -> bool: + return any([await self.deactivated(email) for email in emails]) + async def revoked(self, subjects: list[str]) -> dict[str, int | None]: return {key: self.cutoffs[key] for key in subjects if key in self.cutoffs} diff --git a/tests/unit/test_connected_source_workers.py b/tests/unit/test_connected_source_workers.py index c521ab2c8df..e7a9cd34575 100644 --- a/tests/unit/test_connected_source_workers.py +++ b/tests/unit/test_connected_source_workers.py @@ -215,6 +215,7 @@ async def test_native_connected_notion_turn_publishes_real_rows_then_a_guarded_l "org": "team", "namespace": _MIRROR, "source_id": "source-id", + "crawl_generation": "", "name": "documents", } assert isinstance(listing["started_at"], datetime) diff --git a/tests/unit/test_crawl_approval_reseal.py b/tests/unit/test_crawl_approval_reseal.py new file mode 100644 index 00000000000..36f42260ef9 --- /dev/null +++ b/tests/unit/test_crawl_approval_reseal.py @@ -0,0 +1,146 @@ +"""Root rotation rewrites all historical approval envelopes without replacing authority.""" + +from __future__ import annotations + +import copy +import dataclasses +import json + +import pytest + +from server.auth import source_registration as registration +from server.auth.jwt import AuthorizationClaims +from server.core.secrets_at_rest import seal, unseal +from server.knowledge.app import crawl_reseal +from server.operations.base import Role +from server.settings import settings +from tests.unit.test_crawl_restore import _FIRST, _SECOND, _HistoryWorld + +pytestmark = pytest.mark.asyncio + + +def _approval(source_id: str, generation: str, *, org: str = "org") -> tuple[str, str]: + scope = registration.Scope(org, "namespace", source_id, generation, "f" * 64) + claims = AuthorizationClaims( + subject="registrant", + org=org, + namespaces=("namespace",), + roles=(Role.ORG_ADMIN,), + is_service_account=False, + issued_at=1, + expires_at=2, + creator="original-creator", + ) + plain = json.dumps( + { + "format": 1, + "scope": dataclasses.asdict(scope), + "registrant": "registrant", + "claims": dataclasses.asdict(claims), + }, + sort_keys=True, + ) + return seal(registration.PURPOSE, plain), plain + + +async def _history(monkeypatch): + world = _HistoryWorld(monkeypatch) + monkeypatch.setattr(crawl_reseal, "get_client", lambda: world) + monkeypatch.setattr(settings, "knowledge_crawl_registry_page_size", 1) + first, _ = _approval(_FIRST, "earlier-generation") + second, _ = _approval(_FIRST, "later-generation") + third, _ = _approval(_SECOND, "other-source-generation") + await world.seed(approval_enc=first) + await world.seed(approval_enc=first) + await world.seed(approval_enc=second) + await world.seed(name="secondary", source_id=_SECOND, approval_enc=third) + await world.seed(name="shared", credential_mode="shared", approval_enc="unrelated") + return world + + +def _rotate(monkeypatch): + monkeypatch.setattr(settings, "jwt_secret_previous", settings.jwt_secret) + monkeypatch.setattr( + settings, "jwt_secret", "replacement-root-sealing-secret-which-is-long-enough" + ) + + +async def test_approval_reseal_reaches_every_raw_version_and_retains_exact_source_identity( + monkeypatch, +): + world = await _history(monkeypatch) + before = copy.deepcopy(world.sources) + plaintext = [unseal(registration.PURPOSE, r["approval_enc"]) for r in before[:4]] + _rotate(monkeypatch) + assert await crawl_reseal.approvals(dry_run=False, ch=world) == (3, []) + monkeypatch.setattr(settings, "jwt_secret_previous", "") + for old, row, plain in zip(before[:4], world.sources[:4], plaintext, strict=True): + assert row["approval_enc"] != old["approval_enc"] + assert unseal(registration.PURPOSE, row["approval_enc"], warn=False) == plain + assert not unseal(registration.PURPOSE, old["approval_enc"], warn=False) + frame = json.loads(plain) + scope = registration.Scope(**frame["scope"]) + approval = registration.load(row["approval_enc"], scope, registrant="registrant") + assert approval.scope.source_id == row["source_id"] + assert approval.scope == scope and approval.registrant == frame["registrant"] + assert approval.claims.roles == (Role.ORG_ADMIN,) + assert ( + approval.claims.subject == "registrant" + and approval.claims.creator == "original-creator" + ) + assert approval.claims.expires_at == 2 + assert {k: v for k, v in row.items() if k != "approval_enc"} == { + k: v for k, v in old.items() if k != "approval_enc" + } + assert world.sources[-1] == before[-1] + assert len(world.page_reads) >= 3 and not world.retirements + + +async def test_approval_reseal_dry_run_counts_old_envelopes_without_writing_history(monkeypatch): + world = await _history(monkeypatch) + before = copy.deepcopy(world.sources) + _rotate(monkeypatch) + assert await crawl_reseal.approvals(dry_run=True, ch=world) == (3, []) + assert world.sources == before and not world.executed and not world.retirements + + +async def test_unreadable_approval_is_reported_without_resetting_its_source(monkeypatch): + world = _HistoryWorld(monkeypatch) + monkeypatch.setattr(crawl_reseal, "get_client", lambda: world) + await world.seed(approval_enc="unreadable-ciphertext") + before = copy.deepcopy(world.sources) + _rotate(monkeypatch) + assert await crawl_reseal.approvals(dry_run=False, ch=world) == (0, ["org/namespace/documents"]) + assert world.sources == before and not world.executed + + +async def test_approval_copied_from_another_scope_cannot_be_resealed_as_local_authority( + monkeypatch, +): + world = _HistoryWorld(monkeypatch) + monkeypatch.setattr(crawl_reseal, "get_client", lambda: world) + foreign, _ = _approval(_FIRST, "generation", org="another-org") + await world.seed(approval_enc=foreign) + before = copy.deepcopy(world.sources) + _rotate(monkeypatch) + with pytest.raises(registration.Refused): + await crawl_reseal.approvals(dry_run=False, ch=world) + assert world.sources == before and not world.executed + + +async def test_ignored_history_reseal_fails_its_raw_ciphertext_residue_check(monkeypatch): + world = await _history(monkeypatch) + before = copy.deepcopy(world.sources) + world.ignore_mutation = True + _rotate(monkeypatch) + with pytest.raises(RuntimeError, match="crawl_approval_reseal_residue"): + await crawl_reseal.approvals(dry_run=False, ch=world) + assert world.executed and world.sources == before + + +async def test_approval_reseal_refuses_another_target_without_touching_history(monkeypatch): + world = await _history(monkeypatch) + before = copy.deepcopy((world.sources, world.page_reads, world.executed)) + with pytest.raises(RuntimeError, match="crawl_reseal_target_mismatch"): + await crawl_reseal.approvals(dry_run=False, ch=object()) + assert (world.sources, world.page_reads, world.executed) == before diff --git a/tests/unit/test_crawl_authority.py b/tests/unit/test_crawl_authority.py new file mode 100644 index 00000000000..35ef964aa79 --- /dev/null +++ b/tests/unit/test_crawl_authority.py @@ -0,0 +1,396 @@ +"""Native Drive calls keep source, signer and provider-person authority across awaits.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import hashlib +import json +import time +from typing import Any +from urllib.parse import parse_qs + +import httpx +import jwt +import pytest + +from server.auth import scim +from server.auth import source_registration as registration +from server.auth.jwt import verify_token +from server.clients import gdrive +from server.clients import google_workspace as google +from server.clients._vendor import CredentialRefused, VendorError +from server.core.errors import ValidationError +from server.core.secrets_at_rest import seal +from server.knowledge.app import crawl_authority, crawl_expansion +from server.knowledge.app import sources as source_ops +from server.knowledge.domain.source_crawl import Person +from server.knowledge.domain.sources import KnowledgeSource +from server.operations.base import Role +from tests.unit.principals import acting_as +from tests.unit.test_connected_source_authority import _World as _AuthorityWorld +from tests.unit.test_crawl_registration import _token +from tests.unit.test_crawl_signing_authority import key_view as key_view +from tests.unit.test_google_workspace import account as account + +pytestmark = [pytest.mark.asyncio, pytest.mark.claim_cap] +_BOUNDS = crawl_authority.Bounds(crawl_expansion.Limits(16384, 10, 10)) +_NATIVE_SCIM_READ = scim.any_deactivated + + +class _World(_AuthorityWorld): + def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient, account: Any): + super().__init__(monkeypatch, http) + self.grant = Role.ADMIN + self.provider_calls: list[httpx.Request] = [] + self.claims_sent: list[dict[str, Any]] = [] + self.ended_people: set[str] = set() + self.account = account + self.customer = "workspace" + self.person_email = "one@example.com" + self.after_grant: Any = lambda: None + self.after_native: Any = lambda: None + monkeypatch.setattr(google, "get_client", lambda: http) + monkeypatch.setattr(gdrive, "get_client", lambda: http) + monkeypatch.setattr(scim, "any_deactivated", _NATIVE_SCIM_READ) + monkeypatch.setattr(scim, "get_client", lambda: self) + service = account[0] + self.credential = json.dumps( + { + "type": "service_account", + "client_email": service.client_email, + "private_key": service.private_key, + } + ) + self.source = KnowledgeSource( + org="team", + namespace="shared-space", + name="documents", + kind="gdrive", + source_id="crawl-source", + config={"include": ["docs"]}, + items=[{"type": "file", "id": "file"}], + access="mirrored", + credential_mode="crawl", + secret_enc=seal(source_ops._SECRET_PURPOSE, self.credential), + crawl_options={ + "directory_subject": "directory@example.com", + "subjects": [{"type": "person", "email": "one@example.com"}], + }, + crawl_generation="crawl-generation", + crawl_customer_id="workspace", + crawl_credential_hash=hashlib.sha256(self.credential.encode()).hexdigest(), + created_by="audit-attribution-is-not-authority", + ) + + async def query_one(self, query: str, params: dict[str, Any] | None = None, **kwargs: Any): + if query.startswith("SELECT 1 AS x FROM loom.scim_users FINAL WHERE id IN"): + assert params is not None and set(params) == {"ids"} + ended = self.ended_people | ({"person@example.com"} if self.scim_ended else set()) + ids = {scim.user_id(email) for email in ended} + return {"x": 1} if ids.intersection(params["ids"]) else None + return await super().query_one(query, params, **kwargs) + + async def setup(self) -> None: + assert self.source is not None + auth = verify_token(_token()) + with acting_as(auth): + registrant, approval = await registration.capture( + auth, crawl_authority.scope(self.source) + ) + self.source = dataclasses.replace( + self.source, registrant_subject=registrant, approval_enc=approval + ) + + async def handle(self, request: httpx.Request) -> httpx.Response: + self.provider_calls.append(request) + if request.url.host == "oauth2.googleapis.com": + form = parse_qs(request.content.decode()) + assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] + claims = jwt.decode( + form["assertion"][0], + self.account[1], + algorithms=["RS256"], + audience="https://oauth2.googleapis.com/token", + ) + self.claims_sent.append(claims) + if claims["scope"] in {write.value for write in gdrive.WriteScope}: + assert claims["sub"] == "directory@example.com" + return httpx.Response(400, json={"error": "unauthorized_client"}) + drive = claims["sub"] == "one@example.com" + assert not drive or claims["scope"] == gdrive.ReadScope.DRIVE.value + assert claims["sub"] == ("one@example.com" if drive else "directory@example.com") + if drive: + self.after_grant() + return httpx.Response( + 200, + json={ + "access_token": "private-person-access" + if drive + else "private-directory-access", + "token_type": "Bearer", + "expires_in": 60, + }, + ) + if request.url.host == "admin.googleapis.com": + assert request.headers["authorization"] == "Bearer private-directory-access" + key = request.url.path.rsplit("/", 1)[1] + directory = key == "directory@example.com" + assert directory or key in {"one@example.com", "provider-one"} + return httpx.Response( + 200, + json={ + "id": "directory-user" if directory else "provider-one", + "primaryEmail": "directory@example.com" if directory else self.person_email, + "aliases": [], + "customerId": self.customer, + "suspended": False, + "archived": False, + }, + ) + assert ( + request.url.host == "www.googleapis.com" and request.url.path == "/drive/v3/files/file" + ) + assert request.headers["authorization"] == "Bearer private-person-access" + self.native_requests.append(request) + self.after_native() + return httpx.Response(200, json={"id": "file", "name": "private-document"}) + + +@pytest.fixture +async def crawl_world(monkeypatch: pytest.MonkeyPatch, account: Any, key_view: list[str]): + async def handle(request: httpx.Request) -> httpx.Response: + return await state.handle(request) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http: + state = _World(monkeypatch, http, account) + await state.setup() + yield state + + +async def _ready(state: _World): + assert state.source is not None + authority = await crawl_authority.resolve( + state.source, deadline=time.monotonic() + 10, bounds=_BOUNDS + ) + expanded = await authority.prepare() + (person,) = expanded.people + return authority, person + + +async def test_real_checked_drive_uses_only_the_expanded_provider_person( + crawl_world: _World, +) -> None: + authority, person = await _ready(crawl_world) + access = await authority.drive(person) + assert await gdrive.file_meta(access, "file") == {"id": "file", "name": "private-document"} + assert len(crawl_world.native_requests) == 1 + assert {c["sub"] for c in crawl_world.claims_sent} == { + "directory@example.com", + "one@example.com", + } + assert all( + c["sub"] not in {"person", "person@example.com", crawl_world.source.created_by} + for c in crawl_world.claims_sent + ) + with pytest.raises(TypeError): + str(access) + + +async def test_a_turn_checks_each_person_in_the_directory_only_at_its_drive_grant( + crawl_world: _World, +) -> None: + authority, person = await _ready(crawl_world) + + def lookups() -> int: + return sum("/admin/directory/v1/users/" in c.url.path for c in crawl_world.provider_calls) + + expanded = lookups() + await authority.drive(person) + granted = lookups() + assert granted - expanded == 2 # before and after the one delegated grant + for _ in range(5): + async with authority.using((person,)): + await authority.drive(person) + assert lookups() == granted + + +async def test_a_presenter_deactivated_after_its_drive_read_stops_publication( + crawl_world: _World, +) -> None: + authority, person = await _ready(crawl_world) + published = False + with pytest.raises(CredentialRefused, match="person unavailable"): + async with authority.using((person,)): + await authority.drive(person) + crawl_world.ended_people.add(person.email) + async with crawl_authority.current(crawl_world.source).publication_guard(): + published = True + assert not published + + +async def test_unexpanded_or_email_shaped_loom_subject_cannot_select_delegation( + crawl_world: _World, +) -> None: + authority, _person = await _ready(crawl_world) + before = len(crawl_world.provider_calls) + with pytest.raises(CredentialRefused): + await authority.drive(Person("workspace", "person", "person@example.com", ())) + assert len(crawl_world.provider_calls) == before and not crawl_world.native_requests + + +async def test_provider_address_rebind_during_grant_stops_before_native_drive( + crawl_world: _World, +) -> None: + authority, person = await _ready(crawl_world) + crawl_world.after_grant = lambda: setattr(crawl_world, "person_email", "renamed@example.com") + with pytest.raises(CredentialRefused, match="person changed"): + await authority.drive(person) + assert not crawl_world.native_requests + + +@pytest.mark.parametrize("loss", ["grant", "registration", "deactivation"]) +async def test_native_response_never_returns_after_current_authority_loss( + crawl_world: _World, loss: str +) -> None: + authority, person = await _ready(crawl_world) + + def changed() -> None: + if loss == "grant": + crawl_world.grant = Role.WRITER + elif loss == "registration": + crawl_world.source = dataclasses.replace( + crawl_world.source, crawl_generation="replacement" + ) + else: + crawl_world.ended_people.add("one@example.com") + + crawl_world.after_native = changed + with pytest.raises((PermissionError, VendorError)): + await gdrive.file_meta(await authority.drive(person), "file") + assert len(crawl_world.native_requests) == 1 + + +async def test_non_provider_wait_is_checked_before_result_delivery(crawl_world: _World) -> None: + authority, person = await _ready(crawl_world) + entered = [] + + async def model_wait(_access: Any) -> str: + entered.append(True) + crawl_world.grant = Role.WRITER + return "private-model-result" + + with pytest.raises(PermissionError): + await authority.run(person, model_wait) + assert entered and not crawl_world.native_requests + + +async def test_modified_selection_without_new_approval_makes_zero_provider_calls( + crawl_world: _World, +) -> None: + assert crawl_world.source is not None + crawl_world.source = dataclasses.replace( + crawl_world.source, items=[{"type": "file", "id": "other-file"}] + ) + with pytest.raises(registration.Refused): + await crawl_authority.resolve( + crawl_world.source, deadline=time.monotonic() + 10, bounds=_BOUNDS + ) + assert not crawl_world.provider_calls + + +async def test_different_sealed_key_cannot_inherit_the_approved_key_hash( + crawl_world: _World, +) -> None: + assert crawl_world.source is not None + crawl_world.source = dataclasses.replace( + crawl_world.source, secret_enc=seal(source_ops._SECRET_PURPOSE, "different-secret") + ) + with pytest.raises(CredentialRefused): + await crawl_authority.resolve( + crawl_world.source, deadline=time.monotonic() + 10, bounds=_BOUNDS + ) + assert not crawl_world.provider_calls + + +async def test_workspace_change_is_refused_before_any_drive_grant(crawl_world: _World) -> None: + crawl_world.customer = "different-workspace" + with pytest.raises(CredentialRefused, match="workspace changed"): + await _ready(crawl_world) + assert all(c["scope"] != gdrive.ReadScope.DRIVE.value for c in crawl_world.claims_sent) + assert not crawl_world.native_requests + + +async def test_ordinary_credential_selection_never_falls_back_to_a_crawl_key( + crawl_world: _World, +) -> None: + assert crawl_world.source is not None + assert source_ops.credential_of(crawl_world.source) == "" + with pytest.raises(ValidationError): + await source_ops.credential_for(crawl_world.source, deadline=time.monotonic() + 10) + assert not crawl_world.provider_calls + + +async def test_retained_native_checkout_stops_when_target_person_is_deactivated( + crawl_world: _World, +) -> None: + authority, person = await _ready(crawl_world) + access = await authority.drive(person) + before = len(crawl_world.provider_calls) + crawl_world.ended_people.add(person.email) + with pytest.raises(CredentialRefused, match="person unavailable"): + await gdrive.file_meta(access, "file") + assert len(crawl_world.provider_calls) == before and not crawl_world.native_requests + + +async def test_the_publication_guard_holds_the_source_lease_and_rechecks_standing( + crawl_world: _World, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from contextlib import asynccontextmanager + + from server.core import leases + + @asynccontextmanager + async def holding(key: str, **kwargs: Any): + assert key == "knowledge-source:team:shared-space" + async with crawl_world.lease(key, **kwargs): + yield True + + monkeypatch.setattr(leases, "holding", holding) + authority, person = await _ready(crawl_world) + async with authority.publication_guard(): + assert crawl_world.holders.get(asyncio.current_task(), 0) == 1 + assert not crawl_world.holders.get(asyncio.current_task(), 0) + crawl_world.ended_people.add(person.email) + with pytest.raises(CredentialRefused, match="person unavailable"): + async with authority.using((person,)): + pytest.fail("a deactivated presenter opens no checkout") + + +async def test_only_the_completed_listing_re_reads_the_registrant_grants( + crawl_world: _World, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from contextlib import asynccontextmanager + + from server.core import grant_cache, leases + + @asynccontextmanager + async def holding(key: str, **kwargs: Any): + async with crawl_world.lease(key, **kwargs): + yield True + + monkeypatch.setattr(leases, "holding", holding) + authority, _person = await _ready(crawl_world) + invalidated: list[object] = [] + real = grant_cache.invalidate + monkeypatch.setattr( + grant_cache, "invalidate", lambda *a, **k: (invalidated.append(a), real(*a, **k))[1] + ) + async with authority.publication_guard(): + pass + assert not invalidated, "a document's write keeps the org's grant caches" + async with authority.publication_guard(fresh=True): + pass + assert invalidated diff --git a/tests/unit/test_crawl_composed_flow.py b/tests/unit/test_crawl_composed_flow.py new file mode 100644 index 00000000000..324f9981831 --- /dev/null +++ b/tests/unit/test_crawl_composed_flow.py @@ -0,0 +1,435 @@ +"""Real registration, native worker publication and indexed authority share one generation.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import time +from typing import Any + +import httpx +import pytest + +from server.auth.jwt import verify_token +from server.clients import gdrive +from server.core import instances, request_work +from server.core.errors import ValidationError +from server.knowledge.api.models_sources import KnowledgeSourceAddInput, KnowledgeSourceUpdateInput +from server.knowledge.app import crawl_sources, mirrors, private_sync +from server.knowledge.app import source_access as reads +from server.knowledge.app import source_sync as sync +from server.knowledge.app import sources as ops +from server.knowledge.domain.access_list import from_json +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, mirror_uri +from server.knowledge.store import crawl_publication, documents +from server.knowledge.store import mirrors as mirror_store +from server.knowledge.store import sources as source_store +from server.memory.domain.provenance import pipeline_actor +from server.operations.base import Role +from tests.unit.principals import acting_as +from tests.unit.test_connected_source_publication import _MIRROR +from tests.unit.test_connected_source_publication import _World as _PublicationWorld +from tests.unit.test_crawl_authority import _World as _CrawlWorld +from tests.unit.test_crawl_registration import _token +from tests.unit.test_crawl_signing_authority import key_view as key_view +from tests.unit.test_crawl_worker_observation import _file +from tests.unit.test_google_workspace import account as account + +pytestmark = [pytest.mark.asyncio, pytest.mark.claim_cap] + + +class _World(_CrawlWorld, _PublicationWorld): + """Reuse real authority and upsert fixtures, extending only SQL and provider I/O.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient, account: Any): + super().__init__(monkeypatch, http, account) + self.source = None + self.listings: list[dict[str, Any]] = [] + self.states: list[dict[str, Any]] = [] + self.lose_during_embedding = False + self.lose_during_proof = False + self.unhandled_reads: list[tuple[str, tuple[str, ...]]] = [] + monkeypatch.setattr(crawl_sources, "get_client", lambda: self) + monkeypatch.setattr(instances, "read_live", self.read_live) + monkeypatch.setattr(mirrors, "mirrors_of", self.mirror_rows) + monkeypatch.setattr(mirror_store, "_default_client", lambda: self) + monkeypatch.setattr(crawl_publication, "_default_client", lambda: self) + monkeypatch.setattr(reads.store, "_default_client", lambda: self) + monkeypatch.setattr(reads.mirrors_repo, "mirrors_of", self.mirror_rows) + monkeypatch.setattr(reads.pg, "enabled", lambda: False) + monkeypatch.setattr(source_store, "every_copy", self.every_copy) + monkeypatch.setattr(source_store, "read_states", self.read_states) + monkeypatch.setattr(documents, "publications_owed", self.publications_owed) + monkeypatch.setattr(private_sync, "write_private_cost_event_for", self.cost_event) + + async def read_live(self, ch: Any, *, all_deployments: bool): + assert ch is self and all_deployments + return [{"schema_version": crawl_sources._CRAWL_MIGRATION}] + + async def cost_event(self, **values: Any) -> None: + assert values["org"] == "team" and values["namespace"] == _MIRROR + + def assert_storage_leases(self) -> None: + assert self.held.get(asyncio.current_task(), []) == ["knowledge-source:team:shared-space"] + + async def no_prior_document(self, org: str, namespace: str, uri: str, **kwargs: Any): + assert (org, namespace) == ("team", _MIRROR) + assert set(kwargs) == {"include_superseded"} + return next((row for row in self.document_writes if row["source_uri"] == uri), None) + + async def every_copy(self, org: str, mirror: str, tag: str): + assert self.source is not None + assert (org, mirror, tag) == ("team", _MIRROR, "source-id:" + self.source.source_id) + return [] + + async def read_states(self, org: str, namespace: str, names: list[str]): + assert self.source is not None and org == "team" + assert (namespace, names) in ( + (_MIRROR, [self.source.source_id]), + (self.source.namespace, [self.source.name]), + ) + found = {} + for row in self.states: + if row["namespace"] == namespace: + for name in names: + if row["state_key"] == source_store.state_key(name): + found[name] = {"state_value": row["state_value"], "detail": row["detail"]} + return found + + async def publications_owed(self, org: str, mirror: str, suffix: str) -> bool: + assert self.source is not None + assert (org, mirror, suffix) == ("team", _MIRROR, "#" + self.source.source_id) + return False + + async def mirror_rows(self, org: str, namespaces: list[str], **kwargs: Any): + assert org == "team" and kwargs == {"live_only": True} + return {_MIRROR: "shared-space"} if "shared-space" in namespaces else {} + + async def query_one(self, query: str, params: dict[str, Any] | None = None, **kwargs: Any): + if query.startswith("SELECT count() AS n FROM loom.knowledge_sources FINAL"): + assert params == {"org": "team", "ns": "shared-space", "connected": False, "owner": ""} + return {"n": int(self.source is not None and self.source.active)} + if query.startswith("SELECT count() AS n FROM loom.documents FINAL"): + assert params is not None and params["org"] == "team" + return {"n": 0} + return await super().query_one(query, params, **kwargs) + + async def query_all(self, query: str, params: dict[str, Any], **kwargs: Any): + if "FROM loom.knowledge_group_members FINAL" in query: + assert params["org"] == "team" + return [] + if query.startswith("SELECT namespace, name, credential_mode"): + assert params == {"org": "team", "names": ["shared-space"]} + return ( + [] + if self.source is None + else [ + { + "namespace": self.source.namespace, + "name": self.source.name, + "credential_mode": self.source.credential_mode, + "source_id": self.source.source_id, + } + ] + ) + if "FROM loom.knowledge_source_listings FINAL" in query: + assert params["org"] == "team" + return [ + row + for row in self.listings + if (row["namespace"], row["source_id"]) in params["pairs"] + ] + if "FROM loom.documents FINAL" in query: + assert params["org"] == "team" + return [ + row + for row in self.document_writes + if (row["namespace"], row["source_uri"]) in params["pairs"] + ] + try: + return await super().query_all(query, params, **kwargs) + except AssertionError: + # Preserve fail-closed behavior; surface only the unexpected fake-I/O + # projection and parameter names, never substitute admission evidence. + self.unhandled_reads.append((" ".join(query.split()), tuple(sorted(params)))) + raise + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + if table == source_store.TABLE: + self.assert_storage_leases() + [row] = rows + self.source = source_store._source(row) + self.request = self.request.model_copy( + update={"source_uri": mirror_uri(_file()["webViewLink"], self.source.source_id)} + ) + elif table == source_store.STATE_TABLE: + self.assert_storage_leases() + self.states.extend(dict(row) for row in rows) + elif table == mirror_store.LISTINGS: + self.assert_storage_leases() + self.listings = [dict(row) for row in rows] + else: + await super().insert(table, rows) + + async def handle(self, request: httpx.Request) -> httpx.Response: + if request.url.host == "www.googleapis.com": + assert not self.holders.get(asyncio.current_task(), 0) + assert request.headers["authorization"] == "Bearer private-person-access" + self.native_requests.append(request) + if request.url.path == "/drive/v3/files/file/export": + return httpx.Response( + 200, text="# Notes\n\nThe delegated source publishes this revision." + ) + file = _file() + file["permissions"] = [ + {"type": "user", "role": "reader", "emailAddress": "person@example.com"} + ] + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": [file], "incompleteSearch": False}) + assert request.url.path == "/drive/v3/files/file" + return httpx.Response(200, json=file) + response = await super().handle(request) + if self.lose_during_proof and self.claims_sent: + self.grant = Role.VIEWER + return response + + async def embed_many(self, texts: list[str]) -> list[list[float]]: + result = await super().embed_many(texts) + if self.lose_during_embedding: + self.grant = Role.VIEWER + return result + + +@pytest.fixture +async def world(monkeypatch: pytest.MonkeyPatch, account: Any, key_view: list[str]): + async def provider(request: httpx.Request) -> httpx.Response: + return await state.handle(request) + + marker = request_work._current.set(None) + request_work.begin() + try: + async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: + state = _World(monkeypatch, http, account) + yield state + finally: + request_work._current.reset(marker) + + +def _input(world: _World) -> KnowledgeSourceAddInput: + return KnowledgeSourceAddInput( + org="team", + namespace="shared-space", + name="documents", + kind="gdrive", + credential_mode="crawl", + credential=world.credential, + items=[{"type": "filter", "kinds": ["docs"]}], + include=["docs"], + crawl_options={ + "directory_subject": "directory@example.com", + "subjects": [{"type": "person", "email": "one@example.com"}], + }, + ) + + +def _reader_token() -> str: + # Mirrored reads resolve a reader only for a primary session (`sid`). + return _token(sid="reader-session") + + +async def _register(world: _World) -> None: + with acting_as(verify_token(_token())): + result = await ops.handle_knowledge_source_add(_input(world)) + assert result.name == "documents" and not result.dry_run + assert world.source is not None and world.source.crawl_customer_id == "workspace" + + +async def _turn(world: _World) -> sync.TurnResult: + assert world.source is not None + now = time.monotonic() + run = sync.Pass(sync.PassBudget(now, now + 30), 10) + with acting_as(None), pipeline_actor(SYNC_WORKER_ACTOR), private_sync.scope(): + return await sync._turn_of(world.source)(world.source, {}, run) + + +async def test_registration_native_publication_and_indexed_reader_share_exact_generation( + world: _World, +) -> None: + await _register(world) + assert {claim["scope"] for claim in world.claims_sent} == { + scope.value for scope in (*gdrive.ReadScope, *gdrive.WriteScope) + } + turn = await _turn(world) + assert turn.status == "ok" and turn.complete and turn.changed == 1 + assert len(world.document_writes) == len(world.chunk_writes) == len(world.listings) == 1 + [document] = world.document_writes + assert document["actor"] == SYNC_WORKER_ACTOR + assert from_json(document["access_json"]).owner == "" + assert "person@example.com" in from_json(document["access_json"]).emails + assert world.source is not None + assert world.listings[0]["crawl_generation"] == world.source.crawl_generation + candidate = {key: document[key] for key in ("namespace", "source_uri", "revision")} + candidate["doc_version"] = document["version"] + before = len(world.provider_calls), len(world.native_requests) + with acting_as(verify_token(_reader_token())): + plan = await reads.prepare("team", ["shared-space"]) + assert plan.sources == {(_MIRROR, world.source.source_id): "shared-space"}, ( + world.unhandled_reads, + world.listings, + ) + checked = await plan.check([candidate], chunks=True) + assert checked, world.unhandled_reads + [admitted] = checked + assert admitted.document == document and plan.current(admitted) + assert (len(world.provider_calls), len(world.native_requests)) == before + + +async def test_indexed_reads_keep_the_orgs_grant_caches( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.core import grant_cache + + await _register(world) + assert (await _turn(world)).status == "ok" + dropped: list[object] = [] + monkeypatch.setattr(grant_cache, "invalidate", lambda *a, **k: dropped.append((a, k))) + with acting_as(verify_token(_reader_token())): + plan = await reads.prepare("team", ["shared-space"]) + assert plan.sources == {(_MIRROR, world.source.source_id): "shared-space"} + assert dropped == [] + + +async def test_current_administrator_loss_during_registration_never_publishes_source( + world: _World, +) -> None: + world.lose_during_proof = True + with acting_as(verify_token(_token())), pytest.raises((ValidationError, PermissionError)): + await ops.handle_knowledge_source_add(_input(world)) + assert world.provider_calls and world.source is None and not world.document_writes + + +async def test_actual_embedding_wait_cannot_publish_after_registrant_loses_namespace_admin( + world: _World, +) -> None: + await _register(world) + world.lose_during_embedding = True + with pytest.raises(PermissionError): + await _turn(world) + assert ( + world.embedded + and not world.document_writes + and not world.chunk_writes + and not world.listings + ) + + +@pytest.mark.parametrize("change", ["generation", "approval"]) +async def test_indexed_evidence_is_removed_after_the_registration_changes( + world: _World, change: str +) -> None: + await _register(world) + assert (await _turn(world)).status == "ok" + [document] = world.document_writes + candidate = {key: document[key] for key in ("namespace", "source_uri", "revision")} + candidate["doc_version"] = document["version"] + with acting_as(verify_token(_reader_token())): + plan = await reads.prepare("team", ["shared-space"]) + assert plan.sources == {(_MIRROR, world.source.source_id): "shared-space"}, ( + world.unhandled_reads, + world.listings, + ) + checked = await plan.check([candidate], chunks=True) + assert checked, world.unhandled_reads + [admitted] = checked + assert world.source is not None + if change == "generation": + world.source = dataclasses.replace(world.source, crawl_generation="replaced") + else: + world.source = dataclasses.replace(world.source, approval_enc="replaced") + assert await plan.check([candidate], chunks=True) == [] + assert not plan.current(admitted) + + +async def test_reapproved_generation_cannot_reuse_an_older_completed_listing(world: _World) -> None: + await _register(world) + assert (await _turn(world)).status == "ok" + [document] = world.document_writes + candidate = {key: document[key] for key in ("namespace", "source_uri", "revision")} + candidate["doc_version"] = document["version"] + assert world.source is not None + before = world.source.crawl_generation + with acting_as(verify_token(_token())): + await ops.handle_knowledge_source_update( + KnowledgeSourceUpdateInput( + org="team", + namespace="shared-space", + name="documents", + include=["docs", "pdf"], + ) + ) + assert world.source.crawl_generation != before + with acting_as(verify_token(_reader_token())): + plan = await reads.prepare("team", ["shared-space"]) + assert plan.sources == {} and await plan.check([candidate], chunks=True) == [] + + +async def test_a_deactivated_person_is_left_out_of_registration_and_presents_nothing( + world: _World, +) -> None: + await _register(world) + assert (await _turn(world)).status == "ok" + published = len(world.document_writes), len(world.native_requests) + world.ended_people.add("one@example.com") + with acting_as(verify_token(_token())): + update = await ops.handle_knowledge_source_update( + KnowledgeSourceUpdateInput( + org="team", + namespace="shared-space", + name="documents", + include=["docs", "pdf"], + ) + ) + assert update.crawl_proof is not None and update.crawl_proof.members == 0 + # The next turn expands to nobody: no Drive grant for the person, no new content. + claims = len(world.claims_sent) + turn = await _turn(world) + assert turn.status == "ok" + assert (len(world.document_writes), len(world.native_requests)) == published + assert all(claim["sub"] != "one@example.com" for claim in world.claims_sent[claims:]) + + +async def test_reactivation_readmits_the_person_on_the_next_registration_check( + world: _World, +) -> None: + await _register(world) + world.ended_people.add("one@example.com") + with acting_as(verify_token(_token())): + update = KnowledgeSourceUpdateInput( + org="team", namespace="shared-space", name="documents", include=["docs", "pdf"] + ) + left_out = await ops.handle_knowledge_source_update(update) + world.ended_people.discard("one@example.com") + back = await ops.handle_knowledge_source_update(update) + assert left_out.crawl_proof is not None and left_out.crawl_proof.members == 0 + assert back.crawl_proof is not None and back.crawl_proof.members == 1 + assert "one@example.com" not in back.crawl_proof.model_dump_json() + assert set(back.crawl_proof.read_scopes) == {scope.value for scope in gdrive.ReadScope} + + +async def test_registration_re_reads_grants_only_at_its_permit_and_commit( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.auth import source_registration + + reads: list[bool] = [] + real = source_registration.Approval.validate + + async def recorded(self: Any, *, fresh: bool = True) -> None: + reads.append(fresh) + await real(self, fresh=fresh) + + monkeypatch.setattr(source_registration.Approval, "validate", recorded) + await _register(world) + # Every Directory step keeps the org's grant caches; only the permit, the captured + # approval and the commit under the lease re-read the grants. + assert reads.count(True) == 3 and reads.count(False) > 3 diff --git a/tests/unit/test_crawl_delegation.py b/tests/unit/test_crawl_delegation.py new file mode 100644 index 00000000000..a338c0c81ff --- /dev/null +++ b/tests/unit/test_crawl_delegation.py @@ -0,0 +1,173 @@ +"""Read admission requires each distinct write grant's explicit denial.""" + +from __future__ import annotations + +import time +from typing import Any +from urllib.parse import parse_qs + +import httpx +import jwt +import pytest + +from server.clients import gdrive +from server.clients import google_workspace as google +from server.clients._vendor import CredentialRefused, TooLarge, VendorError +from server.knowledge.app import crawl_delegation +from tests.unit.test_google_workspace import _Body, _http +from tests.unit.test_google_workspace import account as account + +pytestmark = pytest.mark.asyncio +_SUBJECT = "directory@example.com" + + +class _Standing: + def __init__(self) -> None: + self.live = True + + async def validate(self) -> None: + if not self.live: + raise PermissionError("source stopped") + + +def _claims(request: httpx.Request, account: Any) -> dict[str, Any]: + assert str(request.url) == "https://oauth2.googleapis.com/token" + assert not request.headers.get("authorization") + form = parse_qs(request.content.decode()) + assert set(form) == {"grant_type", "assertion"} + assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] + claims = jwt.decode( + form["assertion"][0], account[1], algorithms=["RS256"], audience=str(request.url) + ) + assert set(claims) == {"iss", "sub", "scope", "aud", "iat", "exp"} + assert claims["iss"] == account[0].client_email and claims["sub"] == _SUBJECT + assert claims["exp"] - claims["iat"] == 600 + return claims + + +async def test_all_three_reads_and_four_distinct_write_denials_are_required( + monkeypatch: pytest.MonkeyPatch, account: Any +) -> None: + scopes: list[str] = [] + + def response(request: httpx.Request) -> httpx.Response: + scope = _claims(request, account)["scope"] + scopes.append(scope) + if scope in {read.value for read in gdrive.ReadScope}: + return httpx.Response( + 200, + json={"access_token": "private", "token_type": "Bearer", "expires_in": 60}, + ) + return httpx.Response(400, json={"error": "unauthorized_client"}) + + async with _http(monkeypatch, response) as calls: + await crawl_delegation.require_read_only( + account[0], + subject=_SUBJECT, + standing=_Standing(), + deadline=time.monotonic() + 10, + max_bytes=4096, + ) + assert len(calls) == 7 + assert scopes == [*(s.value for s in gdrive.ReadScope), *(s.value for s in gdrive.WriteScope)] + assert gdrive.WriteScope.DIRECTORY_GROUPS.value != gdrive.WriteScope.DIRECTORY_MEMBERS.value + + +@pytest.mark.parametrize("scope", list(gdrive.WriteScope)) +async def test_each_successful_write_grant_refuses_admission( + monkeypatch: pytest.MonkeyPatch, account: Any, scope: gdrive.WriteScope +) -> None: + def response(request: httpx.Request) -> httpx.Response: + assert _claims(request, account)["scope"] == scope.value + return httpx.Response(200, json={"access_token": "secret-write-token"}) + + async with _http(monkeypatch, response) as calls: + with pytest.raises(CredentialRefused) as error: + await google.require_write_denied( + account[0], + subject=_SUBJECT, + scope=scope, + deadline=time.monotonic() + 10, + max_bytes=4096, + ) + assert len(calls) == 1 and "secret-write-token" not in str(error.value) + + +@pytest.mark.parametrize( + "status,error", + [ + (400, "invalid_grant"), + (400, "access_denied"), + (403, "unauthorized_client"), + (429, "unauthorized_client"), + (503, "unauthorized_client"), + (302, "unauthorized_client"), + ], +) +async def test_uncertain_or_non_scope_failure_is_never_read_only_proof( + monkeypatch: pytest.MonkeyPatch, account: Any, status: int, error: str +) -> None: + async with _http( + monkeypatch, + lambda _: httpx.Response( + status, + json={"error": error, "error_description": "secret-private-response"}, + headers={"location": "https://untrusted.example/redirect"}, + ), + ) as calls: + with pytest.raises(VendorError) as failure: + await google.require_write_denied( + account[0], + subject=_SUBJECT, + scope=gdrive.WriteScope.DIRECTORY_MEMBERS, + deadline=time.monotonic() + 10, + max_bytes=4096, + ) + assert len(calls) == 1 and "secret-private-response" not in str(failure.value) + + +async def test_oversized_denial_closes_stream_without_accepting_it( + monkeypatch: pytest.MonkeyPatch, account: Any +) -> None: + body = _Body(b'{"error":"unauthorized_client",', b'"private":"' + b"s" * 100 + b'"}') + async with _http(monkeypatch, lambda _: httpx.Response(400, stream=body)): + with pytest.raises(TooLarge): + await google.require_write_denied( + account[0], + subject=_SUBJECT, + scope=gdrive.WriteScope.DRIVE, + deadline=time.monotonic() + 10, + max_bytes=32, + ) + assert body.closed + + +async def test_standing_lost_on_a_denial_stops_before_the_next_scope( + monkeypatch: pytest.MonkeyPatch, account: Any +) -> None: + standing = _Standing() + + def response(request: httpx.Request) -> httpx.Response: + scope = _claims(request, account)["scope"] + if scope in {read.value for read in gdrive.ReadScope}: + return httpx.Response( + 200, + json={ + "access_token": "private", + "token_type": "Bearer", + "expires_in": 60, + }, + ) + standing.live = False + return httpx.Response(400, json={"error": "unauthorized_client"}) + + async with _http(monkeypatch, response) as calls: + with pytest.raises(PermissionError): + await crawl_delegation.require_read_only( + account[0], + subject=_SUBJECT, + standing=standing, + deadline=time.monotonic() + 10, + max_bytes=4096, + ) + assert len(calls) == 4 diff --git a/tests/unit/test_crawl_expansion.py b/tests/unit/test_crawl_expansion.py new file mode 100644 index 00000000000..d44053c939c --- /dev/null +++ b/tests/unit/test_crawl_expansion.py @@ -0,0 +1,306 @@ +"""Actual Directory HTTP and crawl identity rules, without a provider or database.""" + +from __future__ import annotations + +import time +from typing import Any +from urllib.parse import parse_qs + +import httpx +import jwt +import pytest + +from server.auth import scim +from server.clients._vendor import CredentialRefused, TooLarge, VendorError +from server.knowledge.app import crawl_authority +from server.knowledge.app.crawl_expansion import Limits, expand +from server.knowledge.domain.source_crawl import Options +from server.settings import settings +from tests.unit.test_google_workspace import _http +from tests.unit.test_google_workspace import account as account + +pytestmark = pytest.mark.asyncio +_NATIVE_SCIM_READ = scim.any_deactivated + + +class _ScimRows: + """loom.scim_users as the batched deactivation read sees it.""" + + def __init__(self) -> None: + self.ended: set[str] = set() + self.asked: list[list[str]] = [] + + async def query_one(self, sql: str, *, params: dict[str, Any]): + self.asked.append(params["ids"]) + return {"x": 1} if self.ended.intersection(params["ids"]) else None + + +@pytest.fixture(autouse=True) +def scim_rows(monkeypatch: pytest.MonkeyPatch) -> _ScimRows: + rows = _ScimRows() + monkeypatch.setattr(scim, "any_deactivated", _NATIVE_SCIM_READ) + monkeypatch.setattr(scim, "get_client", lambda: rows) + return rows + + +class _Standing: + current = True + + async def validate(self) -> None: + if not self.current: + raise PermissionError("source authority ended") + + +class _Directory: + def __init__(self) -> None: + self.members: dict[str, list[dict[str, Any]]] = { + "team@example.com": [ + {"type": "USER", "id": "one", "email": "one@example.com"}, + {"type": "GROUP", "id": "nested", "email": "nested@example.com"}, + ], + "nested": [{"type": "USER", "id": "two", "email": "two@example.com"}], + } + self.customer = "workspace" + self.after_user: Any = lambda: None + + def answer(self, request: httpx.Request) -> httpx.Response: + if request.url.host == "oauth2.googleapis.com": + form = parse_qs(request.content.decode()) + claims = jwt.decode(form["assertion"][0], options={"verify_signature": False}) + assert claims["sub"] == "directory@example.com" + return httpx.Response( + 200, + json={"access_token": "private-token", "token_type": "Bearer", "expires_in": 60}, + ) + assert request.url.host == "admin.googleapis.com" + assert request.headers["authorization"] == "Bearer private-token" + if "/groups/" in request.url.path: + key = request.url.path.split("/groups/", 1)[1].removesuffix("/members") + return httpx.Response(200, json={"members": self.members[key]}) + key = request.url.path.rsplit("/", 1)[1] + identifier = {"one@example.com": "one", "alias@example.com": "one"}.get(key, key) + principal = key == "directory@example.com" + self.after_user() + return httpx.Response( + 200, + json={ + "id": identifier, + "primaryEmail": key if principal else f"{identifier}@example.com", + "aliases": ["alias@example.com"] if identifier == "one" else [], + "customerId": "workspace" if principal else self.customer, + "suspended": False, + "archived": False, + }, + ) + + +def _options(*subjects: tuple[str, str]) -> Options: + return Options.parse( + { + "directory_subject": "directory@example.com", + "subjects": [{"type": kind, "email": email} for kind, email in subjects], + } + ) + + +async def _run( + options: Options, + account: Any, + standing: _Standing, + *, + limits: Limits | None = None, +): + return await expand( + options, + account[0], + standing=standing, + limits=limits or Limits(body_bytes=16384, member_pages=10, groups=10), + deadline=time.monotonic() + 10, + ) + + +async def test_current_scim_deletion_excludes_a_person_and_every_group_entry( + monkeypatch: pytest.MonkeyPatch, account: Any, scim_rows: _ScimRows +) -> None: + directory = _Directory() + # Deactivated under an alias only: every Workspace address of the person is read. + scim_rows.ended.add(scim.user_id("alias@example.com")) + async with _http(monkeypatch, directory.answer): + result = await _run( + _options(("person", "one@example.com"), ("group", "team@example.com")), + account, + _Standing(), + ) + assert [person.id for person in result.people] == ["two"] + assert all("one@example.com" not in members for _, members in result.groups) + + +async def test_complete_nested_groups_and_explicit_alias_share_stable_provider_identity( + monkeypatch: pytest.MonkeyPatch, + account: Any, +) -> None: + directory = _Directory() + async with _http(monkeypatch, directory.answer) as calls: + result = await _run( + _options(("group", "team@example.com"), ("person", "alias@example.com")), + account, + _Standing(), + ) + assert [(p.customer, p.id, p.email) for p in result.people] == [ + ("workspace", "one", "one@example.com"), + ("workspace", "two", "two@example.com"), + ] + assert dict(result.groups) == { + "nested@example.com": ("two@example.com",), + "team@example.com": ("one@example.com", "two@example.com"), + } + assert sum(r.url.path.endswith("/users/one") for r in calls) == 1 + assert not any(r.url.path.endswith("/users/alias@example.com") for r in calls) + assert "example.com" not in repr(result) and "example.com" not in repr(result.people[0]) + + +async def test_deactivated_person_is_absent_from_direct_and_all_nested_membership( + monkeypatch: pytest.MonkeyPatch, + account: Any, + scim_rows: _ScimRows, +) -> None: + directory = _Directory() + scim_rows.ended.add(scim.user_id("two@example.com")) + async with _http(monkeypatch, directory.answer): + result = await _run( + _options(("group", "team@example.com"), ("person", "two@example.com")), + account, + _Standing(), + ) + assert [p.id for p in result.people] == ["one"] + assert dict(result.groups) == { + "nested@example.com": (), + "team@example.com": ("one@example.com",), + } + # One batched read per person, over every Workspace address it has. + assert sorted(scim_rows.asked) == sorted( + [ + sorted(scim.user_id(a) for a in ("one@example.com", "alias@example.com")), + [scim.user_id("two@example.com")], + ] + ) + + +@pytest.mark.parametrize("failure", ["cycle", "customer", "group-bound"]) +async def test_unproven_or_incomplete_expansion_never_returns_partial_readers( + monkeypatch: pytest.MonkeyPatch, + account: Any, + failure: str, +) -> None: + directory = _Directory() + monkeypatch.setattr( + settings, "knowledge_crawl_max_groups", 1 if failure == "group-bound" else 10 + ) + limits = crawl_authority.configured_bounds().directory + if failure == "cycle": + directory.members["nested"] = [{"type": "GROUP", "id": "team", "email": "team@example.com"}] + elif failure == "customer": + directory.members["nested"] = [{"type": "CUSTOMER", "id": "workspace"}] + async with _http(monkeypatch, directory.answer): + with pytest.raises((VendorError, CredentialRefused, TooLarge)): + await _run( + _options(("group", "team@example.com")), + account, + _Standing(), + limits=limits, + ) + + +@pytest.mark.parametrize("state", ["suspended", "external", "missing"]) +async def test_a_selected_person_the_workspace_no_longer_holds_is_left_out( + monkeypatch: pytest.MonkeyPatch, account: Any, state: str +) -> None: + directory = _Directory() + answer = directory.answer + + def unavailable_two(request: httpx.Request) -> httpx.Response: + response = answer(request) + if not request.url.path.endswith("/users/two@example.com"): + return response + if state == "missing": + return httpx.Response(404, json={"error": {"code": 404}}) + body = {**response.json(), "id": "two", "primaryEmail": "two@example.com"} + if state == "external": + body["customerId"] = "foreign-workspace" + else: + body["suspended"] = True + return httpx.Response(200, json=body) + + options = _options(("person", "one@example.com"), ("person", "two@example.com")) + async with _http(monkeypatch, unavailable_two): + if state == "missing": + # An address the Directory does not know may be a typo: the selection refuses. + with pytest.raises((VendorError, CredentialRefused)): + await _run(options, account, _Standing()) + return + result = await _run(options, account, _Standing()) + assert [p.id for p in result.people] == ["one"] + + +@pytest.mark.parametrize("state", ["suspended", "archived", "external", "missing"]) +async def test_an_unavailable_group_member_is_left_out_of_the_readers( + monkeypatch: pytest.MonkeyPatch, account: Any, state: str +) -> None: + directory = _Directory() + answer = directory.answer + + def unavailable_two(request: httpx.Request) -> httpx.Response: + response = answer(request) + if not request.url.path.endswith("/users/two"): + return response + if state == "missing": + return httpx.Response(404, json={"error": {"code": 404}}) + body = response.json() + if state == "external": + body["customerId"] = "foreign-workspace" + else: + body[state] = True + return httpx.Response(200, json=body) + + async with _http(monkeypatch, unavailable_two): + result = await _run(_options(("group", "team@example.com")), account, _Standing()) + assert [p.id for p in result.people] == ["one"] + assert dict(result.groups) == { + "nested@example.com": (), + "team@example.com": ("one@example.com",), + } + + +async def test_loss_during_directory_response_stops_before_another_provider_dispatch( + monkeypatch: pytest.MonkeyPatch, + account: Any, +) -> None: + directory, standing = _Directory(), _Standing() + + def changed() -> None: + standing.current = False + + directory.after_user = changed + async with _http(monkeypatch, directory.answer) as calls: + with pytest.raises(PermissionError): + await _run(_options(("group", "team@example.com")), account, standing) + assert len(calls) == 2 # Token and identity response; no members or person request. + + +async def test_directory_page_budget_is_global_across_selected_groups( + monkeypatch: pytest.MonkeyPatch, + account: Any, +) -> None: + directory = _Directory() + directory.members["team@example.com"] = [] + directory.members["other@example.com"] = [] + monkeypatch.setattr(settings, "knowledge_crawl_directory_max_pages", 1) + async with _http(monkeypatch, directory.answer) as calls: + with pytest.raises(TooLarge, match="page bound"): + await _run( + _options(("group", "team@example.com"), ("group", "other@example.com")), + account, + _Standing(), + limits=crawl_authority.configured_bounds().directory, + ) + assert sum("/groups/" in r.url.path for r in calls) == 1 diff --git a/tests/unit/test_crawl_fleet_migration.py b/tests/unit/test_crawl_fleet_migration.py new file mode 100644 index 00000000000..c65b35e0fa7 --- /dev/null +++ b/tests/unit/test_crawl_fleet_migration.py @@ -0,0 +1,93 @@ +"""Crawl admission waits for the migration that supplies its authorization state.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock + +import pytest + +from server.core.errors import OverloadedError +from server.knowledge.app import crawl_sources +from server.knowledge.domain.sources import KnowledgeSource + +_CRAWL = crawl_sources._CRAWL_MIGRATION + + +def test_the_gate_names_the_crawl_migration() -> None: + from server.core.paths import MIGRATIONS_DIR + + assert (MIGRATIONS_DIR / f"{_CRAWL}_workspace_crawl.sql").is_file() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("supported", [_CRAWL - 2, _CRAWL - 1, _CRAWL]) +async def test_registration_requires_the_crawl_migration_on_every_process( + monkeypatch: pytest.MonkeyPatch, supported: int +) -> None: + client = object() + permit = object() + scope = object() + required_versions: list[int] = [] + validation = AsyncMock() + + async def fleet_at(ch: object, required: int) -> bool: + assert ch is client + required_versions.append(required) + return supported >= required + + monkeypatch.setattr(crawl_sources, "get_client", lambda: client) + monkeypatch.setattr(crawl_sources.crawl_authority, "scope", lambda _source: scope) + monkeypatch.setattr(crawl_sources._Draft, "validate", validation) + monkeypatch.setattr( + crawl_sources.source_registration, "current_permit", AsyncMock(return_value=permit) + ) + monkeypatch.setattr(crawl_sources.machines, "fleet_at", fleet_at) + source = KnowledgeSource("org", "namespace", "name", "gdrive", "source") + + if supported < _CRAWL: + with pytest.raises(OverloadedError, match="not every process enforces crawl authority"): + await crawl_sources._draft(source, None) + assert validation.await_count == 1 + else: + draft = await crawl_sources._draft(source, None) + assert draft.source is source and draft.permit is permit + assert validation.await_count == 2 + assert required_versions == [_CRAWL] + + +@pytest.mark.asyncio +async def test_an_unreadable_scim_standing_refuses_a_crawl_op_as_unavailable( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.auth import login + from server.core.errors import BackendUnavailableError, error_class + + monkeypatch.setattr(crawl_sources.request_work, "mark_mirrored", lambda: True) + with pytest.raises(BackendUnavailableError) as refused: + async with crawl_sources.private(): + raise login.SignInUnavailable() + assert error_class(refused.value.code, refused.value.status_code)[1] is True + + +@pytest.mark.asyncio +@pytest.mark.parametrize("raised", ["refused", "scim"]) +async def test_remove_and_sync_refuse_without_a_server_error( + monkeypatch: pytest.MonkeyPatch, raised: str +) -> None: + from server.auth import login + from server.core.errors import BackendUnavailableError, ValidationError + + async def permit(_scope: object, **_kwargs: object) -> object: + if raised == "scim": + raise login.SignInUnavailable() + raise crawl_sources.source_registration.Refused() + + monkeypatch.setattr(crawl_sources.request_work, "mark_mirrored", lambda: True) + monkeypatch.setattr(crawl_sources.crawl_authority, "scope", lambda _source: object()) + monkeypatch.setattr(crawl_sources.source_registration, "current_permit", permit) + source = KnowledgeSource( + "org", "namespace", "name", "gdrive", "source", credential_mode="crawl" + ) + expected = BackendUnavailableError if raised == "scim" else ValidationError + with pytest.raises(expected): + await crawl_sources.require_operator(source) diff --git a/tests/unit/test_crawl_registration.py b/tests/unit/test_crawl_registration.py new file mode 100644 index 00000000000..cadd97aa139 --- /dev/null +++ b/tests/unit/test_crawl_registration.py @@ -0,0 +1,200 @@ +"""Real JWT and shared authorization rules for an exact retained source approval.""" + +from __future__ import annotations + +import dataclasses +import json +import time +from typing import Any + +import jwt +import pytest + +from server.auth import authz +from server.auth import source_registration as registration +from server.auth.context import current_auth +from server.auth.jwt import AuthInfo, verify_token +from server.core.secrets_at_rest import seal, unseal +from server.operations.base import Role +from server.settings import settings +from tests.unit.principals import acting_as +from tests.unit.test_connected_source_authority import world as world +from tests.unit.test_crawl_signing_authority import _SECOND +from tests.unit.test_crawl_signing_authority import key_view as key_view + +pytestmark = [pytest.mark.asyncio, pytest.mark.claim_cap] +_SCOPE = registration.Scope("team", "shared-space", "crawl-source", "crawl-generation", "f" * 64) + + +def _token(**changes: Any) -> str: + now = int(time.time()) + return jwt.encode( + { + "sub": "person@example.com", + "org": "team", + "namespaces": ["shared-space"], + "roles": ["org_admin"], + "sa": False, + "iss": settings.jwt_issuer, + "aud": settings.jwt_audience, + "iat": now - 10, + "exp": now + 3600, + "jti": "registration-token", + **changes, + }, + _SECOND, + algorithm="HS256", + headers={"kid": "signer"}, + ) + + +async def _approval(state: Any, **changes: Any): + state.grant = Role.ADMIN + raw = _token(**changes) + auth = verify_token(raw) + with acting_as(auth): + registrant, encoded = await registration.capture(auth, _SCOPE) + return auth, registrant, encoded, raw + + +async def test_retained_metadata_is_exact_scoped_and_never_becomes_a_request_principal( + world: Any, + key_view: list[str], +) -> None: + state, _http = world + auth, registrant, encoded, raw = await _approval(state) + approval = registration.load(encoded, _SCOPE, registrant=registrant) + before = current_auth() + await approval.validate() + assert current_auth() is before + assert registrant == "person" and not isinstance(approval.claims, AuthInfo) + assert approval.claims.roles == auth.roles and approval.claims.expires_at == auth.expires_at + plain = unseal(registration.PURPOSE, encoded) + assert raw not in plain and _SECOND not in plain + assert json.loads(plain)["scope"] == dataclasses.asdict(_SCOPE) + with pytest.raises(PermissionError, match="invalid auth principal"): + await authz.check_authorized(approval.claims, Role.ADMIN, "team", "shared-space") + + +@pytest.mark.parametrize("field", ["org", "namespace", "source_id"]) +async def test_an_approval_copied_from_another_scope_fails_its_scope_check( + world: Any, + key_view: list[str], + field: str, +) -> None: + state, _http = world + _auth, _registrant, encoded, _raw = await _approval(state) + scope = {"org": "team", "namespace": "shared-space", "source_id": "crawl-source"} + registration.check_scope(encoded, **scope) + scope[field] = "foreign" + with pytest.raises(registration.Refused): + registration.check_scope(encoded, **scope) + + +@pytest.mark.parametrize("nested", [False, True]) +async def test_unknown_retained_claim_restrictions_refuse_instead_of_being_ignored( + world: Any, + key_view: list[str], + nested: bool, +) -> None: + state, _http = world + _auth, registrant, original, _raw = await _approval(state) + frame = json.loads(unseal(registration.PURPOSE, original)) + target = frame["claims"]["signing_authority"] if nested else frame["claims"] + target["future_restriction"] = {"deny": True} + encoded = seal(registration.PURPOSE, json.dumps(frame)) + with pytest.raises(registration.Refused): + registration.load(encoded, _SCOPE, registrant=registrant) + + +@pytest.mark.parametrize("field", ["namespace", "source_id", "generation", "org", "resource_hash"]) +async def test_copied_ciphertext_cannot_approve_another_source_or_generation( + world: Any, + key_view: list[str], + field: str, +) -> None: + state, _http = world + _auth, registrant, encoded, _raw = await _approval(state) + changed = dataclasses.replace(_SCOPE, **{field: "different"}) + with pytest.raises(registration.Refused): + registration.load(encoded, changed, registrant=registrant) + + +async def test_namespace_demotion_refuses_retained_named_claim_using_fresh_real_grants( + world: Any, + key_view: list[str], +) -> None: + state, _http = world + _auth, registrant, encoded, _raw = await _approval(state) + approval = registration.load(encoded, _SCOPE, registrant=registrant) + state.grant = Role.WRITER + with pytest.raises(PermissionError): + await approval.validate() + + +async def test_flat_wildcard_org_role_keeps_existing_additive_claim_semantics( + world: Any, + key_view: list[str], +) -> None: + state, _http = world + _auth, registrant, encoded, _raw = await _approval(state, namespaces=["*"]) + state.grant = Role.WRITER + await registration.load(encoded, _SCOPE, registrant=registrant).validate() + + +@pytest.mark.parametrize( + "change", + [ + {"roles": ["admin"]}, + {"roles": ["org_admin"], "ns_roles": {"shared-space": "viewer"}}, + ], +) +async def test_registration_requires_both_real_flat_org_role_and_namespace_admin( + world: Any, + key_view: list[str], + change: dict[str, Any], +) -> None: + state, _http = world + state.grant = Role.ADMIN + auth = verify_token(_token(**change)) + with acting_as(auth), pytest.raises(PermissionError): + await registration.capture(auth, _SCOPE) + + +@pytest.mark.parametrize("loss", ["signing-key", "token-revocation", "scim", "expiry"]) +async def test_registration_rechecks_actual_signing_token_and_person_authority( + monkeypatch: pytest.MonkeyPatch, + world: Any, + key_view: list[str], + loss: str, +) -> None: + state, _http = world + auth, registrant, encoded, _raw = await _approval(state) + approval = registration.load(encoded, _SCOPE, registrant=registrant) + if loss == "signing-key": + key_view.remove(_SECOND) + elif loss == "token-revocation": + state.cutoffs["registration-token"] = None + elif loss == "scim": + state.scim_ended = True + else: + assert auth.expires_at is not None + monkeypatch.setattr( + registration, "_now", lambda: auth.expires_at + settings.jwt_leeway_seconds + 1 + ) + with pytest.raises(PermissionError): + await approval.validate() + + +async def test_offline_verified_or_changed_presenter_cannot_create_persistent_approval( + world: Any, + key_view: list[str], +) -> None: + state, _http = world + state.grant = Role.ADMIN + offline = verify_token(_token(), secret=_SECOND) + with acting_as(offline), pytest.raises(registration.Refused): + await registration.capture(offline, _SCOPE) + auth = verify_token(_token()) + with acting_as(auth), pytest.raises(registration.Refused): + await registration.capture(dataclasses.replace(auth), _SCOPE) diff --git a/tests/unit/test_crawl_restore.py b/tests/unit/test_crawl_restore.py new file mode 100644 index 00000000000..e06a7531201 --- /dev/null +++ b/tests/unit/test_crawl_restore.py @@ -0,0 +1,355 @@ +"""Restored crawl authority ends before the real reconciliation publishes held rows.""" + +from __future__ import annotations + +import copy +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from typing import Any + +import pytest + +from server.cli import restore as cli_restore +from server.core import leases +from server.knowledge.app import connected_restore, crawl_restore +from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.store import mirrors, source_retirements +from server.knowledge.store import sources as source_store +from server.settings import settings +from tests.unit.test_connected_account_restore import _unrelated_restore_participants + +pytestmark = pytest.mark.asyncio +_MIRROR = "acl-" + "a" * 24 +_FIRST = "00000000-0000-4000-8000-000000000001" +_SECOND = "00000000-0000-4000-8000-000000000002" + + +def _sql(value: str) -> str: + return " ".join(value.split()) + + +class _HistoryWorld: + """Raw source versions, exact leases and only the SQL used by the real stores.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + settings, "jwt_secret", "first-root-sealing-secret-which-is-long-enough" + ) + monkeypatch.setattr(settings, "jwt_secret_previous", "") + self.queries = 0 + self.sources: list[dict[str, Any]] = [] + self.retirements: list[dict[str, Any]] = [] + self.scope: tuple[str, str] | None = None + self.seeding = False + self.ignore_mutation = False + self.executed: list[str] = [] + self.page_reads: list[tuple[str, str, str]] = [] + monkeypatch.setattr(crawl_restore, "get_client", lambda: self) + monkeypatch.setattr(source_store, "_default_client", lambda: self) + monkeypatch.setattr(mirrors, "_default_client", lambda: self) + monkeypatch.setattr(source_retirements, "_default_client", lambda: self) + monkeypatch.setattr(leases, "holding", self.source_lease) + + @asynccontextmanager + async def source_lease( + self, name: str, *, ttl_s: float, wait_s: float, ch: Any = None, settle_writes: bool + ) -> AsyncIterator[bool]: + assert ch is None or ch is self + assert settle_writes is True + prefix, org, namespace = name.split(":") + assert prefix == "knowledge-source" and org == "org" and namespace == "namespace" + assert self.scope is None and ttl_s == 60.0 and wait_s == 5.0 + self.scope = org, namespace + try: + yield True + finally: + self.scope = None + + async def seed(self, **changes: Any) -> None: + self.seeding = True + try: + source = KnowledgeSource( + **( + { + "org": "org", + "namespace": "namespace", + "name": "documents", + "kind": "gdrive", + "source_id": _FIRST, + "items": [{"type": "file", "id": "file"}], + "credential_mode": "crawl", + "access": "mirrored", + "secret_enc": "retained-service-key", + "approval_enc": "historical-approval", + "registrant_subject": "registrant", + "crawl_generation": "generation", + "crawl_customer_id": "workspace", + "crawl_credential_hash": "a" * 64, + "crawl_options": { + "directory_subject": "directory@example.com", + "subjects": [{"type": "person", "email": "person@example.com"}], + }, + } + | changes + ) + ) + await source_store.insert_source(source, ch=self) + finally: + self.seeding = False + + def _crawl_rows(self, org: str) -> list[dict[str, Any]]: + return [r for r in self.sources if r["org"] == org and r["credential_mode"] == "crawl"] + + async def query_one(self, sql: str, *, params: dict[str, Any] | None = None): + self.queries += 1 + compact = _sql(sql) + if compact.startswith("SELECT count() AS n FROM loom.worker_status "): + assert params == {"s": 2 * settings.supervisor_lease_ttl_s} + return {"n": 0} + if compact.startswith("SELECT count() AS n FROM loom.knowledge_sources "): + assert params is not None + self._count_query(compact, params) + return {"n": len(self._mutation_rows(compact, params))} + if compact.startswith( + "SELECT " + source_store._COLUMNS + " FROM loom.knowledge_sources FINAL " + ): + assert params is not None and set(params) == {"org", "ns", "name"} + assert compact.endswith("AND name = {name:String} LIMIT 1") + assert self.scope == (params["org"], params["ns"]) + found = [ + r + for r in self.sources + if (r["org"], r["namespace"], r["name"]) + == (params["org"], params["ns"], params["name"]) + ] + return copy.deepcopy(found[-1]) if found else None + raise AssertionError(compact) + + async def query_all(self, sql: str, *, params: dict[str, Any]): + self.queries += 1 + compact = _sql(sql) + if compact.startswith("SELECT DISTINCT org FROM loom.knowledge_sources "): + assert params == {"limit": settings.knowledge_crawl_registry_scan_limit + 1} + assert compact == ( + "SELECT DISTINCT org FROM loom.knowledge_sources " + "WHERE credential_mode = 'crawl' ORDER BY org LIMIT {limit:UInt32}" + ) + orgs = sorted({r["org"] for r in self.sources if r["credential_mode"] == "crawl"}) + return [{"org": org} for org in orgs[: params["limit"]]] + if compact.startswith("SELECT DISTINCT " + source_store._COLUMNS): + assert " FINAL " not in compact and set(params) == {"org", "limit"} + assert params["limit"] == settings.knowledge_crawl_registry_scan_limit + 1 + assert compact.endswith( + "AND credential_mode = 'crawl' ORDER BY namespace, name, source_id, updated_at LIMIT {limit:UInt32}" + ) + columns = source_store._COLUMNS.split(", ") + unique = {tuple(row[k] for k in columns) for row in self._crawl_rows(params["org"])} + rows = [dict(zip(columns, values, strict=True)) for values in unique] + return sorted( + rows, key=lambda r: (r["namespace"], r["name"], r["source_id"], r["updated_at"]) + )[: params["limit"]] + if compact.startswith("SELECT mirror, namespace FROM loom.knowledge_mirrors FINAL "): + assert params == {"org": "org", "namespaces": ["namespace"]} + assert compact.endswith("AND NOT deleted ORDER BY mirror") + assert self.scope == ("org", "namespace") + return [{"mirror": _MIRROR, "namespace": "namespace"}] + if compact.startswith("SELECT DISTINCT org, namespace, name FROM loom.knowledge_sources "): + return self._approval_page(compact, params) + if compact.startswith("SELECT DISTINCT toString(source_id) AS source_id, approval_enc "): + return self._approval_values(compact, params) + raise AssertionError(compact) + + def _approval_page(self, sql: str, params: dict[str, Any]): + assert ( + sql + == "SELECT DISTINCT org, namespace, name FROM loom.knowledge_sources WHERE (org, namespace, name) > {after:Tuple(String, String, String)} AND approval_enc != '' ORDER BY org, namespace, name LIMIT {limit:UInt32}" + ) + assert set(params) == {"after", "limit"} + assert params["limit"] == settings.knowledge_crawl_registry_page_size + self.page_reads.append(params["after"]) + keys = sorted( + { + (r["org"], r["namespace"], r["name"]) + for r in self.sources + if r["approval_enc"] and (r["org"], r["namespace"], r["name"]) > params["after"] + } + ) + return [ + dict(zip(("org", "namespace", "name"), k, strict=True)) for k in keys[: params["limit"]] + ] + + def _approval_values(self, sql: str, params: dict[str, Any]): + assert ( + sql + == "SELECT DISTINCT toString(source_id) AS source_id, approval_enc FROM loom.knowledge_sources WHERE org = {org:String} AND namespace = {ns:String} AND name = {name:String} AND credential_mode = 'crawl' AND approval_enc != '' LIMIT {limit:UInt32}" + ) + assert set(params) == {"org", "ns", "name", "limit"} + assert params["limit"] == settings.knowledge_crawl_registry_scan_limit + 1 + assert self.scope == (params["org"], params["ns"]) + pairs = sorted( + { + (r["source_id"], r["approval_enc"]) + for r in self._crawl_rows(params["org"]) + if r["namespace"] == params["ns"] + and r["name"] == params["name"] + and r["approval_enc"] + } + ) + return [ + {"source_id": source, "approval_enc": encoded} + for source, encoded in pairs[: params["limit"]] + ] + + def _mutation_rows(self, sql: str, params: dict[str, Any]): + if set(params) >= {"org", "ns", "id", "old", "new"}: + assert "namespace = {ns:String} AND source_id = {id:String}" in sql + assert "credential_mode = 'crawl' AND approval_enc = {old:String}" in sql + return [ + r + for r in self._crawl_rows(params["org"]) + if r["namespace"] == params["ns"] + and r["source_id"] == params["id"] + and r["approval_enc"] == params["old"] + ] + assert set(params) == {"org"} + assert "org = {org:String} AND credential_mode = 'crawl'" in sql + rows = self._crawl_rows(params["org"]) + if "(active OR approval_enc != '' OR crawl_generation != '')" in sql: + rows = [r for r in rows if r["active"] or r["approval_enc"] or r["crawl_generation"]] + return rows + + def _count_query(self, sql: str, params: dict[str, Any]) -> None: + prefix = "SELECT count() AS n FROM loom.knowledge_sources WHERE " + if "old" in params: + assert sql == ( + prefix + "org = {org:String} AND namespace = {ns:String} " + "AND source_id = {id:String} AND credential_mode = 'crawl' " + "AND approval_enc = {old:String}" + ) + else: + assert sql == ( + prefix + "org = {org:String} AND credential_mode = 'crawl' " + "AND (active OR approval_enc != '' OR crawl_generation != '')" + ) + + async def execute( + self, sql: str, *, params: dict[str, Any], settings: dict[str, Any] | None = None + ): + compact = _sql(sql) + assert compact.startswith("ALTER TABLE loom.knowledge_sources UPDATE ") + self.executed.append(compact) + rows = self._mutation_rows(compact, params) + if "UPDATE approval_enc = {new:String}" in compact: + assert compact == ( + "ALTER TABLE loom.knowledge_sources UPDATE approval_enc = {new:String} " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND source_id = {id:String} AND credential_mode = 'crawl' " + "AND approval_enc = {old:String}" + ) + assert settings == {"mutations_sync": 2} + assert self.scope == (params["org"], params["ns"]) + if not self.ignore_mutation: + for row in rows: + row["approval_enc"] = params["new"] + return + assert compact == ( + "ALTER TABLE loom.knowledge_sources UPDATE active = 0, approval_enc = '', " + "crawl_generation = '' WHERE org = {org:String} AND credential_mode = 'crawl'" + ) + assert settings == {"mutations_sync": 2} and self.scope is None + if not self.ignore_mutation: + for row in rows: + row.update(active=False, approval_enc="", crawl_generation="") + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + if table == source_store.TABLE: + if not self.seeding: + assert self.scope == ("org", "namespace") + self.sources.extend(copy.deepcopy(rows)) + elif table == source_retirements.TABLE: + assert self.scope == ("org", "namespace") + for row in rows: + item = source_retirements.from_row(row) + assert (item.org, item.namespace, item.mirror) == ("org", "namespace", _MIRROR) + assert row["state_value"] == "pending" + self.retirements.extend(copy.deepcopy(rows)) + else: + raise AssertionError(table) + + +async def _restored(monkeypatch: pytest.MonkeyPatch) -> _HistoryWorld: + world = _HistoryWorld(monkeypatch) + await world.seed(approval_enc="older-approval", crawl_generation="older") + await world.seed(approval_enc="newer-approval", crawl_generation="newer") + await world.seed(source_id=_SECOND, approval_enc="replacement-approval") + await world.seed(name="shared", credential_mode="shared", approval_enc="unrelated") + return world + + +def _participants(monkeypatch: pytest.MonkeyPatch, before_publish: Any) -> None: + _unrelated_restore_participants(monkeypatch, before_publish) + + async def no_accounts(*, apply: bool, ch: Any) -> None: + assert isinstance(ch, _HistoryWorld) + + monkeypatch.setattr(connected_restore, "restore_all", no_accounts) + + +async def test_reconcile_invalidates_every_historical_crawl_approval_before_publication( + monkeypatch, +): + world = await _restored(monkeypatch) + shared = copy.deepcopy(world.sources[-1]) + published = [] + + def before_publish(): + assert all( + not r["active"] and not r["approval_enc"] and not r["crawl_generation"] + for r in world._crawl_rows("org") + ) + assert {json.loads(r["detail"])["source_id"] for r in world.retirements} == { + _FIRST, + _SECOND, + } + published.append(True) + + _participants(monkeypatch, before_publish) + assert await cli_restore.reconcile("clickhouse", datetime.now(UTC), apply=True, ch=world) == 0 + assert published == [True, True] + assert world.sources[3] == shared + # The restore's own retirement rows hold no key, selection or registrant; the + # history it restored keeps what the backup held, approval and generation cleared. + seeded, written = world.sources[:4], world.sources[4:] + assert all(r["secret_enc"] == "retained-service-key" for r in seeded) + assert written and all( + not r["secret_enc"] and r["options_json"] == "{}" and not r["registrant_subject"] + for r in written + ) + + +async def test_ignored_history_invalidation_cannot_report_restored_publication_safe(monkeypatch): + world = await _restored(monkeypatch) + world.ignore_mutation = True + published = [] + _participants(monkeypatch, lambda: published.append(True)) + assert await cli_restore.reconcile("clickhouse", datetime.now(UTC), apply=True, ch=world) == 1 + assert world.executed and world.retirements and not published + assert any(r["approval_enc"] for r in world._crawl_rows("org")) + + +async def test_crawl_restore_dry_run_preserves_history(monkeypatch): + world = await _restored(monkeypatch) + before = copy.deepcopy(world.sources) + await crawl_restore.restore_all(apply=False, ch=world) + assert world.sources == before + assert not world.retirements and not world.executed + + +async def test_crawl_restore_refuses_a_different_target_before_storage_access(monkeypatch): + world = await _restored(monkeypatch) + before = copy.deepcopy((world.sources, world.retirements, world.executed, world.queries)) + with pytest.raises(RuntimeError, match="crawl_restore_target_mismatch"): + await crawl_restore.restore_all(apply=True, ch=object()) + assert (world.sources, world.retirements, world.executed, world.queries) == before diff --git a/tests/unit/test_crawl_signing_authority.py b/tests/unit/test_crawl_signing_authority.py new file mode 100644 index 00000000000..7290515f51d --- /dev/null +++ b/tests/unit/test_crawl_signing_authority.py @@ -0,0 +1,89 @@ +"""A retained registration remembers the key that actually verified its claim.""" + +from __future__ import annotations + +import time + +import jwt +import pytest + +from server.auth import jwt as auth_jwt +from server.auth import keyring, revocation +from server.core import cell +from server.settings import settings + +_FIRST = "first-signing-material-with-more-than-thirty-two-bytes" +_SECOND = "second-signing-material-with-more-than-thirty-two-bytes" + + +def _token(secret: str) -> str: + return jwt.encode( + { + "sub": "registrant", + "org": "org", + "namespaces": ["team"], + "roles": ["org_admin"], + "sa": False, + "iss": settings.jwt_issuer, + "aud": settings.jwt_audience, + "iat": int(time.time()), + "jti": "registration-token", + }, + secret, + algorithm="HS256", + headers={"kid": "signer"}, + ) + + +@pytest.fixture +def key_view(monkeypatch: pytest.MonkeyPatch) -> list[str]: + # External snapshots are healthy; the signature/claim verifier remains real. + keys = [_FIRST, _SECOND] + monkeypatch.setattr(cell, "gate_reason", lambda: "") + monkeypatch.setattr(keyring, "loaded", lambda: True) + monkeypatch.setattr(keyring, "stale", lambda: False) + monkeypatch.setattr(keyring, "verification_keys", lambda kid, algorithm: list(keys)) + monkeypatch.setattr(revocation, "loaded", lambda: True) + monkeypatch.setattr(revocation, "snapshot_age_seconds", lambda: 0) + monkeypatch.setattr(revocation, "is_revoked", lambda *args, **kwargs: False) + return keys + + +def test_retained_authority_pins_successful_key_not_first_same_kid_candidate( + key_view: list[str], +) -> None: + auth = auth_jwt.verify_token(_token(_SECOND)) + authority = auth.signing_authority + assert authority is not None and authority.current() + assert (authority.issuer, authority.kid, authority.algorithm) == ( + settings.jwt_issuer, + "signer", + "HS256", + ) + key_view.remove(_SECOND) + assert not authority.current() # A different still-valid key under this kid cannot inherit it. + assert _FIRST not in repr(auth) and _SECOND not in repr(auth) + + +@pytest.mark.parametrize("failure", ["unloaded", "stale", "untrusted-issuer"]) +def test_retained_authority_requires_current_signing_and_issuer_configuration( + monkeypatch: pytest.MonkeyPatch, + key_view: list[str], + failure: str, +) -> None: + authority = auth_jwt.verify_token(_token(_SECOND)).signing_authority + assert authority is not None + if failure == "unloaded": + monkeypatch.setattr(keyring, "loaded", lambda: False) + elif failure == "stale": + monkeypatch.setattr(keyring, "stale", lambda: True) + else: + monkeypatch.setattr(settings, "jwt_issuer", "changed-issuer") + assert not authority.current() + + +def test_explicit_offline_secret_verification_creates_no_persistable_authority( + key_view: list[str], +) -> None: + auth = auth_jwt.verify_token(_token(_SECOND), secret=_SECOND) + assert auth.subject == "registrant" and auth.signing_authority is None diff --git a/tests/unit/test_crawl_source_handlers.py b/tests/unit/test_crawl_source_handlers.py new file mode 100644 index 00000000000..d86b6507840 --- /dev/null +++ b/tests/unit/test_crawl_source_handlers.py @@ -0,0 +1,215 @@ +"""Crawl source handlers: remove and sync_now ask the operator check, a removed or retired +crawl row keeps no selection, approval or registrant, a listing shows crawl options only +to an operator, and a provider outage answers retryably.""" + +from __future__ import annotations + +import contextlib +from collections.abc import AsyncIterator +from typing import Any + +import pytest + +from server.core.errors import ValidationError +from server.knowledge.api.models_sources import ( + KnowledgeSourceRemoveInput, + KnowledgeSourceSyncNowInput, +) +from server.knowledge.app import crawl_sources, source_push, sources +from server.knowledge.domain.sources import KnowledgeSource + +_SOURCE = KnowledgeSource( + org="org", + namespace="team", + name="workspace", + kind="gdrive", + source_id="a8895a80-d41c-4515-8c89-57fc1f7b4994", + config={}, + credential_mode="crawl", + access="mirrored", + items=[{"type": "folder", "id": "folder-identifier"}], + crawl_options={ + "directory_subject": "directory@example.com", + "subjects": [{"type": "group", "email": "team@example.com"}], + }, + approval_enc="sealed-approval", + registrant_subject="admin@example.com", +) + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> dict[str, list[Any]]: + seen: dict[str, list[Any]] = {"operator": [], "inserted": [], "state": []} + + @contextlib.asynccontextmanager + async def lease(*_a: Any, **_k: Any) -> AsyncIterator[None]: + yield + + async def source(*_a: Any) -> KnowledgeSource: + return _SOURCE + + async def operator(src: KnowledgeSource) -> None: + seen["operator"].append(src.name) + + async def nothing(*_a: Any, **_k: Any) -> None: + return None + + async def queued(_src: KnowledgeSource) -> bool: + return True + + async def state(_src: KnowledgeSource) -> dict[str, str]: + return {} + + async def update(_src: KnowledgeSource, _state: Any, change: dict[str, Any]) -> None: + seen["state"].append(change) + + async def insert(src: KnowledgeSource) -> None: + seen["inserted"].append(src) + + monkeypatch.setattr(sources, "sources_lease", lease) + monkeypatch.setattr(sources.store, "get_source", source) + monkeypatch.setattr(sources.store, "insert_source", insert) + monkeypatch.setattr(sources, "_queue_retirement", queued) + monkeypatch.setattr(sources, "_require_source_namespace", nothing) + monkeypatch.setattr(sources, "_read_state", state) + monkeypatch.setattr(sources, "_update_state", update) + monkeypatch.setattr(source_push, "retire", nothing) + monkeypatch.setattr(crawl_sources, "require_operator", operator) + return seen + + +@pytest.mark.asyncio +async def test_remove_checks_the_operator_and_clears_the_crawl_selection( + world: dict[str, list[Any]], +) -> None: + await sources.handle_knowledge_source_remove( + KnowledgeSourceRemoveInput( + org="org", namespace="team", name="workspace", confirm="workspace" + ) + ) + assert world["operator"] == ["workspace"] + (retired,) = world["inserted"] + assert not retired.active and retired.pending_delete + assert (retired.crawl_options, retired.approval_enc, retired.registrant_subject) == ({}, "", "") + assert (retired.credential_enc, retired.secret_enc) == ("", "") + + +@pytest.mark.asyncio +async def test_sync_now_checks_the_operator_before_and_under_the_lease( + world: dict[str, list[Any]], +) -> None: + await sources.handle_knowledge_source_sync_now( + KnowledgeSourceSyncNowInput(org="org", namespace="team", name="workspace") + ) + assert world["operator"] == ["workspace", "workspace"] + assert len(world["state"]) == 1 + + +@pytest.mark.asyncio +async def test_a_refused_operator_records_no_sync_request( + world: dict[str, list[Any]], monkeypatch: pytest.MonkeyPatch +) -> None: + async def refused(_src: KnowledgeSource) -> None: + raise crawl_sources.unavailable() + + monkeypatch.setattr(crawl_sources, "require_operator", refused) + with pytest.raises(ValidationError) as caught: + await sources.handle_knowledge_source_sync_now( + KnowledgeSourceSyncNowInput(org="org", namespace="team", name="workspace") + ) + assert caught.value.to_detail()["code"] == "CREDENTIAL_REFUSED" + assert not world["state"] + + +@pytest.mark.asyncio +async def test_namespace_retirement_clears_the_crawl_selection( + world: dict[str, list[Any]], monkeypatch: pytest.MonkeyPatch +) -> None: + async def listed(*_a: Any) -> list[KnowledgeSource]: + return [_SOURCE] + + monkeypatch.setattr(sources.store, "list_sources", listed) + assert await sources.deactivate_namespace_sources("org", "team") == ["workspace"] + (retired,) = world["inserted"] + assert not retired.active and retired.pending_delete + assert (retired.crawl_options, retired.approval_enc, retired.registrant_subject) == ({}, "", "") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operator", [True, False]) +async def test_a_listing_shows_crawl_options_only_to_an_operator_from_cached_grants( + world: dict[str, list[Any]], monkeypatch: pytest.MonkeyPatch, operator: bool +) -> None: + from server.core import request_work + from server.knowledge.api.models_sources import KnowledgeSourceListInput + + asked: list[bool] = [] + + async def checked(_src: KnowledgeSource, *, fresh: bool = True) -> None: + asked.append(fresh) + if not operator: + raise crawl_sources.unavailable() + + async def listed(*_a: Any) -> list[KnowledgeSource]: + return [_SOURCE] + + async def states(*_a: Any) -> dict[str, Any]: + return {} + + async def nothing_refused(*_a: Any) -> None: + return None + + monkeypatch.setattr(crawl_sources, "require_operator", checked) + monkeypatch.setattr(sources.store, "list_sources", listed) + monkeypatch.setattr(sources.store, "read_states", states) + monkeypatch.setattr(sources, "_source_refusal", nothing_refused) + marker = request_work._current.set(None) + request_work.begin() + try: + out = await sources.handle_knowledge_source_list( + KnowledgeSourceListInput(org="org", namespace="team") + ) + finally: + request_work._current.reset(marker) + (entry,) = out.sources + assert asked == [False] + assert entry.crawl_options == (_SOURCE.crawl_options if operator else {}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("raised", "retryable"), + [ + ("unreachable", True), + ("rate-limited", True), + ("server-error", True), + ("timeout", True), + ("refused", False), + ("invalid", False), + ], +) +async def test_a_provider_outage_answers_retryably_and_a_refusal_does_not( + raised: str, retryable: bool +) -> None: + from server.clients import _vendor + from server.core import request_work + from server.core.errors import BackendUnavailableError + + errors: dict[str, Exception] = { + "unreachable": _vendor.Unreachable("delegated read unavailable"), + "rate-limited": _vendor.RateLimited("delegated read", status=429), + "server-error": _vendor.VendorError("delegated read: http_503", status=503), + "timeout": TimeoutError(), + "refused": _vendor.CredentialRefused("delegated read refused", status=400), + "invalid": _vendor.VendorError("invalid directory response"), + } + marker = request_work._current.set(None) + request_work.begin() + try: + with pytest.raises(BackendUnavailableError if retryable else ValidationError) as caught: + async with crawl_sources.private(): + raise errors[raised] + finally: + request_work._current.reset(marker) + if not retryable: + assert caught.value.to_detail()["code"] == "CREDENTIAL_REFUSED" diff --git a/tests/unit/test_crawl_source_state.py b/tests/unit/test_crawl_source_state.py new file mode 100644 index 00000000000..8a7f37c5188 --- /dev/null +++ b/tests/unit/test_crawl_source_state.py @@ -0,0 +1,251 @@ +"""Real source row construction and complete multi-person union contracts.""" + +from __future__ import annotations + +import dataclasses +import json +from typing import Any + +import pytest + +from server.knowledge.domain.source_crawl import Expansion, Options, Person, Union +from server.knowledge.domain.sources import KnowledgeSource, mirror_synced +from server.knowledge.store import sources + + +def _options() -> dict[str, Any]: + return { + "directory_subject": "directory@example.com", + "subjects": [{"type": "group", "email": "team@example.com"}], + } + + +@pytest.mark.parametrize( + "change", + [ + {"directory_subject": "person@example.com\n"}, + {"subjects": []}, + {"subjects": [{"type": "customer", "email": "all@example.com"}]}, + {"subjects": [{"type": "person", "email": "person@example.com", "id": "guessed"}]}, + {"subjects": [{"type": "person", "email": "person@example.com"}] * 2}, + {"query": "all users"}, + ], +) +def test_crawl_options_refuse_untyped_or_ambiguous_admission(change: dict[str, Any]) -> None: + with pytest.raises(ValueError): + Options.parse(_options() | change) + + +@pytest.mark.asyncio +async def test_real_source_row_roundtrip_keeps_separate_crawl_authority_and_never_serves_it() -> ( + None +): + written: list[dict[str, Any]] = [] + + class Store: + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert table == sources.TABLE + written.extend(rows) + + source = KnowledgeSource( + org="org", + namespace="team", + name="meeting-notes", + kind="gdrive", + source_id="a8895a80-d41c-4515-8c89-57fc1f7b4994", + config={"include": ["docs"]}, + credential_mode="crawl", + access="mirrored", + items=[{"type": "file", "id": "file-identifier"}], + crawl_options=_options(), + registrant_subject="canonical-admin", + approval_enc="sealed-approval", + crawl_generation="registration-generation", + crawl_customer_id="verified-workspace", + crawl_credential_hash="a" * 64, + secret_enc="sealed-delegated-key", + created_by="audit-principal", + ) + await sources.insert_source(source, ch=Store()) + (row,) = written + assert ( + row["kind"] == row["credential_enc"] == row["owner_subject"] == row["connection_id"] == "" + ) + assert json.loads(row["options_json"]) == _options() + restored = sources._source(row) + assert dataclasses.replace(restored, created_at=None, updated_at=None) == source + assert mirror_synced(restored) # Crawl writes remain confined to the checked mirror. + assert restored.registrant_subject != restored.created_by + + +def _people() -> tuple[Person, Person]: + return Person("customer", "one", "one@example.com", ()), Person( + "customer", "two", "two@example.com", () + ) + + +def _file(**changes: Any) -> dict[str, Any]: + return {"id": "file", "version": "1", "mimeType": "text/plain", **changes} + + +def test_one_person_absence_cannot_retire_another_persons_file() -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 100) + union.add(one, [_file(owners=[{"me": True, "emailAddress": one.email}])], whole=True) + with pytest.raises(ValueError, match="incomplete"): + union.complete() + union.add(two, [], whole=True) + (file,) = union.complete() + assert (file.id, file.access.emails, file.presenters) == ("file", (one.email,), (one.id,)) + assert file.access.owner == "" + + +def test_complete_union_uses_explicit_permissions_not_link_only_listing_as_person() -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 100) + union.add( + one, + [ + _file( + permissions=[ + {"type": "user", "role": "reader", "emailAddress": one.email}, + {"type": "anyone", "role": "reader", "allowFileDiscovery": False}, + ] + ) + ], + whole=True, + ) + union.add(two, [_file(permissions=[])], whole=True) + (file,) = union.complete() + assert file.presenters == (one.id, two.id) + assert file.access.emails == (one.email,) + assert not file.access.anyone and not file.access.owner + + +def _shared(person: Person, **change: Any) -> dict[str, Any]: + return _file( + permissions=[{"type": "user", "role": "reader", "emailAddress": person.email}], **change + ) + + +@pytest.mark.parametrize("newer_first", [False, True]) +def test_an_edit_during_the_union_keeps_only_the_newest_revision_and_its_access( + newer_first: bool, +) -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 100) + older, newer = (one, _shared(one)), (two, _shared(two, version="2")) + for person, listed in (newer, older) if newer_first else (older, newer): + union.add(person, [listed], whole=True) + (file,) = union.complete() + # The older observation's ACL never rides with the newer revision's text. + assert (file.metadata["version"], file.presenters) == ("2", (two.id,)) + assert file.access.emails == (two.email,) + + +def test_union_refuses_two_differing_observations_of_one_revision() -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 100) + union.add(one, [_file(permissions=[])], whole=True) + with pytest.raises(ValueError, match="changed"): + union.add(two, [_file(permissions=[], name="renamed")], whole=True) + with pytest.raises(ValueError, match="incomplete"): + union.complete() + + +def test_truncated_listing_never_completes_or_publishes_a_partial_union() -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 100) + with pytest.raises(ValueError, match="incomplete"): + union.add(one, [_file()], whole=False) + union.add(two, [], whole=True) + with pytest.raises(ValueError, match="incomplete"): + union.complete() + + +def test_global_file_bound_applies_to_the_union_not_each_person_separately() -> None: + one, two = _people() + union = Union(Expansion("customer", (one, two), ()), 1) + union.add(one, [_file(id="first")], whole=True) + with pytest.raises(ValueError, match="file bound"): + union.add(two, [_file(id="second")], whole=True) + with pytest.raises(ValueError, match="incomplete"): + union.complete() + + +def test_a_crawl_row_an_older_build_wrote_maps_with_no_options() -> None: + # A build without crawl options writes the column's default, '{}', when it retires a + # crawl source; the row still maps, and crawl authority refuses it. + row = { + "org": "team", + "namespace": "shared-space", + "name": "workspace", + "credential_mode": "crawl", + "options_json": "{}", + "active": 0, + "pending_delete": 1, + } + assert sources._source(row).crawl_options == {} + + +@pytest.mark.parametrize("limit", [2, None]) +async def test_a_bounded_listing_left_with_pages_is_not_whole( + monkeypatch: Any, limit: int | None +) -> None: + from server.clients import gdrive + from server.knowledge.app import source_gdrive_items + + pages = [ + {"files": [{"id": "a"}, {"id": "a"}, {"id": "b"}], "nextPageToken": "next"}, + {"files": [{"id": "c"}]}, + ] + + async def get(*_args: Any, **_kwargs: Any) -> dict[str, Any]: + return pages.pop(0) + + monkeypatch.setattr(gdrive, "bearer_get", get) + folder = [{"type": "folder", "id": "1AbCdEfGhIjKlMnOp"}] + # Three raw rows pass a bound of two though only two files are unique; a page is + # left. Without a bound every page is read and the listing is whole. + listing = await source_gdrive_items.list_items("token", folder, ["docs"], pace_s=0, limit=limit) + assert listing.whole is (limit is None) + assert {f["id"] for f in listing.files} == ({"a", "b"} if limit else {"a", "b", "c"}) + + +async def test_a_retired_crawl_row_without_options_can_be_written_again() -> None: + written: list[dict[str, Any]] = [] + + class Store: + async def insert(self, _table: str, rows: list[dict[str, Any]]) -> None: + written.extend(rows) + + retired = KnowledgeSource( + "team", + "shared-space", + "workspace", + "gdrive", + "source", + credential_mode="crawl", + active=False, + ) + await sources.insert_source(retired, ch=Store()) + assert written[0]["options_json"] == "{}" + + +async def test_a_bounded_listing_left_with_folders_is_not_whole(monkeypatch: Any) -> None: + from server.clients import gdrive + from server.knowledge.app import source_gdrive_items + + queries: list[str] = [] + + async def get(*_args: Any, params: dict[str, Any], **_kwargs: Any) -> dict[str, Any]: + queries.append(params["q"]) + return {"files": [{"id": "a"}, {"id": "a"}, {"id": "b"}]} + + monkeypatch.setattr(gdrive, "bearer_get", get) + folders = [ + {"type": "folder", "id": f"1AbCdEfGhIjKlMn{n:03d}"} for n in range(gdrive.MAX_PARENTS + 1) + ] + # The first chunk's raw rows pass the bound: the next chunk of folders is never asked. + listing = await source_gdrive_items.list_items("token", folders, ["docs"], pace_s=0, limit=2) + assert len(queries) == 1 and listing.whole is False diff --git a/tests/unit/test_crawl_storage_contracts.py b/tests/unit/test_crawl_storage_contracts.py new file mode 100644 index 00000000000..bc8a07d1407 --- /dev/null +++ b/tests/unit/test_crawl_storage_contracts.py @@ -0,0 +1,74 @@ +"""Every crawl membership version carries its complete declared row.""" + +from __future__ import annotations + +import copy +from datetime import UTC, datetime +from typing import Any + +import pytest + +from server.knowledge.domain.source_crawl import Expansion +from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.store import crawl_publication as publication +from tests.unit.schema_ddl import columns + +pytestmark = pytest.mark.asyncio + + +class _Rows: + def __init__(self) -> None: + self.version = 100 + self.inserted: list[tuple[str, list[dict[str, Any]]]] = [] + + async def query_one(self, sql: str, *, params: dict[str, Any]) -> dict[str, int]: + assert sql.startswith("SELECT greatest(") and "max(version) + 1" in sql + assert params["k0"] == "org" + self.version += 1 + return {"v": self.version} + + async def query_all(self, sql: str, *, params: dict[str, Any]): + assert "FROM loom.knowledge_group_members FINAL" in sql + assert params == {"org": "org", "ns": "mirror", "id": "source", "limit": 5} + return [{"group": "old@example.com"}] + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert all(set(row) == set(columns(table.removeprefix("loom."))) for row in rows) + self.inserted.append((table, copy.deepcopy(rows))) + + +async def test_complete_group_replacement_clears_removed_members_without_losing_columns() -> None: + rows = _Rows() + source = KnowledgeSource("org", "namespace", "name", "gdrive", "source", mirror="mirror") + now = datetime.now(UTC) + expansion = Expansion("customer", (), (("new@example.com", ("person@example.com",)),)) + await publication.groups(source, expansion, now, maximum=4, ch=rows) + assert rows.inserted == [ + ( + publication.GROUPS, + [ + { + "org": "org", + "namespace": "mirror", + "source_id": "source", + "group": "new@example.com", + "name": "name", + "members": ["person@example.com"], + "read_at": now, + "deleted": False, + "version": 101, + }, + { + "org": "org", + "namespace": "mirror", + "source_id": "source", + "group": "old@example.com", + "name": "name", + "members": [], + "read_at": now, + "deleted": True, + "version": 101, + }, + ], + ) + ] diff --git a/tests/unit/test_crawl_update_audit.py b/tests/unit/test_crawl_update_audit.py new file mode 100644 index 00000000000..e451771c7f0 --- /dev/null +++ b/tests/unit/test_crawl_update_audit.py @@ -0,0 +1,22 @@ +"""A crawl update's audit row names its delegation proof and item changes, never an address.""" + +from __future__ import annotations + +from server.knowledge.api.models_sources import KnowledgeSourceUpdateInput +from server.knowledge.app import sources +from server.knowledge.app.crawl_sources import audit_hash + + +def test_a_crawl_update_audits_its_delegation_and_counts_items() -> None: + update = KnowledgeSourceUpdateInput(org="team", namespace="shared-space", name="workspace") + proof = { + "subject_hashes": [audit_hash("person", "person@example.com")], + "read_scopes": [], + "write_denials": [], + "members": 1, + } + response = {"name": "workspace", "crawl_proof": proof, "added": [{"id": "a"}], "removed": []} + row = sources.source_update_audit_subject(update, response) + assert row["delegation"] == proof + assert (row["items_added"], row["items_removed"]) == (1, 0) + assert "person@example.com" not in repr(row).lower() diff --git a/tests/unit/test_crawl_worker_observation.py b/tests/unit/test_crawl_worker_observation.py new file mode 100644 index 00000000000..8a6897aa0f3 --- /dev/null +++ b/tests/unit/test_crawl_worker_observation.py @@ -0,0 +1,137 @@ +"""Native item listings build one bounded observation before any publication.""" + +from __future__ import annotations + +import dataclasses +import time +from typing import Any + +import httpx +import pytest + +from server.clients._vendor import CredentialRefused, TooLarge +from server.code.app.index.pass_budget import PassBudget +from server.knowledge.app import crawl_authority, source_sync_crawl +from server.knowledge.app import source_sync as sync +from tests.unit.test_crawl_authority import _BOUNDS, _World +from tests.unit.test_crawl_authority import account as account +from tests.unit.test_crawl_authority import crawl_world as crawl_world +from tests.unit.test_crawl_authority import key_view as key_view + +pytestmark = [pytest.mark.asyncio, pytest.mark.claim_cap] + + +def _file(id: str = "file") -> dict[str, Any]: + return { + "id": id, + "version": "1", + "name": "Private meeting", + "mimeType": "application/vnd.google-apps.document", + "modifiedTime": "2026-01-01T00:00:00.000Z", + "webViewLink": "https://docs.google.com/document/d/" + id, + "permissions": [], + "owners": [{"me": True, "emailAddress": "one@example.com"}], + } + + +def _run() -> sync.Pass: + now = time.monotonic() + return sync.Pass(PassBudget(now, now + 10), 10) + + +async def _authority(world: _World) -> crawl_authority.Authority: + assert world.source is not None + return await crawl_authority.resolve( + world.source, deadline=time.monotonic() + 10, bounds=_BOUNDS + ) + + +async def test_actual_native_single_item_observation_keeps_ownership_without_owner_arm( + crawl_world: _World, +) -> None: + original = crawl_world.handle + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.path == "/drive/v3/files/file": + assert request.url.params["fields"].endswith("owners(me,emailAddress),trashed") + crawl_world.native_requests.append(request) + return httpx.Response(200, json=_file()) + return await original(request) + + crawl_world.handle = provider + authority = await _authority(crawl_world) + expansion, files = await source_sync_crawl.observe(authority, _run(), maximum_files=2) + (file,) = files + assert file.id == "file" and file.access.emails == ("one@example.com",) + assert not file.access.owner and expansion.people[0].id == "provider-one" + assert len(crawl_world.native_requests) == 1 + assert not crawl_world.writes # No memory, ACL, group, listing or retirement writes. + + +async def test_current_source_context_is_required_and_cleared_on_failed_work( + crawl_world: _World, +) -> None: + authority = await _authority(crawl_world) + expansion = await authority.prepare() + assert crawl_world.source is not None + with pytest.raises(CredentialRefused, match="checkout unavailable"): + await sync.require_current(crawl_world.source) + with pytest.raises(RuntimeError, match="extraction failed"): + async with authority.using(expansion.people): + await sync.require_current(crawl_world.source) + raise RuntimeError("extraction failed") + with pytest.raises(CredentialRefused, match="checkout unavailable"): + await sync.require_current(crawl_world.source) + + +@pytest.mark.parametrize("incomplete", [True, False]) +async def test_incomplete_search_or_global_file_cap_never_produces_union( + crawl_world: _World, + incomplete: bool, +) -> None: + assert crawl_world.source is not None + crawl_world.source = dataclasses.replace( + crawl_world.source, items=[{"type": "filter", "kinds": ["docs"]}] + ) + await crawl_world.setup() + original = crawl_world.handle + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.path == "/drive/v3/files": + crawl_world.native_requests.append(request) + second = "pageToken" in request.url.params + return httpx.Response( + 200, + json={ + "files": [_file("second" if second else "first")], + "incompleteSearch": incomplete, + **({} if incomplete or second else {"nextPageToken": "next"}), + }, + ) + return await original(request) + + crawl_world.handle = provider + with pytest.raises(ValueError if incomplete else TooLarge): + await source_sync_crawl.observe(await _authority(crawl_world), _run(), maximum_files=1) + assert len(crawl_world.native_requests) == (1 if incomplete else 2) + assert not crawl_world.writes + + +async def test_native_response_after_registrant_loss_is_not_a_complete_observation( + crawl_world: _World, +) -> None: + from server.operations.base import Role + + original = crawl_world.handle + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.path == "/drive/v3/files/file": + crawl_world.native_requests.append(request) + crawl_world.grant = Role.WRITER + return httpx.Response(200, json=_file()) + return await original(request) + + crawl_world.handle = provider + with pytest.raises(PermissionError): + await source_sync_crawl.observe(await _authority(crawl_world), _run(), maximum_files=2) + assert len(crawl_world.native_requests) == 1 and not crawl_world.writes diff --git a/tests/unit/test_crawl_worker_regressions.py b/tests/unit/test_crawl_worker_regressions.py new file mode 100644 index 00000000000..58bb2c61f9a --- /dev/null +++ b/tests/unit/test_crawl_worker_regressions.py @@ -0,0 +1,395 @@ +"""Native crawl turns retain absence proofs, pass bounds and mirror retry state.""" + +from __future__ import annotations + +import dataclasses +import json +import time +from datetime import UTC, datetime +from types import SimpleNamespace +from typing import Any +from urllib.parse import parse_qs + +import httpx +import jwt +import pytest + +from server.clients import gdrive +from server.knowledge.app import crawl_authority, private_sync, source_sync_crawl +from server.knowledge.app import source_sync as sync +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, mirror_uri +from server.knowledge.store import documents +from server.memory.domain.provenance import pipeline_actor +from server.settings import settings +from tests.unit.principals import acting_as +from tests.unit.test_connected_source_publication import _MIRROR +from tests.unit.test_crawl_authority import _BOUNDS +from tests.unit.test_crawl_composed_flow import _register, _World +from tests.unit.test_crawl_composed_flow import account as account +from tests.unit.test_crawl_composed_flow import key_view as key_view +from tests.unit.test_crawl_composed_flow import world as world +from tests.unit.test_crawl_worker_observation import _file + +pytestmark = pytest.mark.asyncio + + +async def _work( + world: _World, *, left: int = 10, asked: dict[str, Any] | None = None +) -> tuple[sync.TurnResult, sync.Pass]: + assert world.source is not None + now = time.monotonic() + run = sync.Pass(sync.PassBudget(now, now + 20), left) + with acting_as(None), pipeline_actor(SYNC_WORKER_ACTOR), private_sync.scope(): + result = await source_sync_crawl.turn( + world.source, {"detail": json.dumps(asked or {})}, run, bounds=_BOUNDS + ) + return result, run + + +async def _persist(world: _World, result: sync.TurnResult) -> dict[str, str]: + assert world.source is not None and result.mirror == _MIRROR + source = dataclasses.replace(world.source, mirror=_MIRROR) + authority = await crawl_authority.resolve( + source, deadline=time.monotonic() + 20, bounds=_BOUNDS + ) + expansion = await authority.prepare() + old = await sync.mirror_state(source, _MIRROR) + with acting_as(None), pipeline_actor(SYNC_WORKER_ACTOR), private_sync.scope(): + async with authority.using(expansion.people), sync.publication_guard(source): + await sync._write_mirrored_state(source, {}, result, {}, old) + return await sync.mirror_state(source, _MIRROR) + + +def _copies(world: _World, monkeypatch: pytest.MonkeyPatch, count: int) -> list[str]: + assert world.source is not None + rows = [ + { + "file_id": "missing-" + str(i), + "source_uri": mirror_uri( + "https://docs.google.com/document/d/missing-" + str(i), world.source.source_id + ), + "searchable": True, + "source_revision": "old", + "access_json": "{}", + } + for i in range(count) + ] + + async def every_copy(org: str, mirror: str, tag: str): + assert world.source is not None + assert (org, mirror, tag) == ("team", _MIRROR, "source-id:" + world.source.source_id) + return rows + + checked: list[str] = [] + + async def foreign_document(org: str, namespace: str, uri: str, *, include_superseded: bool): + assert (org, namespace, include_superseded) == ("team", _MIRROR, False) + checked.append(uri) + # Retirement still runs its real ownership validator and preserves a foreign latest row. + return SimpleNamespace(actor="another-writer", tags=[]) + + monkeypatch.setattr(sync.store, "every_copy", every_copy) + monkeypatch.setattr(documents, "get_one", foreign_document) + return checked + + +async def test_missing_page_file_requires_native_positive_absence( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + await _register(world) + checked = _copies(world, monkeypatch, 1) + original = world.handle + lookups: list[str] = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.host == "www.googleapis.com": + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": [], "incompleteSearch": False}) + if request.url.path == "/drive/v3/files/missing-0": + lookups.append(request.url.path) + return httpx.Response(200, json=_file("missing-0")) + return await original(request) + + world.handle = provider + result, _ = await _work(world) + assert lookups == ["/drive/v3/files/missing-0"] + assert result.complete and not result.removed + assert ( + not checked + ) # Still reached by the configured docs filter; never considered for deletion. + + +@pytest.mark.parametrize("left", [0, 1]) +async def test_absence_checks_and_retire_attempts_share_the_document_budget( + world: _World, monkeypatch: pytest.MonkeyPatch, left: int +) -> None: + await _register(world) + checked = _copies(world, monkeypatch, 3) + original = world.handle + lookups: list[str] = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.host == "www.googleapis.com": + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": []}) + if request.url.path.startswith("/drive/v3/files/missing-"): + lookups.append(request.url.path) + return httpx.Response(404, json={"error": "notFound"}) + return await original(request) + + world.handle = provider + result, run = await _work(world, left=left) + assert run.left == 0 and result.cut and not result.complete + assert len(lookups) == len(checked) == left + assert not result.removed and not world.listings + + +async def test_empty_folder_query_needs_current_selected_folder_visibility(world: _World) -> None: + await _register(world) + assert world.source is not None + world.source = dataclasses.replace( + world.source, items=[{"type": "filter", "kinds": ["docs"], "in": "selected-folder"}] + ) + await world.setup() # Seal approval for the actual changed selection. + original = world.handle + checked: list[str] = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.host == "www.googleapis.com": + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": []}) + if request.url.path == "/drive/v3/files/selected-folder": + checked.append(request.url.path) + return httpx.Response(404, json={"error": "notFound"}) + return await original(request) + + world.handle = provider + result, _ = await _work(world) + assert checked == ["/drive/v3/files/selected-folder"] + assert not result.complete and not world.listings and not world.document_writes + + +async def test_consecutive_failed_exports_resume_the_mirror_wait_counter(world: _World) -> None: + await _register(world) + original = world.handle + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.path == "/drive/v3/files/file/export": + return httpx.Response(500, json={"error": "temporary"}) + return await original(request) + + world.handle = provider + first, _ = await _work(world) + assert first.waits["file"][1] == 1 and not first.complete + saved = await _persist(world, first) + assert json.loads(saved["detail"])["file_waits"]["file"][1] == 1 + second, _ = await _work(world) + assert second.waits["file"][1] == 2 and not second.complete + assert not world.document_writes + + +@pytest.mark.parametrize("explicit_full", [False, True]) +async def test_whole_enumeration_does_not_regrant_a_settled_revision_before_full_due( + world: _World, explicit_full: bool +) -> None: + await _register(world) + assert world.source is not None + now = datetime.now(UTC).replace(microsecond=0).isoformat() + detail = { + "full_listed_at": now, + "file_waits": {"file": [_file()["modifiedTime"], 3, "too_large"]}, + } + world.states.append( + { + "org": "team", + "namespace": _MIRROR, + "state_key": sync.store.state_key(world.source.source_id), + "state_value": "", + "detail": json.dumps(detail), + } + ) + original = world.handle + exports: list[str] = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.path == "/drive/v3/files/file/export": + exports.append(request.url.path) + return await original(request) + + world.handle = provider + asked = ( + {"requested_at": "explicit-request", "full": True} + if explicit_full + else {"file_waits": {}, "full_listed_at": "forged-namespace-state"} + ) + result, _ = await _work(world, asked=asked) + assert result.documents_seen == 1 # Both paths still enumerate the whole union. + assert result.full is explicit_full + assert len(exports) == int(explicit_full) + if explicit_full: + assert result.waits_reset_for == "explicit-request" and result.changed == 1 + else: + assert result.waits == detail["file_waits"] and result.changed == 0 + + +async def test_one_presenters_absence_cannot_retire_another_presenters_reached_file( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + await _register(world) + assert world.source is not None + world.source = dataclasses.replace( + world.source, + crawl_options={ + **world.source.crawl_options, + "subjects": [ + {"type": "person", "email": "one@example.com"}, + {"type": "person", "email": "two@example.com"}, + ], + }, + ) + await world.setup() + checked = _copies(world, monkeypatch, 1) + original = world.handle + lookups: list[str] = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.host == "admin.googleapis.com" and request.url.path.rsplit("/", 1)[1] in { + "two@example.com", + "provider-two", + }: + return httpx.Response( + 200, + json={ + "id": "provider-two", + "primaryEmail": "two@example.com", + "aliases": [], + "customerId": "workspace", + "suspended": False, + "archived": False, + }, + ) + if request.url.host == "oauth2.googleapis.com": + form = parse_qs(request.content.decode()) + claims = jwt.decode( + form["assertion"][0], + world.account[1], + algorithms=["RS256"], + audience="https://oauth2.googleapis.com/token", + ) + if claims["sub"] == "two@example.com": + assert claims["scope"] == gdrive.ReadScope.DRIVE.value + return httpx.Response( + 200, + json={ + "access_token": "second-person-access", + "token_type": "Bearer", + "expires_in": 60, + }, + ) + if request.url.host == "www.googleapis.com": + if request.url.path == "/drive/v3/files": + return httpx.Response(200, json={"files": []}) + if request.url.path == "/drive/v3/files/missing-0": + bearer = request.headers["authorization"] + lookups.append(bearer) + if bearer == "Bearer private-person-access": + return httpx.Response(404, json={"error": "notFound"}) + assert bearer == "Bearer second-person-access" + return httpx.Response(200, json=_file("missing-0")) + return await original(request) + + world.handle = provider + result, _ = await _work(world) + assert lookups == ["Bearer private-person-access", "Bearer second-person-access"] + assert result.complete and not result.removed and not checked + + +async def test_configured_file_bound_refuses_the_whole_native_turn_before_publication( + world: _World, + monkeypatch: pytest.MonkeyPatch, +) -> None: + await _register(world) + monkeypatch.setattr(settings, "knowledge_crawl_max_files", 1) + original = world.handle + listed = [] + + async def provider(request: httpx.Request) -> httpx.Response: + if request.url.host == "www.googleapis.com" and request.url.path == "/drive/v3/files": + listed.append(request) + return httpx.Response( + 200, + json={ + "files": [_file("first"), _file("second")], + "incompleteSearch": False, + }, + ) + return await original(request) + + world.handle = provider + result, _ = await _work(world) + assert listed and result.status != "ok" and not result.complete + assert not world.document_writes and not world.chunk_writes and not world.listings + assert not world.embedded + + +async def test_only_the_completed_listing_guard_re_reads_grants_in_a_turn( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from contextlib import asynccontextmanager + + await _register(world) + guards: list[bool] = [] + real = crawl_authority.Authority.publication_guard + + @asynccontextmanager + async def recorded(self: crawl_authority.Authority, *, fresh: bool = False) -> Any: + guards.append(fresh) + async with real(self, fresh=fresh): + yield + + monkeypatch.setattr(crawl_authority.Authority, "publication_guard", recorded) + result, _ = await _work(world, asked={"requested_at": "explicit-request", "full": True}) + assert result.changed == 1 + # The document's write keeps the cached grants; the completed listing comes last. + assert guards[-1] is True and guards.count(True) == 1 and len(guards) > 1 + + +async def test_an_absence_ask_spends_one_unit_per_presenter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.knowledge.domain.source_crawl import Expansion, Person + + people = tuple(Person("workspace", f"id-{n}", f"p{n}@example.com", ()) for n in range(3)) + asked: list[str] = [] + + class _Authority: + async def drive(self, person: Person) -> Any: + asked.append(person.id) + return SimpleNamespace(check=lambda: _done()) + + async def _done() -> None: + return None + + async def gone(*_a: Any) -> bool: + return True + + monkeypatch.setattr(sync, "file_gone", gone) + now = time.monotonic() + run = sync.Pass(sync.PassBudget(now, now + 20), 2) + result = sync.TurnResult() + observations = {p.id: SimpleNamespace() for p in people} + expansion = Expansion("workspace", people, ()) + got = await source_sync_crawl._gone(_Authority(), expansion, observations, "f", result, run) + # Two units ask two presenters; the third is never asked and the copy stays. + assert got is None and asked == ["id-0", "id-1"] and run.left == 0 + + +async def test_with_no_eligible_presenter_an_unreached_copy_retires() -> None: + from server.knowledge.domain.source_crawl import Expansion + + now = time.monotonic() + run = sync.Pass(sync.PassBudget(now, now + 20), 5) + got = await source_sync_crawl._gone( + SimpleNamespace(), Expansion("workspace", (), ()), {}, "f", sync.TurnResult(), run + ) + assert got is True and run.left == 4 diff --git a/tests/unit/test_google_workspace.py b/tests/unit/test_google_workspace.py new file mode 100644 index 00000000000..8891ea3eaf0 --- /dev/null +++ b/tests/unit/test_google_workspace.py @@ -0,0 +1,692 @@ +"""Delegated JWTs and bounded Directory HTTP; no registration or provider is needed.""" + +from __future__ import annotations + +import asyncio +import copy +import json +import time +from contextlib import asynccontextmanager +from typing import Any +from urllib.parse import parse_qs + +import httpx +import jwt +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from server.clients import gdrive +from server.clients import google_workspace as google +from server.clients._vendor import CredentialRefused, RateLimited, TooLarge, VendorError +from server.knowledge.app import crawl_authority +from server.settings import settings + +pytestmark = pytest.mark.asyncio + +_SUBJECT = "directory-admin@example.com" +_ACCESS = "private-delegated-access" + + +@pytest.fixture(scope="module") +def account() -> tuple[gdrive.ServiceAccount, Any]: + private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = private.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ).decode() + credential = json.dumps( + { + "type": "service_account", + "client_email": "service@example.com", + "private_key": pem, + "token_uri": "https://untrusted.example/token", + } + ) + return gdrive.parse_service_account(credential), private.public_key() + + +@asynccontextmanager +async def _http(monkeypatch: pytest.MonkeyPatch, handler: Any): + calls: list[httpx.Request] = [] + + async def record(request: httpx.Request) -> httpx.Response: + calls.append(request) + return handler(request) + + async def pace(delay: float) -> None: + assert delay == gdrive.PAGE_PACE_S + + async with httpx.AsyncClient( + transport=httpx.MockTransport(record), follow_redirects=True + ) as client: + monkeypatch.setattr(google, "get_client", lambda: client) + monkeypatch.setattr(google, "_pace", pace) + monkeypatch.setattr(gdrive, "get_client", lambda: client) + yield calls + + +def _token(scope: gdrive.ReadScope, *, deadline: float | None = None) -> google.DelegatedToken: + return google.DelegatedToken(_ACCESS, _SUBJECT, scope, deadline or time.monotonic() + 30) + + +def _person(**changes: Any) -> dict[str, Any]: + return { + "id": "123456", + "primaryEmail": "person@example.com", + "aliases": ["alias@example.com"], + "customerId": "customer-one", + "suspended": False, + "archived": False, + **changes, + } + + +class _Body(httpx.AsyncByteStream): + def __init__(self, *chunks: bytes) -> None: + self.chunks = chunks + self.reads = 0 + self.closed = False + + async def __aiter__(self): + for chunk in self.chunks: + self.reads += 1 + yield chunk + + async def aclose(self) -> None: + self.closed = True + + +class _WaitingBody(_Body): + def __init__(self) -> None: + super().__init__() + self.entered = asyncio.Event() + + async def __aiter__(self): + self.entered.set() + await asyncio.Event().wait() + yield b"" + + +@pytest.mark.parametrize("scope", list(gdrive.ReadScope)) +async def test_grant_signs_exact_delegated_subject_scope_and_fixed_endpoint( + monkeypatch: pytest.MonkeyPatch, account: Any, scope: gdrive.ReadScope +) -> None: + service, public = account + + def answer(request: httpx.Request) -> httpx.Response: + assert str(request.url) == "https://oauth2.googleapis.com/token" + form = parse_qs(request.content.decode()) + assert set(form) == {"grant_type", "assertion"} + assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] + claims = jwt.decode( + form["assertion"][0], public, algorithms=["RS256"], audience=str(request.url) + ) + assert set(claims) == {"iss", "sub", "scope", "aud", "iat", "exp"} + assert (claims["iss"], claims["sub"], claims["scope"]) == ( + service.client_email, + _SUBJECT, + scope.value, + ) + assert claims["exp"] - claims["iat"] == 600 + return httpx.Response( + 200, + json={ + "access_token": _ACCESS, + "token_type": "Bearer", + "expires_in": 3600, + "scope": scope.value, + }, + ) + + clock = time.monotonic() + + def advancing() -> float: + nonlocal clock + clock += 0.001 + return clock + + monkeypatch.setattr(google, "_now", advancing) + deadline = clock + 30 + async with _http(monkeypatch, answer) as calls: + token = await google.delegated_token( + service, subject=_SUBJECT, scope=scope, deadline=deadline, max_bytes=4096 + ) + assert len(calls) == 1 and token.deadline == deadline + assert (token.subject, token.scope) == (_SUBJECT, scope) + assert _ACCESS not in repr(token) and _SUBJECT not in repr(token) + with pytest.raises(TypeError): + str(token) + with pytest.raises(TypeError): + copy.copy(token) + + +async def test_shared_grant_keeps_its_original_payload_and_response_contract( + monkeypatch: pytest.MonkeyPatch, account: Any +) -> None: + service, public = account + + def answer(request: httpx.Request) -> httpx.Response: + form = parse_qs(request.content.decode()) + claims = jwt.decode( + form["assertion"][0], + public, + algorithms=["RS256"], + audience="https://oauth2.googleapis.com/token", + ) + assert "sub" not in claims and claims["scope"] == gdrive.ReadScope.DRIVE.value + return httpx.Response(200, json={"access_token": "ordinary-token"}) + + async with _http(monkeypatch, answer) as calls: + assert await gdrive.access_token(service) == "ordinary-token" + assert len(calls) == 1 and calls[0].url.host == "oauth2.googleapis.com" + + +@pytest.mark.parametrize( + ("subject", "scope"), + [ + (None, gdrive.ReadScope.DRIVE), + ("not-an-email", gdrive.ReadScope.DRIVE), + ("person@example.com\n", gdrive.ReadScope.DIRECTORY_USERS), + (_SUBJECT, "https://www.googleapis.com/auth/drive"), + (_SUBJECT, "https://www.googleapis.com/auth/admin.directory.group.member"), + ], +) +async def test_subject_and_scope_refusals_make_no_http_request( + monkeypatch: pytest.MonkeyPatch, account: Any, subject: Any, scope: Any +) -> None: + async with _http(monkeypatch, lambda request: pytest.fail("no request permitted")) as calls: + with pytest.raises(CredentialRefused): + await google.delegated_token( + account[0], + subject=subject, + scope=scope, + deadline=time.monotonic() + 30, + max_bytes=4096, + ) + assert calls == [] + + +@pytest.mark.parametrize("status", [302, 400, 403, 429]) +async def test_grant_refusals_do_not_read_echoed_secrets_follow_or_retry( + monkeypatch: pytest.MonkeyPatch, account: Any, status: int +) -> None: + body = _Body(b"private-provider-body") + async with _http( + monkeypatch, + lambda request: httpx.Response( + status, headers={"Location": "https://untrusted.example/private"}, stream=body + ), + ) as calls: + with pytest.raises(VendorError) as caught: + await google.delegated_token( + account[0], + subject=_SUBJECT, + scope=gdrive.ReadScope.DRIVE, + deadline=time.monotonic() + 30, + max_bytes=4096, + ) + assert caught.value.status == status and body.closed and body.reads == 0 + assert len(calls) == 1 + assert all(secret not in str(caught.value) for secret in ("private", _SUBJECT, "untrusted")) + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + ({"errors": [{"reason": "userRateLimitExceeded"}]}, RateLimited), + ({"errors": [{"reason": "quotaExceeded"}]}, RateLimited), + ({"status": "RESOURCE_EXHAUSTED"}, RateLimited), + ({"errors": [{"reason": "forbidden"}]}, CredentialRefused), + ], +) +async def test_directory_forbidden_distinguishes_quota_from_credentials_without_error_echo( + monkeypatch: pytest.MonkeyPatch, error: dict[str, Any], expected: type[VendorError] +) -> None: + body = _Body(json.dumps({"error": {**error, "message": "private-provider-body"}}).encode()) + async with _http(monkeypatch, lambda request: httpx.Response(403, stream=body)) as calls: + with pytest.raises(expected) as caught: + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + assert type(caught.value) is expected and caught.value.status == 403 + assert len(calls) == 1 and body.reads == 1 and body.closed + assert all(value not in str(caught.value) for value in ("private", _ACCESS, _SUBJECT)) + + +@pytest.mark.parametrize("raw", [b"not-json", b'{"error":{"errors":12}}', b'{"error":{}}']) +async def test_ambiguous_directory_forbidden_does_not_claim_credential_revocation( + monkeypatch: pytest.MonkeyPatch, raw: bytes +) -> None: + body = _Body(raw) + async with _http(monkeypatch, lambda request: httpx.Response(403, stream=body)) as calls: + with pytest.raises(VendorError) as caught: + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + assert type(caught.value) is VendorError and caught.value.status == 403 + assert len(calls) == 1 and body.reads == 1 and body.closed + assert raw.decode() not in str(caught.value) + + +async def test_directory_error_body_bound_stops_reading_and_closes_stream( + monkeypatch: pytest.MonkeyPatch, +) -> None: + body = _Body(b"x" * 8, b"x" * 9, b"private-must-not-be-read") + async with _http(monkeypatch, lambda request: httpx.Response(403, stream=body)) as calls: + with pytest.raises(TooLarge) as caught: + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=16, + ) + assert caught.value.status == 403 and "private" not in str(caught.value) + assert len(calls) == 1 and body.reads == 2 and body.closed + + +@pytest.mark.parametrize( + "change", + [ + {"token_type": None}, + {"expires_in": True}, + {"access_token": "private\naccess"}, + {"scope": "https://www.googleapis.com/auth/drive"}, + ], +) +async def test_bad_token_metadata_never_returns_a_checkout( + monkeypatch: pytest.MonkeyPatch, account: Any, change: dict[str, Any] +) -> None: + answer = {"access_token": _ACCESS, "token_type": "Bearer", "expires_in": 3600, **change} + async with _http(monkeypatch, lambda request: httpx.Response(200, json=answer)) as calls: + with pytest.raises(VendorError): + await google.delegated_token( + account[0], + subject=_SUBJECT, + scope=gdrive.ReadScope.DRIVE, + deadline=time.monotonic() + 30, + max_bytes=4096, + ) + assert len(calls) == 1 + + +async def test_user_and_directory_identity_require_explicit_active_customer_evidence( + monkeypatch: pytest.MonkeyPatch, +) -> None: + token = _token(gdrive.ReadScope.DIRECTORY_USERS) + + def answer(request: httpx.Request) -> httpx.Response: + person = ( + _person() + if request.url.path.endswith("/123456") + else _person(id="directory-admin-id", primaryEmail=_SUBJECT, aliases=[]) + ) + return httpx.Response(200, json=person) + + async with _http(monkeypatch, answer) as calls: + principal = await google.directory_identity(token, max_bytes=4096) + person = await google.user( + token, "123456", customer_id=principal.customer_id, max_bytes=4096 + ) + assert person.id == "123456" and person.email == "person@example.com" + assert person.aliases == ("alias@example.com",) + assert len(calls) == 2 + assert [r.url.path for r in calls] == [ + "/admin/directory/v1/users/" + _SUBJECT, + "/admin/directory/v1/users/123456", + ] + assert all(r.url.host == "admin.googleapis.com" for r in calls) + assert all(r.headers["Authorization"] == "Bearer " + _ACCESS for r in calls) + assert all("deletionTime" in r.url.params["fields"] for r in calls) + + +@pytest.mark.parametrize( + "change", + [{"suspended": True}, {"archived": True}, {"deletionTime": "deleted"}, {"suspended": None}], +) +async def test_user_refuses_inactive_or_unproven_state( + monkeypatch: pytest.MonkeyPatch, change: dict[str, Any] +) -> None: + async with _http(monkeypatch, lambda request: httpx.Response(200, json=_person(**change))): + with pytest.raises(CredentialRefused): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + + +async def test_external_customer_is_not_an_admitted_employee( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with _http( + monkeypatch, + lambda request: httpx.Response(200, json=_person(customerId="external-customer")), + ) as calls: + with pytest.raises(CredentialRefused): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + assert len(calls) == 1 + + +async def test_user_response_must_match_the_requested_id_or_verified_address( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with _http(monkeypatch, lambda request: httpx.Response(200, json=_person())) as calls: + with pytest.raises(VendorError, match="identity mismatch"): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "different-id", + customer_id="customer-one", + max_bytes=4096, + ) + assert len(calls) == 1 + + +async def test_members_pages_preserve_types_without_inferring_employee_status_or_expanding_customer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def page(request: httpx.Request) -> httpx.Response: + assert request.url.host == "admin.googleapis.com" + assert request.url.path == "/admin/directory/v1/groups/group@example.com/members" + assert request.url.params["maxResults"] == "200" + assert request.url.params["includeDerivedMembership"] == "false" + if "pageToken" not in request.url.params: + return httpx.Response( + 200, + json={ + "members": [{"id": "external", "type": "USER", "email": "other@external.com"}], + "nextPageToken": "next-page", + }, + ) + assert request.url.params["pageToken"] == "next-page" + return httpx.Response( + 200, + json={ + "members": [ + {"id": "nested", "type": "GROUP", "email": "nested@example.com"}, + {"id": "customer-one", "type": "CUSTOMER", "status": "UNDOCUMENTED"}, + ] + }, + ) + + async with _http(monkeypatch, page) as calls: + members = await google.group_members( + _token(gdrive.ReadScope.DIRECTORY_MEMBERS), + "group@example.com", + max_bytes=4096, + max_pages=2, + ) + assert [(m.kind, m.id, m.email) for m in members] == [ + ("USER", "external", "other@external.com"), + ("GROUP", "nested", "nested@example.com"), + ("CUSTOMER", "customer-one", None), + ] + assert len(calls) == 2 and all("/groups/" in r.url.path for r in calls) + + +@pytest.mark.parametrize("failure", ["repeated-token", "repeated-member", "page-bound", "bad-type"]) +async def test_incomplete_membership_never_returns_a_partial_list( + monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + pages = 0 + + def answer(request: httpx.Request) -> httpx.Response: + nonlocal pages + pages += 1 + kind = "UNKNOWN" if failure == "bad-type" else "USER" + identifier = str(pages) if failure != "repeated-member" else "same" + return httpx.Response( + 200, json={"members": [{"type": kind, "id": identifier}], "nextPageToken": "same-page"} + ) + + async with _http(monkeypatch, answer) as calls: + with pytest.raises(VendorError): + await google.group_members( + _token(gdrive.ReadScope.DIRECTORY_MEMBERS), + "group@example.com", + max_bytes=4096, + max_pages=1 if failure == "page-bound" else 3, + ) + assert len(calls) == (1 if failure in {"page-bound", "bad-type"} else 2) + + +async def test_membership_over_the_crawl_bound_is_not_truncated( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pages = 0 + + def answer(request: httpx.Request) -> httpx.Response: + nonlocal pages + pages += 1 + return httpx.Response( + 200, + json={ + "members": [{"type": "USER", "id": f"{pages}-{n}"} for n in range(200)], + "nextPageToken": str(pages), + }, + ) + + async with _http(monkeypatch, answer) as calls: + with pytest.raises(TooLarge, match="crawl bound"): + await google.group_members( + _token(gdrive.ReadScope.DIRECTORY_MEMBERS), + "group@example.com", + max_bytes=32768, + max_pages=11, + ) + assert len(calls) == 11 + + +@pytest.mark.parametrize("configured", [False, True]) +async def test_response_cap_stops_reading_and_closes_stream( + monkeypatch: pytest.MonkeyPatch, + configured: bool, +) -> None: + cap = 16 + if configured: + monkeypatch.setattr(settings, "knowledge_crawl_directory_max_response_bytes", 1024) + cap = crawl_authority.configured_bounds().directory.body_bytes + body = _Body(b"x" * (cap // 2), b"x" * (cap // 2 + 1), b"must-not-be-read") + async with _http(monkeypatch, lambda request: httpx.Response(200, stream=body)) as calls: + with pytest.raises(TooLarge): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=cap, + ) + assert len(calls) == 1 and body.reads == 2 and body.closed + + +async def test_elapsed_pacing_refuses_the_next_page_before_http( + monkeypatch: pytest.MonkeyPatch, +) -> None: + deadline = time.monotonic() + 30 + waits = [] + + async def spent(delay: float) -> None: + waits.append(delay) + monkeypatch.setattr(google, "_now", lambda: deadline + 1) + + async with _http( + monkeypatch, lambda request: httpx.Response(200, json={"nextPageToken": "next"}) + ) as calls: + monkeypatch.setattr(google, "_pace", spent) + with pytest.raises(TimeoutError): + await google.group_members( + _token(gdrive.ReadScope.DIRECTORY_MEMBERS, deadline=deadline), + "group@example.com", + max_bytes=4096, + max_pages=2, + ) + assert len(calls) == 1 and waits == [gdrive.PAGE_PACE_S] + + +async def test_invalid_bounds_scope_and_path_make_no_http_call( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with _http(monkeypatch, lambda request: pytest.fail("no request permitted")) as calls: + with pytest.raises(ValueError): + await google.group_members( + _token(gdrive.ReadScope.DIRECTORY_MEMBERS), "group", max_bytes=4096, max_pages=0 + ) + with pytest.raises(ValueError): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=True, + ) + with pytest.raises(ValueError): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "../users/other", + customer_id="customer-one", + max_bytes=4096, + ) + with pytest.raises(CredentialRefused): + await google.user( + _token(gdrive.ReadScope.DRIVE), "123456", customer_id="customer-one", max_bytes=4096 + ) + with pytest.raises(TimeoutError): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS, deadline=float("nan")), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + assert calls == [] + + +@pytest.mark.parametrize("status", [200, 403]) +async def test_cancellation_closes_the_owned_stream_and_propagates( + monkeypatch: pytest.MonkeyPatch, + status: int, +) -> None: + body = _WaitingBody() + async with _http(monkeypatch, lambda request: httpx.Response(status, stream=body)) as calls: + task = asyncio.create_task( + google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + ) + await body.entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert len(calls) == 1 and body.closed + + +@pytest.mark.parametrize("status", [200, 403]) +async def test_absolute_deadline_covers_stream_body_and_closes_it( + monkeypatch: pytest.MonkeyPatch, + status: int, +) -> None: + body = _WaitingBody() + async with _http(monkeypatch, lambda request: httpx.Response(status, stream=body)) as calls: + with pytest.raises(TimeoutError): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS, deadline=time.monotonic() + 0.1), + "123456", + customer_id="customer-one", + max_bytes=4096, + ) + assert len(calls) == 1 and body.closed + + +def test_a_directory_person_holds_their_domain_alias_addresses() -> None: + found = google._user( + { + "id": "person-id", + "primaryEmail": "person@example.com", + "aliases": ["alias@example.com"], + "nonEditableAliases": ["person@example.net"], + "customerId": "workspace", + "suspended": False, + "archived": False, + } + ) + assert set(found.aliases) == {"alias@example.com", "person@example.net"} + + +def test_a_directory_person_answered_in_mixed_case_reads_lower_case() -> None: + found = google._user( + { + "id": "person-id", + "primaryEmail": "Person@Example.com", + "aliases": ["Alias@example.com"], + "nonEditableAliases": [], + "customerId": "workspace", + "suspended": False, + "archived": False, + } + ) + assert (found.email, found.aliases) == ("person@example.com", ("alias@example.com",)) + + +async def test_a_write_scope_proof_with_no_answer_is_unreachable( + monkeypatch: pytest.MonkeyPatch, account: tuple[gdrive.ServiceAccount, Any] +) -> None: + from server.clients._vendor import Unreachable + + def refuse(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("connection reset", request=request) + + async with _http(monkeypatch, refuse): + with pytest.raises(Unreachable): + await google.require_write_denied( + account[0], + subject=_SUBJECT, + scope=next(iter(gdrive.WriteScope)), + deadline=time.monotonic() + 30, + max_bytes=4096, + ) + + +async def test_a_directory_read_with_no_answer_is_unreachable( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.clients._vendor import Unreachable + + def refuse(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("connection reset", request=request) + + async with _http(monkeypatch, refuse): + with pytest.raises(Unreachable): + await google.user( + _token(gdrive.ReadScope.DIRECTORY_USERS), + "person-id", + customer_id="workspace", + max_bytes=4096, + ) + + +async def test_an_unreadable_write_scope_proof_is_a_refusal( + monkeypatch: pytest.MonkeyPatch, account: tuple[gdrive.ServiceAccount, Any] +) -> None: + async with _http(monkeypatch, lambda request: httpx.Response(400, content=b"not-json")): + with pytest.raises(VendorError) as caught: + await google.require_write_denied( + account[0], + subject=_SUBJECT, + scope=next(iter(gdrive.WriteScope)), + deadline=time.monotonic() + 30, + max_bytes=4096, + ) + assert type(caught.value) is VendorError and caught.value.status == 0 diff --git a/tests/unit/test_restore_reconcile.py b/tests/unit/test_restore_reconcile.py index b5a3f1acc60..e0053ffe702 100644 --- a/tests/unit/test_restore_reconcile.py +++ b/tests/unit/test_restore_reconcile.py @@ -51,14 +51,15 @@ async def no_lost(after: datetime) -> list[Any]: monkeypatch.setattr(knowledge_reconcile, "held_sources", no_sources) monkeypatch.setattr(knowledge_reconcile, "dataset_sources_lost", no_lost) - # These cases isolate memory and erasure replay participants. Real connection - # cleanup and its publication ordering are covered in test_connected_account_restore. - from server.knowledge.app import connected_restore + # These cases isolate memory and erasure replay participants; their restored + # store contains no connected accounts or crawl sources. + from server.knowledge.app import connected_restore, crawl_restore - async def no_connections(*a: Any, **k: Any) -> None: + async def no_private_sources(*a: Any, **k: Any) -> None: pass - monkeypatch.setattr(connected_restore, "restore_all", no_connections) + monkeypatch.setattr(connected_restore, "restore_all", no_private_sources) + monkeypatch.setattr(crawl_restore, "restore_all", no_private_sources) @pytest.fixture(autouse=True) diff --git a/tests/unit/test_rmt_write_paths.py b/tests/unit/test_rmt_write_paths.py index f31f032b418..b902df8309a 100644 --- a/tests/unit/test_rmt_write_paths.py +++ b/tests/unit/test_rmt_write_paths.py @@ -43,10 +43,7 @@ "query_history_sources": ("builder", "test_repository_column_sets_match_schema.py"), "knowledge_mirrors": ("builder", "test_knowledge_mirrors.py"), "knowledge_source_listings": ("builder", "test_knowledge_mirrors.py"), - "knowledge_group_members": ( - "insert_once", - "read-side schema only; no production writer inserts or rewrites membership evidence", - ), + "knowledge_group_members": ("builder", "test_crawl_storage_contracts.py"), "machine_identities": ("builder", "test_machines.py"), "org_model_calls": ("builder", "test_model_calls_switch.py"), "extraction_policies": ("builder", "test_extraction_policy.py"), diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index 0f298cdc55d..7027435a30c 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -172,6 +172,7 @@ def test_the_journal_files() -> None: "114_memory_proposal_review.sql", "115_memory_refusals.sql", "117_code_term_df_unchanged_refresh.sql", + "119_workspace_crawl.sql", ] diff --git a/tests/unit/test_scim.py b/tests/unit/test_scim.py index 97f1a7e0c06..943ae1327ce 100644 --- a/tests/unit/test_scim.py +++ b/tests/unit/test_scim.py @@ -254,10 +254,10 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any if "max(version)" in sql: newest = self.newest(params["k0"]) return {"v": max(time.time_ns(), newest["version"] + 1 if newest else 0)} - row = self.newest(params["id"]) if params else None if "active = 0" in sql: - return {"x": 1} if row and not row["active"] else None - return row + rows = [self.newest(uid) for uid in params["ids"]] + return {"x": 1} if any(row and not row["active"] for row in rows) else None + return self.newest(params["id"]) if params else None async def query_all(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: if sql == ( @@ -3200,3 +3200,35 @@ async def test_requests_at_once_keep_the_invariants() -> None: except AssertionError as e: raise AssertionError(f"{groups}: {e}") from e assert refused_late > 10 # a deactivation landed between a sign-in's two checks + + +async def test_a_large_batch_reads_in_bounded_statements(monkeypatch: pytest.MonkeyPatch) -> None: + sent: list[list[str]] = [] + emails = [f"person{n}@example.com" for n in range(2 * scim._IDS_PER_READ + 1)] + ids = sorted({scim.user_id(e) for e in emails}) + + class _Reads: + def __init__(self, deactivated: set[str]) -> None: + self.deactivated = deactivated + + async def query_one(self, sql: str, params: dict[str, Any]) -> dict[str, Any] | None: + sent.append(list(params["ids"])) + return {"x": 1} if self.deactivated & set(params["ids"]) else None + + monkeypatch.setattr(scim, "get_client", lambda: _Reads(set())) + assert await scim.any_deactivated(emails) is False + assert [len(batch) for batch in sent] == [scim._IDS_PER_READ, scim._IDS_PER_READ, 1] + assert [i for batch in sent for i in batch] == ids, "every id once, in order" + + # A deactivated id answers at its own statement: one read for the first slice, three + # for the last. + for index, reads in ((0, 1), (len(ids) - 1, 3)): + sent.clear() + monkeypatch.setattr(scim, "get_client", lambda index=index: _Reads({ids[index]})) + assert await scim.any_deactivated(emails) is True + assert len(sent) == reads + + +async def test_no_addresses_read_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(scim, "get_client", lambda: pytest.fail("no read for no addresses")) + assert await scim.any_deactivated([]) is False diff --git a/tests/unit/test_scim_people.py b/tests/unit/test_scim_people.py index 884d271705b..722ddd57234 100644 --- a/tests/unit/test_scim_people.py +++ b/tests/unit/test_scim_people.py @@ -107,8 +107,8 @@ async def query_one(self, sql, params=None): qualified.update(row["work_addresses"] & set(p["missing"])) return {"qualified": sorted(qualified)} if "loom.scim_users" in sql: - row = self.users.get(p["id"]) - return {"x": 1} if row and not row["active"] else None + rows = [self.users.get(uid) for uid in p["ids"]] + return {"x": 1} if any(row and not row["active"] for row in rows) else None raise AssertionError(sql) diff --git a/tests/unit/test_secrets_at_rest.py b/tests/unit/test_secrets_at_rest.py index e4f8ee18f5f..dba4d174c72 100644 --- a/tests/unit/test_secrets_at_rest.py +++ b/tests/unit/test_secrets_at_rest.py @@ -51,6 +51,17 @@ def _no_analysis_lease(monkeypatch: pytest.MonkeyPatch) -> None: ) +@pytest.fixture(autouse=True) +def _no_crawl_registries(monkeypatch: pytest.MonkeyPatch) -> None: + """These sealed-registry fakes contain no crawl approvals.""" + from server.knowledge.app import crawl_reseal + + async def empty(*, dry_run: bool, ch: object) -> tuple[int, list[str]]: + return 0, [] + + monkeypatch.setattr(crawl_reseal, "approvals", empty) + + def test_purposes_do_not_open_each_other_and_empty_stays_empty( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -235,8 +246,9 @@ def no_global_client(): pytest.fail("reseal must use the supplied ClickHouse client") @asynccontextmanager - async def source_lease(name: str, *, ttl_s: float, wait_s: float, ch=None): + async def source_lease(name: str, *, ttl_s: float, wait_s: float, ch=None, settle_writes: bool): assert ch is client and name == "knowledge-source:o:docs" + assert settle_writes is True assert ttl_s == 60.0 and wait_s == 5.0 calls.append("lease") yield True diff --git a/tests/unit/test_token_mint.py b/tests/unit/test_token_mint.py index 43a4b0f1d8b..58c1dc43ae5 100644 --- a/tests/unit/test_token_mint.py +++ b/tests/unit/test_token_mint.py @@ -494,8 +494,11 @@ async def test_the_identity_saves_to_reads_is_the_one_the_token_verifies_as( delegated = dataclasses.replace(delegated, saves_to="a") verified = verify_token(delegated.mint("sa:cursor-ab12cd")) built = delegated.as_auth("sa:cursor-ab12cd") - # Set at verification only: the token's id and its iat/exp. - minted_only = {"token_id", "issued_at", "expires_at"} + # Verification attaches both token metadata and the checked signing-key identity. + minted_only = {"token_id", "issued_at", "expires_at", "signing_authority"} + assert built.signing_authority is None + assert isinstance(verified.signing_authority, jwt_mod.SigningAuthority) + assert verified.signing_authority.current() for field in dataclasses.fields(AuthInfo): if field.name not in minted_only: assert getattr(built, field.name) == getattr(verified, field.name), field.name diff --git a/tests/unit/test_vendor_client.py b/tests/unit/test_vendor_client.py index 79dc70bd193..2911aaa4600 100644 --- a/tests/unit/test_vendor_client.py +++ b/tests/unit/test_vendor_client.py @@ -117,15 +117,46 @@ def test_an_answer_that_is_not_a_json_object_is_refused(answer: httpx.Response, assert caught.value.status == 0 -def test_a_network_failure_names_its_type_only() -> None: - def _down(request: httpx.Request) -> httpx.Response: - raise httpx.ConnectError("vendor.example refused", request=request) +def _down(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("vendor.example refused", request=request) + - with pytest.raises(_vendor.VendorError, match="^thing: ConnectError$") as caught: +def test_a_network_failure_names_its_type_only() -> None: + with pytest.raises(_vendor.Unreachable, match="^thing: ConnectError$") as caught: asyncio.run(_vendor.request_json(_client(_down), "GET", URL, "thing")) assert caught.value.status == 0 +def test_a_token_exchange_with_no_answer_is_unreachable() -> None: + with pytest.raises(_vendor.Unreachable, match="^token exchange: ConnectError$"): + asyncio.run(_vendor.exchange_token(_client(_down), URL, "token exchange")) + + +def test_a_capped_read_with_no_answer_is_unreachable() -> None: + with pytest.raises(_vendor.Unreachable, match="^download: ConnectError$"): + asyncio.run(_vendor.get_capped(_client(_down), URL, "tok", "download", max_bytes=10)) + + +def test_a_checked_capped_read_with_no_answer_is_unreachable() -> None: + from server.clients._checked_access import CheckedAccess + + async def run() -> None: + async def validate() -> None: + pass + + access = CheckedAccess( + "checked-token", + kind="gdrive", + deadline=asyncio.get_running_loop().time() + 60, + validate=validate, + ) + url = "https://www.googleapis.com/drive/v3/files/file/export" + await _vendor.get_capped(_client(_down), url, access, "download", max_bytes=10) + + with pytest.raises(_vendor.Unreachable, match="^download: ConnectError$"): + asyncio.run(run()) + + @pytest.mark.parametrize( ("status", "body", "raised", "text"), [