diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f4d65d402..642a0dcb02 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1171,6 +1171,7 @@ jobs: tests/integration/test_knowledge_sharing.py tests/integration/test_knowledge_restore.py tests/integration/test_restored_memory_ids.py + tests/integration/test_instance_consolidation.py tests/integration/test_memory_import.py tests/integration/test_cross_principal_leakage.py tests/integration/test_memory_get.py diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 180a1b4040..4d14b844f9 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -1278,11 +1278,14 @@ no search leg returns it. The other reads that could serve its value follow thre the version before a sweep labelled the row holds the same value unlabelled; a redacted version, which served no value, is not) and `memory.evidence` each write a `memory.sensitive_read` row. The admin dumps `namespace.snapshot` and `erasure.export` - carry `high` rows on purpose and write one per row. A conversation row has no label, so - `erasure.export` labels `high` a turn or thread whose text reads as high and audits it - the same way. `memory.copy_to` and `memory.cross_promote` read a `high` row by key and - copy it to another namespace with its label; each writes its own audit row (both are - `audit=True` ops), which records the copy. + carry `high` rows on purpose and write one per row. `loom instance export` is an + operator's dump, like `dev/backup_loom.py`: it reads the deployment's stores with its + own credentials, carries `high` rows into its owner-only bundle, and writes none. A + conversation row has no label, so `erasure.export` labels `high` a turn or thread whose + text reads as high and audits it the same way. `memory.copy_to` and + `memory.cross_promote` read a `high` row by key and copy it to another namespace with + its label; each writes its own audit row (both are `audit=True` ops), which records the + copy. `memory.get` (with or without `as_of`), `memory.get_by_id` and `memory.bulk_get` never serve a `high` row past its retention window; `memory.history` and `memory.evidence` still do until the sweep. `memory.bulk_get`, like `memory.list`, serves any other row past diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md index bbbccbed42..45c13dab74 100644 --- a/docs/architecture/storage-layout.md +++ b/docs/architecture/storage-layout.md @@ -176,12 +176,12 @@ wave's pull request finds them all and rewrites each in one of four ways. It fin The rewrites: -| Rewrite | When | Example | -| ------------------------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Bind a parameter** | the moved table narrows a ClickHouse read to a small set of keys | switched-off orgs, open runs, candidate ids | -| **Keep a projection or mirror** | the moved table is joined with large ClickHouse tables or feeds a view | `memory_records` with `memory_record_fields` (the record side leg), `agent_runs` in the mentor's scans, `namespaces` in worker scans | -| **Split per store** | one check reads a table in each store while its tables move in different waves | the sign-up check that refuses a name an existing principal holds (`_refuse_empowered` in `server/auth/self_signup.py`): each part reads its store, under the claim that guards it today, until every table it reads is in Postgres | -| **Move together** | two tables are always read together | `session_briefs` with its revisions | +| Rewrite | When | Example | +| ------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Bind a parameter** | the moved table narrows a ClickHouse read to a small set of keys | switched-off orgs, open runs, candidate ids | +| **Keep a projection or mirror** | the moved table is joined with large ClickHouse tables or feeds a view | `memory_records` with `memory_record_fields` (the record side leg), `agent_runs` in the mentor's scans, `namespaces` in worker scans | +| **Split per store** | one check reads a table in each store while its tables move in different waves | the sign-up check that refuses a name an existing principal holds (`refuse_empowered` in `server/auth/self_signup.py`): each part reads its store, under the claim that guards it today, until every table it reads is in Postgres | +| **Move together** | two tables are always read together | `session_briefs` with its revisions | Wave 1 moves namespace budget policy reads to Postgres and keeps spend reads in ClickHouse. In `server/observability/budget.py`, `budget_snapshot` reads @@ -210,7 +210,7 @@ transaction) and inserts its `namespaces` row with `ON CONFLICT`. An owned row w an ownerless one and never over an explicit registration, as `ReplacingMergeTree` ordering decides today. It stays best effort and never fails the write it rides on. A split check keeps its semantics: the sign-up check still refuses every holder -`_refuse_empowered` checks today (`server/auth/self_signup.py`), a grant, a namespace, a +`refuse_empowered` checks today (`server/auth/self_signup.py`), a grant, a namespace, a token, an inbox, a poster rule, a task, and the names a setting grants a role. `tests/unit/test_package_contracts.py` keeps the store modules separate; each rewrite lives in the store module of the table that moved. @@ -1256,7 +1256,7 @@ revocation are stored with the latest expiry the table holds (`revocation_expiry `server/auth/revocation.py`), so they never lapse. `namespace_grants` keys by `(org, namespace, subject)`, with an index on `(lower(subject), org)` for a principal's reach across orgs, which SCIM deprovisioning reads case-folded (`_orgs_beyond` in -`server/auth/scim.py`); the sign-up check reads it within one org (`_refuse_empowered` +`server/auth/scim.py`); the sign-up check reads it within one org (`refuse_empowered` in `server/auth/self_signup.py`). Erasure deletes the org's replay answers in Postgres `idempotency` (its `idempotency_revisions` rows cascading) and sets the org's `idempotency_fences` row, as `server/erasure/store/steps_pg.py` does today: by org, diff --git a/docs/operations/backup-and-recovery.md b/docs/operations/backup-and-recovery.md index bbec5116a7..29180e60ce 100644 --- a/docs/operations/backup-and-recovery.md +++ b/docs/operations/backup-and-recovery.md @@ -548,9 +548,10 @@ when that colour has no workers container does the rolled-forward one keep runni A new Loom process pointed at the same ClickHouse (and Postgres, under `LOOM_STORAGE_AUTHORITY=postgres`), or at a moved or restored one, gets back every -feature. Under the Postgres authority, stop the source before copying either store; -restoring one store from a backup taken at another time is a -[one-store restore](#restoring-one-store). Carry these: +feature. To land some orgs in another deployment that keeps serving its own, see +[moving orgs into another deployment](consolidation.md). Under the Postgres authority, +stop the source before copying either store; restoring one store from a backup taken at +another time is a [one-store restore](#restoring-one-store). Carry these: - ClickHouse: the same service, a copy with its Keeper state, or a `dev/backup_loom.py` dump restored into a ClickHouse that `loom migrate` prepared; diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md new file mode 100644 index 0000000000..711d8132eb --- /dev/null +++ b/docs/operations/consolidation.md @@ -0,0 +1,240 @@ +# Moving orgs into another deployment + +`loom instance export` writes one deployment's orgs into a bundle, and `loom instance +import` lands the bundle in another deployment that may already serve other teams, by a +plan the operator reviews first. Run both with the CLI where each deployment's servers +run, with their settings. To move a whole deployment onto new hosts, see +[moving a deployment](backup-and-recovery.md#moving-a-deployment) instead. + +## What moves + +| Moves | Stays behind | +| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Memory namespaces, with their settings, per-type settings, policies and guide | Code-index and mirror namespaces, and collections: the target indexes the repositories again | +| Password accounts, with their argon2id hash, so the person signs in with their old password | Tokens, signing keys and the service accounts', bots' and connected accounts' credentials: the receipt lists each for its owner to set up again | +| Live grants, under the mapped subjects, with the import as `granted_by` | Pending join requests, revoked grants, groups and the grants of groups, agents and `everyone`, which collections hold | +| Blacklist entries, before any content, each on the created namespaces it reaches | Conversations, session briefs, tasks, promoted shared memories and records: the manifest counts them | +| Live memories with their validity, plus `created_at` and attestation in a created namespace | Documents an end user wrote, which the target could not erase as theirs: the manifest counts them | +| Documents with their originals, embedded again by the target's embedder | Knowledge sources with a remote, and the documents a registered source syncs again or a removed one retires, except recording transcripts: the manifest lists the sources to register again, and counts the documents | +| | Embeddings, caches, traces, rollups, the audit log and agent events: the target builds what it needs again | + +A namespace's settings move except those naming the source's services or rows: +`rerank_endpoint`, `classify_endpoint`, `budget_alert_inbox` and `released_aliases` are +cleared for the target's owners to set again. Imported memories and documents carry +`source_class=imported` and the importing command (`process:cli:instance`) as `actor`. A +document lands with its text and original, and its `ingested_at` is the import's time; +the source's record of how it extracted them (`format`, `parser`, `coverage`, +`artifact_sha256` and its ingestion) stays behind. `memory.bulk_set` embeds a merged +namespace's memories as it writes them; a created namespace's memories reach vector +search once the embedding worker's next full pass embeds them +(`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SECONDS`). + +## Procedure + +1. Finish the source's erasures: the export refuses while one has not completed. Under + the Postgres memory authority it also refuses while a selected namespace has + documents waiting for publication. +2. Stop writes to the source. The bundle holds the rows at the moment each section is + read. An erasure the source runs after the export does not reach the bundle: export + again, or run the same erasure on the target once the import finishes. +3. Export, on the source: + + ```bash + loom instance export --org acme --out ./acme-bundle + loom instance export --org acme --namespace notes --out ./notes-bundle + ``` + + With `--namespace`, the bundle carries that namespace's content, and the account rows + its grants and owner name, so the plan can place them. Those accounts' own content + moves with a later export that selects them, which the target reads as the same + landing. An org or namespace with nothing to export refuses the export. + + A bundle holds password hashes and `high` memories: it is written readable by its + owner only, and is copied to the target whole, the way a database dump is. Like a + dump, the export writes no audit row per memory it reads. + +4. Plan, on the target. The dry run reads the target, prints each decision and refuses + the plan while anything is unresolved: + + ```bash + loom instance import --bundle ./acme-bundle --map map.yaml + ``` + + Each problem says what settles it. Where a map entry does, the run prints the entries + as YAML to copy into the map. The dry run builds every memory the bundle brings into a + namespace it lands, as the run would write it, so one the target cannot store (a date + past 2106, text the Postgres memory authority refuses, a value past its `char_limit`) + is named here, not part way through the run; it may name one the run would then leave + out, such as a key the target holds. + +5. Apply the plan it printed. `--expect-plan` refuses to apply a plan that changed since + the dry run, because the target or the map changed: + + ```bash + loom instance import --bundle ./acme-bundle --map map.yaml --apply --expect-plan 5e25ef6da948b233 + ``` + +6. Hand out the receipt's `set_up_again` list (the source org's service accounts, bots + and connected accounts, whichever namespaces the bundle selects), and register the + repositories and knowledge sources the manifest's `left_behind` names. A source + registered again writes its documents again, and keeps them up to date. A source + removed with its documents kept writes them no more, so they move with the bundle, + and a source retiring its documents takes them with it. A recording source lists only + its last weeks of meetings, so its transcripts move with the bundle instead: they + never change once written, and the source leaves each address it finds held as it is. + +## The map + +```yaml +orgs: # source org: target org (default: the same name) + acme: acme +sso_same_issuer: false # the source signed people in with this identity provider +namespaces: # "/": rule (default: create) + acme/notes: { rename: notes-legacy } + acme/lessons: { merge: lessons } # add grants: true to carry its grants too + acme/scratch: skip +subjects: # "/": rule + acme/alice: u-alice-1a2b3c4d # the same person's account on the target + acme/bob: { claim: bob-legacy } # a claimable account under another handle + acme/user:42: keep # the same end user on the target + acme/sa:ci-1a2b3c: drop +``` + +- **Created namespaces.** A namespace is created under its own name, or the name the map + gives it, owned by the source's owner under the mapped subject; where the map drops + that subject, or there is none, the import owns it, as the dry run says. The plan + refuses a name the target already holds (a namespace or a released alias) and a name + of the form single sign-on gives a person; the apply also refuses a name that holds + data with no namespace row. Two source orgs landing in one target org may not bring + the same name. In a target org that serves others, a namespace anyone in the source + org could join at once lands with `join_policy: approval`, so a namespace admin + approves each member of the target org who asks. Its rows name their verifier and + locker, and its policies and guide revisions their writer, under the mapped subject, + and no one where the map drops or never planned it. Per-type settings, policies and + the guide land with a created namespace only. +- **Merged namespaces.** `merge` writes into an existing namespace through + `memory.bulk_set`, so the blacklist, conflict surfacing, pinned peers and the skip of + an unchanged restatement hold there, with every entry checked, oldest first, and none + reinforcing a row. It only adds: a key the target namespace holds or has held under + the same agent, user and session is left as the target has it. Under the `newest_wins` + policy, where a same-key write retires the older rows in other sessions too, a key is + also left alone where the target holds or has held it for the same user in any agent + or session, or, for a row with no user, for anyone; a namespace definition, which no + other write of its key retires, holds only its own row. Each write reads that again + just before it, so a key the target's owners write while the run goes on stays theirs + too. Of the rows the bundle brings that a write of one would retire (one key under one + agent, user and session, across two merged namespaces too, and under `newest_wins` one + user's rows of a key, or the rows of a key with no user), the newest by `valid_at` + (its `created_at` where it has none), then the first in the bundle, lands, and the + receipt counts the others as `memories_superseded`. Under `newest_wins` the rows with + no user are written first, so a named row of the same key, which a later write with no + user would retire, lands beside them, as the source served both. A namespace + definition, which no other write of its key retires, is written before them. Admission + may still mark a target row a merged one contradicts as conflicted, and retire one: + under `newest_wins`, a row that states the same attribute of the same subject with + another value, unless the merged row is the older statement by `valid_at`, and, with + the conflict resolver on, one it judges the merged row updates. +- **Merged rows.** The source's refusals that reach the source namespace refuse the rows + it brings, and none is stored on the target's namespace. A merge writes the rows reads + serve, active or conflicted (the target's admission judges the pair again): a row in + another state, redacted, or past its expiry when the run starts, is left out (one that + expires before its write lands with a one-second expiry), and pins and locks are not + carried. A merged row's `created_at` is the import's; its validity, expiry, + sensitivity and evidence are the source's. The target's sensitive retention window + applies to a merged row as to any write there, and `memory.bulk_set` gives it the + target's expiry action for the level it grades the row at, so the dry run names a + merged row the source expires by an action other than deleting it when the target's + differs: land its namespace as a created one, which keeps it. The reason recorded for + an expiry is not carried. Admission may decline a memory (a pinned peer, or a + restatement it folds into a row): the receipt counts it as `memories_not_admitted`. + Under the Postgres authority a `memory.bulk_set` call that commits but whose + publication to ClickHouse is owed is left to the delivery worker, and the run goes on: + the receipt counts its entries as `memories_publication_pending`, as admission's + answer for each is lost. +- **Documents.** A document whose `source_uri` the target namespace holds or has held is + left as it is, read just before its write, and of two namespaces merged into one, the + first in the bundle brings an address both hold. Under the Postgres authority a + document that commits but whose publication is owed counts as written, and the run + goes on. +- **Accounts.** An account lands as a claimable password account under its handle. The + plan refuses a handle the target holds, or one that already holds access there (a + grant, a namespace, a token, a task, or a setting such as `LOOM_PLATFORM_ADMINS` names + it), a handle the target revoked outright, in any org, which no token would sign in + as, unless the source revoked that account too, an email any target account signs in + with, and an email another account of the bundle lands with, which single sign-on + would refuse; it proposes a new handle or `drop`. Mapping an account onto a target + account gives that account the source account's content and grants, and nothing proves + a target account's contact email: map only the same person. A single sign-on account + has no password to prove the person, so it needs a mapping, or `sso_same_issuer: true` + when both deployments use the same identity provider, which also carries its links. An + account single sign-on made on the source lands as one it did not make on the target, + so the target never gives back an owner grant the source revoked. An account the + source revoked, by an operator or by SCIM, lands with no password, email or links, and + its grants stay behind, the grants to its emails too: nobody signs in to it, so the + plan checks none of its emails. When the source revoked it after an earlier bundle + landed it as an account that signs in, the plan refuses, whatever the map now does + with it, until the target revokes that account (`loom revoke-token --subject +`), which also ends the tokens and sessions it has had there since. The plan + reads earlier landings only in the target org each source org lands in now. The + revocation reaches the handle in every org of the target deployment; where another org + has an account under it, deleting the landed account (`namespace.delete`) ends this + refusal instead, but ends only its sign-in: a token it already holds keeps its grants + until it expires. For a landing an earlier run did not finish, the plan then proposes + another handle. +- **Subjects.** The plan decides the subjects a landing needs: a created namespace's + grants, owner and end users; a merged one's end users, and its grant subjects when it + carries its grants; none of a skipped one's. A grant to an email admits whoever proves + the address at sign-in on the target, as on the source; it lands under the account + that verified the address there, if one did (see Grants). A `user:` subject is kept in + a target org only the import lands in. In one that serves others, or that two source + orgs land in, it may name another person, so it needs `keep`, a mapping to another + `user:` subject (an id: `user:-` and `user:` name no user), or `drop`. Its decision + moves that end user's memories too; two end users of one source org may not land as + one. `group:`, `agent:` and `everyone` hold grants on collections only, so the plan + refuses one on a moved namespace until the map drops it or maps it to a person's + subject, and refuses a mapping onto one. `sa:` subjects are dropped, and `keep` on one + is refused. Any other subject needs a mapping or `drop`. No grant of a subject the + source revoked outright lands (an end user's revocation is `/user:`), and the + plan refuses mapping one onto a target subject, who would gain its content. The target + does not carry the revocation, so an end user the source revoked needs `keep` or + `drop`: under `keep` the target's end-user tokens for its id read its rows again. +- **Grants.** A grant lands under the subject `grants.create` would write it under (a + verified email's account handle). It is left out when the person already holds that + role or higher there under a verified spelling, or a target admin revoked them there + under any spelling the directory ties to the subject, in any case. A pending request + is no grant: the source's grant replaces it. +- A map entry that names no org, namespace or subject of the bundle refuses the plan. + +## Running it again + +An import that stops part way runs again with the same command. It plans the same digest +unless the target changed what the plan reads: a namespace someone created since in a +target org only the import landed in makes that org one that serves others, and the dry +run then shows the plan's new decisions. A namespace row an earlier run wrote takes two +of them: self-join by approval where it is open, and the owner the map now names in +place of the import's; anything else on it stays as the target has it, and no decision +opens it. Before it creates a namespace it writes an `instance.import` audit row naming +its source (`instance.import.merge` for a merge), and a later plan reads that row as +this source's landing, not as a collision, while the namespace row it finds is the one +the import wrote, with the source's `created_at`, and its owners have not deleted it: a +name someone took since is a collision. Once a namespace's content is written, an +`instance.import.done` row marks it, and later runs leave that namespace alone, so what +its owners deleted or revoked on the target since stays so. Within an unfinished +namespace, a run writes nothing the target holds already: no memory key (agent, user, +session and key) the namespace has held, deleted ones included, so a fact someone wrote +there before the rerun stays theirs, no document whose `source_uri` it has held, no +setting, policy, guide revision or single sign-on link it holds in any state, and no +grant the person holds at that role or higher, or was revoked from. Under the Postgres +memory authority, what the authority holds counts, its publication to ClickHouse owed or +not. These rows live as long as the audit log keeps rows +(`LOOM_RETENTION_AUDIT_LOG_DAYS`). + +An erasure that runs on the target while an import is unfinished removes what the target +holds then, and a purge leaves no row for a later run to find: as after a +[restore](backup-and-recovery.md#undoing-changes-inside-a-namespace), run the same +erasure again once the import finishes. + +## Related + +- [Backup and recovery](backup-and-recovery.md): full backups, and moving a deployment +- [Single sign-on](sso.md#accounts): how a person claims a password account diff --git a/docs/operations/index.md b/docs/operations/index.md index c333605325..70f1dc181c 100644 --- a/docs/operations/index.md +++ b/docs/operations/index.md @@ -24,6 +24,7 @@ Deploy Loom for a team, choose storage and identity settings, and maintain a run - [Monitoring](monitoring.md) lists health checks, metrics, and traces. - [Troubleshooting](troubleshooting.md) starts with symptoms such as empty search results and connection failures. - [Backup and recovery](backup-and-recovery.md) covers ClickHouse, Postgres where used, and document originals. +- [Moving orgs into another deployment](consolidation.md) covers landing one deployment's orgs in another that already serves other teams. - [Upgrades](upgrades.md) explains version checks, migrations, and rolling updates. - [Maintenance](maintenance.md) covers retention, rotation, and scheduled operator tasks. - [Code-index operations](code-index-operations.md) covers indexing, freshness, and failures. diff --git a/docs/operations/meta.ts b/docs/operations/meta.ts index 9a27f8dea7..5a2d17cd67 100644 --- a/docs/operations/meta.ts +++ b/docs/operations/meta.ts @@ -9,6 +9,7 @@ export default { "monitoring", "troubleshooting", "backup-and-recovery", + "consolidation", "maintenance", "upgrades", "supported-versions", diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 98d6a06495..4bd4314443 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -298,6 +298,9 @@ python scripts/codegen/docs_reference.py | `loom sql-access grant` | Make the user read exactly this scope, creating it (and printing its password once) when there is none. | `--user`, `--org`, `--namespaces`, `--all`, `--rotate` | | `loom sql-access revoke` | Take the user's scope away, then drop the user. | `--user` | | `loom sql-access list` | Every granted scope row, by SQL user. | | +| `loom instance` | Move orgs between deployments: export a bundle on the source, import it on the target by a reviewed plan. | | +| `loom instance export` | Write the selected orgs' namespaces, accounts, grants, memories and documents into a new bundle directory. | `--org`, `--namespace`, `--out` | +| `loom instance import` | Plan a bundle's import against this deployment and print it; with --apply and the plan's digest, write it. | `--bundle`, `--map`, `--expect-plan`, `--apply`, `--dry-run` | | `loom reembed` | Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). | `--org`, `--namespace`, `--batch-size`, `--in-database`, `--dry-run`, `--delete-old`, `--key-only`, `--resume` | | `loom reextract` | Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is… | `--org`, `--namespace`, `--into`, `--base-url`, `--token`, `--dates`, `--concurrency`, `--limit-sessions`, `--dry-run` | | `loom deploy-delta` | What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side… | `--swap-at`, `--window-min`, `--ch-os-user`, `--cluster`, `--top`, `--json` | diff --git a/server/auth/self_signup.py b/server/auth/self_signup.py index 090b26fc5b..867953dfcb 100644 --- a/server/auth/self_signup.py +++ b/server/auth/self_signup.py @@ -7,7 +7,7 @@ org = settings.self_signup_org (a request naming another is refused) namespaces = [] roles = ['writer']: a name a setting or a grant empowers cannot - be claimed (`_refuse_empowered`) + be claimed (`refuse_empowered`) sa = false (user token, not service account) For trusted-network deployments where reachability is the access @@ -245,7 +245,7 @@ async def _claim_checked( ) if existing is not None or await directory().in_use(org, namespace, ch=ch): raise _name_claimed(namespace) - await _refuse_empowered(ch, org, namespace) + await refuse_empowered(ch, org, namespace) contact_email = input.email.strip().lower() if not _valid_signup_email(contact_email): @@ -283,7 +283,7 @@ async def _claim_checked( ) ttl_seconds = int(input.ttl_days) * 86400 # Sign-up confers no role: the email is unverified and a platform-admin - # handle cannot be claimed here (`_refuse_empowered`). + # handle cannot be claimed here (`refuse_empowered`). token = mint_token( subject=subject, org=org, @@ -379,7 +379,7 @@ def _claimable_namespace(name: str) -> str: return namespace -async def _refuse_empowered(ch: Any, org: str, name: str) -> None: +async def refuse_empowered(ch: Any, org: str, name: str) -> None: """Refuse, as a taken name, a name a setting empowers, or one holding an unrevoked grant, a namespace, an unrevoked token, a task inbox's owner or poster, a poster rule or a task it posted in the org, read case-folded as grants are; @@ -641,7 +641,7 @@ async def _provision_agent( if existing is not None or await directory().in_use(org, namespace, ch=ch): raise _name_claimed(namespace) # A person claims the account later under the name, as its subject. - await _refuse_empowered(ch, org, namespace) + await refuse_empowered(ch, org, namespace) claim_code = secrets.token_urlsafe(18) sa_hash = hashlib.sha256(f"agent:{org}:{namespace}:{time.time_ns()}".encode()).hexdigest()[:6] diff --git a/server/cli/app.py b/server/cli/app.py index 93402c7665..0353309da0 100644 --- a/server/cli/app.py +++ b/server/cli/app.py @@ -103,7 +103,7 @@ def _load_dotenv_like_the_container() -> None: def _add_module_parsers(sub: Any) -> None: """Subcommands registered by their own modules: code, decisions, knowledge, okf, up, ch-setup, participant, deployment, settings, secrets, signing-key, - provider-lock, export-analytics and sql-access.""" + provider-lock, export-analytics, sql-access and instance.""" from server.cli.code import register_code_cli register_code_cli(sub) @@ -160,6 +160,10 @@ def _add_module_parsers(sub: Any) -> None: register_sql_access_cli(sub) + from server.cli.instance import register_instance_cli + + register_instance_cli(sub) + def _add_claim_release_parser(sub: Any) -> None: """The `claim-release` subcommand.""" diff --git a/server/cli/instance.py b/server/cli/instance.py new file mode 100644 index 0000000000..9a1d415692 --- /dev/null +++ b/server/cli/instance.py @@ -0,0 +1,196 @@ +"""`loom instance export` and `loom instance import`: move orgs from one deployment into +another (`docs/operations/consolidation.md`).""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +from server.cli._apply import add_apply_flags + + +def register_instance_cli(sub: Any) -> None: + p = sub.add_parser( + "instance", + help="Move orgs between deployments: export a bundle on the source, import it on the " + "target by a reviewed plan.", + ) + isub = p.add_subparsers(dest="subcommand", required=True) # tags cli.instance. + e = isub.add_parser( + "export", + help="Write the selected orgs' namespaces, accounts, grants, memories and documents " + "into a new bundle directory. Reads only.", + ) + e.add_argument( + "--org", dest="orgs", action="append", required=True, help="An org to export (repeat)" + ) + e.add_argument( + "--namespace", + dest="namespaces", + action="append", + default=None, + help="Export only this namespace, with the accounts its grants name (repeat; " + "default: every memory namespace of the orgs)", + ) + e.add_argument("--out", required=True, type=Path, help="A new or empty directory") + e.set_defaults(func=_cmd_export) + i = isub.add_parser( + "import", + help="Plan a bundle's import against this deployment and print it; with --apply and " + "the plan's digest, write it.", + ) + i.add_argument("--bundle", required=True, type=Path, help="The bundle directory") + i.add_argument( + "--map", type=Path, default=None, help="The YAML map of orgs, namespaces and subjects" + ) + i.add_argument( + "--expect-plan", + default="", + help="The digest the dry run printed: --apply refuses a plan that changed since", + ) + add_apply_flags(i, writes="write the plan") + i.set_defaults(func=_cmd_import, apply_gated=False) # its own hint names the digest + + +def _cmd_export(args: argparse.Namespace) -> int: + from server.cli._ch import reads, run_connected + from server.cli.instance_bundle import BundleError + from server.cli.instance_export import export + + async def _run(ch: Any) -> dict[str, Any]: + return await export(ch, orgs=args.orgs, namespaces=args.namespaces, out=args.out) + + try: + m = run_connected(_run, org_free=reads("exports the selected orgs' rows")) + except BundleError as e: + raise SystemExit(str(e)) from None + for org, names in m["namespaces"].items(): + print(f"{org}: {len(names)} namespace(s)") + for name, s in m["sections"].items(): + print(f" {name}: {s['rows']} row(s)") + print(f" originals: {m['originals']}") + print(f"wrote {args.out}") + return 0 + + +def _print_plan(bundle: Any, p: Any, targets: Any) -> None: + from server.cli.instance_import import carried, source_key + from server.cli.instance_plan import proposal_yaml + from server.memory.domain.provenance import cli_actor + + content = carried(bundle) + owners = { + (r["org"], r["namespace"]): r.get("owner_email") for r in bundle.records("namespaces") + } + subjects = p.subject_map() + for d in p.namespaces: + land = "skip" if d.action == "skip" else f"{d.action} {d.target_org}/{d.target}" + account = f" (account, {d.account})" if d.account else "" + done = (d.target, source_key(bundle, d.source_org, d.source)) in targets[d.target_org].done + approval = d.approval and not done + joins = " (self-join needs approval: the target org serves others)" if approval else "" + if d.action == "skip": + note = "" + elif done: + note = " (an earlier run finished it: skipped)" + elif (d.source_org, d.source) not in content: + note = " (its row only: a bundle that selects it brings its content)" + else: + note = "" + owner = owners.get((d.source_org, d.source)) + # A row an earlier run wrote (the plan refused any other) keeps an owner it landed. + landed = targets[d.target_org].namespaces.get(d.target) if d.action == "create" else None + kept = landed is not None and landed.get("owner_email") != cli_actor("instance") + if d.action == "create" and not ( + d.account or done or kept or subjects.get((d.source_org, owner)) + ): + note += " (owned by the import: no owner lands)" + print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{note}") + for s in p.subjects: + to = f" → {s.target}" if s.action in ("map", "claim") else "" + note = f" [{s.note}]" if s.note else "" + print(f" subject {s.source_org}/{s.subject}: {s.action}{to}{note}") + if n := bundle.rows("blacklist"): + print( + f" refusals: {n} source pattern(s), each on the created namespaces above that it " + "reaches; a merge refuses the rows it brings by them" + ) + for section in ("service_accounts", "bots", "connected_accounts"): + if n := bundle.rows(section): + print(f" {section}: {n} to set up again on the target (listed by --apply)") + left = bundle.manifest.get("left_behind") or {} + counted: dict[str, int] = {} + for r in left.get("rows") or []: + counted[r["kind"]] = counted.get(r["kind"], 0) + int(r["n"]) + for kind in ("code_repos", "knowledge_sources"): + if n := len(left.get(kind) or []): + print(f" left behind: {kind}: {n} to register again") + for kind, n in sorted(counted.items()): + print(f" left behind: {kind}: {n} row(s)") + if p.problems: + print(f"{len(p.problems)} problem(s): the plan is refused") + for problem in p.problems: + print(f" ✗ {problem}") + if p.proposals: + print("map entries that settle them (edit, add to --map, plan again):") + print(proposal_yaml(p)) + return + print(f"plan {p.digest}") + + +def _cmd_import(args: argparse.Namespace) -> int: + import yaml + + from server.cli._ch import check_acceptance, run_connected + from server.cli.instance_bundle import Bundle, BundleError + from server.cli.instance_import import apply, build_plan, check, load_target + from server.cli.instance_plan import MapError, parse_map + from server.core.ch import sequential_reads + + try: + bundle = Bundle.open(args.bundle) + rules = parse_map(yaml.safe_load(args.map.read_text()) if args.map else None) + except (BundleError, MapError, OSError, yaml.YAMLError) as e: + raise SystemExit(str(e)) from None + target_orgs = sorted({rules.orgs.get(o, o) for o in bundle.manifest["orgs"]}) + + async def _run(ch: Any) -> int: + # Every read sees the target's latest writes, on whichever replica it lands: what a + # rerun must not write again is decided by them. + with sequential_reads(): + return await _plan_and_apply(ch) + + async def _plan_and_apply(ch: Any) -> int: + targets, signs_in = await load_target(ch, target_orgs) + p = build_plan(bundle, rules, targets, signs_in) + await check(ch, bundle, p, targets) + _print_plan(bundle, p, targets) + if p.problems: + return 1 + if args.dry_run: + print( + "dry run: nothing was written; re-run with --apply --expect-plan " + f"{p.digest} to write", + file=sys.stderr, + ) + return 0 + if args.expect_plan != p.digest: + print( + f"--expect-plan {args.expect_plan!r} is not this plan ({p.digest}): review it", + file=sys.stderr, + ) + return 2 + # The target orgs are declared, and a recording cell records them, only to write a + # reviewed plan. + await check_acceptance(orgs=target_orgs) + try: + receipt = await apply(ch, bundle, p, targets) + except BundleError as e: # a file changed since the dry run read it + raise SystemExit(f"{e}: the import stopped part way; run it again") from None + print(json.dumps(receipt, indent=2, default=str)) + return 0 + + return run_connected(_run, orgs=()) diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py new file mode 100644 index 0000000000..38943de153 --- /dev/null +++ b/server/cli/instance_bundle.py @@ -0,0 +1,208 @@ +"""A consolidation bundle: one deployment's rows for a set of orgs, read back on another. + +A bundle is a directory: one gzip JSONL file per section (`memories`, `grants`, ...), the +document originals as raw files named by their SHA-256 under `originals/`, and +`manifest.json`, written last. Each section file is written under a `.part` name and +renamed when it is closed, and the manifest records every section's row count, byte size +and SHA-256, so a reader refuses a bundle whose export was cut off or whose files changed. +The bundle holds password hashes: its directories are 0700 and its files 0600. +A checksum proves the files are the ones the export wrote, not that their content may be +trusted: the importer authorizes and admits every row as it would any other write. +""" + +from __future__ import annotations + +import gzip +import hashlib +import json +import os +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any +from uuid import UUID + +from server.cli._paths import write_private + +FORMAT = "loom-instance-bundle" +VERSION = 1 +MANIFEST = "manifest.json" +ORIGINALS = "originals" +_CHUNK = 1 << 20 + + +class BundleError(ValueError): + """The bundle cannot be read as a complete export: missing, altered or of another + format. The message names the file.""" + + +def _default(v: Any) -> Any: + if isinstance(v, datetime | date): + return v.isoformat() + if isinstance(v, UUID | Decimal): + return str(v) + raise TypeError(f"cannot write {type(v).__name__} to a bundle") + + +def _private(path: str, flags: int) -> int: + return os.open(path, flags, 0o600) + + +def encode(record: Mapping[str, Any]) -> bytes: + """One JSONL line: compact, UTF-8 kept as is.""" + return ( + json.dumps(record, default=_default, ensure_ascii=False, separators=(",", ":")) + "\n" + ).encode() + + +def _sha256_file(path: Path) -> tuple[str, int]: + h, size = hashlib.sha256(), 0 + with path.open("rb") as fh: + while chunk := fh.read(_CHUNK): + h.update(chunk) + size += len(chunk) + return h.hexdigest(), size + + +@dataclass +class _Section: + file: str + rows: int = 0 + + +@dataclass +class BundleWriter: + """Writes one bundle into `out`, an absent or empty directory.""" + + out: Path + _sections: dict[str, _Section] = field(default_factory=dict) + _originals: int = 0 + + def __post_init__(self) -> None: + if self.out.exists() and (not self.out.is_dir() or any(self.out.iterdir())): + raise BundleError( + f"{self.out} is not an empty directory: write each bundle into a new one" + ) + self.out.mkdir(parents=True, mode=0o700, exist_ok=True) + self.out.chmod(0o700) + (self.out / ORIGINALS).mkdir(mode=0o700) + + @contextmanager + def section(self, name: str) -> Iterator[_SectionSink]: + """A sink for `name`'s records; the file is renamed into place when the block + ends without an error, so a failed export leaves no section and no manifest.""" + if name in self._sections: + raise BundleError(f"section {name!r} written twice") + final = self.out / f"{name}.jsonl.gz" + part = final.with_name(final.name + ".part") + with open(part, "wb", opener=_private) as raw, gzip.open(raw, "wb", compresslevel=6) as fh: + sink = _SectionSink(fh) + yield sink + part.rename(final) + self._sections[name] = _Section(final.name, sink.rows) + + def original(self, data: bytes) -> str: + """Store a document original under its SHA-256 (once), and return the digest.""" + digest = hashlib.sha256(data).hexdigest() + path = self.out / ORIGINALS / digest + if not path.exists(): + part = path.with_name(digest + ".part") + with open(part, "wb", opener=_private) as fh: + fh.write(data) + part.rename(path) + self._originals += 1 + return digest + + def finish(self, meta: Mapping[str, Any]) -> dict[str, Any]: + """Write the manifest, which marks the bundle complete, and return it.""" + sections = {} + for name, s in sorted(self._sections.items()): + sha, size = _sha256_file(self.out / s.file) + sections[name] = {"file": s.file, "rows": s.rows, "bytes": size, "sha256": sha} + manifest = { + "format": FORMAT, + "version": VERSION, + **meta, + "sections": sections, + "originals": self._originals, + } + write_private(self.out / MANIFEST, json.dumps(manifest, indent=2, default=_default) + "\n") + return manifest + + +class _SectionSink: + def __init__(self, fh: gzip.GzipFile) -> None: + self._fh = fh + self.rows = 0 + + def write(self, record: Mapping[str, Any]) -> None: + self._fh.write(encode(record)) + self.rows += 1 + + +@dataclass(frozen=True) +class Bundle: + """A complete bundle, its files checked against the manifest when each run opens it: + the checks find an unfinished or damaged copy. The bundle is its operator's own + directory (0700), so a file changed while a run reads it is their change.""" + + path: Path + manifest: dict[str, Any] + digest: str # the manifest's SHA-256, of the bytes read: names it in a plan and a receipt + + @classmethod + def open(cls, path: Path) -> Bundle: + try: + raw = (path / MANIFEST).read_bytes() + manifest = json.loads(raw) + except FileNotFoundError: + raise BundleError( + f"{path} has no {MANIFEST}: the export did not finish, or this is not a bundle" + ) from None + except json.JSONDecodeError as e: + raise BundleError(f"{path / MANIFEST} is not JSON: {e}") from None + if manifest.get("format") != FORMAT: + raise BundleError(f"{path} is not a {FORMAT}") + if manifest.get("version") != VERSION: + raise BundleError( + f"{path} is bundle version {manifest.get('version')}; this build reads {VERSION}" + ) + for name, s in manifest.get("sections", {}).items(): + file = Path(s["file"]) + if file.name != s["file"] or file.suffixes[-2:] != [".jsonl", ".gz"]: + raise BundleError(f"section {name!r} names a file outside the bundle") + try: + sha, size = _sha256_file(path / file) + except FileNotFoundError: + raise BundleError(f"{path / file} is missing") from None + if (sha, size) != (s["sha256"], s["bytes"]): + raise BundleError(f"{path / file} differs from the manifest") + return cls(path, manifest, hashlib.sha256(raw).hexdigest()) + + def rows(self, name: str) -> int: + return int(self.manifest["sections"].get(name, {}).get("rows", 0)) + + def records(self, name: str) -> Iterator[dict[str, Any]]: + """The section's records in written order; none when the bundle has no such + section (an export that selected none).""" + s = self.manifest["sections"].get(name) + if s is None: + return + with gzip.open(self.path / s["file"], "rb") as fh: + for line in fh: + yield json.loads(line) + + def original(self, digest: str) -> bytes: + """A document original's bytes, refused when they do not hash to `digest`.""" + if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): + raise BundleError(f"{digest!r} is not a SHA-256") + try: + data = (self.path / ORIGINALS / digest).read_bytes() + except FileNotFoundError: + raise BundleError(f"original {digest} is missing from the bundle") from None + if hashlib.sha256(data).hexdigest() != digest: + raise BundleError(f"original {digest} differs from its name") + return data diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py new file mode 100644 index 0000000000..e82f8afc1a --- /dev/null +++ b/server/cli/instance_export.py @@ -0,0 +1,482 @@ +"""`loom instance export`: one deployment's orgs as a consolidation bundle. + +The export runs where the source deployment's servers run, with their settings, and only +reads. Each section is the rows of one kind for the selected orgs. Embeddings, the code +index, caches, traces and rollups are left out: the target builds them again, and the +manifest lists the repositories and sources whose owners register them again. + +What is never exported: tokens (none are stored), signing keys, the connected accounts' +encrypted credentials, provider settings, runtime overrides. Password hashes of accounts +are exported (argon2id, no deployment secret mixed in), so the bundle is as sensitive as +the accounts table: it is written with owner-only permissions. +""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator, Iterable, Sequence +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from server.cli.instance_bundle import BundleWriter +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, source_tag + +# SCIM's revocation key prefix (`server.auth.revocation.SCIM_PREFIX`) as a SQL literal. +_SCIM = "\\0scim:" +# The subjects among {lowered} revoked outright, by an operator or by SCIM and under any +# case (grants fold case). +REVOKED = ( + f"SELECT lower(replaceOne(jti, '{_SCIM}', '')) AS subject, reason " + "FROM loom.revoked_tokens FINAL " + f"WHERE lower(replaceOne(jti, '{_SCIM}', '')) IN {{lowered:Array(String)}} " + "AND issued_before IS NULL AND expires_at > now()" +) +PG_PAGE = 5000 # Postgres heads per read, export and import alike +# A knowledge source's copy that a source registered there writes again, or one removed +# with its copies retires: it keeps only its own copies, those its `source:` tag marks +# (`source_sync.ours`), with `{sources}` from `_source_tags`. A recording source lists its +# last weeks only and its transcripts are settled when written, so its copies move, as do +# those of a source removed with its copies kept, which no source writes again. +_RESYNCED = ( + "actor = {sync:String} AND JSONExtractString(metadata, 'source_kind') != 'recording' " + "AND arrayExists(t -> has({sources:Array(String)}, concat(org, '/', namespace, '/', t)), tags)" +) +_STREAM_SETTINGS = { + "max_execution_time": 0, + # UTC with its zone: a plain DateTime would read in the source server's time zone. + "date_time_output_format": "iso", + "output_format_json_quote_64bit_integers": 0, + "output_format_json_named_tuples_as_objects": 0, +} + + +async def stream_rows( + ch: Any, sql: str, params: dict[str, Any], *, settings: dict[str, Any] | None = None +) -> AsyncIterator[dict[str, Any]]: + """A SELECT's rows one at a time off one streamed JSONEachRow response: a table of + millions of rows is read once, never paged and never held.""" + buf = bytearray() + async with ch.raw_stream( + f"{sql}\nFORMAT JSONEachRow", params, settings={**_STREAM_SETTINGS, **(settings or {})} + ) as stream: + async for chunk in stream: + buf += chunk + start = 0 + while (end := buf.find(b"\n", start)) >= 0: + if end > start: + yield json.loads(buf[start:end]) + start = end + 1 + del buf[:start] + if buf.strip(): + yield json.loads(buf) + + +async def _deployment_id(ch: Any) -> str: + row = await ch.query_one("SELECT deployment_id FROM loom.storage_authority FINAL LIMIT 1") + if not row or not row.get("deployment_id"): + raise SystemExit("this ClickHouse records no deployment id: start a server on it once") + return str(row["deployment_id"]) + + +async def refuse_unfinished_erasures(ch: Any, orgs: Sequence[str]) -> None: + """An export reads rows an unfinished erasure may still delete, and the target would + keep them: finish or settle every erasure of the selected orgs first.""" + rows = await ch.query_all( + """ + SELECT toString(id) AS id, org, scope_type, toString(status) AS state + FROM loom.erasure_requests FINAL + WHERE org IN {orgs:Array(String)} AND status != 'completed' + """, + params={"orgs": list(orgs)}, + ) + if rows: + listed = ", ".join(f"{r['id']} ({r['org']} {r['scope_type']}, {r['state']})" for r in rows) + raise SystemExit( + f"erasures that have not completed reach the selected orgs: {listed}. " + "Export once each completes (loom doctor lists failed ones)." + ) + + +async def refuse_unpublished_documents(selected: dict[str, list[str]]) -> None: + """Under the Postgres authority the documents are read from their ClickHouse + projection: a commit whose publication is owed would be missed, or a deleted head + moved. Export once every selected namespace's deliveries settle.""" + from server.core import pg + from server.knowledge.store import pg_documents + + if not pg.enabled(): + return + owed = [] + for org, names in selected.items(): + for ns in names: + pending, parked = await pg_documents.unpublished(org, ns) + if pending or parked: + owed.append(f"{org}/{ns} ({pending} owed, {parked} parked)") + if owed: + raise SystemExit( + "document publications have not finished: " + ", ".join(owed) + ". Stop writes " + "and export once they settle (parked ones need the delivery worker's repair)." + ) + + +def exported_namespace(row: dict[str, Any]) -> bool: + """A memory namespace the organization holds: not a code index's or a benchmark's, + not a mirror's or a code store's (the index rebuilds them), not a collection (which does + not move), and not soft-deleted.""" + from server.auth.sharing import is_collection + from server.core.naming import is_reserved_name + + name = str(row["namespace"]) + return ( + row.get("kind", "memory") == "memory" + and bool(row.get("active", True)) + and not (is_reserved_name(name) or is_collection(name)) + ) + + +def select_namespaces( + rows: list[dict[str, Any]], + grants: list[dict[str, Any]], + wanted: list[str] | None, + links: Iterable[dict[str, Any]] = (), +) -> dict[str, list[str]]: + """Per org, the namespaces the bundle carries: every exported namespace, or the + `wanted` ones together with the accounts that own them or hold grants on them, by + handle or by an email of theirs (contact or single sign-on `links`), so the plan can + place every subject they name: single sign-on on the source admits no one by an + address a revoked or password account names.""" + from server.cli.instance_plan import is_account + + out: dict[str, set[str]] = {} + for r in rows: + if exported_namespace(r) and (wanted is None or r["namespace"] in wanted): + out.setdefault(str(r["org"]), set()).add(str(r["namespace"])) + if wanted is not None: + named: dict[str, set[str]] = {} + for r in rows: + if r["namespace"] in out.get(str(r["org"]), set()): + named.setdefault(str(r["org"]), set()).add(str(r.get("owner_email") or "").lower()) + for g in grants: + if g["namespace"] in out.get(str(g["org"]), set()): + named.setdefault(str(g["org"]), set()).add(str(g["subject"]).lower()) + linked: dict[tuple[str, str], set[str]] = {} + for link in links: + key = (str(link["org"]), str(link["namespace"])) + linked.setdefault(key, set()).add(str(link["email"]).lower()) + for r in rows: + org, name = str(r["org"]), str(r["namespace"]) + email = str(r.get("contact_email") or "") + spelled = {name.lower(), email.lower(), *linked.get((org, name), ())} + if is_account(r) and exported_namespace(r) and (spelled - {""}) & named.get(org, set()): + out.setdefault(org, set()).add(name) + return {org: sorted(names) for org, names in out.items()} + + +def _write(w: BundleWriter, section: str, rows: Iterable[dict[str, Any]]) -> None: + with w.section(section) as sink: + for r in rows: + sink.write(r) + + +async def _table(w: BundleWriter, ch: Any, section: str, sql: str, params: dict[str, Any]) -> None: + with w.section(section) as sink: + async for r in stream_rows(ch, sql, params): + sink.write(r) + + +def _pairs(selected: dict[str, list[str]]) -> list[tuple[str, str]]: + return [(org, ns) for org, names in selected.items() for ns in names] + + +async def _identity_sections( + w: BundleWriter, + ch: Any, + orgs: list[str], + selected: dict[str, list[str]], +) -> None: + p: dict[str, Any] = {"orgs": orgs, "pairs": _pairs(selected)} + in_orgs = "org IN {orgs:Array(String)}" + in_ns = "(org, namespace) IN {pairs:Array(Tuple(String, String))}" + await _table( + w, ch, "namespace_types", f"SELECT * FROM loom.namespace_types FINAL WHERE {in_ns}", p + ) + # A policy only restricts: carried as written, it never widens what a caller may do. + await _table( + w, + ch, + "namespace_policies", + f"SELECT * FROM loom.namespace_policies FINAL WHERE {in_ns} AND tombstoned_at IS NULL", + p, + ) + await _table(w, ch, "namespace_guides", f"SELECT * FROM loom.namespace_guides WHERE {in_ns}", p) + await _table( + w, ch, "sso_links", f"SELECT * FROM loom.sso_links FINAL WHERE {in_ns} AND linked = 1", p + ) + # Listed for their owners to set up again: credentials the source issued or encrypted, + # and trust it placed in an outside issuer, never move. + await _table( + w, + ch, + "service_accounts", + "SELECT org, name, sa_subject, kind, created_by, namespaces, roles " + f"FROM loom.service_accounts FINAL WHERE {in_orgs} AND revoked_at IS NULL " + "AND (expires_at IS NULL OR expires_at > now())", + p, + ) + await _table( + w, + ch, + "bots", + "SELECT org, name, issuer, ns_roles, updated_by FROM loom.machine_identities FINAL " + f"WHERE {in_orgs} AND active", + p, + ) + await _table( + w, + ch, + "connected_accounts", + f"SELECT org, subject, kind FROM loom.connected_accounts FINAL WHERE {in_orgs} AND active", + p, + ) + # The namespaces' refusals, the org's, and the deployment-wide ones ('*'), which the + # importer narrows to the namespaces it lands: a source's wider refusal is not the + # target's to impose on namespaces it did not bring. + await _table( + w, + ch, + "blacklist", + f""" + SELECT * FROM loom.blacklist FINAL + WHERE ({in_ns} OR (org IN {{orgs:Array(String)}} AND namespace = '*') OR org = '*') + AND tombstoned_at IS NULL + """, + p, + ) + + +def _revocation_keys( + rows: Iterable[Any], grants: Iterable[Any], users: Iterable[tuple[str, str]] +) -> list[str]: + """The keys the source may have revoked a subject the bundle brings under, lower-cased + as `REVOKED` compares them: each namespace's name (an account's) and owner, each grant's + subject, and each end user's `/user:` (`end_user_revocation_subject`).""" + from server.core.principals import USER, end_user_revocation_subject + + keys = {str(r["namespace"]) for r in rows} | {str(g["subject"]) for g in grants} + keys |= {str(r["owner_email"]) for r in rows if r.get("owner_email")} + keys |= {end_user_revocation_subject(org, f"{USER}{user}") for org, user in users} + return sorted({k.lower() for k in keys}) + + +Counts = dict[str, dict[str, dict[str, int]]] # org → namespace → section → rows + + +def _count(counts: Counts, org: str, ns: str, section: str) -> None: + per = counts.setdefault(org, {}).setdefault(ns, {}) + per[section] = per.get(section, 0) + 1 + + +async def _memories( + w: BundleWriter, ch: Any, selected: dict[str, list[str]], counts: Counts +) -> set[tuple[str, str]]: + """Every live head of each namespace, as the snapshot payload's rows plus their org + and namespace; returns each (org, user id) of an end user they name.""" + from server.core.naming import is_anonymous_user + from server.identity.api.models import _SnapshotMemoryRow + from server.memory.app import snapshot_rows as snap + + keep = _SnapshotMemoryRow.model_fields + users: set[tuple[str, str]] = set() + with w.section("memories") as sink: + for org, names in selected.items(): + for ns in names: + async for r in memory_heads(ch, org, ns): + sink.write({"org": org, "namespace": ns, **snap.snapshot_fields(r, keep)}) + _count(counts, org, ns, "memories") + if not is_anonymous_user(user := str(r.get("user_id") or "")): + users.add((org, user)) + return users + + +async def memory_heads(ch: Any, org: str, ns: str) -> AsyncIterator[dict[str, Any]]: + """A namespace's live heads: from the authority under Postgres (ClickHouse may lag a + committed delete), one streamed read of ClickHouse otherwise.""" + from server.core import pg + from server.memory.app.snapshot_rows import SNAPSHOT_SELECT + from server.memory.store import pg_memory + from server.memory.store.rows import identity_key + + if pg.enabled(): + after = None + while True: + page = await pg_memory.live_heads_in(org, ns, after=after, limit=PG_PAGE) + for r in page: + yield r + if len(page) < PG_PAGE: + return + after = identity_key(page[-1]) + async for r in stream_rows( + ch, + f"SELECT toString(memory_id) AS memory_id, {SNAPSHOT_SELECT} FROM loom.memory FINAL " + "WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL", + {"org": org, "ns": ns}, + ): + yield r + + +async def _source_tags(ch: Any, orgs: list[str]) -> list[str]: + """`//source:` of each knowledge source of `orgs` that writes its + copies again or retires them: one registered, or one removed with its copies to retire + (`_RESYNCED`).""" + rows = await ch.query_all( + "SELECT org, namespace, name FROM loom.knowledge_sources FINAL " + "WHERE org IN {orgs:Array(String)} AND (active OR pending_delete)", + params={"orgs": orgs}, + ) + return [f"{r['org']}/{r['namespace']}/{source_tag(str(r['name']))}" for r in rows] + + +async def _documents( + w: BundleWriter, ch: Any, selected: dict[str, list[str]], counts: Counts, sources: list[str] +) -> None: + """Each namespace's live documents and the originals they serve. An original the + source cannot read back fails the export: a bundle that silently drops it would leave + the target serving 410 for a document the source still serves.""" + from server.knowledge.store import blobs + + originals: list[tuple[str, str, str, str]] = [] + with w.section("documents") as sink: + for org, names in selected.items(): + for ns in names: + # An end user's document stays behind: the writer takes its user from the + # caller's token only, so the target could not erase it as theirs. So does + # a synced copy while a source of its namespace writes it again or retires it + # (`_RESYNCED`). + async for d in stream_rows( + ch, + "SELECT * FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND superseded_at IS NULL AND user_id = '-' " + f"AND NOT ({_RESYNCED})", + {"org": org, "ns": ns, "sync": SYNC_WORKER_ACTOR, "sources": sources}, + ): + if d.get("blob_path") and not d.get("blob_erased_at"): + originals.append((org, ns, str(d["blob_path"]), str(d["source_uri"]))) + sink.write(d) + _count(counts, org, ns, "documents") + # Read after each stream is closed: a slow object read never stalls an open response. + for org, ns, sha, uri in originals: + stored = await blobs.locate(org, ns, sha, ch=ch) + data = await blobs.read(org, ns, sha, stored=stored, ch=ch) if stored else None + if data is None or w.original(data) != sha: + raise SystemExit( + f"{org}/{ns} document {uri!r}: its original {sha} cannot be read back as " + "stored; repair it or erase the document" + ) + + +async def _left_behind( + ch: Any, orgs: list[str], only: dict[str, list[str]] | None, sources: list[str] +) -> dict[str, Any]: + """What the target rebuilds or its owners redo, named in the manifest for the plan: of + the whole orgs, or with `--namespace` of the exported namespaces (org → names) only.""" + keys = [f"{o}/{n}" for o, names in (only or {}).items() for n in names] + p = {"orgs": orgs, "keys": keys, "sync": SYNC_WORKER_ACTOR, "sources": sources} + scope = "org IN {orgs:Array(String)}" + ( + " AND concat(org, '/', namespace) IN {keys:Array(String)}" if only is not None else "" + ) + repos = await ch.query_all( + f"SELECT org, namespace, repo, git_remote FROM loom.code_repos FINAL WHERE {scope} " + "AND active", + params=p, + ) + to_register = await ch.query_all( + "SELECT org, namespace, name, kind FROM loom.knowledge_sources FINAL " + f"WHERE {scope} AND active AND NOT pending_delete", + params=p, + ) + rows = await ch.query_all( + "SELECT 'conversations' AS kind, org, count() AS n FROM loom.conversations " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'session_briefs', org, count() FROM loom.session_briefs FINAL " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'tasks', org, count() FROM loom.tasks FINAL " + f"WHERE {scope} AND is_deleted = 0 GROUP BY org " + "UNION ALL SELECT 'shared', org, count() FROM loom.shared FINAL " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'memory_records', org, count() FROM loom.memory_records FINAL " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'documents_of_end_users', org, count() FROM loom.documents FINAL " + f"WHERE {scope} AND superseded_at IS NULL AND user_id != '-' GROUP BY org " + "UNION ALL SELECT 'documents_of_sources', org, count() FROM loom.documents FINAL " + f"WHERE {scope} AND superseded_at IS NULL AND user_id = '-' AND {_RESYNCED} GROUP BY org", + params=p, + ) + return {"code_repos": repos, "knowledge_sources": to_register, "rows": rows} + + +async def export( + ch: Any, *, orgs: list[str], namespaces: list[str] | None, out: Path +) -> dict[str, Any]: + """Write the bundle; return its manifest.""" + from server.core import pg + + await refuse_unfinished_erasures(ch, orgs) + source = await _deployment_id(ch) + p = {"orgs": orgs} + in_orgs = "WHERE org IN {orgs:Array(String)}" + rows = [r async for r in stream_rows(ch, f"SELECT * FROM loom.namespaces FINAL {in_orgs}", p)] + grants = [ + r + async for r in stream_rows( + ch, + f"SELECT * FROM loom.namespace_grants FINAL {in_orgs} " + "AND revoked_at IS NULL AND status = 'active'", + p, + ) + ] + links = await ch.query_all( + f"SELECT email, org, namespace FROM loom.sso_links FINAL {in_orgs} AND linked = 1", + params=p, + ) + selected = select_namespaces(rows, grants, namespaces, links) + # An account pulled in for the grants it holds brings its row, not its content. + content = { + org: [n for n in names if namespaces is None or n in namespaces] + for org, names in selected.items() + } + found = {n for names in content.values() for n in names} + missing = sorted(set(orgs) - set(content)) + sorted(set(namespaces or ()) - found) + if missing: + raise SystemExit(f"no memory namespace to export: {', '.join(missing)}") + await refuse_unpublished_documents(content) + w = BundleWriter(out) + rows = [r for r in rows if r["namespace"] in selected.get(r["org"], ())] + grants = [g for g in grants if g["namespace"] in content.get(g["org"], ())] + _write(w, "namespaces", rows) + _write(w, "grants", grants) + await _identity_sections(w, ch, orgs, selected) + counts: Counts = {} + sources = await _source_tags(ch, orgs) + users = await _memories(w, ch, content, counts) + await _documents(w, ch, content, counts, sources) + # No grant of a subject the source revoked lands, and an account it revoked lands with + # no password (`instance_import._grants`, `_land`). + keys = _revocation_keys(rows, grants, users) + await _table(w, ch, "revoked", REVOKED, {"lowered": keys}) + return w.finish( + { + "source": { + "deployment_id": source, + "authority": "postgres" if pg.enabled() else "clickhouse", + }, + "exported_at": datetime.now(UTC).isoformat(), + "orgs": orgs, + "namespaces": selected, + "content": content, # the namespaces whose content moves; the rest are rows only + "counts": counts, + "left_behind": await _left_behind( + ch, orgs, None if namespaces is None else content, sources + ), + } + ) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py new file mode 100644 index 0000000000..5ae958a26c --- /dev/null +++ b/server/cli/instance_import.py @@ -0,0 +1,1217 @@ +"""`loom instance import`: a consolidation bundle into this deployment, by a reviewed plan. + +The plan (`instance_plan`) is computed against the target as it is now and refused while it +has problems; `--apply` takes the digest the dry run printed and refuses a plan that has +changed since, or a different bundle. Each namespace the plan lands is one landing: an +`instance.import` audit row (`instance.import.merge` for a merge) naming its source before +its first row, and an `instance.import.done` row once its grants, memories and documents +are written. A rerun skips a finished landing whole, so nothing the target's owners +changed since comes back; an unfinished one resumes, writing nothing the target holds in +any state. + +A created namespace receives its memories as a restore does (every column, +`source_class=imported`, the importing command as `actor`); a merged one through +`memory.bulk_set`, with its admission. Either receives only keys the target namespace +never held. Documents go through `knowledge.upsert` with their originals, so the +target's embedder embeds them; `memory.bulk_set` embeds a merged namespace's memories as +it writes them, and the embedding worker's next full pass a created one's. Every model +call is made for the target org. +""" + +from __future__ import annotations + +import base64 +import contextlib +import json +import time +import uuid +from collections import Counter +from collections.abc import Iterable, Mapping +from datetime import datetime, timedelta +from itertools import batched +from typing import Any + +from server.cli.instance_bundle import Bundle, BundleError +from server.cli.instance_export import PG_PAGE, REVOKED, stream_rows +from server.cli.instance_plan import ( + MapFile, + NsDecision, + Plan, + TargetOrg, + is_account, + landed_row, + plan, + revoked_subject, +) +from server.core.datetimes import ( + as_aware_utc, + naive_utc_now_seconds, + to_naive_utc, + to_naive_utc_second, + utc_now, +) +from server.core.naming import is_anonymous_user +from server.core.principals import USER +from server.memory.domain.memory_types import is_namespace_definition +from server.memory.store.rows import KeyInNamespace, key_in_namespace + +LANDED = "instance.import" +MERGED = "instance.import.merge" # a merge lands in the target's own namespace +DONE = "instance.import.done" +_BATCH = 500 # not a setting: rows per write call; each writer bounds its statements +# Bundle keys per held-key read, well inside a request's size. Ceiling: a read filters on +# org and namespace, the head of loom.memory's sort key, and on the memory_key ngram +# index, which cannot rule out a granule for a key under three characters: a chunk +# holding one reads the whole namespace, so those keys share the first chunks. A +# projection sorted by key first is the next step if merges into very large namespaces +# get slow. +_KEYS_PER_READ = 1000 +_Ref = tuple[str, str, str] # a source head: (source org, source namespace, memory id) +# Settings that name the source's own services or rows: cleared, the target's owners set +# them again. +_CLEARED: dict[str, Any] = { + "rerank_endpoint": "", + "classify_endpoint": "", + "released_aliases": [], + "budget_alert_inbox": "", +} + + +def source_key(bundle: Bundle, org: str, name: str) -> str: + return f"{bundle.manifest['source']['deployment_id']}/{org}/{name}" + + +def carried(bundle: Bundle) -> set[tuple[str, str]]: + """The (org, namespace) pairs whose content the bundle holds. An account a + `--namespace` export brought for its grants or ownership is a row only: its landing + stays unfinished, so a later bundle that selects it brings its content.""" + return {(o, n) for o, names in bundle.manifest["content"].items() for n in names} + + +async def load_target( + ch: Any, target_orgs: Iterable[str] +) -> tuple[dict[str, TargetOrg], dict[str, list[str]]]: + """Each target org's state the plan reads, and every account on the deployment by + lower-cased email (contact or linked single sign-on).""" + orgs = sorted(set(target_orgs)) + p = {"orgs": orgs, "events": [LANDED, MERGED, DONE]} + rows = await ch.query_all( + "SELECT org, namespace, kind, active, owner_email, password_hash != '' AS password_hash, " + "released_aliases, created_at FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", + params=p, + ) + grants = await ch.query_all( + "SELECT DISTINCT org, subject FROM loom.namespace_grants FINAL " + "WHERE org IN {orgs:Array(String)} AND revoked_at IS NULL AND status = 'active'", + params=p, + ) + landings = await ch.query_all( + "SELECT DISTINCT event_type, org, JSONExtractString(subject, 'name') AS name, " + "JSONExtractString(subject, 'source') AS source, " + "JSONExtractString(subject, 'created_at') AS created_at FROM loom.audit_log " + "WHERE org IN {orgs:Array(String)} AND event_type IN {events:Array(String)}", + params=p, + ) + lowered = sorted({str(r["name"]).lower() for r in landings}) + gone = frozenset( + str(r["subject"]) for r in await ch.query_all(REVOKED, params={"lowered": lowered}) + ) + out: dict[str, TargetOrg] = {} + for org in orgs: + mine = [r for r in rows if r["org"] == org] + names: dict[str, Mapping[str, Any]] = {str(r["namespace"]): r for r in mine} + for r in mine: # a released alias still redirects to its account + for alias in r.get("released_aliases") or []: + names.setdefault(str(alias), {"kind": "alias", "active": False}) + + def pairs(event: str, org: str = org) -> frozenset[tuple[str, str]]: + return frozenset( + (str(r["name"]), str(r["source"])) + for r in landings + if r["org"] == org and r["event_type"] == event + ) + + out[org] = TargetOrg( + namespaces=names, + subjects=frozenset( + {str(r["namespace"]) for r in mine if is_account(r)} + | {str(g["subject"]) for g in grants if g["org"] == org} + | {str(r["owner_email"]) for r in mine if r.get("owner_email")} + ), + landed={ + (str(r["name"]), str(r["source"])): str(r["created_at"]) + for r in landings + if r["org"] == org and r["event_type"] == LANDED + }, + merged=pairs(MERGED), + done=pairs(DONE), + revoked=gone, + ) + signs_in: dict[str, list[str]] = {} + async for r in stream_rows( + ch, + "SELECT lower(contact_email) AS email, org, namespace FROM loom.namespaces FINAL " + "WHERE contact_email != '' AND owner_email = namespace AND active " + "UNION ALL SELECT lower(email), org, namespace FROM loom.sso_links FINAL WHERE linked = 1", + {}, + ): + signs_in.setdefault(str(r["email"]), []).append(f"{r['org']}/{r['namespace']}") + return out, signs_in + + +def build_plan( + bundle: Bundle, + rules: MapFile, + targets: Mapping[str, TargetOrg], + signs_in: Mapping[str, list[str]], +) -> Plan: + rows = list(bundle.records("namespaces")) + named: dict[str, dict[str, dict[str, set[str]]]] = {} + + def add(row: Any, kind: str, subject: Any) -> None: + by_ns = named.setdefault(str(row["org"]), {}).setdefault(str(row["namespace"]), {}) + by_ns.setdefault(kind, set()).add(str(subject)) + + for g in bundle.records("grants"): + add(g, "grant", g["subject"]) + for r in rows: + if not is_account(r) and r.get("owner_email"): + add(r, "owner", r["owner_email"]) + for m in bundle.records("memories"): # an end user's rows follow their decision + if not is_anonymous_user(str(m.get("user_id") or "")): + add(m, "user", f"{USER}{m['user_id']}") + links: dict[str, dict[str, list[str]]] = {} + for link in bundle.records("sso_links"): + links.setdefault(str(link["org"]), {}).setdefault(str(link["namespace"]), []).append( + str(link["email"]) + ) + return plan( + bundle=bundle.digest, + source=bundle.manifest["source"]["deployment_id"], + rules=rules, + namespace_rows=rows, + selected=bundle.manifest["namespaces"], + named=named, + links=links, + revoked=_revoked(bundle), + targets=targets, + signs_in=signs_in, + ) + + +def _revoked(bundle: Bundle) -> set[str]: + return {str(r["subject"]).lower() for r in bundle.records("revoked")} + + +async def _claim_problems( + ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOrg] +) -> None: + """`check`'s account handles: one that holds access on the target, or that the target + revoked outright, is a problem with a `-legacy` handle proposed.""" + from fastapi import HTTPException + + from server.auth.self_signup import refuse_empowered + + # A name the target holds is this import's own row (else the plan refused it). + claims = [ + d + for d in p.namespaces + if d.account + and d.target not in targets[d.target_org].namespaces + and (d.target, source_key(bundle, d.source_org, d.source)) not in targets[d.target_org].done + ] + # One the source revoked lands with no way to sign in, whatever the target revoked. + revoked = _revoked(bundle) + lowered = sorted({d.target.lower() for d in claims if d.source.lower() not in revoked}) + gone = ( + {str(r["subject"]) for r in await ch.query_all(REVOKED, params={"lowered": lowered})} + if lowered + else set() + ) + for d in claims: + if d.source.lower() not in revoked and d.target.lower() in gone: + why = "is revoked on the target, in every org: no token for it would sign in" + else: + try: + await refuse_empowered(ch, d.target_org, d.target.lower()) + continue + except HTTPException: + why = ( + "already holds access on the target (a grant, a namespace, a token, a task " + "or a setting names it)" + ) + p.problems.append(f"{d.source_org}: account {d.source!r}: {d.target!r} {why}") + p.proposals.setdefault("subjects", {})[f"{d.source_org}/{d.source}"] = { + "claim": f"{d.target}-legacy" + } + + +async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOrg]) -> None: + """What the plan cannot see without reading the target: an account handle that + already holds access there (a setting such as `LOOM_PLATFORM_ADMINS` names it, or it + holds a grant, a namespace, a token or a task, as self-signup refuses it) or that the + target revoked outright, so no token for it would sign in (`_claim_problems`), a + refusal this deployment cannot compile, a created namespace whose refusals would pass + the regex budget, a memory the target cannot store or a merge would lose the expiry + action of (`_landing_problem`), an original missing from the bundle. Each is added as + a problem.""" + from pydantic import ValidationError as ModelError + + from server.core.errors import ValidationError + from server.memory.app.blacklist_guard import ( + REGEX_PROGRAM_PER_SCOPE, + compile_regex, + scope_program, + ) + + await _claim_problems(ch, bundle, p, targets) + regexes = [b for b in bundle.records("blacklist") if b["pattern_type"] == "regex"] + todo: dict[tuple[str, str], NsDecision] = {} + for d in p.namespaces: + key = source_key(bundle, d.source_org, d.source) + if d.action == "skip" or (d.target, key) in targets[d.target_org].done: + continue + todo[(d.source_org, d.source)] = d + reach = [b for b in regexes if _reaches(b, d)] + # A merge stores none; a created namespace holds those an earlier run stored. + stored = await _stored(ch, [_pattern_id(b, d) for b in reach if d.action == "create"]) + size = 0 + for b in reach: + try: + program = compile_regex(b["pattern"]).programsize + except ValidationError as e: + p.problems.append( + f"{d.source_org}/{d.source}: the source's refusal {b['pattern']!r} does not " + f"compile on the target ({e}): remove it on the source and export again" + ) + continue + if d.action == "create" and _pattern_id(b, d) not in stored: + size += program + if size and size + await scope_program("namespace", d.target_org, d.target) > ( + REGEX_PROGRAM_PER_SCOPE + ): + p.problems.append( + f"{d.source_org}/{d.source}: the source's regex refusals that reach it would " + f"pass {REGEX_PROGRAM_PER_SCOPE} RE2 instructions on {d.target_org}/{d.target}: " + "remove some on the source and export again" + ) + # The apply stops at a row the target refuses, at every run: named here instead. + run = _Run(ch, bundle, p, targets) + for m in bundle.records("memories"): + if (into := todo.get((m["org"], m["namespace"]))) is None: + continue + try: + row = _row(run, into, m) + if row is not None and (why := await _landing_problem(into, row, run.now)): + p.problems.append( + f"{into.source_org}/{into.source} memory {m['memory_key']!r}: {why}" + ) + except (ModelError, ValidationError) as e: + err = e.errors()[0] if isinstance(e, ModelError) else None + why = f"{'.'.join(map(str, err['loc']))}: {err['msg']}" if err else str(e) + p.problems.append( + f"{into.source_org}/{into.source} memory {m.get('memory_key')!r}: the target " + f"refuses it ({why}): change it on the source and export again" + ) + for doc in bundle.records("documents"): + sha = doc.get("blob_path") + if (doc["org"], doc["namespace"]) in todo and sha and not doc.get("blob_erased_at"): + try: + bundle.original(str(sha)) + except BundleError as e: + p.problems.append( + f"{doc['org']}/{doc['namespace']} document {doc['source_uri']!r}: {e}: " + "copy the whole bundle" + ) + + +async def _landing_problem(d: NsDecision, row: Any, now: datetime) -> str | None: + """Build source row `row` as the apply writes it into `d`'s namespace, raising where the + target refuses it; returns what a merge would lose of it, else None.""" + from server.core.errors import ValidationError + from server.memory.api.models_bulk import _BulkSetEntry + from server.memory.app import snapshot_rows as snap + from server.memory.app.expiry import DEFAULT_ACTION, effective_action + from server.memory.app.sensitivity_level import decoded_text, resolve_level + from server.memory.domain.sensitive_retention import sensitive_retention + from server.settings import settings + + if d.action == "merge": + if not _live(row, now): + return None # left out + _BulkSetEntry.model_validate(entry := _bulk_entry(row)) + # memory.bulk_set takes no expiry action. It gives the row the target's action + # for the sensitivity level it grades the row at: a source action other than + # deletion would be lost. + if row.expires_at is not None and (mine := effective_action(row)) != DEFAULT_ACTION: + text = await decoded_text(json.dumps(entry["value"])) + _, theirs, _ = sensitive_retention( + sensitivity=await resolve_level(row.sensitivity, text), + expires_at=row.expires_at, + on_expire="", + now=now, + settings=settings, + ) + if (theirs or DEFAULT_ACTION) != mine: + return ( + f"a merge expires it by {theirs or DEFAULT_ACTION!r}, not its own {mine!r} " + "(memory.bulk_set takes no expiry action): land the namespace as a " + "created one, which keeps it" + ) + # As memory.bulk_set measures it, which refuses the whole call. + if ( + entry["char_limit"] is not None + and len(json.dumps(entry["value"])) > entry["char_limit"] + ): + raise ValidationError(f"its value is longer than its char_limit {entry['char_limit']}") + # Checked as a restore row: the columns a merge writes are among its columns. + snap.checked_rows( + snap.restore_rows( + [row], + org=d.target_org, + target_namespace=d.target, + rebind_agent=None, + version_base=1, + actor="", + ) + ) + return None + + +def _reaches(b: Mapping[str, Any], d: NsDecision) -> bool: + """Whether a source refusal applies to the source namespace of `d`.""" + return b["org"] == "*" or (b["org"] == d.source_org and b["namespace"] in ("*", d.source)) + + +def _pattern_id(b: Mapping[str, Any], d: NsDecision) -> str: + """A source refusal's id on the namespace `d` creates: one per pattern and landing, so + a pattern the target's owners removed is not added back.""" + return str(uuid.uuid5(uuid.UUID(str(b["pattern_id"])), f"{d.target_org}/{d.target}")) + + +async def _stored(ch: Any, ids: list[str]) -> set[str]: + """Those of `ids` the target's blacklist holds, removed ones included.""" + if not ids: + return set() + rows = await ch.query_all( + "SELECT DISTINCT toString(pattern_id) AS id FROM loom.blacklist " + "WHERE pattern_id IN {ids:Array(UUID)}", + params={"ids": ids}, + ) + return {str(r["id"]) for r in rows} + + +def refusals(patterns: Iterable[Mapping[str, Any]], d: NsDecision) -> list[Any]: + """The source refusals that reach a merged namespace, for the guard's `match_value`: a + merge applies them to the rows it brings and stores none, since the target namespace + is not the source's to refuse for.""" + from server.memory.app.blacklist_guard import BlacklistPattern, compile_regex + + return [ + BlacklistPattern( + pattern_id=str(b["pattern_id"]), + org=str(b["org"]), + namespace=str(b["namespace"]), + pattern=str(b["pattern"]), + pattern_type=str(b["pattern_type"]), + scope=str(b.get("scope") or ""), + reason=str(b.get("reason") or ""), + compiled=compile_regex(b["pattern"]) if b["pattern_type"] == "regex" else None, + ) + for b in patterns + if _reaches(b, d) + ] + + +async def _typed(ch: Any, table: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Bundle rows (JSON values) as the typed insert takes them: the columns this + deployment's table has, each DateTime read back from its ISO text.""" + from server.core import ch_names + + cols = await ch.query_all( + "SELECT name, type FROM system.columns WHERE database = {db:String} " + "AND table = {t:String} AND default_kind NOT IN ('MATERIALIZED', 'ALIAS')", + params={"db": ch_names.database(), "t": table}, + ) + types = {str(r["name"]): str(r["type"]) for r in cols} + out = [] + for r in rows: + row = {} + for c, t in types.items(): + if c in r: + v = r[c] + row[c] = datetime.fromisoformat(v) if "DateTime" in t and isinstance(v, str) else v + out.append(row) + return out + + +class _Run: + """One apply: the plan, the bundle and what was written, for the receipt.""" + + def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOrg]) -> None: + from server.core.datetimes import naive_utc_now_seconds + from server.memory.app.provenance import writer_actor + + self.ch = ch + self.bundle = bundle + self.plan = p + self.targets = targets + self.actor = writer_actor() + self.subjects = p.subject_map() + self.version = time.time_ns() + self.now = naive_utc_now_seconds() + self.revoked = _revoked(bundle) + self.digests = {"bundle": bundle.digest, "plan": p.digest} + self.counts: dict[str, dict[str, int]] = {} + self.by_source: dict[tuple[str, str], NsDecision] = {} # the landings this run writes + # Per merge: the source refusals. Per target namespace: its rows of the bundle's + # keys, each with whether it is a namespace definition, and under newest_wins each + # (user, key) a same-key write retires a row of, None for any user. + self.refusals: dict[tuple[str, str], list[Any]] = {} + self.held: dict[tuple[str, str], dict[KeyInNamespace, bool]] = {} + self.reach: dict[tuple[str, str], set[tuple[str | None, str]]] = {} + + def next_version(self) -> int: + self.version += 1 + return self.version + + def key(self, org: str, name: str) -> str: + return source_key(self.bundle, org, name) + + def count(self, d: NsDecision, what: str, n: int = 1) -> None: + per = self.counts.setdefault(f"{d.target_org}/{d.target}", {}) + per[what] = per.get(what, 0) + n + + def subject(self, org: str, s: str) -> str | None: + """The target subject of source subject `s`; None when dropped or never planned.""" + return self.subjects.get((org, s)) + + def user_id(self, org: str, u: str) -> str | None: + """A row's user as the plan decided `user:`; None when dropped.""" + if u in ("", "-"): + return u + t = self.subject(org, f"{USER}{u}") + return None if t is None else t.removeprefix(USER) + + async def audit( + self, event: str, org: str, namespace: str, name: str, source: str, created_at: str = "" + ) -> None: + from server.observability import audit + + subject = {"name": name, "source": source, **self.digests} + if created_at: + subject["created_at"] = created_at + await audit.emit_strict( + event_type=event, org=org, namespace=namespace, actor=self.actor, subject=subject + ) + + +def _identity() -> Any: + from server.auth.authz import identity_write + + return identity_write() + + +def _for(d: NsDecision) -> Any: + """Model calls (embedding, extraction) made for the target namespace's org.""" + from server.llm import customer + + return customer.for_org(d.target_org, namespace=d.target) + + +async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: + """Record the landing, then, for a created namespace, write its row unless an earlier + run did. Its settings are the source's, less the ones naming the source's services; an + account keeps its password hash (claimable) unless the source revoked it.""" + from fastapi import HTTPException + + from server.auth.directory import directory + from server.auth.grant_claims import account_change + from server.auth.jit import JIT_TAG + from server.auth.self_signup import refuse_empowered + from server.core import grant_cache + from server.identity.store import namespaces as namespaces_repo + + key = run.key(d.source_org, d.source) + target = run.targets[d.target_org] + if d.action == "merge": + if (d.target, key) not in target.merged: + await run.audit(MERGED, d.target_org, d.target, d.target, key) + return + recorded = target.landed.get((d.target, key)) + in_use = SystemExit(f"{d.target_org}/{d.target} is in use on the target: plan again") + async with account_change(d.target_org, d.target): + existing = await namespaces_repo.fetch_row(d.target_org, d.target, ch=run.ch) + if existing is not None: + # An earlier run's row, or a name someone took since its audit row: the plan's test. + if not landed_row(existing, recorded): + raise in_use + if change := _replanned(run, d, existing, row): + # ReplacingMergeTree(updated_at): later than the row it replaces, whatever + # this host's clock says or who wrote that row since the run began. + after = to_naive_utc_second(existing["updated_at"]) + timedelta(seconds=1) + at = max(naive_utc_now_seconds(), after) + with _identity(): + await run.ch.insert( + "loom.namespaces", [{**existing, **change, "updated_at": at}] + ) + await grant_cache.changed(d.target_org) + return + if await directory().in_use(d.target_org, d.target, ch=run.ch): + raise in_use + if d.account: + try: + await refuse_empowered(run.ch, d.target_org, d.target.lower()) + except HTTPException: + raise SystemExit( + f"{d.target_org}/{d.target} holds access on the target: plan again" + ) from None + if recorded is None: + # The row's created_at tells a later plan this landing's row from one a name + # registered since has, whichever bundle it reads. + recorded = str(row["created_at"]) + await run.audit(LANDED, d.target_org, d.target, d.target, key, created_at=recorded) + owner = d.target if d.account else (run.subject(d.source_org, row["owner_email"]) or "") + new = {**row, **_CLEARED, "org": d.target_org, "namespace": d.target} + new.update(owner_email=owner or run.actor, updated_at=run.now, created_at=recorded) + # Single sign-on here never finishes the source's provisioning of it: that would + # give back an owner grant the source revoked, since revoked grants do not move. + new["tags"] = [t for t in new.get("tags") or [] if t != JIT_TAG] + if d.approval: + new["join_policy"] = "approval" + if not d.account: + # Only an account's email names its owner; a hash on anything else signs nobody in. + new.update(password_hash="", contact_email="") + elif d.source.lower() in run.revoked: + # Revoked on the source: no password, email or link signs anyone in to it. + new.update(password_hash="", contact_email="") + with _identity(): + await run.ch.insert("loom.namespaces", await _typed(run.ch, "namespaces", [new])) + await grant_cache.changed(d.target_org) + run.count(d, "namespace") + + +def _replanned( + run: _Run, d: NsDecision, existing: Mapping[str, Any], row: Mapping[str, Any] +) -> dict[str, Any]: + """What the row an earlier run of an unfinished landing wrote takes from the plan + since: self-join by approval where it is open and the target org now serves others, + and the owner the map now names in place of the import's. Nothing else: the target's + admins may have changed the row since, and no decision opens it.""" + from server.identity.domain.join_policy import OPEN, effective_join_policy + + change: dict[str, Any] = {} + if d.approval and effective_join_policy(dict(existing)) == OPEN: + change["join_policy"] = "approval" + if ( + not d.account + and existing.get("owner_email") == run.actor + and (owner := run.subject(d.source_org, row["owner_email"])) + ): + change["owner_email"] = owner + return change + + +# A created namespace's own rows, each table with the key the target is checked by and +# the column naming who wrote a row, mapped as the plan maps its subject (`_actor`). +_CARRIED = { + "namespace_types": ("memory_type", None), + "namespace_policies": ("policy_id", "created_by"), + "namespace_guides": ("revision", "updated_by"), +} + + +async def _carry(run: _Run, d: NsDecision) -> None: + """A created namespace's per-type settings, policies and guide revisions: a merged one + keeps the target's. A row the target holds under the same key, in any state, is left + as it is, so a resumed run never writes back what the target's owners changed.""" + for table, (key, by) in _CARRIED.items(): + have = await run.ch.query_all( + f"SELECT DISTINCT toString({key}) AS k FROM loom.{table} " + "WHERE org = {org:String} AND namespace = {ns:String}", + params={"org": d.target_org, "ns": d.target}, + ) + held = {str(r["k"]) for r in have} + rows = [ + {**t, "org": d.target_org, "namespace": d.target} + for t in run.bundle.records(table) + if (t["org"], t["namespace"]) == (d.source_org, d.source) and str(t[key]) not in held + ] + if by: + for r in rows: + r[by] = _actor(run, d.source_org, r[by]) + if rows: + await run.ch.insert( + f"loom.{table}", + await _typed(run.ch, table, rows), + settings={"async_insert": 0, "wait_for_async_insert": 1}, + ) + run.count(d, table, len(rows)) + + +async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) -> None: + """The source's refusals that reach a created namespace's source (its own, its org's + and the deployment-wide ones), each narrowed to the namespace it lands on: the + target's other namespaces are not the source's to refuse for.""" + from server.memory.api.models_blacklist import BlacklistAddInput + from server.memory.app import blacklist + + reach = [b for b in patterns if _reaches(b, d)] + present = await _stored(run.ch, [_pattern_id(b, d) for b in reach]) + for b in reach: + pid = _pattern_id(b, d) + if pid in present: + continue + await blacklist.add( + BlacklistAddInput.model_validate( + { + "org": d.target_org, + "namespace": d.target, + "pattern": b["pattern"], + "pattern_type": b["pattern_type"], + "scope": "namespace", + "reason": b.get("reason") or "", + "created_by": run.actor, + } + ), + pid, + ) + run.count(d, "refusals") + + +async def _grants(run: _Run) -> None: + """Each live source grant under its mapped subject, by the import: on a created + namespace, and on a merged one when the map carries its grants. Never written: a + dropped subject's, a subject's the source revoked, one the person already holds at + that role or higher, one a target admin revoked from them. The person is matched as the + gate matches them, case folded: a grant under a verified spelling admits, and a + revocation under any spelling the directory ties to the subject reaches them; a + pending request is no grant, so the source's replaces it. A grant is written under + the subject `grants.create` would write it under (a verified email's handle).""" + from server.auth.aliases import canonical_subject, spellings, verified_spellings + from server.core.grant_sql import LIVE_GRANT + from server.identity.store import grants as grants_repo + from server.operations.base import grant_rank + + held = await run.ch.query_all( + "SELECT org, namespace, lower(subject) AS folded, role, revoked_at IS NOT NULL AS " + f"revoked, ({LIVE_GRANT}) AS live FROM loom.namespace_grants FINAL " + "WHERE org IN {orgs:Array(String)}", + params={"orgs": sorted({d.target_org for d in run.by_source.values()})}, + ) + have: dict[tuple[str, str, str], str] = {} # "" when revoked, else the highest live role + for r in held: + k = (str(r["org"]), str(r["namespace"]), str(r["folded"])) + if r["revoked"] or have.get(k) == "": + have[k] = "" + elif r["live"] and (k not in have or grant_rank(str(r["role"])) > grant_rank(have[k])): + have[k] = str(r["role"]) + spelled: dict[tuple[str, str], tuple[str, set[str], set[str]]] = {} + rows = [] + for g in run.bundle.records("grants"): + d = run.by_source.get((g["org"], g["namespace"])) + subject = run.subject(g["org"], g["subject"]) + if d is None or subject is None or (d.action == "merge" and not d.grants): + continue + if revoked_subject(run.revoked, g["org"], g["subject"]): + run.count(d, "grants_of_revoked") + continue + if (d.target_org, subject) not in spelled: + stored = await canonical_subject(d.target_org, subject) + verified = await verified_spellings(d.target_org, subject) + every = await spellings(d.target_org, subject) + spelled[(d.target_org, subject)] = ( + stored, + {n.lower() for n in (stored, *verified)}, + {n.lower() for n in (stored, *every)}, + ) + stored, admits, reaches = spelled[(d.target_org, subject)] + if any(have.get((d.target_org, d.target, n)) == "" for n in reaches): + run.count(d, "grants_revoked_on_target") + continue + held_roles = [have.get((d.target_org, d.target, n)) for n in admits] + if any(r and grant_rank(r) >= grant_rank(g["role"]) for r in held_roles): + continue + have[(d.target_org, d.target, stored.lower())] = str(g["role"]) + rows.append( + { + "org": d.target_org, + "namespace": d.target, + "subject": stored, + "role": g["role"], + "granted_at": run.now, + "granted_by": run.actor, + "revoked_at": None, + "version": run.next_version(), + "status": "active", + } + ) + run.count(d, "grants") + with _identity(): + await grants_repo.insert_rows(rows, ch=run.ch) + + +async def _links(run: _Run) -> None: + """Under `sso_same_issuer`, each landed account's single sign-on links, but a revoked + account's; a link the target holds in any state is the target's.""" + held_links = await run.ch.query_all( + "SELECT DISTINCT email, org, namespace FROM loom.sso_links " + "WHERE org IN {orgs:Array(String)}", + params={"orgs": sorted({d.target_org for d in run.by_source.values()})}, + ) + linked = {(r["email"], r["org"], r["namespace"]) for r in held_links} + links = [] + for link in run.bundle.records("sso_links"): + d = run.by_source.get((link["org"], link["namespace"])) + if ( + d is None + or not d.account + or d.source.lower() in run.revoked + # One the target holds in any state, unlinked included, is the target's. + or (link["email"], d.target_org, d.target) in linked + ): + continue + links.append( + { + **link, + "org": d.target_org, + "namespace": d.target, + "linked_by": run.actor, + "version": run.next_version(), + } + ) + run.count(d, "sso_links") + if links: + with _identity(): + await run.ch.insert("loom.sso_links", await _typed(run.ch, "sso_links", links)) + + +async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[str]: + """Which of `uris` the namespace holds or has held, deleted ones too, under the + Postgres authority its heads as well: one committed since its last publication to + ClickHouse is there only.""" + from server.core import pg + from server.knowledge.store import pg_documents + + held = { + str(r["v"]) + async for r in stream_rows( + ch, + "SELECT DISTINCT source_uri AS v FROM loom.documents WHERE org = {org:String} " + "AND namespace = {ns:String} AND source_uri IN {uris:Array(String)}", + {"org": org, "ns": namespace, "uris": uris}, + ) + } + if pg.enabled(): + held |= await pg_documents.held_uris(org, namespace, uris) + return held + + +async def _memories(run: _Run) -> None: + """Each source head the run keeps (`_kept`). A created namespace takes them as a + restore does: of two heads of one key, the first lands. A merged one writes, of the + rows a write of one would retire, the newest by `valid_at` (its `created_at` where it + has none), then the first in the bundle, and counts the others as + `memories_superseded`: the rows of one key under one agent, user and session, and + under `newest_wins`, where a same-key write reaches past its own agent and session, + one user's rows of a key, and the rows of a key with no user. There a write with no + user also retires the named rows of its key written before it, and a named write + retires none with no user, so the rows with no user are written first and both land, + as the source served them. The rows of one identity compete first: a namespace + definition that wins, which no other write of its key retires, is written before them.""" + await _load_held(run) + batch: dict[tuple[str, str], list[Any]] = {} + exact: dict[tuple[Any, ...], tuple[tuple[datetime, int], _Ref, bool]] = {} + scoped: dict[tuple[Any, ...], tuple[tuple[datetime, int], _Ref]] = {} + merged: Counter[tuple[str, str]] = Counter() # merged rows kept, per source namespace + for i, m in enumerate(run.bundle.records("memories")): + if (got := await _kept(run, m)) is None: + continue + d, row = got + k, t = (d.source_org, d.source), (d.target_org, d.target) + if d.action == "create": + run.held[t][key_in_namespace(m)] = is_namespace_definition(row) + await _batched(run, batch, d, row) + continue + merged[k] += 1 + rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) + ref = (*k, str(m["memory_id"])) + identity = (t, key_in_namespace(row)) + if identity not in exact or rank > exact[identity][0]: + exact[identity] = (rank, ref, is_namespace_definition(row)) + alone: set[_Ref] = set() # the definitions under newest_wins, every winner elsewhere + for (target, (_, user, _, key)), (best, winner, definition) in exact.items(): + if target not in run.reach or definition: + alone.add(winner) + continue + group = (target, None if is_anonymous_user(user) else user, key) + if group not in scoped or best > scoped[group][0]: + scoped[group] = (best, winner) + first = {ref for (_, user, _), (_, ref) in scoped.items() if user is None} + then = {ref for (_, user, _), (_, ref) in scoped.items() if user is not None} + won = Counter(ref[:2] for ref in alone | first | then) + for k, n in merged.items(): + if n > won[k]: + run.count(run.by_source[k], "memories_superseded", n - won[k]) + for wave in (alone, first, then): # a read each: a merge's rows are known once all is read + if wave: + for m in run.bundle.records("memories"): + if (m["org"], m["namespace"], str(m["memory_id"])) in wave: + d = run.by_source[(m["org"], m["namespace"])] + await _batched(run, batch, d, _row(run, d, m)) + for k, rows in batch.items(): + if rows: + await _write_memories(run, run.by_source[k], rows) + rows.clear() + + +def _row(run: _Run, d: NsDecision, m: dict[str, Any]) -> Any: + """Source head `m` under its target user, parsed; None when the plan dropped its user. + Its verifier and locker name a subject as the plan maps it: one it drops or never + planned names no one, so no source subject's act lands as a target subject's.""" + from server.identity.api.models import _SnapshotMemoryRow + + user = run.user_id(d.source_org, str(m.get("user_id") or "-")) + if user is None: + return None + m["user_id"] = user + for col in ("verified_by", "locked_by"): + m[col] = _actor(run, d.source_org, m.get(col)) + return _SnapshotMemoryRow.model_validate( + {k: v for k, v in m.items() if k not in ("org", "namespace")} + ) + + +def _actor(run: _Run, org: str, value: Any) -> str: + """A source actor (`human:`, `process:`) under the subject the plan + maps, else no one (""): no source subject's act lands as a target subject's.""" + from server.memory.domain.trust import HUMAN_PREFIX, PROCESS_PREFIX + + kind, sep, who = (actor := str(value or "")).partition(":") + if not (sep and f"{kind}:" in (HUMAN_PREFIX, PROCESS_PREFIX)): + return actor + to = run.subject(org, who) + return f"{kind}:{to}" if to else "" + + +async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: + """The landing and row of source head `m`; None, counted, when the run leaves it out: + a dropped user's, one a merge does not carry (`_live`), one whose key the target + namespace holds or has held, one a refusal refuses. So a resumed run writes nothing + back over what someone wrote there since, nor a merge over the target's own: under + `newest_wins` a merged key counts as held as far as a same-key write reaches, for the + same user in any agent and session, and, for a row with no user, for anyone; a + namespace definition, which no other write of its key retires, only for itself.""" + from server.memory.app import blacklist_guard + + if (d := run.by_source.get((m["org"], m["namespace"]))) is None: + return None + if (row := _row(run, d, m)) is None: + run.count(d, "memories_of_dropped_users") + return None + if d.action == "merge" and not _live(row, run.now): + run.count(d, "memories_not_live") + return None + t = (d.target_org, d.target) + if _holds(run.held[t], run.reach.get(t, set()) if d.action == "merge" else set(), row): + run.count(d, "memories_the_target_holds") + return None + if await blacklist_guard.find_match( + org=d.target_org, namespace=d.target, value=row.value + ) or blacklist_guard.match_value(run.refusals.get((d.source_org, d.source), []), row.value): + run.count(d, "memories_refused") + return None + return d, row + + +async def _load_held(run: _Run) -> None: + """Per target namespace, its rows of the bundle's keys (`_held_keys`) and, under + `newest_wins`, how far they reach (`_reach`), read in chunks of the bundle's own keys: + what the run holds grows with the target's rows of those keys, not with the rest of + the namespace.""" + from server.memory.app.conflicts import namespace_conflict_policy + + keys: dict[tuple[str, str], set[str]] = {} + for m in run.bundle.records("memories"): + if (d := run.by_source.get((m["org"], m["namespace"]))) is not None: + keys.setdefault((d.target_org, d.target), set()).add(str(m["memory_key"])) + for t, of_t in keys.items(): + run.held[t] = {} + for chunk in batched(sorted(of_t, key=lambda k: (len(k) >= 3, k)), _KEYS_PER_READ): + run.held[t].update(await _held_keys(run.ch, *t, keys=list(chunk))) + if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": + run.reach[t] = _reach(run.held[t]) + + +def _reach(held: Mapping[KeyInNamespace, bool]) -> set[tuple[str | None, str]]: + """How far a namespace's keys reach under `newest_wins`: a named write of a key + retires that user's rows of it, a write with no user every row of it. A namespace + definition (`held` maps each key to whether it is one) reaches no row: a same-key + write never retires one (`same_key_victims`).""" + return { + r + for (_, u, _, k), definition in held.items() + if not definition + for r in ((u, k), (None, k)) + } + + +def _holds(held: Mapping[Any, bool], reach: set[tuple[str | None, str]], row: Any) -> bool: + """Whether a namespace holding `held` (and `reach`, from `_reach` under `newest_wins`) + holds the key of `row`.""" + writer = None if is_anonymous_user(row.user_id) else row.user_id + return key_in_namespace(row) in held or (writer, row.memory_key) in reach + + +async def _batched( + run: _Run, batch: dict[tuple[str, str], list[Any]], d: NsDecision, row: Any +) -> None: + rows = batch.setdefault((d.source_org, d.source), []) + rows.append(row) + if len(rows) >= _BATCH: + await _write_memories(run, d, rows) + rows.clear() + + +async def _write_memories(run: _Run, d: NsDecision, kept: list[Any]) -> None: + from server.memory.app import snapshot_rows as snap + + with _for(d): + if d.action == "merge": + await _merge_memories(run, d, kept) + return + kept, erased = await snap.without_erased(d.target_org, d.target, kept) + run.count(d, "memories_erased", erased) + rows = snap.checked_rows( + snap.restore_rows( + kept, + org=d.target_org, + target_namespace=d.target, + rebind_agent=None, + version_base=run.next_version(), + actor=run.actor, + ) + ) + run.version += len(rows) + if rows: + await snap.insert_version_rows(rows, ch=run.ch) + run.count(d, "memories", len(rows)) + + +async def _held_keys( + ch: Any, org: str, namespace: str, keys: list[str] +) -> dict[KeyInNamespace, bool]: + """Every (agent, user, session, key) of `keys` the namespace holds or has held, a + deleted one included, each with whether its latest version is a namespace + definition: the import only adds keys, so it never revises a fact written there, nor + brings back one its owners deleted. Under the Postgres authority its heads count too, + and answer last: one committed since its last publication to ClickHouse is there + only.""" + from server.core import pg + from server.memory.store import pg_memory + + sql = ( + "SELECT agent, user_id, session_id, memory_key, " + "argMax(memory_type, version) AS memory_type FROM loom.memory " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND memory_key IN {keys:Array(String)} GROUP BY agent, user_id, session_id, memory_key" + ) + params = {"org": org, "ns": namespace, "keys": keys} + held = { + key_in_namespace(r): is_namespace_definition(r) async for r in stream_rows(ch, sql, params) + } + if pg.enabled(): + after = None + while True: + page = await pg_memory.held_in(org, namespace, after=after, limit=PG_PAGE, keys=keys) + held.update(page) + if len(page) < PG_PAGE: + break + after = page[-1][0] + return held + + +def _live(m: Any, now: datetime) -> bool: + """Whether a merge carries source head `m`: a row reads serve (active or conflicted, + which the target's admission judges again), not redacted (its value is the + placeholder, which no read serves), and not past its expiry at `now`, the run's start, + so every pass of a run decides it alike.""" + from server.memory.domain.temporal_sql import SERVED_STATUSES + + return ( + m.status in SERVED_STATUSES + and m.redacted_at is None + and (m.expires_at is None or to_naive_utc(m.expires_at) > now) + ) + + +def _bulk_entry(m: Any) -> dict[str, Any]: + """A live source head (`_live`) as a `memory.bulk_set` entry. Its time of writing + becomes the import's; its validity, sensitivity, expiry and temporal anchor stay the + source's. A pin is not carried: it would refuse the target owners' own later writes + of a close fact.""" + ttl = None + if m.expires_at is not None: # from the write; a row that expired since lands, and expires + ttl = max(1, int((as_aware_utc(m.expires_at) - utc_now()).total_seconds())) + return { + "memory_key": m.memory_key, + "memory_type": m.memory_type, + "value": json.loads(m.value), + "confidence": m.confidence, + "source_trace": m.source_trace, + "source_class": "imported", + "ttl_seconds": ttl, + "tags": m.tags, + "entities": m.entities, + "temporal_anchor": m.temporal_anchor.isoformat() if m.temporal_anchor else None, + "temporal_confidence": m.temporal_confidence, + "valid_at": m.valid_at or m.created_at, + "valid_to": m.valid_to, + "char_limit": m.char_limit, + "files": m.files, + "concepts": m.concepts, + "evidence": m.evidence, + "grounding": m.grounding, + "sensitivity": m.sensitivity, + } + + +async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None: + """Into a namespace the target already serves: through `memory.bulk_set`, so conflict + surfacing, pinned peers and the skip of an unchanged restatement hold, as + `memory.import` writes outside facts: every entry checked, oldest first (the later of + two statements of one attribute in a call retires the earlier), no update detection + on facts the source already distilled, and no reinforcement, which each rerun would + add again.""" + from server.core.pg_lease import PublicationPending + from server.memory.api.models_bulk import MemoryBulkSetInput + from server.memory.app.bulk_set import handle_memory_bulk_set + + t = (d.target_org, d.target) + groups: dict[tuple[str, str, str], list[Any]] = {} + for m in memories: # each live at the run's start (`_kept`); at most _BATCH, one call + groups.setdefault((m.agent, m.user_id, m.session_id), []).append(m) + for (agent, user_id, session_id), rows in groups.items(): + # Read again just before the call: a key the target's owners wrote since `_kept` + # read the namespace, or since an earlier call, stays theirs. + held = await _held_keys(run.ch, *t, keys=sorted({m.memory_key for m in rows})) + reach = _reach(held) if t in run.reach else set() + entries = [_bulk_entry(m) for m in rows if not _holds(held, reach, m)] + if n := len(rows) - len(entries): + run.count(d, "memories_the_target_holds", n) + if not entries: + continue + entries.sort(key=lambda e: to_naive_utc(e["valid_at"]) or run.now) # stable + try: + out = await handle_memory_bulk_set( + MemoryBulkSetInput.model_validate( + { + "org": d.target_org, + "namespace": d.target, + "agent": agent, + "user_id": user_id, + "session_id": session_id, + "detect_updates": False, + "entries": entries, + } + ), + conflict_check_cap=len(entries), + reinforce=False, + ) + except PublicationPending: # committed, its answer lost; the worker publishes it + run.count(d, "memories_publication_pending", len(entries)) + continue + written = sum(1 for w in out.written if w.version) + run.count(d, "memories", written) + if declined := len(entries) - written: # a pinned peer, or a restatement it merged + run.count(d, "memories_not_admitted", declined) + + +async def _documents(run: _Run) -> None: + """Each document through `knowledge.upsert`, with its original: chunked and embedded + by the target's embedder. A source_uri the target namespace serves or has served is + left as it is, whether an earlier run wrote it or the target's owners did, before the + run or during it: each is read just before its write.""" + from server.core.pg_lease import PublicationPending + from server.knowledge.api.models_knowledge import KnowledgeUpsertInput + from server.knowledge.app.writes import handle_knowledge_upsert + + written: dict[tuple[str, str], set[str]] = {} + for doc in run.bundle.records("documents"): + d = run.by_source.get((doc["org"], doc["namespace"])) + if d is None: + continue + t, uri = (d.target_org, d.target), str(doc["source_uri"]) + # Two source namespaces may merge into one: the first copy of an address stays. + if uri in written.setdefault(t, set()) or uri in await _held_uris(run.ch, *t, [uri]): + run.count(d, "documents_present") + continue + written[t].add(uri) + original = None + if doc.get("blob_path") and not doc.get("blob_erased_at"): + original = base64.b64encode(run.bundle.original(doc["blob_path"])).decode() + # PublicationPending: committed, and the delivery worker publishes it. + with _for(d), contextlib.suppress(PublicationPending): + await handle_knowledge_upsert( + KnowledgeUpsertInput( + org=d.target_org, + namespace=d.target, + source_uri=doc["source_uri"], + content=doc["content"], + title=doc.get("title") or "", + description=doc.get("description") or "", + tags=doc.get("tags") or [], + metadata=json.loads(doc.get("metadata") or "{}"), + original_bytes_b64=original, + original_filename=doc.get("original_filename") or "", + blob_content_type=doc.get("blob_content_type") or "", + agent="" if doc.get("agent") in (None, "-") else doc["agent"], + session_id="" if doc.get("session_id") in (None, "-") else doc["session_id"], + source_class="imported", + ) + ) + run.count(d, "documents") + + +async def apply( + ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOrg] +) -> dict[str, Any]: + """Write the plan; return the receipt.""" + run = _Run(ch, bundle, p, targets) + rows = {(str(r["org"]), str(r["namespace"])): r for r in bundle.records("namespaces")} + patterns = list(bundle.records("blacklist")) + todo = [] + for d in p.namespaces: + if d.action == "skip": + continue + if (d.target, run.key(d.source_org, d.source)) in targets[d.target_org].done: + run.count(d, "already_imported") + continue + todo.append(d) + run.by_source = {(d.source_org, d.source): d for d in todo} + for d in todo: # every landing and its refusals before any content + with _for(d): + await _land(run, d, rows[(d.source_org, d.source)]) + if d.action == "create": + await _carry(run, d) + await _blacklist(run, d, patterns) + else: + run.refusals[(d.source_org, d.source)] = refusals(patterns, d) + await _grants(run) + if p.sso_same_issuer: + await _links(run) + await _memories(run) + await _documents(run) + content = carried(bundle) + for d in todo: # a row-only landing stays unfinished: a later bundle brings its content + if (d.source_org, d.source) in content: + await run.audit(DONE, d.target_org, d.target, d.target, run.key(d.source_org, d.source)) + return { + **run.digests, + "counts": run.counts, + "set_up_again": { + s: [r for r in bundle.records(s) if r["org"] in p.orgs] + for s in ("service_accounts", "bots", "connected_accounts") + }, + "left_behind": bundle.manifest.get("left_behind", {}), + } diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py new file mode 100644 index 0000000000..04e0a5e136 --- /dev/null +++ b/server/cli/instance_plan.py @@ -0,0 +1,806 @@ +"""The plan of a consolidation import: what each source org, namespace and subject becomes +on the target. Pure: it reads the bundle's identity rows and a snapshot of the target, and +writes nothing. + +A plan is refused (`Plan.problems`) rather than guessed whenever a source name could land +on someone else's: a namespace the target already has, an account handle or email the +target already gives to an account, a subject the bundle cannot place, an end user +(`user:`) that may name other people in a target org that already serves others, or a +group, agent or `everyone`, which hold grants on collections only, and collections do not +move. Each problem says what settles it, and names the map entry where one does. The map +file (YAML): + + orgs: # source org: target org (default: same name) + acme: acme + sso_same_issuer: false # the source signed people in with this IdP too + namespaces: # "/": rule (default: create) + acme/notes: {rename: notes-legacy} + acme/lessons: {merge: lessons} # add {grants: true} to carry its grants too + acme/scratch: skip + subjects: # "/": rule (default: see below) + acme/alice: u-alice-1a2b3c4d # the same person's account on the target + acme/bob: {claim: bob-legacy} # a claimable account under a new handle + acme/user:42: keep # the same end user on the target + acme/sa:ci-1a2b3c: drop + +An account with no rule lands as a claimable password account under its own handle: the +person's first single sign-on on the target asks for their old Loom password once and +links it (`docs/operations/sso.md#accounts`), and `loom sso adopt` links it too. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Iterable, Mapping +from dataclasses import asdict, dataclass, field +from datetime import datetime +from typing import Any, Literal + +from server.auth.sharing import PERSONAL_ALIAS, is_collection +from server.core.datetimes import as_aware_utc +from server.core.naming import ( + SSO_NAMESPACE_PREFIX, + is_anonymous_user, + is_reserved_name, + is_sso_namespace_name, + validate_namespace_name, +) +from server.core.principals import ( + AGENT, + EVERYONE, + GROUP, + SERVICE_ACCOUNT, + USER, + end_user_revocation_subject, +) +from server.identity.domain.join_policy import OPEN, effective_join_policy + +NsAction = Literal["create", "merge", "skip"] +SubjectAction = Literal["claim", "map", "keep", "drop"] +# Service accounts sign with credentials the source issued: their owners make new ones on +# the target, so their grants are not carried. +DROPPED_PREFIXES = (SERVICE_ACCOUNT,) + + +class MapError(ValueError): + """The map file is malformed: the message names the entry.""" + + +@dataclass(frozen=True) +class NsRule: + action: NsAction + target: str = "" + grants: bool = False + + +@dataclass(frozen=True) +class SubjectRule: + action: SubjectAction + target: str = "" + + +@dataclass +class MapFile: + orgs: dict[str, str] = field(default_factory=dict) + namespaces: dict[str, NsRule] = field(default_factory=dict) + subjects: dict[str, SubjectRule] = field(default_factory=dict) + sso_same_issuer: bool = False + + +def _flag(where: str, v: Any) -> bool: + if not isinstance(v, bool): + raise MapError(f"{where}: expected true or false") + return v + + +def _ns_rule(key: str, raw: Any) -> NsRule: + if raw in ("create", "skip"): + return NsRule(raw) + if isinstance(raw, dict): + if set(raw) - {"rename", "merge", "grants"} or ("rename" in raw) == ("merge" in raw): + raise MapError(f"namespaces.{key}: give one of rename or merge (and grants)") + if "rename" in raw: + if "grants" in raw: + raise MapError(f"namespaces.{key}: grants applies to merge only") + return NsRule("create", str(raw["rename"])) + grants = _flag(f"namespaces.{key}.grants", raw.get("grants", False)) + return NsRule("merge", str(raw["merge"]), grants) + raise MapError(f"namespaces.{key}: expected create, skip, {{rename: …}} or {{merge: …}}") + + +def _subject_rule(key: str, raw: Any) -> SubjectRule: + if raw in ("claim", "drop", "keep"): + return SubjectRule(raw) + if isinstance(raw, dict) and set(raw) == {"claim"}: + return SubjectRule("claim", str(raw["claim"])) + if isinstance(raw, str) and raw: + return SubjectRule("map", raw) + raise MapError(f"subjects.{key}: expected a target subject, claim, {{claim: …}}, keep or drop") + + +def _keyed(section: str, raw: Any) -> dict[str, Any]: + if raw is None: + return {} + if not isinstance(raw, dict): + raise MapError(f"{section}: expected a mapping") + for k in raw: + if not isinstance(k, str) or k.count("/") < 1 or not k.split("/", 1)[1]: + raise MapError(f"{section}.{k}: keys are /") + return raw + + +def parse_map(raw: Any) -> MapFile: + """The map file's YAML, parsed and checked (no target state needed).""" + if raw is None: + return MapFile() + if not isinstance(raw, dict): + raise MapError("the map file is a mapping with orgs, namespaces and subjects") + unknown = set(raw) - {"orgs", "namespaces", "subjects", "sso_same_issuer"} + if unknown: + raise MapError(f"unknown map keys: {', '.join(sorted(unknown))}") + orgs = raw.get("orgs") or {} + if not isinstance(orgs, dict) or not all( + isinstance(k, str) and isinstance(v, str) and v for k, v in orgs.items() + ): + raise MapError("orgs: expected : pairs") + return MapFile( + orgs=dict(orgs), + namespaces={ + k: _ns_rule(k, v) for k, v in _keyed("namespaces", raw.get("namespaces")).items() + }, + subjects={ + k: _subject_rule(k, v) for k, v in _keyed("subjects", raw.get("subjects")).items() + }, + sso_same_issuer=_flag("sso_same_issuer", raw.get("sso_same_issuer", False)), + ) + + +@dataclass(frozen=True) +class TargetOrg: + """What the plan reads of one target org.""" + + namespaces: Mapping[str, Mapping[str, Any]] # name → its row (kind, active, owner_email) + subjects: frozenset[str] # every account handle and grant subject the org holds + # (name, "//") of each namespace an earlier import created, to + # the source row's created_at its audit row records: a run that stopped part way + # resumes, never taken for a collision. + landed: Mapping[tuple[str, str], str] = field(default_factory=dict) + merged: frozenset[tuple[str, str]] = frozenset() # (target namespace, source) merged into + done: frozenset[tuple[str, str]] = frozenset() # the landings an earlier run finished + # The landed names the target revoked outright, lower-cased: a revocation spans orgs. + revoked: frozenset[str] = frozenset() + + def holds(self, name: str, key: str) -> bool: + """Whether namespace `name` is still landing `key`'s: finished, or its row the one + that landing wrote.""" + if (name, key) in self.done: + return True + row = self.namespaces.get(name) + return row is not None and landed_row(row, self.landed.get((name, key))) + + +@dataclass(frozen=True) +class NsDecision: + source_org: str + source: str + target_org: str + target: str + action: NsAction + account: str = "" # "claim" or "sso" when the namespace is an account the import makes + grants: bool = True + # Lands with join_policy approval: on the source anyone in its org could join it as a + # viewer at once, and the target org serves others. + approval: bool = False + + +@dataclass(frozen=True) +class SubjectDecision: + source_org: str + subject: str + action: SubjectAction + target: str = "" + note: str = "" + + +@dataclass +class Plan: + bundle: str # the bundle's digest: a plan applies to the bundle it was made from + orgs: dict[str, str] + namespaces: list[NsDecision] + subjects: list[SubjectDecision] + problems: list[str] + proposals: dict[str, dict[str, Any]] # map entries that would settle the problems + sso_same_issuer: bool = False # whether the accounts' single sign-on links land + + def subject_map(self) -> dict[tuple[str, str], str | None]: + """(source org, subject) → target subject, None for a dropped one.""" + out: dict[tuple[str, str], str | None] = {} + for s in self.subjects: + out[(s.source_org, s.subject)] = None if s.action == "drop" else s.target + return out + + @property + def digest(self) -> str: + """Names the decisions and the bundle: `--expect-plan` refuses to apply a plan + that changed.""" + body = json.dumps( + { + "bundle": self.bundle, + "orgs": self.orgs, + "sso_same_issuer": self.sso_same_issuer, + "namespaces": [asdict(n) for n in self.namespaces], + "subjects": [asdict(s) for s in self.subjects], + }, + sort_keys=True, + ) + return hashlib.sha256(body.encode()).hexdigest()[:16] + + +def is_account(row: Mapping[str, Any]) -> bool: + """A namespace row someone signs in as: its owner is itself, and it holds a password + or single sign-on made it.""" + name = str(row["namespace"]) + return str(row.get("owner_email") or "") == name and ( + bool(row.get("password_hash")) or is_sso_namespace_name(name) + ) + + +def landed_row(row: Mapping[str, Any], created_at: Any) -> bool: + """Whether a target namespace row is the one an import wrote from a source row created + at `created_at`: it keeps that `created_at`, which a name registered since cannot have, + and its owners have not deleted it.""" + + def at(v: Any) -> Any: # the bundle's ISO text or the target's naive UTC + return as_aware_utc(datetime.fromisoformat(v) if isinstance(v, str) else v) + + return ( + bool(created_at) + and bool(row.get("active", True)) + and row.get("created_at") is not None + and at(row["created_at"]) == at(created_at) + ) + + +def revoked_subject(revoked: set[str] | frozenset[str], org: str, subject: str) -> bool: + """Whether the source revoked `subject` of `org` outright, by `revoked` (lower-cased): + under its own name, or an end user's under the key its tokens are revoked by.""" + s = subject.lower() + return s in revoked or ( + s.startswith(USER) and end_user_revocation_subject(org, s).lower() in revoked + ) + + +def _revoked_emails( + rows: Mapping[str, Mapping[str, Any]], links: Mapping[str, list[str]], revoked: set[str] +) -> set[str]: + """The contact and link emails, lower-cased, of the org's accounts the source revoked: + single sign-on there admits no one by them.""" + out: set[str] = set() + for name, row in rows.items(): + if name.lower() in revoked: + out |= { + e.strip().lower() + for e in (str(row.get("contact_email") or ""), *links.get(name, [])) + } + return out - {""} + + +def _collection_only(subject: str) -> bool: + """A subject that holds grants on collections only, which do not move.""" + return subject.startswith((GROUP, AGENT)) or subject == EVERYONE + + +def _name_problem(name: str) -> str | None: + try: + validate_namespace_name(name) + except ValueError as e: + return str(e) + if is_reserved_name(name) or is_collection(name) or name == PERSONAL_ALIAS: + return f"{name!r} is a reserved name" + return None + + +@dataclass +class _Org: + """The work of planning one source org.""" + + source: str # the source deployment's id + org: str + target_org: str + rules: MapFile + target: TargetOrg + # Lower-cased email → "/" of every target account it signs in to, in + # any org: single sign-on refuses an email whose accounts are in two orgs. + signs_in: Mapping[str, list[str]] + links: Mapping[str, list[str]] # account → its single sign-on link emails + rows: dict[str, Mapping[str, Any]] # the source org's namespace rows by name + selected: list[str] + plan: Plan + taken: dict[str, str] # target name → source it lands from, across the target org + # Lower-cased email → "/" of each account of the bundle that lands with + # it, across every source org: single sign-on refuses an email two accounts hold. + emails: dict[str, str] + shared: bool # the target org serves others, or another source org lands in it + # The source subjects revoked outright, and the emails of this org's revoked accounts, + # lower-cased. + revoked: set[str] + + def problem(self, text: str, key: str = "", section: str = "", fix: Any = None) -> None: + self.plan.problems.append(f"{self.org}: {text}") + if key and section: + self.plan.proposals.setdefault(section, {})[key] = fix + + def subject(self, d: SubjectDecision) -> None: + self.plan.subjects.append(d) + + def occupied(self, target: str, source: str) -> bool: + """Whether the target holds `target` other than as this source's landing: one an + earlier run finished, or one it started whose row is still the one it wrote.""" + landing = f"{self.source}/{self.org}/{source}" + return target in self.target.namespaces and not self.target.holds(target, landing) + + def claim_name(self, name: str, source: str) -> bool: + """Reserve `name` in the target org for `source`; False (and a problem) when it + is taken, by this source org or another one landing in the same target org.""" + if (other := self.taken.get(name)) is not None: + self.problem(f"{source} and {other} both land on namespace {name!r}") + return False + self.taken[name] = f"{self.org}/{source}" + return True + + +def _signs_in_elsewhere(o: _Org, name: str, handle: str, emails: Iterable[str]) -> str: + """The first target account other than this source's landing of `name` as `handle`, + while it is still the import's, that one of `emails` signs in to; '' when none.""" + landed = f"{o.source}/{o.org}/{name}" + for email in emails: + for h in o.signs_in.get(email, []): + if h != f"{o.target_org}/{handle}" or not o.target.holds(handle, landed): + return h + return "" + + +def _still_signs_in(o: _Org, name: str) -> str: + """The handle an earlier bundle landed source account `name` under, whichever the map + gives now, that still signs in on the target and that the target has not revoked; + '' when none. Only the target's revocation also ends the tokens and sessions it has + had since.""" + key = f"{o.source}/{o.org}/{name}" + for handle, landing in sorted(o.target.landed): + row = o.target.namespaces.get(handle) or {} + mine = f"{o.target_org}/{handle}" + if ( + landing == key + and o.target.holds(handle, key) + and handle.lower() not in o.target.revoked + # A deleted account signs nobody in (password and single sign-on read `active`). + and bool(row.get("active", True)) + and ( + bool(row.get("password_hash")) or any(mine in held for held in o.signs_in.values()) + ) + ): + return handle + return "" + + +def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: + """One source account: claimed under its handle (or the map's), the same person's + target account, or left out with its namespace.""" + key = f"{o.org}/{name}" + rule = o.rules.subjects.get(key) + # Revoked on the source: it lands with no password, email or link, so none is checked. + revoked = name.lower() in o.revoked + email = "" if revoked else str(row.get("contact_email") or "").strip().lower() + sso = not row.get("password_hash") + if revoked and (held := _still_signs_in(o, name)): + # Whatever the map does with it now: dropped or claimed again, that landing stays. + o.problem( + f"account {name!r}: the source revoked it after an earlier bundle landed it, and " + f"{o.target_org}/{held} still signs in on the target: revoke it there (`loom " + f"revoke-token --subject {held}`, which revokes {held!r} in every org of the " + "deployment), then plan again" + ) + return + if rule is not None and rule.action == "drop": + o.subject(SubjectDecision(o.org, name, "drop", note="account and namespace left out")) + o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, "", "skip")) + return + if rule is not None and rule.action == "map": + account = not (_collection_only(rule.target) or rule.target.startswith(USER)) + if not account or rule.target not in o.target.subjects: + o.problem( + f"subjects.{key}: {rule.target!r} is no account or grant subject of " + f"{o.target_org} on the target a namespace can name" + ) + return + o.subject(SubjectDecision(o.org, name, "map", rule.target)) + _plan_namespace(o, name) # no longer an account: its namespace follows its rule + return + if rule is not None and rule.action == "keep": + o.problem(f"subjects.{key}: an account is claimed, mapped or dropped, not kept") + return + handle = rule.target if rule is not None and rule.target else name + if o.rules.namespaces.get(key) is not None: + o.problem(f"namespaces.{key}: an account's namespace follows its subjects entry") + # Its links land too when the source used this identity provider: each email counts. + emails = {email} - {""} + if o.rules.sso_same_issuer and not revoked: + emails |= {e.strip().lower() for e in o.links.get(name, [])} + if holder := _signs_in_elsewhere(o, name, handle, sorted(emails)): + # Nothing proves that account's contact email: the proposal hands it nothing. + o.problem( + f"account {name!r}: its email already signs in to {holder!r} on the target; map " + "it there if it is the same person (same org only), or drop it", + key, + "subjects", + "drop", + ) + return + if other := next((o.emails[e] for e in sorted(emails) if e in o.emails), ""): + o.problem( + f"account {name!r}: its email is also {other!r}'s, which this bundle brings too, " + "and single sign-on refuses an email two accounts hold: drop one", + key, + "subjects", + "drop", + ) + return + if sso and not o.rules.sso_same_issuer and not revoked: + o.problem( + f"account {name!r} signs in with single sign-on and has no password to prove it " + "on the target: map it to the person's target account, or set " + "sso_same_issuer: true when the source used this identity provider", + key, + "subjects", + "drop", + ) + return + if handle != name and (bad := _name_problem(handle)): + o.problem(f"subjects.{key}: {bad}") + return + if handle != name and handle.startswith(SSO_NAMESPACE_PREFIX) != sso: + o.problem(f"subjects.{key}: {handle!r} is not a handle for this kind of account") + return + if o.occupied(handle, name): + o.problem( + f"account {name!r}: the target already has namespace {handle!r}", + key, + "subjects", + {"claim": f"{handle}-legacy"}, + ) + return + if not o.claim_name(handle, name): + return + o.emails.update(dict.fromkeys(emails, f"{o.org}/{name}")) + note = "revoked on the source: lands with no way to sign in" if revoked else email + o.subject(SubjectDecision(o.org, name, "claim", handle, note=note)) + o.plan.namespaces.append( + NsDecision( + o.org, + name, + o.target_org, + handle, + "create", + account="sso" if sso else "claim", + approval=_opens(o, name), + ) + ) + + +def _opens(o: _Org, name: str) -> bool: + """Whether a viewer could join the namespace at once, in a target org that serves + others: the people of that org are not the source's.""" + return o.shared and effective_join_policy(dict(o.rows[name])) == OPEN + + +def _plan_namespace(o: _Org, name: str) -> None: + key = f"{o.org}/{name}" + rule = o.rules.namespaces.get(key) or NsRule("create") + if rule.action == "skip": + o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, "", "skip")) + return + target = rule.target or name + if rule.action == "merge": + row = o.target.namespaces.get(target) + if row is None or not row.get("active", True) or row.get("kind", "memory") != "memory": + o.problem( + f"namespaces.{key}: the target has no memory namespace {target!r} to merge into" + ) + return + o.plan.namespaces.append( + NsDecision(o.org, name, o.target_org, target, "merge", grants=rule.grants) + ) + return + if bad := _name_problem(target): + o.problem(f"namespaces.{key}: {bad}") + return + if is_sso_namespace_name(target): + o.problem( + f"namespace {target!r} has the form of a single sign-on account's name", + key, + "namespaces", + {"rename": f"{target.removeprefix(SSO_NAMESPACE_PREFIX)}-legacy"}, + ) + return + if o.occupied(target, name): + o.problem( + f"the target already has namespace {target!r}", + key, + "namespaces", + {"rename": f"{target}-legacy"}, + ) + return + if o.claim_name(target, name): + o.plan.namespaces.append( + NsDecision(o.org, name, o.target_org, target, "create", approval=_opens(o, name)) + ) + + +def _plan_subject(o: _Org, subject: str) -> None: + """A grant subject, owner or memory user that is no account of the bundle. With no + rule, or `keep`, it lands under its own name only where that names no one else; `keep` + decides that for an end user of a shared target org.""" + key = f"{o.org}/{subject}" + rule = o.rules.subjects.get(key) + action = rule.action if rule is not None else "" + if rule is not None and rule.action == "claim": + o.problem(f"subjects.{key}: only an account of the bundle can be claimed") + return + if action == "drop": + o.subject(SubjectDecision(o.org, subject, "drop")) + return + if rule is not None and rule.action == "map": + user = subject.startswith(USER) + # An id, so two end users never land as one through the rows with no user. + to_user = rule.target.startswith(USER) and not is_anonymous_user(rule.target[len(USER) :]) + if user and not to_user: + o.problem( + f"subjects.{key}: an end user maps to an end user's id (user:, " + "not '-' or empty, which name no user)" + ) + elif not user and rule.target.startswith(USER): + o.problem(f"subjects.{key}: only an end user maps to an end user (user:)") + elif _collection_only(rule.target): + o.problem(f"subjects.{key}: {rule.target!r} holds grants on collections only") + elif not user and rule.target not in o.target.subjects: + o.problem( + f"subjects.{key}: {rule.target!r} is no subject of {o.target_org} on the target" + ) + else: + o.subject(SubjectDecision(o.org, subject, "map", rule.target)) + return + if _collection_only(subject): + o.problem( + f"{subject!r} holds grants on collections only, and collections do not move: map " + "the grant to a target subject, or drop it", + key, + "subjects", + "drop", + ) + return + if subject.startswith(USER): + revoked = revoked_subject(o.revoked, o.org, subject) + if revoked and action != "keep": + # The target does not carry the revocation: its issuer's tokens for the id + # would read the rows again. + o.problem( + f"the source revoked {subject!r}: keep it only if the target's end-user " + "issuer may let it read its rows again, or drop it", + key, + "subjects", + "drop", + ) + elif o.shared and action != "keep": + # Another deployment's end-user issuer may name other people with the same id. + o.problem( + f"{subject!r} also names people of {o.target_org} on the target, which serves " + "others: keep it when it is the same people (the same end-user issuer), or " + "drop it", + key, + "subjects", + "drop", + ) + else: + note = "revoked on the source: its grants stay behind" if revoked else "" + o.subject(SubjectDecision(o.org, subject, "keep", subject, note=note)) + return + if "@" in subject: + if subject.lower() in o.revoked: + # On the source single sign-on admits no one by an address a revoked account + # names; that account lands with none, so on the target it would. + o.subject(SubjectDecision(o.org, subject, "drop", note="a revoked account's email")) + return + # An email grant admits whoever proves the address at sign-in, on the target as on + # the source; it is never tied to an account whose email the source did not verify. + o.subject(SubjectDecision(o.org, subject, "keep", subject, note="email")) + return + if subject.startswith(DROPPED_PREFIXES): + if action == "keep": + o.problem( + f"{subject!r} is a service account, whose credentials do not move: its owner " + "makes a new one on the target, so drop it", + key, + "subjects", + "drop", + ) + else: + o.subject( + SubjectDecision( + o.org, subject, "drop", note="service account: its owner makes a new one" + ) + ) + return + o.problem( + f"subject {subject!r} holds grants or owns a namespace but is no account of the " + "bundle, and may name someone else on the target: map it to its owner's target " + "subject, or drop it", + key, + "subjects", + "drop", + ) + + +def _check_users(o: _Org) -> None: + """Two end users of one source org landing as one would share each other's rows: a + memory's sort key holds its user, so one's row replaces the other's. Across source orgs + one person may hold an id in each, so the map decides.""" + seen: dict[str, str] = {} + for s in o.plan.subjects: + if s.source_org != o.org or s.action == "drop" or not s.subject.startswith(USER): + continue + if (other := seen.get(s.target)) is not None: + o.problem(f"subjects {other!r} and {s.subject!r} both land as {s.target!r}") + seen[s.target] = s.subject + + +def _needs(d: NsDecision | None, kind: str) -> bool: + """Whether a namespace's subjects of `kind` need deciding: all of a created one's; + of a merged one its end users, and its grant subjects when it carries its grants (the + target keeps its own owner); none of a skipped one's. With no decision, a problem + above, all, so its proposals stay whole.""" + if d is None or d.action == "create": + return True + return d.action == "merge" and (kind == "user" or (kind == "grant" and d.grants)) + + +def plan( + *, + bundle: str, + source: str, + rules: MapFile, + namespace_rows: Iterable[Mapping[str, Any]], + selected: Mapping[str, list[str]], + named: Mapping[str, Mapping[str, Mapping[str, set[str]]]], + links: Mapping[str, Mapping[str, list[str]]], + revoked: set[str], + targets: Mapping[str, TargetOrg], + signs_in: Mapping[str, list[str]], +) -> Plan: + """The decisions for every source org in `selected` (org → exported namespaces) of + deployment `source`. `named` is, per source org and namespace, the subjects it names + by kind: `grant` subjects, its `owner`, its memories' end users (`user:`), each + decided where the namespace needs it (`_needs`); `links` its accounts' single sign-on link + emails; `targets` the target state of each target org; `signs_in` every target + account by email; `revoked` the source subjects revoked outright, lower-cased.""" + p = Plan( + bundle=bundle, + orgs={}, + namespaces=[], + subjects=[], + problems=[], + proposals={}, + sso_same_issuer=rules.sso_same_issuer, + ) + by_org: dict[str, dict[str, Mapping[str, Any]]] = {} + for r in namespace_rows: + by_org.setdefault(str(r["org"]), {})[str(r["namespace"])] = r + landing: dict[str, list[str]] = {} + for org in selected: + landing.setdefault(rules.orgs.get(org, org), []).append(org) + taken: dict[str, dict[str, str]] = {} + emails: dict[str, str] = {} + for org in sorted(selected): + target_org = rules.orgs.get(org, org) + if bad := _name_problem(target_org): + p.problems.append(f"orgs.{org}: {bad}") + continue + p.orgs[org] = target_org + target = targets[target_org] + # The names this import landed there and still holds; one someone registered since + # is someone else's. + ours = { + name + for name, key in target.landed + if key.startswith(f"{source}/") + and key.split("/")[1] in landing[target_org] + and target.holds(name, key) + } + here = by_org.get(org, {}) + o = _Org( + source=source, + org=org, + target_org=target_org, + rules=rules, + target=target, + signs_in=signs_in, + links=links.get(org, {}), + rows=here, + selected=selected[org], + plan=p, + taken=taken.setdefault(target_org, {}), + emails=emails, + shared=len(landing[target_org]) > 1 or bool(set(target.namespaces) - ours), + revoked=revoked | _revoked_emails(here, links.get(org, {}), revoked), + ) + rows = o.rows + accounts = {n for n in o.selected if is_account(rows[n])} + for name in sorted(accounts): + _plan_account(o, name, rows[name]) + for name in sorted(set(o.selected) - accounts): + _plan_namespace(o, name) + # An account is planned above, a problem there included. + decided = accounts | {s.subject for s in p.subjects if s.source_org == org} + lands = {d.source: d for d in p.namespaces if d.source_org == org} + needed = { + s + for ns, kinds in named.get(org, {}).items() + for kind, subs in kinds.items() + if _needs(lands.get(ns), kind) + for s in subs + } + for subject in sorted(needed - decided): + _plan_subject(o, subject) + _check_users(o) + for s in p.subjects: + if ( + s.source_org == org + and s.action == "map" + and revoked_subject(o.revoked, org, s.subject) + ): + other = ( + "claim" + if s.subject in accounts + else "keep" + if s.subject.startswith(USER) + else "" + ) + o.problem( + f"subjects.{org}/{s.subject}: the source revoked {s.subject!r}; mapping it " + f"gives its content to {s.target!r}, whose access stays: " + f"{f'{other} or drop' if other else 'drop'} it" + ) + # A map entry that names nothing is a typo: the plan it would have changed is not shown. + names = {f"{org}/{n}" for org, ns in selected.items() for n in ns} + handles = { + f"{org}/{n}" for org, ns in selected.items() for n in ns if is_account(by_org[org][n]) + } + known = { + "orgs": set(selected), + "namespaces": names, + "subjects": handles + | { + f"{o}/{s}" + for o, by_ns in named.items() + for kinds in by_ns.values() + for subs in kinds.values() + for s in subs + }, + } + for section, keys in ( + ("orgs", rules.orgs), + ("namespaces", rules.namespaces), + ("subjects", rules.subjects), + ): + p.problems.extend( + f"{section}.{k}: names nothing in this bundle" + for k in sorted(set(keys) - known[section]) + ) + return p + + +def proposal_yaml(p: Plan) -> str: + """The map entries that settle a plan's problems, as YAML to edit and pass back.""" + import yaml + + return str(yaml.safe_dump(p.proposals, sort_keys=True, default_flow_style=False)) diff --git a/server/knowledge/store/pg_documents.py b/server/knowledge/store/pg_documents.py index 4d878b860f..50173acdcf 100644 --- a/server/knowledge/store/pg_documents.py +++ b/server/knowledge/store/pg_documents.py @@ -316,6 +316,22 @@ async def heads(org: str, namespace: str, uris: Sequence[str]) -> dict[str, Head return {str(r["source_uri"]): Head(decode_row(r["row"]), bool(r["owed"])) for r in got} +async def held_uris(org: str, namespace: str, uris: Sequence[str]) -> set[str]: + """Which of these sources have a head (deleted ones included), read without the + rows.""" + uris = [u for u in uris if not pg.unstorable(u)] + if not uris or pg.unstorable([org, namespace]): + return set() + got = await pg.fetch( + "SELECT source_uri FROM loom.knowledge_heads " + "WHERE org = $1 AND namespace = $2 AND source_uri = ANY($3::text[])", + org, + namespace, + sorted(set(uris)), + ) + return {str(r["source_uri"]) for r in got} + + async def head_lists(org: str, namespace: str, uris: Sequence[str]) -> dict[str, str]: """The permission list (`access_json`) of each live head among these sources, read without the rest of the row.""" diff --git a/server/memory/app/blacklist_guard.py b/server/memory/app/blacklist_guard.py index 42eb767ff2..c6d323a4ab 100644 --- a/server/memory/app/blacklist_guard.py +++ b/server/memory/app/blacklist_guard.py @@ -391,6 +391,13 @@ def _first_match( ) +def match_value(patterns: list[BlacklistPattern], value: str) -> BlacklistPattern | None: + """The first of `patterns` that matches `value`, as a write is checked, for a caller + holding patterns that are not the cache's (an import's source refusals); no request + budget or matcher turn.""" + return _first_match(patterns, value, value.encode("utf-8", "replace")) + + def _over_budget( org: str, namespace: str, scope: str, size: int, program: int, *, alone: bool ) -> BlacklistPattern: diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 5af3de3a3b..d34cab7445 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -34,7 +34,7 @@ from server.core.numbers import FLOAT32_MAX, float32 from server.core.pg_lease import lease_deadline from server.memory.domain import lock as _lock -from server.memory.domain.memory_types import is_embedded +from server.memory.domain.memory_types import is_embedded, is_namespace_definition from server.memory.domain.proposal_review import enforce_review from server.memory.domain.redaction_lineage import ( REDACTED_VALUE, @@ -45,9 +45,11 @@ from server.memory.store.rows import ( FIRST_VERSION_DEFAULTS, IdentityKey, + KeyInNamespace, MemoryRow, _hydrate, identity_key, + key_in_namespace, memory_head_state, parse_memory_value, ) @@ -2087,6 +2089,35 @@ async def live_heads_in( return [decode_row(r["row"]) for r in rows] +async def held_in( + org: str, + namespace: str, + *, + keys: Sequence[str], + after: KeyInNamespace | None = None, + limit: int = 5000, +) -> list[tuple[KeyInNamespace, bool]]: + """A page of the namespace's heads whose key is one of `keys`, deleted ones included, + in key order after `after`, each with whether it is a namespace definition: what the + namespace holds or has held, its publication to ClickHouse owed or not.""" + if pg.unstorable((org, namespace)): + return [] + args: list[Any] = [org, namespace, limit] + where = "org = $1 AND namespace = $2" + if after is not None: + args += list(after) + where += " AND (agent, user_id, session_id, memory_key) > ($4, $5, $6, $7)" + args.append([k for k in keys if not pg.unstorable(k)]) + where += f" AND memory_key = ANY(${len(args)}::text[])" + rows = await pg.fetch( + "SELECT agent, user_id, session_id, memory_key, row->>'memory_type' AS memory_type " + f"FROM loom.memory_current WHERE {where} " + "ORDER BY org, namespace, agent, user_id, session_id, memory_key LIMIT $3", + *args, + ) + return [(key_in_namespace(r), is_namespace_definition(dict(r))) for r in rows] + + async def unpublished_keepers( org: str, namespace: str, agent: str, user_id: str, shas: Sequence[str], *, scope: Any ) -> list[dict[str, Any]]: diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py new file mode 100644 index 0000000000..e8c3b8d35c --- /dev/null +++ b/tests/integration/test_instance_consolidation.py @@ -0,0 +1,723 @@ +"""`loom instance export` and `loom instance import` against a real ClickHouse: one org +moves into another that already has an account, a grant subject and a namespace with the +source's names. The dry run refuses until the map settles each; the apply lands them under +the mapped names with every field of the source rows, merges a namespace into the +target's without touching a key the target holds or storing the source's refusals there, +carries its grants past a request to join but never past a revocation, and leaves the +target's own rows alone. An account the source revoked lands with no way to +sign in to it. Running it again, finished or resumed part way, writes nothing.""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +import secrets +import subprocess +import sys +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest +import yaml + +from server.auth.jit import JIT_TAG +from server.auth.login import resolve_identity_for_email +from server.cli.instance_bundle import ORIGINALS, Bundle +from server.core.ch import get_client +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR +from tests.integration._resources import unique_org + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = [pytest.mark.asyncio, pytest.mark.usefixtures("ch_target_required")] + +HASH = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdA$aGFzaA" +KEYS = ("deploys", "oncall") +ARR = {"term": "ARR", "aliases": [], "body": "Yearly subscription revenue."} +ORIGINAL = b"# Runbook\nRestart with make restart.\n" +# What a restore owns on a row it writes: everything else is the source's. +RESTORED = {"version", "version_text", "actor", "source_class"} +# What `knowledge.upsert` owns on the document it writes, and the source's record of how it +# extracted it, which stays behind: everything else is the source's. +DOC_OWNED = { + "org", + "namespace", + "doc_id", + "version", + "ingested_at", + "actor", + "source_class", + "format", + "artifact_sha256", + "parser", + "coverage", + "ingestion_id", +} +SEQ = " SETTINGS select_sequential_consistency = 1" +# Org-wide regex refusals, 289 RE2 instructions each: together past half of a scope's 3000, +# so a rerun that counted the stored ones twice would refuse. +TOKENS = [rf"tok{i}-\d{{280}}" for i in range(6)] +TOKEN = "the deploy token is tok3-" + "7" * 280 +# The account SCIM revokes: a revocation names a subject on the whole deployment, so its +# handle is this run's own. +CAROL = f"carol-{secrets.token_hex(4)}" +POLICY = { + "policy_id": "read-before-delete", + "effect": "require", + "actions": ["memory.delete"], + "condition": {"op": "formerly", "within": "1h", "operation": ["memory.get"]}, + "description": "a delete follows a read", + "enabled": False, + "mode": "shadow", +} +# A created namespace's own rows, each compared field for field but for its org and name. +CARRIED = ("namespace_types", "namespace_policies", "namespace_guides") + + +@pytest.fixture(autouse=True) +async def ch() -> Any: + client = get_client() + await client.connect() + yield client + await client.disconnect() + + +async def _account( + ch: Any, org: str, name: str, email: str, active: bool = True, sso: bool = False +) -> None: + """A password account, or one single sign-on made (no password, JIT's tag).""" + now = datetime.now(UTC).replace(tzinfo=None, microsecond=0) + await ch.insert( + "loom.namespaces", + [ + { + "org": org, + "namespace": name, + "owner_email": name, + "contact_email": email, + "password_hash": "" if sso else HASH, + "description": "", + "tags": [JIT_TAG] if sso else [], + "active": active, + "visibility": "private", + "created_at": now, + "updated_at": now, + } + ], + ) + + +async def _link(ch: Any, org: str, name: str, email: str, linked: bool) -> None: + row = {"email": email, "org": org, "namespace": name, "linked": int(linked)} + row |= {"linked_by": "test-suite", "linked_at": datetime.now(UTC), "hosted_domain": ""} + await ch.insert( + "loom.sso_links", [row | {"version": 1 if linked else 2, "issuer": "https://idp.test"}] + ) + + +class _Api: + def __init__(self, url: str, token: str, org: str) -> None: + self.url, self.token, self.org = url, token, org + + def op(self, name: str, **body: Any) -> dict[str, Any]: + r = httpx.post( + f"{self.url}/v1/{name}", + json={"org": self.org, **body}, + headers={"Authorization": f"Bearer {self.token}"}, + timeout=60, + ) + assert r.status_code == 200, (name, r.text) + out: dict[str, Any] = r.json() + return out + + def get(self, namespace: str, key: str) -> dict[str, Any]: + return self.op("memory.get", namespace=namespace, agent="a", memory_key=key) + + def set(self, namespace: str, key: str, value: str) -> None: + self.op("memory.set", namespace=namespace, agent="a", memory_key=key, value=value) + + +def _cli(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "server.cli", "instance", *args], + cwd=ROOT, + env=os.environ, + capture_output=True, + text=True, + timeout=300, + ) + + +async def _seed_source(ch: Any, src: _Api) -> None: + for name in ("alice", "bob", CAROL): + await _account(ch, src.org, name, f"{name}@src.test") + # SCIM deprovisioned carol: the account stays, its key is SCIM's and spelled as it was. + expires = datetime.now(UTC).replace(tzinfo=None) + timedelta(days=30) + await ch.insert( + "loom.revoked_tokens", + [{"jti": "\x00scim:" + CAROL.upper(), "expires_at": expires, "reason": "scim"}], + ) + src.op( + "namespace.register", + namespace="team", + owner_email="alice", + visibility="public", + tag_registry=[{"memory_type": "decision", "retention_days": 30, "hot_quota": 5}], + ) + src.op("policy.set", namespace="team", **POLICY) + src.op( + "namespace.guide_set", + namespace="team", + content="# Team\nDeploys go through make.", + summary="how the team deploys", + expected_revision=0, + note="first guide", + ) + # A grant to the revoked account's email: no one signs in by it on the source. + grants = (("alice", "writer"), ("bob", "viewer"), (CAROL, "viewer")) + for subject, role in (*grants, (f"{CAROL}@src.test", "viewer")): + src.op("grants.create", namespace="team", subject=subject, role=role) + for key in KEYS: + src.set("team", key, f"the team's {key} rule") + src.set("team", "vault", "the vault code is SECRET-123") + src.op("blacklist.add", namespace="team", pattern="SECRET-", reason="no vault codes") + src.op( + "knowledge.add", + namespace="team", + source_uri="runbook.md", + content="# Runbook\nRestart the service.", + title="Runbook", + original_bytes_b64=base64.b64encode(ORIGINAL).decode(), + original_filename="runbook.md", + blob_content_type="text/markdown", + ) + # Knowledge sources' copies: a registered source's file, which it writes again once + # registered there, and a retiring source's; a removed source's file, which no source + # writes again; and a recording's transcript, which a source registered again never lists. + for name, active, retiring in ( + ("drive", True, False), + ("old-drive", False, False), + ("gone", False, True), + ): + await ch.execute( + "INSERT INTO loom.knowledge_sources (org, namespace, name, kind, active, " + "pending_delete) VALUES ({org:String}, 'team', {name:String}, 'gdrive', " + "{active:Bool}, {retiring:Bool})", + {"org": src.org, "name": name, "active": active, "retiring": retiring}, + ) + for uri, kind, source in ( + ("synced.md", "gdrive", "drive"), + ("retiring.md", "gdrive", "gone"), + ("kept.md", "gdrive", "old-drive"), + ("meeting.md", "recording", "drive"), + ): + await ch.execute( + "INSERT INTO loom.documents SELECT * REPLACE ({uri:String} AS source_uri, " + "{sync:String} AS actor, {meta:String} AS metadata, {tags:Array(String)} AS tags) " + "FROM (SELECT * FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = 'team' AND source_uri = 'runbook.md')", + { + "org": src.org, + "sync": SYNC_WORKER_ACTOR, + "uri": uri, + "meta": json.dumps({"source_kind": kind}), + "tags": [f"source:{source}"], + }, + ) + src.op("namespace.register", namespace="notes", owner_email="alice") + for subject, role in (("erin@src.test", "viewer"), ("dave@src.test", "viewer")): + src.op("grants.create", namespace="notes", subject=subject, role=role) + src.op("grants.create", namespace="notes", subject="frank", role="writer") + src.op( + "memory.set", + namespace="notes", + agent="a", + memory_key="standup", + value="standup is at ten", + tags=["rituals"], + confidence=0.8, + ttl_seconds=86400, + sensitivity="low", + ) + src.set("notes", KEYS[0], "the notes' own deploy rule") # a key the target's team holds + # One key in two sessions, values far apart so the source's admission marks neither, + # and a key the target's team holds in another session. + for key, session, at, value in ( + ("employer", "s1", "2024-01-01T00:00:00Z", "Acme Corporation employs the team lead"), + ("employer", "s2", "2025-01-01T00:00:00Z", "the deploy window opens at nine"), + ("city", "s2", "2025-01-01T00:00:00Z", "the office moved to Rome"), + ): + src.op( + "memory.set", + namespace="notes", + agent="a", + session_id=session, + memory_key=key, + value=value, + valid_at=at, + ) + # One key with no user and an end user's newer row of it. + for user, at, value in ( + ("-", "2024-01-01T00:00:00Z", "the platform team owns deploys"), + ("u7", "2025-01-01T00:00:00Z", "release managers sign off on Fridays"), + ): + src.op( + "memory.set", + namespace="notes", + agent="a", + user_id=user, + memory_key="owner", + value=value, + valid_at=at, + ) + # A namespace definition and a newer row with no user of its key, far apart: no other + # write of the key retires a definition. + for agent, kind, at, value in ( + ("-", "definition", "2024-01-01T00:00:00Z", ARR), + ("a", "semantic", "2025-01-01T00:00:00Z", "the standup moved to the big room"), + ): + src.op( + "memory.set", + namespace="notes", + agent=agent, + memory_key="definition/arr", + memory_type=kind, + value=value, + valid_at=at, + ) + src.set("notes", "token", TOKEN) # written before the source refused it + for pattern in TOKENS: + src.op( + "blacklist.add", + namespace="notes", + pattern=pattern, + pattern_type="regex", + scope="org", + reason="no deploy tokens", + ) + + +async def _state(ch: Any, dst: _Api) -> dict[str, Any]: + """Everything an apply writes on the target, to tell that a run wrote nothing.""" + p = {"org": dst.org} + + async def rows(sql: str) -> list[tuple[Any, ...]]: + return sorted(tuple(r.values()) for r in await ch.query_all(sql + SEQ, params=p)) + + return { + "memories": {key: dst.get("team-legacy", key)["version"] for key in KEYS}, + "document": dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md")[ + "revision" + ], + "merged": await rows( # every row of the merged team, the target's own included + "SELECT memory_key, agent, user_id, session_id, status, version FROM loom.memory " + "FINAL WHERE org = {org:String} AND namespace = 'team'" + ), + "namespaces": await rows( + "SELECT namespace, owner_email, updated_at FROM loom.namespaces FINAL " + "WHERE org = {org:String}" + ), + "grants": await rows( + "SELECT namespace, subject, role, version FROM loom.namespace_grants FINAL " + "WHERE org = {org:String}" + ), + "blacklist": await rows( + "SELECT namespace, pattern, scope, toString(pattern_id) FROM loom.blacklist FINAL " + "WHERE org = {org:String}" + ), + "carried": [ + await rows(f"SELECT count() FROM loom.{t} WHERE org = {{org:String}}") for t in CARRIED + ], + } + + +async def test_an_org_moves_into_a_live_one_under_the_map( + ch: Any, control_plane_url: str, mint_test_token: Any, tmp_path: Path +) -> None: + src_org, dst_org = unique_org("isrc"), unique_org("idst") + src = _Api(control_plane_url, mint_test_token(org=src_org, roles=["org_admin"]), src_org) + dst = _Api(control_plane_url, mint_test_token(org=dst_org, roles=["admin"]), dst_org) + await _seed_source(ch, src) + # The target's alice and team are someone else's, and its bob holds a grant. + await _account(ch, dst_org, "alice", "alice@dst.test") + dst.op( + "namespace.register", + namespace="team", + owner_email="alice", + default_conflict_policy="newest_wins", + ) + dst.op("grants.create", namespace="team", subject="bob", role="viewer") + # frank's self-signup email holds writer there, which admits no one as frank. + await _account(ch, dst_org, "frank", "frank@src.test") + dst.op("grants.create", namespace="team", subject="frank@src.test", role="writer") + dst.set("team", KEYS[0], "the target's own rule") + dst.op( + "memory.set", + namespace="team", + agent="a", + session_id="s1", + memory_key="city", + value="the office is in Paris", + ) + # On its team erin asked to join, which grants nothing, and a revocation spelled + # otherwise is dave's. + now = datetime.now(UTC).replace(tzinfo=None, microsecond=0) + row = {"org": dst_org, "namespace": "team", "role": "viewer", "granted_at": now} + row |= {"granted_by": "test-suite", "version": 1} + await ch.insert( + "loom.namespace_grants", + [ + {**row, "subject": "erin@src.test", "status": "pending", "revoked_at": None} + | {"pending_since": now}, + {**row, "subject": "Dave@Src.Test", "status": "active", "revoked_at": now} + | {"pending_since": None}, + ], + ) + + bundle = tmp_path / "bundle" + out = _cli("export", "--org", src_org, "--out", str(bundle)) + assert out.returncode == 0, out.stderr + # A source is another deployment: its accounts do not sign in to this one. + for name in ("alice", "bob", CAROL): + await _account(ch, src_org, name, f"{name}@src.test", active=False) + + mapping = tmp_path / "map.yaml" + mapping.write_text(yaml.safe_dump({"orgs": {src_org: dst_org}})) + refused = _cli("import", "--bundle", str(bundle), "--map", str(mapping)) + assert refused.returncode == 1, refused.stderr + proposals = yaml.safe_load(refused.stdout.split("plan again):\n", 1)[1]) + assert proposals == { + "namespaces": {f"{src_org}/team": {"rename": "team-legacy"}}, + "subjects": { + f"{src_org}/alice": {"claim": "alice-legacy"}, # the target's alice + f"{src_org}/bob": {"claim": "bob-legacy"}, # a grant there names bob + # No account, email or principal the target knows: the minted token's subject, + # and frank, whom the map then names. + f"{src_org}/test-suite": "drop", + f"{src_org}/frank": "drop", + # An end user's id may name other people of a target that serves others. + f"{src_org}/user:u7": "drop", + }, + } + proposals["namespaces"][f"{src_org}/notes"] = {"merge": "team", "grants": True} + proposals["subjects"][f"{src_org}/frank"] = "frank" + proposals["subjects"][f"{src_org}/user:u7"] = "keep" + mapping.write_text(yaml.safe_dump({"orgs": {src_org: dst_org}, **proposals})) + # The dry run reads every original back: one changed since the export refuses it. + original = bundle / ORIGINALS / hashlib.sha256(ORIGINAL).hexdigest() + original.write_bytes(b"# Runbook\nRestart by hand.\n") + altered = _cli("import", "--bundle", str(bundle), "--map", str(mapping)) + assert altered.returncode == 1 and "copy the whole bundle" in altered.stdout, altered.stdout + original.write_bytes(ORIGINAL) + dry = _cli("import", "--bundle", str(bundle), "--map", str(mapping)) + assert dry.returncode == 0, dry.stdout + dry.stderr + digest = re.search(r"^plan (\w+)$", dry.stdout, re.M) + assert digest, dry.stdout + assert f"re-run with --apply --expect-plan {digest[1]} to write" in dry.stderr + plan = ("--map", str(mapping), "--expect-plan", digest[1], "--apply") + applied = _cli("import", "--bundle", str(bundle), *plan) + assert applied.returncode == 0, applied.stdout + applied.stderr + receipt = json.loads(applied.stdout[applied.stdout.rindex('{\n "bundle"') :]) + + for key in KEYS: + before, after = src.get("team", key), dst.get("team-legacy", key) + assert before["found"] and after["found"] + assert {k for k in before if before[k] != after[k]} == RESTORED + assert (after["source_class"], after["actor"]) == ("imported", "process:cli:instance") + assert not dst.get("team-legacy", "vault")["found"] # its refusal landed first + # The merge adds the key the target lacks, with the source's validity, and no other. + before, merged = src.get("notes", "standup"), dst.get("team", "standup") + assert (merged["value"], merged["memory_type"]) == (before["value"], before["memory_type"]) + assert merged["valid_at"] == (before["valid_at"] or before["created_at"]) + carried = ("tags", "confidence", "sensitivity") + assert [merged[k] for k in carried] == [before[k] for k in carried] + expiry = [datetime.fromisoformat(m["expires_at"]) for m in (before, merged)] + assert abs(expiry[0] - expiry[1]) < timedelta(minutes=5) # the source's, as a TTL + assert (merged["source_class"], merged["actor"]) == ("imported", "process:cli:instance") + assert dst.get("team", KEYS[0])["value"] == "the target's own rule" + assert not dst.get("team", KEYS[1])["found"] + assert not dst.get("team", "token")["found"] # the source's refusal, applied in process + + # Under the target's newest_wins a write of a key reaches its other sessions: of the + # source's two only the newer lands, and the target's own row of a key it holds stays + # live; an end user's row lands beside the row with no user of its key. Read from the + # table: memory.get falls back to the key's row in any session. + rows = await ch.query_all( + "SELECT memory_key, user_id, session_id, status, value FROM loom.memory FINAL " + "WHERE org = {org:String} AND namespace = 'team' AND tombstoned_at IS NULL " + "AND memory_key IN ('employer', 'city', 'owner')" + SEQ, + params={"org": dst_org}, + ) + columns = ("memory_key", "user_id", "session_id", "status") + assert {(*(r[c] for c in columns), json.loads(r["value"])) for r in rows} == { + ("employer", "-", "s2", "active", "the deploy window opens at nine"), + ("city", "-", "s1", "active", "the office is in Paris"), + ("owner", "-", "-", "active", "the platform team owns deploys"), + ("owner", "u7", "-", "active", "release managers sign off on Fridays"), + } + assert receipt["counts"][f"{dst_org}/team"]["memories_superseded"] == 1 # employer in s1 + # The definition lands first, and the row with no user of its key beside it. + arr = await ch.query_all( + "SELECT agent, memory_type, status FROM loom.memory FINAL WHERE org = {org:String} " + "AND namespace = 'team' AND memory_key = 'definition/arr' AND tombstoned_at IS NULL" + SEQ, + params={"org": dst_org}, + ) + assert sorted(tuple(r.values()) for r in arr) == [ + ("-", "definition", "active"), + ("a", "semantic", "active"), + ] + + doc = dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md") + assert (doc["found"], doc["content"], doc["title"]) == ( + True, + "# Runbook\nRestart the service.", + "Runbook", + ) + runbook = ( + "SELECT * FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND source_uri = 'runbook.md'" + SEQ + ) + src_doc = await ch.query_one(runbook, params={"org": src_org, "ns": "team"}) + dst_doc = await ch.query_one(runbook, params={"org": dst_org, "ns": "team-legacy"}) + assert src_doc is not None and dst_doc is not None + assert dst_doc["blob_path"] == hashlib.sha256(ORIGINAL).hexdigest() + assert {k for k in src_doc if src_doc[k] != dst_doc[k]} <= DOC_OWNED + assert (dst_doc["actor"], dst_doc["source_class"]) == ("process:cli:instance", "imported") + + accounts = await ch.query_all( + "SELECT namespace, owner_email, contact_email, password_hash, join_policy " + "FROM loom.namespaces FINAL WHERE org = {org:String} ORDER BY namespace" + SEQ, + params={"org": dst_org}, + ) + assert [tuple(r.values()) for r in accounts] == [ + ("alice", "alice", "alice@dst.test", HASH, "inherit"), + ("alice-legacy", "alice-legacy", "alice@src.test", HASH, "inherit"), + ("bob-legacy", "bob-legacy", "bob@src.test", HASH, "inherit"), + (CAROL, CAROL, "", "", "inherit"), # revoked: no password, email or link + ("frank", "frank", "frank@src.test", HASH, "inherit"), + ("team", "alice", "", "", "inherit"), + # Public on the source: in an org that serves others a self-join waits for approval. + ("team-legacy", "alice-legacy", "", "", "approval"), + ] + grants = await ch.query_all( + "SELECT namespace, subject, role FROM loom.namespace_grants FINAL " + "WHERE org = {org:String} AND revoked_at IS NULL AND status = 'active' " + "ORDER BY namespace, subject" + SEQ, + params={"org": dst_org}, + ) + assert [tuple(r.values()) for r in grants if r["namespace"] == "team-legacy"] == [ + ("team-legacy", "alice-legacy", "writer"), + ("team-legacy", "bob-legacy", "viewer"), + ] + # The merge carries erin's grant past her request and frank's past an email of his no + # one verified; dave's revocation stands. + assert {r["subject"]: r["role"] for r in grants if r["namespace"] == "team"} == { + "bob": "viewer", + "erin@src.test": "viewer", + "frank": "writer", + "frank@src.test": "writer", + "test-suite": "admin", + } + for table in CARRIED: + both = [ + await ch.query_all( + f"SELECT * EXCEPT (org, namespace) FROM loom.{table} " + "WHERE org = {org:String} AND namespace = {ns:String}" + SEQ, + params={"org": org, "ns": ns}, + ) + for org, ns in ((src_org, "team"), (dst_org, "team-legacy")) + ] + if by := {"namespace_policies": "created_by", "namespace_guides": "updated_by"}.get(table): + # Written by the minted token's subject, whom the plan drops: by no one there. + assert {r.pop(by).partition(":")[2] for r in both[0]} == {"test-suite"}, table + assert {r.pop(by) for r in both[1]} == {""}, table + assert both[0] and both[0] == both[1], table + found = { + uri: dst.op("knowledge.get", namespace="team-legacy", source_uri=uri) + for uri in ("synced.md", "retiring.md", "kept.md", "meeting.md") + } + assert {uri: got["found"] for uri, got in found.items()} == { + "synced.md": False, + "retiring.md": False, + "kept.md": True, + "meeting.md": True, + } + assert found["meeting.md"]["content"] == found["kept.md"]["content"] == doc["content"] + left_behind = Bundle.open(bundle).manifest["left_behind"] + assert [(r["kind"], r["n"]) for r in left_behind["rows"]] == [("documents_of_sources", 2)] + assert [s["name"] for s in left_behind["knowledge_sources"]] == ["drive"] + assert await resolve_identity_for_email(f"{CAROL}@src.test") is None + state = await _state(ch, dst) + created = ("alice-legacy", "bob-legacy", CAROL, "team-legacy") + # Each on the namespaces the import created that it reaches: the merged team is the + # target's own. + assert [b[:3] for b in state["blacklist"]] == sorted( + [("team-legacy", "SECRET-", "namespace")] + + [(n, pattern, "namespace") for n in created for pattern in TOKENS] + ) + + audit = ( + "SELECT event_type, namespace, JSONExtractString(subject, 'name') AS name, " + "JSONExtractString(subject, 'plan') AS plan FROM loom.audit_log " + "WHERE org = {org:String} AND event_type LIKE 'instance.import%' " + "ORDER BY event_type, name" + SEQ + ) + landed = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] + assert landed == [ + *[("instance.import", n, n, digest[1]) for n in created], + *[("instance.import.done", n, n, digest[1]) for n in sorted((*created, "team"))], + ("instance.import.merge", "team", "team", digest[1]), + ] + + # Resumed part way: every landing recorded, none finished. + await ch.execute( + "ALTER TABLE loom.audit_log DELETE WHERE org = {org:String} " + "AND event_type = 'instance.import.done' SETTINGS mutations_sync = 2", + {"org": dst_org}, + ) + resumed = _cli("import", "--bundle", str(bundle), *plan) + assert resumed.returncode == 0, resumed.stdout + resumed.stderr + assert await _state(ch, dst) == state + again = _cli("import", "--bundle", str(bundle), *plan) + assert again.returncode == 0, again.stdout + again.stderr + assert await _state(ch, dst) == state + assert [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] == landed + dst.set("team", "token", TOKEN) # the target's owners are not refused by the source + + +async def test_a_namespace_bundle_leaves_its_accounts_content_to_a_later_one( + ch: Any, control_plane_url: str, mint_test_token: Any, tmp_path: Path +) -> None: + """A `--namespace` export brings the accounts its grants name as rows only, and counts + what it leaves behind of that namespace only. Their landings stay unfinished, so a + later export of the whole org brings their own content, and an account single sign-on + made, with its link.""" + src_org, dst_org = unique_org("insrc"), unique_org("indst") + src = _Api(control_plane_url, mint_test_token(org=src_org, roles=["admin"]), src_org) + dst = _Api(control_plane_url, mint_test_token(org=dst_org, roles=["admin"]), dst_org) + await _account(ch, src_org, "dana", f"dana@{src_org}.test") + # Single sign-on made fay on the source, with a link. + fay, email = f"u-fay-{secrets.token_hex(4)}", f"fay@{src_org}.test" + await _account(ch, src_org, fay, email, sso=True) + await _link(ch, src_org, fay, email, linked=True) + src.op("namespace.register", namespace="team", owner_email="dana") + src.op("grants.create", namespace="team", subject="dana", role="writer") + # Landed claimable by the first bundle, then revoked on the source. It has no email: on + # this one deployment the source's account would sign in with it too. + gus = f"gus-{secrets.token_hex(4)}" + await _account(ch, src_org, gus, "") + src.op("grants.create", namespace="team", subject=gus, role="viewer") + src.set("team", "deploys", "the team's deploy rule") + src.set("dana", "standup", "dana's own standup note") + src.op("conversation.set_logging", namespace="dana", enabled=True) + src.op( + "conversation.append", + namespace="dana", + agent="a", + thread_id="t1", + role="user", + content="hi", + ) + one, whole = tmp_path / "team-bundle", tmp_path / "org-bundle" + for out, only in ((one, ["--namespace", "team"]), (whole, [])): + done = _cli("export", "--org", src_org, *only, "--out", str(out)) + assert done.returncode == 0, done.stderr + await _account(ch, src_org, "dana", f"dana@{src_org}.test", active=False) + await _account(ch, src_org, fay, email, active=False, sso=True) + await _link(ch, src_org, fay, email, linked=False) + left = [Bundle.open(b).manifest["left_behind"]["rows"] for b in (one, whole)] + assert left[0] == [] and [(r["kind"], r["n"]) for r in left[1]] == [("conversations", 1)] + + mapping = tmp_path / "map.yaml" + rules = {"orgs": {src_org: dst_org}, "subjects": {f"{src_org}/test-suite": "drop"}} + mapping.write_text(yaml.safe_dump(rules | {"sso_same_issuer": True})) + audit = ( + "SELECT event_type, namespace FROM loom.audit_log WHERE org = {org:String} " + "AND event_type LIKE 'instance.import%' ORDER BY event_type, namespace" + SEQ + ) + + def imported(bundle: Path) -> str: + dry = _cli("import", "--bundle", str(bundle), "--map", str(mapping)) + assert dry.returncode == 0, dry.stdout + dry.stderr + digest = re.search(r"^plan (\w+)$", dry.stdout, re.M) + assert digest, dry.stdout + run = _cli( + "import", + "--bundle", + str(bundle), + "--map", + str(mapping), + "--apply", + "--expect-plan", + digest[1], + ) + assert run.returncode == 0, run.stdout + run.stderr + return dry.stdout + + plan = imported(one) + assert "namespace " + src_org + "/dana → create " + dst_org + "/dana (account, claim) " in plan + assert "(its row only" in plan + assert dst.get("team", "deploys")["found"] and not dst.get("dana", "standup")["found"] + rows = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] + assert rows == [ + ("instance.import", "dana"), + ("instance.import", gus), + ("instance.import", "team"), + ("instance.import.done", "team"), + ] + team = dst.get("team", "deploys")["version"] + + # The source revokes gus since: a plan refuses until the target revokes gus too. Source + # and target share this deployment, so the source's revocation is taken back before + # that plan reads the target. + later = tmp_path / "revoked-bundle" + expires = datetime.now(UTC).replace(tzinfo=None) + timedelta(days=30) + await ch.insert("loom.revoked_tokens", [{"jti": gus, "expires_at": expires, "reason": "t"}]) + done = _cli("export", "--org", src_org, "--out", str(later)) + assert done.returncode == 0, done.stderr + assert {r["subject"] for r in Bundle.open(later).records("revoked")} == {gus} + lapsed = datetime.now(UTC).replace(tzinfo=None) - timedelta(days=1) + await ch.insert("loom.revoked_tokens", [{"jti": gus, "expires_at": lapsed, "reason": "t"}]) + refused = _cli("import", "--bundle", str(later), "--map", str(mapping)) + assert refused.returncode == 1, refused.stdout + refused.stderr + assert f"{dst_org}/{gus} still signs in" in refused.stdout, refused.stdout + + plan = imported(whole) + assert "(its row only" not in plan + team_line = next(ln for ln in plan.splitlines() if f"namespace {src_org}/team →" in ln) + assert "(an earlier run finished it: skipped)" in team_line, plan + assert dst.get("dana", "standup")["value"] == "dana's own standup note" + assert dst.get("team", "deploys")["version"] == team # finished: left alone + rows = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] + assert rows == [ + ("instance.import", "dana"), + ("instance.import", gus), + ("instance.import", "team"), + ("instance.import", fay), + ("instance.import.done", "dana"), + ("instance.import.done", gus), + ("instance.import.done", "team"), + ("instance.import.done", fay), + ] + # fay lands with her link, and without JIT's tag: the target never finishes the + # source's provisioning of her. + p = {"org": dst_org, "ns": fay} + row = await ch.query_one( + "SELECT password_hash, contact_email, tags FROM loom.namespaces FINAL " + "WHERE org = {org:String} AND namespace = {ns:String}" + SEQ, + params=p, + ) + assert row is not None and tuple(row.values()) == ("", email, []) + link = await ch.query_one( + "SELECT email, linked, linked_by, hosted_domain, issuer FROM loom.sso_links FINAL " + "WHERE org = {org:String} AND namespace = {ns:String}" + SEQ, + params=p, + ) + assert link is not None + assert tuple(link.values()) == (email, 1, "process:cli:instance", "", "https://idp.test") + who = await resolve_identity_for_email(email) + assert who is not None and who[1] == dst_org diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index f378a3ecbf..f9ad12f2ef 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -1,8 +1,8 @@ { "loom": [ - "usage: loom [-h] [--version] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers} ...", + "usage: loom [-h] [--version] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,instance,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers} ...", "Loom — vendor-neutral agent memory plane on ClickHouse.", - "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub or Linear tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account. pointers Print the code pointer block for the task prompt on standard input.", + "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,instance,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. instance Move orgs between deployments: export a bundle on the source, import it on the target by a reviewed plan. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub or Linear tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account. pointers Print the code pointer block for the task prompt on standard input.", "options: -h, --help show this help message and exit --version show program's version number and exit" ], "loom code": [ @@ -311,6 +311,19 @@ "usage: loom sql-access list [-h]", "options: -h, --help show this help message and exit" ], + "loom instance": [ + "usage: loom instance [-h] {export,import} ...", + "positional arguments: {export,import} export Write the selected orgs' namespaces, accounts, grants, memories and documents into a new bundle directory. Reads only. import Plan a bundle's import against this deployment and print it; with --apply and the plan's digest, write it.", + "options: -h, --help show this help message and exit" + ], + "loom instance export": [ + "usage: loom instance export [-h] --org ORGS [--namespace NAMESPACES] --out OUT", + "options: -h, --help show this help message and exit --org ORGS An org to export (repeat) --namespace NAMESPACES Export only this namespace, with the accounts its grants name (repeat; default: every memory namespace of the orgs) --out OUT A new or empty directory" + ], + "loom instance import": [ + "usage: loom instance import [-h] --bundle BUNDLE [--map MAP] [--expect-plan EXPECT_PLAN] [--apply | --dry-run]", + "options: -h, --help show this help message and exit --bundle BUNDLE The bundle directory --map MAP The YAML map of orgs, namespaces and subjects --expect-plan EXPECT_PLAN The digest the dry run printed: --apply refuses a plan that changed since --apply write the plan (default: dry run) --dry-run report what --apply would write, write nothing (the default)" + ], "loom reembed": [ "usage: loom reembed [-h] [--org ORG] [--namespace NAMESPACE] [--batch-size BATCH_SIZE] [--in-database NAMED_COLLECTION] [--dry-run] [--delete-old] [--key-only] [--resume RESUME]", "options: -h, --help show this help message and exit --org ORG Limit to one org --namespace NAMESPACE Limit to one namespace --batch-size BATCH_SIZE Rows read per page (default: 200) --in-database NAMED_COLLECTION Re-embed inside ClickHouse with aiEmbed (ClickHouse 26.7+): the named collection holding provider/endpoint/api_key. One INSERT … SELECT per table instead of a Python loop; refuses when an embed-text switch is on, and with a customer or identity header set or the inference gateway required (ClickHouse's calls name no one and skip the gateway check). --dry-run Count off-model rows without writing --delete-old Delete off-model rows after re-embedding, except in the orgs the run left for later --key-only Rebuild only the key-axis vectors in scope, from the current key-axis text; value vectors are kept --resume RESUME Continue after the row a previous run's `resume:` line names (the tables before it are done; it carries the orgs --delete-old keeps)" diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index f3edf95e22..40c66820c7 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -8477,6 +8477,310 @@ } ] }, + "instance": { + "prog": "loom instance", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": {}, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [ + "subcommand" + ] + }, + { + "title": "options", + "description": null, + "dests": [ + "help" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [], + "dest": "subcommand", + "action": "_SubParsersAction", + "default": null, + "const": null, + "choices": null, + "nargs": "A...", + "type": null, + "required": true, + "help": null, + "metavar": null, + "subcommands": { + "export": { + "prog": "loom instance export", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": { + "func": "server.cli.instance:_cmd_export" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "orgs", + "namespaces", + "out" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "orgs", + "action": "_AppendAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "An org to export (repeat)", + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespaces", + "action": "_AppendAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Export only this namespace, with the accounts its grants name (repeat; default: every memory namespace of the orgs)", + "metavar": null + }, + { + "option_strings": [ + "--out" + ], + "dest": "out", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": "pathlib:Path", + "required": true, + "help": "A new or empty directory", + "metavar": null + } + ] + }, + "import": { + "prog": "loom instance import", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": { + "dry_run": true, + "apply_gated": false, + "func": "server.cli.instance:_cmd_import" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "bundle", + "map", + "expect_plan", + "dry_run", + "dry_run" + ] + } + ], + "mutually_exclusive": [ + { + "required": false, + "dests": [ + "dry_run", + "dry_run" + ] + } + ], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--bundle" + ], + "dest": "bundle", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": "pathlib:Path", + "required": true, + "help": "The bundle directory", + "metavar": null + }, + { + "option_strings": [ + "--map" + ], + "dest": "map", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": "pathlib:Path", + "required": false, + "help": "The YAML map of orgs, namespaces and subjects", + "metavar": null + }, + { + "option_strings": [ + "--expect-plan" + ], + "dest": "expect_plan", + "action": "_StoreAction", + "default": "", + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "The digest the dry run printed: --apply refuses a plan that changed since", + "metavar": null + }, + { + "option_strings": [ + "--apply" + ], + "dest": "dry_run", + "action": "_StoreFalseAction", + "default": true, + "const": false, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "write the plan (default: dry run)", + "metavar": null + }, + { + "option_strings": [ + "--dry-run" + ], + "dest": "dry_run", + "action": "_StoreTrueAction", + "default": true, + "const": true, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "report what --apply would write, write nothing (the default)", + "metavar": null + } + ] + } + }, + "aliases_of": { + "export": "loom instance export", + "import": "loom instance import" + }, + "choices_help": [ + { + "dest": "export", + "help": "Write the selected orgs' namespaces, accounts, grants, memories and documents into a new bundle directory. Reads only.", + "metavar": "export" + }, + { + "dest": "import", + "help": "Plan a bundle's import against this deployment and print it; with --apply and the plan's digest, write it.", + "metavar": "import" + } + ] + } + ] + }, "reembed": { "prog": "loom reembed", "usage": null, @@ -18295,6 +18599,7 @@ "provider-lock": "loom provider-lock", "export-analytics": "loom export-analytics", "sql-access": "loom sql-access", + "instance": "loom instance", "reembed": "loom reembed", "reextract": "loom reextract", "deploy-delta": "loom deploy-delta", @@ -18435,6 +18740,11 @@ "help": "Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views.", "metavar": "sql-access" }, + { + "dest": "instance", + "help": "Move orgs between deployments: export a bundle on the source, import it on the target by a reviewed plan.", + "metavar": "instance" + }, { "dest": "reembed", "help": "Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them.", diff --git a/tests/unit/test_cli_apply_default.py b/tests/unit/test_cli_apply_default.py index ebb268a174..b5953792c5 100644 --- a/tests/unit/test_cli_apply_default.py +++ b/tests/unit/test_cli_apply_default.py @@ -22,6 +22,7 @@ ["sensitivity-sweep", "--org", "o"], ["demote-activity-narration", "--org", "o", "--namespace", "n"], ["namespaces-adopt", "--org", "o", "--owner", "u"], + ["instance", "import", "--bundle", "b"], ] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py new file mode 100644 index 0000000000..1806094882 --- /dev/null +++ b/tests/unit/test_instance_consolidation.py @@ -0,0 +1,1445 @@ +"""`loom instance`: the bundle refuses what its export did not write, and the plan never +lands a source name or subject on someone else's.""" + +from __future__ import annotations + +import gzip +import stat +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pytest + +from server.cli.instance_bundle import ORIGINALS, Bundle, BundleError, BundleWriter +from server.cli.instance_export import select_namespaces +from server.cli.instance_import import refusals +from server.cli.instance_plan import MapError, NsDecision, TargetOrg, parse_map, plan +from server.core.naming import new_mirror_name +from server.memory.app.blacklist_guard import match_value +from tests.unit.clickhouse_local import CLICKHOUSE, ddl, run + +SOURCE = "dep-1" +EMPTY = TargetOrg({}, frozenset()) +# A source row's created_at as the bundle holds it; its landed row reads back naive UTC. +AT = "2025-03-04T05:06:07Z" +LANDED = {"kind": "memory", "created_at": datetime(2025, 3, 4, 5, 6, 7)} + + +def _account(org: str, name: str, email: str) -> dict[str, Any]: + return { + "org": org, + "namespace": name, + "owner_email": name, + "contact_email": email, + "password_hash": "$argon2id$x", + "created_at": AT, + } + + +def _ns(org: str, name: str, owner: str) -> dict[str, Any]: + return {"org": org, "namespace": name, "owner_email": owner, "created_at": AT} + + +def _plan( + rows: list[dict[str, Any]], + *, + subjects: dict[str, set[str]] | set[str] | None = None, + target: TargetOrg | None = None, + targets: dict[str, TargetOrg] | None = None, + rules: Any = None, + signs_in: dict[str, list[str]] | None = None, + revoked: set[str] | None = None, + links: dict[str, dict[str, list[str]]] | None = None, + bundle: str = "b1", + by_namespace: dict[str, dict[str, dict[str, set[str]]]] | None = None, +) -> Any: + """`subjects` are grant subjects and end users of every namespace of their org; + `by_namespace` names them per namespace and kind.""" + orgs = sorted({r["org"] for r in rows}) + by_org = subjects if isinstance(subjects, dict) else {"acme": subjects or set()} + every = { + o: { + r["namespace"]: { + "grant": {s for s in subs if not s.startswith("user:")}, + "user": {s for s in subs if s.startswith("user:")}, + } + for r in rows + if r["org"] == o + } + for o, subs in by_org.items() + } + return plan( + bundle=bundle, + source=SOURCE, + rules=parse_map(rules), + namespace_rows=rows, + selected={o: sorted(r["namespace"] for r in rows if r["org"] == o) for o in orgs}, + named=every if by_namespace is None else by_namespace, + links=links or {}, + revoked=revoked or set(), + targets=targets or {"acme": target or EMPTY}, + signs_in=signs_in or {}, + ) + + +def test_bundle_round_trip_and_tamper(tmp_path: Path) -> None: + out = tmp_path / "b" + w = BundleWriter(out) + with w.section("memories") as sink: + sink.write({"memory_id": "m1", "value": "ü"}) + digest = w.original(b"bytes") + w.finish({"source": {"deployment_id": SOURCE}}) + b = Bundle.open(out) + assert list(b.records("memories")) == [{"memory_id": "m1", "value": "ü"}] + assert list(b.records("absent")) == [] + assert b.rows("memories") == 1 and b.original(digest) == b"bytes" + # It holds password hashes: owner-only whatever the umask. + for f in [out, *out.rglob("*")]: + assert stat.S_IMODE(f.stat().st_mode) == (0o700 if f.is_dir() else 0o600), f + with pytest.raises(BundleError, match="not an empty directory"): + BundleWriter(out) + with pytest.raises(BundleError, match="not an empty directory"): + BundleWriter(out / "manifest.json") + + (out / "originals" / digest).write_bytes(b"other") + with pytest.raises(BundleError, match="differs from its name"): + b.original(digest) + with gzip.open(out / "memories.jsonl.gz", "wb") as fh: + fh.write(b'{"memory_id":"m2"}\n') + with pytest.raises(BundleError, match="differs from the manifest"): + Bundle.open(out) + (out / "manifest.json").unlink() + with pytest.raises(BundleError, match="did not finish"): + Bundle.open(out) + + +def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: + """The target's alice is someone else: the source's alice and her grants land on the + handle the map names, never on the target's alice.""" + rows = [_account("acme", "alice", "alice@x"), _ns("acme", "team", "alice")] + target = TargetOrg({"alice": {"kind": "memory"}}, frozenset({"alice"})) + refused = _plan(rows, subjects={"alice"}, target=target) + assert any("already has namespace 'alice'" in p for p in refused.problems) + assert refused.proposals == {"subjects": {"acme/alice": {"claim": "alice-legacy"}}} + + ok = _plan(rows, subjects={"alice"}, target=target, rules=refused.proposals) + assert ok.problems == [] + assert ok.subject_map()[("acme", "alice")] == "alice-legacy" + assert {(d.source, d.target, d.account) for d in ok.namespaces} == { + ("alice", "alice-legacy", "claim"), + ("team", "team", ""), + } + landed = TargetOrg( + {**target.namespaces, "alice-legacy": LANDED, "team": LANDED}, + target.subjects | {"alice-legacy"}, + landed=dict.fromkeys( + [("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")], AT + ), + ) + again = _plan( + rows, + subjects={"alice"}, + target=landed, + rules=refused.proposals, + signs_in={"alice@x": ["acme/alice-legacy"]}, + ) + assert again.problems == [] and again.digest == ok.digest + + +def test_collisions_and_unknown_subjects_refuse_the_plan() -> None: + rows = [_ns("acme", "team", "ci-bot"), _ns("acme", "u-ann-ab12cd34", "x")] + target = TargetOrg({"team": {"kind": "memory"}}, frozenset()) + subjects = {"ci-bot", "group:eng", "agent:helper", "everyone", "sa:ci", "bob@x"} + p = _plan(rows, subjects=subjects, target=target) + assert p.proposals["namespaces"]["acme/team"] == {"rename": "team-legacy"} + assert "acme/u-ann-ab12cd34" in p.proposals["namespaces"] # the form JIT gives a person + # Groups, agents and everyone hold grants on collections only: no such grant moves. + assert p.proposals["subjects"] == dict.fromkeys( + ("acme/ci-bot", "acme/group:eng", "acme/agent:helper", "acme/everyone"), "drop" + ) + decided = {s.subject: s.action for s in p.subjects} + assert decided == {"sa:ci": "drop", "bob@x": "keep"} + # `keep` passes the same checks, and refuses a service account, whose token stays. + keep = {"subjects": dict.fromkeys([*p.proposals["subjects"], "acme/sa:ci"], "keep")} + again = _plan(rows, subjects=subjects, target=target, rules=keep) + assert set(again.proposals["subjects"]) == {*p.proposals["subjects"], "acme/sa:ci"} + assert again.proposals["subjects"]["acme/sa:ci"] == "drop" + assert any("'sa:ci' is a service account" in x for x in again.problems), again.problems + assert "sa:ci" not in {s.subject for s in again.subjects} + + +def test_end_users_of_a_shared_target_org_need_the_map() -> None: + """`user:42` may name another person of a target org that serves others; in an org the + import alone lands in, it stays.""" + rows = [_ns("acme", "team", "x")] + rules = {"subjects": {"acme/x": "drop"}} + assert _plan(rows, subjects={"x", "user:42"}, rules=rules).problems == [] + shared = TargetOrg({"theirs": {"kind": "memory"}}, frozenset()) + p = _plan(rows, subjects={"x", "user:42"}, target=shared, rules=rules) + assert p.proposals["subjects"] == {"acme/user:42": "drop"} + rules["subjects"]["acme/user:42"] = "keep" + assert _plan(rows, subjects={"x", "user:42"}, target=shared, rules=rules).problems == [] + + +def test_a_skipped_namespace_needs_no_subject_decided() -> None: + """Its grants, owner and users move nowhere, so the map need not name them.""" + rows = [_ns("acme", "team", "x"), _ns("acme", "scratch", "x")] + shared = TargetOrg({"theirs": {"kind": "memory"}}, frozenset()) + by_namespace = { + "acme": { + "team": {"grant": {"x"}}, + "scratch": {"grant": {"group:eng"}, "owner": {"sa:ci"}, "user": {"user:42"}}, + } + } + rules: dict[str, Any] = {"subjects": {"acme/x": "drop"}} + p = _plan(rows, target=shared, rules=rules, by_namespace=by_namespace) + assert p.proposals["subjects"] == {"acme/group:eng": "drop", "acme/user:42": "drop"} + rules["namespaces"] = {"acme/scratch": "skip"} + assert _plan(rows, target=shared, rules=rules, by_namespace=by_namespace).problems == [] + + +def test_a_merge_needs_its_end_users_decided_and_its_grant_subjects_when_it_carries_them() -> None: + """The target keeps its own owner, and a merge without its grants writes none.""" + rows = [_ns("acme", "team", "carol@x")] + target = TargetOrg({"t": {"kind": "memory"}}, frozenset()) + by_namespace = { + "acme": {"team": {"grant": {"group:eng"}, "owner": {"carol@x"}, "user": {"user:42"}}} + } + rules: dict[str, Any] = {"namespaces": {"acme/team": {"merge": "t"}}} + p = _plan(rows, target=target, rules=rules, by_namespace=by_namespace) + assert p.proposals == {"subjects": {"acme/user:42": "drop"}}, p.problems + rules["namespaces"]["acme/team"]["grants"] = True + p = _plan(rows, target=target, rules=rules, by_namespace=by_namespace) + assert p.proposals == {"subjects": {"acme/group:eng": "drop", "acme/user:42": "drop"}} + + +def test_the_plan_says_who_owns_a_namespace_whose_owner_does_not_land( + capsys: pytest.CaptureFixture[str], +) -> None: + from dataclasses import replace + from types import SimpleNamespace + + from server.cli import instance + + rows = [_ns("acme", "team", "sa:ci"), _ns("acme", "notes", "bob@x")] + p = _plan(rows, subjects={"sa:ci", "bob@x"}) + bundle = SimpleNamespace( + manifest={"content": {"acme": ["team", "notes"]}, "source": {"deployment_id": SOURCE}}, + records=lambda name: rows if name == "namespaces" else [], + rows=lambda name: 0, + ) + instance._print_plan(bundle, p, {"acme": EMPTY}) + lines = { + ln.split()[1]: ln for ln in capsys.readouterr().out.splitlines() if " namespace " in ln + } + assert lines["acme/team"].endswith("(owned by the import: no owner lands)"), lines + assert "owned by the import" not in lines["acme/notes"] + for owner, ownerless in (("process:cli:instance", True), ("carol", False)): + resumed = TargetOrg({"team": {"owner_email": owner}}, frozenset()) # its earlier row + instance._print_plan(bundle, p, {"acme": resumed}) + assert ("owned by the import" in capsys.readouterr().out) is ownerless, owner + finished = TargetOrg({}, frozenset(), done=frozenset({("team", f"{SOURCE}/acme/team")})) + p.namespaces = [replace(d, approval=True) for d in p.namespaces] + instance._print_plan(bundle, p, {"acme": finished}) + out = capsys.readouterr().out + assert "finished it: skipped)\n" in out and "owned by the import" not in out, out + assert [ln.split()[1] for ln in out.splitlines() if "self-join" in ln] == ["acme/notes"] + + +def test_a_subject_the_source_revoked_maps_onto_no_one() -> None: + """A revocation names a token subject or an email by itself and an end user by its + org's key. Mapping one onto a target subject is refused, and so is keeping an end user + the source revoked without saying so: the target does not carry its revocation.""" + from server.cli.instance_plan import revoked_subject + + revoked = {"bob", "acme/user:42"} + assert revoked_subject(revoked, "acme", "Bob") and revoked_subject(revoked, "acme", "user:42") + assert not revoked_subject(revoked, "other", "user:42") # another org's end user + assert not revoked_subject(revoked, "acme", "user:7") + rows = [_ns("acme", "team", "x")] + subjects = {"x", "bob", "user:42"} + target = TargetOrg({}, frozenset({"robert"})) + rules = {"subjects": {"acme/x": "drop", "acme/bob": "robert", "acme/user:42": "user:99"}} + p = _plan(rows, subjects=subjects, target=target, rules=rules, revoked=revoked) + assert sorted(x.split(": ", 2)[2] for x in p.problems) == [ + "the source revoked 'bob'; mapping it gives its content to 'robert', whose access " + "stays: drop it", + "the source revoked 'user:42'; mapping it gives its content to 'user:99', whose " + "access stays: keep or drop it", + ], p.problems + rules["subjects"] |= {"acme/bob": "drop"} + del rules["subjects"]["acme/user:42"] + p = _plan(rows, subjects=subjects, target=target, rules=rules, revoked=revoked) + assert p.proposals == {"subjects": {"acme/user:42": "drop"}}, p.problems + rules["subjects"]["acme/user:42"] = "keep" + p = _plan(rows, subjects=subjects, target=target, rules=rules, revoked=revoked) + assert p.problems == [] + assert [(s.subject, s.action, s.note) for s in p.subjects if s.subject == "user:42"] == [ + ("user:42", "keep", "revoked on the source: its grants stay behind") + ] + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_the_export_reads_the_revocation_of_every_subject_it_brings() -> None: + """Each namespace's name and owner, each grant's subject and each end user under its + org's key: one the source revoked outright reaches the bundle, a lapsed revocation and + a subject the bundle does not bring do not.""" + from server.cli.instance_export import REVOKED, _revocation_keys + + rows = [ + {"namespace": "Alice", "owner_email": "alice"}, + {"namespace": "team", "owner_email": "Owner"}, + ] + grants = [{"subject": "Bob"}, {"subject": "dave@x"}] + keys = _revocation_keys(rows, grants, {("acme", "U42"), ("acme", "7")}) + assert keys == ["acme/user:7", "acme/user:u42", "alice", "bob", "dave@x", "owner", "team"] + setup = [ + ddl("revoked_tokens"), + "INSERT INTO loom.revoked_tokens (jti, expires_at, reason) VALUES " + "('Bob', now() + 3600, 'op'), ('acme/user:7', now() + 3600, 'op'), " + "('owner', now() - 3600, 'lapsed'), ('carl', now() + 3600, 'op')", + ] + revoked = run(setup, REVOKED, {"lowered": keys}) + assert sorted(r["subject"] for r in revoked) == ["acme/user:7", "bob"] + + +def test_end_users_map_to_end_users_and_never_land_as_one() -> None: + rows = [_ns("acme", "team", "x")] + rules = {"subjects": {"acme/x": "drop", "acme/user:a": "user:c", "acme/user:b": "user:c"}} + p = _plan(rows, subjects={"x", "user:a", "user:b"}, rules=rules) + assert any("both land as 'user:c'" in s for s in p.problems) + rules["subjects"]["acme/user:b"] = "user:d" # an end user the target has not seen yet + assert _plan(rows, subjects={"x", "user:a", "user:b"}, rules=rules).problems == [] + rules["subjects"]["acme/user:b"] = "x" + target = TargetOrg({}, frozenset({"x"})) + p = _plan(rows, subjects={"x", "user:a", "user:b"}, target=target, rules=rules) + assert any("an end user maps to an end user" in s for s in p.problems) + for nobody in ("user:-", "user:"): # beside the rows with no user + rules["subjects"]["acme/user:b"] = nobody + p = _plan(rows, subjects={"x", "user:a", "user:b"}, rules=rules) + assert any("an end user maps to an end user" in s for s in p.problems), nobody + rules["subjects"] |= {"acme/user:b": "user:d", "acme/x": "user:9"} + p = _plan(rows, subjects={"x", "user:a", "user:b"}, rules=rules) + assert any("only an end user maps to an end user" in s for s in p.problems), p.problems + + +def test_a_namespace_anyone_could_join_asks_for_approval_in_a_shared_org() -> None: + rows = [{**_ns("acme", "team", "x"), "visibility": "public"}, _ns("acme", "notes", "x")] + rules = {"subjects": {"acme/x": "drop"}} + alone = _plan(rows, subjects={"x"}, rules=rules) + assert not any(d.approval for d in alone.namespaces) + shared = TargetOrg({"theirs": {"kind": "memory"}}, frozenset()) + p = _plan(rows, subjects={"x"}, target=shared, rules=rules) + assert {d.source: d.approval for d in p.namespaces} == {"team": True, "notes": False} + # A merge lands in the target's own namespace: it never makes the org this import's. + merged = TargetOrg( + {"theirs": {"kind": "memory"}}, + frozenset(), + merged=frozenset({("theirs", f"{SOURCE}/acme/old")}), + ) + p = _plan(rows, subjects={"x", "user:7"}, target=merged, rules=rules) + assert p.proposals["subjects"] == {"acme/user:7": "drop"} + # A name this import landed counts as its own only while the row is the one it wrote. + marks = frozenset({("notes", f"{SOURCE}/acme/notes")}) + for row, opens in ( + ({"kind": "memory", "created_at": datetime(2026, 1, 1)}, True), + (LANDED, False), + ): + p = _plan( + rows, + subjects={"x"}, + target=TargetOrg({"notes": row}, frozenset(), landed=dict.fromkeys(marks, AT)), + rules=rules, + ) + assert {d.source: d.approval for d in p.namespaces}["team"] is opens + # So is one this bundle does not bring, an account an earlier `--namespace` bundle + # landed as a row: its audit row records the created_at it was written with. + earlier = {("alice", f"{SOURCE}/acme/alice"): AT} + elsewhere = TargetOrg({"alice": LANDED}, frozenset(), earlier) + p = _plan(rows, subjects={"x"}, target=elsewhere, rules=rules) + assert p.problems == [] and not any(d.approval for d in p.namespaces) + + +def test_the_digest_names_whether_sign_on_links_land() -> None: + rows = [_account("acme", "alice", "a@x")] + off = _plan(rows, links={"acme": {"alice": ["a@x"]}}) + on = _plan(rows, links={"acme": {"alice": ["a@x"]}}, rules={"sso_same_issuer": True}) + assert off.problems == on.problems == [] and off.digest != on.digest + + +def test_two_source_orgs_into_one_target_org() -> None: + """A name two source orgs both bring to one target org refuses the plan, and each + org's end users may be the other's people.""" + rows = [_ns("a", "team", "x"), _ns("b", "team", "x")] + rules = {"orgs": {"a": "t", "b": "t"}, "subjects": {"a/x": "drop", "b/x": "drop"}} + p = _plan(rows, subjects={"a": {"x", "user:7"}, "b": {"x"}}, targets={"t": EMPTY}, rules=rules) + assert "b: team and a/team both land on namespace 'team'" in p.problems + assert p.proposals["subjects"] == {"a/user:7": "drop"} + + +def test_an_email_another_account_signs_in_with_refuses_the_claim() -> None: + rows = [_account("acme", "bob", "Bob@X")] + p = _plan(rows, signs_in={"bob@x": ["other/bob"]}) + assert p.proposals == {"subjects": {"acme/bob": "drop"}} # another org: never mapped + # Nothing proves robert's contact email: the proposal hands bob's content to no one. + p = _plan(rows, signs_in={"bob@x": ["acme/robert"]}) + assert p.proposals == {"subjects": {"acme/bob": "drop"}} and "'acme/robert'" in p.problems[0] + # Its single sign-on links land with it under the same issuer: each email counts. + links = {"acme": {"bob": ["bob.old@x"]}} + p = _plan(rows, signs_in={"bob.old@x": ["other/b"]}, links=links) + assert p.problems == [] + p = _plan( + rows, signs_in={"bob.old@x": ["other/b"]}, links=links, rules={"sso_same_issuer": True} + ) + assert p.proposals == {"subjects": {"acme/bob": "drop"}} + + +def test_a_resumed_run_plans_the_same_digest() -> None: + rows = [_account("acme", "alice", "alice@x"), _ns("acme", "team", "alice")] + subjects = {"alice", "user:7"} + first = _plan(rows, subjects=subjects) + assert first.problems == [] + marks = frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}) + names = {"alice": LANDED, "team": LANDED} + landed = TargetOrg(names, frozenset({"alice"}), landed=dict.fromkeys(marks, AT)) + again = _plan(rows, subjects=subjects, target=landed, signs_in={"alice@x": ["acme/alice"]}) + assert again.problems == [] and again.digest == first.digest + other = _plan(rows, subjects=subjects, target=TargetOrg(landed.namespaces, landed.subjects)) + assert other.problems # the same names, not landed by this source + # A run stopped between its audit row and the namespace row; someone took the name since. + taken = TargetOrg( + {**names, "team": {"kind": "memory", "created_at": datetime(2026, 1, 1)}}, + landed.subjects, + landed=dict.fromkeys(marks, AT), + ) + # Its row is no longer the import's, so the org serves others: its end users are asked. + renamed = { + "namespaces": {"acme/team": {"rename": "team-legacy"}}, + "subjects": {"acme/user:7": "drop"}, + } + p = _plan(rows, subjects=subjects, target=taken, signs_in={"alice@x": ["acme/alice"]}) + assert p.proposals == renamed + deleted = TargetOrg( + {**names, "team": {**LANDED, "active": False}}, + landed.subjects, + landed=dict.fromkeys(marks, AT), + ) + p = _plan(rows, subjects=subjects, target=deleted, signs_in={"alice@x": ["acme/alice"]}) + assert p.proposals == renamed + # Someone signed up as alice since, with her email: it signs in to their account now. + signed_up = TargetOrg( + {**names, "alice": {"kind": "memory", "created_at": datetime(2026, 1, 1)}}, + landed.subjects, + landed=dict.fromkeys(marks, AT), + ) + p = _plan(rows, subjects=subjects, target=signed_up, signs_in={"alice@x": ["acme/alice"]}) + assert p.proposals == {"subjects": {"acme/alice": "drop", "acme/user:7": "drop"}} + # The landing is still the import's, but under another handle than the map's now. + moved = {"acme/alice": {"claim": "alice-2"}} + p = _plan( + rows, + subjects=subjects, + target=landed, + signs_in={"alice@x": ["acme/alice"]}, + rules={"subjects": moved}, + ) + assert any("already signs in to 'acme/alice'" in s for s in p.problems), p.problems + # A finished landing is the target's now, whatever its owners did to the row. + done = TargetOrg(taken.namespaces, landed.subjects, landed=dict.fromkeys(marks, AT), done=marks) + p = _plan(rows, subjects=subjects, target=done, signs_in={"alice@x": ["acme/alice"]}) + assert p.problems == [] + assert _plan(rows, subjects=subjects, bundle="b2").digest != first.digest + + +def test_names_and_flags_the_map_refuses() -> None: + p = _plan( + [_ns("acme", "team", "x"), _ns("acme", "notes", "x")], + subjects={"x"}, + rules={ + "namespaces": {"acme/team": {"merge": "t"}, "acme/notes": {"rename": "col-notes"}}, + "subjects": {"acme/x": "drop"}, + }, + ) + assert any("no memory namespace 't'" in s for s in p.problems) + assert any("'col-notes' is a reserved name" in s for s in p.problems) + with pytest.raises(MapError, match="namespaces.acme/team"): + parse_map({"namespaces": {"acme/team": {"rename": "a", "merge": "b"}}}) + with pytest.raises(MapError, match="unknown map keys"): + parse_map({"namespace": {}}) + with pytest.raises(MapError, match="sso_same_issuer: expected true or false"): + parse_map({"sso_same_issuer": "false"}) + with pytest.raises(MapError, match="grants: expected true or false"): + parse_map({"namespaces": {"acme/team": {"merge": "t", "grants": "no"}}}) + + +def test_one_namespace_brings_the_accounts_its_grants_name() -> None: + rows = [ + _account("acme", "alice", "a@x"), + _account("acme", "bob", "b@x"), + _account("acme", "carol", "c@x"), + _ns("acme", "team", "alice"), + _ns("acme", "acl-reviews", "alice"), # only a mirror's own form is reserved + _ns("acme", new_mirror_name(), "alice"), + _ns("acme", "col-shared", "alice"), + ] + grants = [{"org": "acme", "namespace": "team", "subject": "bob"}] + assert select_namespaces(rows, grants, ["team"]) == {"acme": ["alice", "bob", "team"]} + assert select_namespaces(rows, grants, None) == { + "acme": ["acl-reviews", "alice", "bob", "carol", "team"] + } + # A grant to an email brings the accounts naming it, by contact or link: single sign-on + # admits no one by an address a revoked or password account names. + rows.append(_account("acme", "dan", "dan@x")) + links = [{"org": "acme", "namespace": "dan", "email": "Dan.SSO@x"}] + by_email = [{"org": "acme", "namespace": "team", "subject": s} for s in ("C@x", "dan.sso@x")] + assert select_namespaces(rows, by_email, ["team"], links) == { + "acme": ["alice", "carol", "dan", "team"] + } + + +def test_an_account_the_source_revoked_lands_with_no_email_to_check() -> None: + """Its email never lands, so another account signing in with it is no collision; its + content may still move, but never onto a target account by a mapping.""" + rows = [_account("acme", "carol", "c@x")] + p = _plan(rows, signs_in={"c@x": ["acme/carla"]}, revoked={"carol"}) + assert p.problems == [] + assert [s.note for s in p.subjects] == ["revoked on the source: lands with no way to sign in"] + mapped = _plan( + rows, + target=TargetOrg({}, frozenset({"carla"})), + rules={"subjects": {"acme/carol": "carla"}}, + revoked={"carol"}, + ) + assert any("the source revoked 'carol'" in s for s in mapped.problems) + # No one signs in by its emails on the source; with none of them landing, a grant to + # one would admit whoever proves it on the target. + links = {"acme": {"carol": ["carol.sso@x"]}} + p = _plan(rows, subjects={"C@x", "carol.sso@x"}, revoked={"carol"}, links=links) + assert {s.subject: (s.action, s.note) for s in p.subjects if "@" in s.subject} == { + e: ("drop", "a revoked account's email") for e in ("C@x", "carol.sso@x") + } + mapped = _plan( + rows, + subjects={"c@x"}, + target=TargetOrg({}, frozenset({"carla"})), + rules={"subjects": {"acme/c@x": "carla"}}, + revoked={"carol"}, + ) + assert any("the source revoked 'c@x'" in s for s in mapped.problems) + + +def test_an_account_revoked_since_an_earlier_landing_is_revoked_on_the_target_first() -> None: + """An earlier bundle landed it as one that signs in: a later plan says so until the + target revokes it, whose revocation also ends what it signed in to since.""" + rows = [_account("acme", "carol", "c@x")] + marks = dict.fromkeys([("carol", f"{SOURCE}/acme/carol")], AT) + claimable = {"carol": {**LANDED, "password_hash": True}} + target = TargetOrg(claimable, frozenset({"carol"}), landed=marks) + p = _plan(rows, target=target, signs_in={"c@x": ["acme/carol"]}, revoked={"carol"}) + assert any("revoke-token --subject carol" in s for s in p.problems), p.problems + # Dropped now, or claimed under another handle: the earlier landing still signs in. + for rule in ("drop", {"claim": "carol-2"}): + p = _plan(rows, target=target, revoked={"carol"}, rules={"subjects": {"acme/carol": rule}}) + assert any("still signs in" in s for s in p.problems), (rule, p.problems) + mapped = TargetOrg(claimable, frozenset({"carol", "carla"}), landed=marks) + p = _plan(rows, target=mapped, revoked={"carol"}, rules={"subjects": {"acme/carol": "carla"}}) + assert any("still signs in" in s for s in p.problems), p.problems + # A finished landing the target's owners deleted signs nobody in. + gone = {"carol": {**LANDED, "password_hash": True, "active": False}} + deleted = TargetOrg(gone, frozenset({"carol"}), landed=marks, done=frozenset(marks)) + assert _plan(rows, target=deleted, revoked={"carol"}).problems == [] + revoked = TargetOrg(claimable, frozenset({"carol"}), landed=marks, revoked=frozenset({"carol"})) + assert _plan(rows, target=revoked, revoked={"carol"}).problems == [] + # A run resumed on a landing of the revoked account: it signs nobody in. + resumed = TargetOrg({"carol": LANDED}, frozenset({"carol"}), landed=marks) + assert _plan(rows, target=resumed, revoked={"carol"}).problems == [] + + +def test_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> None: + d = NsDecision("acme", "notes", "acme", "team", "merge") + patterns = [ + {"org": "acme", "namespace": "*", "pattern": r"tok-\d{4}", "pattern_type": "regex"}, + {"org": "*", "namespace": "*", "pattern": "SECRET", "pattern_type": "substring"}, + {"org": "acme", "namespace": "vault", "pattern": "deploys", "pattern_type": "substring"}, + {"org": "other", "namespace": "*", "pattern": "x", "pattern_type": "substring"}, + ] + held = refusals([{**b, "pattern_id": str(uuid.uuid4())} for b in patterns], d) + assert len(held) == 2 # its org's and the deployment's; not another namespace's + assert match_value(held, '"the tok-1234 key"') and match_value(held, '"a SECRET"') + assert match_value(held, '"a secret on deploys, tok-12"') is None + + +def test_two_accounts_of_the_bundle_never_land_with_one_email() -> None: + """Single sign-on refuses an email two accounts hold, in any org.""" + rows = [_account("a", "alice", "Alice@X"), _account("b", "alice", "alice@x")] + rules: dict[str, Any] = { + "orgs": {"a": "t", "b": "t"}, + "subjects": {"b/alice": {"claim": "alice-b"}}, + } + p = _plan(rows, targets={"t": EMPTY}, rules=rules, subjects={}) + assert any("its email is also 'a/alice''s" in s for s in p.problems) + assert p.proposals == {"subjects": {"b/alice": "drop"}} + rules["subjects"]["b/alice"] = "drop" + assert _plan(rows, targets={"t": EMPTY}, rules=rules, subjects={}).problems == [] + + +def test_the_map_names_only_what_the_bundle_holds_and_whom_a_namespace_can_name() -> None: + rows = [_account("acme", "alice", "a@x"), _ns("acme", "team", "alice")] + target = TargetOrg({}, frozenset({"group:eng", "everyone", "carla", "user:9"})) + typo = _plan(rows, target=target, rules={"namespaces": {"acme/teem": "skip"}}) + assert typo.problems == ["namespaces.acme/teem: names nothing in this bundle"] + # A namespace is no subject: its entry belongs under namespaces. + wrong = _plan(rows, target=target, rules={"subjects": {"acme/team": "skip"}}) + assert wrong.problems == ["subjects.acme/team: names nothing in this bundle"] + for rules, named in ( + ({"subjects": {"acme/alice": "group:eng"}}, "group:eng"), # an account onto one + ({"subjects": {"acme/alice": "user:9"}}, "user:9"), # nor onto an end user + ({"subjects": {"acme/bob@x": "everyone"}}, "everyone"), + ): + p = _plan(rows, subjects={"bob@x"}, target=target, rules=rules) + assert len(p.problems) == 1 and repr(named) in p.problems[0], p.problems + fine = {"subjects": {"acme/bob@x": "carla"}} + assert _plan(rows, subjects={"bob@x"}, target=target, rules=fine).problems == [] + + +async def test_a_resume_counts_what_the_postgres_authority_holds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Under the Postgres authority a head committed since its last publication is in the + authority only, deleted ones too: a resumed import counts them as written.""" + from server.cli import instance_import as imp + from server.core import pg + from server.knowledge.store import pg_documents + from server.memory.store import pg_memory + + heads = [(("-", "-", "-", "k3"), True)] # a definition, in the authority only + heads += [(("a", "-", "-", f"k{i}"), False) for i in range(3)] # in key order + + async def held_in( + org: str, ns: str, *, keys: list[str], after: Any = None, limit: int = 5000 + ) -> Any: + return [h for h in heads if (after is None or h[0] > after) and h[0][3] in keys][:limit] + + async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: + for agent, key, uri, kind in ( + ("a", "k-ch", "ch.md", "fact"), + ("a", "k1", "held.md", "fact"), + ("-", "k-def", "def.md", "definition"), + ): + if key in params.get("keys", [key]) and uri in params.get("uris", [uri]): + yield { + "agent": agent, + "user_id": "-", + "session_id": "-", + "memory_key": key, + "memory_type": kind, + "v": uri, + } + + async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: + return {u for u in uris if u == "held.md"} + + monkeypatch.setattr(pg, "enabled", lambda: True) + monkeypatch.setattr(pg_memory, "held_in", held_in) + monkeypatch.setattr(imp, "PG_PAGE", 2) # a full page reads on; a short one is the last + monkeypatch.setattr(pg_documents, "held_uris", held_uris) + monkeypatch.setattr(imp, "stream_rows", stream_rows) + every = ["k-ch", "k-def", "k0", "k1", "k2", "k3", "k-none"] + held = await imp._held_keys(None, "o", "n", keys=every) + assert {k[3] for k in held} == {"k-ch", "k-def", "k0", "k1", "k2", "k3"} + assert {k[3] for k, definition in held.items() if definition} == {"k-def", "k3"} + assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k1"} + assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"held.md"} + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +async def test_the_export_refuses_before_it_writes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An erasure of a selected org that has not completed, an org or a namespace that + selects nothing, and under the Postgres authority a namespace whose document + publications are owed each refuse the export before it writes a bundle.""" + from server.cli import instance_export as exp + from server.core import pg + from server.knowledge.store import pg_documents + + def erasure(org: str, status: str) -> str: + return ( + "INSERT INTO loom.erasure_requests (id, org, scope_type, status, version) " + f"VALUES (generateUUIDv4(), '{org}', 'org', '{status}', 1)" + ) + + setup = [ + ddl("erasure_requests"), + erasure("held", "queued"), + erasure("held", "failed"), + erasure("acme", "completed"), + ddl("storage_authority"), + "INSERT INTO loom.storage_authority (authority, epoch, deployment_id) " + "VALUES ('clickhouse', 1, 'src')", + ddl("namespaces"), + "INSERT INTO loom.namespaces (org, namespace, owner_email) VALUES ('acme', 'team', 'al')", + ddl("namespace_grants"), + ddl("sso_links"), + ] + + class Local: + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: + return run(setup, sql, params) + + async def query_one(self, sql: str, params: Any = None) -> Any: + return next(iter(run(setup, sql, params)), None) + + async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: + for r in run(setup, sql, params): + yield r + + async def unpublished(org: str, ns: str) -> tuple[int, int]: + return 2, 1 + + monkeypatch.setattr(exp, "stream_rows", stream_rows) + out = tmp_path / "bundle" + with pytest.raises(SystemExit, match="erasures that have not completed") as refused: + await exp.export(Local(), orgs=["held", "acme"], namespaces=None, out=out) + assert "queued" in str(refused.value) and "failed" in str(refused.value) + assert "acme" not in str(refused.value) # its erasure completed + with pytest.raises(SystemExit, match="no memory namespace to export: ghost$"): + await exp.export(Local(), orgs=["acme", "ghost"], namespaces=None, out=out) + with pytest.raises(SystemExit, match="no memory namespace to export: nope$"): + await exp.export(Local(), orgs=["acme"], namespaces=["team", "nope"], out=out) + monkeypatch.setattr(pg, "enabled", lambda: True) + monkeypatch.setattr(pg_documents, "unpublished", unpublished) + owed = r"document publications have not finished: acme/team \(2 owed, 1 parked\)" + with pytest.raises(SystemExit, match=owed): + await exp.export(Local(), orgs=["acme"], namespaces=None, out=out) + assert not out.exists() + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +async def test_a_synced_copy_stays_behind_only_while_a_source_writes_it_again() -> None: + """A copy whose source is registered there, or retiring its copies, stays behind; one + of a source removed with its copies kept, which no source writes again, moves, as do a + recording's transcript and the copies no source of their own namespace marks.""" + from server.cli import instance_export as exp + from server.knowledge.domain.sources import SYNC_WORKER_ACTOR + + sources = [ + "INSERT INTO loom.knowledge_sources (org, namespace, name, kind, active, " + f"pending_delete) VALUES ('o', 'n', '{name}', 'gdrive', {active}, {retiring})" + for name, active, retiring in ( + ("drive", "true", "false"), + ("old-drive", "false", "false"), # removed, its copies kept + ("gone", "false", "true"), # removed, its copies retiring + ) + ] + docs = [ + "INSERT INTO loom.documents (org, namespace, source_uri, actor, tags, metadata) VALUES " + f"('o', '{ns}', '{uri}', '{actor}', ['{tag}'], '{{\"source_kind\": \"{kind}\"}}')" + for ns, uri, actor, tag, kind in ( + ("n", "synced.md", SYNC_WORKER_ACTOR, "source:drive", "gdrive"), + ("n", "retiring.md", SYNC_WORKER_ACTOR, "source:gone", "gdrive"), + ("n", "kept.md", SYNC_WORKER_ACTOR, "source:old-drive", "gdrive"), + ("n", "meeting.md", SYNC_WORKER_ACTOR, "source:drive", "recording"), + ("n", "mine.md", "human:alice", "source:drive", "gdrive"), + ("other", "elsewhere.md", SYNC_WORKER_ACTOR, "source:drive", "gdrive"), + ) + ] + setup = [ddl("knowledge_sources"), *sources, ddl("documents"), *docs] + + class Local: + async def query_all(self, sql: str, params: Any = None) -> list[dict[str, Any]]: + return run(setup, sql, params) + + tags = await exp._source_tags(Local(), ["o"]) + assert sorted(tags) == ["o/n/source:drive", "o/n/source:gone"] + stays = run( + setup, + f"SELECT source_uri FROM loom.documents WHERE {exp._RESYNCED} ORDER BY source_uri", + {"sync": SYNC_WORKER_ACTOR, "sources": tags}, + ) + assert [r["source_uri"] for r in stays] == ["retiring.md", "synced.md"] + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +async def test_the_held_reads_run_on_the_production_tables( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """On the production tables a key's latest version says whether it is a namespace + definition, and each read returns only what it is asked for, of its own namespace.""" + from server.cli import instance_import as imp + from server.core import pg + + def memory(ns: str, agent: str, key: str, kind: str, version: int) -> str: + return ( + "INSERT INTO loom.memory (org, namespace, agent, user_id, session_id, memory_key, " + f"memory_type, version) VALUES ('o', '{ns}', '{agent}', '-', '-', '{key}', " + f"'{kind}', {version})" + ) + + setup = [ + ddl("memory"), + memory("n", "-", "k-was", "definition", 1), + memory("n", "-", "k-was", "semantic", 2), # no longer one + memory("n", "-", "k-def", "semantic", 1), + memory("n", "-", "k-def", "definition", 2), + memory("n", "a", "k-def", "definition", 3), # under an agent: not namespace-wide + memory("other", "-", "k-x", "definition", 1), + ddl("documents"), + "INSERT INTO loom.documents (org, namespace, source_uri) VALUES ('o', 'n', 'held.md'), " + "('o', 'n', 'held.md'), ('o', 'n', 'other.md'), ('o', 'other', 'new.md')", + ] + + async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: + for r in run(setup, sql, params): + yield r + + monkeypatch.setattr(pg, "enabled", lambda: False) + monkeypatch.setattr(imp, "stream_rows", stream_rows) + assert await imp._held_keys(None, "o", "n", keys=["k-was", "k-def", "k-x"]) == { + ("-", "-", "-", "k-was"): False, + ("-", "-", "-", "k-def"): True, + ("a", "-", "-", "k-def"): False, + } + assert await imp._held_keys(None, "o", "n", keys=["k-was"]) == {("-", "-", "-", "k-was"): False} + assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"held.md"} + + +async def test_an_original_changed_after_the_dry_run_stops_its_document( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The apply reads each original again as it writes its document: one changed since + the dry run read it raises before anything is written.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + + w = BundleWriter(tmp_path / "b") + sha = w.original(b"# Runbook\n") + with w.section("documents") as sink: + sink.write({"org": "a", "namespace": "n", "source_uri": "r.md", "blob_path": sha}) + w.finish({"source": {"deployment_id": SOURCE}}) + bundle = Bundle.open(tmp_path / "b") + (tmp_path / "b" / ORIGINALS / sha).write_bytes(b"# Runbook, changed\n") + + async def nothing(*_: Any) -> set[str]: + return set() + + monkeypatch.setattr(imp, "_held_uris", nothing) + d = NsDecision("a", "n", "t", "n", "create") + run: Any = SimpleNamespace(bundle=bundle, ch=None, by_source={("a", "n"): d}) + with pytest.raises(BundleError, match="differs from its name"): + await imp._documents(run) + + +def test_an_original_changed_since_the_dry_run_stops_the_apply( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A plan that changed since its review writes nothing. The dry run reads every + original back; one changed before the apply reads it stops the run with a line that + says to run it again.""" + import argparse + import asyncio + from types import SimpleNamespace + + from server.cli import _ch, instance + from server.cli import instance_import as imp + + async def nothing(*_: Any, **__: Any) -> Any: + return {}, {} + + async def changed(*_: Any) -> Any: + raise BundleError("original ab12: its bytes are not the manifest's") + + accepted: list[Any] = [] + + async def accept(**kw: Any) -> None: + accepted.append(kw) + + plan = SimpleNamespace(problems=[], digest="d1") + monkeypatch.setattr(Bundle, "open", lambda _: SimpleNamespace(manifest={"orgs": ["a"]})) + monkeypatch.setattr(_ch, "run_connected", lambda run, orgs: asyncio.run(run(None))) + monkeypatch.setattr(_ch, "check_acceptance", accept) + for name, fake in (("load_target", nothing), ("check", nothing), ("apply", changed)): + monkeypatch.setattr(imp, name, fake) + monkeypatch.setattr(imp, "build_plan", lambda *_: plan) + monkeypatch.setattr(instance, "_print_plan", lambda *_: None) + stale = argparse.Namespace(bundle="b", map=None, dry_run=False, expect_plan="d0") + assert instance._cmd_import(stale) == 2 and accepted == [] # `apply` would raise + said = capsys.readouterr() + assert not said.out and "--expect-plan 'd0' is not this plan (d1)" in said.err + args = argparse.Namespace(bundle="b", map=None, dry_run=False, expect_plan="d1") + with pytest.raises(SystemExit, match="ab12.*the import stopped part way; run it again"): + instance._cmd_import(args) + + +async def test_a_landing_holds_to_its_recorded_created_at_and_its_resume_to_the_plan( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The source row was created again since an earlier run recorded the landing: the + apply tests the target's row, and writes the one it still owes, by the recorded + created_at, as the plan does. A resume under a plan that changed since narrows the row + its earlier run wrote: approval where it is open, and the owner the map now names in + place of the import's; nothing else on it changes, and no decision opens it.""" + from contextlib import asynccontextmanager, nullcontext + from types import SimpleNamespace + + from server.auth import directory, grant_claims + from server.cli import instance_import as imp + from server.core import grant_cache + from server.identity.store import namespaces as repo + + held: list[Any] = [] + written: list[dict[str, Any]] = [] + + @asynccontextmanager + async def change(*_: Any, **__: Any) -> Any: + yield + + async def fetch_row(*_: Any, **__: Any) -> Any: + return held[0] if held else None + + async def nothing(*_: Any, **__: Any) -> Any: + return False + + async def typed(ch: Any, table: str, rows: list[Any]) -> Any: + return rows + + async def insert(table: str, rows: list[Any], **_: Any) -> None: + written.extend(rows) + + monkeypatch.setattr(grant_claims, "account_change", change) + monkeypatch.setattr(repo, "fetch_row", fetch_row) + monkeypatch.setattr(directory, "directory", lambda: SimpleNamespace(in_use=nothing)) + monkeypatch.setattr(grant_cache, "changed", nothing) + monkeypatch.setattr(imp, "_typed", typed) + monkeypatch.setattr(imp, "_identity", nullcontext) + target = TargetOrg({}, frozenset(), landed={("team", f"{SOURCE}/acme/team"): AT}) + run: Any = SimpleNamespace( + key=lambda o, n: f"{SOURCE}/{o}/{n}", + targets={"acme": target}, + audit=nothing, + subject=lambda o, s: s, + actor="process:cli:instance", + now=datetime(2026, 2, 1), + ch=SimpleNamespace(insert=insert), + count=lambda *_: None, + ) + d = NsDecision("acme", "team", "acme", "team", "create") + again = {**_ns("acme", "team", "alice"), "created_at": "2026-01-01T00:00:00Z"} + await imp._land(run, d, again) # the row it still owes + assert [r["created_at"] for r in written] == [AT] + held.append(LANDED) + await imp._land(run, d, again) # the row it wrote + assert len(written) == 1 + held[0] = {**LANDED, "created_at": datetime(2026, 1, 1)} + with pytest.raises(SystemExit, match="in use on the target"): + await imp._land(run, d, again) # a row someone registered since + # The target org serves others since, and the map names the owner now. The new + # version is later than the row it replaces, even one written after this host's now. + monkeypatch.setattr(imp, "naive_utc_now_seconds", lambda: datetime(2026, 2, 1)) + since = NsDecision("acme", "team", "acme", "team", "create", approval=True) + for was, at in ( + (datetime(2026, 1, 1), datetime(2026, 2, 1)), + (datetime(2026, 3, 1), datetime(2026, 3, 1, 0, 0, 1)), + ): + open_row = {**LANDED, "visibility": "public", "owner_email": run.actor, "updated_at": was} + held[0] = {**open_row, "description": "set since"} + await imp._land(run, since, again) + assert written[-1] == { + **held[0], + "join_policy": "approval", + "owner_email": "alice", + "updated_at": at, + } + for row in (written[-1], {**held[0], "join_policy": "closed", "owner_email": "carol"}): + held[0] = row # replanned already; a row its admins closed and gave an owner + await imp._land(run, since, again) + assert len(written) == 3 + + +async def test_a_resumed_run_writes_no_key_the_created_namespace_held( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Someone wrote a key into the created namespace before the rerun: its source head, + whose memory id differs, is not written over it. A created namespace is written as a + restore, so the same key under another agent is written, under newest_wins too.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.memory.app import blacklist_guard, conflicts + + w = BundleWriter(tmp_path / "b") + with w.section("memories") as sink: + for agent, k in (("a", "k1"), ("b", "k1"), ("a", "k2")): + sink.write(_head("n", k, agent=agent)) + w.finish({"source": {"deployment_id": SOURCE}}) + written: list[str] = [] + counted: list[str] = [] + + async def held_keys(ch: Any, org: str, ns: str, keys: list[str]) -> Any: + return {("a", "-", "-", "k1"): False} + + async def write(run: Any, d: Any, rows: list[Any]) -> None: + written.extend(r.memory_key for r in rows) + + async def newest_wins(*_: Any, **__: Any) -> str: + return "newest_wins" + + async def nothing(**_: Any) -> None: + return None + + monkeypatch.setattr(imp, "_held_keys", held_keys) + monkeypatch.setattr(imp, "_write_memories", write) + monkeypatch.setattr(conflicts, "namespace_conflict_policy", newest_wins) + monkeypatch.setattr(blacklist_guard, "find_match", nothing) + run: Any = SimpleNamespace( + bundle=Bundle.open(tmp_path / "b"), + ch=None, + held={}, + reach={}, + refusals={}, + now=datetime(2026, 2, 1), + by_source={("acme", "n"): NsDecision("acme", "n", "acme", "n", "create")}, + user_id=lambda o, u: u, + count=lambda d, what, n=1: counted.append(what), + ) + await imp._memories(run) + assert written == ["k1", "k2"] and counted == ["memories_the_target_holds"] + + +async def test_two_merges_into_one_namespace_land_an_address_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two source namespaces merged into one target both hold an address: the first copy + lands and the second is counted as present, as a key both hold would be. An address + the target's owners write while the run goes on is read just before its write. A + document committed with its publication owed counts as written, and the run goes on.""" + from contextlib import nullcontext + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.core.pg_lease import PublicationPending + from server.knowledge.app import writes + + w = BundleWriter(tmp_path / "b") + with w.section("documents") as sink: + for ns, uri in ( + ("notes", "runbook.md"), + ("scratch", "runbook.md"), + ("notes", "own.md"), + ("notes", "new.md"), + ): + sink.write({"org": "acme", "namespace": ns, "source_uri": uri, "content": ns}) + w.finish({"source": {"deployment_id": SOURCE}}) + landed: list[str] = [] + counted: list[str] = [] + + async def held(ch: Any, org: str, ns: str, uris: list[str]) -> set[str]: + return {"own.md"} if landed else set() # the owners wrote it since; not one asked + + async def upsert(body: Any) -> None: + landed.append(body.content) + if body.source_uri == "runbook.md": + raise PublicationPending() # committed; the worker publishes it + + monkeypatch.setattr(imp, "_held_uris", held) + monkeypatch.setattr(imp, "_for", lambda d: nullcontext()) + monkeypatch.setattr(writes, "handle_knowledge_upsert", upsert) + run: Any = SimpleNamespace( + bundle=Bundle.open(tmp_path / "b"), + ch=None, + by_source={ + ("acme", ns): NsDecision("acme", ns, "acme", "team", "merge") + for ns in ("notes", "scratch") + }, + count=lambda d, what, n=1: counted.append(what), + ) + await imp._documents(run) + assert landed == ["notes", "notes"] + assert counted == ["documents", "documents_present", "documents_present", "documents"] + + +def _head(namespace: str, key: str, **row: Any) -> dict[str, Any]: + """A source memory head as the export writes it.""" + return { + "org": "acme", + "namespace": namespace, + "memory_id": str(uuid.uuid4()), + "agent": "a", + "user_id": "-", + "session_id": "-", + "run_id": "", + "memory_key": key, + "memory_type": "semantic", + "value": '"v"', + "confidence": 1.0, + "source_trace": "", + "pinned": False, + **row, + } + + +async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_other( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A row the merge does not carry claims no key, so a live row of its key lands. Of rows + a write of one would retire the newest lands: one key under one agent, user and session, + across two merged namespaces too, and under newest_wins one user's key in any agent and + session, and the rows of a key with no user. There a row with no user, written first, + lands beside a named one of its key, and a key the target holds that far is held; a run + resumed after the rows with no user writes the rest.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.memory.app import blacklist_guard, conflicts + + heads: list[tuple[str, ...]] = [ # "" for no valid_at + ("n", "b", "alice", "s2", "k1", "", "active"), # alice holds k1 on the target + ("n", "a", "bob", "s1", "k1", "2024", "active"), + ("n", "a", "-", "-", "k1", "", "active"), # alice's target row has the key + ("n", "a", "carol", "s1", "k3", "2024", "active"), + ("n", "a", "carol", "s2", "k3", "2025", "active"), # later in the bundle, and newer + ("n", "b", "-", "-", "k3", "2023", "active"), # after carol's, written before it + ("n", "a", "dave", "s1", "k4", "2026", "superseded"), # not carried + ("n", "a", "dave", "s2", "k4", "2024", "active"), + ("m", "a", "bob", "s1", "k1", "2025", "active"), # the second namespace's is newer + ("n", "a", "erin", "s1", "k5", "2026", "active", "2026-01-01T00:00:00"), # expired + ("n", "a", "erin", "s2", "k5", "2024", "active", "2026-06-01T00:00:00"), + ("n", "a", "fay", "s1", "k6", "2025", "active", "", "2025-06-01T00:00:00"), # redacted + ("n", "a", "fay", "s2", "k6", "2024", "active"), + ("n", "a", "gus", "s1", "k8", "2025", "conflicted"), # served, judged again + ("n", "-", "-", "-", "k7", "2023", "active", "", "", "definition"), # namespace-wide + ("n", "a", "-", "-", "k7", "2025", "active"), # leaves the definition be + ("n", "-", "-", "-", "k9", "2023", "active", "", "", "definition"), + ("m", "-", "-", "-", "k9", "2024", "active"), # its identity, newer: written over it + ("n", "-", "-", "-", "k10", "2023", "active"), # older than the definition at its identity + ("m", "-", "-", "-", "k10", "2024", "active", "", "", "definition"), + ] + w = BundleWriter(tmp_path / "b") + with w.section("memories") as sink: + for i, (ns, agent, user, session, key, year, status, *more) in enumerate(heads): + identity = {"agent": agent, "user_id": user, "session_id": session} + at = f"{year}-01-01T00:00:00" if year else None + row = {"valid_at": at, "status": status} + extra = zip(("expires_at", "redacted_at", "memory_type"), more, strict=False) + row |= {k: v for k, v in extra if v} + sink.write(_head(ns, key, memory_id=str(uuid.UUID(int=i)), **row, **identity)) + w.finish({"source": {"deployment_id": SOURCE}}) + policy = "" + written: list[int] = [] + counted: dict[tuple[str, str], int] = {} + + held = {("a", "alice", "s1", "k1"): False} + reads: list[list[str]] = [] + + async def held_keys(ch: Any, org: str, ns: str, keys: list[str]) -> Any: + reads.append(keys) + return {k: v for k, v in held.items() if k[3] in keys} + + async def current(*_: Any, **__: Any) -> str: + return policy + + async def write(run: Any, d: Any, rows: list[Any]) -> None: + written.extend(uuid.UUID(r.memory_id).int for r in rows) + + async def nothing(**_: Any) -> None: + return None + + def count(d: Any, what: str, n: int = 1) -> None: + counted[(d.source, what)] = counted.get((d.source, what), 0) + n + + monkeypatch.setattr(imp, "_held_keys", held_keys) + monkeypatch.setattr(imp, "_write_memories", write) + monkeypatch.setattr(conflicts, "namespace_conflict_policy", current) + monkeypatch.setattr(imp, "_KEYS_PER_READ", 2) + monkeypatch.setattr(blacklist_guard, "find_match", nothing) + for policy, expected, counts in ( + ( + "newest_wins", + [14, 19, 5, 15, 17, 4, 7, 10, 12, 13, 8], # the definitions, no user, the rest + {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 4}, + ), + ( + "auto_reinforce", + [0, 2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 8, 17, 19], + {"memories_not_live": 3, "memories_superseded": 3}, + ), + ): + written.clear() + counted.clear() + reads.clear() + run: Any = SimpleNamespace( + bundle=Bundle.open(tmp_path / "b"), + ch=None, + held={}, + reach={}, + refusals={}, + now=datetime(2026, 2, 1), + by_source={ + ("acme", ns): NsDecision("acme", ns, "acme", "team", "merge") for ns in "nm" + }, + user_id=lambda o, u: u, + count=count, + ) + await imp._memories(run) + assert written == expected, policy + # The bundle's nine keys in chunks of two, never the whole namespace, those under + # three characters first. + assert [len(k) for k in reads] == [2, 2, 2, 2, 1], policy + assert [k for chunk in reads for k in chunk] == [f"k{i}" for i in (1, *range(3, 11))] + assert counted == {("n", what): n for what, n in counts.items()}, policy + # Resumed after the run's first two calls, which wrote the definition and row 5: the + # definition reaches no row, so row 15 of its key still lands, and so does the rest. + policy = "newest_wins" + held = {("a", "alice", "s1", "k1"): False, ("-", "-", "-", "k7"): True} + held[("b", "-", "-", "k3")] = False # k7 in a later chunk than k1 and k3 + written.clear() + run.held, run.reach = {}, {} + await imp._memories(run) + assert written == [19, 17, 15, 8, 4, 7, 10, 12, 13] # m's batch began first + + +async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: + """Every entry checked, oldest first, with no update detection, no reinforcement and + no pin; an entry admission declines is counted.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.core.pg_lease import PublicationPending + from server.identity.api.models import _SnapshotMemoryRow + from server.memory.api.models_bulk import MAX_BULK_ENTRIES + from server.memory.app import bulk_set + + calls: list[tuple[Any, dict[str, Any]]] = [] + counts: dict[str, int] = {} + + async def bulk(body: Any, **kw: Any) -> Any: + if body.agent == "c": + raise PublicationPending() # committed; its answer is lost + calls.append((body, kw)) + return SimpleNamespace( + written=[SimpleNamespace(version=int(e.memory_key != "k-old")) for e in body.entries] + ) + + def count(d: Any, what: str, n: int = 1) -> None: + counts[what] = counts.get(what, 0) + n + + async def held_keys(ch: Any, org: str, ns: str, keys: list[str]) -> Any: + asked.append(keys) + if calls: # the owners wrote k-late after the first call + return {("b", "-", "s2", "k-late"): False} + # k-undated written since, in another session; the target's definition of k-new + # reaches no row. + return {("b", "alice", "s9", "k-undated"): False, ("-", "-", "-", "k-new"): True} + + asked: list[Any] = [] + monkeypatch.setattr(bulk_set, "handle_memory_bulk_set", bulk) + monkeypatch.setattr(imp, "_held_keys", held_keys) + monkeypatch.setattr(imp, "utc_now", lambda: datetime(2026, 2, 1, tzinfo=UTC)) + rows = [ + _SnapshotMemoryRow.model_validate( + _head("n", key, valid_at=at, expires_at=expires, pinned=True) + ) + for key, at, expires in ( + ("k-undated", None, None), + ("k-new", "2025-03-01T00:00:00Z", "2026-01-15T00:00:00"), # since the run began + ("k-old", "2025-01-01T00:00:00", "2026-02-01T01:00:00"), + ) + ] + rows.append(_SnapshotMemoryRow.model_validate(_head("n", "k-late", agent="b", session_id="s2"))) + rows.append(_SnapshotMemoryRow.model_validate(_head("n", "k-pending", agent="c"))) + # k-new live at the run's start; the target uses newest_wins, where a write with no + # user reaches the key in every session. + run: Any = SimpleNamespace( + now=datetime(2026, 1, 1), ch=None, reach={("acme", "team"): set()}, count=count + ) + await imp._merge_memories(run, NsDecision("acme", "n", "acme", "team", "merge"), rows) + assert imp._BATCH <= MAX_BULK_ENTRIES # so a group of a batch is one call + assert asked == [["k-new", "k-old", "k-undated"], ["k-late"], ["k-pending"]] # each call + [(body, kw)] = calls + assert [e.memory_key for e in body.entries] == ["k-old", "k-new"] + assert kw == {"conflict_check_cap": 2, "reinforce": False} + assert body.detect_updates is False and not any(e.pinned for e in body.entries) + assert [e.ttl_seconds for e in body.entries] == [3600, 1] # from the write + assert counts == { + "memories": 1, + "memories_not_admitted": 1, + "memories_the_target_holds": 2, + "memories_publication_pending": 1, + } + + +async def test_the_dry_run_names_a_memory_the_target_refuses( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The apply would stop at the same row at every run: the dry run builds each row it + writes and names the ones the target refuses, but not a row it leaves out.""" + from server.cli import instance_import as imp + from server.cli.instance_plan import Plan + from server.core import datetimes + from server.settings import settings + + monkeypatch.setattr(datetimes, "naive_utc_now_seconds", lambda: datetime(2026, 1, 1)) + monkeypatch.setattr(imp, "utc_now", lambda: datetime(2026, 1, 1, tzinfo=UTC)) + # The target's sensitive retention window expires a medium row by anonymizing it. + monkeypatch.setattr(settings, "memory_sensitive_retention_days", 30) + monkeypatch.setattr(settings, "memory_sensitive_on_expire", "anonymize") + + late = "2200-01-01T00:00:00" # past what a DateTime column holds + w = BundleWriter(tmp_path / "b") + with w.section("memories") as sink: + sink.write(_head("notes", "late", valid_at=late)) + sink.write(_head("notes", "fine")) + sink.write(_head("team", "odd", valid_at=late)) + # memory.bulk_set measures json.dumps of the value, which escapes the é + sink.write(_head("team", "long", value='"héllo"', char_limit=7)) + sink.write(_head("team", "demoted", on_expire="demote", expires_at="2099-01-01T00:00:00")) + sink.write(_head("team", "never", on_expire="demote")) # never expires: nothing lost + # The target's window, on a row the source never expires or deletes at its expiry. + sink.write(_head("team", "window", sensitivity="medium")) + sink.write(_head("team", "deleted", sensitivity="medium", expires_at="2026-03-01T00:00:00")) + sink.write(_head("team", "gone", valid_at=late, status="tombstoned")) # left out + sink.write(_head("team", "scrubbed", valid_at=late, redacted_at="2025-01-01T00:00:00")) + sink.write(_head("team", "theirs", valid_at=late, user_id="alice")) # a dropped user + sink.write(_head("old", "skipped", valid_at=late)) + w.finish({"source": {"deployment_id": SOURCE}}) + p = Plan( + bundle="b", + orgs={"acme": "acme"}, + namespaces=[ + NsDecision("acme", "notes", "acme", "notes", "create"), + NsDecision("acme", "team", "acme", "team", "merge"), + NsDecision("acme", "old", "acme", "old", "skip"), + ], + subjects=[], + problems=[], + proposals={}, + ) + await imp.check(None, Bundle.open(tmp_path / "b"), p, {"acme": EMPTY}) + assert [x.split(":")[0] for x in p.problems] == [ + "acme/notes memory 'late'", + "acme/team memory 'odd'", + "acme/team memory 'long'", + "acme/team memory 'demoted'", + ], p.problems + assert "a merge expires it by 'tombstone', not its own 'demote'" in p.problems[-1] + + +async def test_the_dry_run_names_the_refusals_the_target_cannot_take( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A source refusal this deployment cannot compile is named for each namespace it + reaches, and a created namespace whose refusals would pass the target's regex budget + is named too; a merge stores none of them, so it has no budget to pass.""" + from server.cli import instance_import as imp + from server.cli.instance_plan import Plan + from server.memory.app import blacklist_guard + + async def stored(ch: Any, ids: list[str]) -> set[str]: + return set() + + async def nearly_full(*_: Any) -> int: + return blacklist_guard.REGEX_PROGRAM_PER_SCOPE - 1 # what the target already runs + + monkeypatch.setattr(imp, "_stored", stored) + monkeypatch.setattr(blacklist_guard, "scope_program", nearly_full) + w = BundleWriter(tmp_path / "b") + with w.section("blacklist") as sink: + for pattern in ("(a)\\1", "tok-[0-9]+"): # a backreference: not RE2 + sink.write( + { + "org": "acme", + "namespace": "*", + "pattern_id": str(uuid.uuid4()), + "pattern": pattern, + "pattern_type": "regex", + } + ) + with w.section("memories"): + pass + w.finish({"source": {"deployment_id": SOURCE}}) + p = Plan( + bundle="b", + orgs={"acme": "acme"}, + namespaces=[ + NsDecision("acme", "notes", "acme", "notes", "create"), + NsDecision("acme", "team", "acme", "team", "merge"), + ], + subjects=[], + problems=[], + proposals={}, + ) + await imp.check(None, Bundle.open(tmp_path / "b"), p, {"acme": EMPTY}) + assert [x.split(": ", 1)[0] for x in p.problems] == ["acme/notes", "acme/notes", "acme/team"] + assert "'(a)\\\\1' does not compile on the target" in p.problems[0], p.problems + assert f"would pass {blacklist_guard.REGEX_PROGRAM_PER_SCOPE} RE2" in p.problems[1] + assert "does not compile" in p.problems[2] + + +async def test_a_handle_the_target_revoked_is_refused_unless_the_source_revoked_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A revocation spans orgs: an account claimed under a handle the target revoked + outright would land with no token that signs in. One the source revoked lands with none + either way, and still takes no handle that holds access there.""" + from types import SimpleNamespace + + from fastapi import HTTPException + + from server.auth import self_signup + from server.cli import instance_import as imp + from server.cli.instance_plan import Plan + + async def query_all(sql: str, params: dict[str, Any]) -> Any: + return [{"subject": s, "reason": "operator"} for s in ("alice", "carol")] + + async def empowered(ch: Any, org: str, name: str) -> None: + if name in ("bob", "dan"): + raise HTTPException(409) + + async def stored(ch: Any, ids: list[str]) -> set[str]: + return set() + + monkeypatch.setattr(self_signup, "refuse_empowered", empowered) + monkeypatch.setattr(imp, "_stored", stored) + w = BundleWriter(tmp_path / "b") + with w.section("revoked") as sink: + for name in ("Carol", "dan"): # the source revoked them; read case-folded + sink.write({"subject": name, "reason": "operator"}) + w.finish({"source": {"deployment_id": SOURCE}}) + names = ("alice", "bob", "carol", "dan") + p = Plan( + bundle="b", + orgs={"acme": "acme"}, + namespaces=[NsDecision("acme", n, "acme", n, "create", account="claim") for n in names], + subjects=[], + problems=[], + proposals={}, + ) + ch: Any = SimpleNamespace(query_all=query_all) + await imp.check(ch, Bundle.open(tmp_path / "b"), p, {"acme": EMPTY}) + assert [x.split("'")[1] for x in p.problems] == ["alice", "bob", "dan"], p.problems + assert "'alice' is revoked on the target, in every org" in p.problems[0] + assert all("already holds access" in x for x in p.problems[1:]) + assert p.proposals == { + "subjects": {f"acme/{n}": {"claim": f"{n}-legacy"} for n in "alice bob dan".split()} + } + + +def test_a_landed_row_names_its_verifier_and_locker_as_the_plan_maps_them() -> None: + from types import SimpleNamespace + + from server.cli import instance_import as imp + + subjects = {("acme", "alice"): "alice-legacy", ("acme", "sa:ci"): None} + run: Any = SimpleNamespace(user_id=lambda o, u: u, subject=lambda o, s: subjects.get((o, s))) + d = NsDecision("acme", "notes", "acme", "notes-legacy", "create") + for verified, locked, want in ( + ("human:alice", "process:sa:ci", ("human:alice-legacy", "")), + ("human:bob", "", ("", "")), # never planned + ("a note", "human:alice", ("a note", "human:alice-legacy")), # no subject named + ): + row = imp._row(run, d, _head("notes", "k", verified_by=verified, locked_by=locked)) + assert (row.verified_by, row.locked_by) == want, verified diff --git a/tests/unit/test_namespaces_writers_mirror_classification.py b/tests/unit/test_namespaces_writers_mirror_classification.py index 548bfed05d..8ddd3a409f 100644 --- a/tests/unit/test_namespaces_writers_mirror_classification.py +++ b/tests/unit/test_namespaces_writers_mirror_classification.py @@ -89,6 +89,7 @@ def test_every_literal_namespaces_insert_is_a_known_writer() -> None: "server/identity/app/claim_release.py", # SELECT * new version: release "server/identity/app/collections.py", # registry_row + full-row copy (title) "server/identity/app/collection_budgets.py", # SELECT * via namespaces_repo.fetch_row + "server/cli/instance_import.py", # the source's full row, as the bundle's SELECT * holds it } found = set() for path in (ROOT / "server").rglob("*.py"): diff --git a/tests/unit/test_pg_durable_reads.py b/tests/unit/test_pg_durable_reads.py index ef0d14799d..4591fed178 100644 --- a/tests/unit/test_pg_durable_reads.py +++ b/tests/unit/test_pg_durable_reads.py @@ -61,6 +61,10 @@ # ClickHouse only durably. A new caller is classified here before it ships. _CALLERS = { "server/health.py": "counts for the health report; sends nothing", + "server/cli/instance_export.py": "a bundle to the operator; sends nothing, and an " + "import's writes from it commit", + "server/cli/instance_import.py": "what a resumed import must not write again; the " + "writes it decides commit", "server/knowledge/workers/pg_delivery.py": "counts the backlog for a gauge; sends nothing", "server/memory/workers/pg_delivery.py": "counts the backlogs for gauges; sends nothing", "server/knowledge/app/ingest_jobs.py": "a job's status to the caller and the worker's " diff --git a/tests/unit/test_signup_privilege.py b/tests/unit/test_signup_privilege.py index 801d20fc84..209cc68087 100644 --- a/tests/unit/test_signup_privilege.py +++ b/tests/unit/test_signup_privilege.py @@ -195,17 +195,17 @@ def grant(subject: str, version: int, revoked: str = "NULL", status: str = "acti ddl("tasks"), ] - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "carol")) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "carol")) with pytest.raises(HTTPException) as ei: - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "dave")) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "dave")) assert ei.value.status_code == 409 with pytest.raises(HTTPException): - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "erin")) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "erin")) with pytest.raises(HTTPException): # a namespace's owner may rewrite it - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "frank")) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "frank")) with pytest.raises(HTTPException): - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "gail")) - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", "hal")) # its token was revoked + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "gail")) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", "hal")) # its token was revoked @pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") @@ -236,9 +236,9 @@ def test_a_task_inbox_row_naming_a_subject_reserves_its_name() -> None: for name in ("ivy", "jo", "pat", "lee", "max"): with pytest.raises(HTTPException): - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", name)) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", name)) for name in ("kim", "ned"): - asyncio.run(ss._refuse_empowered(_Local(setup), "dev", name)) + asyncio.run(ss.refuse_empowered(_Local(setup), "dev", name)) @pytest.mark.parametrize("org", ["eve-org", "clickhouse"])