From ba81a0f0a6f4d6b101d706fae599db410dc2d204 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 20:37:36 +0530 Subject: [PATCH 01/32] loom instance export and import move orgs into a deployment that serves others An export writes one deployment's orgs as a bundle: namespaces, accounts with their password hashes, live grants, groups, blacklist entries, memories, and documents with their originals, each section checksummed in a manifest. An import plans the bundle against the target, refuses a plan while any source name or subject could land on someone else's, and applies the plan whose digest the operator reviewed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/backup-and-recovery.md | 3 +- docs/operations/consolidation.md | 110 ++++ docs/operations/index.md | 1 + docs/operations/meta.ts | 1 + docs/reference/cli.md | 3 + server/cli/app.py | 6 +- server/cli/instance.py | 136 +++++ server/cli/instance_bundle.py | 203 ++++++++ server/cli/instance_export.py | 366 +++++++++++++ server/cli/instance_import.py | 594 ++++++++++++++++++++++ server/cli/instance_plan.py | 491 ++++++++++++++++++ tests/unit/snapshots/cli_help.json | 17 +- tests/unit/snapshots/cli_tree.json | 310 +++++++++++ tests/unit/test_instance_consolidation.py | 158 ++++++ 14 files changed, 2395 insertions(+), 4 deletions(-) create mode 100644 docs/operations/consolidation.md create mode 100644 server/cli/instance.py create mode 100644 server/cli/instance_bundle.py create mode 100644 server/cli/instance_export.py create mode 100644 server/cli/instance_import.py create mode 100644 server/cli/instance_plan.py create mode 100644 tests/unit/test_instance_consolidation.py diff --git a/docs/operations/backup-and-recovery.md b/docs/operations/backup-and-recovery.md index bbec5116a73..565050009f4 100644 --- a/docs/operations/backup-and-recovery.md +++ b/docs/operations/backup-and-recovery.md @@ -548,7 +548,8 @@ 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; +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: diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md new file mode 100644 index 00000000000..22fbec9319e --- /dev/null +++ b/docs/operations/consolidation.md @@ -0,0 +1,110 @@ +# 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 and per-type settings | 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 and revoked grants | +| Groups the target org does not have, with their mapped members | Conversations, session briefs and tasks: the manifest counts them | +| Blacklist entries, before any content | Knowledge sources with a remote: the manifest lists them to register again | +| Memories: every live head, with its `created_at`, validity and attestation | Embeddings, caches, traces and rollups: the target builds them again | +| Documents with their originals, embedded again by the target's embedder | The audit log and agent events | + +Imported memories and documents carry `source_class=imported` and the importing command +(`process:cli:instance`) as `actor`. 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. +2. Stop writes to the source. The bundle holds the rows at the moment each section is + read. +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 + of every subject its grants and owner name, so the plan can place them. The bundle + holds password hashes: it is written readable by its owner only, and is copied to the + target the way a database dump is. + +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 names the map entry that settles it, and the run prints those entries as + YAML to copy into the map. + +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, and register the repositories and + knowledge sources the manifest's `left_behind` names. + +## 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/sa:ci-1a2b3c: drop +``` + +- **Namespaces.** A namespace is created under its own name, or the name the map gives + it. 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. + `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; + a merged row's `created_at` is the import's and its `valid_at` the source's. A document + whose `source_uri` the target namespace already serves is left as it is. +- **Accounts.** An account lands as a claimable password account under its handle. The + plan refuses a handle the target holds and an email any target account signs in with, + proposing a new handle or the target account. Mapping an account onto a target account + gives that account the source account's content and grants: 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 the source revoked lands with no password. +- **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves + the address at sign-in on the target. `user:`, `agent:` and `group:` subjects are kept, + except a group the target org already has, which needs a mapping. `sa:` subjects are + dropped. Any other subject needs a mapping or `drop`. + +## Running it again + +An import that stops part way runs again with the same command. Before it creates a +namespace it writes an `instance.import` audit row naming the source namespace, and a +later plan reads that row as this source's landing, not as a collision. A run writes no +memory id the namespace has held, deleted ones included, and no document whose +`source_uri` it serves; a grant whose subject already holds that role or a higher one is +not written again. + +## 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 c333605325b..70f1dc181c7 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 9a27f8dea72..5a2d17cd67c 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 15c1e62101e..f849b3ad65c 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -292,6 +292,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/cli/app.py b/server/cli/app.py index 93402c7665b..0353309da03 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 00000000000..cf2ae880a50 --- /dev/null +++ b/server/cli/instance.py @@ -0,0 +1,136 @@ +"""`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 +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="instance_cmd", required=True) + 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) + + +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) -> None: + from server.cli.instance_plan import proposal_yaml + + 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 "" + print(f" namespace {d.source_org}/{d.source} → {land}{account}") + 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}") + 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)") + for kind, rows in (bundle.manifest.get("left_behind") or {}).items(): + if rows: + print(f" left behind: {kind}: {len(rows)} 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 run_connected + from server.cli.instance_bundle import Bundle, BundleError + from server.cli.instance_import import apply, build_plan, load_target + from server.cli.instance_plan import MapError, parse_map + + 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: + targets, signs_in = await load_target(ch, target_orgs) + p = build_plan(bundle, rules, targets, signs_in) + _print_plan(bundle, p) + if p.problems: + return 1 + if args.dry_run: + return 0 + if args.expect_plan != p.digest: + print(f"--expect-plan {args.expect_plan!r} is not this plan ({p.digest}): review it") + return 2 + receipt = await apply(ch, bundle, p, rules, targets) + print(json.dumps(receipt, indent=2, default=str)) + return 0 + + return run_connected(_run, orgs=() if args.dry_run else target_orgs) diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py new file mode 100644 index 00000000000..2dbfb7882a6 --- /dev/null +++ b/server/cli/instance_bundle.py @@ -0,0 +1,203 @@ +"""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. +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 + +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) + if isinstance(v, bytes): + return v.decode("utf-8", errors="replace") + if isinstance(v, set | frozenset | tuple): + return list(v) + raise TypeError(f"cannot write {type(v).__name__} to a bundle") + + +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 any(self.out.iterdir()): + raise BundleError(f"{self.out} is not empty: write each bundle into a new directory") + (self.out / ORIGINALS).mkdir(parents=True, exist_ok=True) + + @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 gzip.open(part, "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") + part.write_bytes(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, + } + part = self.out / (MANIFEST + ".part") + part.write_text(json.dumps(manifest, indent=2, default=_default) + "\n") + os.replace(part, self.out / MANIFEST) + 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 opened.""" + + path: Path + manifest: dict[str, Any] + + @classmethod + def open(cls, path: Path) -> Bundle: + try: + manifest = json.loads((path / MANIFEST).read_text()) + 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) + + @property + def digest(self) -> str: + """The manifest's SHA-256: names this bundle in a plan and a receipt.""" + return hashlib.sha256((self.path / MANIFEST).read_bytes()).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 00000000000..2bde9f65ddc --- /dev/null +++ b/server/cli/instance_export.py @@ -0,0 +1,366 @@ +"""`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 +import os +from collections.abc import AsyncIterator, Sequence +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from server.cli.instance_bundle import BundleWriter + +# A namespace name of these forms is not the organization's to move: a mirror's or a code +# store's (the index rebuilds them), a collection (moved with its owner's account). +_NOT_EXPORTED_PREFIXES = ("acl-", "crs-", "col-") +_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 status + FROM loom.erasure_requests FINAL + WHERE org IN {orgs:Array(String)} AND status != 'completed' + AND requested_at > now() - INTERVAL 89 DAY + """, + params={"orgs": list(orgs)}, + ) + if rows: + listed = ", ".join(f"{r['id']} ({r['org']} {r['scope_type']}, {r['status']})" 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)." + ) + + +def exported_namespace(row: dict[str, Any]) -> bool: + """A memory namespace the organization holds: not a code index's, a benchmark's, a + mirror's, a code store's or a collection, and not soft-deleted.""" + name = str(row["namespace"]) + return ( + row.get("kind", "memory") == "memory" + and bool(row.get("active", True)) + and not name.startswith(_NOT_EXPORTED_PREFIXES) + ) + + +def select_namespaces( + rows: list[dict[str, Any]], grants: list[dict[str, Any]], wanted: list[str] | None +) -> dict[str, list[str]]: + """Per org, the namespaces the bundle carries: every exported one, or the `wanted` + ones together with the accounts that own them or hold grants on them, so the plan can + place every subject they name.""" + 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 "")) + for g in grants: + if g["namespace"] in out.get(str(g["org"]), set()): + named.setdefault(str(g["org"]), set()).add(str(g["subject"])) + for r in rows: + if ( + is_account(r) + and exported_namespace(r) + and r["namespace"] in named.get(r["org"], ()) + ): + out[str(r["org"])].add(str(r["namespace"])) + return {org: sorted(names) for org, names in out.items()} + + +def _write(w: BundleWriter, section: str, rows: list[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] +) -> list[dict[str, Any]]: + rows = [r async for r in stream_rows(ch, sql, params)] + _write(w, section, rows) + return rows + + +async def _identity_sections( + w: BundleWriter, ch: Any, orgs: list[str], selected: dict[str, list[str]] +) -> None: + namespaces = sorted({n for names in selected.values() for n in names}) + p = {"orgs": orgs, "ns": namespaces} + in_orgs = "org IN {orgs:Array(String)}" + in_ns = f"{in_orgs} AND namespace IN {{ns:Array(String)}}" + await _table(w, ch, "types", f"SELECT * FROM loom.namespace_types FINAL WHERE {in_ns}", p) + await _table( + w, + ch, + "groups", + f"SELECT * FROM loom.principal_groups FINAL WHERE {in_orgs} AND NOT deleted", + 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 org's and its namespaces' refusals; the deployment-wide ones ('*') too, which the + # importer narrows to the target org: a source's global refusal is not another org's. + await _table( + w, + ch, + "blacklist", + """ + SELECT * FROM loom.blacklist FINAL + WHERE (org IN {orgs:Array(String)} + AND (namespace = '*' OR namespace IN {ns:Array(String)}) + OR org = '*') + AND tombstoned_at IS NULL + """, + p, + ) + # A subject the source revoked outright stays revoked where its account lands. + await _table( + w, + ch, + "revoked", + "SELECT jti AS subject, reason FROM loom.revoked_tokens FINAL " + "WHERE jti IN {ns:Array(String)} AND issued_before IS NULL AND expires_at > now()", + p, + ) + + +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 +) -> None: + """Every live head of each namespace, as the snapshot payload's rows plus their org + and namespace.""" + from server.identity.api.models import _SnapshotMemoryRow + from server.memory.app import snapshot_rows as snap + + keep = _SnapshotMemoryRow.model_fields + 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") + + +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 page := await pg_memory.live_heads_in(org, ns, after=after, limit=5000): + for r in page: + yield r + after = identity_key(page[-1]) + return + 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 _documents( + w: BundleWriter, ch: Any, selected: dict[str, list[str]], counts: Counts +) -> 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: + 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", + {"org": org, "ns": ns}, + ): + 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: + raise SystemExit( + f"{org}/{ns} document {uri!r}: its original {sha} cannot be read; " + "repair it or erase the document" + ) + w.original(data) + + +async def _left_behind(ch: Any, orgs: list[str]) -> dict[str, Any]: + """What the target rebuilds or its owners redo, named in the manifest for the plan.""" + p = {"orgs": orgs} + repos = await ch.query_all( + "SELECT org, namespace, repo, git_remote FROM loom.code_repos FINAL " + "WHERE org IN {orgs:Array(String)} AND active", + params=p, + ) + sources = await ch.query_all( + "SELECT org, namespace, name, kind FROM loom.knowledge_sources FINAL " + "WHERE org IN {orgs:Array(String)} AND active AND NOT pending_delete", + params=p, + ) + rows = await ch.query_all( + "SELECT 'conversations' AS kind, org, count() AS n FROM loom.conversations " + "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'tasks', org, count() FROM loom.tasks FINAL " + "WHERE org IN {orgs:Array(String)} AND is_deleted = 0 GROUP BY org", + params=p, + ) + return {"code_repos": repos, "knowledge_sources": sources, "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) + os.umask(0o077) + w = BundleWriter(out) + p = {"orgs": orgs} + rows = [ + r + async for r in stream_rows( + ch, "SELECT * FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", p + ) + ] + grants = [ + r + async for r in stream_rows( + ch, + "SELECT * FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)} " + "AND revoked_at IS NULL AND status = 'active'", + p, + ) + ] + selected = select_namespaces(rows, grants, namespaces) + _write(w, "namespaces", [r for r in rows if r["namespace"] in selected.get(r["org"], ())]) + _write(w, "grants", [g for g in grants if g["namespace"] in selected.get(g["org"], ())]) + await _identity_sections(w, ch, orgs, selected) + # 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() + } + counts: Counts = {} + await _memories(w, ch, content, counts) + await _documents(w, ch, content, counts) + return w.finish( + { + "source": { + "deployment_id": source, + "authority": "postgres" if pg.enabled() else "clickhouse", + }, + "exported_at": datetime.now(UTC).isoformat(), + "orgs": orgs, + "namespaces": selected, + "counts": counts, + "left_behind": await _left_behind(ch, orgs), + } + ) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py new file mode 100644 index 00000000000..ae460d6589f --- /dev/null +++ b/server/cli/instance_import.py @@ -0,0 +1,594 @@ +"""`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. Apply then writes, in order: the refusals (blacklist), each created +namespace (an audit row naming its source first, so a run that stops part way is resumed, +then the namespace row), types and groups, grants under the mapped subjects, memories and +documents. 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. Documents go through `knowledge.upsert` with their +originals, so the target's embedder embeds them; memories are embedded by the embedding +worker's next full pass. A rerun skips what landed: memory ids the namespace has had, +documents whose source_uri already holds the same content. +""" + +from __future__ import annotations + +import base64 +import json +import time +import uuid +from collections.abc import Iterable, Mapping +from datetime import datetime +from typing import Any + +from server.cli.instance_bundle import Bundle +from server.cli.instance_export import stream_rows +from server.cli.instance_plan import MapFile, NsDecision, Plan, TargetOrg, is_account, plan + +_ACTOR = "process:cli:instance" +LANDED_EVENT = "instance.import" +_BATCH = 500 +# Settings that name the source's own services or rows: cleared, the target's owners set +# them again. +_CLEARED = {"rerank_endpoint": "", "classify_endpoint": "", "released_aliases": []} +_CLEARED_STR = ("budget_alert_inbox",) + + +def source_key(bundle: Bundle, org: str, namespace: str) -> str: + return f"{bundle.manifest['source']['deployment_id']}/{org}/{namespace}" + + +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} + rows = await ch.query_all( + "SELECT org, namespace, kind, active, owner_email, password_hash != '' AS password_hash, " + "released_aliases 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, + ) + groups = await ch.query_all( + "SELECT org, group_id FROM loom.principal_groups FINAL " + "WHERE org IN {orgs:Array(String)} AND NOT deleted", + params=p, + ) + landed = await ch.query_all( + "SELECT DISTINCT org, namespace, JSONExtractString(subject, 'source') AS source " + "FROM loom.audit_log WHERE org IN {orgs:Array(String)} " + "AND event_type = {event:String}", + params={**p, "event": LANDED_EVENT}, + ) + 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}) + 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")} + ), + groups=frozenset(str(g["group_id"]) for g in groups if g["org"] == org), + landed=frozenset( + (str(r["namespace"]), str(r["source"])) for r in landed if r["org"] == org + ), + ) + 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")) + selected: dict[str, list[str]] = bundle.manifest["namespaces"] + subjects: dict[str, set[str]] = {} + for g in bundle.records("grants"): + subjects.setdefault(str(g["org"]), set()).add(str(g["subject"])) + for r in rows: + if not is_account(r) and r.get("owner_email"): + subjects.setdefault(str(r["org"]), set()).add(str(r["owner_email"])) + for g in bundle.records("groups"): + subjects.setdefault(str(g["org"]), set()).update(str(m) for m in g.get("members") or []) + return plan( + source=bundle.manifest["source"]["deployment_id"], + rules=rules, + namespace_rows=rows, + selected=selected, + grant_subjects=subjects, + revoked={str(r["subject"]) for r in bundle.records("revoked")}, + targets=targets, + signs_in=signs_in, + ) + + +async def _columns(ch: Any, table: str) -> dict[str, str]: + rows = await ch.query_all( + "SELECT name, type FROM system.columns WHERE database = 'loom' AND table = {t:String} " + "AND default_kind NOT IN ('MATERIALIZED', 'ALIAS')", + params={"t": table}, + ) + return {str(r["name"]): str(r["type"]) for r in rows} + + +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.""" + types = await _columns(ch, table) + out = [] + for r in rows: + row = {} + for c, t in types.items(): + if c not in r: + continue + v = r[c] + if "DateTime" in t and isinstance(v, str): + v = datetime.fromisoformat(v) + row[c] = 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(fallback=_ACTOR) + self.subjects = p.subject_map() + self.version = time.time_ns() + self.now = naive_utc_now_seconds() + self.revoked = {str(r["subject"]) for r in bundle.records("revoked")} + self.counts: dict[str, dict[str, int]] = {} + + def next_version(self) -> int: + self.version += 1 + return self.version + + 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`: mapped, or `s` itself when the plan + did not decide it (an id the identity tuple carries); None when dropped.""" + return self.subjects.get((org, s), s) + + +async def _blacklist(run: _Run) -> None: + """The source's refusals, before any content: an org's and its namespaces' land in the + target org, a deployment-wide one is narrowed to each target org.""" + from server.memory.api.models_blacklist import BlacklistAddInput + from server.memory.app import blacklist + + ns_map = run.plan.namespace_map() + for b in run.bundle.records("blacklist"): + orgs = [b["org"]] if b["org"] != "*" else sorted(run.plan.orgs) + for org in orgs: + if org not in run.plan.orgs: + continue + target_org = run.plan.orgs[org] + if b["scope"] == "namespace": + d = ns_map.get((org, str(b["namespace"]))) + if d is None or d.action == "skip": + continue + scope, namespace = "namespace", d.target + else: + scope, namespace = "org", "*" + # One id per source pattern and target org: a rerun writes the same row again. + pid = uuid.uuid5(uuid.UUID(str(b["pattern_id"])), target_org) + await blacklist.add( + BlacklistAddInput.model_validate( + { + "org": target_org, + "namespace": namespace, + "pattern": b["pattern"], + "pattern_type": b["pattern_type"], + "scope": scope, + "reason": b.get("reason") or "", + "created_by": run.actor, + } + ), + str(pid), + ) + + +async def _namespace(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: + """Create the namespace `d` lands on: its landing recorded first, then its row unless + an earlier run wrote it. 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 server.auth.authz import identity_write + from server.auth.directory import directory + from server.auth.grant_claims import account_change + from server.core import grant_cache + from server.identity.store import namespaces as namespaces_repo + from server.observability import audit + + key = source_key(run.bundle, d.source_org, d.source) + async with account_change(d.target_org, d.target): + existing = await namespaces_repo.fetch_row(d.target_org, d.target, ch=run.ch) + landed = await run.ch.query_one( + "SELECT 1 AS x FROM loom.audit_log WHERE org = {org:String} " + "AND namespace = {ns:String} AND event_type = {event:String} " + "AND JSONExtractString(subject, 'source') = {source:String} LIMIT 1", + params={"org": d.target_org, "ns": d.target, "event": LANDED_EVENT, "source": key}, + ) + if landed is None: + if existing is not None or await directory().in_use(d.target_org, d.target, ch=run.ch): + raise SystemExit(f"{d.target_org}/{d.target} is in use on the target: plan again") + await audit.emit_strict( + event_type=LANDED_EVENT, + org=d.target_org, + namespace=d.target, + actor=run.actor, + subject={"source": key, "bundle": run.bundle.digest, "plan": run.plan.digest}, + ) + if existing is not None: + return + owner = ( + d.target if d.account else (run.subject(d.source_org, row["owner_email"]) or run.actor) + ) + new = {**row, **_CLEARED, "org": d.target_org, "namespace": d.target} + new.update({c: "" for c in _CLEARED_STR}, owner_email=owner, updated_at=run.now) + 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 in run.revoked: + new["password_hash"] = "" # revoked on the source: nobody claims it + with identity_write(): + await run.ch.insert("loom.namespaces", await _typed(run.ch, "namespaces", [new])) + await grant_cache.changed(d.target_org) + run.count(d, "namespace") + + +async def _types_and_groups(run: _Run, decisions: list[NsDecision]) -> None: + by_target = {(d.source_org, d.source): d for d in decisions} + have = await run.ch.query_all( + "SELECT org, namespace, memory_type FROM loom.namespace_types FINAL " + "WHERE org IN {orgs:Array(String)}", + params={"orgs": sorted(set(run.plan.orgs.values()))}, + ) + present = {(r["org"], r["namespace"], r["memory_type"]) for r in have} + types = [] + for t in run.bundle.records("types"): + d = by_target.get((t["org"], t["namespace"])) + if d is None or (d.target_org, d.target, t["memory_type"]) in present: + continue + types.append({**t, "org": d.target_org, "namespace": d.target, "updated_at": run.now}) + if types: + await run.ch.insert( + "loom.namespace_types", + await _typed(run.ch, "namespace_types", types), + settings={"async_insert": 0, "wait_for_async_insert": 1}, + ) + groups = [] + for g in run.bundle.records("groups"): + target_org = run.plan.orgs.get(str(g["org"])) + if target_org is None or g["group_id"] in run.targets[target_org].groups: + continue # the plan refused every grant to a group the target already has + members = sorted({m for s in g["members"] if (m := run.subject(g["org"], s))}) + groups.append({**g, "org": target_org, "members": members, "version": run.next_version()}) + if groups: + with _identity(): + await run.ch.insert( + "loom.principal_groups", await _typed(run.ch, "principal_groups", groups) + ) + + +def _identity() -> Any: + from server.auth.authz import identity_write + + return identity_write() + + +async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> 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 and the subject holds + no equal or higher role there. A dropped subject's grant is not written.""" + from server.identity.store import grants as grants_repo + from server.operations.base import grant_rank + + by_source = {(d.source_org, d.source): d for d in decisions} + held = await run.ch.query_all( + "SELECT org, namespace, subject, role FROM loom.namespace_grants FINAL " + "WHERE org IN {orgs:Array(String)} AND revoked_at IS NULL AND status = 'active'", + params={"orgs": sorted(set(run.plan.orgs.values()))}, + ) + have = {(r["org"], r["namespace"], r["subject"]): str(r["role"]) for r in held} + rows = [] + for g in run.bundle.records("grants"): + d = 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 + prior = have.get((d.target_org, d.target, subject)) + if prior is not None and grant_rank(prior) >= grant_rank(g["role"]): + continue + rows.append( + { + "org": d.target_org, + "namespace": d.target, + "subject": subject, + "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) + if not sso_same_issuer: + return + links = [] + for link in run.bundle.records("sso_links"): + d = by_source.get((link["org"], link["namespace"])) + if d is None or not d.account or d.source in run.revoked: + continue + links.append( + { + **link, + "org": d.target_org, + "namespace": d.target, + "linked_by": run.actor, + "version": run.next_version(), + } + ) + if links: + with _identity(): + await run.ch.insert("loom.sso_links", await _typed(run.ch, "sso_links", links)) + + +async def _seen_ids(ch: Any, org: str, namespace: str) -> set[str]: + """Every memory id the namespace has held, deleted ones too: a rerun never writes + back a row the target's owners deleted since the first run.""" + return { + str(r["id"]) + async for r in stream_rows( + ch, + "SELECT DISTINCT toString(memory_id) AS id FROM loom.memory " + "WHERE org = {org:String} AND namespace = {ns:String}", + {"org": org, "ns": namespace}, + ) + } + + +async def _memories(run: _Run, decisions: list[NsDecision]) -> None: + by_source = {(d.source_org, d.source): d for d in decisions} + batch: dict[tuple[str, str], list[dict[str, Any]]] = {} + seen: dict[tuple[str, str], set[str]] = {} + for m in run.bundle.records("memories"): + d = by_source.get((m["org"], m["namespace"])) + if d is None: + continue + if d.action == "create": + if (d.source_org, d.source) not in seen: + seen[(d.source_org, d.source)] = await _seen_ids(run.ch, d.target_org, d.target) + if m["memory_id"] in seen[(d.source_org, d.source)]: + run.count(d, "memories_present") + continue + for col in ("user_id", "verified_by", "locked_by"): + if m.get(col) and m[col] != "-": + m[col] = run.subject(d.source_org, m[col]) or ("-" if col == "user_id" else "") + rows = batch.setdefault((d.source_org, d.source), []) + rows.append(m) + if len(rows) >= _BATCH: + await _write_memories(run, d, rows) + rows.clear() + for key, rows in batch.items(): + if rows: + await _write_memories(run, by_source[key], rows) + + +async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) -> None: + from server.identity.api.models import _SnapshotMemoryRow + from server.memory.app import blacklist_guard + from server.memory.app import snapshot_rows as snap + + memories = [ + _SnapshotMemoryRow.model_validate( + {k: v for k, v in m.items() if k not in ("org", "namespace")} + ) + for m in raw + ] + kept = [] + for m in memories: + if await blacklist_guard.find_match(org=d.target_org, namespace=d.target, value=m.value): + run.count(d, "memories_refused") + else: + kept.append(m) + 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 _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. The row's time + of writing is the import's; its stated validity is the source's.""" + from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput + from server.memory.app.bulk_set import handle_memory_bulk_set + + groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} + for m in memories: + groups.setdefault((m.agent, m.user_id, m.session_id), []).append( + { + "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", + "tags": m.tags, + "entities": m.entities, + "valid_at": m.valid_at or m.created_at, + "valid_to": m.valid_to, + "pinned": m.pinned, + "char_limit": m.char_limit, + "files": m.files, + "concepts": m.concepts, + } + ) + for (agent, user_id, session_id), entries in groups.items(): + for start in range(0, len(entries), MAX_BULK_ENTRIES): + 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, + "entries": entries[start : start + MAX_BULK_ENTRIES], + } + ) + ) + run.count(d, "memories", sum(1 for w in out.written if w.version)) + + +async def _live_uris(ch: Any, org: str, namespace: str) -> set[str]: + return { + str(r["source_uri"]) + async for r in stream_rows( + ch, + "SELECT source_uri FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND superseded_at IS NULL", + {"org": org, "ns": namespace}, + ) + } + + +async def _documents(run: _Run, decisions: list[NsDecision]) -> None: + """Each document through `knowledge.upsert`, with its original: chunked and embedded + by the target's embedder. A source_uri the target namespace already serves is left as + it is, whether an earlier run wrote it or the target's owners did.""" + from server.knowledge.api.models_knowledge import KnowledgeUpsertInput + from server.knowledge.app.writes import handle_knowledge_upsert + + by_source = {(d.source_org, d.source): d for d in decisions} + live: dict[tuple[str, str], set[str]] = {} + for doc in run.bundle.records("documents"): + d = by_source.get((doc["org"], doc["namespace"])) + if d is None: + continue + if (d.target_org, d.target) not in live: + live[(d.target_org, d.target)] = await _live_uris(run.ch, d.target_org, d.target) + if doc["source_uri"] in live[(d.target_org, d.target)]: + run.count(d, "documents_present") + continue + original = None + if doc.get("blob_path") and not doc.get("blob_erased_at"): + original = base64.b64encode(run.bundle.original(doc["blob_path"])).decode() + 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 _merge_landings(run: _Run, decisions: list[NsDecision]) -> None: + """A merge's audit row, once per source namespace and target.""" + from server.observability import audit + + for d in decisions: + key = source_key(run.bundle, d.source_org, d.source) + if d.action == "merge" and (d.target, key) not in run.targets[d.target_org].landed: + await audit.emit_strict( + event_type=LANDED_EVENT, + org=d.target_org, + namespace=d.target, + actor=run.actor, + subject={"source": key, "bundle": run.bundle.digest, "plan": run.plan.digest}, + ) + + +async def apply( + ch: Any, bundle: Bundle, p: Plan, rules: MapFile, 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")} + live = [d for d in p.namespaces if d.action != "skip"] + await _blacklist(run) + for d in live: + if d.action == "create": + await _namespace(run, d, rows[(d.source_org, d.source)]) + await _merge_landings(run, live) + await _types_and_groups(run, live) + await _grants(run, live, rules.sso_same_issuer) + await _memories(run, live) + await _documents(run, live) + return { + "bundle": bundle.digest, + "plan": p.digest, + "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 00000000000..b6eb99bf8fc --- /dev/null +++ b/server/cli/instance_plan.py @@ -0,0 +1,491 @@ +"""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 grant subject the bundle cannot place. Each problem +names the map entry that settles it. 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/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 typing import Any, Literal + +from server.core.naming import ( + SSO_NAMESPACE_PREFIX, + is_reserved_name, + is_sso_namespace_name, + validate_namespace_name, +) + +NsAction = Literal["create", "merge", "skip"] +SubjectAction = Literal["claim", "map", "keep", "drop"] +# Subjects that name a principal of the org, not a person's account: kept as they are. +KEPT_PREFIXES = ("user:", "agent:", "group:") +KEPT_SUBJECTS = frozenset({"everyone"}) +# Service accounts and bots sign with credentials the source issued: their owners make +# new ones on the target, so their grants are not carried. +DROPPED_PREFIXES = ("sa:",) + + +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 _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 raw.get("grants"): + raise MapError(f"namespaces.{key}: grants applies to merge only") + return NsRule("create", str(raw["rename"])) + return NsRule("merge", str(raw["merge"]), bool(raw.get("grants", False))) + 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=bool(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 + groups: frozenset[str] + # (namespace, "//") of each landing an earlier import + # recorded: a run that stopped part way is resumed, never taken for a collision. + landed: frozenset[tuple[str, str]] = frozenset() + + +@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 + + +@dataclass(frozen=True) +class SubjectDecision: + source_org: str + subject: str + action: SubjectAction + target: str = "" + note: str = "" + + +@dataclass +class Plan: + 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 + + 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 + + def namespace_map(self) -> dict[tuple[str, str], NsDecision]: + return {(n.source_org, n.source): n for n in self.namespaces} + + @property + def digest(self) -> str: + """Names the decisions: `--expect-plan` refuses to apply a plan that changed.""" + body = json.dumps( + { + "orgs": self.orgs, + "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 _name_problem(name: str) -> str | None: + try: + validate_namespace_name(name) + except ValueError as e: + return str(e) + if is_reserved_name(name): + 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 contact email → "/" of every target account it reaches, + # in any org: single sign-on refuses an email whose accounts are in two orgs. + signs_in: Mapping[str, list[str]] + rows: dict[str, Mapping[str, Any]] # the source org's namespace rows by name + selected: list[str] + plan: Plan + taken: dict[str, str] = field(default_factory=dict) # target name → source it lands from + + 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 earlier landing.""" + return ( + target in self.target.namespaces + and (target, f"{self.source}/{self.org}/{source}") not in self.target.landed + ) + + def claim_name(self, name: str, source: str) -> bool: + """Reserve `name` on the target for `source`; False (and a problem) when it is taken.""" + 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] = source + return True + + +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) + email = str(row.get("contact_email") or "").strip().lower() + sso = not row.get("password_hash") + 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": + if 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" + ) + 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") + landed = f"{o.source}/{o.org}/{name}" + holders = [ + h + for h in (o.signs_in.get(email, []) if email else []) + if (h.partition("/")[2], landed) not in o.target.landed + or h.partition("/")[0] != o.target_org + ] + if holders: + org, _, account = holders[0].partition("/") + fix = account if org == o.target_org else "drop" + o.problem( + f"account {name!r}: {email} already signs in to {holders[0]!r} on the target; map " + "it there if it is the same person (same org only), or drop it", + key, + "subjects", + fix, + ) + return + if sso and not o.rules.sso_same_issuer: + 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, key): + return + o.subject(SubjectDecision(o.org, name, "claim", handle, note=email)) + o.plan.namespaces.append( + NsDecision(o.org, name, o.target_org, handle, "create", account="sso" if sso else "claim") + ) + + +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, key): + o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, target, "create")) + + +def _plan_subject(o: _Org, subject: str) -> None: + """A grant subject or owner that is no account of the bundle.""" + key = f"{o.org}/{subject}" + rule = o.rules.subjects.get(key) + if rule is not None: + if rule.action == "map" 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" + ) + return + if rule.action == "claim": + o.problem(f"subjects.{key}: only an account of the bundle can be claimed") + return + o.subject( + SubjectDecision( + o.org, subject, rule.action, rule.target if rule.action == "map" else subject + ) + ) + return + if subject.startswith("group:") and subject.removeprefix("group:") in o.target.groups: + o.problem( + f"group {subject!r} exists on the target with its own members: map the grants to " + "a target subject, or drop them", + key, + "subjects", + "drop", + ) + return + if subject in KEPT_SUBJECTS or subject.startswith(KEPT_PREFIXES): + o.subject(SubjectDecision(o.org, subject, "keep", subject)) + return + if subject.startswith(DROPPED_PREFIXES): + o.subject( + SubjectDecision( + o.org, subject, "drop", note="service account: its owner makes a new one" + ) + ) + return + if "@" in subject: + # 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 + o.problem( + f"subject {subject!r} holds grants or owns a namespace but is no account of the " + "bundle: map it to its owner's target subject, or drop it", + key, + "subjects", + "drop", + ) + + +def plan( + *, + source: str, + rules: MapFile, + namespace_rows: Iterable[Mapping[str, Any]], + selected: Mapping[str, list[str]], + grant_subjects: Mapping[str, set[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). + `grant_subjects` is each source org's grant subjects and namespace owners; `targets` + the target state of each target org; `signs_in` every target account by email; `revoked` + the source subjects revoked outright.""" + p = Plan(orgs={}, namespaces=[], subjects=[], problems=[], proposals={}) + by_org: dict[str, dict[str, Mapping[str, Any]]] = {} + for r in namespace_rows: + by_org.setdefault(str(r["org"]), {})[str(r["namespace"])] = r + 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 + o = _Org( + source, + org, + target_org, + rules, + targets[target_org], + signs_in, + by_org.get(org, {}), + selected[org], + p, + ) + 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} + for subject in sorted(grant_subjects.get(org, set()) - decided): + _plan_subject(o, subject) + for s in p.subjects: + if s.source_org == org and s.subject in revoked and s.action == "map": + 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: claim or drop it" + ) + 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/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index d5c7820eac0..c31b528de8f 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": [ @@ -286,6 +286,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 6eda63b71c8..3ae7e95160e 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -7430,6 +7430,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": [ + "instance_cmd" + ] + }, + { + "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": "instance_cmd", + "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": true, + "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, @@ -17248,6 +17552,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", @@ -17388,6 +17693,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_instance_consolidation.py b/tests/unit/test_instance_consolidation.py new file mode 100644 index 00000000000..a0fb8c2df8b --- /dev/null +++ b/tests/unit/test_instance_consolidation.py @@ -0,0 +1,158 @@ +"""`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 +from pathlib import Path +from typing import Any + +import pytest + +from server.cli.instance_bundle import Bundle, BundleError, BundleWriter +from server.cli.instance_export import select_namespaces +from server.cli.instance_plan import MapError, TargetOrg, parse_map, plan + +SOURCE = "dep-1" + + +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", + } + + +def _ns(org: str, name: str, owner: str) -> dict[str, Any]: + return {"org": org, "namespace": name, "owner_email": owner} + + +def _plan( + rows: list[dict[str, Any]], + *, + subjects: set[str] | None = None, + target: TargetOrg | None = None, + rules: Any = None, + signs_in: dict[str, list[str]] | None = None, +) -> Any: + return plan( + source=SOURCE, + rules=parse_map(rules), + namespace_rows=rows, + selected={"acme": sorted(r["namespace"] for r in rows)}, + grant_subjects={"acme": subjects or set()}, + revoked=set(), + targets={"acme": target or TargetOrg({}, frozenset(), frozenset())}, + 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" + with pytest.raises(BundleError, match="not empty"): + BundleWriter(out) + + (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"}), frozenset()) + 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", ""), + } + + +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(), frozenset({"eng"})) + p = _plan(rows, subjects={"ci-bot", "group:eng", "group:ops", "sa:ci", "bob@x"}, 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 + assert p.proposals["subjects"] == {"acme/ci-bot": "drop", "acme/group:eng": "drop"} + decided = {s.subject: s.action for s in p.subjects} + assert decided == {"group:ops": "keep", "sa:ci": "drop", "bob@x": "keep"} + + +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 + p = _plan(rows, signs_in={"bob@x": ["acme/robert"]}) + assert p.proposals == {"subjects": {"acme/bob": "robert"}} + + +def test_a_resumed_run_plans_the_same_digest() -> None: + rows = [_account("acme", "alice", "alice@x"), _ns("acme", "team", "alice")] + first = _plan(rows, subjects={"alice"}) + landed = TargetOrg( + {"alice": {"kind": "memory"}, "team": {"kind": "memory"}}, + frozenset({"alice"}), + frozenset(), + landed=frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}), + ) + again = _plan(rows, subjects={"alice"}, target=landed, signs_in={"alice@x": ["acme/alice"]}) + assert again.problems == [] and again.digest == first.digest + other = _plan( + rows, + subjects={"alice"}, + target=TargetOrg(landed.namespaces, landed.subjects, frozenset()), + ) + assert other.problems # the same names, not landed by this source + + +def test_merge_needs_a_target_namespace_and_map_errors_name_the_entry() -> None: + p = _plan( + [_ns("acme", "team", "x")], + subjects={"x"}, + rules={"namespaces": {"acme/team": {"merge": "t"}}}, + ) + assert any("no memory namespace 't'" 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": {}}) + + +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-mirror", "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": ["alice", "bob", "carol", "team"]} From 6313d22016db2583e747fe81c92dda83e07b5735 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 21:20:58 +0530 Subject: [PATCH 02/32] loom instance import: a finished landing is left alone, shared target orgs need the map - An instance.import.done audit row marks each namespace whose content landed; later runs skip it, so what the target deleted or revoked since stays so. Groups get landing rows too, and reruns skip revoked grants and existing blacklist ids. - Two source orgs landing in one target org share its names and groups; a name or group both bring refuses the plan. - everyone, user: and agent: subjects need keep, a mapping or drop in a target org that serves others; memory user ids follow the user: decision, and two source users may not land as one. - Blacklist patterns land narrowed to the moved namespaces they reach. - A merge carries validity, expiry, sensitivity, evidence and grounding, and skips rows that are no live fact; per-type settings land with created namespaces only. - Model calls run under the target org's customer attribution. - The plan digest binds the bundle; the map's flags are strict booleans; collection and alias names are refused. - The export carries only the groups its grants name, filters identity rows by the selected pairs, streams every section, checks each original's hash, and refuses under the Postgres authority while documents await publication. - A claim under another handle plans the same digest when run again. - An integration test moves an org into a live one, field for field, with a merge and a rerun that writes nothing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 49 +- server/cli/instance.py | 2 + server/cli/instance_export.py | 155 +++-- server/cli/instance_import.py | 629 ++++++++++-------- server/cli/instance_plan.py | 198 ++++-- .../test_instance_consolidation.py | 204 ++++++ tests/unit/test_instance_consolidation.py | 150 ++++- 7 files changed, 961 insertions(+), 426 deletions(-) create mode 100644 tests/integration/test_instance_consolidation.py diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 22fbec9319e..33d6b81ec61 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -13,8 +13,8 @@ run, with their settings. To move a whole deployment onto new hosts, see | Memory namespaces, with their settings and per-type settings | 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 and revoked grants | -| Groups the target org does not have, with their mapped members | Conversations, session briefs and tasks: the manifest counts them | -| Blacklist entries, before any content | Knowledge sources with a remote: the manifest lists them to register again | +| Groups the moved grants name, with their mapped members | Conversations, session briefs and tasks: the manifest counts them | +| Blacklist entries, before any content, each on the moved namespaces it reaches | Knowledge sources with a remote: the manifest lists them to register again | | Memories: every live head, with its `created_at`, validity and attestation | Embeddings, caches, traces and rollups: the target builds them again | | Documents with their originals, embedded again by the target's embedder | The audit log and agent events | @@ -24,7 +24,9 @@ worker's next full pass embeds them (`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SEC ## Procedure -1. Finish the source's erasures: the export refuses while one has not completed. +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. 3. Export, on the source: @@ -34,8 +36,8 @@ worker's next full pass embeds them (`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SEC loom instance export --org acme --namespace notes --out ./notes-bundle ``` - With `--namespace`, the bundle carries that namespace's content and the account rows - of every subject its grants and owner name, so the plan can place them. The bundle + With `--namespace`, the bundle carries that namespace's content, and the account rows + and groups its grants and owner name, so the plan can place them. The bundle holds password hashes: it is written readable by its owner only, and is copied to the target the way a database dump is. @@ -78,11 +80,15 @@ subjects: # "/": rule - **Namespaces.** A namespace is created under its own name, or the name the map gives it. 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. + that holds data with no namespace row. Two source orgs landing in one target org may + not bring the same name. `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; - a merged row's `created_at` is the import's and its `valid_at` the source's. A document - whose `source_uri` the target namespace already serves is left as it is. + conflict surfacing, pinned peers and the skip of an unchanged restatement hold there. + It writes live facts only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the + target namespace already serves is left as it is. Per-type settings land with a + created namespace only. - **Accounts.** An account lands as a claimable password account under its handle. The plan refuses a handle the target holds and an email any target account signs in with, proposing a new handle or the target account. Mapping an account onto a target account @@ -91,18 +97,25 @@ subjects: # "/": rule or `sso_same_issuer: true` when both deployments use the same identity provider, which also carries its links. An account the source revoked lands with no password. - **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves - the address at sign-in on the target. `user:`, `agent:` and `group:` subjects are kept, - except a group the target org already has, which needs a mapping. `sa:` subjects are - dropped. Any other subject needs a mapping or `drop`. + the address at sign-in on the target. `everyone`, `user:` and `agent:` subjects are + kept in a target org only the import lands in. In one that serves others, or that two + source orgs land in, they would also name its own people, so each needs `keep`, a + mapping or `drop`. A `user:` mapping also moves the memories of that end user; two + source users may not land as one. A `group:` subject is kept, except a group the target + org already has or that two source orgs both bring, which needs a mapping. `sa:` + subjects are dropped. Any other subject needs a mapping or `drop`. ## Running it again -An import that stops part way runs again with the same command. Before it creates a -namespace it writes an `instance.import` audit row naming the source namespace, and a -later plan reads that row as this source's landing, not as a collision. A run writes no -memory id the namespace has held, deleted ones included, and no document whose -`source_uri` it serves; a grant whose subject already holds that role or a higher one is -not written again. +An import that stops part way runs again with the same command, and plans the same +digest. Before it lands a namespace or a group it writes an `instance.import` audit row +naming its source, and a later plan reads that row as this source's landing, not as 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 no memory id the +namespace has held, deleted ones included, and no document whose `source_uri` it has +held; it writes no grant its subject already holds at that role or higher, or that was +revoked. ## Related diff --git a/server/cli/instance.py b/server/cli/instance.py index cf2ae880a50..31c8cd928b0 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -86,6 +86,8 @@ def _print_plan(bundle: Any, p: Any) -> None: 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 namespaces above that it reaches") 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)") diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 2bde9f65ddc..93242855150 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -15,7 +15,7 @@ import json import os -from collections.abc import AsyncIterator, Sequence +from collections.abc import AsyncIterator, Iterable, Sequence from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -70,7 +70,6 @@ async def refuse_unfinished_erasures(ch: Any, orgs: Sequence[str]) -> None: SELECT toString(id) AS id, org, scope_type, toString(status) AS status FROM loom.erasure_requests FINAL WHERE org IN {orgs:Array(String)} AND status != 'completed' - AND requested_at > now() - INTERVAL 89 DAY """, params={"orgs": list(orgs)}, ) @@ -82,6 +81,28 @@ async def refuse_unfinished_erasures(ch: Any, orgs: Sequence[str]) -> None: ) +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, a benchmark's, a mirror's, a code store's or a collection, and not soft-deleted.""" @@ -94,62 +115,86 @@ def exported_namespace(row: dict[str, Any]) -> bool: def select_namespaces( - rows: list[dict[str, Any]], grants: list[dict[str, Any]], wanted: list[str] | None -) -> dict[str, list[str]]: - """Per org, the namespaces the bundle carries: every exported one, or the `wanted` - ones together with the accounts that own them or hold grants on them, so the plan can - place every subject they name.""" + rows: list[dict[str, Any]], + grants: list[dict[str, Any]], + groups: list[dict[str, Any]], + wanted: list[str] | None, +) -> tuple[dict[str, list[str]], dict[str, list[str]]]: + """Per org, the namespaces the bundle carries, and the groups their grants name: every + exported namespace, or the `wanted` ones together with the accounts that own them, + hold grants on them or belong to a group that does, so the plan can place every + subject they name.""" 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"])) + 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 "")) + for g in grants: + if g["namespace"] in out.get(str(g["org"]), set()): + named.setdefault(str(g["org"]), set()).add(str(g["subject"])) + group_ids: dict[str, list[str]] = {} + for g in groups: + org = str(g["org"]) + if f"group:{g['group_id']}" in named.get(org, set()): + group_ids.setdefault(org, []).append(str(g["group_id"])) + named[org].update(str(m) for m in g.get("members") or []) 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 "")) - for g in grants: - if g["namespace"] in out.get(str(g["org"]), set()): - named.setdefault(str(g["org"]), set()).add(str(g["subject"])) for r in rows: if ( is_account(r) and exported_namespace(r) - and r["namespace"] in named.get(r["org"], ()) + and r["namespace"] in named.get(str(r["org"]), ()) ): - out[str(r["org"])].add(str(r["namespace"])) - return {org: sorted(names) for org, names in out.items()} + out.setdefault(str(r["org"]), set()).add(str(r["namespace"])) + return ( + {org: sorted(names) for org, names in out.items()}, + {org: sorted(ids) for org, ids in group_ids.items()}, + ) -def _write(w: BundleWriter, section: str, rows: list[dict[str, Any]]) -> None: +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] -) -> list[dict[str, Any]]: - rows = [r async for r in stream_rows(ch, sql, params)] - _write(w, section, rows) - return rows +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]] + w: BundleWriter, + ch: Any, + orgs: list[str], + selected: dict[str, list[str]], + group_ids: dict[str, list[str]], ) -> None: - namespaces = sorted({n for names in selected.values() for n in names}) - p = {"orgs": orgs, "ns": namespaces} + p: dict[str, Any] = { + "orgs": orgs, + "pairs": _pairs(selected), + "groups": [(org, g) for org, ids in group_ids.items() for g in ids], + "subjects": sorted({ns for _, ns in _pairs(selected)}), + } in_orgs = "org IN {orgs:Array(String)}" - in_ns = f"{in_orgs} AND namespace IN {{ns:Array(String)}}" + in_ns = "(org, namespace) IN {pairs:Array(Tuple(String, String))}" await _table(w, ch, "types", f"SELECT * FROM loom.namespace_types FINAL WHERE {in_ns}", p) await _table( w, ch, "groups", - f"SELECT * FROM loom.principal_groups FINAL WHERE {in_orgs} AND NOT deleted", + "SELECT * FROM loom.principal_groups FINAL " + "WHERE (org, group_id) IN {groups:Array(Tuple(String, String))} AND NOT deleted", p, ) await _table( @@ -181,28 +226,27 @@ async def _identity_sections( f"SELECT org, subject, kind FROM loom.connected_accounts FINAL WHERE {in_orgs} AND active", p, ) - # The org's and its namespaces' refusals; the deployment-wide ones ('*') too, which the - # importer narrows to the target org: a source's global refusal is not another org's. + # 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 (org IN {orgs:Array(String)} - AND (namespace = '*' OR namespace IN {ns:Array(String)}) - OR org = '*') + WHERE ({in_ns} OR (org IN {{orgs:Array(String)}} AND namespace = '*') OR org = '*') AND tombstoned_at IS NULL """, p, ) - # A subject the source revoked outright stays revoked where its account lands. + # An account the source revoked outright lands with no password. await _table( w, ch, "revoked", "SELECT jti AS subject, reason FROM loom.revoked_tokens FINAL " - "WHERE jti IN {ns:Array(String)} AND issued_before IS NULL AND expires_at > now()", + "WHERE jti IN {subjects:Array(String)} AND issued_before IS NULL AND expires_at > now()", p, ) @@ -282,12 +326,11 @@ async def _documents( 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: + if data is None or w.original(data) != sha: raise SystemExit( - f"{org}/{ns} document {uri!r}: its original {sha} cannot be read; " - "repair it or erase the document" + f"{org}/{ns} document {uri!r}: its original {sha} cannot be read back as " + "stored; repair it or erase the document" ) - w.original(data) async def _left_behind(ch: Any, orgs: list[str]) -> dict[str, Any]: @@ -306,6 +349,8 @@ async def _left_behind(ch: Any, orgs: list[str]) -> dict[str, Any]: rows = await ch.query_all( "SELECT 'conversations' AS kind, org, count() AS n FROM loom.conversations " "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'session_briefs', org, count() FROM loom.session_briefs FINAL " + "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'tasks', org, count() FROM loom.tasks FINAL " "WHERE org IN {orgs:Array(String)} AND is_deleted = 0 GROUP BY org", params=p, @@ -321,33 +366,39 @@ async def export( await refuse_unfinished_erasures(ch, orgs) source = await _deployment_id(ch) - os.umask(0o077) - w = BundleWriter(out) p = {"orgs": orgs} - rows = [ + 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, "SELECT * FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", p + ch, + f"SELECT * FROM loom.namespace_grants FINAL {in_orgs} " + "AND revoked_at IS NULL AND status = 'active'", + p, ) ] - grants = [ + groups = [ r async for r in stream_rows( ch, - "SELECT * FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)} " - "AND revoked_at IS NULL AND status = 'active'", + f"SELECT org, group_id, members FROM loom.principal_groups FINAL {in_orgs} " + "AND NOT deleted", p, ) ] - selected = select_namespaces(rows, grants, namespaces) - _write(w, "namespaces", [r for r in rows if r["namespace"] in selected.get(r["org"], ())]) - _write(w, "grants", [g for g in grants if g["namespace"] in selected.get(g["org"], ())]) - await _identity_sections(w, ch, orgs, selected) + selected, group_ids = select_namespaces(rows, grants, groups, namespaces) # 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() } + await refuse_unpublished_documents(content) + os.umask(0o077) + w = BundleWriter(out) + _write(w, "namespaces", (r for r in rows if r["namespace"] in selected.get(r["org"], ()))) + _write(w, "grants", (g for g in grants if g["namespace"] in selected.get(g["org"], ()))) + await _identity_sections(w, ch, orgs, selected, group_ids) counts: Counts = {} await _memories(w, ch, content, counts) await _documents(w, ch, content, counts) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index ae460d6589f..efee1939324 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -2,15 +2,18 @@ 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. Apply then writes, in order: the refusals (blacklist), each created -namespace (an audit row naming its source first, so a run that stops part way is resumed, -then the namespace row), types and groups, grants under the mapped subjects, memories and -documents. A created namespace receives its memories as a restore does (every column, +changed since, or a different bundle. Each namespace the plan lands is one landing: an +`instance.import` audit row 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 no memory id or document the namespace has held and no +grant its subject already holds or a target admin revoked. + +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. Documents go through `knowledge.upsert` with their originals, so the target's embedder embeds them; memories are embedded by the embedding -worker's next full pass. A rerun skips what landed: memory ids the namespace has had, -documents whose source_uri already holds the same content. +worker's next full pass. Every model call is made for the target org. """ from __future__ import annotations @@ -20,24 +23,31 @@ import time import uuid from collections.abc import Iterable, Mapping -from datetime import datetime +from datetime import UTC, datetime from typing import Any from server.cli.instance_bundle import Bundle from server.cli.instance_export import stream_rows from server.cli.instance_plan import MapFile, NsDecision, Plan, TargetOrg, is_account, plan -_ACTOR = "process:cli:instance" -LANDED_EVENT = "instance.import" +LANDED = "instance.import" +DONE = "instance.import.done" _BATCH = 500 # Settings that name the source's own services or rows: cleared, the target's owners set # them again. -_CLEARED = {"rerank_endpoint": "", "classify_endpoint": "", "released_aliases": []} -_CLEARED_STR = ("budget_alert_inbox",) +_CLEARED: dict[str, Any] = { + "rerank_endpoint": "", + "classify_endpoint": "", + "released_aliases": [], + "budget_alert_inbox": "", +} +# A row in any other state is history, not a fact a merge states again. +_MERGED_STATUS = "active" +_SEQUENTIAL = " SETTINGS select_sequential_consistency = 1" -def source_key(bundle: Bundle, org: str, namespace: str) -> str: - return f"{bundle.manifest['source']['deployment_id']}/{org}/{namespace}" +def source_key(bundle: Bundle, org: str, name: str) -> str: + return f"{bundle.manifest['source']['deployment_id']}/{org}/{name}" async def load_target( @@ -46,7 +56,7 @@ async def load_target( """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} + p = {"orgs": orgs, "events": [LANDED, DONE]} rows = await ch.query_all( "SELECT org, namespace, kind, active, owner_email, password_hash != '' AS password_hash, " "released_aliases FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", @@ -62,11 +72,11 @@ async def load_target( "WHERE org IN {orgs:Array(String)} AND NOT deleted", params=p, ) - landed = await ch.query_all( - "SELECT DISTINCT org, namespace, JSONExtractString(subject, 'source') AS source " - "FROM loom.audit_log WHERE org IN {orgs:Array(String)} " - "AND event_type = {event:String}", - params={**p, "event": LANDED_EVENT}, + landings = await ch.query_all( + "SELECT DISTINCT event_type, org, JSONExtractString(subject, 'name') AS name, " + "JSONExtractString(subject, 'source') AS source FROM loom.audit_log " + "WHERE org IN {orgs:Array(String)} AND event_type IN {events:Array(String)}" + _SEQUENTIAL, + params=p, ) out: dict[str, TargetOrg] = {} for org in orgs: @@ -75,6 +85,14 @@ async def load_target( 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( @@ -83,9 +101,8 @@ async def load_target( | {str(r["owner_email"]) for r in mine if r.get("owner_email")} ), groups=frozenset(str(g["group_id"]) for g in groups if g["org"] == org), - landed=frozenset( - (str(r["namespace"]), str(r["source"])) for r in landed if r["org"] == org - ), + landed=pairs(LANDED), + done=pairs(DONE), ) signs_in: dict[str, list[str]] = {} async for r in stream_rows( @@ -106,50 +123,60 @@ def build_plan( signs_in: Mapping[str, list[str]], ) -> Plan: rows = list(bundle.records("namespaces")) - selected: dict[str, list[str]] = bundle.manifest["namespaces"] subjects: dict[str, set[str]] = {} + + def add(org: Any, subject: Any) -> None: + subjects.setdefault(str(org), set()).add(str(subject)) + for g in bundle.records("grants"): - subjects.setdefault(str(g["org"]), set()).add(str(g["subject"])) + add(g["org"], g["subject"]) for r in rows: if not is_account(r) and r.get("owner_email"): - subjects.setdefault(str(r["org"]), set()).add(str(r["owner_email"])) + add(r["org"], r["owner_email"]) + groups: dict[str, set[str]] = {} for g in bundle.records("groups"): - subjects.setdefault(str(g["org"]), set()).update(str(m) for m in g.get("members") or []) + groups.setdefault(str(g["org"]), set()).add(str(g["group_id"])) + for m in g.get("members") or []: + add(g["org"], m) + for m in bundle.records("memories"): # an end user's rows follow their decision + if m.get("user_id") not in (None, "", "-"): + add(m["org"], 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=selected, + selected=bundle.manifest["namespaces"], grant_subjects=subjects, + groups=groups, + links=links, revoked={str(r["subject"]) for r in bundle.records("revoked")}, targets=targets, signs_in=signs_in, ) -async def _columns(ch: Any, table: str) -> dict[str, str]: - rows = await ch.query_all( +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.""" + cols = await ch.query_all( "SELECT name, type FROM system.columns WHERE database = 'loom' AND table = {t:String} " "AND default_kind NOT IN ('MATERIALIZED', 'ALIAS')", params={"t": table}, ) - return {str(r["name"]): str(r["type"]) for r in rows} - - -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.""" - types = await _columns(ch, 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 not in r: - continue - v = r[c] - if "DateTime" in t and isinstance(v, str): - v = datetime.fromisoformat(v) - row[c] = v + 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 @@ -160,12 +187,13 @@ class _Run: 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 + from server.memory.domain.provenance import cli_actor self.ch = ch self.bundle = bundle self.plan = p self.targets = targets - self.actor = writer_actor(fallback=_ACTOR) + self.actor = writer_actor(fallback=cli_actor("instance")) self.subjects = p.subject_map() self.version = time.time_ns() self.now = naive_utc_now_seconds() @@ -176,157 +204,189 @@ 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`: mapped, or `s` itself when the plan - did not decide it (an id the identity tuple carries); None when dropped.""" + """The target subject of source subject `s`; None when dropped.""" return self.subjects.get((org, s), 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) -> None: + from server.observability import audit + + await audit.emit_strict( + event_type=event, + org=org, + namespace=namespace, + actor=self.actor, + subject={ + "name": name, + "source": source, + "bundle": self.bundle.digest, + "plan": self.plan.digest, + }, + ) -async def _blacklist(run: _Run) -> None: - """The source's refusals, before any content: an org's and its namespaces' land in the - target org, a deployment-wide one is narrowed to each target org.""" - from server.memory.api.models_blacklist import BlacklistAddInput - from server.memory.app import blacklist - ns_map = run.plan.namespace_map() - for b in run.bundle.records("blacklist"): - orgs = [b["org"]] if b["org"] != "*" else sorted(run.plan.orgs) - for org in orgs: - if org not in run.plan.orgs: - continue - target_org = run.plan.orgs[org] - if b["scope"] == "namespace": - d = ns_map.get((org, str(b["namespace"]))) - if d is None or d.action == "skip": - continue - scope, namespace = "namespace", d.target - else: - scope, namespace = "org", "*" - # One id per source pattern and target org: a rerun writes the same row again. - pid = uuid.uuid5(uuid.UUID(str(b["pattern_id"])), target_org) - await blacklist.add( - BlacklistAddInput.model_validate( - { - "org": target_org, - "namespace": namespace, - "pattern": b["pattern"], - "pattern_type": b["pattern_type"], - "scope": scope, - "reason": b.get("reason") or "", - "created_by": run.actor, - } - ), - str(pid), - ) +def _identity() -> Any: + from server.auth.authz import identity_write + return identity_write() -async def _namespace(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: - """Create the namespace `d` lands on: its landing recorded first, then its row unless - an earlier run wrote it. 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 server.auth.authz import 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 server.auth.directory import directory from server.auth.grant_claims import account_change from server.core import grant_cache from server.identity.store import namespaces as namespaces_repo - from server.observability import audit - key = source_key(run.bundle, d.source_org, d.source) + key = run.key(d.source_org, d.source) + landed = (d.target, key) in run.targets[d.target_org].landed + if d.action == "merge": + if not landed: + await run.audit(LANDED, d.target_org, d.target, d.target, key) + return async with account_change(d.target_org, d.target): existing = await namespaces_repo.fetch_row(d.target_org, d.target, ch=run.ch) - landed = await run.ch.query_one( - "SELECT 1 AS x FROM loom.audit_log WHERE org = {org:String} " - "AND namespace = {ns:String} AND event_type = {event:String} " - "AND JSONExtractString(subject, 'source') = {source:String} LIMIT 1", - params={"org": d.target_org, "ns": d.target, "event": LANDED_EVENT, "source": key}, - ) - if landed is None: + if not landed: if existing is not None or await directory().in_use(d.target_org, d.target, ch=run.ch): raise SystemExit(f"{d.target_org}/{d.target} is in use on the target: plan again") - await audit.emit_strict( - event_type=LANDED_EVENT, - org=d.target_org, - namespace=d.target, - actor=run.actor, - subject={"source": key, "bundle": run.bundle.digest, "plan": run.plan.digest}, - ) + await run.audit(LANDED, d.target_org, d.target, d.target, key) if existing is not None: return - owner = ( - d.target if d.account else (run.subject(d.source_org, row["owner_email"]) or run.actor) - ) + 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({c: "" for c in _CLEARED_STR}, owner_email=owner, updated_at=run.now) + new.update(owner_email=owner or run.actor, updated_at=run.now) 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 in run.revoked: new["password_hash"] = "" # revoked on the source: nobody claims it - with identity_write(): + 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") -async def _types_and_groups(run: _Run, decisions: list[NsDecision]) -> None: - by_target = {(d.source_org, d.source): d for d in decisions} - have = await run.ch.query_all( - "SELECT org, namespace, memory_type FROM loom.namespace_types FINAL " - "WHERE org IN {orgs:Array(String)}", - params={"orgs": sorted(set(run.plan.orgs.values()))}, - ) - present = {(r["org"], r["namespace"], r["memory_type"]) for r in have} - types = [] - for t in run.bundle.records("types"): - d = by_target.get((t["org"], t["namespace"])) - if d is None or (d.target_org, d.target, t["memory_type"]) in present: - continue - types.append({**t, "org": d.target_org, "namespace": d.target, "updated_at": run.now}) - if types: +async def _types(run: _Run, d: NsDecision) -> None: + """A created namespace's per-type settings: a merged one keeps the target's.""" + rows = [ + {**t, "org": d.target_org, "namespace": d.target, "updated_at": run.now} + for t in run.bundle.records("types") + if (t["org"], t["namespace"]) == (d.source_org, d.source) + ] + if rows: await run.ch.insert( "loom.namespace_types", - await _typed(run.ch, "namespace_types", types), + await _typed(run.ch, "namespace_types", rows), settings={"async_insert": 0, "wait_for_async_insert": 1}, ) - groups = [] + + +async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) -> None: + """The source's refusals that reach the source namespace (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. One id per pattern and landing, so a + pattern the target's owners removed is not added back.""" + from server.memory.api.models_blacklist import BlacklistAddInput + from server.memory.app import blacklist + + ids = [ + uuid.uuid5(uuid.UUID(str(b["pattern_id"])), f"{d.target_org}/{d.target}") for b in patterns + ] + have = await run.ch.query_all( + "SELECT DISTINCT toString(pattern_id) AS id FROM loom.blacklist " + "WHERE pattern_id IN {ids:Array(UUID)}", + params={"ids": [str(i) for i in ids]}, + ) + present = {str(r["id"]) for r in have} + for b, pid in zip(patterns, ids, strict=True): + reaches = b["org"] == "*" or ( + b["org"] == d.source_org and b["namespace"] in ("*", d.source) + ) + if not reaches or str(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, + } + ), + str(pid), + ) + run.count(d, "refusals") + + +async def _groups(run: _Run, decisions: list[NsDecision]) -> None: + """The groups the plan keeps and the target org does not have (or an earlier run of + this source created and did not finish), with their mapped members.""" + kept = {(s.source_org, s.subject) for s in run.plan.subjects if s.action == "keep"} + orgs = {d.source_org for d in decisions} + rows = [] for g in run.bundle.records("groups"): - target_org = run.plan.orgs.get(str(g["org"])) - if target_org is None or g["group_id"] in run.targets[target_org].groups: - continue # the plan refused every grant to a group the target already has - members = sorted({m for s in g["members"] if (m := run.subject(g["org"], s))}) - groups.append({**g, "org": target_org, "members": members, "version": run.next_version()}) - if groups: + org, name = str(g["org"]), f"group:{g['group_id']}" + if org not in orgs or (org, name) not in kept: + continue + target_org, key = run.plan.orgs[org], run.key(org, name) + target = run.targets[target_org] + if (name, key) not in target.landed: + await run.audit(LANDED, target_org, "*", name, key) + elif g["group_id"] in target.groups: + continue # landed by an earlier run: its members are the target's now + members = sorted({m for s in g["members"] if (m := run.subject(org, s))}) + rows.append({**g, "org": target_org, "members": members, "version": run.next_version()}) + if rows: with _identity(): await run.ch.insert( - "loom.principal_groups", await _typed(run.ch, "principal_groups", groups) + "loom.principal_groups", await _typed(run.ch, "principal_groups", rows) ) -def _identity() -> Any: - from server.auth.authz import identity_write - - return identity_write() - - async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> 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 and the subject holds - no equal or higher role there. A dropped subject's grant is not written.""" + namespace, and on a merged one when the map carries its grants. Never written: a + dropped subject's, one the subject already holds at that role or higher, one a target + admin revoked.""" from server.identity.store import grants as grants_repo from server.operations.base import grant_rank by_source = {(d.source_org, d.source): d for d in decisions} held = await run.ch.query_all( - "SELECT org, namespace, subject, role FROM loom.namespace_grants FINAL " - "WHERE org IN {orgs:Array(String)} AND revoked_at IS NULL AND status = 'active'", - params={"orgs": sorted(set(run.plan.orgs.values()))}, + "SELECT org, namespace, subject, role, revoked_at IS NOT NULL AS revoked " + "FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)}" + _SEQUENTIAL, + params={"orgs": sorted({d.target_org for d in decisions})}, ) - have = {(r["org"], r["namespace"], r["subject"]): str(r["role"]) for r in held} + have = { + (r["org"], r["namespace"], r["subject"]): "" if r["revoked"] else str(r["role"]) + for r in held + } rows = [] for g in run.bundle.records("grants"): d = by_source.get((g["org"], g["namespace"])) @@ -334,8 +394,9 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) if d is None or subject is None or (d.action == "merge" and not d.grants): continue prior = have.get((d.target_org, d.target, subject)) - if prior is not None and grant_rank(prior) >= grant_rank(g["role"]): + if prior == "" or (prior is not None and grant_rank(prior) >= grant_rank(g["role"])): continue + have[(d.target_org, d.target, subject)] = str(g["role"]) rows.append( { "org": d.target_org, @@ -352,35 +413,33 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) run.count(d, "grants") with _identity(): await grants_repo.insert_rows(rows, ch=run.ch) - if not sso_same_issuer: - return - links = [] - for link in run.bundle.records("sso_links"): - d = by_source.get((link["org"], link["namespace"])) - if d is None or not d.account or d.source in run.revoked: - continue - links.append( - { - **link, - "org": d.target_org, - "namespace": d.target, - "linked_by": run.actor, - "version": run.next_version(), - } - ) + links = [ + { + **link, + "org": d.target_org, + "namespace": d.target, + "linked_by": run.actor, + "version": run.next_version(), + } + for link in run.bundle.records("sso_links") + if sso_same_issuer + and (d := by_source.get((link["org"], link["namespace"]))) is not None + and d.account + and d.source not in run.revoked + ] if links: with _identity(): await run.ch.insert("loom.sso_links", await _typed(run.ch, "sso_links", links)) -async def _seen_ids(ch: Any, org: str, namespace: str) -> set[str]: - """Every memory id the namespace has held, deleted ones too: a rerun never writes - back a row the target's owners deleted since the first run.""" +async def _seen(ch: Any, column: str, org: str, namespace: str) -> set[str]: + """Every memory id or document source_uri the namespace has held, deleted ones too.""" + table = "memory" if column == "memory_id" else "documents" return { - str(r["id"]) + str(r["v"]) async for r in stream_rows( ch, - "SELECT DISTINCT toString(memory_id) AS id FROM loom.memory " + f"SELECT DISTINCT toString({column}) AS v FROM loom.{table} " "WHERE org = {org:String} AND namespace = {ns:String}", {"org": org, "ns": namespace}, ) @@ -395,23 +454,26 @@ async def _memories(run: _Run, decisions: list[NsDecision]) -> None: d = by_source.get((m["org"], m["namespace"])) if d is None: continue + k = (d.source_org, d.source) if d.action == "create": - if (d.source_org, d.source) not in seen: - seen[(d.source_org, d.source)] = await _seen_ids(run.ch, d.target_org, d.target) - if m["memory_id"] in seen[(d.source_org, d.source)]: + if k not in seen: + seen[k] = await _seen(run.ch, "memory_id", d.target_org, d.target) + if m["memory_id"] in seen[k]: run.count(d, "memories_present") continue - for col in ("user_id", "verified_by", "locked_by"): - if m.get(col) and m[col] != "-": - m[col] = run.subject(d.source_org, m[col]) or ("-" if col == "user_id" else "") - rows = batch.setdefault((d.source_org, d.source), []) + user = run.user_id(d.source_org, str(m.get("user_id") or "-")) + if user is None: + run.count(d, "memories_of_dropped_users") + continue + m["user_id"] = user + rows = batch.setdefault(k, []) rows.append(m) if len(rows) >= _BATCH: await _write_memories(run, d, rows) rows.clear() - for key, rows in batch.items(): + for k, rows in batch.items(): if rows: - await _write_memories(run, by_source[key], rows) + await _write_memories(run, by_source[k], rows) async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) -> None: @@ -419,66 +481,85 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - from server.memory.app import blacklist_guard from server.memory.app import snapshot_rows as snap - memories = [ - _SnapshotMemoryRow.model_validate( + kept = [] + for m in raw: + row = _SnapshotMemoryRow.model_validate( {k: v for k, v in m.items() if k not in ("org", "namespace")} ) - for m in raw - ] - kept = [] - for m in memories: - if await blacklist_guard.find_match(org=d.target_org, namespace=d.target, value=m.value): + if await blacklist_guard.find_match(org=d.target_org, namespace=d.target, value=row.value): run.count(d, "memories_refused") else: - kept.append(m) - 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, + kept.append(row) + 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)) + run.version += len(rows) + if rows: + await snap.insert_version_rows(rows, ch=run.ch) + run.count(d, "memories", len(rows)) + + +def _bulk_entry(m: Any) -> dict[str, Any] | None: + """A source head as a `memory.bulk_set` entry, None when it is no live fact: a row in + another state, or one past its expiry. Its time of writing becomes the import's; its + validity, sensitivity, expiry and temporal anchor stay the source's.""" + if m.status != _MERGED_STATUS: + return None + ttl = None + if m.expires_at is not None: + expires = m.expires_at if m.expires_at.tzinfo else m.expires_at.replace(tzinfo=UTC) + ttl = int((expires - datetime.now(UTC)).total_seconds()) + if ttl <= 0: + return None + 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, + "pinned": m.pinned, + "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. The row's time - of writing is the import's; its stated validity is the source's.""" + surfacing, pinned peers and the skip of an unchanged restatement hold.""" from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} for m in memories: - groups.setdefault((m.agent, m.user_id, m.session_id), []).append( - { - "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", - "tags": m.tags, - "entities": m.entities, - "valid_at": m.valid_at or m.created_at, - "valid_to": m.valid_to, - "pinned": m.pinned, - "char_limit": m.char_limit, - "files": m.files, - "concepts": m.concepts, - } - ) + if (entry := _bulk_entry(m)) is None: + run.count(d, "memories_not_live") + continue + groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) for (agent, user_id, session_id), entries in groups.items(): for start in range(0, len(entries), MAX_BULK_ENTRIES): out = await handle_memory_bulk_set( @@ -496,92 +577,78 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None run.count(d, "memories", sum(1 for w in out.written if w.version)) -async def _live_uris(ch: Any, org: str, namespace: str) -> set[str]: - return { - str(r["source_uri"]) - async for r in stream_rows( - ch, - "SELECT source_uri FROM loom.documents FINAL WHERE org = {org:String} " - "AND namespace = {ns:String} AND superseded_at IS NULL", - {"org": org, "ns": namespace}, - ) - } - - async def _documents(run: _Run, decisions: list[NsDecision]) -> None: """Each document through `knowledge.upsert`, with its original: chunked and embedded - by the target's embedder. A source_uri the target namespace already serves is left as - it is, whether an earlier run wrote it or the target's owners did.""" + 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.""" from server.knowledge.api.models_knowledge import KnowledgeUpsertInput from server.knowledge.app.writes import handle_knowledge_upsert by_source = {(d.source_org, d.source): d for d in decisions} - live: dict[tuple[str, str], set[str]] = {} + seen: dict[tuple[str, str], set[str]] = {} for doc in run.bundle.records("documents"): d = by_source.get((doc["org"], doc["namespace"])) if d is None: continue - if (d.target_org, d.target) not in live: - live[(d.target_org, d.target)] = await _live_uris(run.ch, d.target_org, d.target) - if doc["source_uri"] in live[(d.target_org, d.target)]: + if (d.target_org, d.target) not in seen: + seen[(d.target_org, d.target)] = await _seen( + run.ch, "source_uri", d.target_org, d.target + ) + if doc["source_uri"] in seen[(d.target_org, d.target)]: run.count(d, "documents_present") continue original = None if doc.get("blob_path") and not doc.get("blob_erased_at"): original = base64.b64encode(run.bundle.original(doc["blob_path"])).decode() - 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", + with _for(d): + 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 _merge_landings(run: _Run, decisions: list[NsDecision]) -> None: - """A merge's audit row, once per source namespace and target.""" - from server.observability import audit - - for d in decisions: - key = source_key(run.bundle, d.source_org, d.source) - if d.action == "merge" and (d.target, key) not in run.targets[d.target_org].landed: - await audit.emit_strict( - event_type=LANDED_EVENT, - org=d.target_org, - namespace=d.target, - actor=run.actor, - subject={"source": key, "bundle": run.bundle.digest, "plan": run.plan.digest}, - ) - - async def apply( ch: Any, bundle: Bundle, p: Plan, rules: MapFile, 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")} - live = [d for d in p.namespaces if d.action != "skip"] - await _blacklist(run) - for d in live: - if d.action == "create": - await _namespace(run, d, rows[(d.source_org, d.source)]) - await _merge_landings(run, live) - await _types_and_groups(run, live) - await _grants(run, live, rules.sso_same_issuer) - await _memories(run, live) - await _documents(run, live) + 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) + 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 _types(run, d) + await _blacklist(run, d, patterns) + await _groups(run, todo) + await _grants(run, todo, rules.sso_same_issuer) + await _memories(run, todo) + await _documents(run, todo) + for d in todo: + await run.audit(DONE, d.target_org, d.target, d.target, run.key(d.source_org, d.source)) return { "bundle": bundle.digest, "plan": p.digest, diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index b6eb99bf8fc..9b7198f2097 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -4,8 +4,10 @@ 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 grant subject the bundle cannot place. Each problem -names the map entry that settles it. The map file (YAML): +target already gives to an account, a group the target org already has, a subject the +bundle cannot place, or a principal (`everyone`, `user:`, `agent:`) that names other people +in a target org that already serves others. Each problem names the map entry that settles +it. The map file (YAML): orgs: # source org: target org (default: same name) acme: acme @@ -17,6 +19,7 @@ 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 @@ -32,6 +35,7 @@ from dataclasses import asdict, dataclass, field from typing import Any, Literal +from server.auth.sharing import PERSONAL_ALIAS, is_collection from server.core.naming import ( SSO_NAMESPACE_PREFIX, is_reserved_name, @@ -41,11 +45,12 @@ NsAction = Literal["create", "merge", "skip"] SubjectAction = Literal["claim", "map", "keep", "drop"] -# Subjects that name a principal of the org, not a person's account: kept as they are. -KEPT_PREFIXES = ("user:", "agent:", "group:") -KEPT_SUBJECTS = frozenset({"everyone"}) -# Service accounts and bots sign with credentials the source issued: their owners make -# new ones on the target, so their grants are not carried. +# Principals another deployment's issuers, or the whole target org, also answer to: kept +# as they are only while the target org serves no one else. +ORG_RELATIVE_PREFIXES = ("user:", "agent:") +EVERYONE = "everyone" +# Service accounts sign with credentials the source issued: their owners make new ones on +# the target, so their grants are not carried. DROPPED_PREFIXES = ("sa:",) @@ -74,6 +79,12 @@ class MapFile: 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) @@ -81,10 +92,11 @@ def _ns_rule(key: str, raw: Any) -> NsRule: 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 raw.get("grants"): + if "grants" in raw: raise MapError(f"namespaces.{key}: grants applies to merge only") return NsRule("create", str(raw["rename"])) - return NsRule("merge", str(raw["merge"]), bool(raw.get("grants", False))) + 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: …}}") @@ -131,7 +143,7 @@ def parse_map(raw: Any) -> MapFile: subjects={ k: _subject_rule(k, v) for k, v in _keyed("subjects", raw.get("subjects")).items() }, - sso_same_issuer=bool(raw.get("sso_same_issuer", False)), + sso_same_issuer=_flag("sso_same_issuer", raw.get("sso_same_issuer", False)), ) @@ -142,9 +154,11 @@ class TargetOrg: 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 groups: frozenset[str] - # (namespace, "//") of each landing an earlier import - # recorded: a run that stopped part way is resumed, never taken for a collision. + # (name, "//") of each landing an earlier import recorded, a + # namespace's or a group's ("group:"): a run that stopped part way resumes, never + # taken for a collision. landed: frozenset[tuple[str, str]] = frozenset() + done: frozenset[tuple[str, str]] = frozenset() # the landings an earlier run finished @dataclass(frozen=True) @@ -169,6 +183,7 @@ class SubjectDecision: @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] @@ -187,9 +202,11 @@ def namespace_map(self) -> dict[tuple[str, str], NsDecision]: @property def digest(self) -> str: - """Names the decisions: `--expect-plan` refuses to apply a plan that changed.""" + """Names the decisions and the bundle: `--expect-plan` refuses to apply a plan + that changed.""" body = json.dumps( { + "bundle": self.bundle, "orgs": self.orgs, "namespaces": [asdict(n) for n in self.namespaces], "subjects": [asdict(s) for s in self.subjects], @@ -213,7 +230,7 @@ def _name_problem(name: str) -> str | None: validate_namespace_name(name) except ValueError as e: return str(e) - if is_reserved_name(name): + if is_reserved_name(name) or is_collection(name) or name == PERSONAL_ALIAS: return f"{name!r} is a reserved name" return None @@ -227,13 +244,15 @@ class _Org: target_org: str rules: MapFile target: TargetOrg - # Lower-cased contact email → "/" of every target account it reaches, - # in any org: single sign-on refuses an email whose accounts are in two orgs. + # 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] = field(default_factory=dict) # target name → source it lands from + taken: dict[str, str] # target name → source it lands from, across the target org + shared: bool # the target org serves others, or another source org lands in it def problem(self, text: str, key: str = "", section: str = "", fix: Any = None) -> None: self.plan.problems.append(f"{self.org}: {text}") @@ -243,6 +262,10 @@ def problem(self, text: str, key: str = "", section: str = "", fix: Any = None) def subject(self, d: SubjectDecision) -> None: self.plan.subjects.append(d) + def ours(self, name: str) -> bool: + """Whether this source's earlier run landed `name` in the target org.""" + return (name, f"{self.source}/{self.org}/{name}") in self.target.landed + def occupied(self, target: str, source: str) -> bool: """Whether the target holds `target` other than as this source's earlier landing.""" return ( @@ -251,14 +274,27 @@ def occupied(self, target: str, source: str) -> bool: ) def claim_name(self, name: str, source: str) -> bool: - """Reserve `name` on the target for `source`; False (and a problem) when it is taken.""" + """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] = source + self.taken[name] = f"{self.org}/{source}" return True +def _signs_in_elsewhere(o: _Org, name: str, emails: Iterable[str]) -> str: + """The first target account other than this source's earlier landing of `name` 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, []): + org, _, account = h.partition("/") + if org != o.target_org or (account, landed) not in o.target.landed: + return h + 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.""" @@ -286,22 +322,18 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: 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") - landed = f"{o.source}/{o.org}/{name}" - holders = [ - h - for h in (o.signs_in.get(email, []) if email else []) - if (h.partition("/")[2], landed) not in o.target.landed - or h.partition("/")[0] != o.target_org - ] - if holders: - org, _, account = holders[0].partition("/") - fix = account if org == o.target_org else "drop" + # Its links land too when the source used this identity provider: each email counts. + emails = {email} - {""} + if o.rules.sso_same_issuer: + emails |= {e.strip().lower() for e in o.links.get(name, [])} + if holder := _signs_in_elsewhere(o, name, sorted(emails)): + org, _, account = holder.partition("/") o.problem( - f"account {name!r}: {email} already signs in to {holders[0]!r} on the target; map " + 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", - fix, + account if org == o.target_org else "drop", ) return if sso and not o.rules.sso_same_issuer: @@ -328,7 +360,7 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: {"claim": f"{handle}-legacy"}, ) return - if not o.claim_name(handle, key): + if not o.claim_name(handle, name): return o.subject(SubjectDecision(o.org, name, "claim", handle, note=email)) o.plan.namespaces.append( @@ -373,12 +405,13 @@ def _plan_namespace(o: _Org, name: str) -> None: {"rename": f"{target}-legacy"}, ) return - if o.claim_name(target, key): + if o.claim_name(target, name): o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, target, "create")) def _plan_subject(o: _Org, subject: str) -> None: - """A grant subject or owner that is no account of the bundle.""" + """A grant subject, owner, group member or memory user that is no account of the + bundle.""" key = f"{o.org}/{subject}" rule = o.rules.subjects.get(key) if rule is not None: @@ -396,17 +429,31 @@ def _plan_subject(o: _Org, subject: str) -> None: ) ) return - if subject.startswith("group:") and subject.removeprefix("group:") in o.target.groups: - o.problem( - f"group {subject!r} exists on the target with its own members: map the grants to " - "a target subject, or drop them", - key, - "subjects", - "drop", - ) + if subject.startswith("group:"): + gid = subject.removeprefix("group:") + if gid in o.target.groups and not o.ours(subject): + o.problem( + f"group {subject!r} exists on the target with its own members: map the grants " + "to a target subject, or drop them", + key, + "subjects", + "drop", + ) + else: + o.subject(SubjectDecision(o.org, subject, "keep", subject)) return - if subject in KEPT_SUBJECTS or subject.startswith(KEPT_PREFIXES): - o.subject(SubjectDecision(o.org, subject, "keep", subject)) + if subject == EVERYONE or subject.startswith(ORG_RELATIVE_PREFIXES): + if o.shared: + 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: + o.subject(SubjectDecision(o.org, subject, "keep", subject)) return if subject.startswith(DROPPED_PREFIXES): o.subject( @@ -429,42 +476,76 @@ def _plan_subject(o: _Org, subject: str) -> None: ) +def _check_users(o: _Org) -> None: + """Two end users 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.""" + 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 plan( *, + bundle: str, source: str, rules: MapFile, namespace_rows: Iterable[Mapping[str, Any]], selected: Mapping[str, list[str]], grant_subjects: Mapping[str, set[str]], + groups: 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). - `grant_subjects` is each source org's grant subjects and namespace owners; `targets` - the target state of each target org; `signs_in` every target account by email; `revoked` - the source subjects revoked outright.""" - p = Plan(orgs={}, namespaces=[], subjects=[], problems=[], proposals={}) + """The decisions for every source org in `selected` (org → exported namespaces) of + deployment `source`. `grant_subjects` is each source org's grant subjects, namespace + owners, group members and memory users (`user:`); `groups` and `links` its group + ids and 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.""" + p = Plan(bundle=bundle, orgs={}, namespaces=[], subjects=[], problems=[], proposals={}) 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]] = {} + group_from: dict[tuple[str, 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] + ours = { + name + for name, key in target.landed + if key.startswith(f"{source}/") and key.split("/")[1] in landing[target_org] + } o = _Org( - source, - org, - target_org, - rules, - targets[target_org], - signs_in, - by_org.get(org, {}), - selected[org], - p, + source=source, + org=org, + target_org=target_org, + rules=rules, + target=target, + signs_in=signs_in, + links=links.get(org, {}), + rows=by_org.get(org, {}), + selected=selected[org], + plan=p, + taken=taken.setdefault(target_org, {}), + shared=len(landing[target_org]) > 1 or bool(set(target.namespaces) - ours), ) + for gid in sorted(groups.get(org, set())): + if (other := group_from.setdefault((target_org, gid), org)) != org: + o.problem(f"group {gid!r} of {other} and of {org} both land in {target_org}") rows = o.rows accounts = {n for n in o.selected if is_account(rows[n])} for name in sorted(accounts): @@ -475,6 +556,7 @@ def plan( decided = accounts | {s.subject for s in p.subjects if s.source_org == org} for subject in sorted(grant_subjects.get(org, set()) - decided): _plan_subject(o, subject) + _check_users(o) for s in p.subjects: if s.source_org == org and s.subject in revoked and s.action == "map": o.problem( diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py new file mode 100644 index 00000000000..3a61a241cd2 --- /dev/null +++ b/tests/integration/test_instance_consolidation.py @@ -0,0 +1,204 @@ +"""`loom instance export` and `loom instance import` against a real ClickHouse: one org +moves into another that already has an account and a namespace with the same names. The +dry run refuses until the map settles both; the apply lands them under the mapped names +with every field of the source rows, merges a third namespace into the target's, leaves +the target's own rows alone, and a second apply of the same plan writes nothing.""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import httpx +import pytest +import yaml + +from server.core.ch import get_client +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") +# What a restore owns on a row it writes: everything else is the source's. +RESTORED = {"version", "version_text", "actor", "source_class"} + + +@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) -> None: + 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": HASH, + "description": "", + "tags": [], + "active": active, + "visibility": "private", + "created_at": now, + "updated_at": now, + } + ], + ) + + +def _op(url: str, token: str, name: str, body: dict[str, Any]) -> dict[str, Any]: + r = httpx.post( + f"{url}/v1/{name}", json=body, headers={"Authorization": f"Bearer {token}"}, timeout=60 + ) + assert r.status_code == 200, (name, r.text) + out: dict[str, Any] = r.json() + return out + + +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, + ) + + +def _get(url: str, token: str, org: str, namespace: str, key: str) -> dict[str, Any]: + body = {"org": org, "namespace": namespace, "agent": "a", "memory_key": key} + return _op(url, token, "memory.get", body) + + +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, dst = unique_org("isrc"), unique_org("idst") + s = mint_test_token(org=src, roles=["admin"]) + t = mint_test_token(org=dst, roles=["admin"]) + await _account(ch, src, "alice", "alice@src.test") + _op( + control_plane_url, + s, + "namespace.register", + {"org": src, "namespace": "team", "owner_email": "alice"}, + ) + _op( + control_plane_url, + s, + "grants.create", + {"org": src, "namespace": "team", "subject": "alice", "role": "writer"}, + ) + for key in KEYS: + body = {"org": src, "namespace": "team", "agent": "a", "memory_key": key} + _op(control_plane_url, s, "memory.set", {**body, "value": f"the team's {key} rule"}) + notes = {"org": src, "namespace": "notes", "owner_email": "alice"} + _op(control_plane_url, s, "namespace.register", notes) + standup = {"org": src, "namespace": "notes", "agent": "a", "memory_key": "standup"} + _op(control_plane_url, s, "memory.set", {**standup, "value": "standup is at ten"}) + # The target's own alice and team are someone else's. + await _account(ch, dst, "alice", "alice@dst.test") + _op( + control_plane_url, + t, + "namespace.register", + {"org": dst, "namespace": "team", "owner_email": "alice"}, + ) + theirs = {"org": dst, "namespace": "team", "agent": "a", "memory_key": KEYS[0]} + _op(control_plane_url, t, "memory.set", {**theirs, "value": "the target's own rule"}) + + bundle = tmp_path / "bundle" + out = _cli("export", "--org", src, "--out", str(bundle)) + assert out.returncode == 0, out.stderr + # A source is another deployment: its accounts do not sign in to this one. + await _account(ch, src, "alice", "alice@src.test", active=False) + + mapping = tmp_path / "map.yaml" + mapping.write_text(yaml.safe_dump({"orgs": {src: dst}})) + 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}/team": {"rename": "team-legacy"}}, + # The minted token's subject: no account, email or principal the target knows. + "subjects": {f"{src}/alice": {"claim": "alice-legacy"}, f"{src}/test-suite": "drop"}, + } + proposals["namespaces"][f"{src}/notes"] = {"merge": "team"} + mapping.write_text(yaml.safe_dump({"orgs": {src: dst}, **proposals})) + 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 + plan = ("--map", str(mapping), "--expect-plan", digest[1], "--apply") + applied = _cli("import", "--bundle", str(bundle), *plan) + assert applied.returncode == 0, applied.stdout + applied.stderr + + versions = {} + for key in KEYS: + before = _get(control_plane_url, s, src, "team", key) + after = _get(control_plane_url, t, dst, "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") + versions[key] = after["version"] + assert _get(control_plane_url, t, dst, "team", KEYS[0])["value"] == "the target's own rule" + assert not _get(control_plane_url, t, dst, "team", KEYS[1])["found"] + # A merge writes through memory.bulk_set: the fact and its validity are the source's. + before = _get(control_plane_url, s, src, "notes", "standup") + merged = _get(control_plane_url, t, dst, "team", "standup") + assert (merged["value"], merged["memory_type"]) == (before["value"], before["memory_type"]) + assert merged["valid_at"] == (before["valid_at"] or before["created_at"]) + assert (merged["source_class"], merged["actor"]) == ("imported", "process:cli:instance") + versions["standup"] = merged["version"] + + accounts = await ch.query_all( + "SELECT namespace, owner_email, contact_email, password_hash FROM loom.namespaces FINAL " + "WHERE org = {org:String} AND namespace IN ('alice', 'alice-legacy') ORDER BY namespace", + params={"org": dst}, + ) + assert [tuple(r.values()) for r in accounts] == [ + ("alice", "alice", "alice@dst.test", HASH), + ("alice-legacy", "alice-legacy", "alice@src.test", HASH), + ] + grants = await ch.query_all( + "SELECT namespace, subject, role FROM loom.namespace_grants FINAL " + "WHERE org = {org:String} AND revoked_at IS NULL ORDER BY namespace, subject", + params={"org": dst}, + ) + assert ("team-legacy", "alice-legacy", "writer") in [tuple(r.values()) for r in grants] + assert all(r["namespace"] != "team" for r in grants if r["subject"] == "alice-legacy") + + audit = ( + "SELECT event_type, namespace, JSONExtractString(subject, 'plan') AS plan " + "FROM loom.audit_log WHERE org = {org:String} AND event_type LIKE 'instance.import%' " + "ORDER BY event_type, namespace SETTINGS select_sequential_consistency = 1" + ) + landed = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst})] + assert landed == [ + (event, name, digest[1]) + for event in ("instance.import", "instance.import.done") + for name in ("alice-legacy", "team", "team-legacy") + ] + + again = _cli("import", "--bundle", str(bundle), *plan) + assert again.returncode == 0, again.stdout + again.stderr + assert f"plan {digest[1]}" in again.stdout + assert [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst})] == landed + for key in KEYS: + assert _get(control_plane_url, t, dst, "team-legacy", key)["version"] == versions[key] + assert _get(control_plane_url, t, dst, "team", "standup")["version"] == versions["standup"] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index a0fb8c2df8b..ef26cc404d3 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -14,6 +14,7 @@ from server.cli.instance_plan import MapError, TargetOrg, parse_map, plan SOURCE = "dep-1" +EMPTY = TargetOrg({}, frozenset(), frozenset()) def _account(org: str, name: str, email: str) -> dict[str, Any]: @@ -33,19 +34,27 @@ def _ns(org: str, name: str, owner: str) -> dict[str, Any]: def _plan( rows: list[dict[str, Any]], *, - subjects: set[str] | None = None, + 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, + groups: dict[str, set[str]] | None = None, + links: dict[str, dict[str, list[str]]] | None = None, + bundle: str = "b1", ) -> Any: + orgs = sorted({r["org"] for r in rows}) return plan( + bundle=bundle, source=SOURCE, rules=parse_map(rules), namespace_rows=rows, - selected={"acme": sorted(r["namespace"] for r in rows)}, - grant_subjects={"acme": subjects or set()}, + selected={o: sorted(r["namespace"] for r in rows if r["org"] == o) for o in orgs}, + grant_subjects=subjects if isinstance(subjects, dict) else {"acme": subjects or set()}, + groups=groups or {}, + links=links or {}, revoked=set(), - targets={"acme": target or TargetOrg({}, frozenset(), frozenset())}, + targets=targets or {"acme": target or EMPTY}, signs_in=signs_in or {}, ) @@ -92,6 +101,22 @@ def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: ("alice", "alice-legacy", "claim"), ("team", "team", ""), } + landed = TargetOrg( + {**target.namespaces, "alice-legacy": {}, "team": {}}, + target.subjects | {"alice-legacy"}, + frozenset(), + landed=frozenset( + {("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")} + ), + ) + 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: @@ -105,54 +130,145 @@ def test_collisions_and_unknown_subjects_refuse_the_plan() -> None: assert decided == {"group:ops": "keep", "sa:ci": "drop", "bob@x": "keep"} +def test_principals_of_a_shared_target_org_need_the_map() -> None: + """`everyone`, `user:` and `agent:` also name the target org's own people once it + serves others; in an org the import alone lands in, they stay.""" + rows = [_ns("acme", "team", "x")] + subjects = {"x", "everyone", "user:42", "agent:helper"} + alone = _plan(rows, subjects=subjects, rules={"subjects": {"acme/x": "drop"}}) + assert alone.problems == [] + shared = TargetOrg({"theirs": {"kind": "memory"}}, frozenset(), frozenset()) + p = _plan(rows, subjects=subjects, target=shared, rules={"subjects": {"acme/x": "drop"}}) + assert p.proposals["subjects"] == { + "acme/everyone": "drop", + "acme/user:42": "drop", + "acme/agent:helper": "drop", + } + kept = _plan( + rows, + subjects=subjects, + target=shared, + rules={"subjects": {"acme/x": "drop", **dict.fromkeys(p.proposals["subjects"], "keep")}}, + ) + assert kept.problems == [] + + +def test_two_end_users_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"}} + target = TargetOrg({}, frozenset({"user:c"}), frozenset()) + p = _plan(rows, subjects={"x", "user:a", "user:b"}, target=target, rules=rules) + assert any("both land as 'user:c'" in s for s in p.problems) + + +def test_two_source_orgs_into_one_target_org() -> None: + """A name or group two source orgs both bring to one target org refuses the plan, and + each org's principals are shared with the other's.""" + 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", "everyone"}, "b": {"x"}}, + targets={"t": EMPTY}, + rules=rules, + groups={"a": {"eng"}, "b": {"eng"}}, + ) + assert "b: team and a/team both land on namespace 'team'" in p.problems + assert any("group 'eng' of a and of b both land in t" in s for s in p.problems) + assert p.proposals["subjects"] == {"a/everyone": "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 p = _plan(rows, signs_in={"bob@x": ["acme/robert"]}) assert p.proposals == {"subjects": {"acme/bob": "robert"}} + # 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")] - first = _plan(rows, subjects={"alice"}) + subjects = {"alice", "group:eng", "user:7"} + first = _plan(rows, subjects=subjects, groups={"acme": {"eng"}}) + assert first.problems == [] landed = TargetOrg( {"alice": {"kind": "memory"}, "team": {"kind": "memory"}}, frozenset({"alice"}), - frozenset(), - landed=frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}), + frozenset({"eng"}), + landed=frozenset( + { + ("alice", f"{SOURCE}/acme/alice"), + ("team", f"{SOURCE}/acme/team"), + ("group:eng", f"{SOURCE}/acme/group:eng"), + } + ), + ) + again = _plan( + rows, + subjects=subjects, + target=landed, + groups={"acme": {"eng"}}, + signs_in={"alice@x": ["acme/alice"]}, ) - again = _plan(rows, subjects={"alice"}, target=landed, signs_in={"alice@x": ["acme/alice"]}) assert again.problems == [] and again.digest == first.digest other = _plan( rows, - subjects={"alice"}, - target=TargetOrg(landed.namespaces, landed.subjects, frozenset()), + subjects=subjects, + target=TargetOrg(landed.namespaces, landed.subjects, landed.groups), + groups={"acme": {"eng"}}, ) assert other.problems # the same names, not landed by this source + assert _plan(rows, subjects=subjects, bundle="b2").digest != first.digest -def test_merge_needs_a_target_namespace_and_map_errors_name_the_entry() -> None: +def test_names_and_flags_the_map_refuses() -> None: p = _plan( - [_ns("acme", "team", "x")], + [_ns("acme", "team", "x"), _ns("acme", "notes", "x")], subjects={"x"}, - rules={"namespaces": {"acme/team": {"merge": "t"}}}, + 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: +def test_one_namespace_brings_the_accounts_and_groups_its_grants_name() -> None: rows = [ _account("acme", "alice", "a@x"), _account("acme", "bob", "b@x"), _account("acme", "carol", "c@x"), + _account("acme", "dan", "d@x"), _ns("acme", "team", "alice"), _ns("acme", "acl-mirror", "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": ["alice", "bob", "carol", "team"]} + grants = [ + {"org": "acme", "namespace": "team", "subject": "bob"}, + {"org": "acme", "namespace": "team", "subject": "group:eng"}, + ] + groups = [ + {"org": "acme", "group_id": "eng", "members": ["carol"]}, + {"org": "acme", "group_id": "ops", "members": ["dan"]}, + ] + selected, group_ids = select_namespaces(rows, grants, groups, ["team"]) + assert selected == {"acme": ["alice", "bob", "carol", "team"]} + assert group_ids == {"acme": ["eng"]} + selected, _ = select_namespaces(rows, grants, groups, None) + assert selected == {"acme": ["alice", "bob", "carol", "dan", "team"]} From 044655aeded5643d52d3ffd228161d228cbffaf6 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 22:07:42 +0530 Subject: [PATCH 03/32] loom instance import: claimed handles must hold no access, merges only add - A claimed account handle that already holds access on the target (a platform-admin or trusted-caller setting, a grant, a namespace, a token, a task) refuses the plan with a new-handle proposal, and the apply checks it again under the account claim: the same check self-signup runs, now public as refuse_empowered. - The export reads revocations under SCIM's key and any case, so a deprovisioned account lands with no password and no links. - keep runs the checks no rule runs; it only settles an end user of a shared target org. - A namespace anyone could join at once lands with join_policy approval in a target org that serves others. - A merge writes no key the target namespace holds or has held; a resumed run writes no per-type setting, policy, guide revision or single sign-on link the target holds in any state. - Groups, agents and everyone hold grants on collections only, which do not move: the group path is removed, and such a subject needs drop or a mapping. - Policies and guides move with created namespaces; promoted shared memories, records and end users' documents are counted as left behind. - The digest names sso_same_issuer; merges land under their own audit event, so a target org merged into stays shared; a user: subject maps to any user: subject; an undecided subject maps to nothing. - The dry run checks the regex budget and every original before anything is written; the target orgs are declared only to write a reviewed plan; an export that selects nothing is refused. - The integration test covers a target-held handle, a SCIM-revoked account, a refusal, a document and its original, a public namespace, a merge key both sides hold, and a resume of unfinished landings; it also runs in CI's Postgres pass. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- .github/workflows/ci.yml | 1 + docs/architecture/storage-layout.md | 16 +- docs/operations/consolidation.md | 93 +++--- server/auth/self_signup.py | 10 +- server/cli/instance.py | 13 +- server/cli/instance_export.py | 100 ++++--- server/cli/instance_import.py | 259 +++++++++++------ server/cli/instance_plan.py | 145 +++++----- .../test_instance_consolidation.py | 270 ++++++++++++------ tests/unit/test_instance_consolidation.py | 151 +++++----- tests/unit/test_signup_privilege.py | 16 +- 11 files changed, 642 insertions(+), 432 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf25ce1961d..1996501fb4f 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/storage-layout.md b/docs/architecture/storage-layout.md index 2fbc65800b3..63ce5b0e631 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. @@ -1255,7 +1255,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/consolidation.md b/docs/operations/consolidation.md index 33d6b81ec61..bac6cf88e88 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -10,17 +10,20 @@ run, with their settings. To move a whole deployment onto new hosts, see | Moves | Stays behind | | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -| Memory namespaces, with their settings and per-type settings | Code-index and mirror namespaces, and collections: the target indexes the repositories again | +| 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 and revoked grants | -| Groups the moved grants name, with their mapped members | Conversations, session briefs and tasks: the manifest counts them | -| Blacklist entries, before any content, each on the moved namespaces it reaches | Knowledge sources with a remote: the manifest lists them to register again | -| Memories: every live head, with its `created_at`, validity and attestation | Embeddings, caches, traces and rollups: the target builds them again | -| Documents with their originals, embedded again by the target's embedder | The audit log and agent events | - -Imported memories and documents carry `source_class=imported` and the importing command -(`process:cli:instance`) as `actor`. Memories reach vector search once the embedding -worker's next full pass embeds them (`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SECONDS`). +| 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 moved namespaces it reaches | Conversations, session briefs, tasks, promoted shared memories and records: the manifest counts them | +| Memories: every live head, with its `created_at`, validity and attestation | 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: the manifest lists them to register again | +| | 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`. +Memories reach vector search once the embedding worker's next full pass embeds them +(`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SECONDS`). ## Procedure @@ -37,9 +40,10 @@ worker's next full pass embeds them (`LOOM_EMBEDDING_WORKER_ORPHAN_FULL_SCAN_SEC ``` With `--namespace`, the bundle carries that namespace's content, and the account rows - and groups its grants and owner name, so the plan can place them. The bundle - holds password hashes: it is written readable by its owner only, and is copied to the - target the way a database dump is. + its grants and owner name, so the plan can place them. An org or namespace with + nothing to export refuses the export. The bundle holds password hashes: it is written + readable by its owner only, and is copied to the target whole, the way a database + dump is. 4. Plan, on the target. The dry run reads the target, prints each decision and refuses the plan while anything is unresolved: @@ -74,6 +78,7 @@ namespaces: # "/": rule (default: create) 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 ``` @@ -81,41 +86,49 @@ subjects: # "/": rule it. 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. + 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. `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. - It writes live facts only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the - target namespace already serves is left as it is. Per-type settings land with a - created namespace only. + 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. It writes live facts only: a row in another + state, or past its expiry, is left out, 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. A document whose `source_uri` the target namespace already serves is left as + it is. Per-type settings, policies and the guide land with a created namespace only. - **Accounts.** An account lands as a claimable password account under its handle. The - plan refuses a handle the target holds and an email any target account signs in with, - proposing a new handle or the target account. Mapping an account onto a target account - gives that account the source account's content and grants: 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 the source revoked lands with no password. + 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), and an email any target account signs in with; it proposes a new handle or the + target account. Mapping an account onto a target account gives that account the + source account's content and grants: 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 the source revoked, by an operator or by SCIM, + lands with no password and no links. - **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves - the address at sign-in on the target. `everyone`, `user:` and `agent:` subjects are - kept in a target org only the import lands in. In one that serves others, or that two - source orgs land in, they would also name its own people, so each needs `keep`, a - mapping or `drop`. A `user:` mapping also moves the memories of that end user; two - source users may not land as one. A `group:` subject is kept, except a group the target - org already has or that two source orgs both bring, which needs a mapping. `sa:` - subjects are dropped. Any other subject needs a mapping or `drop`. + the address at sign-in on the target. 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, or + `drop`. Its decision moves that end user's memories too; two source users 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 target + subject. `sa:` subjects are dropped. Any other subject needs a mapping or `drop`. ## Running it again An import that stops part way runs again with the same command, and plans the same -digest. Before it lands a namespace or a group it writes an `instance.import` audit row -naming its source, and a later plan reads that row as this source's landing, not as 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 no memory id the -namespace has held, deleted ones included, and no document whose `source_uri` it has -held; it writes no grant its subject already holds at that role or higher, or that was -revoked. +digest. 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. 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 id the namespace has +held, deleted ones included, 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 its +subject holds at that role or higher, or that was revoked. These rows live as long as the +audit log keeps rows (`LOOM_RETENTION_AUDIT_LOG_DAYS`). ## Related diff --git a/server/auth/self_signup.py b/server/auth/self_signup.py index 090b26fc5b1..867953dfcb4 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/instance.py b/server/cli/instance.py index 31c8cd928b0..3dde54388e4 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -81,7 +81,8 @@ def _print_plan(bundle: Any, p: Any) -> None: 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 "" - print(f" namespace {d.source_org}/{d.source} → {land}{account}") + joins = " (self-join needs approval: the target org serves others)" if d.approval else "" + print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}") for s in p.subjects: to = f" → {s.target}" if s.action in ("map", "claim") else "" note = f" [{s.note}]" if s.note else "" @@ -108,9 +109,9 @@ def _print_plan(bundle: Any, p: Any) -> None: def _cmd_import(args: argparse.Namespace) -> int: import yaml - from server.cli._ch import run_connected + 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, load_target + from server.cli.instance_import import apply, build_plan, check, load_target from server.cli.instance_plan import MapError, parse_map try: @@ -123,6 +124,7 @@ def _cmd_import(args: argparse.Namespace) -> int: async def _run(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) if p.problems: return 1 @@ -131,8 +133,11 @@ async def _run(ch: Any) -> int: if args.expect_plan != p.digest: print(f"--expect-plan {args.expect_plan!r} is not this plan ({p.digest}): review it") 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) receipt = await apply(ch, bundle, p, rules, targets) print(json.dumps(receipt, indent=2, default=str)) return 0 - return run_connected(_run, orgs=() if args.dry_run else target_orgs) + return run_connected(_run, orgs=()) diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 93242855150..6b4edcdd430 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -25,6 +25,8 @@ # A namespace name of these forms is not the organization's to move: a mirror's or a code # store's (the index rebuilds them), a collection (moved with its owner's account). _NOT_EXPORTED_PREFIXES = ("acl-", "crs-", "col-") +# SCIM's revocation key prefix (`server.auth.revocation.SCIM_PREFIX`) as a SQL literal. +_SCIM = "\\0scim:" _STREAM_SETTINGS = { "max_execution_time": 0, # UTC with its zone: a plain DateTime would read in the source server's time zone. @@ -115,35 +117,25 @@ def exported_namespace(row: dict[str, Any]) -> bool: def select_namespaces( - rows: list[dict[str, Any]], - grants: list[dict[str, Any]], - groups: list[dict[str, Any]], - wanted: list[str] | None, -) -> tuple[dict[str, list[str]], dict[str, list[str]]]: - """Per org, the namespaces the bundle carries, and the groups their grants name: every - exported namespace, or the `wanted` ones together with the accounts that own them, - hold grants on them or belong to a group that does, so the plan can place every - subject they name.""" + rows: list[dict[str, Any]], grants: list[dict[str, Any]], wanted: list[str] | None +) -> 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, so the + plan can place every subject they name.""" 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"])) - 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 "")) - for g in grants: - if g["namespace"] in out.get(str(g["org"]), set()): - named.setdefault(str(g["org"]), set()).add(str(g["subject"])) - group_ids: dict[str, list[str]] = {} - for g in groups: - org = str(g["org"]) - if f"group:{g['group_id']}" in named.get(org, set()): - group_ids.setdefault(org, []).append(str(g["group_id"])) - named[org].update(str(m) for m in g.get("members") or []) 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 "")) + for g in grants: + if g["namespace"] in out.get(str(g["org"]), set()): + named.setdefault(str(g["org"]), set()).add(str(g["subject"])) for r in rows: if ( is_account(r) @@ -151,10 +143,7 @@ def select_namespaces( and r["namespace"] in named.get(str(r["org"]), ()) ): out.setdefault(str(r["org"]), set()).add(str(r["namespace"])) - return ( - {org: sorted(names) for org, names in out.items()}, - {org: sorted(ids) for org, ids in group_ids.items()}, - ) + return {org: sorted(names) for org, names in out.items()} def _write(w: BundleWriter, section: str, rows: Iterable[dict[str, Any]]) -> None: @@ -178,25 +167,26 @@ async def _identity_sections( ch: Any, orgs: list[str], selected: dict[str, list[str]], - group_ids: dict[str, list[str]], ) -> None: p: dict[str, Any] = { "orgs": orgs, "pairs": _pairs(selected), - "groups": [(org, g) for org, ids in group_ids.items() for g in ids], "subjects": sorted({ns for _, ns in _pairs(selected)}), } in_orgs = "org IN {orgs:Array(String)}" in_ns = "(org, namespace) IN {pairs:Array(Tuple(String, String))}" - await _table(w, ch, "types", f"SELECT * FROM loom.namespace_types FINAL WHERE {in_ns}", p) + 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, - "groups", - "SELECT * FROM loom.principal_groups FINAL " - "WHERE (org, group_id) IN {groups:Array(Tuple(String, String))} AND NOT deleted", + "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 ) @@ -240,14 +230,16 @@ async def _identity_sections( """, p, ) - # An account the source revoked outright lands with no password. + # An account the source revoked outright, by an operator or by SCIM and under any + # case (grants fold case), lands with no password. await _table( w, ch, "revoked", - "SELECT jti AS subject, reason FROM loom.revoked_tokens FINAL " - "WHERE jti IN {subjects:Array(String)} AND issued_before IS NULL AND expires_at > now()", - p, + f"SELECT lower(replaceOne(jti, '{_SCIM}', '')) AS subject, reason " + "FROM loom.revoked_tokens FINAL WHERE subject IN {lowered:Array(String)} " + "AND issued_before IS NULL AND expires_at > now()", + {**p, "lowered": sorted({s.lower() for s in p["subjects"]})}, ) @@ -271,12 +263,12 @@ async def _memories( 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): + 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") -async def _memory_heads(ch: Any, org: str, ns: str) -> AsyncIterator[dict[str, Any]]: +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 @@ -312,10 +304,12 @@ async def _documents( 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. 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 namespace = {ns:String} AND superseded_at IS NULL AND user_id = '-'", {"org": org, "ns": ns}, ): if d.get("blob_path") and not d.get("blob_erased_at"): @@ -352,7 +346,14 @@ async def _left_behind(ch: Any, orgs: list[str]) -> dict[str, Any]: "UNION ALL SELECT 'session_briefs', org, count() FROM loom.session_briefs FINAL " "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'tasks', org, count() FROM loom.tasks FINAL " - "WHERE org IN {orgs:Array(String)} AND is_deleted = 0 GROUP BY org", + "WHERE org IN {orgs:Array(String)} AND is_deleted = 0 GROUP BY org " + "UNION ALL SELECT 'shared', org, count() FROM loom.shared FINAL " + "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'memory_records', org, count() FROM loom.memory_records FINAL " + "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + "UNION ALL SELECT 'documents_of_end_users', org, count() FROM loom.documents FINAL " + "WHERE org IN {orgs:Array(String)} AND superseded_at IS NULL AND user_id != '-' " + "GROUP BY org", params=p, ) return {"code_repos": repos, "knowledge_sources": sources, "rows": rows} @@ -378,27 +379,22 @@ async def export( p, ) ] - groups = [ - r - async for r in stream_rows( - ch, - f"SELECT org, group_id, members FROM loom.principal_groups FINAL {in_orgs} " - "AND NOT deleted", - p, - ) - ] - selected, group_ids = select_namespaces(rows, grants, groups, namespaces) + selected = select_namespaces(rows, grants, namespaces) # 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) os.umask(0o077) w = BundleWriter(out) _write(w, "namespaces", (r for r in rows if r["namespace"] in selected.get(r["org"], ()))) - _write(w, "grants", (g for g in grants if g["namespace"] in selected.get(g["org"], ()))) - await _identity_sections(w, ch, orgs, selected, group_ids) + _write(w, "grants", (g for g in grants if g["namespace"] in content.get(g["org"], ()))) + await _identity_sections(w, ch, orgs, selected) counts: Counts = {} await _memories(w, ch, content, counts) await _documents(w, ch, content, counts) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index efee1939324..2de6c2582b6 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -3,17 +3,18 @@ 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 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 no memory id or document the namespace has held and no -grant its subject already holds or a target admin revoked. +`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. Documents go through `knowledge.upsert` with their -originals, so the target's embedder embeds them; memories are embedded by the embedding -worker's next full pass. Every model call is made for the target org. +`memory.bulk_set`, with its admission, for keys the target namespace never held. +Documents go through `knowledge.upsert` with their originals, so the target's embedder +embeds them; memories are embedded by the embedding worker's next full pass. Every model +call is made for the target org. """ from __future__ import annotations @@ -31,6 +32,7 @@ from server.cli.instance_plan import MapFile, NsDecision, Plan, TargetOrg, is_account, plan LANDED = "instance.import" +MERGED = "instance.import.merge" # a merge lands in the target's own namespace DONE = "instance.import.done" _BATCH = 500 # Settings that name the source's own services or rows: cleared, the target's owners set @@ -56,7 +58,7 @@ async def load_target( """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, DONE]} + 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 FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", @@ -67,11 +69,6 @@ async def load_target( "WHERE org IN {orgs:Array(String)} AND revoked_at IS NULL AND status = 'active'", params=p, ) - groups = await ch.query_all( - "SELECT org, group_id FROM loom.principal_groups FINAL " - "WHERE org IN {orgs:Array(String)} AND NOT deleted", - params=p, - ) landings = await ch.query_all( "SELECT DISTINCT event_type, org, JSONExtractString(subject, 'name') AS name, " "JSONExtractString(subject, 'source') AS source FROM loom.audit_log " @@ -100,8 +97,8 @@ def pairs(event: str, org: str = org) -> frozenset[tuple[str, str]]: | {str(g["subject"]) for g in grants if g["org"] == org} | {str(r["owner_email"]) for r in mine if r.get("owner_email")} ), - groups=frozenset(str(g["group_id"]) for g in groups if g["org"] == org), landed=pairs(LANDED), + merged=pairs(MERGED), done=pairs(DONE), ) signs_in: dict[str, list[str]] = {} @@ -133,11 +130,6 @@ def add(org: Any, subject: Any) -> None: for r in rows: if not is_account(r) and r.get("owner_email"): add(r["org"], r["owner_email"]) - groups: dict[str, set[str]] = {} - for g in bundle.records("groups"): - groups.setdefault(str(g["org"]), set()).add(str(g["group_id"])) - for m in g.get("members") or []: - add(g["org"], m) for m in bundle.records("memories"): # an end user's rows follow their decision if m.get("user_id") not in (None, "", "-"): add(m["org"], f"user:{m['user_id']}") @@ -153,14 +145,81 @@ def add(org: Any, subject: Any) -> None: namespace_rows=rows, selected=bundle.manifest["namespaces"], grant_subjects=subjects, - groups=groups, links=links, - revoked={str(r["subject"]) for r in bundle.records("revoked")}, + 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 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 empowers it, or it holds a grant, a namespace, + a token or a task, as self-signup refuses it), a namespace whose refusals would pass + the regex budget, an original missing from the bundle. Each is added as a problem.""" + from fastapi import HTTPException + + from server.auth.self_signup import refuse_empowered + from server.core.errors import ValidationError + from server.memory.app.blacklist_guard import ( + REGEX_PROGRAM_PER_SCOPE, + compile_regex, + scope_program, + ) + + for d in p.namespaces: + key = source_key(bundle, d.source_org, d.source) + if not d.account or (d.target, key) in targets[d.target_org].landed: + continue + try: + await refuse_empowered(ch, d.target_org, d.target.lower()) + except HTTPException: + p.problems.append( + f"{d.source_org}: account {d.source!r}: {d.target!r} already holds access on " + "the target (a grant, a namespace, a token, a task or a setting names it)" + ) + p.proposals.setdefault("subjects", {})[f"{d.source_org}/{d.source}"] = { + "claim": f"{d.target}-legacy" + } + regexes = [b for b in bundle.records("blacklist") if b["pattern_type"] == "regex"] + for d in p.namespaces: + if d.action == "skip": + continue + size = 0 + for b in regexes: + if _reaches(b, d): + try: + size += compile_regex(b["pattern"]).programsize + except ValidationError: + continue + 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" + ) + landing = {(d.source_org, d.source) for d in p.namespaces if d.action != "skip"} + for doc in bundle.records("documents"): + sha = doc.get("blob_path") + if (doc["org"], doc["namespace"]) in landing and sha and not doc.get("blob_erased_at"): + if not (bundle.path / "originals" / str(sha)).is_file(): + p.problems.append( + f"{doc['org']}/{doc['namespace']} document {doc['source_uri']!r}: the " + f"bundle has no original {sha}: copy the whole bundle" + ) + + +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)) + + 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.""" @@ -197,7 +256,8 @@ def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, Targe self.subjects = p.subject_map() self.version = time.time_ns() self.now = naive_utc_now_seconds() - self.revoked = {str(r["subject"]) for r in bundle.records("revoked")} + self.revoked = _revoked(bundle) + self.digests = {"bundle": bundle.digest, "plan": p.digest} self.counts: dict[str, dict[str, int]] = {} def next_version(self) -> int: @@ -212,8 +272,8 @@ def count(self, d: NsDecision, what: str, n: int = 1) -> None: 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.""" - return self.subjects.get((org, s), s) + """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.""" @@ -230,12 +290,7 @@ async def audit(self, event: str, org: str, namespace: str, name: str, source: s org=org, namespace=namespace, actor=self.actor, - subject={ - "name": name, - "source": source, - "bundle": self.bundle.digest, - "plan": self.plan.digest, - }, + subject={"name": name, "source": source, **self.digests}, ) @@ -256,32 +311,45 @@ 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.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) - landed = (d.target, key) in run.targets[d.target_org].landed + target = run.targets[d.target_org] if d.action == "merge": - if not landed: - await run.audit(LANDED, d.target_org, d.target, d.target, key) + if (d.target, key) not in target.merged: + await run.audit(MERGED, d.target_org, d.target, d.target, key) return + landed = (d.target, key) in target.landed async with account_change(d.target_org, d.target): existing = await namespaces_repo.fetch_row(d.target_org, d.target, ch=run.ch) if not landed: if existing is not None or await directory().in_use(d.target_org, d.target, ch=run.ch): raise SystemExit(f"{d.target_org}/{d.target} is in use on the target: plan again") + 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 await run.audit(LANDED, d.target_org, d.target, d.target, key) if existing is not None: return 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) + 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 in run.revoked: + elif d.source.lower() in run.revoked: new["password_hash"] = "" # revoked on the source: nobody claims it with _identity(): await run.ch.insert("loom.namespaces", await _typed(run.ch, "namespaces", [new])) @@ -289,19 +357,37 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: run.count(d, "namespace") -async def _types(run: _Run, d: NsDecision) -> None: - """A created namespace's per-type settings: a merged one keeps the target's.""" - rows = [ - {**t, "org": d.target_org, "namespace": d.target, "updated_at": run.now} - for t in run.bundle.records("types") - if (t["org"], t["namespace"]) == (d.source_org, d.source) - ] - if rows: - await run.ch.insert( - "loom.namespace_types", - await _typed(run.ch, "namespace_types", rows), - settings={"async_insert": 0, "wait_for_async_insert": 1}, +# A created namespace's own rows, each table with the key the target is checked by. +_CARRIED = { + "namespace_types": "memory_type", + "namespace_policies": "policy_id", + "namespace_guides": "revision", +} + + +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 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}" + _SEQUENTIAL, + 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 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: @@ -322,10 +408,7 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - ) present = {str(r["id"]) for r in have} for b, pid in zip(patterns, ids, strict=True): - reaches = b["org"] == "*" or ( - b["org"] == d.source_org and b["namespace"] in ("*", d.source) - ) - if not reaches or str(pid) in present: + if not _reaches(b, d) or str(pid) in present: continue await blacklist.add( BlacklistAddInput.model_validate( @@ -344,31 +427,6 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - run.count(d, "refusals") -async def _groups(run: _Run, decisions: list[NsDecision]) -> None: - """The groups the plan keeps and the target org does not have (or an earlier run of - this source created and did not finish), with their mapped members.""" - kept = {(s.source_org, s.subject) for s in run.plan.subjects if s.action == "keep"} - orgs = {d.source_org for d in decisions} - rows = [] - for g in run.bundle.records("groups"): - org, name = str(g["org"]), f"group:{g['group_id']}" - if org not in orgs or (org, name) not in kept: - continue - target_org, key = run.plan.orgs[org], run.key(org, name) - target = run.targets[target_org] - if (name, key) not in target.landed: - await run.audit(LANDED, target_org, "*", name, key) - elif g["group_id"] in target.groups: - continue # landed by an earlier run: its members are the target's now - members = sorted({m for s in g["members"] if (m := run.subject(org, s))}) - rows.append({**g, "org": target_org, "members": members, "version": run.next_version()}) - if rows: - with _identity(): - await run.ch.insert( - "loom.principal_groups", await _typed(run.ch, "principal_groups", rows) - ) - - async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> 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 @@ -413,6 +471,14 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) run.count(d, "grants") with _identity(): await grants_repo.insert_rows(rows, ch=run.ch) + if not sso_same_issuer: + return + held_links = await run.ch.query_all( + "SELECT DISTINCT email, org, namespace FROM loom.sso_links " + "WHERE org IN {orgs:Array(String)}" + _SEQUENTIAL, + params={"orgs": sorted({d.target_org for d in decisions})}, + ) + linked = {(r["email"], r["org"], r["namespace"]) for r in held_links} links = [ { **link, @@ -422,10 +488,11 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) "version": run.next_version(), } for link in run.bundle.records("sso_links") - if sso_same_issuer - and (d := by_source.get((link["org"], link["namespace"]))) is not None + if (d := by_source.get((link["org"], link["namespace"]))) is not None and d.account - and d.source not in run.revoked + and d.source.lower() not in run.revoked + # One the target holds in any state, unlinked included, is the target's. + and (link["email"], d.target_org, d.target) not in linked ] if links: with _identity(): @@ -512,6 +579,30 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - run.count(d, "memories", len(rows)) +async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, str, str]]: + """Every (agent, user, session, key) the namespace holds or has held, a deleted one + included: a merge only adds keys, so it never revises the target's own fact, nor + brings back one its owners deleted.""" + from server.cli.instance_export import memory_heads + from server.core import pg + + def ident(r: Mapping[str, Any]) -> tuple[str, str, str, str]: + return (str(r["agent"]), str(r["user_id"]), str(r["session_id"]), str(r["memory_key"])) + + held = { + ident(r) + async for r in stream_rows( + ch, + "SELECT DISTINCT agent, user_id, session_id, memory_key FROM loom.memory " + "WHERE org = {org:String} AND namespace = {ns:String}", + {"org": org, "ns": namespace}, + ) + } + if pg.enabled(): # a head committed since its last publication is in the authority only + held.update([ident(r) async for r in memory_heads(ch, org, namespace)]) + return held + + def _bulk_entry(m: Any) -> dict[str, Any] | None: """A source head as a `memory.bulk_set` entry, None when it is no live fact: a row in another state, or one past its expiry. Its time of writing becomes the import's; its @@ -554,8 +645,12 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set + held = await _held_keys(run.ch, d.target_org, d.target) groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} for m in memories: + if (m.agent, m.user_id, m.session_id, m.memory_key) in held: + run.count(d, "memories_the_target_holds") + continue if (entry := _bulk_entry(m)) is None: run.count(d, "memories_not_live") continue @@ -641,17 +736,15 @@ async def apply( with _for(d): await _land(run, d, rows[(d.source_org, d.source)]) if d.action == "create": - await _types(run, d) + await _carry(run, d) await _blacklist(run, d, patterns) - await _groups(run, todo) await _grants(run, todo, rules.sso_same_issuer) await _memories(run, todo) await _documents(run, todo) for d in todo: await run.audit(DONE, d.target_org, d.target, d.target, run.key(d.source_org, d.source)) return { - "bundle": bundle.digest, - "plan": p.digest, + **run.digests, "counts": run.counts, "set_up_again": { s: [r for r in bundle.records(s) if r["org"] in p.orgs] diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 9b7198f2097..3661a02ee68 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -4,9 +4,10 @@ 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 group the target org already has, a subject the -bundle cannot place, or a principal (`everyone`, `user:`, `agent:`) that names other people -in a target org that already serves others. Each problem names the map entry that settles +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 names the map entry that settles it. The map file (YAML): orgs: # source org: target org (default: same name) @@ -42,13 +43,11 @@ is_sso_namespace_name, validate_namespace_name, ) +from server.core.principals import AGENT, EVERYONE, GROUP, USER +from server.identity.domain.join_policy import OPEN, effective_join_policy NsAction = Literal["create", "merge", "skip"] SubjectAction = Literal["claim", "map", "keep", "drop"] -# Principals another deployment's issuers, or the whole target org, also answer to: kept -# as they are only while the target org serves no one else. -ORG_RELATIVE_PREFIXES = ("user:", "agent:") -EVERYONE = "everyone" # Service accounts sign with credentials the source issued: their owners make new ones on # the target, so their grants are not carried. DROPPED_PREFIXES = ("sa:",) @@ -153,11 +152,10 @@ class TargetOrg: 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 - groups: frozenset[str] - # (name, "//") of each landing an earlier import recorded, a - # namespace's or a group's ("group:"): a run that stopped part way resumes, never - # taken for a collision. + # (name, "//") of each namespace an earlier import created: a + # run that stopped part way resumes, never taken for a collision. landed: frozenset[tuple[str, str]] = frozenset() + merged: frozenset[tuple[str, str]] = frozenset() # (target namespace, source) merged into done: frozenset[tuple[str, str]] = frozenset() # the landings an earlier run finished @@ -170,6 +168,9 @@ class NsDecision: 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) @@ -189,6 +190,7 @@ class Plan: 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.""" @@ -197,9 +199,6 @@ def subject_map(self) -> dict[tuple[str, str], str | None]: out[(s.source_org, s.subject)] = None if s.action == "drop" else s.target return out - def namespace_map(self) -> dict[tuple[str, str], NsDecision]: - return {(n.source_org, n.source): n for n in self.namespaces} - @property def digest(self) -> str: """Names the decisions and the bundle: `--expect-plan` refuses to apply a plan @@ -208,6 +207,7 @@ def digest(self) -> str: { "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], }, @@ -262,10 +262,6 @@ def problem(self, text: str, key: str = "", section: str = "", fix: Any = None) def subject(self, d: SubjectDecision) -> None: self.plan.subjects.append(d) - def ours(self, name: str) -> bool: - """Whether this source's earlier run landed `name` in the target org.""" - return (name, f"{self.source}/{self.org}/{name}") in self.target.landed - def occupied(self, target: str, source: str) -> bool: """Whether the target holds `target` other than as this source's earlier landing.""" return ( @@ -364,10 +360,24 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: return o.subject(SubjectDecision(o.org, name, "claim", handle, note=email)) o.plan.namespaces.append( - NsDecision(o.org, name, o.target_org, handle, "create", account="sso" if sso else "claim") + 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") @@ -406,44 +416,47 @@ def _plan_namespace(o: _Org, name: str) -> None: ) return if o.claim_name(target, name): - o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, target, "create")) + 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, group member or memory user that is no account of the - bundle.""" + """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) - if rule is not None: - if rule.action == "map" 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" - ) - return - if rule.action == "claim": - o.problem(f"subjects.{key}: only an account of the bundle can be claimed") - return - o.subject( - SubjectDecision( - o.org, subject, rule.action, rule.target if rule.action == "map" else subject - ) - ) + 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 subject.startswith("group:"): - gid = subject.removeprefix("group:") - if gid in o.target.groups and not o.ours(subject): + if rule is not None and rule.action == "map": + user = subject.startswith(USER) + if user != rule.target.startswith(USER): + o.problem(f"subjects.{key}: an end user maps to an end user (user:)") + elif not user and rule.target not in o.target.subjects: o.problem( - f"group {subject!r} exists on the target with its own members: map the grants " - "to a target subject, or drop them", - key, - "subjects", - "drop", + f"subjects.{key}: {rule.target!r} is no subject of {o.target_org} on the target" ) else: - o.subject(SubjectDecision(o.org, subject, "keep", subject)) + o.subject(SubjectDecision(o.org, subject, "map", rule.target)) + return + if subject.startswith((GROUP, AGENT)) or subject == EVERYONE: + 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 == EVERYONE or subject.startswith(ORG_RELATIVE_PREFIXES): - if o.shared: + if subject.startswith(USER): + # Another deployment's end-user issuer may name other people with the same id. + if o.shared and action != "keep": 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 " @@ -455,21 +468,22 @@ def _plan_subject(o: _Org, subject: str) -> None: else: o.subject(SubjectDecision(o.org, subject, "keep", subject)) return - if subject.startswith(DROPPED_PREFIXES): + if "@" in subject: + # 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) and action != "keep": o.subject( SubjectDecision( o.org, subject, "drop", note="service account: its owner makes a new one" ) ) return - if "@" in subject: - # 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 o.problem( f"subject {subject!r} holds grants or owns a namespace but is no account of the " - "bundle: map it to its owner's target subject, or drop it", + "bundle, and may name someone else on the target: map it to its owner's target " + "subject, or drop it", key, "subjects", "drop", @@ -496,7 +510,6 @@ def plan( namespace_rows: Iterable[Mapping[str, Any]], selected: Mapping[str, list[str]], grant_subjects: Mapping[str, set[str]], - groups: Mapping[str, set[str]], links: Mapping[str, Mapping[str, list[str]]], revoked: set[str], targets: Mapping[str, TargetOrg], @@ -504,11 +517,19 @@ def plan( ) -> Plan: """The decisions for every source org in `selected` (org → exported namespaces) of deployment `source`. `grant_subjects` is each source org's grant subjects, namespace - owners, group members and memory users (`user:`); `groups` and `links` its group - ids and its accounts' single sign-on link emails; `targets` the target state of each + owners and memory users (`user:`); `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.""" - p = Plan(bundle=bundle, orgs={}, namespaces=[], subjects=[], problems=[], proposals={}) + 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 @@ -516,7 +537,6 @@ def plan( for org in selected: landing.setdefault(rules.orgs.get(org, org), []).append(org) taken: dict[str, dict[str, str]] = {} - group_from: dict[tuple[str, str], str] = {} for org in sorted(selected): target_org = rules.orgs.get(org, org) if bad := _name_problem(target_org): @@ -543,9 +563,6 @@ def plan( taken=taken.setdefault(target_org, {}), shared=len(landing[target_org]) > 1 or bool(set(target.namespaces) - ours), ) - for gid in sorted(groups.get(org, set())): - if (other := group_from.setdefault((target_org, gid), org)) != org: - o.problem(f"group {gid!r} of {other} and of {org} both land in {target_org}") rows = o.rows accounts = {n for n in o.selected if is_account(rows[n])} for name in sorted(accounts): @@ -558,7 +575,7 @@ def plan( _plan_subject(o, subject) _check_users(o) for s in p.subjects: - if s.source_org == org and s.subject in revoked and s.action == "map": + if s.source_org == org and s.subject.lower() in revoked and s.action == "map": 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: claim or drop it" diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 3a61a241cd2..c157f094fd4 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -1,16 +1,19 @@ """`loom instance export` and `loom instance import` against a real ClickHouse: one org -moves into another that already has an account and a namespace with the same names. The -dry run refuses until the map settles both; the apply lands them under the mapped names -with every field of the source rows, merges a third namespace into the target's, leaves -the target's own rows alone, and a second apply of the same plan writes nothing.""" +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, and leaves the target's own rows alone. +Running it again, finished or resumed part way, writes nothing.""" from __future__ import annotations +import base64 +import hashlib import os import re import subprocess import sys -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -26,8 +29,10 @@ HASH = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdA$aGFzaA" KEYS = ("deploys", "oncall") +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"} +SEQ = " SETTINGS select_sequential_consistency = 1" @pytest.fixture(autouse=True) @@ -60,13 +65,26 @@ async def _account(ch: Any, org: str, name: str, email: str, active: bool = True ) -def _op(url: str, token: str, name: str, body: dict[str, Any]) -> dict[str, Any]: - r = httpx.post( - f"{url}/v1/{name}", json=body, headers={"Authorization": f"Bearer {token}"}, timeout=60 - ) - assert r.status_code == 200, (name, r.text) - out: dict[str, Any] = r.json() - return out +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]: @@ -80,66 +98,112 @@ def _cli(*args: str) -> subprocess.CompletedProcess[str]: ) -def _get(url: str, token: str, org: str, namespace: str, key: str) -> dict[str, Any]: - body = {"org": org, "namespace": namespace, "agent": "a", "memory_key": key} - return _op(url, token, "memory.get", body) +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", "expires_at": expires, "reason": "scim"}] + ) + src.op("namespace.register", namespace="team", owner_email="alice", visibility="public") + for subject, role in (("alice", "writer"), ("bob", "viewer"), ("carol", "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", + ) + src.op("namespace.register", namespace="notes", owner_email="alice") + 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 + + +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": { + (ns, key): dst.get(ns, key)["version"] + for ns, key in [("team-legacy", k) for k in KEYS] + [("team", "standup")] + }, + "document": dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md")[ + "revision" + ], + "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}" + ), + } 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, dst = unique_org("isrc"), unique_org("idst") - s = mint_test_token(org=src, roles=["admin"]) - t = mint_test_token(org=dst, roles=["admin"]) - await _account(ch, src, "alice", "alice@src.test") - _op( - control_plane_url, - s, - "namespace.register", - {"org": src, "namespace": "team", "owner_email": "alice"}, - ) - _op( - control_plane_url, - s, - "grants.create", - {"org": src, "namespace": "team", "subject": "alice", "role": "writer"}, - ) - for key in KEYS: - body = {"org": src, "namespace": "team", "agent": "a", "memory_key": key} - _op(control_plane_url, s, "memory.set", {**body, "value": f"the team's {key} rule"}) - notes = {"org": src, "namespace": "notes", "owner_email": "alice"} - _op(control_plane_url, s, "namespace.register", notes) - standup = {"org": src, "namespace": "notes", "agent": "a", "memory_key": "standup"} - _op(control_plane_url, s, "memory.set", {**standup, "value": "standup is at ten"}) - # The target's own alice and team are someone else's. - await _account(ch, dst, "alice", "alice@dst.test") - _op( - control_plane_url, - t, - "namespace.register", - {"org": dst, "namespace": "team", "owner_email": "alice"}, - ) - theirs = {"org": dst, "namespace": "team", "agent": "a", "memory_key": KEYS[0]} - _op(control_plane_url, t, "memory.set", {**theirs, "value": "the target's own rule"}) + src_org, dst_org = unique_org("isrc"), unique_org("idst") + 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 _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") + dst.op("grants.create", namespace="team", subject="bob", role="viewer") + dst.set("team", KEYS[0], "the target's own rule") bundle = tmp_path / "bundle" - out = _cli("export", "--org", src, "--out", str(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. - await _account(ch, src, "alice", "alice@src.test", active=False) + 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: dst}})) + 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}/team": {"rename": "team-legacy"}}, - # The minted token's subject: no account, email or principal the target knows. - "subjects": {f"{src}/alice": {"claim": "alice-legacy"}, f"{src}/test-suite": "drop"}, + "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 + # The minted token's subject: no account, email or principal the target knows. + f"{src_org}/test-suite": "drop", + }, } - proposals["namespaces"][f"{src}/notes"] = {"merge": "team"} - mapping.write_text(yaml.safe_dump({"orgs": {src: dst}, **proposals})) + proposals["namespaces"][f"{src_org}/notes"] = {"merge": "team"} + mapping.write_text(yaml.safe_dump({"orgs": {src_org: dst_org}, **proposals})) 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) @@ -148,57 +212,89 @@ async def test_an_org_moves_into_a_live_one_under_the_map( applied = _cli("import", "--bundle", str(bundle), *plan) assert applied.returncode == 0, applied.stdout + applied.stderr - versions = {} for key in KEYS: - before = _get(control_plane_url, s, src, "team", key) - after = _get(control_plane_url, t, dst, "team-legacy", key) + 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") - versions[key] = after["version"] - assert _get(control_plane_url, t, dst, "team", KEYS[0])["value"] == "the target's own rule" - assert not _get(control_plane_url, t, dst, "team", KEYS[1])["found"] - # A merge writes through memory.bulk_set: the fact and its validity are the source's. - before = _get(control_plane_url, s, src, "notes", "standup") - merged = _get(control_plane_url, t, dst, "team", "standup") + 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") - versions["standup"] = merged["version"] + assert dst.get("team", KEYS[0])["value"] == "the target's own rule" + assert not dst.get("team", KEYS[1])["found"] + + 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", + ) + blob = await ch.query_one( + "SELECT blob_path FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = 'team-legacy' AND source_uri = 'runbook.md'" + SEQ, + params={"org": dst_org}, + ) + assert blob is not None and blob["blob_path"] == hashlib.sha256(ORIGINAL).hexdigest() accounts = await ch.query_all( - "SELECT namespace, owner_email, contact_email, password_hash FROM loom.namespaces FINAL " - "WHERE org = {org:String} AND namespace IN ('alice', 'alice-legacy') ORDER BY namespace", - params={"org": dst}, + "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), - ("alice-legacy", "alice-legacy", "alice@src.test", HASH), + ("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", "carol@src.test", "", "inherit"), # revoked: nobody claims it + ("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 ORDER BY namespace, subject", - params={"org": dst}, + "WHERE org = {org:String} AND revoked_at IS NULL ORDER BY namespace, subject" + SEQ, + params={"org": dst_org}, ) - assert ("team-legacy", "alice-legacy", "writer") in [tuple(r.values()) for r in grants] - assert all(r["namespace"] != "team" for r in grants if r["subject"] == "alice-legacy") + assert [tuple(r.values()) for r in grants if r["namespace"] == "team-legacy"] == [ + ("team-legacy", "alice-legacy", "writer"), + ("team-legacy", "bob-legacy", "viewer"), + ("team-legacy", "carol", "viewer"), + ] + assert {r["subject"] for r in grants if r["namespace"] == "team"} == {"bob", "test-suite"} + state = await _state(ch, dst) + assert [b[:3] for b in state["blacklist"]] == [("team-legacy", "SECRET-", "namespace")] audit = ( - "SELECT event_type, namespace, JSONExtractString(subject, 'plan') AS plan " - "FROM loom.audit_log WHERE org = {org:String} AND event_type LIKE 'instance.import%' " - "ORDER BY event_type, namespace SETTINGS select_sequential_consistency = 1" + "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})] + landed = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] + created = ("alice-legacy", "bob-legacy", "carol", "team-legacy") assert landed == [ - (event, name, digest[1]) - for event in ("instance.import", "instance.import.done") - for name in ("alice-legacy", "team", "team-legacy") + *[("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 f"plan {digest[1]}" in again.stdout - assert [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst})] == landed - for key in KEYS: - assert _get(control_plane_url, t, dst, "team-legacy", key)["version"] == versions[key] - assert _get(control_plane_url, t, dst, "team", "standup")["version"] == versions["standup"] + assert await _state(ch, dst) == state + assert [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] == landed diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index ef26cc404d3..76ec4df9e7f 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -14,7 +14,7 @@ from server.cli.instance_plan import MapError, TargetOrg, parse_map, plan SOURCE = "dep-1" -EMPTY = TargetOrg({}, frozenset(), frozenset()) +EMPTY = TargetOrg({}, frozenset()) def _account(org: str, name: str, email: str) -> dict[str, Any]: @@ -39,7 +39,6 @@ def _plan( targets: dict[str, TargetOrg] | None = None, rules: Any = None, signs_in: dict[str, list[str]] | None = None, - groups: dict[str, set[str]] | None = None, links: dict[str, dict[str, list[str]]] | None = None, bundle: str = "b1", ) -> Any: @@ -51,7 +50,6 @@ def _plan( namespace_rows=rows, selected={o: sorted(r["namespace"] for r in rows if r["org"] == o) for o in orgs}, grant_subjects=subjects if isinstance(subjects, dict) else {"acme": subjects or set()}, - groups=groups or {}, links=links or {}, revoked=set(), targets=targets or {"acme": target or EMPTY}, @@ -89,7 +87,7 @@ 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"}), frozenset()) + 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"}}} @@ -104,7 +102,6 @@ def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: landed = TargetOrg( {**target.namespaces, "alice-legacy": {}, "team": {}}, target.subjects | {"alice-legacy"}, - frozenset(), landed=frozenset( {("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")} ), @@ -121,61 +118,82 @@ def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: 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(), frozenset({"eng"})) - p = _plan(rows, subjects={"ci-bot", "group:eng", "group:ops", "sa:ci", "bob@x"}, target=target) + 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 - assert p.proposals["subjects"] == {"acme/ci-bot": "drop", "acme/group:eng": "drop"} + # 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 == {"group:ops": "keep", "sa:ci": "drop", "bob@x": "keep"} + assert decided == {"sa:ci": "drop", "bob@x": "keep"} + # `keep` passes the same checks. + keep = {"subjects": dict.fromkeys(p.proposals["subjects"], "keep")} + again = _plan(rows, subjects=subjects, target=target, rules=keep) + assert set(again.proposals["subjects"]) == set(p.proposals["subjects"]) -def test_principals_of_a_shared_target_org_need_the_map() -> None: - """`everyone`, `user:` and `agent:` also name the target org's own people once it - serves others; in an org the import alone lands in, they stay.""" +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")] - subjects = {"x", "everyone", "user:42", "agent:helper"} - alone = _plan(rows, subjects=subjects, rules={"subjects": {"acme/x": "drop"}}) - assert alone.problems == [] - shared = TargetOrg({"theirs": {"kind": "memory"}}, frozenset(), frozenset()) - p = _plan(rows, subjects=subjects, target=shared, rules={"subjects": {"acme/x": "drop"}}) - assert p.proposals["subjects"] == { - "acme/everyone": "drop", - "acme/user:42": "drop", - "acme/agent:helper": "drop", - } - kept = _plan( - rows, - subjects=subjects, - target=shared, - rules={"subjects": {"acme/x": "drop", **dict.fromkeys(p.proposals["subjects"], "keep")}}, - ) - assert kept.problems == [] + 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_two_end_users_never_land_as_one() -> None: +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"}} - target = TargetOrg({}, frozenset({"user:c"}), frozenset()) - p = _plan(rows, subjects={"x", "user:a", "user:b"}, target=target, rules=rules) + 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) + + +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"} + + +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 or group two source orgs both bring to one target org refuses the plan, and - each org's principals are shared with the other's.""" + """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", "everyone"}, "b": {"x"}}, - targets={"t": EMPTY}, - rules=rules, - groups={"a": {"eng"}, "b": {"eng"}}, - ) + 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 any("group 'eng' of a and of b both land in t" in s for s in p.problems) - assert p.proposals["subjects"] == {"a/everyone": "drop"} + assert p.proposals["subjects"] == {"a/user:7": "drop"} def test_an_email_another_account_signs_in_with_refuses_the_claim() -> None: @@ -196,35 +214,17 @@ def test_an_email_another_account_signs_in_with_refuses_the_claim() -> None: def test_a_resumed_run_plans_the_same_digest() -> None: rows = [_account("acme", "alice", "alice@x"), _ns("acme", "team", "alice")] - subjects = {"alice", "group:eng", "user:7"} - first = _plan(rows, subjects=subjects, groups={"acme": {"eng"}}) + subjects = {"alice", "user:7"} + first = _plan(rows, subjects=subjects) assert first.problems == [] landed = TargetOrg( {"alice": {"kind": "memory"}, "team": {"kind": "memory"}}, frozenset({"alice"}), - frozenset({"eng"}), - landed=frozenset( - { - ("alice", f"{SOURCE}/acme/alice"), - ("team", f"{SOURCE}/acme/team"), - ("group:eng", f"{SOURCE}/acme/group:eng"), - } - ), - ) - again = _plan( - rows, - subjects=subjects, - target=landed, - groups={"acme": {"eng"}}, - signs_in={"alice@x": ["acme/alice"]}, + landed=frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}), ) + 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, landed.groups), - groups={"acme": {"eng"}}, - ) + other = _plan(rows, subjects=subjects, target=TargetOrg(landed.namespaces, landed.subjects)) assert other.problems # the same names, not landed by this source assert _plan(rows, subjects=subjects, bundle="b2").digest != first.digest @@ -250,25 +250,14 @@ def test_names_and_flags_the_map_refuses() -> None: parse_map({"namespaces": {"acme/team": {"merge": "t", "grants": "no"}}}) -def test_one_namespace_brings_the_accounts_and_groups_its_grants_name() -> None: +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"), - _account("acme", "dan", "d@x"), _ns("acme", "team", "alice"), _ns("acme", "acl-mirror", "alice"), ] - grants = [ - {"org": "acme", "namespace": "team", "subject": "bob"}, - {"org": "acme", "namespace": "team", "subject": "group:eng"}, - ] - groups = [ - {"org": "acme", "group_id": "eng", "members": ["carol"]}, - {"org": "acme", "group_id": "ops", "members": ["dan"]}, - ] - selected, group_ids = select_namespaces(rows, grants, groups, ["team"]) - assert selected == {"acme": ["alice", "bob", "carol", "team"]} - assert group_ids == {"acme": ["eng"]} - selected, _ = select_namespaces(rows, grants, groups, None) - assert selected == {"acme": ["alice", "bob", "carol", "dan", "team"]} + grants = [{"org": "acme", "namespace": "team", "subject": "bob"}] + assert select_namespaces(rows, grants, ["team"]) == {"acme": ["alice", "bob", "team"]} + assert select_namespaces(rows, grants, None) == {"acme": ["alice", "bob", "carol", "team"]} diff --git a/tests/unit/test_signup_privilege.py b/tests/unit/test_signup_privilege.py index 801d20fc842..209cc680870 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"]) From 637dae7b3ca5ef2eec67ddd57ef9d3f6be4eb381 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 22:46:02 +0530 Subject: [PATCH 04/32] loom instance import: a revoked account has no way in, a merge stores no refusals - An account the source revoked lands with no password, email or link, and its grants stay behind: an empty hash with a contact email was claimable by whoever proved that email at the target's identity provider. - A landed name is this import's own only while its row keeps the source's created_at; a name taken between the audit row and the namespace row is a collision, and a missing row is checked for use and access again. - A merge refuses the rows it brings by the source's refusals in process and stores none on the target's namespace. - The regex budget counts only the patterns a created namespace still has to store and skips finished landings, so a rerun is not refused; a refusal this deployment cannot compile is a plan problem. - A merge reads its target namespace's keys once per run, not per batch. - The bundle writer makes its directories 0700 and files 0600 itself, replacing the process-wide umask; an --out that names a file is refused. - The left-behind counts of a --namespace export cover those namespaces, and the dry run prints each counted kind with its row count. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/backup-and-recovery.md | 6 +- docs/operations/consolidation.md | 17 +- server/cli/instance.py | 17 +- server/cli/instance_bundle.py | 26 ++- server/cli/instance_export.py | 36 ++-- server/cli/instance_import.py | 174 +++++++++++++----- server/cli/instance_plan.py | 31 +++- .../test_instance_consolidation.py | 37 +++- tests/unit/test_instance_consolidation.py | 54 +++++- 9 files changed, 287 insertions(+), 111 deletions(-) diff --git a/docs/operations/backup-and-recovery.md b/docs/operations/backup-and-recovery.md index 565050009f4..29180e60cec 100644 --- a/docs/operations/backup-and-recovery.md +++ b/docs/operations/backup-and-recovery.md @@ -549,9 +549,9 @@ 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. 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: +[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 index bac6cf88e88..7b84ebd3d72 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -13,7 +13,7 @@ run, with their settings. To move a whole deployment onto new hosts, see | 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 moved namespaces it reaches | Conversations, session briefs, tasks, promoted shared memories and records: the manifest counts them | +| 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 | | Memories: every live head, with its `created_at`, validity and attestation | 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: the manifest lists them to register again | | | Embeddings, caches, traces, rollups, the audit log and agent events: the target builds what it needs again | @@ -92,7 +92,9 @@ subjects: # "/": rule `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. 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. It writes live facts only: a row in another + and session is left as the target has it. The source's refusals that reach the + source namespace refuse the rows it brings, and none is stored on the target's + namespace. It writes live facts only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the target namespace already serves is left as @@ -106,13 +108,14 @@ subjects: # "/": rule 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 the source revoked, by an operator or by SCIM, - lands with no password and no links. + lands with no password, email or links, and its grants stay behind: nobody signs in + to it. - **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves the address at sign-in on the target. 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, or - `drop`. Its decision moves that end user's memories too; two source users may not land - as one. `group:`, `agent:` and `everyone` hold grants on collections only, so the plan + `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 target subject. `sa:` subjects are dropped. Any other subject needs a mapping or `drop`. @@ -121,7 +124,9 @@ subjects: # "/": rule An import that stops part way runs again with the same command, and plans the same digest. 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. Once a namespace's content is written, an +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`: 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 id the namespace has diff --git a/server/cli/instance.py b/server/cli/instance.py index 3dde54388e4..baa6309b68b 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -88,13 +88,22 @@ def _print_plan(bundle: Any, p: Any) -> None: 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 namespaces above that it reaches") + 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)") - for kind, rows in (bundle.manifest.get("left_behind") or {}).items(): - if rows: - print(f" left behind: {kind}: {len(rows)} row(s)") + 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: diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py index 2dbfb7882a6..d71f94fcde2 100644 --- a/server/cli/instance_bundle.py +++ b/server/cli/instance_bundle.py @@ -5,6 +5,7 @@ `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. """ @@ -24,6 +25,8 @@ from typing import Any from uuid import UUID +from server.cli._paths import write_private + FORMAT = "loom-instance-bundle" VERSION = 1 MANIFEST = "manifest.json" @@ -48,6 +51,10 @@ def _default(v: Any) -> Any: 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 ( @@ -79,9 +86,13 @@ class BundleWriter: _originals: int = 0 def __post_init__(self) -> None: - if self.out.exists() and any(self.out.iterdir()): - raise BundleError(f"{self.out} is not empty: write each bundle into a new directory") - (self.out / ORIGINALS).mkdir(parents=True, exist_ok=True) + 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]: @@ -91,7 +102,7 @@ def section(self, name: str) -> Iterator[_SectionSink]: raise BundleError(f"section {name!r} written twice") final = self.out / f"{name}.jsonl.gz" part = final.with_name(final.name + ".part") - with gzip.open(part, "wb", compresslevel=6) as fh: + with open(part, "wb", opener=_private) as raw, gzip.open(raw, "wb", compresslevel=6) as fh: sink = _SectionSink(fh) yield sink part.rename(final) @@ -103,7 +114,8 @@ def original(self, data: bytes) -> str: path = self.out / ORIGINALS / digest if not path.exists(): part = path.with_name(digest + ".part") - part.write_bytes(data) + with open(part, "wb", opener=_private) as fh: + fh.write(data) part.rename(path) self._originals += 1 return digest @@ -121,9 +133,7 @@ def finish(self, meta: Mapping[str, Any]) -> dict[str, Any]: "sections": sections, "originals": self._originals, } - part = self.out / (MANIFEST + ".part") - part.write_text(json.dumps(manifest, indent=2, default=_default) + "\n") - os.replace(part, self.out / MANIFEST) + write_private(self.out / MANIFEST, json.dumps(manifest, indent=2, default=_default) + "\n") return manifest diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 6b4edcdd430..830eb698c32 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -14,7 +14,6 @@ from __future__ import annotations import json -import os from collections.abc import AsyncIterator, Iterable, Sequence from datetime import UTC, datetime from pathlib import Path @@ -327,33 +326,39 @@ async def _documents( ) -async def _left_behind(ch: Any, orgs: list[str]) -> dict[str, Any]: - """What the target rebuilds or its owners redo, named in the manifest for the plan.""" - p = {"orgs": orgs} +async def _left_behind( + ch: Any, orgs: list[str], only: dict[str, list[str]] | None +) -> 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} + 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( - "SELECT org, namespace, repo, git_remote FROM loom.code_repos FINAL " - "WHERE org IN {orgs:Array(String)} AND active", + f"SELECT org, namespace, repo, git_remote FROM loom.code_repos FINAL WHERE {scope} " + "AND active", params=p, ) sources = await ch.query_all( "SELECT org, namespace, name, kind FROM loom.knowledge_sources FINAL " - "WHERE org IN {orgs:Array(String)} AND active AND NOT pending_delete", + 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 " - "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'session_briefs', org, count() FROM loom.session_briefs FINAL " - "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'tasks', org, count() FROM loom.tasks FINAL " - "WHERE org IN {orgs:Array(String)} AND is_deleted = 0 GROUP BY org " + f"WHERE {scope} AND is_deleted = 0 GROUP BY org " "UNION ALL SELECT 'shared', org, count() FROM loom.shared FINAL " - "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'memory_records', org, count() FROM loom.memory_records FINAL " - "WHERE org IN {orgs:Array(String)} AND tombstoned_at IS NULL GROUP BY org " + f"WHERE {scope} AND tombstoned_at IS NULL GROUP BY org " "UNION ALL SELECT 'documents_of_end_users', org, count() FROM loom.documents FINAL " - "WHERE org IN {orgs:Array(String)} AND superseded_at IS NULL AND user_id != '-' " - "GROUP BY org", + f"WHERE {scope} AND superseded_at IS NULL AND user_id != '-' GROUP BY org", params=p, ) return {"code_repos": repos, "knowledge_sources": sources, "rows": rows} @@ -390,7 +395,6 @@ async def export( if missing: raise SystemExit(f"no memory namespace to export: {', '.join(missing)}") await refuse_unpublished_documents(content) - os.umask(0o077) w = BundleWriter(out) _write(w, "namespaces", (r for r in rows if r["namespace"] in selected.get(r["org"], ()))) _write(w, "grants", (g for g in grants if g["namespace"] in content.get(g["org"], ()))) @@ -408,6 +412,6 @@ async def export( "orgs": orgs, "namespaces": selected, "counts": counts, - "left_behind": await _left_behind(ch, orgs), + "left_behind": await _left_behind(ch, orgs, None if namespaces is None else content), } ) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 2de6c2582b6..155d1b0c516 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -27,9 +27,17 @@ from datetime import UTC, datetime from typing import Any -from server.cli.instance_bundle import Bundle +from server.cli.instance_bundle import ORIGINALS, Bundle from server.cli.instance_export import stream_rows -from server.cli.instance_plan import MapFile, NsDecision, Plan, TargetOrg, is_account, plan +from server.cli.instance_plan import ( + MapFile, + NsDecision, + Plan, + TargetOrg, + is_account, + landed_row, + plan, +) LANDED = "instance.import" MERGED = "instance.import.merge" # a merge lands in the target's own namespace @@ -61,7 +69,7 @@ async def load_target( 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 FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", + "released_aliases, created_at FROM loom.namespaces FINAL WHERE org IN {orgs:Array(String)}", params=p, ) grants = await ch.query_all( @@ -159,8 +167,9 @@ def _revoked(bundle: Bundle) -> set[str]: 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 empowers it, or it holds a grant, a namespace, - a token or a task, as self-signup refuses it), a namespace whose refusals would pass - the regex budget, an original missing from the bundle. Each is added as a problem.""" + a token or a task, as self-signup refuses it), a refusal this deployment cannot compile, + a created namespace whose refusals would pass the regex budget, an original missing + from the bundle. Each is added as a problem.""" from fastapi import HTTPException from server.auth.self_signup import refuse_empowered @@ -172,8 +181,13 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) for d in p.namespaces: - key = source_key(bundle, d.source_org, d.source) - if not d.account or (d.target, key) in targets[d.target_org].landed: + t = targets[d.target_org] + # A name the target holds is this import's own row (else the plan refused it). + if ( + not d.account + or d.target in t.namespaces + or (d.target, source_key(bundle, d.source_org, d.source)) in t.done + ): continue try: await refuse_empowered(ch, d.target_org, d.target.lower()) @@ -187,15 +201,24 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr } regexes = [b for b in bundle.records("blacklist") if b["pattern_type"] == "regex"] for d in p.namespaces: - if d.action == "skip": + key = source_key(bundle, d.source_org, d.source) + if d.action == "skip" or (d.target, key) in targets[d.target_org].done: continue + 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 regexes: - if _reaches(b, d): - try: - size += compile_regex(b["pattern"]).programsize - except ValidationError: - continue + 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 ): @@ -208,7 +231,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr for doc in bundle.records("documents"): sha = doc.get("blob_path") if (doc["org"], doc["namespace"]) in landing and sha and not doc.get("blob_erased_at"): - if not (bundle.path / "originals" / str(sha)).is_file(): + if not (bundle.path / ORIGINALS / str(sha)).is_file(): p.problems.append( f"{doc['org']}/{doc['namespace']} document {doc['source_uri']!r}: the " f"bundle has no original {sha}: copy the whole bundle" @@ -220,6 +243,43 @@ def _reaches(b: Mapping[str, Any], d: NsDecision) -> bool: 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[tuple[Any, str]]: + """The source refusals that reach a merged namespace, as the guard runs them: 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 compile_regex + + return [ + (compile_regex(b["pattern"]) if b["pattern_type"] == "regex" else None, b["pattern"]) + for b in patterns + if _reaches(b, d) + ] + + +def _refused(refusals: list[tuple[Any, str]], value: str) -> bool: + """Whether a refusal matches `value`: a regex in its UTF-8, a substring in the text.""" + data = value.encode("utf-8", "replace") + return any(r.search(data) if r is not None else s in value for r, s in refusals) + + 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.""" @@ -246,19 +306,21 @@ class _Run: 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 - from server.memory.domain.provenance import cli_actor self.ch = ch self.bundle = bundle self.plan = p self.targets = targets - self.actor = writer_actor(fallback=cli_actor("instance")) + 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]] = {} + # Per merge: the source refusals, and the keys its target namespace holds. + self.refusals: dict[tuple[str, str], list[tuple[Any, str]]] = {} + self.held: dict[tuple[str, str], set[tuple[str, str, str, str]]] = {} def next_version(self) -> int: self.version += 1 @@ -326,21 +388,25 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: await run.audit(MERGED, d.target_org, d.target, d.target, key) return landed = (d.target, key) in target.landed + 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 not landed: - if existing is not None or await directory().in_use(d.target_org, d.target, ch=run.ch): - raise SystemExit(f"{d.target_org}/{d.target} is in use on the target: plan again") - 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 - await run.audit(LANDED, d.target_org, d.target, d.target, key) if existing is not None: + # An earlier run's row, or a name someone took since its audit row. + if not landed or not landed_row(existing, row): + raise in_use 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 not landed: + await run.audit(LANDED, d.target_org, d.target, d.target, key) 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) @@ -350,7 +416,8 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: # 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: - new["password_hash"] = "" # revoked on the source: nobody claims it + # 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) @@ -391,24 +458,17 @@ async def _carry(run: _Run, d: NsDecision) -> None: async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) -> None: - """The source's refusals that reach the source namespace (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. One id per pattern and landing, so a - pattern the target's owners removed is not added back.""" + """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 - ids = [ - uuid.uuid5(uuid.UUID(str(b["pattern_id"])), f"{d.target_org}/{d.target}") for b in patterns - ] - have = await run.ch.query_all( - "SELECT DISTINCT toString(pattern_id) AS id FROM loom.blacklist " - "WHERE pattern_id IN {ids:Array(UUID)}", - params={"ids": [str(i) for i in ids]}, - ) - present = {str(r["id"]) for r in have} - for b, pid in zip(patterns, ids, strict=True): - if not _reaches(b, d) or str(pid) in present: + 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( @@ -422,7 +482,7 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - "created_by": run.actor, } ), - str(pid), + pid, ) run.count(d, "refusals") @@ -430,8 +490,8 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> 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, one the subject already holds at that role or higher, one a target - admin revoked.""" + dropped subject's, a subject's the source revoked, one the subject already holds at + that role or higher, one a target admin revoked.""" from server.identity.store import grants as grants_repo from server.operations.base import grant_rank @@ -451,6 +511,9 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) 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 str(g["subject"]).lower() in run.revoked: + run.count(d, "grants_of_revoked") + continue prior = have.get((d.target_org, d.target, subject)) if prior == "" or (prior is not None and grant_rank(prior) >= grant_rank(g["role"])): continue @@ -553,7 +616,9 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - row = _SnapshotMemoryRow.model_validate( {k: v for k, v in m.items() if k not in ("org", "namespace")} ) - if await blacklist_guard.find_match(org=d.target_org, namespace=d.target, value=row.value): + if await blacklist_guard.find_match( + org=d.target_org, namespace=d.target, value=row.value + ) or _refused(run.refusals.get((d.source_org, d.source), []), row.value): run.count(d, "memories_refused") else: kept.append(row) @@ -645,15 +710,20 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set - held = await _held_keys(run.ch, d.target_org, d.target) + t = (d.target_org, d.target) + if t not in run.held: # once per target namespace: each write adds its keys below + run.held[t] = await _held_keys(run.ch, d.target_org, d.target) + held = run.held[t] groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} for m in memories: - if (m.agent, m.user_id, m.session_id, m.memory_key) in held: + ident = (m.agent, m.user_id, m.session_id, m.memory_key) + if ident in held: run.count(d, "memories_the_target_holds") continue if (entry := _bulk_entry(m)) is None: run.count(d, "memories_not_live") continue + held.add(ident) groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) for (agent, user_id, session_id), entries in groups.items(): for start in range(0, len(entries), MAX_BULK_ENTRIES): @@ -737,7 +807,9 @@ async def apply( await _land(run, d, rows[(d.source_org, d.source)]) if d.action == "create": await _carry(run, d) - await _blacklist(run, d, patterns) + await _blacklist(run, d, patterns) + else: + run.refusals[(d.source_org, d.source)] = _refusals(patterns, d) await _grants(run, todo, rules.sso_same_issuer) await _memories(run, todo) await _documents(run, todo) diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 3661a02ee68..27e557ac4de 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -34,6 +34,7 @@ import json from collections.abc import Iterable, Mapping from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime from typing import Any, Literal from server.auth.sharing import PERSONAL_ALIAS, is_collection @@ -225,6 +226,19 @@ def is_account(row: Mapping[str, Any]) -> bool: ) +def landed_row(row: Mapping[str, Any], source_row: Mapping[str, Any]) -> bool: + """Whether a target namespace row is the one an import wrote from `source_row`: it + keeps the source's `created_at`, which a name registered since cannot have.""" + + def at(v: Any) -> Any: # the bundle's ISO text or the target's naive UTC + t = datetime.fromisoformat(v) if isinstance(v, str) else v + return t.replace(tzinfo=UTC) if isinstance(t, datetime) and t.tzinfo is None else t + + return row.get("created_at") is not None and at(row["created_at"]) == at( + source_row.get("created_at") + ) + + def _name_problem(name: str) -> str | None: try: validate_namespace_name(name) @@ -263,11 +277,13 @@ 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 earlier landing.""" - return ( - target in self.target.namespaces - and (target, f"{self.source}/{self.org}/{source}") not in self.target.landed - ) + """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.""" + row = self.target.namespaces.get(target) + key = (target, f"{self.source}/{self.org}/{source}") + if row is None or key in self.target.done: + return False + return key not in self.target.landed or not landed_row(row, self.rows[source]) def claim_name(self, name: str, source: str) -> bool: """Reserve `name` in the target org for `source`; False (and a problem) when it @@ -491,8 +507,9 @@ def _plan_subject(o: _Org, subject: str) -> None: def _check_users(o: _Org) -> None: - """Two end users 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.""" + """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:"): diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index c157f094fd4..bca91d89ea0 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -2,8 +2,9 @@ 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, and leaves the target's own rows alone. -Running it again, finished or resumed part way, writes nothing.""" +target's without touching a key the target holds or storing the source's refusals there, +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 @@ -21,6 +22,7 @@ import pytest import yaml +from server.auth.login import resolve_identity_for_email from server.core.ch import get_client from tests.integration._resources import unique_org @@ -33,6 +35,10 @@ # What a restore owns on a row it writes: everything else is the source's. RESTORED = {"version", "version_text", "actor", "source_class"} 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 @pytest.fixture(autouse=True) @@ -136,6 +142,16 @@ async def _seed_source(ch: Any, src: _Api) -> None: sensitivity="low", ) src.set("notes", KEYS[0], "the notes' own deploy rule") # a key the target's team holds + 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]: @@ -172,7 +188,7 @@ 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=["admin"]), src_org) + 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. @@ -229,6 +245,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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 doc = dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md") assert (doc["found"], doc["content"], doc["title"]) == ( @@ -252,7 +269,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("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", "carol@src.test", "", "inherit"), # revoked: nobody claims it + ("carol", "carol", "", "", "inherit"), # revoked: no password, email or link ("team", "alice", "", "", "inherit"), # Public on the source: in an org that serves others a self-join waits for approval. ("team-legacy", "alice-legacy", "", "", "approval"), @@ -265,11 +282,17 @@ async def test_an_org_moves_into_a_live_one_under_the_map( assert [tuple(r.values()) for r in grants if r["namespace"] == "team-legacy"] == [ ("team-legacy", "alice-legacy", "writer"), ("team-legacy", "bob-legacy", "viewer"), - ("team-legacy", "carol", "viewer"), ] assert {r["subject"] for r in grants if r["namespace"] == "team"} == {"bob", "test-suite"} + assert await resolve_identity_for_email("carol@src.test") is None state = await _state(ch, dst) - assert [b[:3] for b in state["blacklist"]] == [("team-legacy", "SECRET-", "namespace")] + 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, " @@ -278,7 +301,6 @@ async def test_an_org_moves_into_a_live_one_under_the_map( "ORDER BY event_type, name" + SEQ ) landed = [tuple(r.values()) for r in await ch.query_all(audit, params={"org": dst_org})] - created = ("alice-legacy", "bob-legacy", "carol", "team-legacy") 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"))], @@ -298,3 +320,4 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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 diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 76ec4df9e7f..c7c656b0316 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -4,6 +4,8 @@ from __future__ import annotations import gzip +import stat +from datetime import datetime from pathlib import Path from typing import Any @@ -11,10 +13,14 @@ from server.cli.instance_bundle import Bundle, BundleError, BundleWriter from server.cli.instance_export import select_namespaces -from server.cli.instance_plan import MapError, TargetOrg, parse_map, plan +from server.cli.instance_import import _refusals, _refused +from server.cli.instance_plan import MapError, NsDecision, TargetOrg, parse_map, plan 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]: @@ -24,11 +30,12 @@ def _account(org: str, name: str, email: str) -> dict[str, Any]: "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} + return {"org": org, "namespace": name, "owner_email": owner, "created_at": AT} def _plan( @@ -68,8 +75,13 @@ def test_bundle_round_trip_and_tamper(tmp_path: Path) -> None: 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" - with pytest.raises(BundleError, match="not empty"): + # 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"): @@ -100,7 +112,7 @@ def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: ("team", "team", ""), } landed = TargetOrg( - {**target.namespaces, "alice-legacy": {}, "team": {}}, + {**target.namespaces, "alice-legacy": LANDED, "team": LANDED}, target.subjects | {"alice-legacy"}, landed=frozenset( {("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")} @@ -217,15 +229,25 @@ def test_a_resumed_run_plans_the_same_digest() -> None: subjects = {"alice", "user:7"} first = _plan(rows, subjects=subjects) assert first.problems == [] - landed = TargetOrg( - {"alice": {"kind": "memory"}, "team": {"kind": "memory"}}, - frozenset({"alice"}), - landed=frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}), - ) + marks = frozenset({("alice", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")}) + names = {"alice": LANDED, "team": LANDED} + landed = TargetOrg(names, frozenset({"alice"}), landed=marks) 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=marks, + ) + p = _plan(rows, subjects=subjects, target=taken, signs_in={"alice@x": ["acme/alice"]}) + assert p.proposals == {"namespaces": {"acme/team": {"rename": "team-legacy"}}} + # A finished landing is the target's now, whatever its owners did to the row. + done = TargetOrg(taken.namespaces, landed.subjects, landed=marks, 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 @@ -261,3 +283,17 @@ def test_one_namespace_brings_the_accounts_its_grants_name() -> None: grants = [{"org": "acme", "namespace": "team", "subject": "bob"}] assert select_namespaces(rows, grants, ["team"]) == {"acme": ["alice", "bob", "team"]} assert select_namespaces(rows, grants, None) == {"acme": ["alice", "bob", "carol", "team"]} + + +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"}, + ] + refusals = _refusals(patterns, d) + assert len(refusals) == 2 # its org's and the deployment's; not another namespace's + assert _refused(refusals, '"the tok-1234 key"') and _refused(refusals, '"a SECRET"') + assert not _refused(refusals, '"a secret on deploys, tok-12"') From 5a4c351096cbde4a90d53a057a5713385bf6285b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:32:51 +0530 Subject: [PATCH 05/32] loom instance import: a row-only landing stays unfinished, acl- names move - The manifest names the namespaces whose content the bundle holds, and instance.import.done is written for those only: an account a --namespace export brought for its grants landed done with none of its content, so a later whole-org import skipped it. The dry run marks row-only landings. - The export leaves out only the reserved mirror and code-store forms and collections, not every acl- or crs- name. - The plan checks no email or link of an account the source revoked, since none of them lands, and says it lands revoked. - Under the Postgres authority, a resume reads every head the authority holds, deleted and unpublished ones included, as written already. - Every read of a plan and apply is sequentially consistent, replacing the per-statement settings. - A merge matches the source refusals with the guard's own matcher. - The integration test's revoked account has a handle of its own, and a new test runs a --namespace bundle and then a whole-org one. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 11 +- server/cli/instance.py | 16 ++- server/cli/instance_export.py | 14 +-- server/cli/instance_import.py | 91 ++++++++++------ server/cli/instance_plan.py | 17 +-- server/memory/app/blacklist_guard.py | 7 ++ server/memory/store/pg_memory.py | 26 +++++ .../test_instance_consolidation.py | 102 ++++++++++++++++-- tests/unit/test_instance_consolidation.py | 40 +++++-- 9 files changed, 259 insertions(+), 65 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 7b84ebd3d72..5899cecc08b 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -40,8 +40,9 @@ Memories reach vector search once the embedding worker's next full pass embeds t ``` With `--namespace`, the bundle carries that namespace's content, and the account rows - its grants and owner name, so the plan can place them. An org or namespace with - nothing to export refuses the export. The bundle holds password hashes: it is written + 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. The bundle holds password hashes: it is written readable by its owner only, and is copied to the target whole, the way a database dump is. @@ -52,8 +53,8 @@ Memories reach vector search once the embedding worker's next full pass embeds t loom instance import --bundle ./acme-bundle --map map.yaml ``` - Each problem names the map entry that settles it, and the run prints those entries as - YAML to copy into the map. + Each problem says what settles it. Where a map entry does, the run prints the entries + as YAML to copy into the map. 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: @@ -109,7 +110,7 @@ subjects: # "/": rule `sso_same_issuer: true` when both deployments use the same identity provider, which also carries its links. An account the source revoked, by an operator or by SCIM, lands with no password, email or links, and its grants stay behind: nobody signs in - to it. + to it, so the plan checks none of its emails. - **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves the address at sign-in on the target. 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 diff --git a/server/cli/instance.py b/server/cli/instance.py index baa6309b68b..9875fccaf3f 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -76,13 +76,20 @@ async def _run(ch: Any) -> dict[str, Any]: def _print_plan(bundle: Any, p: Any) -> None: + from server.cli.instance_import import carried from server.cli.instance_plan import proposal_yaml + content = carried(bundle) 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 "" joins = " (self-join needs approval: the target org serves others)" if d.approval else "" - print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}") + rows = ( + " (its row only: a bundle that selects it brings its content)" + if d.action != "skip" and (d.source_org, d.source) not in content + else "" + ) + print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{rows}") for s in p.subjects: to = f" → {s.target}" if s.action in ("map", "claim") else "" note = f" [{s.note}]" if s.note else "" @@ -122,6 +129,7 @@ def _cmd_import(args: argparse.Namespace) -> int: 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) @@ -131,6 +139,12 @@ def _cmd_import(args: argparse.Namespace) -> int: 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) diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 830eb698c32..fde13c0571f 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -21,9 +21,6 @@ from server.cli.instance_bundle import BundleWriter -# A namespace name of these forms is not the organization's to move: a mirror's or a code -# store's (the index rebuilds them), a collection (moved with its owner's account). -_NOT_EXPORTED_PREFIXES = ("acl-", "crs-", "col-") # SCIM's revocation key prefix (`server.auth.revocation.SCIM_PREFIX`) as a SQL literal. _SCIM = "\\0scim:" _STREAM_SETTINGS = { @@ -105,13 +102,17 @@ async def refuse_unpublished_documents(selected: dict[str, list[str]]) -> None: def exported_namespace(row: dict[str, Any]) -> bool: - """A memory namespace the organization holds: not a code index's, a benchmark's, a - mirror's, a code store's or a collection, and not soft-deleted.""" + """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 name.startswith(_NOT_EXPORTED_PREFIXES) + and not (is_reserved_name(name) or is_collection(name)) ) @@ -411,6 +412,7 @@ async def export( "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), } diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 155d1b0c516..7f7a809e7c0 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -23,7 +23,7 @@ import json import time import uuid -from collections.abc import Iterable, Mapping +from collections.abc import AsyncIterator, Iterable, Mapping from datetime import UTC, datetime from typing import Any @@ -53,13 +53,19 @@ } # A row in any other state is history, not a fact a merge states again. _MERGED_STATUS = "active" -_SEQUENTIAL = " SETTINGS select_sequential_consistency = 1" 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]]]: @@ -80,7 +86,7 @@ async def load_target( landings = await ch.query_all( "SELECT DISTINCT event_type, org, JSONExtractString(subject, 'name') AS name, " "JSONExtractString(subject, 'source') AS source FROM loom.audit_log " - "WHERE org IN {orgs:Array(String)} AND event_type IN {events:Array(String)}" + _SEQUENTIAL, + "WHERE org IN {orgs:Array(String)} AND event_type IN {events:Array(String)}", params=p, ) out: dict[str, TargetOrg] = {} @@ -166,10 +172,10 @@ def _revoked(bundle: Bundle) -> set[str]: 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 empowers it, or it holds a grant, a namespace, - a token or a task, as self-signup refuses it), a refusal this deployment cannot compile, - a created namespace whose refusals would pass the regex budget, an original missing - from the bundle. Each is added as a problem.""" + 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), a refusal + this deployment cannot compile, a created namespace whose refusals would pass the regex + budget, an original missing from the bundle. Each is added as a problem.""" from fastapi import HTTPException from server.auth.self_signup import refuse_empowered @@ -261,25 +267,28 @@ async def _stored(ch: Any, ids: list[str]) -> set[str]: return {str(r["id"]) for r in rows} -def _refusals(patterns: Iterable[Mapping[str, Any]], d: NsDecision) -> list[tuple[Any, str]]: - """The source refusals that reach a merged namespace, as the guard runs them: 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 compile_regex +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 [ - (compile_regex(b["pattern"]) if b["pattern_type"] == "regex" else None, b["pattern"]) + 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) ] -def _refused(refusals: list[tuple[Any, str]], value: str) -> bool: - """Whether a refusal matches `value`: a regex in its UTF-8, a substring in the text.""" - data = value.encode("utf-8", "replace") - return any(r.search(data) if r is not None else s in value for r, s in refusals) - - 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.""" @@ -319,7 +328,7 @@ def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, Targe self.digests = {"bundle": bundle.digest, "plan": p.digest} self.counts: dict[str, dict[str, int]] = {} # Per merge: the source refusals, and the keys its target namespace holds. - self.refusals: dict[tuple[str, str], list[tuple[Any, str]]] = {} + self.refusals: dict[tuple[str, str], list[Any]] = {} self.held: dict[tuple[str, str], set[tuple[str, str, str, str]]] = {} def next_version(self) -> int: @@ -439,7 +448,7 @@ async def _carry(run: _Run, d: NsDecision) -> None: for table, key 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}" + _SEQUENTIAL, + "WHERE org = {org:String} AND namespace = {ns:String}", params={"org": d.target_org, "ns": d.target}, ) held = {str(r["k"]) for r in have} @@ -498,7 +507,7 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) by_source = {(d.source_org, d.source): d for d in decisions} held = await run.ch.query_all( "SELECT org, namespace, subject, role, revoked_at IS NOT NULL AS revoked " - "FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)}" + _SEQUENTIAL, + "FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)}", params={"orgs": sorted({d.target_org for d in decisions})}, ) have = { @@ -538,7 +547,7 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) return held_links = await run.ch.query_all( "SELECT DISTINCT email, org, namespace FROM loom.sso_links " - "WHERE org IN {orgs:Array(String)}" + _SEQUENTIAL, + "WHERE org IN {orgs:Array(String)}", params={"orgs": sorted({d.target_org for d in decisions})}, ) linked = {(r["email"], r["org"], r["namespace"]) for r in held_links} @@ -565,7 +574,7 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) async def _seen(ch: Any, column: str, org: str, namespace: str) -> set[str]: """Every memory id or document source_uri the namespace has held, deleted ones too.""" table = "memory" if column == "memory_id" else "documents" - return { + seen = { str(r["v"]) async for r in stream_rows( ch, @@ -574,6 +583,25 @@ async def _seen(ch: Any, column: str, org: str, namespace: str) -> set[str]: {"org": org, "ns": namespace}, ) } + if column == "memory_id": + seen.update([str(r["memory_id"]) async for r in _authority_heads(org, namespace)]) + return seen + + +async def _authority_heads(org: str, namespace: str) -> AsyncIterator[dict[str, Any]]: + """Under the Postgres authority, every head of the namespace, deleted ones included: a + head committed since its last publication to ClickHouse is there only.""" + from server.core import pg + from server.memory.store import pg_memory + + if not pg.enabled(): + return + after = None + while page := await pg_memory.held_in(org, namespace, after=after): + for r in page: + yield r + last = page[-1] + after = (last["agent"], last["user_id"], last["session_id"], last["memory_key"]) async def _memories(run: _Run, decisions: list[NsDecision]) -> None: @@ -618,7 +646,7 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - ) if await blacklist_guard.find_match( org=d.target_org, namespace=d.target, value=row.value - ) or _refused(run.refusals.get((d.source_org, d.source), []), row.value): + ) or blacklist_guard.match_value(run.refusals.get((d.source_org, d.source), []), row.value): run.count(d, "memories_refused") else: kept.append(row) @@ -648,8 +676,6 @@ async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, s """Every (agent, user, session, key) the namespace holds or has held, a deleted one included: a merge only adds keys, so it never revises the target's own fact, nor brings back one its owners deleted.""" - from server.cli.instance_export import memory_heads - from server.core import pg def ident(r: Mapping[str, Any]) -> tuple[str, str, str, str]: return (str(r["agent"]), str(r["user_id"]), str(r["session_id"]), str(r["memory_key"])) @@ -663,8 +689,7 @@ def ident(r: Mapping[str, Any]) -> tuple[str, str, str, str]: {"org": org, "ns": namespace}, ) } - if pg.enabled(): # a head committed since its last publication is in the authority only - held.update([ident(r) async for r in memory_heads(ch, org, namespace)]) + held.update([ident(r) async for r in _authority_heads(org, namespace)]) return held @@ -809,12 +834,14 @@ async def apply( await _carry(run, d) await _blacklist(run, d, patterns) else: - run.refusals[(d.source_org, d.source)] = _refusals(patterns, d) + run.refusals[(d.source_org, d.source)] = refusals(patterns, d) await _grants(run, todo, rules.sso_same_issuer) await _memories(run, todo) await _documents(run, todo) - for d in todo: - await run.audit(DONE, d.target_org, d.target, d.target, run.key(d.source_org, d.source)) + 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, diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 27e557ac4de..7163e6c84c8 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -7,8 +7,8 @@ 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 names the map entry that settles -it. The map file (YAML): +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 @@ -267,6 +267,7 @@ class _Org: plan: Plan taken: dict[str, str] # target name → source it lands from, across the target org shared: bool # the target org serves others, or another source org lands in it + revoked: set[str] # the source subjects revoked outright, lower-cased def problem(self, text: str, key: str = "", section: str = "", fix: Any = None) -> None: self.plan.problems.append(f"{self.org}: {text}") @@ -312,7 +313,9 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: target account, or left out with its namespace.""" key = f"{o.org}/{name}" rule = o.rules.subjects.get(key) - email = str(row.get("contact_email") or "").strip().lower() + # 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 rule is not None and rule.action == "drop": o.subject(SubjectDecision(o.org, name, "drop", note="account and namespace left out")) @@ -336,7 +339,7 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> 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: + 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, sorted(emails)): org, _, account = holder.partition("/") @@ -348,7 +351,7 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: account if org == o.target_org else "drop", ) return - if sso and not o.rules.sso_same_issuer: + 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 " @@ -374,7 +377,8 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: return if not o.claim_name(handle, name): return - o.subject(SubjectDecision(o.org, name, "claim", handle, note=email)) + 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, @@ -579,6 +583,7 @@ def plan( plan=p, taken=taken.setdefault(target_org, {}), shared=len(landing[target_org]) > 1 or bool(set(target.namespaces) - ours), + revoked=revoked, ) rows = o.rows accounts = {n for n in o.selected if is_account(rows[n])} diff --git a/server/memory/app/blacklist_guard.py b/server/memory/app/blacklist_guard.py index 42eb767ff22..c6d323a4ab4 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 5af3de3a3bc..e13c36faa7e 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -2087,6 +2087,32 @@ async def live_heads_in( return [decode_row(r["row"]) for r in rows] +async def held_in( + org: str, + namespace: str, + *, + after: tuple[str, str, str, str] | None = None, + limit: int = 5000, +) -> list[dict[str, Any]]: + """A page of every head of a namespace, deleted ones included, as its memory id and + (agent, user_id, session_id, memory_key), in key order after `after`: 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)" + rows = await pg.fetch( + "SELECT memory_id::text AS memory_id, agent, user_id, session_id, memory_key " + f"FROM loom.memory_current WHERE {where} " + "ORDER BY org, namespace, agent, user_id, session_id, memory_key LIMIT $3", + *args, + ) + return [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 index bca91d89ea0..e42c23aa740 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -12,6 +12,7 @@ import hashlib import os import re +import secrets import subprocess import sys from datetime import UTC, datetime, timedelta @@ -23,6 +24,7 @@ import yaml from server.auth.login import resolve_identity_for_email +from server.cli.instance_bundle import Bundle from server.core.ch import get_client from tests.integration._resources import unique_org @@ -39,6 +41,9 @@ # 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)}" @pytest.fixture(autouse=True) @@ -105,15 +110,16 @@ def _cli(*args: str) -> subprocess.CompletedProcess[str]: async def _seed_source(ch: Any, src: _Api) -> None: - for name in ("alice", "bob", "carol"): + 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", "expires_at": expires, "reason": "scim"}] + "loom.revoked_tokens", + [{"jti": "\x00scim:" + CAROL.upper(), "expires_at": expires, "reason": "scim"}], ) src.op("namespace.register", namespace="team", owner_email="alice", visibility="public") - for subject, role in (("alice", "writer"), ("bob", "viewer"), ("carol", "viewer")): + for subject, role in (("alice", "writer"), ("bob", "viewer"), (CAROL, "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") @@ -201,7 +207,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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"): + for name in ("alice", "bob", CAROL): await _account(ch, src_org, name, f"{name}@src.test", active=False) mapping = tmp_path / "map.yaml" @@ -269,7 +275,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("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 + (CAROL, CAROL, "", "", "inherit"), # revoked: no password, email or link ("team", "alice", "", "", "inherit"), # Public on the source: in an org that serves others a self-join waits for approval. ("team-legacy", "alice-legacy", "", "", "approval"), @@ -284,9 +290,9 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("team-legacy", "bob-legacy", "viewer"), ] assert {r["subject"] for r in grants if r["namespace"] == "team"} == {"bob", "test-suite"} - assert await resolve_identity_for_email("carol@src.test") is None + 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") + 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( @@ -321,3 +327,85 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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.""" + 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") + src.op("namespace.register", namespace="team", owner_email="dana") + src.op("grants.create", namespace="team", subject="dana", role="writer") + 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) + 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" + mapping.write_text( + yaml.safe_dump({"orgs": {src_org: dst_org}, "subjects": {f"{src_org}/test-suite": "drop"}}) + ) + 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", "team"), + ("instance.import.done", "team"), + ] + team = dst.get("team", "deploys")["version"] + + assert "(its row only" not in imported(whole) + 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", "team"), + ("instance.import.done", "dana"), + ("instance.import.done", "team"), + ] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index c7c656b0316..fecf088c981 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -5,6 +5,7 @@ import gzip import stat +import uuid from datetime import datetime from pathlib import Path from typing import Any @@ -13,8 +14,10 @@ from server.cli.instance_bundle import Bundle, BundleError, BundleWriter from server.cli.instance_export import select_namespaces -from server.cli.instance_import import _refusals, _refused +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 SOURCE = "dep-1" EMPTY = TargetOrg({}, frozenset()) @@ -46,6 +49,7 @@ def _plan( 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", ) -> Any: @@ -58,7 +62,7 @@ def _plan( selected={o: sorted(r["namespace"] for r in rows if r["org"] == o) for o in orgs}, grant_subjects=subjects if isinstance(subjects, dict) else {"acme": subjects or set()}, links=links or {}, - revoked=set(), + revoked=revoked or set(), targets=targets or {"acme": target or EMPTY}, signs_in=signs_in or {}, ) @@ -278,11 +282,31 @@ def test_one_namespace_brings_the_accounts_its_grants_name() -> None: _account("acme", "bob", "b@x"), _account("acme", "carol", "c@x"), _ns("acme", "team", "alice"), - _ns("acme", "acl-mirror", "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": ["alice", "bob", "carol", "team"]} + assert select_namespaces(rows, grants, None) == { + "acme": ["acl-reviews", "alice", "bob", "carol", "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) def test_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> None: @@ -293,7 +317,7 @@ def test_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> None: {"org": "acme", "namespace": "vault", "pattern": "deploys", "pattern_type": "substring"}, {"org": "other", "namespace": "*", "pattern": "x", "pattern_type": "substring"}, ] - refusals = _refusals(patterns, d) - assert len(refusals) == 2 # its org's and the deployment's; not another namespace's - assert _refused(refusals, '"the tok-1234 key"') and _refused(refusals, '"a SECRET"') - assert not _refused(refusals, '"a secret on deploys, tok-12"') + 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 From 05b839320cf32e957f763fab3f504c9bb8b72b0e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:38:21 +0530 Subject: [PATCH 06/32] loom instance: pass the unit gates the import's statements meet - The import's namespace writer is a known one: it writes the source's full row, classification and join policy included. - The export and the import are classified journal readers: the export sends nothing, and the import's reads decide writes that commit. - The column read names the configured database, not `loom` by value. - No SELECT alias shadows a column its statement filters on. - The write batch says why it is not a setting. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_export.py | 7 ++++--- server/cli/instance_import.py | 10 ++++++---- .../test_namespaces_writers_mirror_classification.py | 1 + tests/unit/test_pg_durable_reads.py | 4 ++++ 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index fde13c0571f..99ea5e2559f 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -65,14 +65,14 @@ async def refuse_unfinished_erasures(ch: Any, orgs: Sequence[str]) -> None: 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 status + 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['status']})" for r in 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)." @@ -237,7 +237,8 @@ async def _identity_sections( ch, "revoked", f"SELECT lower(replaceOne(jti, '{_SCIM}', '')) AS subject, reason " - "FROM loom.revoked_tokens FINAL WHERE subject IN {lowered:Array(String)} " + "FROM loom.revoked_tokens FINAL " + f"WHERE lower(replaceOne(jti, '{_SCIM}', '')) IN {{lowered:Array(String)}} " "AND issued_before IS NULL AND expires_at > now()", {**p, "lowered": sorted({s.lower() for s in p["subjects"]})}, ) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 7f7a809e7c0..4b7a5d78f6f 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -42,7 +42,7 @@ LANDED = "instance.import" MERGED = "instance.import.merge" # a merge lands in the target's own namespace DONE = "instance.import.done" -_BATCH = 500 +_BATCH = 500 # not a setting: rows per write call; each writer bounds its statements # Settings that name the source's own services or rows: cleared, the target's owners set # them again. _CLEARED: dict[str, Any] = { @@ -292,10 +292,12 @@ def refusals(patterns: Iterable[Mapping[str, Any]], d: NsDecision) -> list[Any]: 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 = 'loom' AND table = {t:String} " - "AND default_kind NOT IN ('MATERIALIZED', 'ALIAS')", - params={"t": table}, + "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 = [] diff --git a/tests/unit/test_namespaces_writers_mirror_classification.py b/tests/unit/test_namespaces_writers_mirror_classification.py index 548bfed05d5..8ddd3a409f6 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 2a7c7a6c705..3460934e97c 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 " From 14bdc82fa6b767a82fc38846f7a1ad1ce828d902 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:17:29 +0530 Subject: [PATCH 07/32] loom instance import: grants match the person, bundle accounts never share an email - A grant is left out when the person holds that role or higher under any spelling the directory ties to the subject, case folded, or was revoked there; a pending request is no grant, so the source's replaces it. It is written under the subject `grants.create` would write it under. - The plan refuses two accounts of the bundle that land with one email, which single sign-on refuses, and proposes `drop`. - The plan refuses a map entry that names nothing in the bundle, and a mapping onto a subject that holds grants on collections only. - A landed namespace row its owners deleted is no landing of this import. - Under the Postgres authority, a document head it holds counts as written. - The dry run reads every original back with its hash checked; an apply that finds one changed since stops and says to run it again. - An account single sign-on made on the source lands untagged, so the target never finishes its provisioning with an owner grant the source revoked. - The docs say the export writes no audit row per memory it reads, as a database dump does. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 4 +- docs/operations/consolidation.md | 66 ++++++++++------ server/cli/instance.py | 5 +- server/cli/instance_import.py | 76 ++++++++++++++----- server/cli/instance_plan.py | 59 +++++++++++--- .../test_instance_consolidation.py | 31 +++++++- tests/unit/test_instance_consolidation.py | 75 ++++++++++++++++++ 7 files changed, 256 insertions(+), 60 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 2299dadb8b5..a5c6fea4710 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -1266,7 +1266,9 @@ 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 + 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 ClickHouse with the deployment's + 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 diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 5899cecc08b..f0bc862668d 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -42,9 +42,11 @@ Memories reach vector search once the embedding worker's next full pass embeds t 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. The bundle holds password hashes: it is written - readable by its owner only, and is copied to the target whole, the way a database - dump is. + 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: @@ -103,38 +105,52 @@ subjects: # "/": rule - **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), and an email any target account signs in with; it proposes a new handle or the - target account. Mapping an account onto a target account gives that account the + it), 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, the + target account or `drop`. Mapping an account onto a target account gives that account the source account's content and grants: 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 the source revoked, by an operator or by SCIM, - lands with no password, email or links, and its grants stay behind: nobody signs in - to it, so the plan checks none of its emails. + 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: nobody signs in to it, so the + plan checks none of its emails. - **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves the address at sign-in on the target. 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, 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 target - subject. `sa:` subjects are dropped. Any other subject needs a mapping or `drop`. + `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. Any + other subject needs a mapping or `drop`. +- **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, under any spelling + the directory ties to the subject and in any case, already holds that role or higher + there, or a target admin revoked them there. 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, and plans the same -digest. 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`: 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 id the namespace has -held, deleted ones included, 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 its -subject holds at that role or higher, or that was revoked. These rows live as long as the -audit log keeps rows (`LOOM_RETENTION_AUDIT_LOG_DAYS`). +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. 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 id the namespace has held, deleted ones included, 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`). ## Related diff --git a/server/cli/instance.py b/server/cli/instance.py index 9875fccaf3f..3343a019ed1 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -159,7 +159,10 @@ async def _plan_and_apply(ch: Any) -> int: # The target orgs are declared, and a recording cell records them, only to write a # reviewed plan. await check_acceptance(orgs=target_orgs) - receipt = await apply(ch, bundle, p, rules, targets) + try: + receipt = await apply(ch, bundle, p, rules, 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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 4b7a5d78f6f..0b5d281fb1f 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -27,7 +27,7 @@ from datetime import UTC, datetime from typing import Any -from server.cli.instance_bundle import ORIGINALS, Bundle +from server.cli.instance_bundle import Bundle, BundleError from server.cli.instance_export import stream_rows from server.cli.instance_plan import ( MapFile, @@ -38,6 +38,7 @@ landed_row, plan, ) +from server.core.principals import USER LANDED = "instance.import" MERGED = "instance.import.merge" # a merge lands in the target's own namespace @@ -146,7 +147,7 @@ def add(org: Any, subject: Any) -> None: add(r["org"], r["owner_email"]) for m in bundle.records("memories"): # an end user's rows follow their decision if m.get("user_id") not in (None, "", "-"): - add(m["org"], f"user:{m['user_id']}") + add(m["org"], 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( @@ -237,10 +238,12 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr for doc in bundle.records("documents"): sha = doc.get("blob_path") if (doc["org"], doc["namespace"]) in landing and sha and not doc.get("blob_erased_at"): - if not (bundle.path / ORIGINALS / str(sha)).is_file(): + try: + bundle.original(str(sha)) + except BundleError as e: p.problems.append( - f"{doc['org']}/{doc['namespace']} document {doc['source_uri']!r}: the " - f"bundle has no original {sha}: copy the whole bundle" + f"{doc['org']}/{doc['namespace']} document {doc['source_uri']!r}: {e}: " + "copy the whole bundle" ) @@ -352,8 +355,8 @@ 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:") + 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) -> None: from server.observability import audit @@ -388,6 +391,7 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: 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 @@ -421,6 +425,9 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: 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) + # 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: @@ -501,21 +508,31 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> 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 subject already holds at - that role or higher, one a target admin revoked.""" + 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: under every spelling the directory ties to the subject, case folded; + 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 + from server.core.grant_sql import LIVE_GRANT from server.identity.store import grants as grants_repo from server.operations.base import grant_rank by_source = {(d.source_org, d.source): d for d in decisions} held = await run.ch.query_all( - "SELECT org, namespace, subject, role, revoked_at IS NOT NULL AS revoked " - "FROM loom.namespace_grants FINAL WHERE org IN {orgs:Array(String)}", + "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 decisions})}, ) - have = { - (r["org"], r["namespace"], r["subject"]): "" if r["revoked"] else str(r["role"]) - for r in held - } + 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, list[str]]] = {} rows = [] for g in run.bundle.records("grants"): d = by_source.get((g["org"], g["namespace"])) @@ -525,15 +542,23 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) if str(g["subject"]).lower() in run.revoked: run.count(d, "grants_of_revoked") continue - prior = have.get((d.target_org, d.target, subject)) - if prior == "" or (prior is not None and grant_rank(prior) >= grant_rank(g["role"])): + if (d.target_org, subject) not in spelled: + stored = await canonical_subject(d.target_org, subject) + every = [stored, *await spellings(d.target_org, subject)] + spelled[(d.target_org, subject)] = (stored, sorted({n.lower() for n in every})) + stored, folded = spelled[(d.target_org, subject)] + priors = [have.get((d.target_org, d.target, n)) for n in folded] + if "" in priors: + run.count(d, "grants_revoked_on_target") continue - have[(d.target_org, d.target, subject)] = str(g["role"]) + if any(p is not None and grant_rank(p) >= grant_rank(g["role"]) for p in priors): + continue + have[(d.target_org, d.target, stored.lower())] = str(g["role"]) rows.append( { "org": d.target_org, "namespace": d.target, - "subject": subject, + "subject": stored, "role": g["role"], "granted_at": run.now, "granted_by": run.actor, @@ -769,6 +794,15 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None run.count(d, "memories", sum(1 for w in out.written if w.version)) +async def _authority_document(org: str, namespace: str, uri: str) -> bool: + """Under the Postgres authority, whether the namespace holds or has held `uri`: a + head committed since its last publication to ClickHouse is there only.""" + from server.core import pg + from server.knowledge.store import pg_documents + + return pg.enabled() and bool(await pg_documents.heads(org, namespace, [uri])) + + async def _documents(run: _Run, decisions: list[NsDecision]) -> 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 @@ -786,7 +820,9 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: seen[(d.target_org, d.target)] = await _seen( run.ch, "source_uri", d.target_org, d.target ) - if doc["source_uri"] in seen[(d.target_org, d.target)]: + if doc["source_uri"] in seen[(d.target_org, d.target)] or await _authority_document( + d.target_org, d.target, doc["source_uri"] + ): run.count(d, "documents_present") continue original = None diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 7163e6c84c8..28cb68e0264 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -44,14 +44,14 @@ is_sso_namespace_name, validate_namespace_name, ) -from server.core.principals import AGENT, EVERYONE, GROUP, USER +from server.core.principals import AGENT, EVERYONE, GROUP, SERVICE_ACCOUNT, USER 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 = ("sa:",) +DROPPED_PREFIXES = (SERVICE_ACCOUNT,) class MapError(ValueError): @@ -228,17 +228,25 @@ def is_account(row: Mapping[str, Any]) -> bool: def landed_row(row: Mapping[str, Any], source_row: Mapping[str, Any]) -> bool: """Whether a target namespace row is the one an import wrote from `source_row`: it - keeps the source's `created_at`, which a name registered since cannot have.""" + keeps the source's `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 t = datetime.fromisoformat(v) if isinstance(v, str) else v return t.replace(tzinfo=UTC) if isinstance(t, datetime) and t.tzinfo is None else t - return row.get("created_at") is not None and at(row["created_at"]) == at( - source_row.get("created_at") + return ( + bool(row.get("active", True)) + and row.get("created_at") is not None + and at(row["created_at"]) == at(source_row.get("created_at")) ) +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) @@ -266,6 +274,9 @@ class _Org: 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 revoked: set[str] # the source subjects revoked outright, lower-cased @@ -322,10 +333,10 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, "", "skip")) return if rule is not None and rule.action == "map": - if rule.target not in o.target.subjects: + if _collection_only(rule.target) 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" + f"{o.target_org} on the target a namespace can name" ) return o.subject(SubjectDecision(o.org, name, "map", rule.target)) @@ -351,6 +362,15 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: account if org == o.target_org else "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 " @@ -377,6 +397,7 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: 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( @@ -458,6 +479,8 @@ def _plan_subject(o: _Org, subject: str) -> None: user = subject.startswith(USER) if user != rule.target.startswith(USER): o.problem(f"subjects.{key}: 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" @@ -465,7 +488,7 @@ def _plan_subject(o: _Org, subject: str) -> None: else: o.subject(SubjectDecision(o.org, subject, "map", rule.target)) return - if subject.startswith((GROUP, AGENT)) or subject == EVERYONE: + 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", @@ -516,7 +539,7 @@ def _check_users(o: _Org) -> None: 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:"): + 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}") @@ -558,6 +581,7 @@ def plan( 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): @@ -582,6 +606,7 @@ def plan( 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, ) @@ -602,6 +627,22 @@ def plan( f"subjects.{org}/{s.subject}: the source revoked {s.subject!r}; mapping it " f"gives its content to {s.target!r}, whose access stays: claim or 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} + known = { + "orgs": set(selected), + "namespaces": names, + "subjects": names | {f"{org}/{s}" for org, subs in grant_subjects.items() 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 diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index e42c23aa740..d0f88a6fbfd 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -3,7 +3,8 @@ 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, -and leaves the target's own rows alone. An account the source revoked lands with no way to +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 @@ -136,6 +137,8 @@ async def _seed_source(ch: Any, src: _Api) -> None: blob_content_type="text/markdown", ) src.op("namespace.register", namespace="notes", owner_email="alice") + for subject in ("erin@src.test", "dave@src.test"): + src.op("grants.create", namespace="notes", subject=subject, role="viewer") src.op( "memory.set", namespace="notes", @@ -202,6 +205,20 @@ async def test_an_org_moves_into_a_live_one_under_the_map( dst.op("namespace.register", namespace="team", owner_email="alice") dst.op("grants.create", namespace="team", subject="bob", role="viewer") dst.set("team", KEYS[0], "the target's own rule") + # 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)) @@ -224,7 +241,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( f"{src_org}/test-suite": "drop", }, } - proposals["namespaces"][f"{src_org}/notes"] = {"merge": "team"} + proposals["namespaces"][f"{src_org}/notes"] = {"merge": "team", "grants": True} mapping.write_text(yaml.safe_dump({"orgs": {src_org: dst_org}, **proposals})) dry = _cli("import", "--bundle", str(bundle), "--map", str(mapping)) assert dry.returncode == 0, dry.stdout + dry.stderr @@ -282,14 +299,20 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ] grants = await ch.query_all( "SELECT namespace, subject, role FROM loom.namespace_grants FINAL " - "WHERE org = {org:String} AND revoked_at IS NULL ORDER BY namespace, subject" + SEQ, + "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"), ] - assert {r["subject"] for r in grants if r["namespace"] == "team"} == {"bob", "test-suite"} + # The merge carries erin's grant past her request; dave's revocation stands. + assert {r["subject"]: r["role"] for r in grants if r["namespace"] == "team"} == { + "bob": "viewer", + "erin@src.test": "viewer", + "test-suite": "admin", + } 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") diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index fecf088c981..ef726c70461 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -248,6 +248,11 @@ def test_a_resumed_run_plans_the_same_digest() -> None: ) p = _plan(rows, subjects=subjects, target=taken, signs_in={"alice@x": ["acme/alice"]}) assert p.proposals == {"namespaces": {"acme/team": {"rename": "team-legacy"}}} + deleted = TargetOrg( + {**names, "team": {**LANDED, "active": False}}, landed.subjects, landed=marks + ) + p = _plan(rows, subjects=subjects, target=deleted, signs_in={"alice@x": ["acme/alice"]}) + assert p.proposals == {"namespaces": {"acme/team": {"rename": "team-legacy"}}} # A finished landing is the target's now, whatever its owners did to the row. done = TargetOrg(taken.namespaces, landed.subjects, landed=marks, done=marks) p = _plan(rows, subjects=subjects, target=done, signs_in={"alice@x": ["acme/alice"]}) @@ -321,3 +326,73 @@ def test_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> None: 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 = {"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"})) + typo = _plan(rows, target=target, rules={"namespaces": {"acme/teem": "skip"}}) + assert typo.problems == ["namespaces.acme/teem: names nothing in this bundle"] + for rules, named in ( + ({"subjects": {"acme/alice": "group:eng"}}, "group:eng"), # an account onto one + ({"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 = [ + { + "memory_id": f"m{i}", + "agent": "a", + "user_id": "-", + "session_id": "-", + "memory_key": f"k{i}", + } + for i in range(3) + ] + + async def held_in(org: str, ns: str, *, after: Any = None, limit: int = 5000) -> Any: + key = lambda h: (h["agent"], h["user_id"], h["session_id"], h["memory_key"]) # noqa: E731 + return [h for h in heads if after is None or key(h) > after][:2] # pages of two + + async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: + if " AS v " in sql: + yield {"v": "m-ch"} + else: + yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} + + async def document_heads(org: str, ns: str, uris: list[str]) -> dict[str, Any]: + return {u: object() for u in uris if u == "held.md"} + + monkeypatch.setattr(pg, "enabled", lambda: True) + monkeypatch.setattr(pg_memory, "held_in", held_in) + monkeypatch.setattr(pg_documents, "heads", document_heads) + monkeypatch.setattr(imp, "stream_rows", stream_rows) + assert await imp._seen(None, "memory_id", "o", "n") == {"m-ch", "m0", "m1", "m2"} + assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} + assert await imp._authority_document("o", "n", "held.md") + assert not await imp._authority_document("o", "n", "new.md") From a20d3e7f877333dfa69a50d819caffa2aa95e714 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:02:45 +0530 Subject: [PATCH 08/32] loom instance: a revoked account's emails and a source's synced copies stay behind - A grant to an email a revoked source account names is dropped: on the source single sign-on admits no one by that address, and the account lands with no email, so on the target it would. Mapping one is refused. - The export leaves a knowledge source's synced documents behind and counts them (`documents_of_sources`): a source registered again writes and keeps only its own copies. - A carried grant is left out for a role the person holds under a verified spelling only, as the gate admits them; any spelling still reaches a revocation. - A landed name counts toward an org the import alone serves only while its row is the one the import wrote, or its content is finished. - A subjects entry naming a namespace that is no account refuses the plan. - The dry run's hint gives the whole apply line, `--expect-plan` included. - `apply` takes `sso_same_issuer` from the plan the digest binds. - One Postgres read of document heads per namespace, not per document. - The docs say an erasure during an unfinished import is run again after it, as after a restore, and correct the email-grant wording. - Tests: per-type settings, policies and guide revisions compared field for field, a single sign-on account landing untagged with its link, the dry run refusing a changed original, apply's stop on one, a revoked account's email grant, a synced document, and a grant past an unverified spelling. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 2 +- docs/operations/consolidation.md | 26 ++-- server/cli/instance.py | 10 +- server/cli/instance_export.py | 17 ++- server/cli/instance_import.py | 53 ++++--- server/cli/instance_plan.py | 42 ++++-- .../test_instance_consolidation.py | 136 ++++++++++++++++-- tests/unit/snapshots/cli_tree.json | 2 +- tests/unit/test_instance_consolidation.py | 74 +++++++++- 9 files changed, 292 insertions(+), 70 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index a5c6fea4710..f09513ed8fb 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -1267,7 +1267,7 @@ no search leg returns it. The other reads that could serve its value follow thre 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. `loom instance export` is an - operator's dump, like `dev/backup_loom.py`: it reads ClickHouse with the deployment's + 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 diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index f0bc862668d..8f90ebec856 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -15,7 +15,7 @@ run, with their settings. To move a whole deployment onto new hosts, see | 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 | | Memories: every live head, with its `created_at`, validity and attestation | 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: the manifest lists them to register again | +| Documents with their originals, embedded again by the target's embedder | Knowledge sources with a remote and the documents they synced: the manifest lists them 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: @@ -66,7 +66,8 @@ Memories reach vector search once the embedding worker's next full pass embeds t ``` 6. Hand out the receipt's `set_up_again` list, and register the repositories and - knowledge sources the manifest's `left_behind` names. + knowledge sources the manifest's `left_behind` names. A source registered again + writes its documents again, and keeps them up to date. ## The map @@ -114,10 +115,11 @@ subjects: # "/": rule 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: nobody signs in to it, so the - plan checks none of its emails. -- **Subjects.** A grant to an email stays a grant to that email: it admits whoever proves - the address at sign-in on the target. A `user:` subject is kept in a target org only + 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. +- **Subjects.** 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, or `drop`. Its decision moves that end user's memories too; two end users of one source @@ -126,10 +128,10 @@ subjects: # "/": rule to a person's subject, and refuses a mapping onto one. `sa:` subjects are dropped. Any other subject needs a mapping or `drop`. - **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, under any spelling - the directory ties to the subject and in any case, already holds that role or higher - there, or a target admin revoked them there. A pending request is no grant: the - source's grant replaces it. + 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 @@ -152,6 +154,10 @@ 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 diff --git a/server/cli/instance.py b/server/cli/instance.py index 3343a019ed1..25c9560f6b1 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -5,6 +5,7 @@ import argparse import json +import sys from pathlib import Path from typing import Any @@ -51,7 +52,7 @@ def register_instance_cli(sub: Any) -> None: 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) + i.set_defaults(func=_cmd_import, apply_gated=False) # its own hint names the digest def _cmd_export(args: argparse.Namespace) -> int: @@ -152,6 +153,11 @@ async def _plan_and_apply(ch: Any) -> int: 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") @@ -160,7 +166,7 @@ async def _plan_and_apply(ch: Any) -> int: # reviewed plan. await check_acceptance(orgs=target_orgs) try: - receipt = await apply(ch, bundle, p, rules, targets) + 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)) diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 99ea5e2559f..7d13caadb08 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -20,6 +20,7 @@ from typing import Any from server.cli.instance_bundle import BundleWriter +from server.knowledge.domain.sources import SYNC_WORKER_ACTOR # SCIM's revocation key prefix (`server.auth.revocation.SCIM_PREFIX`) as a SQL literal. _SCIM = "\\0scim:" @@ -306,12 +307,15 @@ async def _documents( 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. + # caller's token only, so the target could not erase it as theirs. So does + # a knowledge source's copy: the source, registered again, writes its own, + # and keeps only those up to date. 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 = '-'", - {"org": org, "ns": ns}, + "AND namespace = {ns:String} AND superseded_at IS NULL AND user_id = '-' " + "AND actor != {sync:String}", + {"org": org, "ns": ns, "sync": SYNC_WORKER_ACTOR}, ): if d.get("blob_path") and not d.get("blob_erased_at"): originals.append((org, ns, str(d["blob_path"]), str(d["source_uri"]))) @@ -334,7 +338,7 @@ async def _left_behind( """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} + p = {"orgs": orgs, "keys": keys, "sync": SYNC_WORKER_ACTOR} scope = "org IN {orgs:Array(String)}" + ( " AND concat(org, '/', namespace) IN {keys:Array(String)}" if only is not None else "" ) @@ -360,7 +364,10 @@ async def _left_behind( "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", + 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 actor = {sync:String} GROUP BY org", params=p, ) return {"code_repos": repos, "knowledge_sources": sources, "rows": rows} diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 0b5d281fb1f..ae896585cbc 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -510,10 +510,11 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) 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: under every spelling the directory ties to the subject, case folded; - a pending request is no grant, so the source's replaces it. A grant is written under + 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 + 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 @@ -532,7 +533,7 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) 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, list[str]]] = {} + spelled: dict[tuple[str, str], tuple[str, set[str], set[str]]] = {} rows = [] for g in run.bundle.records("grants"): d = by_source.get((g["org"], g["namespace"])) @@ -544,14 +545,19 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) continue if (d.target_org, subject) not in spelled: stored = await canonical_subject(d.target_org, subject) - every = [stored, *await spellings(d.target_org, subject)] - spelled[(d.target_org, subject)] = (stored, sorted({n.lower() for n in every})) - stored, folded = spelled[(d.target_org, subject)] - priors = [have.get((d.target_org, d.target, n)) for n in folded] - if "" in priors: + 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 - if any(p is not None and grant_rank(p) >= grant_rank(g["role"]) for p in priors): + 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( @@ -794,13 +800,13 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None run.count(d, "memories", sum(1 for w in out.written if w.version)) -async def _authority_document(org: str, namespace: str, uri: str) -> bool: - """Under the Postgres authority, whether the namespace holds or has held `uri`: a +async def _authority_documents(org: str, namespace: str, uris: list[str]) -> set[str]: + """Under the Postgres authority, which of `uris` the namespace holds or has held: a head committed since its last publication to ClickHouse is there only.""" from server.core import pg from server.knowledge.store import pg_documents - return pg.enabled() and bool(await pg_documents.heads(org, namespace, [uri])) + return set(await pg_documents.heads(org, namespace, uris)) if pg.enabled() else set() async def _documents(run: _Run, decisions: list[NsDecision]) -> None: @@ -811,18 +817,19 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: from server.knowledge.app.writes import handle_knowledge_upsert by_source = {(d.source_org, d.source): d for d in decisions} - seen: dict[tuple[str, str], set[str]] = {} + uris: dict[tuple[str, str], list[str]] = {} + for doc in run.bundle.records("documents"): + if (d := by_source.get((doc["org"], doc["namespace"]))) is not None: + uris.setdefault((d.target_org, d.target), []).append(str(doc["source_uri"])) + seen = { + k: await _seen(run.ch, "source_uri", *k) | await _authority_documents(*k, v) + for k, v in uris.items() + } for doc in run.bundle.records("documents"): d = by_source.get((doc["org"], doc["namespace"])) if d is None: continue - if (d.target_org, d.target) not in seen: - seen[(d.target_org, d.target)] = await _seen( - run.ch, "source_uri", d.target_org, d.target - ) - if doc["source_uri"] in seen[(d.target_org, d.target)] or await _authority_document( - d.target_org, d.target, doc["source_uri"] - ): + if doc["source_uri"] in seen[(d.target_org, d.target)]: run.count(d, "documents_present") continue original = None @@ -851,7 +858,7 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: async def apply( - ch: Any, bundle: Bundle, p: Plan, rules: MapFile, targets: Mapping[str, TargetOrg] + 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) @@ -873,7 +880,7 @@ async def apply( await _blacklist(run, d, patterns) else: run.refusals[(d.source_org, d.source)] = refusals(patterns, d) - await _grants(run, todo, rules.sso_same_issuer) + await _grants(run, todo, p.sso_same_issuer) await _memories(run, todo) await _documents(run, todo) content = carried(bundle) diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 28cb68e0264..7d898d5411a 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -278,7 +278,9 @@ class _Org: # 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 - revoked: set[str] # the source subjects revoked outright, lower-cased + # 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}") @@ -512,6 +514,11 @@ def _plan_subject(o: _Org, subject: str) -> None: o.subject(SubjectDecision(o.org, subject, "keep", subject)) 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")) @@ -589,11 +596,16 @@ def plan( continue p.orgs[org] = target_org target = targets[target_org] - ours = { - name - for name, key in target.landed - if key.startswith(f"{source}/") and key.split("/")[1] in landing[target_org] - } + # The names this import landed there and still holds: finished, or the row the + # one it wrote. A name someone registered since is someone else's. + ours = set() + for name, key in target.landed: + _, src_org, src = key.split("/", 2) + row, was = target.namespaces.get(name), by_org.get(src_org, {}).get(src) + if key.startswith(f"{source}/") and src_org in landing[target_org]: + if (name, key) in target.done or (row and was and landed_row(row, was)): + ours.add(name) + here = by_org.get(org, {}) o = _Org( source=source, org=org, @@ -602,13 +614,20 @@ def plan( target=target, signs_in=signs_in, links=links.get(org, {}), - rows=by_org.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=revoked + | { + e.strip().lower() + for name, row in here.items() + if name.lower() in revoked + for e in (str(row.get("contact_email") or ""), *links.get(org, {}).get(name, [])) + if e.strip() + }, ) rows = o.rows accounts = {n for n in o.selected if is_account(rows[n])} @@ -622,17 +641,20 @@ def plan( _plan_subject(o, subject) _check_users(o) for s in p.subjects: - if s.source_org == org and s.subject.lower() in revoked and s.action == "map": + if s.source_org == org and s.subject.lower() in o.revoked and s.action == "map": 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: claim or 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} + accounts = { + 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": names | {f"{org}/{s}" for org, subs in grant_subjects.items() for s in subs}, + "subjects": accounts | {f"{org}/{s}" for org, subs in grant_subjects.items() for s in subs}, } for section, keys in ( ("orgs", rules.orgs), diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index d0f88a6fbfd..1af0657cb1d 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -24,9 +24,11 @@ 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 Bundle +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] @@ -45,6 +47,17 @@ # 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) @@ -55,7 +68,10 @@ async def ch() -> Any: await client.disconnect() -async def _account(ch: Any, org: str, name: str, email: str, active: bool = True) -> None: +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", @@ -65,9 +81,9 @@ async def _account(ch: Any, org: str, name: str, email: str, active: bool = True "namespace": name, "owner_email": name, "contact_email": email, - "password_hash": HASH, + "password_hash": "" if sso else HASH, "description": "", - "tags": [], + "tags": [JIT_TAG] if sso else [], "active": active, "visibility": "private", "created_at": now, @@ -77,6 +93,14 @@ async def _account(ch: Any, org: str, name: str, email: str, active: bool = True ) +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 @@ -119,8 +143,25 @@ async def _seed_source(ch: Any, src: _Api) -> None: "loom.revoked_tokens", [{"jti": "\x00scim:" + CAROL.upper(), "expires_at": expires, "reason": "scim"}], ) - src.op("namespace.register", namespace="team", owner_email="alice", visibility="public") - for subject, role in (("alice", "writer"), ("bob", "viewer"), (CAROL, "viewer")): + 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") @@ -136,9 +177,17 @@ async def _seed_source(ch: Any, src: _Api) -> None: original_filename="runbook.md", blob_content_type="text/markdown", ) + # A knowledge source's copy of a file, which the source writes again once registered. + await ch.execute( + "INSERT INTO loom.documents SELECT * REPLACE ('synced.md' AS source_uri, " + "{sync:String} AS actor) 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}, + ) src.op("namespace.register", namespace="notes", owner_email="alice") - for subject in ("erin@src.test", "dave@src.test"): - src.op("grants.create", namespace="notes", subject=subject, role="viewer") + 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", @@ -190,6 +239,9 @@ async def rows(sql: str) -> list[tuple[Any, ...]]: "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 + ], } @@ -204,6 +256,9 @@ async def test_an_org_moves_into_a_live_one_under_the_map( await _account(ch, dst_org, "alice", "alice@dst.test") dst.op("namespace.register", namespace="team", owner_email="alice") 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") # On its team erin asked to join, which grants nothing, and a revocation spelled # otherwise is dave's. @@ -237,12 +292,21 @@ async def test_an_org_moves_into_a_live_one_under_the_map( "subjects": { f"{src_org}/alice": {"claim": "alice-legacy"}, # the target's alice f"{src_org}/bob": {"claim": "bob-legacy"}, # a grant there names bob - # The minted token's subject: no account, email or principal the target knows. + # 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", }, } proposals["namespaces"][f"{src_org}/notes"] = {"merge": "team", "grants": True} + proposals["subjects"][f"{src_org}/frank"] = "frank" 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) @@ -293,6 +357,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("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"), @@ -307,12 +372,29 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("team-legacy", "alice-legacy", "writer"), ("team-legacy", "bob-legacy", "viewer"), ] - # The merge carries erin's grant past her request; dave's revocation stands. + # 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")) + ] + assert both[0] and both[0] == both[1], table + synced = dst.op("knowledge.get", namespace="team-legacy", source_uri="synced.md") + assert not synced["found"] + left = Bundle.open(bundle).manifest["left_behind"]["rows"] + assert [(r["kind"], r["n"]) for r in left] == [("documents_of_sources", 1)] 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") @@ -357,11 +439,16 @@ async def test_a_namespace_bundle_leaves_its_accounts_content_to_a_later_one( ) -> 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.""" + 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") src.set("team", "deploys", "the team's deploy rule") @@ -380,13 +467,14 @@ async def test_a_namespace_bundle_leaves_its_accounts_content_to_a_later_one( 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" - mapping.write_text( - yaml.safe_dump({"orgs": {src_org: dst_org}, "subjects": {f"{src_org}/test-suite": "drop"}}) - ) + 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 @@ -429,6 +517,26 @@ def imported(bundle: Path) -> str: assert rows == [ ("instance.import", "dana"), ("instance.import", "team"), + ("instance.import", fay), ("instance.import.done", "dana"), ("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_tree.json b/tests/unit/snapshots/cli_tree.json index 3ae7e95160e..afa5172d725 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -7589,7 +7589,7 @@ "allow_abbrev": true, "defaults": { "dry_run": true, - "apply_gated": true, + "apply_gated": false, "func": "server.cli.instance:_cmd_import" }, "groups": [ diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index ef726c70461..624afb56bbb 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -193,6 +193,19 @@ def test_a_namespace_anyone_could_join_asks_for_approval_in_a_shared_org() -> No ) 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=marks), + rules=rules, + ) + assert {d.source: d.approval for d in p.namespaces}["team"] is opens def test_the_digest_names_whether_sign_on_links_land() -> None: @@ -246,13 +259,18 @@ def test_a_resumed_run_plans_the_same_digest() -> None: landed.subjects, landed=marks, ) + # 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 == {"namespaces": {"acme/team": {"rename": "team-legacy"}}} + assert p.proposals == renamed deleted = TargetOrg( {**names, "team": {**LANDED, "active": False}}, landed.subjects, landed=marks ) p = _plan(rows, subjects=subjects, target=deleted, signs_in={"alice@x": ["acme/alice"]}) - assert p.proposals == {"namespaces": {"acme/team": {"rename": "team-legacy"}}} + assert p.proposals == renamed # A finished landing is the target's now, whatever its owners did to the row. done = TargetOrg(taken.namespaces, landed.subjects, landed=marks, done=marks) p = _plan(rows, subjects=subjects, target=done, signs_in={"alice@x": ["acme/alice"]}) @@ -312,6 +330,21 @@ def test_an_account_the_source_revoked_lands_with_no_email_to_check() -> None: 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_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> None: @@ -344,6 +377,9 @@ def test_the_map_names_only_what_the_bundle_holds_and_whom_a_namespace_can_name( target = TargetOrg({}, frozenset({"group:eng", "everyone", "carla"})) 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/bob@x": "everyone"}}, "everyone"), @@ -394,5 +430,35 @@ async def document_heads(org: str, ns: str, uris: list[str]) -> dict[str, Any]: monkeypatch.setattr(imp, "stream_rows", stream_rows) assert await imp._seen(None, "memory_id", "o", "n") == {"m-ch", "m0", "m1", "m2"} assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} - assert await imp._authority_document("o", "n", "held.md") - assert not await imp._authority_document("o", "n", "new.md") + assert await imp._authority_documents("o", "n", ["held.md", "new.md"]) == {"held.md"} + + +def test_an_original_changed_since_the_dry_run_stops_the_apply( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """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") + + 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", nothing) + 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) + 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) From 449033197b537c2d0586a75e1bc2ed62e3f9013e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:33:52 +0530 Subject: [PATCH 09/32] loom instance: a landing records its created_at, recording transcripts move - A `--namespace` export brings the accounts a grant names by email too, by contact or single sign-on link: on the source single sign-on admits no one by an address a revoked or password account names, and the plan needs the account to place such a grant. - A recording source's transcripts move with the bundle: a source registered again lists its last weeks only, and a transcript never changes once written. Every other synced copy stays behind as before. - The `instance.import` audit row records the source row's `created_at`, and `TargetOrg.holds` decides from it whether a landing is still the import's, whichever bundle the plan reads. A row-only landing an earlier bundle made no longer makes the org one that serves others. - A resumed import reads which document addresses the Postgres authority holds without their rows (`pg_documents.held_uris`). - Tests: the selection by email, a landing from another bundle, an original changed after the dry run stopping `_documents` itself, the dry run's hint, a recording transcript landing, and `instance import` among the commands whose default is a dry run. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 22 ++--- server/cli/instance_export.py | 48 +++++++---- server/cli/instance_import.py | 24 ++++-- server/cli/instance_plan.py | 81 +++++++++++-------- server/knowledge/store/pg_documents.py | 16 ++++ .../test_instance_consolidation.py | 27 +++++-- tests/unit/test_cli_apply_default.py | 1 + tests/unit/test_instance_consolidation.py | 65 ++++++++++++--- 8 files changed, 198 insertions(+), 86 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 8f90ebec856..f945cdf2631 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -8,15 +8,15 @@ run, with their settings. To move a whole deployment onto new hosts, see ## 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 | -| Memories: every live head, with its `created_at`, validity and attestation | 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 they synced: the manifest lists them to register again, and counts the documents | -| | Embeddings, caches, traces, rollups, the audit log and agent events: the target builds what it needs again | +| 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 | +| Memories: every live head, with its `created_at`, validity and attestation | 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 they synced but 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 @@ -67,7 +67,9 @@ Memories reach vector search once the embedding worker's next full pass embeds t 6. Hand out the receipt's `set_up_again` list, 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. + writes its documents again, and keeps them up to date. 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 diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 7d13caadb08..274c4611ce7 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -24,6 +24,10 @@ # SCIM's revocation key prefix (`server.auth.revocation.SCIM_PREFIX`) as a SQL literal. _SCIM = "\\0scim:" +# A knowledge source's copy that the source, registered again, writes again: it keeps only +# its own copies up to date (`source_sync.ours`). A recording source lists its last weeks +# only and its transcripts are settled when written, so its copies move. +_RESYNCED = "actor = {sync:String} AND JSONExtractString(metadata, 'source_kind') != 'recording'" _STREAM_SETTINGS = { "max_execution_time": 0, # UTC with its zone: a plain DateTime would read in the source server's time zone. @@ -118,11 +122,16 @@ def exported_namespace(row: dict[str, Any]) -> bool: def select_namespaces( - rows: list[dict[str, Any]], grants: list[dict[str, Any]], wanted: list[str] | None + 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, so the - plan can place every subject they name.""" + `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]] = {} @@ -133,17 +142,20 @@ def select_namespaces( 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 "")) + 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"])) + 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: - if ( - is_account(r) - and exported_namespace(r) - and r["namespace"] in named.get(str(r["org"]), ()) - ): - out.setdefault(str(r["org"]), set()).add(str(r["namespace"])) + 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()} @@ -308,13 +320,12 @@ async def _documents( 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 knowledge source's copy: the source, registered again, writes its own, - # and keeps only those up to date. + # a copy a knowledge source writes again once registered. 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 = '-' " - "AND actor != {sync:String}", + f"AND NOT ({_RESYNCED})", {"org": org, "ns": ns, "sync": SYNC_WORKER_ACTOR}, ): if d.get("blob_path") and not d.get("blob_erased_at"): @@ -366,8 +377,7 @@ async def _left_behind( "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 actor = {sync:String} GROUP BY org", + f"WHERE {scope} AND superseded_at IS NULL AND user_id = '-' AND {_RESYNCED} GROUP BY org", params=p, ) return {"code_repos": repos, "knowledge_sources": sources, "rows": rows} @@ -393,7 +403,11 @@ async def export( p, ) ] - selected = select_namespaces(rows, grants, namespaces) + 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] diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index ae896585cbc..176577e8681 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -86,7 +86,8 @@ async def load_target( ) landings = await ch.query_all( "SELECT DISTINCT event_type, org, JSONExtractString(subject, 'name') AS name, " - "JSONExtractString(subject, 'source') AS source FROM loom.audit_log " + "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, ) @@ -112,7 +113,11 @@ def pairs(event: str, org: str = org) -> frozenset[tuple[str, str]]: | {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=pairs(LANDED), + 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), ) @@ -358,7 +363,9 @@ def user_id(self, org: str, u: str) -> str | None: 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) -> None: + async def audit( + self, event: str, org: str, namespace: str, name: str, source: str, **more: str + ) -> None: from server.observability import audit await audit.emit_strict( @@ -366,7 +373,7 @@ async def audit(self, event: str, org: str, namespace: str, name: str, source: s org=org, namespace=namespace, actor=self.actor, - subject={"name": name, "source": source, **self.digests}, + subject={"name": name, "source": source, **more, **self.digests}, ) @@ -408,7 +415,7 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: 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. - if not landed or not landed_row(existing, row): + if not landed or not landed_row(existing, row["created_at"]): raise in_use return if await directory().in_use(d.target_org, d.target, ch=run.ch): @@ -421,7 +428,10 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: f"{d.target_org}/{d.target} holds access on the target: plan again" ) from None if not landed: - await run.audit(LANDED, d.target_org, d.target, d.target, key) + # The row's created_at tells a later plan this landing's row from one a name + # registered since has, whichever bundle it reads. + created = str(row["created_at"]) + await run.audit(LANDED, d.target_org, d.target, d.target, key, created_at=created) 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) @@ -806,7 +816,7 @@ async def _authority_documents(org: str, namespace: str, uris: list[str]) -> set from server.core import pg from server.knowledge.store import pg_documents - return set(await pg_documents.heads(org, namespace, uris)) if pg.enabled() else set() + return await pg_documents.held_uris(org, namespace, uris) if pg.enabled() else set() async def _documents(run: _Run, decisions: list[NsDecision]) -> None: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 7d898d5411a..d3d06aa0512 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -153,12 +153,21 @@ class TargetOrg: 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: a - # run that stopped part way resumes, never taken for a collision. - landed: frozenset[tuple[str, str]] = frozenset() + # (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 + 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.""" + row = self.namespaces.get(name) + if (name, key) in self.done: + return True + return row is not None and landed_row(row, self.landed.get((name, key))) + @dataclass(frozen=True) class NsDecision: @@ -226,22 +235,38 @@ def is_account(row: Mapping[str, Any]) -> bool: ) -def landed_row(row: Mapping[str, Any], source_row: Mapping[str, Any]) -> bool: - """Whether a target namespace row is the one an import wrote from `source_row`: it - keeps the source's `created_at`, which a name registered since cannot have, and its - owners have not deleted it.""" +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 t = datetime.fromisoformat(v) if isinstance(v, str) else v return t.replace(tzinfo=UTC) if isinstance(t, datetime) and t.tzinfo is None else t return ( - bool(row.get("active", True)) + bool(created_at) + and bool(row.get("active", True)) and row.get("created_at") is not None - and at(row["created_at"]) == at(source_row.get("created_at")) + and at(row["created_at"]) == at(created_at) ) +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 @@ -293,11 +318,8 @@ def subject(self, d: SubjectDecision) -> None: 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.""" - row = self.target.namespaces.get(target) - key = (target, f"{self.source}/{self.org}/{source}") - if row is None or key in self.target.done: - return False - return key not in self.target.landed or not landed_row(row, self.rows[source]) + 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 @@ -596,15 +618,15 @@ def plan( continue p.orgs[org] = target_org target = targets[target_org] - # The names this import landed there and still holds: finished, or the row the - # one it wrote. A name someone registered since is someone else's. - ours = set() - for name, key in target.landed: - _, src_org, src = key.split("/", 2) - row, was = target.namespaces.get(name), by_org.get(src_org, {}).get(src) - if key.startswith(f"{source}/") and src_org in landing[target_org]: - if (name, key) in target.done or (row and was and landed_row(row, was)): - ours.add(name) + # 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, @@ -620,14 +642,7 @@ def plan( taken=taken.setdefault(target_org, {}), emails=emails, shared=len(landing[target_org]) > 1 or bool(set(target.namespaces) - ours), - revoked=revoked - | { - e.strip().lower() - for name, row in here.items() - if name.lower() in revoked - for e in (str(row.get("contact_email") or ""), *links.get(org, {}).get(name, [])) - if e.strip() - }, + revoked=revoked | _revoked_emails(here, links.get(org, {}), revoked), ) rows = o.rows accounts = {n for n in o.selected if is_account(rows[n])} @@ -648,13 +663,13 @@ def plan( ) # 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} - accounts = { + 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": accounts | {f"{org}/{s}" for org, subs in grant_subjects.items() for s in subs}, + "subjects": handles | {f"{org}/{s}" for org, subs in grant_subjects.items() for s in subs}, } for section, keys in ( ("orgs", rules.orgs), diff --git a/server/knowledge/store/pg_documents.py b/server/knowledge/store/pg_documents.py index 4d878b860f7..50173acdcfe 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/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 1af0657cb1d..6e0d3c6a243 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -11,6 +11,7 @@ import base64 import hashlib +import json import os import re import secrets @@ -177,13 +178,21 @@ async def _seed_source(ch: Any, src: _Api) -> None: original_filename="runbook.md", blob_content_type="text/markdown", ) - # A knowledge source's copy of a file, which the source writes again once registered. - await ch.execute( - "INSERT INTO loom.documents SELECT * REPLACE ('synced.md' AS source_uri, " - "{sync:String} AS actor) 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}, - ) + # Knowledge sources' copies: a file's, which its source writes again once registered, + # and a recording's transcript, which a source registered again never lists. + for uri, kind in (("synced.md", "gdrive"), ("meeting.md", "recording")): + await ch.execute( + "INSERT INTO loom.documents SELECT * REPLACE ({uri:String} AS source_uri, " + "{sync:String} AS actor, {meta:String} AS metadata) 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}), + }, + ) 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) @@ -311,6 +320,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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 @@ -392,7 +402,8 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ] assert both[0] and both[0] == both[1], table synced = dst.op("knowledge.get", namespace="team-legacy", source_uri="synced.md") - assert not synced["found"] + meeting = dst.op("knowledge.get", namespace="team-legacy", source_uri="meeting.md") + assert not synced["found"] and meeting["found"] and meeting["content"] == doc["content"] left = Bundle.open(bundle).manifest["left_behind"]["rows"] assert [(r["kind"], r["n"]) for r in left] == [("documents_of_sources", 1)] assert await resolve_identity_for_email(f"{CAROL}@src.test") is None diff --git a/tests/unit/test_cli_apply_default.py b/tests/unit/test_cli_apply_default.py index ebb268a1743..b5953792c59 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 index 624afb56bbb..88f3c35f721 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -12,7 +12,7 @@ import pytest -from server.cli.instance_bundle import Bundle, BundleError, BundleWriter +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 @@ -118,8 +118,8 @@ def test_same_handle_two_people_lands_under_the_map_handle_only() -> None: landed = TargetOrg( {**target.namespaces, "alice-legacy": LANDED, "team": LANDED}, target.subjects | {"alice-legacy"}, - landed=frozenset( - {("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")} + landed=dict.fromkeys( + [("alice-legacy", f"{SOURCE}/acme/alice"), ("team", f"{SOURCE}/acme/team")], AT ), ) again = _plan( @@ -202,10 +202,16 @@ def test_a_namespace_anyone_could_join_asks_for_approval_in_a_shared_org() -> No p = _plan( rows, subjects={"x"}, - target=TargetOrg({"notes": row}, frozenset(), landed=marks), + 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: @@ -248,7 +254,7 @@ def test_a_resumed_run_plans_the_same_digest() -> None: 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=marks) + 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)) @@ -257,7 +263,7 @@ def test_a_resumed_run_plans_the_same_digest() -> None: taken = TargetOrg( {**names, "team": {"kind": "memory", "created_at": datetime(2026, 1, 1)}}, landed.subjects, - landed=marks, + landed=dict.fromkeys(marks, AT), ) # Its row is no longer the import's, so the org serves others: its end users are asked. renamed = { @@ -267,12 +273,14 @@ def test_a_resumed_run_plans_the_same_digest() -> None: 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=marks + {**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 # A finished landing is the target's now, whatever its owners did to the row. - done = TargetOrg(taken.namespaces, landed.subjects, landed=marks, done=marks) + 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 @@ -314,6 +322,14 @@ def test_one_namespace_brings_the_accounts_its_grants_name() -> None: 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: @@ -421,18 +437,45 @@ async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: else: yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} - async def document_heads(org: str, ns: str, uris: list[str]) -> dict[str, Any]: - return {u: object() for u in uris if u == "held.md"} + 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(pg_documents, "heads", document_heads) + monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) assert await imp._seen(None, "memory_id", "o", "n") == {"m-ch", "m0", "m1", "m2"} assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} assert await imp._authority_documents("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, "_seen", nothing) + monkeypatch.setattr(imp, "_authority_documents", nothing) + run: Any = SimpleNamespace(bundle=bundle, ch=None) + with pytest.raises(BundleError, match="differs from its name"): + await imp._documents(run, [NsDecision("a", "n", "t", "n", "create")]) + + def test_an_original_changed_since_the_dry_run_stops_the_apply( monkeypatch: pytest.MonkeyPatch, ) -> None: From c6e8988f81f2694c520935b5b9c3cbbe5a48e4e1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:50:39 +0530 Subject: [PATCH 10/32] loom instance: a landing's email and row are the import's only while it holds - An email that signs in to a target account is excused only while that account is still this import's landing (`TargetOrg.holds`). A name someone signed up with since, with the same email, now refuses the account with a proposal to map it there, instead of landing it under another handle with an email the target's account also holds. - The apply tests an existing namespace row against the `created_at` the landing's audit row recorded, the value the plan used, not the bundle's: a source row created again between bundles no longer passes the dry run and stops every apply. - The audit helper takes `created_at` as a named argument. - Prose: the consolidation table's wording, and hand-wrapped lines. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 4 ++-- docs/operations/consolidation.md | 25 ++++++++++++----------- server/cli/instance_import.py | 15 +++++++------- server/cli/instance_plan.py | 11 +++++----- tests/unit/test_instance_consolidation.py | 8 ++++++++ 5 files changed, 35 insertions(+), 28 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index f09513ed8fb..97f0eb96f6b 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -1268,8 +1268,8 @@ no search leg returns it. The other reads that could serve its value follow thre `memory.sensitive_read` row. The admin dumps `namespace.snapshot` and `erasure.export` 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 + 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. diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index f945cdf2631..c1e76c02a96 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -8,15 +8,15 @@ run, with their settings. To move a whole deployment onto new hosts, see ## 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 | -| Memories: every live head, with its `created_at`, validity and attestation | 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 they synced but 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 | +| 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 | +| Memories: every live head, with its `created_at`, validity and attestation | 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 they synced 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 @@ -100,8 +100,8 @@ subjects: # "/": rule 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. The source's refusals that reach the source namespace refuse the rows it brings, and none is stored on the target's - namespace. It writes live facts only: a row in another - state, or past its expiry, is left out, and locks are not carried. A merged row's + namespace. It writes live facts only: a row in another state, or past its expiry, is + left out, 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. A document whose `source_uri` the target namespace already serves is left as it is. Per-type settings, policies and the guide land with a created namespace only. @@ -158,7 +158,8 @@ 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. +[restore](backup-and-recovery.md#undoing-changes-inside-a-namespace), run the same +erasure again once the import finishes. ## Related diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 176577e8681..e217a8e7398 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -364,16 +364,15 @@ def user_id(self, org: str, u: str) -> str | None: return None if t is None else t.removeprefix(USER) async def audit( - self, event: str, org: str, namespace: str, name: str, source: str, **more: str + 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={"name": name, "source": source, **more, **self.digests}, + event_type=event, org=org, namespace=namespace, actor=self.actor, subject=subject ) @@ -414,8 +413,8 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: 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. - if not landed or not landed_row(existing, row["created_at"]): + # An earlier run's row, or a name someone took since its audit row: the plan's test. + if not landed_row(existing, target.landed.get((d.target, key))): raise in_use return if await directory().in_use(d.target_org, d.target, ch=run.ch): diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index d3d06aa0512..692b2a0d075 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -332,13 +332,13 @@ def claim_name(self, name: str, source: str) -> bool: def _signs_in_elsewhere(o: _Org, name: str, emails: Iterable[str]) -> str: - """The first target account other than this source's earlier landing of `name` that - one of `emails` signs in to; '' when none.""" + """The first target account other than this source's landing of `name`, 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, []): org, _, account = h.partition("/") - if org != o.target_org or (account, landed) not in o.target.landed: + if org != o.target_org or not o.target.holds(account, landed): return h return "" @@ -591,9 +591,8 @@ def plan( """The decisions for every source org in `selected` (org → exported namespaces) of deployment `source`. `grant_subjects` is each source org's grant subjects, namespace owners and memory users (`user:`); `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.""" + 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={}, diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 88f3c35f721..99d9821d24c 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -279,6 +279,14 @@ def test_a_resumed_run_plans_the_same_digest() -> None: ) 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": "alice", "acme/user:7": "drop"}} # 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"]}) From 906daf2b46cff88295b45defa295efe7cdebd5e9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:25:43 +0530 Subject: [PATCH 11/32] loom instance: a resumed run never writes over a fact written since - A created namespace skips each source head whose key (agent, user, session and key) the namespace holds or has held, as a merge does, not only the memory ids an earlier run wrote: a fact someone wrote there before the rerun stays theirs. `_seen` reads document addresses only, and `pg_memory.held_in` pages head keys by `KeyInNamespace`. - An account the source revoked after an earlier bundle landed it as one that signs in refuses the plan until the target revokes it, which also ends its tokens and sessions there. `load_target` reads the target's revocations of landed names; the export and the import share the query. - An email that signs in to a target account is proposed `drop`: nothing proves a target account's contact email. Only the import's landing under the handle the map now gives is excused. - A landing that recorded its audit row but no namespace row writes it with the recorded `created_at`. - The bundle's digest is the SHA-256 of the manifest bytes the open read. - The dry run marks a landing an earlier run finished. - Docs: merged memories are embedded as `memory.bulk_set` writes them; a document's extraction record stays behind; rewrapped paragraphs. - Tests: `_land` against a recorded `created_at` that differs from the bundle's, a resumed run and a key written since, a revoke after a landing, a landing under a changed handle, and every column of a landed document. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/security.md | 9 +- docs/operations/consolidation.md | 85 +++++----- server/cli/instance.py | 19 ++- server/cli/instance_bundle.py | 15 +- server/cli/instance_export.py | 23 ++- server/cli/instance_import.py | 82 ++++------ server/cli/instance_plan.py | 41 +++-- server/memory/store/pg_memory.py | 11 +- .../test_instance_consolidation.py | 30 +++- tests/unit/test_instance_consolidation.py | 149 ++++++++++++++++-- 10 files changed, 313 insertions(+), 151 deletions(-) diff --git a/docs/architecture/security.md b/docs/architecture/security.md index 97f0eb96f6b..c36668cf194 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -1269,10 +1269,11 @@ no search leg returns it. The other reads that could serve its value follow thre 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. + 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/operations/consolidation.md b/docs/operations/consolidation.md index c1e76c02a96..b8d65ac4746 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -21,8 +21,11 @@ run, with their settings. To move a whole deployment onto new hosts, see 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`. -Memories reach vector search once the embedding worker's next full pass embeds them +`source_class=imported` and the importing command (`process:cli:instance`) as `actor`. A +document lands with its text and original; the source's record of how it extracted them +(`format`, `parser`, `coverage` 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 @@ -94,40 +97,43 @@ subjects: # "/": rule 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. - `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. - 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. The source's refusals that reach the - source namespace refuse the rows it brings, and none is stored on the target's - namespace. It writes live facts only: a row in another state, or past its expiry, is - left out, 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. A document whose `source_uri` the target namespace already serves is left as - it is. Per-type settings, policies and the guide land with a created namespace only. + approves each member of the target org who asks. `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. 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. The source's refusals that reach the source namespace refuse the + rows it brings, and none is stored on the target's namespace. It writes live facts + only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the target + namespace already serves is left as it is. Per-type settings, policies and the guide + land with a created namespace only. - **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), 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, the - target account or `drop`. Mapping an account onto a target account gives that account the - source account's content and grants: 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. + 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 until the target revokes it (`loom revoke-token --subject `), + which also ends the tokens and sessions it has had there since. - **Subjects.** 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, 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. Any + 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, 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. Any other subject needs a mapping or `drop`. - **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 @@ -138,26 +144,27 @@ subjects: # "/": rule ## 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. 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 +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. 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 id the namespace has held, deleted ones included, no document whose +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 +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. diff --git a/server/cli/instance.py b/server/cli/instance.py index 25c9560f6b1..1228ca47eef 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -76,8 +76,8 @@ async def _run(ch: Any) -> dict[str, Any]: return 0 -def _print_plan(bundle: Any, p: Any) -> None: - from server.cli.instance_import import carried +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 content = carried(bundle) @@ -85,11 +85,14 @@ def _print_plan(bundle: Any, p: Any) -> None: land = "skip" if d.action == "skip" else f"{d.action} {d.target_org}/{d.target}" account = f" (account, {d.account})" if d.account else "" joins = " (self-join needs approval: the target org serves others)" if d.approval else "" - rows = ( - " (its row only: a bundle that selects it brings its content)" - if d.action != "skip" and (d.source_org, d.source) not in content - else "" - ) + if d.action == "skip": + rows = "" + elif (d.target, source_key(bundle, d.source_org, d.source)) in targets[d.target_org].done: + rows = " (an earlier run finished it: skipped)" + elif (d.source_org, d.source) not in content: + rows = " (its row only: a bundle that selects it brings its content)" + else: + rows = "" print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{rows}") for s in p.subjects: to = f" → {s.target}" if s.action in ("map", "claim") else "" @@ -149,7 +152,7 @@ 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) + _print_plan(bundle, p, targets) if p.problems: return 1 if args.dry_run: diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py index d71f94fcde2..3f7e8ac3eab 100644 --- a/server/cli/instance_bundle.py +++ b/server/cli/instance_bundle.py @@ -149,15 +149,19 @@ def write(self, record: Mapping[str, Any]) -> None: @dataclass(frozen=True) class Bundle: - """A complete bundle, its files checked against the manifest when opened.""" + """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: - manifest = json.loads((path / MANIFEST).read_text()) + 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" @@ -180,12 +184,7 @@ def open(cls, path: Path) -> Bundle: 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) - - @property - def digest(self) -> str: - """The manifest's SHA-256: names this bundle in a plan and a receipt.""" - return hashlib.sha256((self.path / MANIFEST).read_bytes()).hexdigest() + return cls(path, manifest, hashlib.sha256(raw).hexdigest()) def rows(self, name: str) -> int: return int(self.manifest["sections"].get(name, {}).get("rows", 0)) diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 274c4611ce7..73f0d9a09a8 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -24,6 +24,14 @@ # 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()" +) # A knowledge source's copy that the source, registered again, writes again: it keeps only # its own copies up to date (`source_sync.ours`). A recording source lists its last weeks # only and its transcripts are settled when written, so its copies move. @@ -243,18 +251,9 @@ async def _identity_sections( """, p, ) - # An account the source revoked outright, by an operator or by SCIM and under any - # case (grants fold case), lands with no password. - await _table( - w, - ch, - "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()", - {**p, "lowered": sorted({s.lower() for s in p["subjects"]})}, - ) + # An account the source revoked lands with no password. + lowered = sorted({s.lower() for s in p["subjects"]}) + await _table(w, ch, "revoked", REVOKED, {**p, "lowered": lowered}) Counts = dict[str, dict[str, dict[str, int]]] # org → namespace → section → rows diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index e217a8e7398..f8b9964d9d3 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -13,8 +13,9 @@ `source_class=imported`, the importing command as `actor`); a merged one through `memory.bulk_set`, with its admission, for keys the target namespace never held. Documents go through `knowledge.upsert` with their originals, so the target's embedder -embeds them; memories are embedded by the embedding worker's next full pass. Every model -call is made for the target org. +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 @@ -28,7 +29,7 @@ from typing import Any from server.cli.instance_bundle import Bundle, BundleError -from server.cli.instance_export import stream_rows +from server.cli.instance_export import REVOKED, stream_rows from server.cli.instance_plan import ( MapFile, NsDecision, @@ -39,6 +40,7 @@ plan, ) from server.core.principals import USER +from server.memory.store.rows import key_in_namespace LANDED = "instance.import" MERGED = "instance.import.merge" # a merge lands in the target's own namespace @@ -91,6 +93,10 @@ async def load_target( "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] @@ -120,6 +126,7 @@ def pairs(event: str, org: str = org) -> frozenset[tuple[str, str]]: }, merged=pairs(MERGED), done=pairs(DONE), + revoked=gone, ) signs_in: dict[str, list[str]] = {} async for r in stream_rows( @@ -408,13 +415,13 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: if (d.target, key) not in target.merged: await run.audit(MERGED, d.target_org, d.target, d.target, key) return - landed = (d.target, key) in target.landed + 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, target.landed.get((d.target, key))): + if not landed_row(existing, recorded): raise in_use return if await directory().in_use(d.target_org, d.target, ch=run.ch): @@ -426,14 +433,14 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: raise SystemExit( f"{d.target_org}/{d.target} holds access on the target: plan again" ) from None - if not landed: + 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. - created = str(row["created_at"]) - await run.audit(LANDED, d.target_org, d.target, d.target, key, created_at=created) + 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) + 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] @@ -613,21 +620,17 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) await run.ch.insert("loom.sso_links", await _typed(run.ch, "sso_links", links)) -async def _seen(ch: Any, column: str, org: str, namespace: str) -> set[str]: - """Every memory id or document source_uri the namespace has held, deleted ones too.""" - table = "memory" if column == "memory_id" else "documents" - seen = { +async def _seen(ch: Any, org: str, namespace: str) -> set[str]: + """Every document source_uri the namespace has held, deleted ones too.""" + return { str(r["v"]) async for r in stream_rows( ch, - f"SELECT DISTINCT toString({column}) AS v FROM loom.{table} " + "SELECT DISTINCT source_uri AS v FROM loom.documents " "WHERE org = {org:String} AND namespace = {ns:String}", {"org": org, "ns": namespace}, ) } - if column == "memory_id": - seen.update([str(r["memory_id"]) async for r in _authority_heads(org, namespace)]) - return seen async def _authority_heads(org: str, namespace: str) -> AsyncIterator[dict[str, Any]]: @@ -642,30 +645,31 @@ async def _authority_heads(org: str, namespace: str) -> AsyncIterator[dict[str, while page := await pg_memory.held_in(org, namespace, after=after): for r in page: yield r - last = page[-1] - after = (last["agent"], last["user_id"], last["session_id"], last["memory_key"]) + after = key_in_namespace(page[-1]) async def _memories(run: _Run, decisions: list[NsDecision]) -> None: + """Each source head whose key the target namespace never held: a resumed run writes + nothing back over what someone wrote there since, nor a merge over the target's own.""" by_source = {(d.source_org, d.source): d for d in decisions} batch: dict[tuple[str, str], list[dict[str, Any]]] = {} - seen: dict[tuple[str, str], set[str]] = {} for m in run.bundle.records("memories"): d = by_source.get((m["org"], m["namespace"])) if d is None: continue - k = (d.source_org, d.source) - if d.action == "create": - if k not in seen: - seen[k] = await _seen(run.ch, "memory_id", d.target_org, d.target) - if m["memory_id"] in seen[k]: - run.count(d, "memories_present") - continue user = run.user_id(d.source_org, str(m.get("user_id") or "-")) if user is None: run.count(d, "memories_of_dropped_users") continue m["user_id"] = user + t = (d.target_org, d.target) + if t not in run.held: # once per target namespace: each write adds its key below + run.held[t] = await _held_keys(run.ch, *t) + if key_in_namespace(m) in run.held[t]: + run.count(d, "memories_the_target_holds") + continue + run.held[t].add(key_in_namespace(m)) + k = (d.source_org, d.source) rows = batch.setdefault(k, []) rows.append(m) if len(rows) >= _BATCH: @@ -716,14 +720,10 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, str, str]]: """Every (agent, user, session, key) the namespace holds or has held, a deleted one - included: a merge only adds keys, so it never revises the target's own fact, nor + included: the import only adds keys, so it never revises a fact written there, nor brings back one its owners deleted.""" - - def ident(r: Mapping[str, Any]) -> tuple[str, str, str, str]: - return (str(r["agent"]), str(r["user_id"]), str(r["session_id"]), str(r["memory_key"])) - held = { - ident(r) + key_in_namespace(r) async for r in stream_rows( ch, "SELECT DISTINCT agent, user_id, session_id, memory_key FROM loom.memory " @@ -731,7 +731,7 @@ def ident(r: Mapping[str, Any]) -> tuple[str, str, str, str]: {"org": org, "ns": namespace}, ) } - held.update([ident(r) async for r in _authority_heads(org, namespace)]) + held.update([key_in_namespace(r) async for r in _authority_heads(org, namespace)]) return held @@ -777,20 +777,11 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set - t = (d.target_org, d.target) - if t not in run.held: # once per target namespace: each write adds its keys below - run.held[t] = await _held_keys(run.ch, d.target_org, d.target) - held = run.held[t] groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} for m in memories: - ident = (m.agent, m.user_id, m.session_id, m.memory_key) - if ident in held: - run.count(d, "memories_the_target_holds") - continue if (entry := _bulk_entry(m)) is None: run.count(d, "memories_not_live") continue - held.add(ident) groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) for (agent, user_id, session_id), entries in groups.items(): for start in range(0, len(entries), MAX_BULK_ENTRIES): @@ -830,10 +821,7 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: for doc in run.bundle.records("documents"): if (d := by_source.get((doc["org"], doc["namespace"]))) is not None: uris.setdefault((d.target_org, d.target), []).append(str(doc["source_uri"])) - seen = { - k: await _seen(run.ch, "source_uri", *k) | await _authority_documents(*k, v) - for k, v in uris.items() - } + seen = {k: await _seen(run.ch, *k) | await _authority_documents(*k, v) for k, v in uris.items()} for doc in run.bundle.records("documents"): d = by_source.get((doc["org"], doc["namespace"])) if d is None: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 692b2a0d075..1657c62e734 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -159,13 +159,15 @@ class TargetOrg: 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.""" - row = self.namespaces.get(name) 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))) @@ -331,18 +333,32 @@ def claim_name(self, name: str, source: str) -> bool: return True -def _signs_in_elsewhere(o: _Org, name: str, emails: Iterable[str]) -> str: - """The first target account other than this source's landing of `name`, while it is - still the import's, that one of `emails` signs in to; '' when none.""" +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, []): - org, _, account = h.partition("/") - if org != o.target_org or not o.target.holds(account, landed): + if h != f"{o.target_org}/{handle}" or not o.target.holds(handle, landed): return h return "" +def _revoked_since(o: _Org, name: str, handle: str) -> bool: + """Whether the source revoked an account after an earlier bundle landed it as one that + signs in, and the target has not revoked it: only the target's revocation also ends + the tokens and sessions it has since.""" + mine = f"{o.target_org}/{handle}" + return ( + o.target.holds(handle, f"{o.source}/{o.org}/{name}") + and handle.lower() not in o.target.revoked + and ( + bool((o.target.namespaces.get(handle) or {}).get("password_hash")) + or any(mine in held for held in o.signs_in.values()) + ) + ) + + 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.""" @@ -376,14 +392,14 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: 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, sorted(emails)): - org, _, account = holder.partition("/") + 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", - account if org == o.target_org else "drop", + "drop", ) return if other := next((o.emails[e] for e in sorted(emails) if e in o.emails), ""): @@ -419,6 +435,13 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: {"claim": f"{handle}-legacy"}, ) return + if revoked and _revoked_since(o, name, handle): + o.problem( + f"account {name!r}: the source revoked it after an earlier bundle landed it, and " + f"{o.target_org}/{handle} still signs in on the target: revoke it there " + f"(`loom revoke-token --subject {handle}`), then plan again" + ) + return if not o.claim_name(handle, name): return o.emails.update(dict.fromkeys(emails, f"{o.org}/{name}")) diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index e13c36faa7e..0d71791faea 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -45,6 +45,7 @@ from server.memory.store.rows import ( FIRST_VERSION_DEFAULTS, IdentityKey, + KeyInNamespace, MemoryRow, _hydrate, identity_key, @@ -2091,12 +2092,12 @@ async def held_in( org: str, namespace: str, *, - after: tuple[str, str, str, str] | None = None, + after: KeyInNamespace | None = None, limit: int = 5000, ) -> list[dict[str, Any]]: - """A page of every head of a namespace, deleted ones included, as its memory id and - (agent, user_id, session_id, memory_key), in key order after `after`: what the - namespace holds or has held, its publication to ClickHouse owed or not.""" + """A page of every head of a namespace, deleted ones included, as its (agent, user_id, + session_id, memory_key), in key order after `after`: 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] @@ -2105,7 +2106,7 @@ async def held_in( args += list(after) where += " AND (agent, user_id, session_id, memory_key) > ($4, $5, $6, $7)" rows = await pg.fetch( - "SELECT memory_id::text AS memory_id, agent, user_id, session_id, memory_key " + "SELECT agent, user_id, session_id, memory_key " f"FROM loom.memory_current WHERE {where} " "ORDER BY org, namespace, agent, user_id, session_id, memory_key LIMIT $3", *args, diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 6e0d3c6a243..08e2414778d 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -40,6 +40,22 @@ 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. @@ -350,12 +366,16 @@ async def test_an_org_moves_into_a_live_one_under_the_map( "# Runbook\nRestart the service.", "Runbook", ) - blob = await ch.query_one( - "SELECT blob_path FROM loom.documents FINAL WHERE org = {org:String} " - "AND namespace = 'team-legacy' AND source_uri = 'runbook.md'" + SEQ, - params={"org": dst_org}, + runbook = ( + "SELECT * FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND source_uri = 'runbook.md'" + SEQ ) - assert blob is not None and blob["blob_path"] == hashlib.sha256(ORIGINAL).hexdigest() + 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 " diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 99d9821d24c..49a87952656 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -235,8 +235,9 @@ 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": "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) @@ -286,7 +287,17 @@ def test_a_resumed_run_plans_the_same_digest() -> None: 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": "alice", "acme/user:7": "drop"}} + 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"]}) @@ -371,6 +382,22 @@ def test_an_account_the_source_revoked_lands_with_no_email_to_check() -> None: 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 + 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 = [ @@ -423,25 +450,20 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( from server.core import pg from server.knowledge.store import pg_documents from server.memory.store import pg_memory + from server.memory.store.rows import key_in_namespace heads = [ - { - "memory_id": f"m{i}", - "agent": "a", - "user_id": "-", - "session_id": "-", - "memory_key": f"k{i}", - } - for i in range(3) + {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": f"k{i}"} for i in range(3) ] async def held_in(org: str, ns: str, *, after: Any = None, limit: int = 5000) -> Any: - key = lambda h: (h["agent"], h["user_id"], h["session_id"], h["memory_key"]) # noqa: E731 - return [h for h in heads if after is None or key(h) > after][:2] # pages of two + return [h for h in heads if after is None or key_in_namespace(h) > after][ + :2 + ] # pages of two async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: if " AS v " in sql: - yield {"v": "m-ch"} + yield {"v": "ch.md"} else: yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} @@ -452,7 +474,7 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: monkeypatch.setattr(pg_memory, "held_in", held_in) monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) - assert await imp._seen(None, "memory_id", "o", "n") == {"m-ch", "m0", "m1", "m2"} + assert await imp._seen(None, "o", "n") == {"ch.md"} assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} assert await imp._authority_documents("o", "n", ["held.md", "new.md"]) == {"held.md"} @@ -513,3 +535,102 @@ async def changed(*_: Any) -> Any: 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_the_created_at_its_audit_row_recorded( + 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.""" + 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 + + +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.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + + w = BundleWriter(tmp_path / "b") + with w.section("memories") as sink: + for k in ("k1", "k2"): + head = {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": k} + sink.write({"org": "acme", "namespace": "n", "memory_id": f"src-{k}", **head}) + w.finish({"source": {"deployment_id": SOURCE}}) + written: list[str] = [] + counted: list[str] = [] + + async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: + return {("a", "-", "-", "k1")} + + async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: + written.extend(r["memory_key"] for r in rows) + + monkeypatch.setattr(imp, "_held_keys", held_keys) + monkeypatch.setattr(imp, "_write_memories", write) + run: Any = SimpleNamespace( + bundle=Bundle.open(tmp_path / "b"), + ch=None, + held={}, + user_id=lambda o, u: u, + count=lambda d, what, n=1: counted.append(what), + ) + await imp._memories(run, [NsDecision("acme", "n", "acme", "n", "create")]) + assert written == ["k2"] and counted == ["memories_the_target_holds"] From daa9aa40b013a290523007f3f2964d589633b0ae Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:43:36 +0530 Subject: [PATCH 12/32] loom instance: a revoked account's earlier landing refuses whatever the map does - The plan checks every earlier landing of an account the source revoked, before its map entry: one the target still lets sign in, and has not revoked, refuses the plan whether the map keeps the account, drops it or claims it under another handle. The problem text and the docs say the target's `loom revoke-token --subject` reaches the handle in every org. - `pg_memory.held_in` returns the keys themselves; `_held_keys` pages it without a wrapper, and `_seen` is `_held_uris`. - Docs and docstring: created and merged namespaces both receive only keys the target never held; a document's `ingested_at` and `artifact_sha256` are named. - Tests: the revoked landing under `drop` and under another claim, and the dry run's mark on a landing an earlier run finished. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 15 +++--- server/cli/instance_import.py | 37 +++++++------- server/cli/instance_plan.py | 48 +++++++++++-------- server/memory/store/pg_memory.py | 10 ++-- .../test_instance_consolidation.py | 5 +- tests/unit/test_instance_consolidation.py | 22 ++++----- 6 files changed, 71 insertions(+), 66 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index b8d65ac4746..52a2439e9ce 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -22,10 +22,11 @@ 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; the source's record of how it extracted them -(`format`, `parser`, `coverage` 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 +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 @@ -123,8 +124,10 @@ subjects: # "/": rule 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 until the target revokes it (`loom revoke-token --subject `), - which also ends the tokens and sessions it has had there since. + 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 revocation reaches the handle in every org of the + target deployment, so check first that no other org has an account under it. - **Subjects.** 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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index f8b9964d9d3..17cd821d7b4 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -11,7 +11,8 @@ 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, for keys the target namespace never held. +`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 @@ -24,7 +25,7 @@ import json import time import uuid -from collections.abc import AsyncIterator, Iterable, Mapping +from collections.abc import Iterable, Mapping from datetime import UTC, datetime from typing import Any @@ -620,7 +621,7 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) await run.ch.insert("loom.sso_links", await _typed(run.ch, "sso_links", links)) -async def _seen(ch: Any, org: str, namespace: str) -> set[str]: +async def _held_uris(ch: Any, org: str, namespace: str) -> set[str]: """Every document source_uri the namespace has held, deleted ones too.""" return { str(r["v"]) @@ -633,21 +634,6 @@ async def _seen(ch: Any, org: str, namespace: str) -> set[str]: } -async def _authority_heads(org: str, namespace: str) -> AsyncIterator[dict[str, Any]]: - """Under the Postgres authority, every head of the namespace, deleted ones included: a - head committed since its last publication to ClickHouse is there only.""" - from server.core import pg - from server.memory.store import pg_memory - - if not pg.enabled(): - return - after = None - while page := await pg_memory.held_in(org, namespace, after=after): - for r in page: - yield r - after = key_in_namespace(page[-1]) - - async def _memories(run: _Run, decisions: list[NsDecision]) -> None: """Each source head whose key the target namespace never held: a resumed run writes nothing back over what someone wrote there since, nor a merge over the target's own.""" @@ -721,7 +707,11 @@ async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) - async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, str, str]]: """Every (agent, user, session, key) the namespace holds or has held, a deleted one included: the import only adds keys, so it never revises a fact written there, nor - brings back one its owners deleted.""" + brings back one its owners deleted. Under the Postgres authority its heads count too: + one committed since its last publication to ClickHouse is there only.""" + from server.core import pg + from server.memory.store import pg_memory + held = { key_in_namespace(r) async for r in stream_rows( @@ -731,7 +721,10 @@ async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, s {"org": org, "ns": namespace}, ) } - held.update([key_in_namespace(r) async for r in _authority_heads(org, namespace)]) + after = None + while pg.enabled() and (page := await pg_memory.held_in(org, namespace, after=after)): + held.update(page) + after = page[-1] return held @@ -821,7 +814,9 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: for doc in run.bundle.records("documents"): if (d := by_source.get((doc["org"], doc["namespace"]))) is not None: uris.setdefault((d.target_org, d.target), []).append(str(doc["source_uri"])) - seen = {k: await _seen(run.ch, *k) | await _authority_documents(*k, v) for k, v in uris.items()} + seen = { + k: await _held_uris(run.ch, *k) | await _authority_documents(*k, v) for k, v in uris.items() + } for doc in run.bundle.records("documents"): d = by_source.get((doc["org"], doc["namespace"])) if d is None: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 1657c62e734..f39d6c62893 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -344,19 +344,25 @@ def _signs_in_elsewhere(o: _Org, name: str, handle: str, emails: Iterable[str]) return "" -def _revoked_since(o: _Org, name: str, handle: str) -> bool: - """Whether the source revoked an account after an earlier bundle landed it as one that - signs in, and the target has not revoked it: only the target's revocation also ends - the tokens and sessions it has since.""" - mine = f"{o.target_org}/{handle}" - return ( - o.target.holds(handle, f"{o.source}/{o.org}/{name}") - and handle.lower() not in o.target.revoked - and ( - bool((o.target.namespaces.get(handle) or {}).get("password_hash")) - or any(mine in held for held in o.signs_in.values()) - ) - ) +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): + mine = f"{o.target_org}/{handle}" + if ( + landing == key + and o.target.holds(handle, key) + and handle.lower() not in o.target.revoked + and ( + bool((o.target.namespaces.get(handle) or {}).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: @@ -368,6 +374,15 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: 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")) @@ -435,13 +450,6 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: {"claim": f"{handle}-legacy"}, ) return - if revoked and _revoked_since(o, name, handle): - o.problem( - f"account {name!r}: the source revoked it after an earlier bundle landed it, and " - f"{o.target_org}/{handle} still signs in on the target: revoke it there " - f"(`loom revoke-token --subject {handle}`), then plan again" - ) - return if not o.claim_name(handle, name): return o.emails.update(dict.fromkeys(emails, f"{o.org}/{name}")) diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 0d71791faea..bcbedcd4c11 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -2094,10 +2094,10 @@ async def held_in( *, after: KeyInNamespace | None = None, limit: int = 5000, -) -> list[dict[str, Any]]: - """A page of every head of a namespace, deleted ones included, as its (agent, user_id, - session_id, memory_key), in key order after `after`: what the namespace holds or has - held, its publication to ClickHouse owed or not.""" +) -> list[KeyInNamespace]: + """A page of the keys of every head of a namespace, deleted ones included, in key order + after `after`: 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] @@ -2111,7 +2111,7 @@ async def held_in( "ORDER BY org, namespace, agent, user_id, session_id, memory_key LIMIT $3", *args, ) - return [dict(r) for r in rows] + return [(r["agent"], r["user_id"], r["session_id"], r["memory_key"]) for r in rows] async def unpublished_keepers( diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 08e2414778d..dfd1527b19e 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -541,7 +541,10 @@ def imported(bundle: Path) -> str: ] team = dst.get("team", "deploys")["version"] - assert "(its row only" not in imported(whole) + 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})] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 49a87952656..cee809c7c76 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -391,6 +391,10 @@ def test_an_account_revoked_since_an_earlier_landing_is_revoked_on_the_target_fi 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) 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. @@ -450,22 +454,15 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( from server.core import pg from server.knowledge.store import pg_documents from server.memory.store import pg_memory - from server.memory.store.rows import key_in_namespace - heads = [ - {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": f"k{i}"} for i in range(3) - ] + heads = [("a", "-", "-", f"k{i}") for i in range(3)] async def held_in(org: str, ns: str, *, after: Any = None, limit: int = 5000) -> Any: - return [h for h in heads if after is None or key_in_namespace(h) > after][ - :2 - ] # pages of two + # pages of two + return [h for h in heads if after is None or h > after][:2] async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: - if " AS v " in sql: - yield {"v": "ch.md"} - else: - yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} + yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: return {u for u in uris if u == "held.md"} @@ -474,7 +471,6 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: monkeypatch.setattr(pg_memory, "held_in", held_in) monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) - assert await imp._seen(None, "o", "n") == {"ch.md"} assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} assert await imp._authority_documents("o", "n", ["held.md", "new.md"]) == {"held.md"} @@ -499,7 +495,7 @@ async def test_an_original_changed_after_the_dry_run_stops_its_document( async def nothing(*_: Any) -> set[str]: return set() - monkeypatch.setattr(imp, "_seen", nothing) + monkeypatch.setattr(imp, "_held_uris", nothing) monkeypatch.setattr(imp, "_authority_documents", nothing) run: Any = SimpleNamespace(bundle=bundle, ch=None) with pytest.raises(BundleError, match="differs from its name"): From 5d28c2c919a54dce91509e24601182ccfb75091f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:58:08 +0530 Subject: [PATCH 13/32] loom instance: two merges into one namespace land an address once - Two source namespaces may merge into one target namespace: a document address the run has written is counted as present for the next one, as a memory key is, instead of superseding the first copy. - A landing the target deleted no longer counts as one that still signs in: password and single sign-on read `active`. - Docs: the plan reads earlier landings in the target orgs the map names, and deleting the landed account settles the plan where another org holds the handle, ending only its sign-in. - `pg_memory.held_in` builds keys with `key_in_namespace`; the module docstring is reflowed. - Tests: two merges with one address, a revoked account mapped onto a target account, a finished landing the target deleted, and, end to end, an account revoked on the source after a first bundle landed it refusing a later plan. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 7 ++- server/cli/instance_import.py | 11 +++-- server/cli/instance_plan.py | 6 ++- server/memory/store/pg_memory.py | 3 +- .../test_instance_consolidation.py | 26 +++++++++++ tests/unit/test_instance_consolidation.py | 46 +++++++++++++++++++ 6 files changed, 89 insertions(+), 10 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 52a2439e9ce..80b8ff1420d 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -126,8 +126,11 @@ subjects: # "/": rule 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 revocation reaches the handle in every org of the - target deployment, so check first that no other org has an account under it. + sessions it has had there since. The plan reads the earlier landings in the target + orgs the map names. 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`) settles the plan instead, but ends only its sign-in: a token it + already holds keeps its grants until it expires. - **Subjects.** 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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 17cd821d7b4..1234ea5a783 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -12,11 +12,10 @@ 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. +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 @@ -824,6 +823,8 @@ async def _documents(run: _Run, decisions: list[NsDecision]) -> None: if doc["source_uri"] in seen[(d.target_org, d.target)]: run.count(d, "documents_present") continue + # Two source namespaces may merge into one: the first copy of an address stays. + seen[(d.target_org, d.target)].add(doc["source_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() diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index f39d6c62893..5b2b17d71f9 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -351,14 +351,16 @@ def _still_signs_in(o: _Org, name: str) -> str: 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((o.target.namespaces.get(handle) or {}).get("password_hash")) - or any(mine in held for held in o.signs_in.values()) + bool(row.get("password_hash")) or any(mine in held for held in o.signs_in.values()) ) ): return handle diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index bcbedcd4c11..8ac52838131 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -49,6 +49,7 @@ MemoryRow, _hydrate, identity_key, + key_in_namespace, memory_head_state, parse_memory_value, ) @@ -2111,7 +2112,7 @@ async def held_in( "ORDER BY org, namespace, agent, user_id, session_id, memory_key LIMIT $3", *args, ) - return [(r["agent"], r["user_id"], r["session_id"], r["memory_key"]) for r in rows] + return [key_in_namespace(r) for r in rows] async def unpublished_keepers( diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index dfd1527b19e..06597d7eef4 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -482,6 +482,11 @@ async def test_a_namespace_bundle_leaves_its_accounts_content_to_a_later_one( 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) @@ -536,11 +541,30 @@ def imported(bundle: Path) -> str: 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} + await ch.execute( + "ALTER TABLE loom.revoked_tokens DELETE WHERE jti = {jti:String} " + "SETTINGS mutations_sync = 2", + {"jti": gus}, + ) + 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) @@ -550,9 +574,11 @@ def imported(bundle: Path) -> str: 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), ] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index cee809c7c76..6ce4c1aad78 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -395,6 +395,13 @@ def test_an_account_revoked_since_an_earlier_landing_is_revoked_on_the_target_fi 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. @@ -630,3 +637,42 @@ async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: ) await imp._memories(run, [NsDecision("acme", "n", "acme", "n", "create")]) assert written == ["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.""" + from contextlib import nullcontext + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.knowledge.app import writes + + w = BundleWriter(tmp_path / "b") + with w.section("documents") as sink: + for ns in ("notes", "scratch"): + sink.write({"org": "acme", "namespace": ns, "source_uri": "runbook.md", "content": ns}) + w.finish({"source": {"deployment_id": SOURCE}}) + landed: list[str] = [] + counted: list[str] = [] + + async def nothing(*_: Any) -> set[str]: + return set() + + async def upsert(body: Any) -> None: + landed.append(body.content) + + monkeypatch.setattr(imp, "_held_uris", nothing) + monkeypatch.setattr(imp, "_authority_documents", nothing) + 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, + count=lambda d, what, n=1: counted.append(what), + ) + merges = [NsDecision("acme", ns, "acme", "team", "merge") for ns in ("notes", "scratch")] + await imp._documents(run, merges) + assert landed == ["notes"] and counted == ["documents", "documents_present"] From d5828b20f2007f93d0025ac0bde6ff1fa8cf20df Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:15:50 +0530 Subject: [PATCH 14/32] loom instance: the receipt counts memories admission declined - A merged entry `memory.bulk_set` declines (a pinned peer, or a restatement it folds into a row) is counted as `memories_not_admitted`, so the receipt adds up to the source's count. - The single sign-on links land in their own step (`_links`), run under `sso_same_issuer`, not at the end of `_grants`. - Docs: a document address the namespace holds or has held is left alone, and of two namespaces merged into one the first brings an address or key both hold; the revoked-landing paragraph names the one target org the plan reads and what a delete leads to for an unfinished landing. - The integration test lapses the revocation with a newer row instead of a mutation. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 18 +++++++++------ server/cli/instance_import.py | 22 ++++++++++++++----- .../test_instance_consolidation.py | 7 ++---- 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 80b8ff1420d..31b7dbb0926 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -107,8 +107,11 @@ subjects: # "/": rule only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the target - namespace already serves is left as it is. Per-type settings, policies and the guide - land with a created namespace only. + namespace holds or has held is left as it is. Of two namespaces merged into one, the + first in the bundle brings an address or key both hold. Admission may decline a memory + (a pinned peer, or a restatement it folds into a row): the receipt counts it as + `memories_not_admitted`. Per-type settings, policies and the guide land with a created + namespace only. - **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 @@ -126,11 +129,12 @@ subjects: # "/": rule 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 the earlier landings in the target - orgs the map names. 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`) settles the plan instead, but ends only its sign-in: a token it - already holds keeps its grants until it expires. + 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 asks for another handle or `drop`. - **Subjects.** 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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 1234ea5a783..9d910f3b5df 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -521,7 +521,7 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - run.count(d, "refusals") -async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) -> None: +async def _grants(run: _Run, decisions: list[NsDecision]) -> 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 @@ -592,8 +592,12 @@ async def _grants(run: _Run, decisions: list[NsDecision], sso_same_issuer: bool) run.count(d, "grants") with _identity(): await grants_repo.insert_rows(rows, ch=run.ch) - if not sso_same_issuer: - return + + +async def _links(run: _Run, decisions: list[NsDecision]) -> 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.""" + by_source = {(d.source_org, d.source): d for d in decisions} held_links = await run.ch.query_all( "SELECT DISTINCT email, org, namespace FROM loom.sso_links " "WHERE org IN {orgs:Array(String)}", @@ -777,6 +781,7 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) for (agent, user_id, session_id), entries in groups.items(): for start in range(0, len(entries), MAX_BULK_ENTRIES): + chunk = entries[start : start + MAX_BULK_ENTRIES] out = await handle_memory_bulk_set( MemoryBulkSetInput.model_validate( { @@ -785,11 +790,14 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None "agent": agent, "user_id": user_id, "session_id": session_id, - "entries": entries[start : start + MAX_BULK_ENTRIES], + "entries": chunk, } ) ) - run.count(d, "memories", sum(1 for w in out.written if w.version)) + written = sum(1 for w in out.written if w.version) + run.count(d, "memories", written) + if declined := len(chunk) - written: # a pinned peer, or a restatement it merged + run.count(d, "memories_not_admitted", declined) async def _authority_documents(org: str, namespace: str, uris: list[str]) -> set[str]: @@ -873,7 +881,9 @@ async def apply( await _blacklist(run, d, patterns) else: run.refusals[(d.source_org, d.source)] = refusals(patterns, d) - await _grants(run, todo, p.sso_same_issuer) + await _grants(run, todo) + if p.sso_same_issuer: + await _links(run, todo) await _memories(run, todo) await _documents(run, todo) content = carried(bundle) diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 06597d7eef4..fe48aa1037c 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -556,11 +556,8 @@ def imported(bundle: Path) -> str: 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} - await ch.execute( - "ALTER TABLE loom.revoked_tokens DELETE WHERE jti = {jti:String} " - "SETTINGS mutations_sync = 2", - {"jti": 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 From 67d34aa1bcc4d83a9e55318695dfec46be6f416f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:48:28 +0530 Subject: [PATCH 15/32] loom instance: a merge writes outside facts as memory.import does - A merge's `memory.bulk_set` calls check every entry, whatever `bulk_conflict_check_max_entries` caps a call at, send each call oldest first, and turn off update detection and reinforcement, which each rerun would add again. - Under `newest_wins`, a same-key write retires the older rows in every session of its user (of anyone, for a write with no user): a merged key counts as held that far, the merge's own writes included. - A merge no longer carries a source pin, which would refuse the target owners' own later writes of a close fact. - The dry run builds every memory row the apply writes and names each one the target refuses, which would otherwise stop every apply at that row. - The receipt counts single sign-on links; the landings are built once on the run; the Postgres authority's documents are read in `_held_uris`. - Docs: merge admission settings, the `newest_wins` reach, what admission may still mark or retire, pins, the dry run's memory check, and the handle the plan proposes after a delete. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 21 ++- server/cli/instance_import.py | 188 ++++++++++++++------- tests/unit/test_instance_consolidation.py | 193 ++++++++++++++++++++-- 3 files changed, 323 insertions(+), 79 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 31b7dbb0926..d9acbb34d05 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -60,7 +60,9 @@ search once the embedding worker's next full pass embeds them ``` Each problem says what settles it. Where a map entry does, the run prints the entries - as YAML to copy into the map. + as YAML to copy into the map. The dry run builds every memory the run would write, so + one the target cannot store (a date past 2106, text the Postgres memory authority + refuses) is named here, not part way through the run. 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: @@ -100,12 +102,17 @@ subjects: # "/": rule source org could join at once lands with `join_policy: approval`, so a namespace admin approves each member of the target org who asks. `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. 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. The source's refusals that reach the source namespace refuse the + 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 same user holds it in any agent or + session, or, for a row with no user, where anyone holds it. Admission may still mark a target row a merged one + contradicts as conflicted, and, with the conflict resolver on, retire one it judges the + merged row updates. The source's refusals that reach the source namespace refuse the rows it brings, and none is stored on the target's namespace. It writes live facts - only: a row in another state, or past its expiry, is left out, and locks are not - carried. A merged row's `created_at` is the import's; its validity, expiry, + only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the target namespace holds or has held is left as it is. Of two namespaces merged into one, the first in the bundle brings an address or key both hold. Admission may decline a memory @@ -134,7 +141,7 @@ subjects: # "/": rule 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 asks for another handle or `drop`. + did not finish, the plan then proposes another handle. - **Subjects.** 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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 9d910f3b5df..2e583ecbd7e 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -39,6 +39,8 @@ landed_row, plan, ) +from server.core.datetimes import to_naive_utc +from server.core.naming import is_anonymous_user from server.core.principals import USER from server.memory.store.rows import key_in_namespace @@ -188,8 +190,10 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr 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), a refusal this deployment cannot compile, a created namespace whose refusals would pass the regex - budget, an original missing from the bundle. Each is added as a problem.""" + budget, a memory the target cannot store, an original missing from the bundle. Each is + added as a problem.""" from fastapi import HTTPException + from pydantic import ValidationError as ModelError from server.auth.self_signup import refuse_empowered from server.core.errors import ValidationError @@ -219,10 +223,12 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr "claim": f"{d.target}-legacy" } 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"]) @@ -246,6 +252,21 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr 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"): + into = todo.get((m["org"], m["namespace"])) + if into is None or run.user_id(into.source_org, str(m.get("user_id") or "-")) is None: + continue + try: + _built(into, m) + 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" + ) landing = {(d.source_org, d.source) for d in p.namespaces if d.action != "skip"} for doc in bundle.records("documents"): sha = doc.get("blob_path") @@ -259,6 +280,33 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) +def _built(d: NsDecision, m: Mapping[str, Any]) -> None: + """Build source head `m` as the apply writes it into `d`'s namespace, raising where the + target refuses it.""" + from server.identity.api.models import _SnapshotMemoryRow + from server.memory.api.models_bulk import _BulkSetEntry + from server.memory.app import snapshot_rows as snap + + row = _SnapshotMemoryRow.model_validate( + {k: v for k, v in m.items() if k not in ("org", "namespace")} + ) + if d.action == "merge": + if (entry := _bulk_entry(row)) is None: + return # left out + _BulkSetEntry.model_validate(entry) + # 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="", + ) + ) + + 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)) @@ -344,9 +392,12 @@ def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, Targe self.revoked = _revoked(bundle) self.digests = {"bundle": bundle.digest, "plan": p.digest} self.counts: dict[str, dict[str, int]] = {} - # Per merge: the source refusals, and the keys its target namespace holds. + self.by_source: dict[tuple[str, str], NsDecision] = {} # the landings this run writes + # Per merge: the source refusals. Per target namespace: the keys it holds, 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], set[tuple[str, str, str, str]]] = {} + self.reach: dict[tuple[str, str], set[tuple[str | None, str]]] = {} def next_version(self) -> int: self.version += 1 @@ -521,7 +572,7 @@ async def _blacklist(run: _Run, d: NsDecision, patterns: list[dict[str, Any]]) - run.count(d, "refusals") -async def _grants(run: _Run, decisions: list[NsDecision]) -> None: +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 @@ -535,12 +586,11 @@ async def _grants(run: _Run, decisions: list[NsDecision]) -> None: from server.identity.store import grants as grants_repo from server.operations.base import grant_rank - by_source = {(d.source_org, d.source): d for d in decisions} 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 decisions})}, + 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: @@ -552,7 +602,7 @@ async def _grants(run: _Run, decisions: list[NsDecision]) -> None: spelled: dict[tuple[str, str], tuple[str, set[str], set[str]]] = {} rows = [] for g in run.bundle.records("grants"): - d = by_source.get((g["org"], g["namespace"])) + 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 @@ -594,39 +644,49 @@ async def _grants(run: _Run, decisions: list[NsDecision]) -> None: await grants_repo.insert_rows(rows, ch=run.ch) -async def _links(run: _Run, decisions: list[NsDecision]) -> None: +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.""" - by_source = {(d.source_org, d.source): d for d in decisions} 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 decisions})}, + 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 = [ - { - **link, - "org": d.target_org, - "namespace": d.target, - "linked_by": run.actor, - "version": run.next_version(), - } - for link in run.bundle.records("sso_links") - if (d := by_source.get((link["org"], link["namespace"]))) is not None - and d.account - and d.source.lower() not in run.revoked - # One the target holds in any state, unlinked included, is the target's. - and (link["email"], d.target_org, d.target) not in linked - ] + 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) -> set[str]: - """Every document source_uri the namespace has held, deleted ones too.""" - return { +async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[str]: + """Every document source_uri the namespace has held, deleted ones too. Under the + Postgres authority, those of `uris` it holds as well: a head 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, @@ -635,15 +695,22 @@ async def _held_uris(ch: Any, org: str, namespace: str) -> set[str]: {"org": org, "ns": namespace}, ) } + if pg.enabled(): + held |= await pg_documents.held_uris(org, namespace, uris) + return held -async def _memories(run: _Run, decisions: list[NsDecision]) -> None: +async def _memories(run: _Run) -> None: """Each source head whose key the target namespace never held: a resumed run writes - nothing back over what someone wrote there since, nor a merge over the target's own.""" - by_source = {(d.source_org, d.source): d for d in decisions} + nothing back over what someone wrote there since, nor a merge over the target's own. + Under `newest_wins` a same-key write retires older rows past its own agent and session, + so a merged key also counts as held where it would retire one: the same user's in any + agent and session, and, for a row with no user, anyone's.""" + from server.memory.app.conflicts import namespace_conflict_policy + batch: dict[tuple[str, str], list[dict[str, Any]]] = {} for m in run.bundle.records("memories"): - d = by_source.get((m["org"], m["namespace"])) + d = run.by_source.get((m["org"], m["namespace"])) if d is None: continue user = run.user_id(d.source_org, str(m.get("user_id") or "-")) @@ -651,13 +718,21 @@ async def _memories(run: _Run, decisions: list[NsDecision]) -> None: run.count(d, "memories_of_dropped_users") continue m["user_id"] = user - t = (d.target_org, d.target) + t, key = (d.target_org, d.target), str(m["memory_key"]) if t not in run.held: # once per target namespace: each write adds its key below run.held[t] = await _held_keys(run.ch, *t) - if key_in_namespace(m) in run.held[t]: + if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": + run.reach[t] = {r for _, u, _, k in run.held[t] for r in ((u, k), (None, k))} + reach = run.reach.get(t) + writer = None if is_anonymous_user(user) else user + if key_in_namespace(m) in run.held[t] or ( + d.action == "merge" and reach is not None and (writer, key) in reach + ): run.count(d, "memories_the_target_holds") continue run.held[t].add(key_in_namespace(m)) + if reach is not None: + reach.update(((user, key), (None, key))) k = (d.source_org, d.source) rows = batch.setdefault(k, []) rows.append(m) @@ -666,7 +741,7 @@ async def _memories(run: _Run, decisions: list[NsDecision]) -> None: rows.clear() for k, rows in batch.items(): if rows: - await _write_memories(run, by_source[k], rows) + await _write_memories(run, run.by_source[k], rows) async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) -> None: @@ -734,7 +809,8 @@ async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, s def _bulk_entry(m: Any) -> dict[str, Any] | None: """A source head as a `memory.bulk_set` entry, None when it is no live fact: a row in another state, or one past its expiry. Its time of writing becomes the import's; its - validity, sensitivity, expiry and temporal anchor stay the source's.""" + 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.""" if m.status != _MERGED_STATUS: return None ttl = None @@ -758,7 +834,6 @@ def _bulk_entry(m: Any) -> dict[str, Any] | None: "valid_at": m.valid_at or m.created_at, "valid_to": m.valid_to, "char_limit": m.char_limit, - "pinned": m.pinned, "files": m.files, "concepts": m.concepts, "evidence": m.evidence, @@ -769,7 +844,11 @@ def _bulk_entry(m: Any) -> dict[str, Any] | None: 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.""" + 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.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set @@ -780,6 +859,7 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None continue groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) for (agent, user_id, session_id), entries in groups.items(): + entries.sort(key=lambda e: to_naive_utc(e["valid_at"]) or run.now) # stable for start in range(0, len(entries), MAX_BULK_ENTRIES): chunk = entries[start : start + MAX_BULK_ENTRIES] out = await handle_memory_bulk_set( @@ -790,9 +870,12 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None "agent": agent, "user_id": user_id, "session_id": session_id, + "detect_updates": False, "entries": chunk, } - ) + ), + conflict_check_cap=len(chunk), + reinforce=False, ) written = sum(1 for w in out.written if w.version) run.count(d, "memories", written) @@ -800,32 +883,20 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None run.count(d, "memories_not_admitted", declined) -async def _authority_documents(org: str, namespace: str, uris: list[str]) -> set[str]: - """Under the Postgres authority, which of `uris` the namespace holds or has held: a - head committed since its last publication to ClickHouse is there only.""" - from server.core import pg - from server.knowledge.store import pg_documents - - return await pg_documents.held_uris(org, namespace, uris) if pg.enabled() else set() - - -async def _documents(run: _Run, decisions: list[NsDecision]) -> None: +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.""" from server.knowledge.api.models_knowledge import KnowledgeUpsertInput from server.knowledge.app.writes import handle_knowledge_upsert - by_source = {(d.source_org, d.source): d for d in decisions} uris: dict[tuple[str, str], list[str]] = {} for doc in run.bundle.records("documents"): - if (d := by_source.get((doc["org"], doc["namespace"]))) is not None: + if (d := run.by_source.get((doc["org"], doc["namespace"]))) is not None: uris.setdefault((d.target_org, d.target), []).append(str(doc["source_uri"])) - seen = { - k: await _held_uris(run.ch, *k) | await _authority_documents(*k, v) for k, v in uris.items() - } + seen = {k: await _held_uris(run.ch, *k, v) for k, v in uris.items()} for doc in run.bundle.records("documents"): - d = by_source.get((doc["org"], doc["namespace"])) + d = run.by_source.get((doc["org"], doc["namespace"])) if d is None: continue if doc["source_uri"] in seen[(d.target_org, d.target)]: @@ -873,6 +944,7 @@ async def apply( 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)]) @@ -881,11 +953,11 @@ async def apply( await _blacklist(run, d, patterns) else: run.refusals[(d.source_org, d.source)] = refusals(patterns, d) - await _grants(run, todo) + await _grants(run) if p.sso_same_issuer: - await _links(run, todo) - await _memories(run, todo) - await _documents(run, todo) + 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: diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 6ce4c1aad78..c81c1044462 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -426,7 +426,10 @@ def test_a_merge_refuses_what_the_source_refuses_as_the_guard_does() -> 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 = {"orgs": {"a": "t", "b": "t"}, "subjects": {"b/alice": {"claim": "alice-b"}}} + 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"}} @@ -469,7 +472,7 @@ async def held_in(org: str, ns: str, *, after: Any = None, limit: int = 5000) -> return [h for h in heads if after is None or h > after][:2] async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: - yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch"} + yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch", "v": "ch.md"} async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: return {u for u in uris if u == "held.md"} @@ -479,7 +482,7 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} - assert await imp._authority_documents("o", "n", ["held.md", "new.md"]) == {"held.md"} + assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"ch.md", "held.md"} async def test_an_original_changed_after_the_dry_run_stops_its_document( @@ -503,10 +506,10 @@ async def nothing(*_: Any) -> set[str]: return set() monkeypatch.setattr(imp, "_held_uris", nothing) - monkeypatch.setattr(imp, "_authority_documents", nothing) - run: Any = SimpleNamespace(bundle=bundle, ch=None) + 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, [NsDecision("a", "n", "t", "n", "create")]) + await imp._documents(run) def test_an_original_changed_since_the_dry_run_stops_the_apply( @@ -606,15 +609,17 @@ 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.""" + 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 conflicts w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: - for k in ("k1", "k2"): - head = {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": k} + for agent, k in (("a", "k1"), ("b", "k1"), ("a", "k2")): + head = {"agent": agent, "user_id": "-", "session_id": "-", "memory_key": k} sink.write({"org": "acme", "namespace": "n", "memory_id": f"src-{k}", **head}) w.finish({"source": {"deployment_id": SOURCE}}) written: list[str] = [] @@ -626,17 +631,23 @@ async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str] async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: written.extend(r["memory_key"] for r in rows) + async def newest_wins(*_: Any, **__: Any) -> str: + return "newest_wins" + monkeypatch.setattr(imp, "_held_keys", held_keys) monkeypatch.setattr(imp, "_write_memories", write) + monkeypatch.setattr(conflicts, "namespace_conflict_policy", newest_wins) run: Any = SimpleNamespace( bundle=Bundle.open(tmp_path / "b"), ch=None, held={}, + reach={}, + 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, [NsDecision("acme", "n", "acme", "n", "create")]) - assert written == ["k2"] and counted == ["memories_the_target_holds"] + 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( @@ -665,14 +676,168 @@ async def upsert(body: Any) -> None: landed.append(body.content) monkeypatch.setattr(imp, "_held_uris", nothing) - monkeypatch.setattr(imp, "_authority_documents", nothing) 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), ) - merges = [NsDecision("acme", ns, "acme", "team", "merge") for ns in ("notes", "scratch")] - await imp._documents(run, merges) + await imp._documents(run) assert landed == ["notes"] and counted == ["documents", "documents_present"] + + +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_under_newest_wins_a_merge_holds_a_key_a_same_key_write_reaches( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Under newest_wins a same-key write retires the same user's rows in any agent and + session, and a write with no user anyone's: a merge counts those keys as held, the + ones it writes too. Under another policy only the exact key is held.""" + from types import SimpleNamespace + + from server.cli import instance_import as imp + from server.memory.app import conflicts + + heads = [ + ("b", "alice", "s2", "k1"), # alice holds k1 in another agent and session + ("a", "bob", "s1", "k1"), # bob holds none + ("a", "-", "-", "k1"), # alice's row has the key + ("a", "carol", "s1", "k3"), + ("b", "-", "-", "k3"), # carol's row, written just before, has it + ("a", "carol", "s2", "k3"), + ] + w = BundleWriter(tmp_path / "b") + with w.section("memories") as sink: + for agent, user, session, key in heads: + head = {"agent": agent, "user_id": user, "session_id": session, "memory_key": key} + sink.write({"org": "acme", "namespace": "n", **head}) + w.finish({"source": {"deployment_id": SOURCE}}) + policy = "" + written: list[tuple[str, str, str, str]] = [] + + async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: + return {("a", "alice", "s1", "k1")} + + async def current(*_: Any, **__: Any) -> str: + return policy + + async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: + written.extend((r["agent"], r["user_id"], r["session_id"], r["memory_key"]) for r in rows) + + monkeypatch.setattr(imp, "_held_keys", held_keys) + monkeypatch.setattr(imp, "_write_memories", write) + monkeypatch.setattr(conflicts, "namespace_conflict_policy", current) + for policy, expected in ( + ("newest_wins", [heads[1], heads[3]]), + ("auto_reinforce", heads), + ): + written.clear() + run: Any = SimpleNamespace( + bundle=Bundle.open(tmp_path / "b"), + ch=None, + held={}, + reach={}, + by_source={("acme", "n"): NsDecision("acme", "n", "acme", "team", "merge")}, + user_id=lambda o, u: u, + count=lambda *_: None, + ) + await imp._memories(run) + assert written == expected, policy + + +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.identity.api.models import _SnapshotMemoryRow + 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: + 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 + + monkeypatch.setattr(bulk_set, "handle_memory_bulk_set", bulk) + rows = [ + _SnapshotMemoryRow.model_validate(_head("n", key, valid_at=at, pinned=True)) + for key, at in ( + ("k-undated", None), + ("k-new", "2025-03-01T00:00:00Z"), + ("k-old", "2025-01-01T00:00:00"), + ) + ] + run: Any = SimpleNamespace(now=datetime(2026, 2, 1), count=count) + await imp._merge_memories(run, NsDecision("acme", "n", "acme", "team", "merge"), rows) + [(body, kw)] = calls + assert [e.memory_key for e in body.entries] == ["k-old", "k-new", "k-undated"] + assert kw == {"conflict_check_cap": 3, "reinforce": False} + assert body.detect_updates is False and not any(e.pinned for e in body.entries) + assert counts == {"memories": 2, "memories_not_admitted": 1} + + +async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> 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 + + 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)) + sink.write(_head("team", "gone", valid_at=late, status="tombstoned")) # left out + 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'", + ], p.problems From c4fca22a1ef93a24eee1f585c0eb0149453ab15a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:23:24 +0530 Subject: [PATCH 16/32] loom instance: a merge writes the newest of rows that would retire each other - A row the merge leaves out (a dropped user's, one not live, a refused one, one the target holds) is decided before it claims a key, so a live row of its key still lands. - Of the merged rows that would retire each other (one key under one agent, user and session, across two merged namespaces too, and under newest_wins as far as a same-key write reaches), the newest by valid_at, then created_at, then bundle order, lands; the receipt counts the others as memories_superseded. A first pass over the bundle finds them, a second writes them. - The dry run measures a merged value against its char_limit as memory.bulk_set does, which refuses the whole call. - Docs: under newest_wins admission may retire a target row stating the same attribute with another value unless the merged row is the older statement; the reach is of keys the target holds or has held; the dry run may name a row the run leaves out; the paragraph is rewrapped. - The integration test merges into a newest_wins namespace and reads back which rows are live. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 40 ++-- server/cli/instance_import.py | 175 ++++++++++++------ .../test_instance_consolidation.py | 47 ++++- tests/unit/test_instance_consolidation.py | 94 +++++++--- 4 files changed, 255 insertions(+), 101 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index d9acbb34d05..aedb67b9415 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -60,9 +60,11 @@ search once the embedding worker's next full pass embeds them ``` 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 run would write, so - one the target cannot store (a date past 2106, text the Postgres memory authority - refuses) is named here, not part way through the run. + 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: @@ -106,19 +108,25 @@ subjects: # "/": rule 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 same user holds it in any agent or - session, or, for a row with no user, where anyone holds it. Admission may still mark a target row a merged one - contradicts as conflicted, and, with the conflict resolver on, retire one it judges the - merged row updates. The source's refusals that reach the source namespace refuse the - rows it brings, and none is stored on the target's namespace. It writes live facts - only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the target - namespace holds or has held is left as it is. Of two namespaces merged into one, the - first in the bundle brings an address or key both hold. Admission may decline a memory - (a pinned peer, or a restatement it folds into a row): the receipt counts it as - `memories_not_admitted`. Per-type settings, policies and the guide land with a created - namespace only. + 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. Of the rows + the bundle brings that would retire each other (one key under one agent, user and + session, across two merged namespaces too, and under `newest_wins` as far as a + same-key write reaches), the newest by `valid_at`, then `created_at`, lands, and the + receipt counts the others as `memories_superseded`. 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. The source's refusals that reach the source + namespace refuse the rows it brings, and none is stored on the target's namespace. It + writes live facts only: a row in another state, or past its expiry, is left out, 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. A document whose + `source_uri` the target namespace holds or has held is left as it is, and of two + namespaces merged into one, the first in the bundle brings an address both hold. + Admission may decline a memory (a pinned peer, or a restatement it folds into a row): + the receipt counts it as `memories_not_admitted`. Per-type settings, policies and the + guide land with a created namespace only. - **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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 2e583ecbd7e..001b126d211 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -24,6 +24,7 @@ import json import time import uuid +from collections import Counter from collections.abc import Iterable, Mapping from datetime import UTC, datetime from typing import Any @@ -255,11 +256,11 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr # 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"): - into = todo.get((m["org"], m["namespace"])) - if into is None or run.user_id(into.source_org, str(m.get("user_id") or "-")) is None: + if (into := todo.get((m["org"], m["namespace"]))) is None: continue try: - _built(into, m) + if (row := _row(run, into, m)) is not None: + _built(into, row) 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) @@ -280,20 +281,23 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) -def _built(d: NsDecision, m: Mapping[str, Any]) -> None: - """Build source head `m` as the apply writes it into `d`'s namespace, raising where the +def _built(d: NsDecision, row: Any) -> None: + """Build source row `row` as the apply writes it into `d`'s namespace, raising where the target refuses it.""" - from server.identity.api.models import _SnapshotMemoryRow + from server.core.errors import ValidationError from server.memory.api.models_bulk import _BulkSetEntry from server.memory.app import snapshot_rows as snap - row = _SnapshotMemoryRow.model_validate( - {k: v for k, v in m.items() if k not in ("org", "namespace")} - ) if d.action == "merge": if (entry := _bulk_entry(row)) is None: return # left out _BulkSetEntry.model_validate(entry) + # 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( @@ -701,65 +705,122 @@ async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[ async def _memories(run: _Run) -> None: - """Each source head whose key the target namespace never held: a resumed run writes - nothing back over what someone wrote there since, nor a merge over the target's own. - Under `newest_wins` a same-key write retires older rows past its own agent and session, - so a merged key also counts as held where it would retire one: the same user's in any - agent and session, and, for a row with no user, anyone's.""" - from server.memory.app.conflicts import namespace_conflict_policy - - batch: dict[tuple[str, str], list[dict[str, Any]]] = {} - for m in run.bundle.records("memories"): - d = run.by_source.get((m["org"], m["namespace"])) - if d is None: - continue - user = run.user_id(d.source_org, str(m.get("user_id") or "-")) - if user is None: - run.count(d, "memories_of_dropped_users") + """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 that would retire each other, the newest by `valid_at`, then `created_at`, then + the first in the bundle, and counts the others as `memories_superseded`. The rows of + one key under one agent, user and session retire each other; under `newest_wins`, + where a same-key write reaches past its own agent and session, so do one user's rows + of a key, and a row with no user and any row of its key.""" + batch: dict[tuple[str, str], list[Any]] = {} + newest: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} + named: dict[tuple[Any, ...], tuple[datetime, int]] = {} # newest_wins: a key's newest named + kept: dict[tuple[str, str], int] = {} # merged rows kept, per source namespace + for i, m in enumerate(run.bundle.records("memories")): + if (got := await _kept(run, m)) is None: continue - m["user_id"] = user - t, key = (d.target_org, d.target), str(m["memory_key"]) - if t not in run.held: # once per target namespace: each write adds its key below - run.held[t] = await _held_keys(run.ch, *t) - if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": - run.reach[t] = {r for _, u, _, k in run.held[t] for r in ((u, k), (None, k))} - reach = run.reach.get(t) - writer = None if is_anonymous_user(user) else user - if key_in_namespace(m) in run.held[t] or ( - d.action == "merge" and reach is not None and (writer, key) in reach - ): - run.count(d, "memories_the_target_holds") + d, row = got + k, t = (d.source_org, d.source), (d.target_org, d.target) + if d.action == "create": + run.held[t].add(key_in_namespace(m)) + await _batched(run, batch, d, row) continue - run.held[t].add(key_in_namespace(m)) - if reach is not None: - reach.update(((user, key), (None, key))) - k = (d.source_org, d.source) - rows = batch.setdefault(k, []) - rows.append(m) - if len(rows) >= _BATCH: - await _write_memories(run, d, rows) - rows.clear() + kept[k] = kept.get(k, 0) + 1 + rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) + group: tuple[Any, ...] = (t, key_in_namespace(m)) + if t in run.reach: + user = None if is_anonymous_user(row.user_id) else row.user_id + group = (t, user, row.memory_key) + if user is not None: + named[(t, row.memory_key)] = max(rank, named.get((t, row.memory_key), rank)) + if group not in newest or rank > newest[group][0]: + newest[group] = (rank, (*k, str(m["memory_id"]))) + winners = set() + for group, (rank, ref) in newest.items(): + if len(group) == 3: # newest_wins: a row with no user and a named one reach each other + t, user, key = group + anon = newest.get((t, None, key)) + rival = named.get((t, key)) if user is None else anon[0] if anon else None + if rival is not None and rival > rank: + continue + winners.add(ref) + won = Counter(ref[:2] for ref in winners) + for k, n in kept.items(): + if n > won[k]: + run.count(run.by_source[k], "memories_superseded", n - won[k]) + if winners: # a second read: the rows a merge writes are known once all are read + for m in run.bundle.records("memories"): + if (m["org"], m["namespace"], str(m["memory_id"])) in winners: + 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) -async def _write_memories(run: _Run, d: NsDecision, raw: list[dict[str, Any]]) -> None: +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.""" 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 + return _SnapshotMemoryRow.model_validate( + {k: v for k, v in m.items() if k not in ("org", "namespace")} + ) + + +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 (`_bulk_entry`), 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.""" from server.memory.app import blacklist_guard + from server.memory.app.conflicts import namespace_conflict_policy + + 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 _bulk_entry(row) is None: + run.count(d, "memories_not_live") + return None + t = (d.target_org, d.target) + if t not in run.held: # once per target namespace + run.held[t] = await _held_keys(run.ch, *t) + if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": + run.reach[t] = {r for _, u, _, k in run.held[t] for r in ((u, k), (None, k))} + writer = None if is_anonymous_user(row.user_id) else row.user_id + if key_in_namespace(m) in run.held[t] or ( + d.action == "merge" and (writer, row.memory_key) in run.reach.get(t, ()) + ): + 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 _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 - kept = [] - for m in raw: - row = _SnapshotMemoryRow.model_validate( - {k: v for k, v in m.items() if k not in ("org", "namespace")} - ) - 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") - else: - kept.append(row) with _for(d): if d.action == "merge": await _merge_memories(run, d, kept) diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index fe48aa1037c..6572274a635 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -225,6 +225,22 @@ async def _seed_source(ch: Any, src: _Api) -> None: 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, + ) src.set("notes", "token", TOKEN) # written before the source refused it for pattern in TOKENS: src.op( @@ -279,12 +295,25 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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") + 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) @@ -360,6 +389,22 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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. Read from the table: memory.get falls back to the key's row in any session. + rows = await ch.query_all( + "SELECT memory_key, 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')" + SEQ, + params={"org": dst_org}, + ) + assert { + (r["memory_key"], r["session_id"], r["status"], 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"), + } + doc = dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md") assert (doc["found"], doc["content"], doc["title"]) == ( True, diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index c81c1044462..2f5051a7d0b 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -614,13 +614,12 @@ async def test_a_resumed_run_writes_no_key_the_created_namespace_held( from types import SimpleNamespace from server.cli import instance_import as imp - from server.memory.app import conflicts + 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")): - head = {"agent": agent, "user_id": "-", "session_id": "-", "memory_key": k} - sink.write({"org": "acme", "namespace": "n", "memory_id": f"src-{k}", **head}) + sink.write(_head("n", k, agent=agent)) w.finish({"source": {"deployment_id": SOURCE}}) written: list[str] = [] counted: list[str] = [] @@ -628,20 +627,26 @@ async def test_a_resumed_run_writes_no_key_the_created_namespace_held( async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: return {("a", "-", "-", "k1")} - async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: - written.extend(r["memory_key"] for r in rows) + 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), @@ -711,33 +716,44 @@ def _head(namespace: str, key: str, **row: Any) -> dict[str, Any]: } -async def test_under_newest_wins_a_merge_holds_a_key_a_same_key_write_reaches( +async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_other( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """Under newest_wins a same-key write retires the same user's rows in any agent and - session, and a write with no user anyone's: a merge counts those keys as held, the - ones it writes too. Under another policy only the exact key is held.""" + """A row the merge does not carry claims no key, so a live row of its key lands. Of rows + that would retire each other the newest lands: one key under one agent, user and + session, across two merged namespaces too, and under newest_wins the same user's key in + any agent and session, and a row with no user with any of its key. Under newest_wins a + key the target holds that far is held.""" from types import SimpleNamespace from server.cli import instance_import as imp - from server.memory.app import conflicts + from server.memory.app import blacklist_guard, conflicts heads = [ - ("b", "alice", "s2", "k1"), # alice holds k1 in another agent and session - ("a", "bob", "s1", "k1"), # bob holds none - ("a", "-", "-", "k1"), # alice's row has the key - ("a", "carol", "s1", "k3"), - ("b", "-", "-", "k3"), # carol's row, written just before, has it - ("a", "carol", "s2", "k3"), + ("n", "b", "alice", "s2", "k1", None, "active"), # alice holds k1 on the target + ("n", "a", "bob", "s1", "k1", "2024", "active"), + ("n", "a", "-", "-", "k1", None, "active"), # alice's target row has the key + ("n", "a", "carol", "s1", "k3", "2024", "active"), + ("n", "b", "-", "-", "k3", "2023", "active"), # older than carol's + ("n", "a", "carol", "s2", "k3", "2025", "active"), # later in the bundle, and newer + ("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 ] w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: - for agent, user, session, key in heads: - head = {"agent": agent, "user_id": user, "session_id": session, "memory_key": key} - sink.write({"org": "acme", "namespace": "n", **head}) + for i, (ns, agent, user, session, key, year, status) in enumerate(heads): + identity = {"agent": agent, "user_id": user, "session_id": session} + at = f"{year}-01-01T00:00:00" if year else None + sink.write( + _head( + ns, key, memory_id=str(uuid.UUID(int=i)), valid_at=at, status=status, **identity + ) + ) w.finish({"source": {"deployment_id": SOURCE}}) policy = "" - written: list[tuple[str, str, str, str]] = [] + written: list[int] = [] + counted: dict[tuple[str, str], int] = {} async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: return {("a", "alice", "s1", "k1")} @@ -745,28 +761,49 @@ async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str] async def current(*_: Any, **__: Any) -> str: return policy - async def write(run: Any, d: Any, rows: list[dict[str, Any]]) -> None: - written.extend((r["agent"], r["user_id"], r["session_id"], r["memory_key"]) for r in rows) + 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) - for policy, expected in ( - ("newest_wins", [heads[1], heads[3]]), - ("auto_reinforce", heads), + monkeypatch.setattr(blacklist_guard, "find_match", nothing) + for policy, expected, counts in ( + ( + "newest_wins", + [5, 7, 8], + {"memories_the_target_holds": 2, "memories_not_live": 1, "memories_superseded": 3}, + ), + ( + "auto_reinforce", + [0, 2, 3, 4, 5, 7, 8], + {"memories_not_live": 1, "memories_superseded": 1}, + ), ): written.clear() + counted.clear() run: Any = SimpleNamespace( bundle=Bundle.open(tmp_path / "b"), ch=None, held={}, reach={}, - by_source={("acme", "n"): NsDecision("acme", "n", "acme", "team", "merge")}, + 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=lambda *_: None, + count=count, ) await imp._memories(run) assert written == expected, policy + assert counted == {("n", what): n for what, n in counts.items()}, policy async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: @@ -820,6 +857,8 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> 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", "gone", valid_at=late, status="tombstoned")) # left out sink.write(_head("team", "theirs", valid_at=late, user_id="alice")) # a dropped user sink.write(_head("old", "skipped", valid_at=late)) @@ -840,4 +879,5 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> assert [x.split(":")[0] for x in p.problems] == [ "acme/notes memory 'late'", "acme/team memory 'odd'", + "acme/team memory 'long'", ], p.problems From adf898f310e5f8450644be85f0a941b837b73c21 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:41:54 +0530 Subject: [PATCH 17/32] loom instance: a merged row with no user lands beside a named one of its key - Under newest_wins a named write never retires a row with no user, and a write with no user retires the named rows of its key written before it. The merge's rows with no user now compete only with each other, one user's rows only with that user's, and the rows with no user are written in a pass before the named ones: both land, as the source served them, and a run resumed between the two passes writes the same rows. - The exact-identity and newest_wins groups are kept apart, and the counter of merged rows kept is named `carried`. - Docs and docstrings: the newest by valid_at (its created_at where it has none), then the first in the bundle; the order of the two passes. - Tests: a row with no user beside a newer named one, a run resumed after the rows with no user, and the receipt's `memories_superseded` end to end. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 37 ++++++----- server/cli/instance_import.py | 63 +++++++++---------- .../test_instance_consolidation.py | 2 + tests/unit/test_instance_consolidation.py | 25 +++++--- 4 files changed, 69 insertions(+), 58 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index aedb67b9415..7f82f790058 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -110,23 +110,26 @@ subjects: # "/": rule 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. Of the rows - the bundle brings that would retire each other (one key under one agent, user and - session, across two merged namespaces too, and under `newest_wins` as far as a - same-key write reaches), the newest by `valid_at`, then `created_at`, lands, and the - receipt counts the others as `memories_superseded`. 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. The source's refusals that reach the source - namespace refuse the rows it brings, and none is stored on the target's namespace. It - writes live facts only: a row in another state, or past its expiry, is left out, 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. A document whose - `source_uri` the target namespace holds or has held is left as it is, and of two - namespaces merged into one, the first in the bundle brings an address both hold. - Admission may decline a memory (a pinned peer, or a restatement it folds into a row): - the receipt counts it as `memories_not_admitted`. Per-type settings, policies and the - guide land with a created namespace only. + 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. 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. The source's refusals that reach the source namespace + refuse the rows it brings, and none is stored on the target's namespace. It writes + live facts only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the + target namespace holds or has held is left as it is, and of two namespaces merged into + one, the first in the bundle brings an address both hold. Admission may decline a + memory (a pinned peer, or a restatement it folds into a row): the receipt counts it as + `memories_not_admitted`. Per-type settings, policies and the guide land with a created + namespace only. - **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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 001b126d211..f3201189c12 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -707,15 +707,17 @@ async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[ 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 that would retire each other, the newest by `valid_at`, then `created_at`, then - the first in the bundle, and counts the others as `memories_superseded`. The rows of - one key under one agent, user and session retire each other; under `newest_wins`, - where a same-key write reaches past its own agent and session, so do one user's rows - of a key, and a row with no user and any row of its key.""" + 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 no + row with no user: those go first, so both land, as the source served them.""" batch: dict[tuple[str, str], list[Any]] = {} - newest: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} - named: dict[tuple[Any, ...], tuple[datetime, int]] = {} # newest_wins: a key's newest named - kept: dict[tuple[str, str], int] = {} # merged rows kept, per source namespace + exact: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} + scoped: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} + carried: 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 @@ -725,37 +727,32 @@ async def _memories(run: _Run) -> None: run.held[t].add(key_in_namespace(m)) await _batched(run, batch, d, row) continue - kept[k] = kept.get(k, 0) + 1 + carried[k] += 1 rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) - group: tuple[Any, ...] = (t, key_in_namespace(m)) - if t in run.reach: + group: tuple[Any, ...] + if t in run.reach: # newest_wins: (target, user or None, key) user = None if is_anonymous_user(row.user_id) else row.user_id - group = (t, user, row.memory_key) - if user is not None: - named[(t, row.memory_key)] = max(rank, named.get((t, row.memory_key), rank)) - if group not in newest or rank > newest[group][0]: - newest[group] = (rank, (*k, str(m["memory_id"]))) - winners = set() - for group, (rank, ref) in newest.items(): - if len(group) == 3: # newest_wins: a row with no user and a named one reach each other - t, user, key = group - anon = newest.get((t, None, key)) - rival = named.get((t, key)) if user is None else anon[0] if anon else None - if rival is not None and rival > rank: - continue - winners.add(ref) - won = Counter(ref[:2] for ref in winners) - for k, n in kept.items(): + groups, group = scoped, (t, user, row.memory_key) + else: + groups, group = exact, (t, key_in_namespace(m)) + if group not in groups or rank > groups[group][0]: + groups[group] = (rank, (*k, str(m["memory_id"]))) + first = {ref for _, ref in exact.values()} + 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 first | then) + for k, n in carried.items(): if n > won[k]: run.count(run.by_source[k], "memories_superseded", n - won[k]) - if winners: # a second read: the rows a merge writes are known once all are read - for m in run.bundle.records("memories"): - if (m["org"], m["namespace"], str(m["memory_id"])) in winners: + for wave in (first, then): # a read each: what a merge writes is known once all is read + for m in run.bundle.records("memories") if wave else (): + 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) + 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: diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 6572274a635..892cd4ae666 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -369,6 +369,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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) @@ -404,6 +405,7 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("employer", "s2", "active", "the deploy window opens at nine"), ("city", "s1", "active", "the office is in Paris"), } + assert receipt["counts"][f"{dst_org}/team"]["memories_superseded"] == 1 # employer in s1 doc = dst.op("knowledge.get", namespace="team-legacy", source_uri="runbook.md") assert (doc["found"], doc["content"], doc["title"]) == ( diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 2f5051a7d0b..6e1cf7eba2d 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -720,10 +720,11 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe 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 - that would retire each other the newest lands: one key under one agent, user and - session, across two merged namespaces too, and under newest_wins the same user's key in - any agent and session, and a row with no user with any of its key. Under newest_wins a - key the target holds that far is held.""" + 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 @@ -734,7 +735,7 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("n", "a", "bob", "s1", "k1", "2024", "active"), ("n", "a", "-", "-", "k1", None, "active"), # alice's target row has the key ("n", "a", "carol", "s1", "k3", "2024", "active"), - ("n", "b", "-", "-", "k3", "2023", "active"), # older than carol's + ("n", "b", "-", "-", "k3", "2023", "active"), # lands beside carol's ("n", "a", "carol", "s2", "k3", "2025", "active"), # later in the bundle, and newer ("n", "a", "dave", "s1", "k4", "2026", "superseded"), # not carried ("n", "a", "dave", "s2", "k4", "2024", "active"), @@ -755,8 +756,10 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe written: list[int] = [] counted: dict[tuple[str, str], int] = {} + held = {("a", "alice", "s1", "k1")} + async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: - return {("a", "alice", "s1", "k1")} + return set(held) async def current(*_: Any, **__: Any) -> str: return policy @@ -777,8 +780,8 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [5, 7, 8], - {"memories_the_target_holds": 2, "memories_not_live": 1, "memories_superseded": 3}, + [4, 5, 7, 8], # the row with no user first + {"memories_the_target_holds": 2, "memories_not_live": 1, "memories_superseded": 2}, ), ( "auto_reinforce", @@ -804,6 +807,12 @@ def count(d: Any, what: str, n: int = 1) -> None: await imp._memories(run) assert written == expected, policy assert counted == {("n", what): n for what, n in counts.items()}, policy + # Resumed after the rows with no user: the target holds row 4, and the rest still land. + policy, held = "newest_wins", {("a", "alice", "s1", "k1"), ("b", "-", "-", "k3")} + written.clear() + run.held, run.reach = {}, {} + await imp._memories(run) + assert written == [5, 7, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: From e840a2dff54cbb2aaf793af1f5fd3af08a5108cf Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:54:32 +0530 Subject: [PATCH 18/32] loom instance: the merge order of rows with no user is tested on its own - The unit test puts the row with no user after the named row of its key in the bundle, so only writing the rows with no user first passes it. - The integration test merges an end user's newer row beside the row with no user of its key into the newest_wins target, and reads both back live. - The merged-row counter is `merged`, not the module's `carried`; the docstring says the rows with no user are written first; the second pass is a plain `if`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_import.py | 20 ++++++----- .../test_instance_consolidation.py | 35 ++++++++++++++----- tests/unit/test_instance_consolidation.py | 8 ++--- 3 files changed, 42 insertions(+), 21 deletions(-) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index f3201189c12..a9d94d5b82d 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -712,12 +712,13 @@ async def _memories(run: _Run) -> None: `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 no - row with no user: those go first, so both land, as the source served them.""" + 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.""" batch: dict[tuple[str, str], list[Any]] = {} exact: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} scoped: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} - carried: Counter[tuple[str, str]] = Counter() # merged rows kept, per source namespace + 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 @@ -727,7 +728,7 @@ async def _memories(run: _Run) -> None: run.held[t].add(key_in_namespace(m)) await _batched(run, batch, d, row) continue - carried[k] += 1 + merged[k] += 1 rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) group: tuple[Any, ...] if t in run.reach: # newest_wins: (target, user or None, key) @@ -741,14 +742,15 @@ async def _memories(run: _Run) -> None: 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 first | then) - for k, n in carried.items(): + for k, n in merged.items(): if n > won[k]: run.count(run.by_source[k], "memories_superseded", n - won[k]) for wave in (first, then): # a read each: what a merge writes is known once all is read - for m in run.bundle.records("memories") if wave else (): - 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)) + 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) diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 892cd4ae666..02feff355ef 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -241,6 +241,20 @@ async def _seed_source(ch: Any, src: _Api) -> None: 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, + ) src.set("notes", "token", TOKEN) # written before the source refused it for pattern in TOKENS: src.op( @@ -350,10 +364,13 @@ async def test_an_org_moves_into_a_live_one_under_the_map( # 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() @@ -392,18 +409,20 @@ async def test_an_org_moves_into_a_live_one_under_the_map( # 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. Read from the table: memory.get falls back to the key's row in any session. + # 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, session_id, status, value FROM loom.memory FINAL " + "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')" + SEQ, + "AND memory_key IN ('employer', 'city', 'owner')" + SEQ, params={"org": dst_org}, ) - assert { - (r["memory_key"], r["session_id"], r["status"], 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"), + 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 diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 6e1cf7eba2d..3f2d8df21fe 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -735,8 +735,8 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("n", "a", "bob", "s1", "k1", "2024", "active"), ("n", "a", "-", "-", "k1", None, "active"), # alice's target row has the key ("n", "a", "carol", "s1", "k3", "2024", "active"), - ("n", "b", "-", "-", "k3", "2023", "active"), # lands beside carol's ("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 @@ -780,7 +780,7 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [4, 5, 7, 8], # the row with no user first + [5, 4, 7, 8], # the row with no user first {"memories_the_target_holds": 2, "memories_not_live": 1, "memories_superseded": 2}, ), ( @@ -807,12 +807,12 @@ def count(d: Any, what: str, n: int = 1) -> None: await imp._memories(run) assert written == expected, policy assert counted == {("n", what): n for what, n in counts.items()}, policy - # Resumed after the rows with no user: the target holds row 4, and the rest still land. + # Resumed after the rows with no user: the target holds row 5, and the rest still land. policy, held = "newest_wins", {("a", "alice", "s1", "k1"), ("b", "-", "-", "k3")} written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [5, 7, 8] + assert written == [4, 7, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: From 828dc3d283574960ce4f04b4df3cb7321e58bff5 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:12:06 +0530 Subject: [PATCH 19/32] loom instance: a merged row past its expiry is tested on a fixed clock - `_bulk_entry` reads the time through `utc_now`, so the unit test pins the clock: a newer row of a key past its expiry is left out and counted as not live, and the older live row of its key lands. - The rerun state compares every row of the merged `team`, with its status and version, so a rerun that writes or retires a merged `newest_wins` row fails it; it replaces the single `team` key read through `memory.get`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_import.py | 4 +-- .../test_instance_consolidation.py | 9 +++--- tests/unit/test_instance_consolidation.py | 30 +++++++++---------- 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index a9d94d5b82d..35544664280 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -40,7 +40,7 @@ landed_row, plan, ) -from server.core.datetimes import to_naive_utc +from server.core.datetimes import to_naive_utc, utc_now from server.core.naming import is_anonymous_user from server.core.principals import USER from server.memory.store.rows import key_in_namespace @@ -876,7 +876,7 @@ def _bulk_entry(m: Any) -> dict[str, Any] | None: ttl = None if m.expires_at is not None: expires = m.expires_at if m.expires_at.tzinfo else m.expires_at.replace(tzinfo=UTC) - ttl = int((expires - datetime.now(UTC)).total_seconds()) + ttl = int((expires - utc_now()).total_seconds()) # as each row is written if ttl <= 0: return None return { diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 02feff355ef..843bc2e88fc 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -275,13 +275,14 @@ 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": { - (ns, key): dst.get(ns, key)["version"] - for ns, key in [("team-legacy", k) for k in KEYS] + [("team", "standup")] - }, + "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}" diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 3f2d8df21fe..9018a44fb2e 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -6,7 +6,7 @@ import gzip import stat import uuid -from datetime import datetime +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -730,27 +730,26 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe from server.cli import instance_import as imp from server.memory.app import blacklist_guard, conflicts - heads = [ - ("n", "b", "alice", "s2", "k1", None, "active"), # alice holds k1 on the target + 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", None, "active"), # alice's target row has the key + ("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"), ] w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: - for i, (ns, agent, user, session, key, year, status) in enumerate(heads): + for i, (ns, agent, user, session, key, year, status, *expiry) in enumerate(heads): identity = {"agent": agent, "user_id": user, "session_id": session} at = f"{year}-01-01T00:00:00" if year else None - sink.write( - _head( - ns, key, memory_id=str(uuid.UUID(int=i)), valid_at=at, status=status, **identity - ) - ) + row = {"valid_at": at, "status": status, "expires_at": next(iter(expiry), None)} + sink.write(_head(ns, key, memory_id=str(uuid.UUID(int=i)), **row, **identity)) w.finish({"source": {"deployment_id": SOURCE}}) policy = "" written: list[int] = [] @@ -777,16 +776,17 @@ def count(d: Any, what: str, n: int = 1) -> None: monkeypatch.setattr(imp, "_write_memories", write) monkeypatch.setattr(conflicts, "namespace_conflict_policy", current) monkeypatch.setattr(blacklist_guard, "find_match", nothing) + monkeypatch.setattr(imp, "utc_now", lambda: datetime(2026, 2, 1, tzinfo=UTC)) for policy, expected, counts in ( ( "newest_wins", - [5, 4, 7, 8], # the row with no user first - {"memories_the_target_holds": 2, "memories_not_live": 1, "memories_superseded": 2}, + [5, 4, 7, 10, 8], # the row with no user first + {"memories_the_target_holds": 2, "memories_not_live": 2, "memories_superseded": 2}, ), ( "auto_reinforce", - [0, 2, 3, 4, 5, 7, 8], - {"memories_not_live": 1, "memories_superseded": 1}, + [0, 2, 3, 4, 5, 7, 10, 8], + {"memories_not_live": 2, "memories_superseded": 1}, ), ): written.clear() @@ -812,7 +812,7 @@ def count(d: Any, what: str, n: int = 1) -> None: written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [4, 7, 8] + assert written == [4, 7, 10, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: From e8557642aaeb95886d9d98a6975dfadf1290e52f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:36:04 +0530 Subject: [PATCH 20/32] loom instance: a merge decides a row live once, at the run's start - `_live` decides whether a merge carries a row against the run's start, so the pass that ranks rows and the write agree: a row that expires between them was ranked the winner of its key, then dropped, and its key landed with no row. `_bulk_entry` takes the expiry from the time of writing, at least a second, so such a row lands and expires as it did on the source. - The plan decides only the subjects of namespaces it does not skip: a skipped namespace's grants, owner and end users move nowhere. - A test runs the import with a stale `--expect-plan`: exit 2, with neither the acceptance check nor the apply called. - `as_aware_utc` replaces a copy of it; the docs say a merged row keeps its validity, and only a created namespace its `created_at` and attestation. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 37 +++++++------- server/cli/instance_import.py | 59 +++++++++++------------ server/cli/instance_plan.py | 15 ++++-- tests/unit/test_instance_consolidation.py | 47 ++++++++++++++---- 4 files changed, 95 insertions(+), 63 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 7f82f790058..774d1f33906 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -14,7 +14,7 @@ run, with their settings. To move a whole deployment onto new hosts, see | 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 | -| Memories: every live head, with its `created_at`, validity and attestation | Documents an end user wrote, which the target could not erase as theirs: 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 they synced 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 | @@ -122,14 +122,14 @@ subjects: # "/": rule row is the older statement by `valid_at`, and, with the conflict resolver on, one it judges the merged row updates. The source's refusals that reach the source namespace refuse the rows it brings, and none is stored on the target's namespace. It writes - live facts only: a row in another state, or past its expiry, is left out, 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. A document whose `source_uri` the - target namespace holds or has held is left as it is, and of two namespaces merged into - one, the first in the bundle brings an address both hold. Admission may decline a - memory (a pinned peer, or a restatement it folds into a row): the receipt counts it as - `memories_not_admitted`. Per-type settings, policies and the guide land with a created - namespace only. + live facts only: a row in another state, or past its expiry when the run starts, is + left out, 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. A document + whose `source_uri` the target namespace holds or has held is left as it is, and of two + namespaces merged into one, the first in the bundle brings an address both hold. + Admission may decline a memory (a pinned peer, or a restatement it folds into a row): + the receipt counts it as `memories_not_admitted`. Per-type settings, policies and the + guide land with a created namespace only. - **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 @@ -153,15 +153,16 @@ subjects: # "/": rule 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.** 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, 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. Any +- **Subjects.** The plan decides the subjects of every namespace it does not skip: their + grants, owners and end users. 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, 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. Any other subject needs a mapping or `drop`. - **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 diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 35544664280..a519e5e5b60 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -26,7 +26,7 @@ import uuid from collections import Counter from collections.abc import Iterable, Mapping -from datetime import UTC, datetime +from datetime import datetime from typing import Any from server.cli.instance_bundle import Bundle, BundleError @@ -40,7 +40,7 @@ landed_row, plan, ) -from server.core.datetimes import to_naive_utc, utc_now +from server.core.datetimes import as_aware_utc, to_naive_utc, utc_now from server.core.naming import is_anonymous_user from server.core.principals import USER from server.memory.store.rows import key_in_namespace @@ -150,19 +150,20 @@ def build_plan( signs_in: Mapping[str, list[str]], ) -> Plan: rows = list(bundle.records("namespaces")) - subjects: dict[str, set[str]] = {} + subjects: dict[str, dict[str, set[str]]] = {} - def add(org: Any, subject: Any) -> None: - subjects.setdefault(str(org), set()).add(str(subject)) + def add(row: Any, subject: Any) -> None: + by_ns = subjects.setdefault(str(row["org"]), {}) + by_ns.setdefault(str(row["namespace"]), set()).add(str(subject)) for g in bundle.records("grants"): - add(g["org"], g["subject"]) + add(g, g["subject"]) for r in rows: if not is_account(r) and r.get("owner_email"): - add(r["org"], r["owner_email"]) + add(r, r["owner_email"]) for m in bundle.records("memories"): # an end user's rows follow their decision if m.get("user_id") not in (None, "", "-"): - add(m["org"], f"{USER}{m['user_id']}") + add(m, 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( @@ -260,7 +261,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr continue try: if (row := _row(run, into, m)) is not None: - _built(into, row) + _built(into, row, run.now) 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) @@ -281,7 +282,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) -def _built(d: NsDecision, row: Any) -> None: +def _built(d: NsDecision, row: Any, now: datetime) -> None: """Build source row `row` as the apply writes it into `d`'s namespace, raising where the target refuses it.""" from server.core.errors import ValidationError @@ -289,9 +290,9 @@ def _built(d: NsDecision, row: Any) -> None: from server.memory.app import snapshot_rows as snap if d.action == "merge": - if (entry := _bulk_entry(row)) is None: + if not _live(row, now): return # left out - _BulkSetEntry.model_validate(entry) + _BulkSetEntry.model_validate(entry := _bulk_entry(row)) # As memory.bulk_set measures it, which refuses the whole call. if ( entry["char_limit"] is not None @@ -785,7 +786,7 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: if (row := _row(run, d, m)) is None: run.count(d, "memories_of_dropped_users") return None - if d.action == "merge" and _bulk_entry(row) is 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) @@ -866,19 +867,20 @@ async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, s return held -def _bulk_entry(m: Any) -> dict[str, Any] | None: - """A source head as a `memory.bulk_set` entry, None when it is no live fact: a row in - another state, or one past its expiry. 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.""" - if m.status != _MERGED_STATUS: - return None +def _live(m: Any, now: datetime) -> bool: + """Whether a merge carries source head `m`: an active row, not past its expiry at + `now`, the run's start, so every pass of a run decides it alike.""" + return m.status == _MERGED_STATUS 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: - expires = m.expires_at if m.expires_at.tzinfo else m.expires_at.replace(tzinfo=UTC) - ttl = int((expires - utc_now()).total_seconds()) # as each row is written - if ttl <= 0: - return 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, @@ -913,11 +915,8 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None from server.memory.app.bulk_set import handle_memory_bulk_set groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} - for m in memories: - if (entry := _bulk_entry(m)) is None: - run.count(d, "memories_not_live") - continue - groups.setdefault((m.agent, m.user_id, m.session_id), []).append(entry) + for m in memories: # each live at the run's start (`_kept`) + groups.setdefault((m.agent, m.user_id, m.session_id), []).append(_bulk_entry(m)) for (agent, user_id, session_id), entries in groups.items(): entries.sort(key=lambda e: to_naive_utc(e["valid_at"]) or run.now) # stable for start in range(0, len(entries), MAX_BULK_ENTRIES): diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 5b2b17d71f9..511e9112f02 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -615,15 +615,16 @@ def plan( rules: MapFile, namespace_rows: Iterable[Mapping[str, Any]], selected: Mapping[str, list[str]], - grant_subjects: Mapping[str, set[str]], + grant_subjects: 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`. `grant_subjects` is each source org's grant subjects, namespace - owners and memory users (`user:`); `links` its accounts' single sign-on link + deployment `source`. `grant_subjects` is, per source org and namespace, its grant + subjects, owner and memory users (`user:`), which only a namespace the plan does + not skip needs decided; `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( @@ -684,7 +685,10 @@ def plan( _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} - for subject in sorted(grant_subjects.get(org, set()) - decided): + skipped = {d.source for d in p.namespaces if d.source_org == org and d.action == "skip"} + lands = grant_subjects.get(org, {}).items() + needed = {s for ns, subs in lands if ns not in skipped for s in subs} + for subject in sorted(needed - decided): _plan_subject(o, subject) _check_users(o) for s in p.subjects: @@ -701,7 +705,8 @@ def plan( known = { "orgs": set(selected), "namespaces": names, - "subjects": handles | {f"{org}/{s}" for org, subs in grant_subjects.items() for s in subs}, + "subjects": handles + | {f"{o}/{s}" for o, by_ns in grant_subjects.items() for ss in by_ns.values() for s in ss}, } for section, keys in ( ("orgs", rules.orgs), diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 9018a44fb2e..a7fe1a9a214 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -52,15 +52,19 @@ def _plan( revoked: set[str] | None = None, links: dict[str, dict[str, list[str]]] | None = None, bundle: str = "b1", + by_namespace: dict[str, dict[str, set[str]]] | None = None, ) -> Any: + """`subjects` holds on every namespace of its org; `by_namespace` per namespace.""" orgs = sorted({r["org"] for r in rows}) + by_org = subjects if isinstance(subjects, dict) else {"acme": subjects or set()} + every = {o: {r["namespace"]: s for r in rows if r["org"] == o} for o, s 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}, - grant_subjects=subjects if isinstance(subjects, dict) else {"acme": subjects or set()}, + grant_subjects=every if by_namespace is None else by_namespace, links=links or {}, revoked=revoked or set(), targets=targets or {"acme": target or EMPTY}, @@ -164,6 +168,18 @@ def test_end_users_of_a_shared_target_org_need_the_map() -> None: 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": {"x"}, "scratch": {"group:eng", "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_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"}} @@ -515,8 +531,9 @@ async def nothing(*_: Any) -> set[str]: def test_an_original_changed_since_the_dry_run_stops_the_apply( monkeypatch: pytest.MonkeyPatch, ) -> None: - """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.""" + """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 @@ -530,14 +547,21 @@ async def nothing(*_: Any, **__: Any) -> Any: 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", nothing) + 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 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) @@ -776,7 +800,6 @@ def count(d: Any, what: str, n: int = 1) -> None: monkeypatch.setattr(imp, "_write_memories", write) monkeypatch.setattr(conflicts, "namespace_conflict_policy", current) monkeypatch.setattr(blacklist_guard, "find_match", nothing) - monkeypatch.setattr(imp, "utc_now", lambda: datetime(2026, 2, 1, tzinfo=UTC)) for policy, expected, counts in ( ( "newest_wins", @@ -837,12 +860,15 @@ def count(d: Any, what: str, n: int = 1) -> None: counts[what] = counts.get(what, 0) + n monkeypatch.setattr(bulk_set, "handle_memory_bulk_set", bulk) + monkeypatch.setattr(imp, "utc_now", lambda: datetime(2026, 2, 1, tzinfo=UTC)) rows = [ - _SnapshotMemoryRow.model_validate(_head("n", key, valid_at=at, pinned=True)) - for key, at in ( - ("k-undated", None), - ("k-new", "2025-03-01T00:00:00Z"), - ("k-old", "2025-01-01T00:00:00"), + _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"), ) ] run: Any = SimpleNamespace(now=datetime(2026, 2, 1), count=count) @@ -851,6 +877,7 @@ def count(d: Any, what: str, n: int = 1) -> None: assert [e.memory_key for e in body.entries] == ["k-old", "k-new", "k-undated"] assert kw == {"conflict_check_cap": 3, "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, None] # from the write assert counts == {"memories": 2, "memories_not_admitted": 1} From bbde4632495755c16a26fa9a17e02a378fd04d34 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:55:53 +0530 Subject: [PATCH 21/32] loom instance: a merge leaves a redacted head out - `_live` requires `redacted_at` empty: a redacted head stays active with the placeholder as its value, which no read serves, and a merge wrote it as a fact with its redaction marks dropped. It is counted as not live, so a live row of its key lands. - The plan refuses a mapping of an end user onto `user:-` or `user:`, which would land their rows beside the rows with no user. - The runbook says a row that expires before its write lands with a one-second expiry; `landed_row` uses `as_aware_utc`; the `_kept` docstring names `_live`; the merge test's run starts before its expiry. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 5 +++-- server/cli/instance_import.py | 13 +++++++++---- server/cli/instance_plan.py | 11 +++++++---- tests/unit/test_instance_consolidation.py | 23 +++++++++++++++-------- 4 files changed, 34 insertions(+), 18 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 774d1f33906..2faf57b426d 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -122,8 +122,9 @@ subjects: # "/": rule row is the older statement by `valid_at`, and, with the conflict resolver on, one it judges the merged row updates. The source's refusals that reach the source namespace refuse the rows it brings, and none is stored on the target's namespace. It writes - live facts only: a row in another state, or past its expiry when the run starts, is - left out, and pins and locks are not carried. A merged row's `created_at` is the + live facts only: 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. A document whose `source_uri` the target namespace holds or has held is left as it is, and of two namespaces merged into one, the first in the bundle brings an address both hold. diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index a519e5e5b60..15622260a1d 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -773,7 +773,7 @@ def _row(run: _Run, d: NsDecision, m: dict[str, Any]) -> Any: 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 (`_bulk_entry`), one whose key the target + 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 @@ -868,9 +868,14 @@ async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, s def _live(m: Any, now: datetime) -> bool: - """Whether a merge carries source head `m`: an active row, not past its expiry at - `now`, the run's start, so every pass of a run decides it alike.""" - return m.status == _MERGED_STATUS and (m.expires_at is None or to_naive_utc(m.expires_at) > now) + """Whether a merge carries source head `m`: an active row, 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.""" + return ( + m.status == _MERGED_STATUS + 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]: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 511e9112f02..e1f1db28c21 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -34,12 +34,14 @@ import json from collections.abc import Iterable, Mapping from dataclasses import asdict, dataclass, field -from datetime import UTC, datetime +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, @@ -243,8 +245,7 @@ def landed_row(row: Mapping[str, Any], created_at: Any) -> bool: and its owners have not deleted it.""" def at(v: Any) -> Any: # the bundle's ISO text or the target's naive UTC - t = datetime.fromisoformat(v) if isinstance(v, str) else v - return t.replace(tzinfo=UTC) if isinstance(t, datetime) and t.tzinfo is None else t + return as_aware_utc(datetime.fromisoformat(v) if isinstance(v, str) else v) return ( bool(created_at) @@ -534,7 +535,9 @@ def _plan_subject(o: _Org, subject: str) -> None: return if rule is not None and rule.action == "map": user = subject.startswith(USER) - if user != rule.target.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 != to_user: o.problem(f"subjects.{key}: 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") diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index a7fe1a9a214..1770da90884 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -191,6 +191,10 @@ def test_end_users_map_to_end_users_and_never_land_as_one() -> None: 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 def test_a_namespace_anyone_could_join_asks_for_approval_in_a_shared_org() -> None: @@ -766,13 +770,16 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("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"), ] w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: - for i, (ns, agent, user, session, key, year, status, *expiry) in enumerate(heads): + 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, "expires_at": next(iter(expiry), None)} + row = {"valid_at": at, "status": status} + row |= {k: v or None for k, v in zip(("expires_at", "redacted_at"), more, strict=False)} sink.write(_head(ns, key, memory_id=str(uuid.UUID(int=i)), **row, **identity)) w.finish({"source": {"deployment_id": SOURCE}}) policy = "" @@ -803,13 +810,13 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [5, 4, 7, 10, 8], # the row with no user first - {"memories_the_target_holds": 2, "memories_not_live": 2, "memories_superseded": 2}, + [5, 4, 7, 10, 12, 8], # the row with no user first + {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 2}, ), ( "auto_reinforce", - [0, 2, 3, 4, 5, 7, 10, 8], - {"memories_not_live": 2, "memories_superseded": 1}, + [0, 2, 3, 4, 5, 7, 10, 12, 8], + {"memories_not_live": 3, "memories_superseded": 1}, ), ): written.clear() @@ -835,7 +842,7 @@ def count(d: Any, what: str, n: int = 1) -> None: written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [4, 7, 10, 8] + assert written == [4, 7, 10, 12, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: @@ -871,7 +878,7 @@ def count(d: Any, what: str, n: int = 1) -> None: ("k-old", "2025-01-01T00:00:00", "2026-02-01T01:00:00"), ) ] - run: Any = SimpleNamespace(now=datetime(2026, 2, 1), count=count) + run: Any = SimpleNamespace(now=datetime(2026, 1, 1), count=count) # k-new live then await imp._merge_memories(run, NsDecision("acme", "n", "acme", "team", "merge"), rows) [(body, kw)] = calls assert [e.memory_key for e in body.entries] == ["k-old", "k-new", "k-undated"] From d1626d03937b6059088e5e2f9ece6800514bf694 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:29:29 +0530 Subject: [PATCH 22/32] loom instance: a merge reads the target's keys again at each write - Each merge call reads the target's keys of its entries again just before `memory.bulk_set`, and each document its address before `knowledge.upsert`, with the rule `_kept` uses (`_holds`): a key or address the target's owners write while the run goes on stays theirs. `_held_keys` and `pg_memory.held_in` take the keys to read; `_held_uris` reads only the addresses asked for. - The dry run names a merged row whose `on_expire` is not the one the target's `memory.bulk_set` gives its sensitivity: the target would delete what the source demotes or anonymizes. A created namespace keeps it. - A created row's `verified_by` and `locked_by` name a subject as the plan maps it, and no one where it drops or never planned it. - The plan decides a merged namespace's end users, and its grant subjects only when it carries its grants, never its owner; the dry run says when a created namespace's owner does not land. A mapping onto `user:-` says why it is refused. The runbook covers a source erasure after the export. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 103 +++++++++-------- server/cli/instance.py | 7 ++ server/cli/instance_import.py | 132 +++++++++++++-------- server/cli/instance_plan.py | 42 +++++-- server/memory/store/pg_memory.py | 10 +- tests/unit/test_instance_consolidation.py | 133 ++++++++++++++++++---- 6 files changed, 304 insertions(+), 123 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 2faf57b426d..ad254cacdf1 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -35,7 +35,8 @@ search once the embedding worker's next full pass embeds them 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. + 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 @@ -97,40 +98,48 @@ subjects: # "/": rule ``` - **Namespaces.** A namespace is created under its own name, or the name the map gives - it. 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. `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. 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. 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. The source's refusals that reach the source namespace - refuse the rows it brings, and none is stored on the target's namespace. It writes - live facts only: 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. A document - whose `source_uri` the target namespace holds or has held is left as it is, and of two - namespaces merged into one, the first in the bundle brings an address both hold. - Admission may decline a memory (a pinned peer, or a restatement it folds into a row): - the receipt counts it as `memories_not_admitted`. Per-type settings, policies and the - guide land with a created namespace only. + 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. `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. 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. 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. The source's refusals that + reach the source namespace refuse the rows it brings, and none is stored on the + target's namespace. It writes live facts only: 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. `memory.bulk_set` sets the expiry action the target gives a row's + sensitivity, so the dry run names a merged row whose own action differs: land its + namespace as a created one, which keeps it. The reason recorded for an expiry is not + carried. A created namespace's rows name their verifier and locker under the mapped + subject, and no one where the map drops or never planned it. 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. Admission may decline a memory (a pinned peer, or a restatement it + folds into a row): the receipt counts it as `memories_not_admitted`. Per-type + settings, policies and the guide land with a created namespace only. - **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 @@ -154,17 +163,19 @@ subjects: # "/": rule 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 of every namespace it does not skip: their - grants, owners and end users. 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, 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. Any - other subject needs a mapping or `drop`. +- **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. Any other subject + needs a mapping or `drop`. - **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 diff --git a/server/cli/instance.py b/server/cli/instance.py index 1228ca47eef..e0f8225fd6f 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -81,6 +81,10 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: from server.cli.instance_plan import proposal_yaml 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 "" @@ -93,6 +97,9 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: rows = " (its row only: a bundle that selects it brings its content)" else: rows = "" + owner = owners.get((d.source_org, d.source)) + if d.action == "create" and not d.account and not subjects.get((d.source_org, owner)): + rows += " (owned by the import: no owner lands)" print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{rows}") for s in p.subjects: to = f" → {s.target}" if s.action in ("map", "claim") else "" diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 15622260a1d..ee11212eb75 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -150,20 +150,20 @@ def build_plan( signs_in: Mapping[str, list[str]], ) -> Plan: rows = list(bundle.records("namespaces")) - subjects: dict[str, dict[str, set[str]]] = {} + named: dict[str, dict[str, dict[str, set[str]]]] = {} - def add(row: Any, subject: Any) -> None: - by_ns = subjects.setdefault(str(row["org"]), {}) - by_ns.setdefault(str(row["namespace"]), set()).add(str(subject)) + 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, g["subject"]) + add(g, "grant", g["subject"]) for r in rows: if not is_account(r) and r.get("owner_email"): - add(r, r["owner_email"]) + add(r, "owner", r["owner_email"]) for m in bundle.records("memories"): # an end user's rows follow their decision - if m.get("user_id") not in (None, "", "-"): - add(m, f"{USER}{m['user_id']}") + 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( @@ -175,7 +175,7 @@ def add(row: Any, subject: Any) -> None: rules=rules, namespace_rows=rows, selected=bundle.manifest["namespaces"], - grant_subjects=subjects, + named=named, links=links, revoked=_revoked(bundle), targets=targets, @@ -288,11 +288,22 @@ def _built(d: NsDecision, row: Any, now: datetime) -> 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.domain.sensitive_retention import sensitive_retention + from server.settings import settings if d.action == "merge": if not _live(row, now): return # left out _BulkSetEntry.model_validate(entry := _bulk_entry(row)) + # memory.bulk_set takes no expiry action: the target sets its sensitivity's. + _, theirs, _ = sensitive_retention( + sensitivity=row.sensitivity, expires_at=None, on_expire="", now=now, settings=settings + ) + if (row.on_expire or "tombstone") != (theirs or "tombstone"): + raise ValidationError( + f"a merge expires it by {theirs or 'tombstone'!r}, not its {row.on_expire!r}: " + "land its namespace as a created one" + ) # As memory.bulk_set measures it, which refuses the whole call. if ( entry["char_limit"] is not None @@ -685,9 +696,9 @@ async def _links(run: _Run) -> None: async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[str]: - """Every document source_uri the namespace has held, deleted ones too. Under the - Postgres authority, those of `uris` it holds as well: a head committed since its last - publication to ClickHouse is there only.""" + """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 @@ -695,9 +706,9 @@ async def _held_uris(ch: Any, org: str, namespace: str, uris: list[str]) -> set[ 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}", - {"org": org, "ns": namespace}, + "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(): @@ -759,13 +770,21 @@ async def _memories(run: _Run) -> None: 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.""" + """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 + from server.memory.domain.trust import HUMAN_PREFIX, PROCESS_PREFIX 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"): # under the subject the plan maps, else no one + kind, sep, who = str(m.get(col) or "").partition(":") + if sep and f"{kind}:" in (HUMAN_PREFIX, PROCESS_PREFIX): + to = run.subject(d.source_org, who) + m[col] = f"{kind}:{to}" if to else "" return _SnapshotMemoryRow.model_validate( {k: v for k, v in m.items() if k not in ("org", "namespace")} ) @@ -793,11 +812,8 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: if t not in run.held: # once per target namespace run.held[t] = await _held_keys(run.ch, *t) if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": - run.reach[t] = {r for _, u, _, k in run.held[t] for r in ((u, k), (None, k))} - writer = None if is_anonymous_user(row.user_id) else row.user_id - if key_in_namespace(m) in run.held[t] or ( - d.action == "merge" and (writer, row.memory_key) in run.reach.get(t, ()) - ): + run.reach[t] = _reach(run.held[t]) + 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( @@ -808,6 +824,19 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: return d, row +def _reach(held: set[tuple[str, str, str, str]]) -> 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.""" + return {r for _, u, _, k in held for r in ((u, k), (None, k))} + + +def _holds(held: set[Any], 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: @@ -843,25 +872,30 @@ async def _write_memories(run: _Run, d: NsDecision, kept: list[Any]) -> None: run.count(d, "memories", len(rows)) -async def _held_keys(ch: Any, org: str, namespace: str) -> set[tuple[str, str, str, str]]: - """Every (agent, user, session, key) the namespace holds or has held, a deleted one - included: 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: - one committed since its last publication to ClickHouse is there only.""" +async def _held_keys( + ch: Any, org: str, namespace: str, keys: list[str] | None = None +) -> set[tuple[str, str, str, str]]: + """Every (agent, user, session, key) the namespace holds or has held, of `keys` when + given, a deleted one included: 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: one committed since its last publication to ClickHouse is there + only.""" from server.core import pg from server.memory.store import pg_memory - held = { - key_in_namespace(r) - async for r in stream_rows( - ch, - "SELECT DISTINCT agent, user_id, session_id, memory_key FROM loom.memory " - "WHERE org = {org:String} AND namespace = {ns:String}", - {"org": org, "ns": namespace}, - ) - } + sql = ( + "SELECT DISTINCT agent, user_id, session_id, memory_key FROM loom.memory " + "WHERE org = {org:String} AND namespace = {ns:String}" + ) + params: dict[str, Any] = {"org": org, "ns": namespace} + if keys is not None: + sql += " AND memory_key IN {keys:Array(String)}" + params["keys"] = keys + held = {key_in_namespace(r) async for r in stream_rows(ch, sql, params)} after = None - while pg.enabled() and (page := await pg_memory.held_in(org, namespace, after=after)): + while pg.enabled() and ( + page := await pg_memory.held_in(org, namespace, after=after, keys=keys) + ): held.update(page) after = page[-1] return held @@ -919,9 +953,17 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None from server.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput from server.memory.app.bulk_set import handle_memory_bulk_set + t = (d.target_org, d.target) + # Read again at the write: a key the target's owners wrote since `_kept` read the + # namespace stays theirs. + held = await _held_keys(run.ch, *t, keys=sorted({m.memory_key for m in memories})) + reach = _reach(held) if t in run.reach else set() groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} for m in memories: # each live at the run's start (`_kept`) - groups.setdefault((m.agent, m.user_id, m.session_id), []).append(_bulk_entry(m)) + if _holds(held, reach, m): + run.count(d, "memories_the_target_holds") + else: + groups.setdefault((m.agent, m.user_id, m.session_id), []).append(_bulk_entry(m)) for (agent, user_id, session_id), entries in groups.items(): entries.sort(key=lambda e: to_naive_utc(e["valid_at"]) or run.now) # stable for start in range(0, len(entries), MAX_BULK_ENTRIES): @@ -950,24 +992,22 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None 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.""" + 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.knowledge.api.models_knowledge import KnowledgeUpsertInput from server.knowledge.app.writes import handle_knowledge_upsert - uris: dict[tuple[str, str], list[str]] = {} - for doc in run.bundle.records("documents"): - if (d := run.by_source.get((doc["org"], doc["namespace"]))) is not None: - uris.setdefault((d.target_org, d.target), []).append(str(doc["source_uri"])) - seen = {k: await _held_uris(run.ch, *k, v) for k, v in uris.items()} + 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 - if doc["source_uri"] in seen[(d.target_org, d.target)]: + 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 - # Two source namespaces may merge into one: the first copy of an address stays. - seen[(d.target_org, d.target)].add(doc["source_uri"]) + 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() diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index e1f1db28c21..59b026970a4 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -538,7 +538,10 @@ def _plan_subject(o: _Org, subject: str) -> None: # 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 != to_user: - o.problem(f"subjects.{key}: an end user maps to an end user (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 _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: @@ -611,6 +614,16 @@ def _check_users(o: _Org) -> None: 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, @@ -618,16 +631,16 @@ def plan( rules: MapFile, namespace_rows: Iterable[Mapping[str, Any]], selected: Mapping[str, list[str]], - grant_subjects: Mapping[str, Mapping[str, set[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`. `grant_subjects` is, per source org and namespace, its grant - subjects, owner and memory users (`user:`), which only a namespace the plan does - not skip needs decided; `links` its accounts' single sign-on link + 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( @@ -688,9 +701,14 @@ def plan( _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} - skipped = {d.source for d in p.namespaces if d.source_org == org and d.action == "skip"} - lands = grant_subjects.get(org, {}).items() - needed = {s for ns, subs in lands if ns not in skipped for s in subs} + 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) @@ -709,7 +727,13 @@ def plan( "orgs": set(selected), "namespaces": names, "subjects": handles - | {f"{o}/{s}" for o, by_ns in grant_subjects.items() for ss in by_ns.values() for s in ss}, + | { + 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), diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 8ac52838131..68227e3c131 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -2095,10 +2095,11 @@ async def held_in( *, after: KeyInNamespace | None = None, limit: int = 5000, + keys: Sequence[str] | None = None, ) -> list[KeyInNamespace]: - """A page of the keys of every head of a namespace, deleted ones included, in key order - after `after`: what the namespace holds or has held, its publication to ClickHouse owed - or not.""" + """A page of the keys of every head of a namespace, of `keys` when given, deleted ones + included, in key order after `after`: 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] @@ -2106,6 +2107,9 @@ async def held_in( if after is not None: args += list(after) where += " AND (agent, user_id, session_id, memory_key) > ($4, $5, $6, $7)" + if keys is not None: + 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 " f"FROM loom.memory_current WHERE {where} " diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 1770da90884..0beb7615f4d 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -52,19 +52,30 @@ def _plan( revoked: set[str] | None = None, links: dict[str, dict[str, list[str]]] | None = None, bundle: str = "b1", - by_namespace: dict[str, dict[str, set[str]]] | None = None, + by_namespace: dict[str, dict[str, dict[str, set[str]]]] | None = None, ) -> Any: - """`subjects` holds on every namespace of its org; `by_namespace` per namespace.""" + """`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"]: s for r in rows if r["org"] == o} for o, s in by_org.items()} + 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}, - grant_subjects=every if by_namespace is None else by_namespace, + named=every if by_namespace is None else by_namespace, links=links or {}, revoked=revoked or set(), targets=targets or {"acme": target or EMPTY}, @@ -172,7 +183,12 @@ 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": {"x"}, "scratch": {"group:eng", "user:42"}}} + 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"} @@ -180,6 +196,43 @@ def test_a_skipped_namespace_needs_no_subject_decided() -> None: 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 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"] + + 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"}} @@ -487,9 +540,11 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( heads = [("a", "-", "-", f"k{i}") for i in range(3)] - async def held_in(org: str, ns: str, *, after: Any = None, limit: int = 5000) -> Any: + async def held_in( + org: str, ns: str, *, after: Any = None, limit: int = 5000, keys: Any = None + ) -> Any: # pages of two - return [h for h in heads if after is None or h > after][:2] + return [h for h in heads if (after is None or h > after) and keys in (None, [h[3]])][:2] async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch", "v": "ch.md"} @@ -502,6 +557,7 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} + assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k-ch", "k1"} assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"ch.md", "held.md"} @@ -687,7 +743,8 @@ 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.""" + 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.""" from contextlib import nullcontext from types import SimpleNamespace @@ -696,19 +753,24 @@ async def test_two_merges_into_one_namespace_land_an_address_once( w = BundleWriter(tmp_path / "b") with w.section("documents") as sink: - for ns in ("notes", "scratch"): - sink.write({"org": "acme", "namespace": ns, "source_uri": "runbook.md", "content": ns}) + 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 nothing(*_: Any) -> set[str]: - return set() + 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) - monkeypatch.setattr(imp, "_held_uris", nothing) + monkeypatch.setattr(imp, "_held_uris", held) monkeypatch.setattr(imp, "_for", lambda d: nullcontext()) monkeypatch.setattr(writes, "handle_knowledge_upsert", upsert) run: Any = SimpleNamespace( @@ -721,7 +783,8 @@ async def upsert(body: Any) -> None: count=lambda d, what, n=1: counted.append(what), ) await imp._documents(run) - assert landed == ["notes"] and counted == ["documents", "documents_present"] + assert landed == ["notes", "notes"] + assert counted == ["documents", "documents_present", "documents_present", "documents"] def _head(namespace: str, key: str, **row: Any) -> dict[str, Any]: @@ -866,7 +929,13 @@ async def bulk(body: Any, **kw: Any) -> Any: 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: Any = None) -> Any: + asked.append(keys) + return {("b", "alice", "s9", "k-undated")} # written since, in another session + + 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( @@ -878,14 +947,19 @@ def count(d: Any, what: str, n: int = 1) -> None: ("k-old", "2025-01-01T00:00:00", "2026-02-01T01:00:00"), ) ] - run: Any = SimpleNamespace(now=datetime(2026, 1, 1), count=count) # k-new live then + # 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 asked == [["k-new", "k-old", "k-undated"]] # once, just before the write [(body, kw)] = calls - assert [e.memory_key for e in body.entries] == ["k-old", "k-new", "k-undated"] - assert kw == {"conflict_check_cap": 3, "reinforce": False} + 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, None] # from the write - assert counts == {"memories": 2, "memories_not_admitted": 1} + 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": 1} async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> None: @@ -902,7 +976,9 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> 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", "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}}) @@ -923,4 +999,23 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> "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 'demote'" in p.problems[-1] + + +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 From 0e6ea2353a9e485b3bfaf295b13326fe5b579d6d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:45:42 +0530 Subject: [PATCH 23/32] loom instance: a merge reads the target's keys before each call - `_merge_memories` reads the target's keys of a group's entries just before that group's `memory.bulk_set` call, not once per batch: a key the target's owners write after an earlier call of the batch stays theirs. A batch is at most `_BATCH` rows, under `MAX_BULK_ENTRIES`, so a group is one call; the chunk loop that could never run twice is gone. - The dry run names a merged row's `on_expire` only when the row expires on the target, by the level `memory.bulk_set` grades there: an action on a row that never expires loses nothing. The problem says the merge loses it, not that the target refuses it. - The dry run's owner note leaves out a landing an earlier run finished; a grant subject mapped onto `user:` has its own refusal text; the held-key and held-address tests check the filters the reads send. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 18 ++--- server/cli/instance.py | 5 +- server/cli/instance_import.py | 98 ++++++++++++----------- server/cli/instance_plan.py | 4 +- tests/unit/test_instance_consolidation.py | 33 ++++++-- 5 files changed, 95 insertions(+), 63 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index ad254cacdf1..1e77d6d5947 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -131,15 +131,15 @@ subjects: # "/": rule 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. `memory.bulk_set` sets the expiry action the target gives a row's - sensitivity, so the dry run names a merged row whose own action differs: land its - namespace as a created one, which keeps it. The reason recorded for an expiry is not - carried. A created namespace's rows name their verifier and locker under the mapped - subject, and no one where the map drops or never planned it. 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. Admission may decline a memory (a pinned peer, or a restatement it - folds into a row): the receipt counts it as `memories_not_admitted`. Per-type - settings, policies and the guide land with a created namespace only. + sensitivity, so the dry run names a merged row that expires there whose own action + differs: land its namespace as a created one, which keeps it. The reason recorded for + an expiry is not carried. A created namespace's rows name their verifier and locker + under the mapped subject, and no one where the map drops or never planned it. 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. Admission may decline a memory (a pinned peer, or + a restatement it folds into a row): the receipt counts it as `memories_not_admitted`. + Per-type settings, policies and the guide land with a created namespace only. - **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 diff --git a/server/cli/instance.py b/server/cli/instance.py index e0f8225fd6f..6b13d170a1b 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -89,16 +89,17 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: land = "skip" if d.action == "skip" else f"{d.action} {d.target_org}/{d.target}" account = f" (account, {d.account})" if d.account else "" joins = " (self-join needs approval: the target org serves others)" if d.approval else "" + done = (d.target, source_key(bundle, d.source_org, d.source)) in targets[d.target_org].done if d.action == "skip": rows = "" - elif (d.target, source_key(bundle, d.source_org, d.source)) in targets[d.target_org].done: + elif done: rows = " (an earlier run finished it: skipped)" elif (d.source_org, d.source) not in content: rows = " (its row only: a bundle that selects it brings its content)" else: rows = "" owner = owners.get((d.source_org, d.source)) - if d.action == "create" and not d.account and not subjects.get((d.source_org, owner)): + if d.action == "create" and not (d.account or done or subjects.get((d.source_org, owner))): rows += " (owned by the import: no owner lands)" print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{rows}") for s in p.subjects: diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index ee11212eb75..a29afd9e8cf 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -260,8 +260,11 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr if (into := todo.get((m["org"], m["namespace"]))) is None: continue try: - if (row := _row(run, into, m)) is not None: - _built(into, row, run.now) + row = _row(run, into, m) + if row is not None and (why := await _built(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) @@ -282,27 +285,31 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) -def _built(d: NsDecision, row: Any, now: datetime) -> None: +async def _built(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.""" + target refuses it; what a merge would lose of it, as a problem.""" 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.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 # left out + return None # left out _BulkSetEntry.model_validate(entry := _bulk_entry(row)) - # memory.bulk_set takes no expiry action: the target sets its sensitivity's. - _, theirs, _ = sensitive_retention( - sensitivity=row.sensitivity, expires_at=None, on_expire="", now=now, settings=settings + # memory.bulk_set takes no expiry action: on a row that expires there it sets the + # one the target gives the level it grades, as it grades it. + level = await resolve_level(row.sensitivity, await decoded_text(json.dumps(entry["value"]))) + expires, theirs, _ = sensitive_retention( + sensitivity=level, expires_at=row.expires_at, on_expire="", now=now, settings=settings ) - if (row.on_expire or "tombstone") != (theirs or "tombstone"): - raise ValidationError( - f"a merge expires it by {theirs or 'tombstone'!r}, not its {row.on_expire!r}: " - "land its namespace as a created one" + if expires is not None and (row.on_expire or "tombstone") != (theirs or "tombstone"): + return ( + f"a merge expires it by {theirs or 'tombstone'!r}, not its own " + f"{row.on_expire!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 ( @@ -321,6 +328,7 @@ def _built(d: NsDecision, row: Any, now: datetime) -> None: actor="", ) ) + return None def _reaches(b: Mapping[str, Any], d: NsDecision) -> bool: @@ -950,43 +958,43 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None 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.memory.api.models_bulk import MAX_BULK_ENTRIES, MemoryBulkSetInput + 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) - # Read again at the write: a key the target's owners wrote since `_kept` read the - # namespace stays theirs. - held = await _held_keys(run.ch, *t, keys=sorted({m.memory_key for m in memories})) - reach = _reach(held) if t in run.reach else set() - groups: dict[tuple[str, str, str], list[dict[str, Any]]] = {} - for m in memories: # each live at the run's start (`_kept`) - if _holds(held, reach, m): - run.count(d, "memories_the_target_holds") - else: - groups.setdefault((m.agent, m.user_id, m.session_id), []).append(_bulk_entry(m)) - for (agent, user_id, session_id), entries in groups.items(): + 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 - for start in range(0, len(entries), MAX_BULK_ENTRIES): - chunk = entries[start : start + MAX_BULK_ENTRIES] - 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": chunk, - } - ), - conflict_check_cap=len(chunk), - reinforce=False, - ) - written = sum(1 for w in out.written if w.version) - run.count(d, "memories", written) - if declined := len(chunk) - written: # a pinned peer, or a restatement it merged - run.count(d, "memories_not_admitted", declined) + 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, + ) + 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: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 59b026970a4..df02182ca3a 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -537,11 +537,13 @@ def _plan_subject(o: _Org, subject: str) -> None: 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 != to_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: diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 0beb7615f4d..c2f45a9de3a 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -231,6 +231,10 @@ def test_the_plan_says_who_owns_a_namespace_whose_owner_does_not_land( } assert lines["acme/team"].endswith("(owned by the import: no owner lands)"), lines assert "owned by the import" not in lines["acme/notes"] + finished = TargetOrg({}, frozenset(), done=frozenset({("team", f"{SOURCE}/acme/team")})) + 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 def test_end_users_map_to_end_users_and_never_land_as_one() -> None: @@ -248,6 +252,9 @@ def test_end_users_map_to_end_users_and_never_land_as_one() -> None: 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: @@ -546,8 +553,13 @@ async def held_in( # pages of two return [h for h in heads if (after is None or h > after) and keys in (None, [h[3]])][:2] + sent: list[tuple[str, Any]] = [] + async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: - yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": "k-ch", "v": "ch.md"} + sent.append((sql, params)) + for key, uri in (("k-ch", "ch.md"), ("k1", "held.md")): + if key in params.get("keys", [key]) and uri in params.get("uris", [uri]): + yield {"agent": "a", "user_id": "-", "session_id": "-", "memory_key": key, "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"} @@ -557,8 +569,11 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: monkeypatch.setattr(pg_documents, "held_uris", held_uris) monkeypatch.setattr(imp, "stream_rows", stream_rows) assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} - assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k-ch", "k1"} - assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"ch.md", "held.md"} + assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k1"} + assert "memory_key IN {keys:Array(String)}" in sent[-1][0] and sent[-1][1]["keys"] == ["k1"] + assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"held.md"} + assert "source_uri IN {uris:Array(String)}" in sent[-1][0] + assert sent[-1][1]["uris"] == ["held.md", "new.md"] async def test_an_original_changed_after_the_dry_run_stops_its_document( @@ -915,6 +930,7 @@ async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPa from server.cli import instance_import as imp 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]]] = [] @@ -931,6 +947,8 @@ def count(d: Any, what: str, n: int = 1) -> None: async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: asked.append(keys) + if calls: # the owners wrote k-late after the first call + return {("b", "-", "s2", "k-late")} return {("b", "alice", "s9", "k-undated")} # written since, in another session asked: list[Any] = [] @@ -947,19 +965,21 @@ async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: ("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"))) # 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 asked == [["k-new", "k-old", "k-undated"]] # once, just before the write + 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"]] # just before 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": 1} + assert counts == {"memories": 1, "memories_not_admitted": 1, "memories_the_target_holds": 2} async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> None: @@ -977,6 +997,7 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> # 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 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 @@ -1001,7 +1022,7 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> "acme/team memory 'long'", "acme/team memory 'demoted'", ], p.problems - assert "a merge expires it by 'tombstone', not its 'demote'" in p.problems[-1] + assert "a merge expires it by 'tombstone', not its own 'demote'" in p.problems[-1] def test_a_landed_row_names_its_verifier_and_locker_as_the_plan_maps_them() -> None: From 7eacd3738e61d0bf7964ace19b3eedec8578bbe8 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:10:03 +0530 Subject: [PATCH 24/32] loom instance: a merge carries conflicted rows and keeps definitions - A merge carries the rows reads serve, active or conflicted; the target's admission judges a conflicted pair again. It dropped conflicted rows as not live. - Under `newest_wins` a namespace definition is a group of its own, written before the rows with no user of its key: no other write of the key retires it, so both land, as the source served them. - The dry run names a merged row's expiry action only when the source expires the row by an action other than deleting it and the target's differs; a row the target's retention window expires that the source never expires, or deletes at its expiry, loses nothing. `_merge_problem` names it. - An account mapped onto `user:` is refused. The Postgres head reads stop at a short page. The dry-run test runs on a fixed clock. The runbook says `set_up_again` is the org's. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 56 +++++++++-------- server/cli/instance.py | 12 ++-- server/cli/instance_export.py | 8 ++- server/cli/instance_import.py | 74 ++++++++++++++--------- server/cli/instance_plan.py | 3 +- tests/unit/test_instance_consolidation.py | 34 ++++++++--- 6 files changed, 114 insertions(+), 73 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 1e77d6d5947..5f1eadfe386 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -74,11 +74,13 @@ search once the embedding worker's next full pass embeds them loom instance import --bundle ./acme-bundle --map map.yaml --apply --expect-plan 5e25ef6da948b233 ``` -6. Hand out the receipt's `set_up_again` list, 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 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. +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 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 @@ -120,26 +122,30 @@ subjects: # "/": rule (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. 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. The source's refusals that - reach the source namespace refuse the rows it brings, and none is stored on the - target's namespace. It writes live facts only: 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. `memory.bulk_set` sets the expiry action the target gives a row's - sensitivity, so the dry run names a merged row that expires there whose own action - differs: land its namespace as a created one, which keeps it. The reason recorded for - an expiry is not carried. A created namespace's rows name their verifier and locker - under the mapped subject, and no one where the map drops or never planned it. 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. Admission may decline a memory (a pinned peer, or - a restatement it folds into a row): the receipt counts it as `memories_not_admitted`. - Per-type settings, policies and the guide land with a created namespace only. + 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. The source's refusals + that reach the source namespace refuse the rows it brings, and none is stored on the + target's namespace. It 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. A created namespace's rows + name their verifier and locker under the mapped subject, and no one where the map + drops or never planned it. 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. Admission may decline a + memory (a pinned peer, or a restatement it folds into a row): the receipt counts it as + `memories_not_admitted`. Per-type settings, policies and the guide land with a created + namespace only. - **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 diff --git a/server/cli/instance.py b/server/cli/instance.py index 6b13d170a1b..45dce54e0a4 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -91,17 +91,17 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: joins = " (self-join needs approval: the target org serves others)" if d.approval else "" done = (d.target, source_key(bundle, d.source_org, d.source)) in targets[d.target_org].done if d.action == "skip": - rows = "" + note = "" elif done: - rows = " (an earlier run finished it: skipped)" + note = " (an earlier run finished it: skipped)" elif (d.source_org, d.source) not in content: - rows = " (its row only: a bundle that selects it brings its content)" + note = " (its row only: a bundle that selects it brings its content)" else: - rows = "" + note = "" owner = owners.get((d.source_org, d.source)) if d.action == "create" and not (d.account or done or subjects.get((d.source_org, owner))): - rows += " (owned by the import: no owner lands)" - print(f" namespace {d.source_org}/{d.source} → {land}{account}{joins}{rows}") + 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 "" diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 73f0d9a09a8..9a7a0ff1084 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -290,12 +290,14 @@ async def memory_heads(ch: Any, org: str, ns: str) -> AsyncIterator[dict[str, An from server.memory.store.rows import identity_key if pg.enabled(): - after = None - while page := await pg_memory.live_heads_in(org, ns, after=after, limit=5000): + after, limit = None, 5000 + while True: + page = await pg_memory.live_heads_in(org, ns, after=after, limit=limit) for r in page: yield r + if len(page) < limit: + return after = identity_key(page[-1]) - return async for r in stream_rows( ch, f"SELECT toString(memory_id) AS memory_id, {SNAPSHOT_SELECT} FROM loom.memory FINAL " diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index a29afd9e8cf..44c474242b7 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -43,6 +43,7 @@ from server.core.datetimes import as_aware_utc, to_naive_utc, 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 key_in_namespace LANDED = "instance.import" @@ -58,7 +59,7 @@ "budget_alert_inbox": "", } # A row in any other state is history, not a fact a merge states again. -_MERGED_STATUS = "active" +_PG_PAGE = 5000 # Postgres heads per read def source_key(bundle: Bundle, org: str, name: str) -> str: @@ -192,8 +193,9 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr 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), a refusal this deployment cannot compile, a created namespace whose refusals would pass the regex - budget, a memory the target cannot store, an original missing from the bundle. Each is - added as a problem.""" + budget, a memory the target cannot store or a merge would lose the expiry action of + (`_merge_problem`), an original missing from the bundle. Each is added as a + problem.""" from fastapi import HTTPException from pydantic import ValidationError as ModelError @@ -261,7 +263,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr continue try: row = _row(run, into, m) - if row is not None and (why := await _built(into, row, run.now)): + if row is not None and (why := await _merge_problem(into, row, run.now)): p.problems.append( f"{into.source_org}/{into.source} memory {m['memory_key']!r}: {why}" ) @@ -285,12 +287,13 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) -async def _built(d: NsDecision, row: Any, now: datetime) -> str | None: +async def _merge_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; what a merge would lose of it, as a problem.""" + 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 @@ -299,18 +302,24 @@ async def _built(d: NsDecision, row: Any, now: datetime) -> str | None: if not _live(row, now): return None # left out _BulkSetEntry.model_validate(entry := _bulk_entry(row)) - # memory.bulk_set takes no expiry action: on a row that expires there it sets the - # one the target gives the level it grades, as it grades it. - level = await resolve_level(row.sensitivity, await decoded_text(json.dumps(entry["value"]))) - expires, theirs, _ = sensitive_retention( - sensitivity=level, expires_at=row.expires_at, on_expire="", now=now, settings=settings - ) - if expires is not None and (row.on_expire or "tombstone") != (theirs or "tombstone"): - return ( - f"a merge expires it by {theirs or 'tombstone'!r}, not its own " - f"{row.on_expire!r} (memory.bulk_set takes no expiry action): land the " - "namespace as a created one, which keeps it" + # 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 @@ -734,7 +743,8 @@ async def _memories(run: _Run) -> None: 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.""" + as the source served them. A namespace definition, which no other write of its key + retires, is one group of its own and is written before them.""" batch: dict[tuple[str, str], list[Any]] = {} exact: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} scoped: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} @@ -751,21 +761,21 @@ async def _memories(run: _Run) -> None: merged[k] += 1 rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) group: tuple[Any, ...] - if t in run.reach: # newest_wins: (target, user or None, key) + if t in run.reach and not is_namespace_definition(row): # (target, user or None, key) user = None if is_anonymous_user(row.user_id) else row.user_id groups, group = scoped, (t, user, row.memory_key) else: groups, group = exact, (t, key_in_namespace(m)) if group not in groups or rank > groups[group][0]: groups[group] = (rank, (*k, str(m["memory_id"]))) - first = {ref for _, ref in exact.values()} - first |= {ref for (_, user, _), (_, ref) in scoped.items() if user is None} + alone = {ref for _, ref in exact.values()} # under newest_wins, the definitions + 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 first | then) + 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 (first, then): # a read each: what a merge writes is known once all is read + 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: @@ -901,20 +911,24 @@ async def _held_keys( params["keys"] = keys held = {key_in_namespace(r) async for r in stream_rows(ch, sql, params)} after = None - while pg.enabled() and ( - page := await pg_memory.held_in(org, namespace, after=after, keys=keys) - ): + while pg.enabled(): + page = await pg_memory.held_in(org, namespace, after=after, limit=_PG_PAGE, keys=keys) held.update(page) + if len(page) < _PG_PAGE: + return held after = page[-1] return held def _live(m: Any, now: datetime) -> bool: - """Whether a merge carries source head `m`: an active row, 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.""" + """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 == _MERGED_STATUS + 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) ) diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index df02182ca3a..218e1753272 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -391,7 +391,8 @@ def _plan_account(o: _Org, name: str, row: Mapping[str, Any]) -> None: o.plan.namespaces.append(NsDecision(o.org, name, o.target_org, "", "skip")) return if rule is not None and rule.action == "map": - if _collection_only(rule.target) or rule.target not in o.target.subjects: + 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" diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index c2f45a9de3a..e3c6c5eab03 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -519,7 +519,7 @@ def test_two_accounts_of_the_bundle_never_land_with_one_email() -> None: 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"})) + 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. @@ -527,6 +527,7 @@ def test_the_map_names_only_what_the_bundle_holds_and_whom_a_namespace_can_name( 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) @@ -550,8 +551,7 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( async def held_in( org: str, ns: str, *, after: Any = None, limit: int = 5000, keys: Any = None ) -> Any: - # pages of two - return [h for h in heads if (after is None or h > after) and keys in (None, [h[3]])][:2] + return [h for h in heads if (after is None or h > after) and keys in (None, [h[3]])][:limit] sent: list[tuple[str, Any]] = [] @@ -566,6 +566,7 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: 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) assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} @@ -850,6 +851,9 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("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 ] w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: @@ -857,7 +861,8 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe 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} - row |= {k: v or None for k, v in zip(("expires_at", "redacted_at"), more, strict=False)} + 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 = "" @@ -888,12 +893,12 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [5, 4, 7, 10, 12, 8], # the row with no user first + [14, 5, 15, 4, 7, 10, 12, 13, 8], # the definition, the rows with no user, the rest {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 2}, ), ( "auto_reinforce", - [0, 2, 3, 4, 5, 7, 10, 12, 8], + [0, 2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 8], {"memories_not_live": 3, "memories_superseded": 1}, ), ): @@ -920,7 +925,7 @@ def count(d: Any, what: str, n: int = 1) -> None: written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [4, 7, 10, 12, 8] + assert written == [14, 15, 4, 7, 10, 12, 13, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: @@ -982,11 +987,21 @@ async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: assert counts == {"memories": 1, "memories_not_admitted": 1, "memories_the_target_holds": 2} -async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> None: +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") @@ -998,6 +1013,9 @@ async def test_the_dry_run_names_a_memory_the_target_refuses(tmp_path: Path) -> 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 From 8d0b23944563c042c0345599a47e9de79ac63a8b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:52:47 +0530 Subject: [PATCH 25/32] loom instance: a namespace definition holds only its own row - The held-key reads return each key's latest `memory_type` (ClickHouse `argMax(memory_type, version)`, the Postgres authority's `row->>'memory_type'`), and under `newest_wins` a namespace definition claims no reach: a same-key write never retires one. A definition the run wrote in an earlier pass, or the target holds, no longer holds back the row with no user of its key, in one run or on resume. - A created namespace's policies and guide revisions name their writer as the plan maps the subject, like a memory's verifier and locker. - A write that commits with its publication owed (`PublicationPending`) no longer stops the run: a document counts as written, a `memory.bulk_set` call's entries as `memories_publication_pending`. - The Postgres page size is one constant, `instance_export.PG_PAGE`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 29 ++-- server/cli/instance_export.py | 7 +- server/cli/instance_import.py | 130 +++++++++++------- server/memory/store/pg_memory.py | 13 +- .../test_instance_consolidation.py | 30 ++++ tests/unit/test_instance_consolidation.py | 67 ++++++--- 6 files changed, 188 insertions(+), 88 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 5f1eadfe386..818a8a5a418 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -114,9 +114,10 @@ subjects: # "/": rule 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. 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 + 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 @@ -139,13 +140,17 @@ subjects: # "/": rule 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. A created namespace's rows - name their verifier and locker under the mapped subject, and no one where the map - drops or never planned it. 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. Admission may decline a - memory (a pinned peer, or a restatement it folds into a row): the receipt counts it as - `memories_not_admitted`. Per-type settings, policies and the guide land with a created - namespace only. + 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. 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. 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 write that commits but whose publication to ClickHouse + is owed is left to the delivery worker, and the run goes on: the receipt counts such a + write's memories as `memories_publication_pending`, as admission's answer for each is + lost, and its document as written. Per-type settings, policies and the guide land with + a created namespace only. - **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 @@ -164,8 +169,8 @@ subjects: # "/": rule 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 + 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. diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 9a7a0ff1084..95fca2101ca 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -32,6 +32,7 @@ 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 the source, registered again, writes again: it keeps only # its own copies up to date (`source_sync.ours`). A recording source lists its last weeks # only and its transcripts are settled when written, so its copies move. @@ -290,12 +291,12 @@ async def memory_heads(ch: Any, org: str, ns: str) -> AsyncIterator[dict[str, An from server.memory.store.rows import identity_key if pg.enabled(): - after, limit = None, 5000 + after = None while True: - page = await pg_memory.live_heads_in(org, ns, after=after, limit=limit) + page = await pg_memory.live_heads_in(org, ns, after=after, limit=PG_PAGE) for r in page: yield r - if len(page) < limit: + if len(page) < PG_PAGE: return after = identity_key(page[-1]) async for r in stream_rows( diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 44c474242b7..fa265d25863 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -21,6 +21,7 @@ from __future__ import annotations import base64 +import contextlib import json import time import uuid @@ -30,7 +31,7 @@ from typing import Any from server.cli.instance_bundle import Bundle, BundleError -from server.cli.instance_export import REVOKED, stream_rows +from server.cli.instance_export import PG_PAGE, REVOKED, stream_rows from server.cli.instance_plan import ( MapFile, NsDecision, @@ -44,7 +45,7 @@ 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 key_in_namespace +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 @@ -58,8 +59,6 @@ "released_aliases": [], "budget_alert_inbox": "", } -# A row in any other state is history, not a fact a merge states again. -_PG_PAGE = 5000 # Postgres heads per read def source_key(bundle: Bundle, org: str, name: str) -> str: @@ -426,10 +425,11 @@ def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, Targe 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: the keys it holds, and under - # newest_wins each (user, key) a same-key write retires a row of, None for any user. + # Per merge: the source refusals. Per target namespace: the keys it holds, 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], set[tuple[str, str, str, str]]] = {} + 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: @@ -542,11 +542,12 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: run.count(d, "namespace") -# A created namespace's own rows, each table with the key the target is checked by. +# 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", - "namespace_policies": "policy_id", - "namespace_guides": "revision", + "namespace_types": ("memory_type", None), + "namespace_policies": ("policy_id", "created_by"), + "namespace_guides": ("revision", "updated_by"), } @@ -554,7 +555,7 @@ 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 in _CARRIED.items(): + 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}", @@ -566,6 +567,9 @@ async def _carry(run: _Run, d: NsDecision) -> None: 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}", @@ -755,7 +759,7 @@ async def _memories(run: _Run) -> None: d, row = got k, t = (d.source_org, d.source), (d.target_org, d.target) if d.action == "create": - run.held[t].add(key_in_namespace(m)) + run.held[t][key_in_namespace(m)] = is_namespace_definition(row) await _batched(run, batch, d, row) continue merged[k] += 1 @@ -792,29 +796,38 @@ def _row(run: _Run, d: NsDecision, m: dict[str, Any]) -> Any: 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 - from server.memory.domain.trust import HUMAN_PREFIX, PROCESS_PREFIX 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"): # under the subject the plan maps, else no one - kind, sep, who = str(m.get(col) or "").partition(":") - if sep and f"{kind}:" in (HUMAN_PREFIX, PROCESS_PREFIX): - to = run.subject(d.source_org, who) - m[col] = f"{kind}:{to}" if to else "" + 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.""" + 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 from server.memory.app.conflicts import namespace_conflict_policy @@ -842,13 +855,20 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: return d, row -def _reach(held: set[tuple[str, str, str, str]]) -> set[tuple[str | None, str]]: +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.""" - return {r for _, u, _, k in held for r in ((u, k), (None, k))} + 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: set[Any], reach: set[tuple[str | None, str]], row: Any) -> bool: +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 @@ -892,31 +912,36 @@ async def _write_memories(run: _Run, d: NsDecision, kept: list[Any]) -> None: async def _held_keys( ch: Any, org: str, namespace: str, keys: list[str] | None = None -) -> set[tuple[str, str, str, str]]: +) -> dict[KeyInNamespace, bool]: """Every (agent, user, session, key) the namespace holds or has held, of `keys` when - given, a deleted one included: 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: one committed since its last publication to ClickHouse is there + given, 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 DISTINCT agent, user_id, session_id, memory_key FROM loom.memory " + "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}" ) params: dict[str, Any] = {"org": org, "ns": namespace} if keys is not None: sql += " AND memory_key IN {keys:Array(String)}" params["keys"] = keys - held = {key_in_namespace(r) async for r in stream_rows(ch, sql, params)} + sql += " GROUP BY agent, user_id, session_id, memory_key" + held = { + key_in_namespace(r): is_namespace_definition(r) async for r in stream_rows(ch, sql, params) + } after = None while pg.enabled(): - page = await pg_memory.held_in(org, namespace, after=after, limit=_PG_PAGE, keys=keys) + page = await pg_memory.held_in(org, namespace, after=after, limit=PG_PAGE, keys=keys) held.update(page) - if len(page) < _PG_PAGE: + if len(page) < PG_PAGE: return held - after = page[-1] + after = page[-1][0] return held @@ -972,6 +997,7 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None 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 @@ -990,21 +1016,25 @@ async def _merge_memories(run: _Run, d: NsDecision, memories: list[Any]) -> None if not entries: continue entries.sort(key=lambda e: to_naive_utc(e["valid_at"]) or run.now) # stable - 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, - ) + 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 @@ -1016,6 +1046,7 @@ async def _documents(run: _Run) -> None: 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 @@ -1033,7 +1064,8 @@ async def _documents(run: _Run) -> None: original = None if doc.get("blob_path") and not doc.get("blob_erased_at"): original = base64.b64encode(run.bundle.original(doc["blob_path"])).decode() - with _for(d): + # PublicationPending: committed, and the delivery worker publishes it. + with _for(d), contextlib.suppress(PublicationPending): await handle_knowledge_upsert( KnowledgeUpsertInput( org=d.target_org, diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 68227e3c131..5eecda99fe2 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, @@ -2096,10 +2096,11 @@ async def held_in( after: KeyInNamespace | None = None, limit: int = 5000, keys: Sequence[str] | None = None, -) -> list[KeyInNamespace]: +) -> list[tuple[KeyInNamespace, bool]]: """A page of the keys of every head of a namespace, of `keys` when given, deleted ones - included, in key order after `after`: what the namespace holds or has held, its - publication to ClickHouse owed or not.""" + included, in key order after `after`, each with whether its head 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] @@ -2111,12 +2112,12 @@ async def held_in( 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 " + "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) for r in rows] + return [(key_in_namespace(r), is_namespace_definition(dict(r))) for r in rows] async def unpublished_keepers( diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index 843bc2e88fc..bad904e97e4 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -37,6 +37,7 @@ 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"} @@ -255,6 +256,21 @@ async def _seed_source(ch: Any, src: _Api) -> None: 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( @@ -426,6 +442,16 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ("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"]) == ( @@ -487,6 +513,10 @@ async def test_an_org_moves_into_a_live_one_under_the_map( ) 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 synced = dst.op("knowledge.get", namespace="team-legacy", source_uri="synced.md") meeting = dst.op("knowledge.get", namespace="team-legacy", source_uri="meeting.md") diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index e3c6c5eab03..34bd8753208 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -546,30 +546,47 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( from server.knowledge.store import pg_documents from server.memory.store import pg_memory - heads = [("a", "-", "-", f"k{i}") for i in range(3)] + 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, *, after: Any = None, limit: int = 5000, keys: Any = None ) -> Any: - return [h for h in heads if (after is None or h > after) and keys in (None, [h[3]])][:limit] + return [h for h in heads if (after is None or h[0] > after) and keys in (None, [h[0][3]])][ + :limit + ] sent: list[tuple[str, Any]] = [] async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: sent.append((sql, params)) - for key, uri in (("k-ch", "ch.md"), ("k1", "held.md")): + 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": "a", "user_id": "-", "session_id": "-", "memory_key": key, "v": 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(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) - assert {k[3] for k in await imp._held_keys(None, "o", "n")} == {"k-ch", "k0", "k1", "k2"} + held = await imp._held_keys(None, "o", "n") + 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 "argMax(memory_type, version)" in sent[-1][0] and "GROUP BY" in sent[-1][0] assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k1"} assert "memory_key IN {keys:Array(String)}" in sent[-1][0] and sent[-1][1]["keys"] == ["k1"] assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"held.md"} @@ -724,8 +741,8 @@ async def test_a_resumed_run_writes_no_key_the_created_namespace_held( written: list[str] = [] counted: list[str] = [] - async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: - return {("a", "-", "-", "k1")} + async def held_keys(ch: Any, org: str, ns: str) -> dict[tuple[str, str, str, str], bool]: + return {("a", "-", "-", "k1"): False} async def write(run: Any, d: Any, rows: list[Any]) -> None: written.extend(r.memory_key for r in rows) @@ -869,10 +886,10 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe written: list[int] = [] counted: dict[tuple[str, str], int] = {} - held = {("a", "alice", "s1", "k1")} + held = {("a", "alice", "s1", "k1"): False} - async def held_keys(ch: Any, org: str, ns: str) -> set[tuple[str, str, str, str]]: - return set(held) + async def held_keys(ch: Any, org: str, ns: str) -> dict[tuple[str, str, str, str], bool]: + return dict(held) async def current(*_: Any, **__: Any) -> str: return policy @@ -920,12 +937,15 @@ def count(d: Any, what: str, n: int = 1) -> None: await imp._memories(run) assert written == expected, policy assert counted == {("n", what): n for what, n in counts.items()}, policy - # Resumed after the rows with no user: the target holds row 5, and the rest still land. - policy, held = "newest_wins", {("a", "alice", "s1", "k1"), ("b", "-", "-", "k3")} + # 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 written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [14, 15, 4, 7, 10, 12, 13, 8] + assert written == [15, 4, 7, 10, 12, 13, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: @@ -934,6 +954,7 @@ async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPa 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 @@ -942,6 +963,8 @@ async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPa 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] @@ -953,8 +976,10 @@ def count(d: Any, what: str, n: int = 1) -> None: async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: asked.append(keys) if calls: # the owners wrote k-late after the first call - return {("b", "-", "s2", "k-late")} - return {("b", "alice", "s9", "k-undated")} # written since, in another session + 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) @@ -971,6 +996,7 @@ async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: ) ] 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( @@ -978,13 +1004,18 @@ async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: ) 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"]] # just before each 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} + 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( From 7e1599a2bf27deebadf0aff95162dc8b6b74d40e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 08:15:00 +0530 Subject: [PATCH 26/32] loom instance: a merge picks one row per identity before newest_wins - The rows of one identity compete first, then the winner goes to its pass: a namespace definition before the rows with no user, any other row on to its user's key under `newest_wins`. A definition and a newer row of another type at its identity, from two merged namespaces, no longer both win, which wrote the older and held back the newer. - The held-key and held-address reads are tested on clickhouse-local over the production tables, a key whose type changed between versions among them, in place of checks on the SQL text. - A document committed with its publication owed is tested to count as written while the run goes on. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_import.py | 30 +++++----- tests/unit/test_instance_consolidation.py | 70 ++++++++++++++++++----- 2 files changed, 74 insertions(+), 26 deletions(-) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index fa265d25863..ba255d67627 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -747,11 +747,12 @@ async def _memories(run: _Run) -> None: 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. A namespace definition, which no other write of its key - retires, is one group of its own and is written before them.""" + 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.""" + Ref = tuple[str, str, str] # (source org, source namespace, memory id) batch: dict[tuple[str, str], list[Any]] = {} - exact: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} - scoped: dict[tuple[Any, ...], tuple[tuple[datetime, int], tuple[str, str, str]]] = {} + 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: @@ -764,15 +765,18 @@ async def _memories(run: _Run) -> None: continue merged[k] += 1 rank = (to_naive_utc(row.valid_at or row.created_at) or run.now, -i) - group: tuple[Any, ...] - if t in run.reach and not is_namespace_definition(row): # (target, user or None, key) - user = None if is_anonymous_user(row.user_id) else row.user_id - groups, group = scoped, (t, user, row.memory_key) - else: - groups, group = exact, (t, key_in_namespace(m)) - if group not in groups or rank > groups[group][0]: - groups[group] = (rank, (*k, str(m["memory_id"]))) - alone = {ref for _, ref in exact.values()} # under newest_wins, the definitions + 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() # under newest_wins, the definitions + for (t, (_, user, _, key)), (rank, ref, definition) in exact.items(): + if t not in run.reach or definition: + alone.add(ref) + continue + group = (t, None if is_anonymous_user(user) else user, key) + if group not in scoped or rank > scoped[group][0]: + scoped[group] = (rank, ref) 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) diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 34bd8753208..0c2a537efb3 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -18,6 +18,7 @@ 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()) @@ -556,10 +557,7 @@ async def held_in( :limit ] - sent: list[tuple[str, Any]] = [] - async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: - sent.append((sql, params)) for agent, key, uri, kind in ( ("a", "k-ch", "ch.md", "fact"), ("a", "k1", "held.md", "fact"), @@ -586,12 +584,52 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: held = await imp._held_keys(None, "o", "n") 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 "argMax(memory_type, version)" in sent[-1][0] and "GROUP BY" in sent[-1][0] assert {k[3] for k in await imp._held_keys(None, "o", "n", keys=["k1"])} == {"k1"} - assert "memory_key IN {keys:Array(String)}" in sent[-1][0] and sent[-1][1]["keys"] == ["k1"] assert await imp._held_uris(None, "o", "n", ["held.md", "new.md"]) == {"held.md"} - assert "source_uri IN {uris:Array(String)}" in sent[-1][0] - assert sent[-1][1]["uris"] == ["held.md", "new.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") == { + ("-", "-", "-", "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( @@ -777,11 +815,13 @@ async def test_two_merges_into_one_namespace_land_an_address_once( ) -> 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.""" + 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") @@ -802,6 +842,8 @@ async def held(ch: Any, org: str, ns: str, uris: list[str]) -> set[str]: 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()) @@ -871,6 +913,8 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("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 ] w = BundleWriter(tmp_path / "b") with w.section("memories") as sink: @@ -910,13 +954,13 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [14, 5, 15, 4, 7, 10, 12, 13, 8], # the definition, the rows with no user, the rest - {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 2}, + [14, 5, 15, 17, 4, 7, 10, 12, 13, 8], # the definition, no user, the rest + {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 3}, ), ( "auto_reinforce", - [0, 2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 8], - {"memories_not_live": 3, "memories_superseded": 1}, + [0, 2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 8, 17], + {"memories_not_live": 3, "memories_superseded": 2}, ), ): written.clear() @@ -945,7 +989,7 @@ def count(d: Any, what: str, n: int = 1) -> None: written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [15, 4, 7, 10, 12, 13, 8] + assert written == [15, 17, 4, 7, 10, 12, 13, 8] async def test_a_merge_writes_as_memory_import_does(monkeypatch: pytest.MonkeyPatch) -> None: From 1f1c07d98403b9cf8b090a97be4916a9a01bd5e2 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 08:43:39 +0530 Subject: [PATCH 27/32] loom instance: a removed source's kept documents move - A knowledge source's synced copy stays behind only while a source of its namespace writes it again or retires it: registered there, or removed with its copies to retire, as the copy's `source:` tag names it (`_source_tags`, `_RESYNCED`). A source removed with its copies kept writes them no more, so they move as any document does; they were left behind with no source listed to bring them back. - The merge reads the target's held keys in chunks of the bundle's own keys (`_load_held`), so the run's memory grows with the bundle, not with the target namespace. - The bundle encoder no longer turns bytes into text with replacement characters, nor handles tuples, which JSON encodes itself. - `keep` on an `sa:` subject is refused, as the runbook now says; `_Ref` moves to module level and `_memories`' second loop takes its own names. - A test covers a namespace definition winning over an older row of another type at its identity. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 31 ++++----- server/cli/instance_bundle.py | 4 +- server/cli/instance_export.py | 42 ++++++++---- server/cli/instance_import.py | 47 +++++++++----- .../test_instance_consolidation.py | 49 ++++++++++---- tests/unit/test_instance_consolidation.py | 64 ++++++++++++++++--- 6 files changed, 174 insertions(+), 63 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 818a8a5a418..3d084826fd1 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -8,15 +8,15 @@ run, with their settings. To move a whole deployment onto new hosts, see ## 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 they synced 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 | +| 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 @@ -77,10 +77,11 @@ search once the embedding worker's next full pass embeds them 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 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. + 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 @@ -185,8 +186,8 @@ subjects: # "/": rule 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. Any other subject - needs a mapping or `drop`. + 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`. - **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 diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py index 3f7e8ac3eab..c57045e1352 100644 --- a/server/cli/instance_bundle.py +++ b/server/cli/instance_bundle.py @@ -44,9 +44,7 @@ def _default(v: Any) -> Any: return v.isoformat() if isinstance(v, UUID | Decimal): return str(v) - if isinstance(v, bytes): - return v.decode("utf-8", errors="replace") - if isinstance(v, set | frozenset | tuple): + if isinstance(v, set | frozenset): return list(v) raise TypeError(f"cannot write {type(v).__name__} to a bundle") diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 95fca2101ca..f69a13b0889 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -20,7 +20,7 @@ from typing import Any from server.cli.instance_bundle import BundleWriter -from server.knowledge.domain.sources import SYNC_WORKER_ACTOR +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:" @@ -33,10 +33,15 @@ "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 the source, registered again, writes again: it keeps only -# its own copies up to date (`source_sync.ours`). A recording source lists its last weeks -# only and its transcripts are settled when written, so its copies move. -_RESYNCED = "actor = {sync:String} AND JSONExtractString(metadata, 'source_kind') != 'recording'" +# 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. @@ -308,8 +313,20 @@ async def memory_heads(ch: Any, org: str, ns: str) -> AsyncIterator[dict[str, An 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 + 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 @@ -328,7 +345,7 @@ async def _documents( "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}, + {"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"]))) @@ -346,12 +363,12 @@ async def _documents( async def _left_behind( - ch: Any, orgs: list[str], only: dict[str, list[str]] | None + 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} + 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 "" ) @@ -425,8 +442,9 @@ async def export( _write(w, "grants", (g for g in grants if g["namespace"] in content.get(g["org"], ()))) await _identity_sections(w, ch, orgs, selected) counts: Counts = {} + sources = await _source_tags(ch, orgs) await _memories(w, ch, content, counts) - await _documents(w, ch, content, counts) + await _documents(w, ch, content, counts, sources) return w.finish( { "source": { @@ -438,6 +456,8 @@ async def export( "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), + "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 index ba255d67627..d235c5ad6cb 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -51,6 +51,8 @@ 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 +_KEYS_PER_READ = 1000 # bundle keys per held-key read, well inside a request's size +_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] = { @@ -749,10 +751,10 @@ async def _memories(run: _Run) -> None: 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.""" - Ref = tuple[str, str, str] # (source org, source namespace, memory id) + 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]] = {} + 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: @@ -769,14 +771,14 @@ async def _memories(run: _Run) -> None: 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() # under newest_wins, the definitions - for (t, (_, user, _, key)), (rank, ref, definition) in exact.items(): - if t not in run.reach or definition: - alone.add(ref) + alone: set[_Ref] = set() # under newest_wins, the definitions + for (target, (_, user, _, key)), (best, winner, definition) in exact.items(): + if target not in run.reach or definition: + alone.add(winner) continue - group = (t, None if is_anonymous_user(user) else user, key) - if group not in scoped or rank > scoped[group][0]: - scoped[group] = (rank, ref) + 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) @@ -833,7 +835,6 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: 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 - from server.memory.app.conflicts import namespace_conflict_policy if (d := run.by_source.get((m["org"], m["namespace"]))) is None: return None @@ -844,10 +845,6 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: run.count(d, "memories_not_live") return None t = (d.target_org, d.target) - if t not in run.held: # once per target namespace - run.held[t] = await _held_keys(run.ch, *t) - if await namespace_conflict_policy(*t, ch=run.ch) == "newest_wins": - run.reach[t] = _reach(run.held[t]) 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 @@ -859,6 +856,26 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: return d, row +async def _load_held(run: _Run) -> None: + """Per target namespace, those of the bundle's keys it holds or has held (`_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 bundle, never with the target.""" + from itertools import batched + + 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), _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 diff --git a/tests/integration/test_instance_consolidation.py b/tests/integration/test_instance_consolidation.py index bad904e97e4..e8c3b8d35c4 100644 --- a/tests/integration/test_instance_consolidation.py +++ b/tests/integration/test_instance_consolidation.py @@ -195,19 +195,37 @@ async def _seed_source(ch: Any, src: _Api) -> None: original_filename="runbook.md", blob_content_type="text/markdown", ) - # Knowledge sources' copies: a file's, which its source writes again once registered, - # and a recording's transcript, which a source registered again never lists. - for uri, kind in (("synced.md", "gdrive"), ("meeting.md", "recording")): + # 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) FROM (SELECT * FROM " - "loom.documents FINAL WHERE org = {org:String} AND namespace = 'team' " - "AND source_uri = 'runbook.md')", + "{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") @@ -518,11 +536,20 @@ async def test_an_org_moves_into_a_live_one_under_the_map( 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 - synced = dst.op("knowledge.get", namespace="team-legacy", source_uri="synced.md") - meeting = dst.op("knowledge.get", namespace="team-legacy", source_uri="meeting.md") - assert not synced["found"] and meeting["found"] and meeting["content"] == doc["content"] - left = Bundle.open(bundle).manifest["left_behind"]["rows"] - assert [(r["kind"], r["n"]) for r in left] == [("documents_of_sources", 1)] + 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") diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 0c2a537efb3..71a4db3d5be 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -588,6 +588,51 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: 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_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, @@ -779,7 +824,7 @@ async def test_a_resumed_run_writes_no_key_the_created_namespace_held( written: list[str] = [] counted: list[str] = [] - async def held_keys(ch: Any, org: str, ns: str) -> dict[tuple[str, str, str, str], bool]: + async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: return {("a", "-", "-", "k1"): False} async def write(run: Any, d: Any, rows: list[Any]) -> None: @@ -915,6 +960,8 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe ("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: @@ -932,8 +979,9 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe held = {("a", "alice", "s1", "k1"): False} - async def held_keys(ch: Any, org: str, ns: str) -> dict[tuple[str, str, str, str], bool]: - return dict(held) + async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: + assert keys is not None and len(keys) <= imp._KEYS_PER_READ # the bundle's keys only + return {k: v for k, v in held.items() if k[3] in keys} async def current(*_: Any, **__: Any) -> str: return policy @@ -954,13 +1002,13 @@ def count(d: Any, what: str, n: int = 1) -> None: for policy, expected, counts in ( ( "newest_wins", - [14, 5, 15, 17, 4, 7, 10, 12, 13, 8], # the definition, no user, the rest - {"memories_the_target_holds": 2, "memories_not_live": 3, "memories_superseded": 3}, + [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], - {"memories_not_live": 3, "memories_superseded": 2}, + [0, 2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 8, 17, 19], + {"memories_not_live": 3, "memories_superseded": 3}, ), ): written.clear() @@ -989,7 +1037,7 @@ def count(d: Any, what: str, n: int = 1) -> None: written.clear() run.held, run.reach = {}, {} await imp._memories(run) - assert written == [15, 17, 4, 7, 10, 12, 13, 8] + 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: From 73380f5c745f42f2bf2db6976db248cf531283fd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 09:02:26 +0530 Subject: [PATCH 28/32] loom instance: the held-key reads always name their keys - `_held_keys` and `pg_memory.held_in` take the keys they read: every caller names them, and the whole-namespace path is gone. - The held keys are what the target holds of the bundle's keys, not of the rest of the namespace, as the docstrings now say; a ceiling note names the read's cost on a very large namespace and the upgrade. - `_left_behind` names its source rows apart from the source tags it takes; the export's comment, the `alone` comment and the bundle encoder's unreachable set branch are fixed or gone. - The merge test reads the held keys in chunks of two, a key held in a later chunk among them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_bundle.py | 2 -- server/cli/instance_export.py | 7 +++-- server/cli/instance_import.py | 35 ++++++++++++----------- server/memory/store/pg_memory.py | 14 ++++----- tests/unit/test_instance_consolidation.py | 25 ++++++++++------ 5 files changed, 44 insertions(+), 39 deletions(-) diff --git a/server/cli/instance_bundle.py b/server/cli/instance_bundle.py index c57045e1352..38943de1538 100644 --- a/server/cli/instance_bundle.py +++ b/server/cli/instance_bundle.py @@ -44,8 +44,6 @@ def _default(v: Any) -> Any: return v.isoformat() if isinstance(v, UUID | Decimal): return str(v) - if isinstance(v, set | frozenset): - return list(v) raise TypeError(f"cannot write {type(v).__name__} to a bundle") diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index f69a13b0889..2e2b09f3313 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -339,7 +339,8 @@ async def _documents( 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 copy a knowledge source writes again once registered. + # 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} " @@ -377,7 +378,7 @@ async def _left_behind( "AND active", params=p, ) - sources = await ch.query_all( + 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, @@ -399,7 +400,7 @@ async def _left_behind( f"WHERE {scope} AND superseded_at IS NULL AND user_id = '-' AND {_RESYNCED} GROUP BY org", params=p, ) - return {"code_repos": repos, "knowledge_sources": sources, "rows": rows} + return {"code_repos": repos, "knowledge_sources": to_register, "rows": rows} async def export( diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index d235c5ad6cb..5d6f28b0c33 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -51,7 +51,10 @@ 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 -_KEYS_PER_READ = 1000 # bundle keys per held-key read, well inside a request's size +# Bundle keys per held-key read, well inside a request's size. ponytail: a read filters +# on the namespace, the head of loom.memory's sort key, and the memory_key ngram +# index; a key-first projection 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. @@ -427,9 +430,9 @@ def __init__(self, ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, Targe 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: the keys it holds, 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. + # 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]]] = {} @@ -771,7 +774,7 @@ async def _memories(run: _Run) -> None: 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() # under newest_wins, the definitions + 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) @@ -857,9 +860,10 @@ async def _kept(run: _Run, m: dict[str, Any]) -> tuple[NsDecision, Any] | None: async def _load_held(run: _Run) -> None: - """Per target namespace, those of the bundle's keys it holds or has held (`_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 bundle, never with the target.""" + """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 itertools import batched from server.memory.app.conflicts import namespace_conflict_policy @@ -932,10 +936,10 @@ async def _write_memories(run: _Run, d: NsDecision, kept: list[Any]) -> None: async def _held_keys( - ch: Any, org: str, namespace: str, keys: list[str] | None = None + ch: Any, org: str, namespace: str, keys: list[str] ) -> dict[KeyInNamespace, bool]: - """Every (agent, user, session, key) the namespace holds or has held, of `keys` when - given, a deleted one included, each with whether its latest version is a namespace + """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 @@ -946,13 +950,10 @@ async def _held_keys( 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}" + "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: dict[str, Any] = {"org": org, "ns": namespace} - if keys is not None: - sql += " AND memory_key IN {keys:Array(String)}" - params["keys"] = keys - sql += " 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) } diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 5eecda99fe2..682edd10a70 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -2093,14 +2093,13 @@ async def held_in( org: str, namespace: str, *, + keys: Sequence[str], after: KeyInNamespace | None = None, limit: int = 5000, - keys: Sequence[str] | None = None, ) -> list[tuple[KeyInNamespace, bool]]: - """A page of the keys of every head of a namespace, of `keys` when given, deleted ones - included, in key order after `after`, each with whether its head is a namespace - definition: what the namespace holds or has held, its publication to ClickHouse owed - or not.""" + """A page of the heads of a namespace of 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] @@ -2108,9 +2107,8 @@ async def held_in( if after is not None: args += list(after) where += " AND (agent, user_id, session_id, memory_key) > ($4, $5, $6, $7)" - if keys is not None: - args.append([k for k in keys if not pg.unstorable(k)]) - where += f" AND memory_key = ANY(${len(args)}::text[])" + 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} " diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 71a4db3d5be..0eeecfa5a66 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -553,9 +553,7 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( async def held_in( org: str, ns: str, *, after: Any = None, limit: int = 5000, keys: Any = None ) -> Any: - return [h for h in heads if (after is None or h[0] > after) and keys in (None, [h[0][3]])][ - :limit - ] + 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 ( @@ -581,7 +579,8 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: 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) - held = await imp._held_keys(None, "o", "n") + 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"} @@ -668,7 +667,7 @@ async def stream_rows(ch: Any, sql: str, params: Any, **_: Any) -> Any: monkeypatch.setattr(pg, "enabled", lambda: False) monkeypatch.setattr(imp, "stream_rows", stream_rows) - assert await imp._held_keys(None, "o", "n") == { + 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, @@ -824,7 +823,7 @@ async def test_a_resumed_run_writes_no_key_the_created_namespace_held( written: list[str] = [] counted: list[str] = [] - async def held_keys(ch: Any, org: str, ns: str, keys: Any = None) -> Any: + 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: @@ -978,9 +977,10 @@ async def test_a_merge_writes_the_newest_of_the_rows_that_would_retire_each_othe 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: Any = None) -> Any: - assert keys is not None and len(keys) <= imp._KEYS_PER_READ # the bundle's keys only + 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: @@ -998,6 +998,7 @@ def count(d: Any, what: str, n: int = 1) -> None: 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 ( ( @@ -1013,6 +1014,7 @@ def count(d: Any, what: str, n: int = 1) -> None: ): written.clear() counted.clear() + reads.clear() run: Any = SimpleNamespace( bundle=Bundle.open(tmp_path / "b"), ch=None, @@ -1028,12 +1030,17 @@ def count(d: Any, what: str, n: int = 1) -> None: ) await imp._memories(run) assert written == expected, policy + # The bundle's nine keys in chunks of two, never the whole namespace. + assert [len(k) for k in reads] == [2, 2, 2, 2, 1], policy + assert sorted(k for chunk in reads for k in chunk) == sorted( + 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 + held[("b", "-", "-", "k3")] = False # k3 and k7 in later chunks than k1 written.clear() run.held, run.reach = {}, {} await imp._memories(run) From 1746958399797e45f3c950a78a6b3f2ab20527bf Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 09:16:54 +0530 Subject: [PATCH 29/32] loom instance: name the held-key read's ceiling plainly - The note at `_KEYS_PER_READ` says what a read filters on (org and namespace, then the memory_key ngram index, which a key under three characters skips) and the next step, in plain words. - `itertools.batched` is imported at the top of the module. - `pg_memory.held_in`'s docstring reads as the namespace's heads of given keys; the test fakes take `keys` as the real reads do. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/cli/instance_import.py | 10 +++++----- server/memory/store/pg_memory.py | 6 +++--- tests/unit/test_instance_consolidation.py | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 5d6f28b0c33..bce096fdbbe 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -28,6 +28,7 @@ from collections import Counter from collections.abc import Iterable, Mapping from datetime import datetime +from itertools import batched from typing import Any from server.cli.instance_bundle import Bundle, BundleError @@ -51,9 +52,10 @@ 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. ponytail: a read filters -# on the namespace, the head of loom.memory's sort key, and the memory_key ngram -# index; a key-first projection if merges into very large namespaces get slow. +# 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 a key under three characters skips; 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 @@ -864,8 +866,6 @@ async def _load_held(run: _Run) -> None: `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 itertools import batched - from server.memory.app.conflicts import namespace_conflict_policy keys: dict[tuple[str, str], set[str]] = {} diff --git a/server/memory/store/pg_memory.py b/server/memory/store/pg_memory.py index 682edd10a70..d34cab74458 100644 --- a/server/memory/store/pg_memory.py +++ b/server/memory/store/pg_memory.py @@ -2097,9 +2097,9 @@ async def held_in( after: KeyInNamespace | None = None, limit: int = 5000, ) -> list[tuple[KeyInNamespace, bool]]: - """A page of the heads of a namespace of 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.""" + """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] diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 0eeecfa5a66..0292b569efa 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -551,7 +551,7 @@ async def test_a_resume_counts_what_the_postgres_authority_holds( heads += [(("a", "-", "-", f"k{i}"), False) for i in range(3)] # in key order async def held_in( - org: str, ns: str, *, after: Any = None, limit: int = 5000, keys: Any = None + 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] @@ -1072,7 +1072,7 @@ async def bulk(body: Any, **kw: Any) -> Any: 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: Any = None) -> Any: + 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} From 687bc55d3285d2dc1afd8c9d6ae1968ebb1d1087 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 09:54:05 +0530 Subject: [PATCH 30/32] loom instance: short keys read first, tags name the subcommand, refusals tested The held-key reads put bundle keys under three characters in the first chunks: the memory_key ngram index cannot rule a granule out for one, so a chunk holding one reads the whole namespace, and grouping them keeps that to the fewest reads. _held_keys pages the Postgres heads in the shape of the export's pager. The instance group's subparser dest is `subcommand`, so its statements carry cli.instance.export and cli.instance.import; a stale --expect-plan is reported on stderr. _merge_problem is _landing_problem, as it judges created namespaces too. New tests: the export refusing before it writes (an erasure that has not completed, a selection of nothing, document publications owed), keep on an sa: subject refused, the dry run naming refusals the target cannot compile or budget, and the stale-plan message on stderr. The runbook's namespaces bullet is split into created namespaces, merged namespaces, merged rows and documents. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 68 ++++++------ server/cli/instance.py | 7 +- server/cli/instance_import.py | 29 ++--- tests/unit/snapshots/cli_tree.json | 4 +- tests/unit/test_instance_consolidation.py | 127 +++++++++++++++++++++- 5 files changed, 182 insertions(+), 53 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 3d084826fd1..7e33674fb02 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -100,15 +100,19 @@ subjects: # "/": rule acme/sa:ci-1a2b3c: drop ``` -- **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. `merge` writes into an existing namespace through +- **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 @@ -129,29 +133,29 @@ subjects: # "/": rule 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. The source's refusals - that reach the source namespace refuse the rows it brings, and none is stored on the - target's namespace. It 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. A created namespace's 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. 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. 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 write that commits but whose publication to ClickHouse - is owed is left to the delivery worker, and the run goes on: the receipt counts such a - write's memories as `memories_publication_pending`, as admission's answer for each is - lost, and its document as written. Per-type settings, policies and the guide land with - a created namespace only. + 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 diff --git a/server/cli/instance.py b/server/cli/instance.py index 45dce54e0a4..8170b825864 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -18,7 +18,7 @@ def register_instance_cli(sub: Any) -> None: 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="instance_cmd", required=True) + 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 " @@ -171,7 +171,10 @@ async def _plan_and_apply(ch: Any) -> int: ) return 0 if args.expect_plan != p.digest: - print(f"--expect-plan {args.expect_plan!r} is not this plan ({p.digest}): review it") + 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. diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index bce096fdbbe..f512cf798ca 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -54,8 +54,10 @@ _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 a key under three characters skips; a projection sorted by key first is -# the next step if merges into very large namespaces get slow. +# 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 @@ -200,7 +202,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr holds a grant, a namespace, a token or a task, as self-signup refuses it), 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 - (`_merge_problem`), an original missing from the bundle. Each is added as a + (`_landing_problem`), an original missing from the bundle. Each is added as a problem.""" from fastapi import HTTPException from pydantic import ValidationError as ModelError @@ -269,7 +271,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr continue try: row = _row(run, into, m) - if row is not None and (why := await _merge_problem(into, row, run.now)): + 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}" ) @@ -293,7 +295,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr ) -async def _merge_problem(d: NsDecision, row: Any, now: datetime) -> str | None: +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 @@ -874,7 +876,7 @@ async def _load_held(run: _Run) -> 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), _KEYS_PER_READ): + 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]) @@ -957,13 +959,14 @@ async def _held_keys( held = { key_in_namespace(r): is_namespace_definition(r) async for r in stream_rows(ch, sql, params) } - after = None - while pg.enabled(): - page = await pg_memory.held_in(org, namespace, after=after, limit=PG_PAGE, keys=keys) - held.update(page) - if len(page) < PG_PAGE: - return held - after = page[-1][0] + 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 diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 7d04e1d86ed..40c66820c78 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -8491,7 +8491,7 @@ "title": "positional arguments", "description": null, "dests": [ - "instance_cmd" + "subcommand" ] }, { @@ -8522,7 +8522,7 @@ }, { "option_strings": [], - "dest": "instance_cmd", + "dest": "subcommand", "action": "_SubParsersAction", "default": null, "const": null, diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 0292b569efa..4f1ba77bb69 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -161,10 +161,13 @@ def test_collisions_and_unknown_subjects_refuse_the_plan() -> None: ) decided = {s.subject: s.action for s in p.subjects} assert decided == {"sa:ci": "drop", "bob@x": "keep"} - # `keep` passes the same checks. - keep = {"subjects": dict.fromkeys(p.proposals["subjects"], "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"]) == set(p.proposals["subjects"]) + assert set(again.proposals["subjects"]) == {*p.proposals["subjects"], "acme/sa:ci"} + assert again.proposals["subjects"]["acme/sa:ci"] == "drop" + assert any("'sa:ci'" in problem for problem 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: @@ -587,6 +590,69 @@ async def held_uris(org: str, ns: str, uris: list[str]) -> set[str]: 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 @@ -704,7 +770,7 @@ async def nothing(*_: Any) -> set[str]: def test_an_original_changed_since_the_dry_run_stops_the_apply( - monkeypatch: pytest.MonkeyPatch, + 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 @@ -737,6 +803,8 @@ async def accept(**kw: Any) -> None: 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) @@ -1173,6 +1241,57 @@ async def test_the_dry_run_names_a_memory_the_target_refuses( 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] + + def test_a_landed_row_names_its_verifier_and_locker_as_the_plan_maps_them() -> None: from types import SimpleNamespace From ad7cc5f1144f362beaaec7bb8cdd95cc7c0af6ce Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 10:28:28 +0530 Subject: [PATCH 31/32] loom instance: a resume narrows its own row, revoked handles are refused A resumed landing whose namespace row an earlier run wrote returned without reading the plan again, so a plan that now asked for self-join approval (the target org serves others since) or named the owner was printed and never written. The row now takes from the plan only what narrows it: join_policy approval where it is open, and the mapped owner in place of the import's. Anything else on it stays, as the target's admins may have changed it, and no decision opens it. The plan refuses an account handle the target revoked outright, with a -legacy proposal: a revocation spans orgs, so the account would land with no token that signs in. An account the source revoked lands with no way to sign in either way and gets only the access check. The account checks move to _claim_problems. Also: keep on an sa: subject is refused with its own reason; the original check covers only the landings the apply writes; the dry run prints no approval on a finished landing, and the owner note follows the owner a resumed row keeps; the held-key read order is pinned by a test. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 36 ++++---- server/cli/instance.py | 11 ++- server/cli/instance_import.py | 105 ++++++++++++++++------ server/cli/instance_plan.py | 19 ++-- tests/unit/test_instance_consolidation.py | 91 +++++++++++++++++-- 5 files changed, 203 insertions(+), 59 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 7e33674fb02..71921ef4741 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -159,7 +159,8 @@ subjects: # "/": rule - **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), an email any target account signs in with, and an email another account of the + it), a handle the target revoked outright, in any org, which no token would sign in + as, 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 @@ -204,21 +205,24 @@ subjects: # "/": rule 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. 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`). +run then shows the plan's new decisions. A namespace row an earlier run wrote takes from +them only what narrows it: 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. +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 diff --git a/server/cli/instance.py b/server/cli/instance.py index 8170b825864..9a1d4156923 100644 --- a/server/cli/instance.py +++ b/server/cli/instance.py @@ -79,6 +79,7 @@ async def _run(ch: Any) -> dict[str, Any]: 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 = { @@ -88,8 +89,9 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: 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 "" - joins = " (self-join needs approval: the target org serves others)" if d.approval 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: @@ -99,7 +101,12 @@ def _print_plan(bundle: Any, p: Any, targets: Any) -> None: else: note = "" owner = owners.get((d.source_org, d.source)) - if d.action == "create" and not (d.account or done or subjects.get((d.source_org, owner))): + # 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: diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index f512cf798ca..40044a8ca73 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -196,18 +196,59 @@ 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: + why = "is revoked on the target, in every org: no token for it would sign in" + if d.source.lower() in revoked or d.target.lower() not in gone: + 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), 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 fastapi import HTTPException + 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.auth.self_signup import refuse_empowered from server.core.errors import ValidationError from server.memory.app.blacklist_guard import ( REGEX_PROGRAM_PER_SCOPE, @@ -215,25 +256,7 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr scope_program, ) - for d in p.namespaces: - t = targets[d.target_org] - # A name the target holds is this import's own row (else the plan refused it). - if ( - not d.account - or d.target in t.namespaces - or (d.target, source_key(bundle, d.source_org, d.source)) in t.done - ): - continue - try: - await refuse_empowered(ch, d.target_org, d.target.lower()) - except HTTPException: - p.problems.append( - f"{d.source_org}: account {d.source!r}: {d.target!r} already holds access on " - "the target (a grant, a namespace, a token, a task or a setting names it)" - ) - p.proposals.setdefault("subjects", {})[f"{d.source_org}/{d.source}"] = { - "claim": f"{d.target}-legacy" - } + 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: @@ -282,10 +305,9 @@ async def check(ch: Any, bundle: Bundle, p: Plan, targets: Mapping[str, TargetOr 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" ) - landing = {(d.source_org, d.source) for d in p.namespaces if d.action != "skip"} for doc in bundle.records("documents"): sha = doc.get("blob_path") - if (doc["org"], doc["namespace"]) in landing and sha and not doc.get("blob_erased_at"): + 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: @@ -516,6 +538,12 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> 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 := _narrowed(run, d, existing, row): + with _identity(): + await run.ch.insert( + "loom.namespaces", [{**existing, **change, "updated_at": run.now}] + ) + await grant_cache.changed(d.target_org) return if await directory().in_use(d.target_org, d.target, ch=run.ch): raise in_use @@ -551,6 +579,27 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: run.count(d, "namespace") +def _narrowed( + 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 = { diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 218e1753272..324175bae76 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -587,12 +587,21 @@ def _plan_subject(o: _Org, subject: str) -> None: # 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) and action != "keep": - o.subject( - SubjectDecision( - o.org, subject, "drop", note="service account: its owner makes a new one" + 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 " diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index 4f1ba77bb69..aff141fd3e9 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -166,7 +166,7 @@ def test_collisions_and_unknown_subjects_refuse_the_plan() -> None: 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'" in problem for problem in again.problems), again.problems + 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} @@ -218,6 +218,7 @@ def test_a_merge_needs_its_end_users_decided_and_its_grant_subjects_when_it_carr 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 @@ -235,10 +236,16 @@ def test_the_plan_says_who_owns_a_namespace_whose_owner_does_not_land( } 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_end_users_map_to_end_users_and_never_land_as_one() -> None: @@ -810,12 +817,14 @@ async def accept(**kw: Any) -> None: instance._cmd_import(args) -async def test_a_landing_holds_to_the_created_at_its_audit_row_recorded( +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.""" + 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 @@ -870,6 +879,17 @@ async def insert(table: str, rows: list[Any], **_: Any) -> None: 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. + since = NsDecision("acme", "team", "acme", "team", "create", approval=True) + held[0] = {**LANDED, "visibility": "public", "owner_email": run.actor, "description": "x"} + await imp._land(run, since, again) + assert written[1:] == [ + {**held[0], "join_policy": "approval", "owner_email": "alice", "updated_at": run.now} + ] + for row in (written[-1], {**held[0], "join_policy": "closed", "owner_email": "carol"}): + held[0] = row # narrowed already; a row its admins closed and gave an owner + await imp._land(run, since, again) + assert len(written) == 2 async def test_a_resumed_run_writes_no_key_the_created_namespace_held( @@ -1098,17 +1118,16 @@ def count(d: Any, what: str, n: int = 1) -> None: ) await imp._memories(run) assert written == expected, policy - # The bundle's nine keys in chunks of two, never the whole namespace. + # 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 sorted(k for chunk in reads for k in chunk) == sorted( - f"k{i}" for i in (1, *range(3, 11)) - ) + 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 # k3 and k7 in later chunks than k1 + held[("b", "-", "-", "k3")] = False # k7 in a later chunk than k1 and k3 written.clear() run.held, run.reach = {}, {} await imp._memories(run) @@ -1292,6 +1311,62 @@ async def nearly_full(*_: Any) -> int: 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_export import REVOKED + from server.cli.instance_plan import Plan + + asked: list[list[str]] = [] + + async def query_all(sql: str, params: dict[str, Any]) -> Any: + assert sql == REVOKED + asked.append(params["lowered"]) + 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 asked == [["alice", "bob"]] + 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 5bb9cdc6cf07fe4e61f376d08473622ba3503e1f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 10:55:11 +0530 Subject: [PATCH 32/32] loom instance: every subject the source revoked keeps its grants behind The export read the source's outright revocations only for the selected namespace names, so a revoked token subject or end user never reached the bundle: its grants landed, and the plan's refusal to map a revoked subject never fired. The export now reads them for every namespace name, owner, grant subject and end user it brings, the end user under the key its tokens are revoked by (`/user:`, `_revocation_keys`). revoked_subject reads that key for the plan and for _grants. The target does not carry the revocation, so an end user the source revoked needs an explicit keep or drop. A resumed landing's replanned row (`_replanned`) is stamped later than the row it replaces: loom.namespaces is ReplacingMergeTree(updated_at), and the run's start time could lose to a row written since or to a clock ahead of the CLI host's. Also: the runbook names the exception for a handle both sides revoked and says what a resumed row takes without calling an owner narrowing; _claim_problems branches once per refusal. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/consolidation.md | 63 ++++++++-------- server/cli/instance_export.py | 44 +++++++---- server/cli/instance_import.py | 28 +++++-- server/cli/instance_plan.py | 52 +++++++++++-- tests/unit/test_instance_consolidation.py | 89 +++++++++++++++++++---- 5 files changed, 206 insertions(+), 70 deletions(-) diff --git a/docs/operations/consolidation.md b/docs/operations/consolidation.md index 71921ef4741..711d8132ebe 100644 --- a/docs/operations/consolidation.md +++ b/docs/operations/consolidation.md @@ -160,26 +160,27 @@ subjects: # "/": rule 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, 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. + 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 @@ -192,7 +193,11 @@ subjects: # "/": rule 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`. + 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 @@ -205,14 +210,14 @@ subjects: # "/": rule 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 from -them only what narrows it: 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. -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 +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, diff --git a/server/cli/instance_export.py b/server/cli/instance_export.py index 2e2b09f3313..e82f8afc1a1 100644 --- a/server/cli/instance_export.py +++ b/server/cli/instance_export.py @@ -195,11 +195,7 @@ async def _identity_sections( orgs: list[str], selected: dict[str, list[str]], ) -> None: - p: dict[str, Any] = { - "orgs": orgs, - "pairs": _pairs(selected), - "subjects": sorted({ns for _, ns in _pairs(selected)}), - } + 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( @@ -257,9 +253,20 @@ async def _identity_sections( """, p, ) - # An account the source revoked lands with no password. - lowered = sorted({s.lower() for s in p["subjects"]}) - await _table(w, ch, "revoked", REVOKED, {**p, "lowered": lowered}) + + +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 @@ -272,19 +279,24 @@ def _count(counts: Counts, org: str, ns: str, section: str) -> None: async def _memories( w: BundleWriter, ch: Any, selected: dict[str, list[str]], counts: Counts -) -> None: +) -> set[tuple[str, str]]: """Every live head of each namespace, as the snapshot payload's rows plus their org - and namespace.""" + 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]]: @@ -439,13 +451,19 @@ async def export( raise SystemExit(f"no memory namespace to export: {', '.join(missing)}") await refuse_unpublished_documents(content) w = BundleWriter(out) - _write(w, "namespaces", (r for r in rows if r["namespace"] in selected.get(r["org"], ()))) - _write(w, "grants", (g for g in grants if g["namespace"] in content.get(g["org"], ()))) + 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) - await _memories(w, ch, content, counts) + 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": { diff --git a/server/cli/instance_import.py b/server/cli/instance_import.py index 40044a8ca73..5ae958a26c5 100644 --- a/server/cli/instance_import.py +++ b/server/cli/instance_import.py @@ -27,7 +27,7 @@ import uuid from collections import Counter from collections.abc import Iterable, Mapping -from datetime import datetime +from datetime import datetime, timedelta from itertools import batched from typing import Any @@ -41,8 +41,15 @@ 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.datetimes import as_aware_utc, to_naive_utc, 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 @@ -222,8 +229,9 @@ async def _claim_problems( else set() ) for d in claims: - why = "is revoked on the target, in every org: no token for it would sign in" - if d.source.lower() in revoked or d.target.lower() not in gone: + 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 @@ -538,10 +546,14 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> 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 := _narrowed(run, d, existing, row): + 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": run.now}] + "loom.namespaces", [{**existing, **change, "updated_at": at}] ) await grant_cache.changed(d.target_org) return @@ -579,7 +591,7 @@ async def _land(run: _Run, d: NsDecision, row: dict[str, Any]) -> None: run.count(d, "namespace") -def _narrowed( +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 @@ -701,7 +713,7 @@ async def _grants(run: _Run) -> None: 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 str(g["subject"]).lower() in run.revoked: + if revoked_subject(run.revoked, g["org"], g["subject"]): run.count(d, "grants_of_revoked") continue if (d.target_org, subject) not in spelled: diff --git a/server/cli/instance_plan.py b/server/cli/instance_plan.py index 324175bae76..04e0a5e136a 100644 --- a/server/cli/instance_plan.py +++ b/server/cli/instance_plan.py @@ -46,7 +46,14 @@ is_sso_namespace_name, validate_namespace_name, ) -from server.core.principals import AGENT, EVERYONE, GROUP, SERVICE_ACCOUNT, USER +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"] @@ -255,6 +262,15 @@ def at(v: Any) -> Any: # the bundle's ISO text or the target's naive UTC ) +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]: @@ -564,8 +580,19 @@ def _plan_subject(o: _Org, subject: str) -> None: ) return if subject.startswith(USER): - # Another deployment's end-user issuer may name other people with the same id. - if o.shared and action != "keep": + 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 " @@ -575,7 +602,8 @@ def _plan_subject(o: _Org, subject: str) -> None: "drop", ) else: - o.subject(SubjectDecision(o.org, subject, "keep", subject)) + 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: @@ -725,10 +753,22 @@ def plan( _plan_subject(o, subject) _check_users(o) for s in p.subjects: - if s.source_org == org and s.subject.lower() in o.revoked and s.action == "map": + 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: claim or drop 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} diff --git a/tests/unit/test_instance_consolidation.py b/tests/unit/test_instance_consolidation.py index aff141fd3e9..18060948827 100644 --- a/tests/unit/test_instance_consolidation.py +++ b/tests/unit/test_instance_consolidation.py @@ -248,6 +248,63 @@ def test_the_plan_says_who_owns_a_namespace_whose_owner_does_not_land( 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"}} @@ -879,17 +936,27 @@ async def insert(table: str, rows: list[Any], **_: Any) -> None: 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 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) - held[0] = {**LANDED, "visibility": "public", "owner_email": run.actor, "description": "x"} - await imp._land(run, since, again) - assert written[1:] == [ - {**held[0], "join_policy": "approval", "owner_email": "alice", "updated_at": run.now} - ] + 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 # narrowed already; a row its admins closed and gave an owner + held[0] = row # replanned already; a row its admins closed and gave an owner await imp._land(run, since, again) - assert len(written) == 2 + assert len(written) == 3 async def test_a_resumed_run_writes_no_key_the_created_namespace_held( @@ -1323,14 +1390,9 @@ async def test_a_handle_the_target_revoked_is_refused_unless_the_source_revoked_ from server.auth import self_signup from server.cli import instance_import as imp - from server.cli.instance_export import REVOKED from server.cli.instance_plan import Plan - asked: list[list[str]] = [] - async def query_all(sql: str, params: dict[str, Any]) -> Any: - assert sql == REVOKED - asked.append(params["lowered"]) return [{"subject": s, "reason": "operator"} for s in ("alice", "carol")] async def empowered(ch: Any, org: str, name: str) -> None: @@ -1358,7 +1420,6 @@ async def stored(ch: Any, ids: list[str]) -> set[str]: ) ch: Any = SimpleNamespace(query_all=query_all) await imp.check(ch, Bundle.open(tmp_path / "b"), p, {"acme": EMPTY}) - assert asked == [["alice", "bob"]] 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:])