# ClickHouse Loom > Self-hosted MCP server that gives AI agents shared long-term memory, document search with citations, and a code index stored in ClickHouse. # ClickHouse Loom documentation Source: https://loom.clickhouse.com/docs Give agents access to shared memory, cited documents, and indexed code through MCP, HTTP, or the SDKs. [Install Loom](/docs/getting-started/quickstart) [Try the playground](https://loom.clickhouse.com/playground/source-change) ## Start here - [Connect a coding agent](/docs/getting-started/connect-a-coding-agent) Share project context across agent sessions. - [Build with the SDKs](/docs/getting-started/first-agent) Write and recall a memory from your own agent. - [Configure models](/docs/getting-started/models-and-keys) Choose the models for retrieval and generation. - [Deploy for a team](/docs/operations/deployment) Choose a deployment and set up access for your team. For a specific client or framework, [find your integration](/docs/features/integrations). ## Browse the docs - [Guides](/docs/guides) Configure access, investigate agent runs, and connect tools. - [Features](/docs/features) Explore memory, documents, code, work records, and audit controls. - [Reference](/docs/reference) Find SDKs, HTTP and MCP operations, CLI commands, and settings. - [Operations](/docs/operations) Monitor, upgrade, and recover a Loom deployment. ## Use cases See how Loom supports [shared agent memory](/docs/use-cases/agent-memory), [document search with citations](/docs/use-cases/document-search), and [code intelligence](/docs/use-cases/code-intelligence). Browse the [use-case library](/docs/use-cases) or [casos de uso en español](https://loom.clickhouse.com/docs/es/use-cases). ## Evaluate and contribute [Check whether Loom fits](/docs/getting-started/overview), [evaluate it with your workload](/docs/getting-started/evaluate), or read the [architecture](/docs/architecture/system-overview) and [benchmark results](/docs/benchmarks/results). Contributors can start with the [repository guide](/docs/development/repository-guide). ## Find a quick answer Look up a term in the [glossary](/docs/glossary) or an answer in the [FAQ](/docs/faq). Agents can use the [documentation index](https://loom.clickhouse.com/docs/llms.txt) or the [combined Markdown](https://loom.clickhouse.com/docs/llms-full.txt). --- # Microsoft Agent Framework context provider Source: https://loom.clickhouse.com/docs/architecture/agent-framework-adapter `LoomContextProvider` implements the framework's context-provider interface over the asynchronous Python SDK. The optional extra admits only the tested framework minor series; the core SDK and server do not import the framework. Before a run, the provider searches the latest user text and adds matching facts to the framework's instructions. After the run, it sends new user and assistant text to `memory.set_from_messages` in bounded batches. It runs that hook once per turn, including a framework middleware loop. The framework keeps its own history; this provider stores durable facts rather than replacing a history provider. ## Invariants The user and framework session id derive a Loom session, preventing two users' equally named sessions from sharing extracted chunks. An omitted user reads all namespace memories the token permits and writes shared rows. Explicit user ids cannot have surrounding whitespace. Namespace grants authorize access; a user parameter is a filter. The server supplies actor and source provenance and applies ordinary conflict, erasure and rolling-schema rules. No database, cache or local history is added. Errors propagate through the framework's provider hooks, including errors after a model reply. Concurrent writes follow the server's normal conflict rules. ## Conversation protection A provider serves one logical conversation family. It retains the application-owned protection handles present at construction and callback entry, including ambient contributors and each later bound client handle. Native user and session ids route requests; they do not create or replace this authority. Restore reopens the existing capsule before constructing the provider. Owned recall and extraction run in the SDK's automatic capture context. The transport rechecks every retained family after credentials and before dispatch, observes replies before conversion, and durably marks all contributors before releasing a marked reply. The first marked recall may reach the model. Later automatic work refuses, and each extraction batch is checked before the next one can start. A refusal after a model reply propagates through the native provider lifecycle; it cannot undo the answer or tool effects. The provider adds no capability declaration or restored-host qualification. ## Source entry points - `sdk/python/loom/integrations/agent_framework.py`: `LoomContextProvider`. - `sdk/python/tests/test_agent_framework.py`: native provider and agent behavior. - `tests/integration/test_sdk_agent_framework_memory.py`: live extraction and recall. [Framework setup](/docs/features/integrations/frameworks#microsoft-agent-framework) --- # Agno user-memory database Source: https://loom.clickhouse.com/docs/architecture/agno-adapter The Agno adapter implements the user-memory methods of its 3.2 `BaseDb` interface through the synchronous Loom SDK. The optional minor-pinned dependency stays out of the core SDK and server. `MemoryManager` accepts this database independently of an agent's session database. Non-memory capabilities refuse instead of using a framework-default store. ## Invariants Each adapter binds a user and application store. Every SDK call carries that user and a derived session; keys include the same scope digest plus a native-id digest. A different explicit user is refused. Native user memories are JSON in episodic Loom rows, preserving ids, metadata and revisions without semantic merging of different native records. Actor and source provenance come from Loom's normal write path. The ordinary memory deletion, erasure and rolling-schema rules apply. Listing follows capped and projected pages, deduplicates overlap and hydrates truncated values before converting them to native objects. Content, topics and attribution filters, sorting, pagination and statistics run over this scoped user/store snapshot. There is no local persistent state. Concurrent edits keep the latest server write; bulk operations are a sequence of writes and can partially finish on failure. Namespace grants isolate mutually untrusted applications. ## Source entry points - `sdk/python/loom/integrations/agno.py`: `LoomMemoryDb`. - `sdk/python/tests/test_agno.py`: native memory-manager behavior. - `tests/integration/test_sdk_agno_memory.py`: live memory scope and provenance. --- # Assistant design Source: https://loom.clickhouse.com/docs/architecture/assistant Loom's native assistant answers namespace questions through bounded model turns and read-only operations, under the caller's identity. It owns context selection, tool execution, streaming, cancellation, citations and accounting in the web process. It does not require a separate chat runtime or a conversation database. ## Surfaces The dashboard Ask AI panel, `POST /v1/assistant/chat/completions`, `assistant.ask`, its MCP tool and both SDKs use the same runtime. The chat route accepts OpenAI-shaped user and assistant messages, with streaming or whole responses. The op accepts a question and history. Callers provide history; Loom stores no conversation for these interfaces. A system message, file, tool result or model supplied by a client cannot override the server's runtime. The namespace header and existing op identity tuple keep their meaning. ```mermaid flowchart LR Caller["dashboard / SDK / HTTP / MCP"] --> Runtime["native assistant"] Runtime --> Context["bounded host context"] Runtime --> Model["explicit streaming provider"] Model --> Runtime Context --> Transport["authenticated MCP transport"] Runtime --> Transport Transport --> Operations["read-only registry operations"] Operations --> Evidence["answer-owned receipts"] Evidence --> Publication["citation and accounting checks"] ``` ## Each caller's own identity Admission checks the caller's viewer role, narrowed reads, expiry, org model-call switch, namespace budget share and concurrency. Org-wide callers and answer tokens or their descendants cannot start an answer. A viewer token is delegated from the asker's own subject, for this namespace and answer lifetime, ending with the caller's session or revocation. No global service account authorizes a tool call. The namespace's active mirrored-source registrations mark the answer before budget, context or model work. Marked responses send the marker first and use private accounting. The delegated token retains session protection and the answer's fixed mirror-admission bit. Current source ACLs still decide each returned item. A source becoming active later cannot widen an unmarked answer. Unknown admission refuses. Every native tool request goes through `/mcp?toolset=assistant` in process, in a child task with the answer's bearer and run id. It passes token verification, revocation, namespace and row-reach checks, role gates, idempotency and operation accounting. The existing assistant roster and forced arguments prevent writes, reinforcement, arbitrary run ids and recursive assistant calls. The model sees a bounded subset of schemas for relevant read operations, without provider overrides. Tool results and history are untrusted data and confer no authority. ### Support Citations are checked against structured results actually delivered during this answer, not an eventually consistent analytics read. A memory citation needs its exact key and version; a code citation needs a returned path and line span; a document citation needs a returned source and section; a help citation requires text from `help.get` for the page or section. An outline from a truncated or continuation read supplies no evidence for unread sections. A SQL block must match a successful `insights.query` statement. Unknown citations or operation and setting names refuse completion. Arbitrary result text cannot supply source identifiers for verification. A verified citation proves that evidence was returned, not that every sentence is entailed by it. Each citation check records whether that source was returned to this answer. Support for an uncited answer derives from its tool receipts. Prior-value questions read `memory.history` after locating the key. A historical memory citation binds the requested key to the exact version and value returned in that receipt; redacted rows cannot verify it. Current-value questions use current reads. Population questions use `namespace.inventory`, keeping its read scope, observed-agent and member distinction, totals, bounded top lists and incomplete reasons. A complete count does not make a shorter top list exhaustive. ### Steps Host context and model-selected tools have separate `origin` values in progress events. Each tool has a run id and an existing request-ledger row. Model progress records the logical turn, physical attempts, duration and usage status. Generations use existing trace spans and customer attribution. Streaming text is provisional until `[DONE]`. EOF, a failed tool, a malformed model frame, a provider refusal or an exhausted budget cannot publish a completed answer. Required private cost delivery precedes `[DONE]`. Source proofs retained from tools are renewed after final accounting and before the terminal event, including tools whose nested transport runs in another task. Disconnects close and join the model and tool work before final accounting. ### Starters and cards The dashboard's existing namespace starters and draft cards use their existing operations. A write remains the person's explicit action under their own role. ### Asking again A retry is the caller's choice. Model requests are sent once per logical turn; an uncertain stream is never replayed automatically. There is no fallback provider. ## The agent definition `server/assistant/domain/instructions.py` holds the instructions. The host selects bounded initial context before the first model request. Named code questions use a symbol lookup; conceptual code questions use code search; Loom usage questions use help search; counts use the analysis catalog; other questions use memory and document search. Additional calls are adaptive, with a shared total bound and normalized query deduplication. The model need not select its initial context. ## Loom's documentation Help searches read the build's bundled documentation. A model must fetch a returned section before citing it. The source's audience distinguishes operating Loom from using it, and examples are not deployment facts. ## The analysis op `insights.query` runs one read-only SQL statement over an allowlisted set of Loom tables and returns its rows, capped. The agent uses it for questions no other read answers, such as which agents wrote the most contradicted facts last week or what a namespace holds by kind and age. Any token with `viewer` on the namespaces it names can call it directly, on any transport, and it joins the [assistant toolset](/docs/reference/mcp#the-assistant-toolset). A token whose `read_scope` is narrower than its namespaces is refused it, as every op outside `SCOPED_OPS` and `NARROW_SAFE_OPS` is. The event catalog has two views. Use `loom.analysis_ordinary_agent_events` for ordinary requests and worker events, or `loom.analysis_agent_events` for the request ledger with marked model, spend, work and outcome fields masked. Both views enforce the signed organization and namespace before returning rows. Their definer reads the physical event tables and the analyst holds column grants on the views. Both physical tables and their storage metadata are outside those grants. The projections, signed predicates and definer clauses are included in the entity version digest. ### The boundary is the database user The statement runs as a dedicated ClickHouse user, `loom_analyst`, never as Loom's own user or the reader user. Loom does not parse or rewrite the statement to scope it. It sends the scope as settings and runs the statement, less one trailing `;`, as a subquery, `SELECT * FROM (` and `)` on lines of their own, so a trailing `--` comment ends at the newline. ClickHouse parses only a `SELECT` or `WITH` there and reports a syntax error for anything else. The wrapper is not what isolates orgs; the user's grants, settings profile and row policies are: | What the statement tries | What stops it | | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | a table or column outside the allowlist (tokens, secrets, keys) | grants: `SELECT(col, …)` on each allowlisted table, nothing else | | another org or namespace, through a filter, `JOIN` or subquery | a row policy on each physical table and the same signed predicate inside the masked event view | | a deleted or erased row, or a version a later one replaced | the row policy carries the table's live predicate and applies after `FINAL` (below) | | `system.*`, `information_schema`, `SHOW`, `DESCRIBE`, `KILL QUERY` | no grant on `system` tables, `SHOW COLUMNS` or `system.processes` | | `EXPLAIN`, whose estimates count other orgs' rows | inside the subquery, `EXPLAIN` needs `CREATE TEMPORARY TABLE`, which the user lacks | | `mergeTreeIndex()` and other index readers | ClickHouse refuses them on a table with a row policy | | `url()`, `file()`, `s3()`, `remote()`, `cluster()`, `executable()` | no `READ ON URL`, `FILE`, `S3`, `REMOTE` and no `CREATE TEMPORARY TABLE` grant | | `aiGenerate()` and the other AI functions, which send rows out | they take credentials only from a named collection, and the user has no `NAMED COLLECTION` grant | | a write, DDL or a temporary table | `readonly = 2`, held `CONST` in the user's settings profile | | `SETTINGS` that widen time, memory, rows read or result size | the profile's `MAX` constraints; `result_overflow_mode` and `read_overflow_mode` are `'throw'` and `CONST` | | `SETTINGS use_query_cache = 1` or `use_query_condition_cache = 1` | both `0`, `CONST`, so no cached result or granule map crosses from one scope to another | | `SETTINGS send_logs_level = 'trace'`, whose log lines quote the key | `send_logs_level = 'none'`, `CONST` | | `SETTINGS max_threads = 256`, taking the host's CPU | `max_threads` pinned as `MAX` | | `SETTINGS` that rename the scope | the row policy's signature check fails, so the statement reads no rows | **Signed row policies.** Loom sends four custom settings with each statement: the org (`loom_org`), the namespaces (`loom_ns`), an expiry (`loom_exp`) and `loom_sig`, the HMAC-SHA256 under a 256-bit key of one length-prefixed string of the other three and the statement's query id: the request's `::`, new for each statement, whose per-request random nonce keeps two requests, of one tenant or two, from sharing an id (a probe outside a request takes a random UUID). The client's retry of a statement resends the same id with `replace_running_query = 1`, so it replaces its own attempt ClickHouse still runs. The expiry covers every attempt the client's retry ladder can make at the time cap (`scope_ttl_s` in `server/insights/app/analysis.py`). Each physical allowlisted table's policy, `TO loom_analyst`, admits a row only when its `org` and `namespace` match the settings, the expiry is in the future, and the signature matches the hash ClickHouse computes with the key written into the policy. A statement may set custom settings itself (`readonly = 2` allows it), but without the key it cannot sign another scope, so a changed scope reads nothing. A statement can read its own scope with `getSetting`, but the policy signs the query id Loom sends with the statement (`initialQueryID()`, the same on every server the statement fans out to), so a signature lifted from one statement reads nothing when sent with another, by the same caller or any other. The policy reads every setting through `toString`, so a statement that sets one to a number or an array cannot make the policy raise an error, whose message would quote the policy and its key; and Loom never passes on a ClickHouse message that names the scope settings. **The settings prefix.** ClickHouse takes a custom setting only under a prefix its `custom_settings_prefixes` names: `SQL_` in ClickHouse's default configuration, `custom_` on ClickHouse Cloud. The first time it loads the secrets, Loom sends `SELECT 1` with `loom_probe` for `SQL_` and then `custom_`, and names the scope settings and the profiles' stamps under the first one the server takes; a server that takes neither refuses analysis with a message that names `custom_settings_prefixes`. The prefix is the server's, not the version's: a server on ClickHouse's default configuration keeps `SQL_` and the same entities, and the structure digest a version pins is spelled with `SQL_`. On a `custom_` server each Loom process leaves one refused `SQL_loom_probe` in the server's logs. Each policy also carries its table's live predicate, the one the erasure census counts (`tombstoned_at IS NULL` on `loom.memory`), and the profile holds `final = 1` and `apply_row_policy_after_final = 1` `CONST`. A deletion or an erasure tombstones every version of a row, and the row stays in the table until a merge or a purge, so `FINAL` picks each key's latest version and the policy then drops it when that version is a tombstone: a deleted or erased key is absent, and its earlier versions do not come back. A second policy, `AS PERMISSIVE USING 1 TO ALL EXCEPT loom_analyst`, on every table the analyst has a policy on (the canary and a retired table included), lets every other user, Loom's own included, read every row of them, whatever the server's `users_without_row_policies_can_read_rows` says. ClickHouse ORs the permissive policies on a table, so this one would widen any permissive policy someone else put on one of these tables: before every write Loom lists them in `system.row_policies` and, finding one, writes nothing and reports it, naming it in the server log and in `loom ch-setup`'s refusal, for an admin to drop or make restrictive. A restrictive policy is left alone, since it narrows every user it names. The analyst user, its profiles and its policies' names are server-wide, so analysis needs one Loom per ClickHouse service: a deployment that finds the analyst's scope policy in another database writes nothing and reports it, naming that database in the server log. The key and the analyst's password are random and kept together, as one sealed value, in one row of `loom.analysis_secrets`. The password holds a lower and an upper case letter, a digit and a symbol, which ClickHouse Cloud requires of a user's password. The row is sealed with `server/core/secrets_at_rest.py` in the shape `loom secrets reseal` rewrites (`SEALED` in `server/cli/secrets.py`). The reseal reads under `own_write_reads`, skips a row that is gone and holds the analysis lease; with [analysis key rotation](#analysis-key-rotation-limits) the CLI rotation holds it too, so they never interleave, and the printed rotation, which takes no lease, stores its row at a version from ClickHouse's clock at insert time in nanoseconds, far above any reseal's `version + 1`. A row a reseal puts back during a rotation is handled by the [order of a write](#provisioning). The first write draws them under the lease below and every replica reads the same row. A root-secret rotation only reseals them, so the policies never change key; when the key cannot be read, [provisioning](#provisioning) says what happens. The analyst user cannot read the key: it has no grant on `system.row_policies` or on `loom.analysis_secrets`, and it cannot run `EXPLAIN`. The masked view's signed predicate uses the same hidden-argument expressions. The analyst profile pins `format_display_secrets_in_show_and_select = 0`, and the analyst has no display-secrets privilege. Native isolation checks cover the view's metadata, result predicates and raw-table denial as well as policy and query-log secrecy. **What the query log holds.** Loom never turns query logging off: ClickHouse Cloud pins `log_queries` for the service's users and refuses a statement or a settings profile that changes it. It keeps the secrets out of what is logged instead: - Every statement that carries the key or the password runs with `log_queries_cut_to_length = 1` and `log_formatted_queries = 0` (`LOG_TEXT_CUT` in `server/insights/domain/analysis.py`), which ClickHouse Cloud leaves unconstrained. ClickHouse then logs the statement, in `system.query_log`, in its server log and in `system.opentelemetry_span_log` (Cloud traces a share of statements), as only the number of characters it removed, and writes no `formatted_query`, which the cut does not reach. The printed SQL sets both first, for the session it runs in. - ClickHouse itself leaves the password out of a logged `IDENTIFIED BY`. - With `LOOM_CH_LOG_COMMENT_STATEMENT_DIGEST` on, `log_comment` carries a statement's shape and first 200 characters; a statement that carries a secret, or one run as the analyst, carries the literal-masked shape alone. - An error raised inside a row policy quotes the policy, and ClickHouse logs that error in `system.query_log`'s `exception` column; the probe's unsigned read raises one on every table by design. So the key's two padded forms, the only places the key enters the HMAC, are written in the policy as `decrypt(encrypt(pad, key), key)` (AES-256-ECB), which ClickHouse evaluates to the pad and prints as `decrypt('aes-256-ecb', '[HIDDEN]')` in an error message and in `SHOW CREATE ROW POLICY`. The HMAC is the same, so a build N-1, which wrote the pads in clear, signs statements these policies accept. The key is in ClickHouse's own access storage (on disk, or in Keeper when access is replicated), in a backup of the access entities, in the distributed DDL queue of a cluster that writes access `ON CLUSTER`, in `system.row_policies`, which shows the policy's arguments in full, and in any server log line other than the statement line the cut shortens. All of these are read only by whoever administers the ClickHouse host, who can read every row anyway, and by Loom's own user where it has `SHOW ROW POLICIES`; that user can already open the sealed row. **Why the model receives no ClickHouse credentials.** A ClickHouse login in the agent would read every org, skip the request ledger and the exposure records, and keep no link to the asker's token. The analysis op runs inside Loom's request path: the token is verified first, the namespaces are checked as on any read, and the call is ledgered. ### Provisioning The analyst user, its settings profiles, grants and policies are written with SQL, never in a ClickHouse config file, which would put the key in the repository. A server whose ClickHouse user has access management (the bundled ClickHouse's `loom` user, a self-managed admin) writes them itself, and draws the secrets row when there is none and it sees no analyst user, in the order the rules below give (the order of a write), so a first install cut short is a row without a user, which the next boot finishes with the stored key. Elsewhere an admin uses one of two commands: - `loom ch-setup`, run as a user with access management, writes the entities under the rules below (it holds the lease and writes unless the stored version is newer than its own), so it is also the repair on a server that cannot write them. It draws the row only when there is none and no analyst user exists; over a lost row with the user still there, it refuses: until the rotation of [analysis key rotation](#analysis-key-rotation-limits), the recovery is to drop the analyst user and run it again. - `loom ch-setup --apply-analyst-sql`, run with explicitly configured existing access-management credentials, applies only the analyst entities under the same lease and lost-key rules. It reads the native policy definitions for Loom's database before writing the policies and grants. The setup creates the analyst login on first use and keeps its existing password on later writes. `loom ch-setup --print-analyst-sql` refuses with a nonzero result and prints no statements or secrets. The setup verifies the live policy definitions before it writes. General `--print-sql` prints database and reader preparation with a password placeholder. Entity writes cut their query-log text and disable local statement capture so policy expressions and passwords stay out of both logs. The allowlist lives in code with the column comments that become the agent's catalog, so the grants, the policies, the event views and the catalog come from one definition. The rules a write keeps: - **One writer at a time.** A write holds the cluster lease `analysis.entities` (`server/core/leases.py`), waiting for it when another holds it, and reads what the entities hold once it has it. `loom secrets reseal` takes the same lease. - **Never over a newer build.** The analyst's main settings profile carries the stored version; a version names exactly one set of grants and policies (a unit test pins it), so a change to either is a new version. A build writes when there is no stored version or its own is newer, and at its own version only to repair (below) or as `loom ch-setup`, so during a rolling upgrade a build N-1 never narrows N's grants or loosens N's policies. N-1 keeps answering on N's entities: its statements that name a column N dropped are refused until the roll forward. - **The order of a write.** The version is the last of the entities. The main profile's pins come after every policy, the canary's included: on an upgrade the older profile's `log_queries = 0` stays in force until no policy holds the pads in clear. They come before every grant, so a new pin is in force before the grant it guards. A first draw by a boot or `loom ch-setup`, made while no analyst user exists, stores the secrets row before it creates the user. A rotation, by the CLI or the printed SQL (both with [analysis key rotation](#analysis-key-rotation-limits)), is a short maintenance step that keeps analysis unavailable while it runs: 1. It deletes the secrets row, which only decides what a rotation cut short looks like: a lost row, which `loom doctor` maps to `--rotate-analysis-key`. 2. It sets the new password, so a statement that reaches a server holding the new password cannot sign in with the old one, wherever its key came from. 3. It ends every statement the analyst is running (`KILL QUERY WHERE user = 'loom_analyst' SYNC`, `ON CLUSTER` where there is a cluster). That needs the `KILL QUERY` grant beside access management; the CLI checks for it before the delete and refuses without it. A statement ended this way answers `ANALYSIS_UNAVAILABLE`. 4. It writes the policies and the rest of the entities under the new key. 5. It waits for the new policies to reach every server, ends the analyst's statements again (a statement a lagging server started under its old policy keeps that policy until it ends), and then stores the new row, with ClickHouse's clock at insert as its stored time, which `loom secrets reseal` carries over unchanged. Where the admin user can read `clusterAllReplicas(, system.row_policies)`, the CLI waits until each server's policy carries the new key: once it does, a new statement with the old key reads nothing there, whatever password the server still holds. When a server is unreachable, or has not taken the new key after ten settle times, it exits without storing the row and names the server; analysis stays unavailable, and a rerun once the server is back rotates again. Elsewhere, and always in the printed SQL, which cannot wait on a condition, it waits a settle time instead (`ch_analysis_rotation_settle_s`, a catalog setting, default 30 seconds), which the operator sets above the lag the deployment's ClickHouse shows for access changes. On a single server, on a cluster that applies access statements `ON CLUSTER` with `distributed_ddl_output_mode = throw`, and wherever the CLI confirms every server's policies, no answer is ever empty during a rotation: it is right or `ANALYSIS_UNAVAILABLE`. Where it can only wait the settle time and access replicates asynchronously (through Keeper, as on ClickHouse Cloud), a server slower than that could, once the row is stored, still hold the old policies: until it applies them, a statement it serves under the new key reads no rows or fails to sign in (never another scope's rows), a probe that reaches it answers `ANALYSIS_UNAVAILABLE`, and, after a leak, whoever holds the old key and password can read any org's allowlisted rows through it. `loom doctor` judges a rotation by the time stored with the row, against ClickHouse's `now()`, and always by probes: a few dozen signed reads, each on a new connection so that a load balancer spreads them. A probe that signs in reports the server it reached (`hostName()`); one that fails to sign in runs nothing and names no server. Where Loom's user can list policies, doctor also reads which key each server's policy carries: through `clusterAllReplicas(, system.row_policies)` on a cluster (it needs the `REMOTE` and `CREATE TEMPORARY TABLE` grants and `SHOW ROW POLICIES`), or from the local `system.row_policies` on a single server. Within three settle times of the stored time, any failure is a server still applying the rotation, and it names a longer settle time. Past that: - Some probes pass and others fail: some servers are not applying access changes, an admin's problem, which it names (with the servers, where the policy read shows them) instead of `--live`, since a new rotation would not reach them either. - Every probe fails and the policy read shows every server on one key, the row's or another: no server is behind the others, so the row itself is stale, a rotation stopped after the password change with a row a reseal put back, and it names `--live`. - Every probe fails and the servers disagree: some servers are not applying access changes, an admin's problem, which doctor names with both groups of servers, asking to be run again once they agree; the rule above then decides the row. - Every probe fails and there is no policy read (Loom's user cannot list the policies, or cannot list every server's): the two causes look the same, so it names both. - **The caps apart.** The caps are deployment settings, kept in a second profile of their own: a write holding the lease (a boot, `loom ch-setup`) writes them when the stored ones differ from its settings, the printed SQL always writes them, and nothing else does, so they never touch the version. They are read at boot, not live; with [analysis key rotation](#analysis-key-rotation-limits), `loom doctor` reports a caps profile that differs from the server's settings. - **No granted table without its policy.** By default ClickHouse lets a user with no policy on a table read every row of it, so each policy is replaced in place, every other user's before the analyst's, before any grant is given; then every grant and role outside the allowlist and the canary is revoked, and then the allowlist is granted, since a table's revoke also takes the column grants under it; and a policy is never dropped: a table that leaves the allowlist keeps one that reads nothing. - **The key never changes by itself.** The secrets row is drawn once, and every read of it, the one under the lease included, runs with the read-your-writes setting Loom uses across replicas (`own_write_reads` in `server/core/ch.py`). A replica reads the key from the row at each probe (with [analysis key rotation](#analysis-key-rotation-limits), before each statement); a rotation's `KILL QUERY` (the order of a write) ends the statements already running. A row that does not open, or is gone while the analyst user exists, answers `ANALYSIS_UNAVAILABLE` and is a `loom doctor` problem. Until [analysis key rotation](#analysis-key-rotation-limits) the recovery is to drop the analyst user and run `loom ch-setup` again; with it, the recovery is `loom ch-setup --rotate-analysis-key`, which runs from a CLI at least as new as the stored version, first proves its `LOOM_JWT_SECRET` is the deployment's against the root's own record in `loom.signing_keys` (refusing where none is recorded), and refuses while the analysis row opens; then, holding the lease, it draws a new key and password and does a full write of its own version under them, in the order of a write, storing the row at the version it read plus one, or at ClickHouse's clock when there was no row. Until the row is stored no replica has a key to sign with, so every replica answers `ANALYSIS_UNAVAILABLE`, and a run cut short leaves that state for the next run to finish. A rotation on purpose, after a key may have leaked, is the same command with `--live`, which skips the refusal for a row that opens and drops the row once the version and root checks pass, so analysis is unavailable for the length of the run; a replica that still holds the old password gets an authentication failure, which answers `ANALYSIS_UNAVAILABLE` too. A replica probes the analyst user at boot and then every `ch_analysis_probe_interval_s` (a minute by default), in the background, as the analyst itself, so the probe needs no access management: A signed read of `loom.analysis_canary`, whose one row sits in a reserved scope (the empty org and namespace, which `insights.query` refuses as a request's scope) under a policy with the same key, must return that row: the policies accept the key. After that check, a stored entity version newer than this build's skips the remaining catalog and grant checks: the newer build checks its own entities. A current, older or absent version continues with these checks: - a signed read of each allowlisted table in that reserved scope must count no rows: no extra policy widens what the analyst reads (under the server default a table with no analyst policy counts rows too, which a write repairs; a write is never made over a permissive policy Loom did not write, which is named instead); - a `system` table, and a column outside the allowlist (`memory.value`), must be refused; - an unsigned read of each allowlisted table and of the canary must fail for want of the scope settings (the table has a policy that reads them), and the analyst's own `SHOW GRANTS` must name nothing but the allowlist and the canary. A failed check answers `ANALYSIS_UNAVAILABLE`, which no client resends, and is a `loom doctor` problem. Every ClickHouse answer that is not a clean probe is a finding, a statement's own cap included (a count in the reserved scope that hits one was not narrowed to nothing by a policy), and a repair that fails keeps the finding it was for: a replica whose problem no write could fix answers `ANALYSIS_UNAVAILABLE` with the problem in `loom doctor`. A probe that got no answer at all (a dropped connection, a client-side wait that ran out, the pool or the lease held elsewhere, the analyst's concurrency cap, a server short of memory) is no pass either: it keeps a finding, and leaves a replica that was serving or starting answering `OVERLOADED`, which a client resends after 5 s, as does a statement that finds ClickHouse short of memory. No replica serves on a check that has not passed; past three probe intervals with no answer, `/v1/health` and `loom doctor` name it while the replica keeps answering `OVERLOADED`. `/v1/health` answers without a token, so the problem it shows is Loom's own text: a ClickHouse error shows as its code and error name, with what it means for a cause Loom knows (a password the server's rules refuse, a missing privilege); the password gets its own fix, every other cause the default, and an error without a code shows its kind. The driver's text and the names of policies and databases go to the server log, and the 503 a caller gets names no cause. Unless the stored version is newer than its own, a replica that writes the entities itself writes them again under the lease after a check failed with a definite answer that a write repairs: a table without its policy, a canary under another key (with [analysis key rotation](#analysis-key-rotation-limits), checked again once three settle times have passed since the row's stored time, as `loom doctor` does, since a server still applying a rotation looks the same), a grant outside the allowlist. Elsewhere `loom doctor` names `loom ch-setup` as the fix. A policy Loom did not write, which a write cannot remove, is left to an admin: `loom doctor` reports it, and the server log names it where Loom's user can list policies, or the table that admits rows in the reserved scope where it cannot. The canary shows only that its own policy has the key; a single table's policy under another key, which only a hand edit leaves, shows as empty answers from that table. Between a policy dropped by hand and the next probe, ClickHouse by default lets the analyst read every row of that table. The ClickHouse that Loom configures itself (the bundled ClickHouse in Compose and the chart's development ClickHouse) sets `access_control_improvements.users_without_row_policies_can_read_rows` to false, under which a user with no policy on a table that has policies reads nothing, while the permissive `USING 1` policy keeps every other user reading. Every other server, ClickHouse Cloud and a self-managed one included, keeps the default and has that window, one probe long. ### What it can read The allowlist covers metadata, not content: the identity tuple, keys, kinds, versions, timestamps, counts, statuses, op names and latencies, from the memory, conflict, usage, document and request-ledger tables. Memory values, document text, chunks, prompts, search queries and ledger arguments are left out; a question about content goes through `memory.search`, `memory.ask` or `knowledge.search`, which apply their own scope and sensitivity rules. The allowlist admits a table only when what the [erasure saga](/docs/architecture/memory-architecture#erasure-saga) removes from it is gone for the analyst too: its policy carries the census live predicate of a table the saga tombstones (`server/erasure/store/census.py`), the saga deletes or scrubs its rows in place (as `agent_events.scrub` does), or the census lists it as holding no memory content. So a statement after an erasure cannot read what it removed. ### The catalog `insights.catalog` returns the allowlisted tables, their columns, types and comments, and the notes a correct query needs: which tables hold one live row per key and which one row per event. It is generated from the allowlist, so it never names a column the user cannot read, and it leaves out the probe's canary. ### Limits, fairness and the ledger A statement runs under the caps the profile pins as `MAX`: execution time, rows read, memory and result rows, each a setting in the catalog. A statement over a cap fails with the cap it hit and how to narrow the query. Every org's statements run as the one analyst user, so fairness between orgs comes from Loom: `insights.query` and `assistant.ask` each get their own rate-limit class (`server/core/ratelimit.py`; the chat route draws from `assistant.ask`'s), so neither spends the budget of the ops filed under `default`, and the profile's `max_concurrent_queries_for_user` bounds the analyst user's share of ClickHouse. Each replica also runs at most a set number of statements per org at once (a catalog setting, default 2). That limit is per replica, so one org can hold that many times the replica count; with the defaults (8 for the user, 2 per org) an org holds half the share on two replicas and all of it on four, and a deployment with more replicas lowers the per-org setting or raises the user's. Each call writes one `agent_events` row with its row count and latency (identifier keys in `server/observability/event_args.py`) and the statement's digest and length. The `sql` argument joins the ledger's text keys, which record a digest, never the text; a restricted namespace drops text keys from the ledger, so the op also records the digest as `sql_digest`, an identifier key. Citation verification matches SQL against the arguments of a successful request-owned `insights.query` receipt. The analyst profile holds `log_queries_cut_to_length = 1` and `log_formatted_queries = 0` as `CONST`, so `system.query_log`, the span log and the server log record each statement the analyst runs without its text: its user, timing, rows read and settings, the scope and its signature among them. A signature reads rows only with the analyst's password, for its own query id, until its expiry. A statement ClickHouse refuses is logged with its error message, which can quote the whole statement (an unknown column's error quotes the query it was looked up in, the caller's statement inside the wrapper), also for a restricted namespace whose ledger drops the text; ClickHouse Cloud pins `log_queries_min_type`, so the error rows cannot be left out. Each probe adds error rows to `system.query_log`: one for each allowlisted table and the canary (the unsigned reads) and one for each read it expects refused. The deploy delta leaves the analyst's statements out of its shapes. The rows a statement returns are stored nowhere; an error can quote a value it failed on, which ClickHouse's logs keep ([stored data](#stored-data-and-erasure)). ## Isolation proof The operation transport and database analysis-user checks remain the authorization boundaries. Native runtime fixtures must cover scope replacement, token revocation, model-selected tools outside the roster, forged citations, interrupted streams and required private delivery. Mocked tests do not establish a deployed provider or a real database boundary; those integration checks require an isolated admitted stack. ## Analysis key rotation limits The analysis-key rotation described in the analysis sections is a separate design, not a capability added by the native model runtime. Existing recovery procedures and maintenance limits continue to apply. The native runtime changes no database-user provisioning or rotation algorithm and does not establish a rotation integration test. ## Deployment The assistant runs in the Loom web image. `LOOM_ASSISTANT_ENABLED` enables it, and `assistant.nativeEnabled` renders the setting in Helm. Paid answers require an explicit native provider and model with a completion price. Provider credentials and gateway transport use the existing Loom mechanisms. No additional service, ingress peer, container image or database is rendered. See [operator steps](/docs/operations/assistant). ## Stored data and erasure Live answer state consists of request-owned tasks, bounded messages and receipts. It is discarded when the request ends. A disconnected request is not resumable. No live cancellable state is put in an analytical table. Existing request and cost ledgers, audit and exposure records keep their current storage and erasure rules. This change adds no content table, identity database or schema migration. Caller-held dashboard history is still managed by its existing protected session rules. External chat archives stay outside Loom; the offline history converter checks owner bindings and retains stable conversation, message and parent identities. It produces caller-held data for the existing history input, not a second server store. Retained provisioning metadata and database volumes are not erased by a code upgrade. ## Model and cost OpenAI and Anthropic use the shared guarded HTTP model pool; Bedrock uses a signed Converse stream through that pool. The fake route is explicit and offline. Real providers need configured credentials and a known price. `assistant_price_model` names a price-table reference for an alias; its operator must verify that rate for the selected route. Usage records preserve cache reads and both cache-write TTLs; reasoning tokens remain unknown when the provider does not report them. No default temperature or speculative 400 negotiation is sent. Bounds cover total time, model steps, tool count, context bytes, tool result size, answer size, per-turn output tokens, total tokens and model cost. Each model turn reserves an upper estimate before sending. A failed request with incomplete usage retains the reservation as an estimate, not fabricated tokens; its ledger arguments mark `out_cost_estimated` and `out_model_usage_status`. Reported usage is charged once, including failures after usage arrived. Host context and model-selected tools share the answer's remaining cost allowance. The shared model HTTP sender reserves a priced upper bound before every provider send, including retries and redirects. Only text inputs use the serialized-byte input bound; image, audio, document and provider-owned tool payloads refuse. Serialized request bytes bound text input tokens; the output cap and largest cache-write rate bound completion cost. Unpriced models, unbounded output and protocols without a bounded price refuse before dispatch. Prices are specific to embedding or completion protocols and to the provider route; a completion rate cannot admit an embedding or a native provider alias. Offline fake-model prices cannot authorize an HTTP inference send. Built-in LLM reranking uses the completion reservation. External reranking and native embedding routes without a configured price contract refuse before sending. Authentication token exchange is separate from inference. A swallowed tool refusal still refuses the answer. Tool reservations remain charged to the answer allowance after failure or cancellation. Reported charges remain on the tool's own ledger row; sends without reported usage leave reservation estimates on the answer ledger, with no invented token counts. Known charges are never reported a second time. Reservations are conservative and can refuse further work before actual reported spend reaches the ceiling. A zero cost ceiling refuses calls. ## Who can use it Authentication and viewer access to the namespace are required. A model-call switch or an unreadable budget refuses further work. The analysis user remains a separate read-only database boundary; a model never receives database credentials. ## Rolling upgrades No schema is changed. Historical additive migrations and retained metadata stay readable by an older build. Runtime replacement is a capability cutover, not proof that old and new assistant implementations can share every deployment setting. Keep the assistant disabled during a mixed serving fleet until its native path is verified. Keep mirrored-source creation unavailable until all serving builds and consumers enforce its publication boundaries. Do not restart a retired runtime to roll back: its durable queues may execute work. The [cutover procedure](/docs/operations/assistant#retention-and-cutover) requires an approved maintenance window and a separately reviewed rollback plan. ## Source entry points - `server/assistant/app/runtime.py`: admission, mirror marking and publication. - `server/assistant/app/agent.py`: bounded host and model orchestration. - `server/assistant/app/tools.py`: registry schemas and authenticated MCP dispatch. - `server/assistant/app/evidence.py`: citation receipts. - `server/llm/agent.py`, `agent_http.py`, `agent_bedrock.py`: streaming model protocol. - `server/assistant/app/routes.py`, `ask.py`: chat and op surfaces. ## Invariants Each tool authorizes the asker's subject and fixed scope. A result cannot grant access. Each answer has one run, finite work and one model usage capture per sent turn. Required private delivery and source checks precede completion. No background model job or resume queue is created. No operator data is deleted as part of runtime replacement. ## Related - [Storage authority](/docs/architecture/storage-authority) - [Rolling upgrades](/docs/architecture/rolling-upgrades) - [LLM architecture](/docs/architecture/llm-architecture) - [Assistant setup](/docs/operations/assistant) --- # Cells Source: https://loom.clickhouse.com/docs/architecture/cells A deployment's memory can outgrow one Postgres primary and one ClickHouse service, and an org may want its memory in services of its own. A **cell** is one complete Loom deployment as this documentation describes it: its replicas and workers, one Postgres unit (a primary with its standbys), one ClickHouse service, one document bucket prefix, its own public host, and its own signing keys, grants, workers and erasure. A **router** on the deployment's shared host sends a request to the cell that holds what it addresses. An org lives in exactly one cell, the one that placed it, and never leaves it. An org is placed at attach (the orgs the cell held, and its configured orgs), by `loom cell update` (a changed configured org) or `loom cell place`, or at the first verified request of a principal scoped to it. A deployment with one cell and no router works as a single deployment does. Cells need the Postgres authority (`LOOM_STORAGE_AUTHORITY=postgres`) and authentication that every transport enforces (`auth_actually_required()`, and `LOOM_MCP_AUTH_MODE` not `open`): `loom cell attach` refuses without them, and a process with `LOOM_CELL` set refuses to boot without them. [Storage authority](/docs/architecture/storage-authority) describes what a cell holds and how its two stores agree. ## Participant lifecycle baseline A participant advertising the ninth `host_proof` field `cell-retirement-v1` enrolls before its first fresh primary acceptance read and uses permanent guarded retirement. A serving cell heartbeat includes its `participant_id` beside the fingerprint, allowing a replacement to be joined to the participant registry. Workers children enroll independently and do not publish serving instance rows. Native commands hold one admission scope through their complete org or principal work and drain: claim lookup and release share that scope; token readiness, keyring read, signing and audit share another. Connections and helper calls do not retire a command that still has principal work to perform. Store pairing is verified before enrollment and fresh acceptance. Org-free diagnostics do not install an accepting view. The pre-schema `ch-setup` ownership probe discards its diagnostic mode result and checks only store/cell identity before raw database user/profile setup; its optional analyst-row work opens a separate verified, enrolled scope and obtains fresh acceptance. That bootstrap exception admits no tenant or token work. Local physical-death evidence requires the same host, kernel boot and PID namespace. It accepts an absent PID, a different process birth, or the captured birth in a single fresh kernel process record showing a zombie with exactly one thread. A zombie leader with other threads is unproved. Known-zero tagged queries remain a separate requirement before retirement; kernel process exit does not settle a query still executing in a store. Permanent completion drains application work and buffered writes before sealing Postgres openings. Pool construction, connection initialization, acquisition and native control tasks remain owned until they actually finish. Completion closes its pool within the remaining shutdown deadline; a later disconnect does not start another cleanup wait. Under the Postgres authority, every authority session carries the participant UUID in its startup `application_name`, including dedicated and unmarked sessions. Retirement verifies the deployment and epoch against the exact ClickHouse and Postgres pair, then requires no other backend with that participant tag. Idle backends count too. The metadata verifier excludes only its own backend and must finish closing within the same deadline. Local abort, cancellation and an unacknowledged close leave the participant unretired; later positive backend absence can resolve it. Manual retirement, reaped-child recovery and dead-process sweeps use the same store checks. The proof relies on the deployment's existing [primary endpoint and fencing requirements](/docs/operations/postgres#self-hosted-postgres). Builds without participant session tags use the generic authority application name `loom`. Recertifying their retained identities requires all such Postgres backends to be absent, including idle pools; stop and drain the remaining legacy authority clients before that census. Unrelated tagged participants can remain live. A deployment whose verified, immutable authority is ClickHouse needs only its ClickHouse settlement checks, including during recovery of a legacy participant. A missing authority record or a mismatched configuration never selects that path. The capability identifies installed code; it does not prove that every older process or unsafe retirement client has disappeared. Before online configuration finalization is supported, stop every unsafe manual retirement and pruning writer and prevent its binary/image from restarting. Inventory and positively terminate every accepting server, workers child, standalone worker and native command that overlapped those writers. Include paused boots, already retired/pruned identities and lifecycle-capable processes started during the overlap: old maintenance code could have hidden their rows too. Only then start replacement accepting and maintenance processes with this lifecycle. A shared image tag, pod deletion, readiness or heartbeat expiry is insufficient. Keep exact PID/boot/namespace/start or trusted runtime termination evidence with the deployment's upgrade record. No CLI flag or stored acknowledgement substitutes for that evidence, and the runtime census does not verify the external inventory. Census retained legacy rows while unsafe writers are stopped. Recertify a retained identity only after exact verifiable physical death and positive settlement in every authority store. Keep empty or unknown proofs quarantined. If the legacy inventory is incomplete, stop all accepting/native-command and retirement/pruning processes, positively terminate or fence every runtime that could execute an old binary, and prevent old restarts. Only after that physical quiescence may the operator request an exact audited cleanup of selected unknown legacy participant identities. There is no automatic age-based cleanup or affirmation bypass. Restart only guarded lifecycle processes afterward. Unknown or partitioned runtimes remain blockers. This baseline is an operational prerequisite, not a release-cut requirement. Configuration finalization also needs the directory's controller-fencing protocol; the lifecycle certificate alone cannot authorize reservation release. ## Why whole deployments A cell shares no store, key, lease or worker with another. Every guarantee a single deployment makes (tenant isolation, a revocation that holds at once, erasure coverage, a worker lease, an audit chain, a restore) holds per cell unchanged, and an org's data, grants and erasure never span cells. The router adds the directory and the routing rules below; each cell adds a check that it holds the org a request addresses. What spans orgs becomes per cell: - a token is valid in the cell that minted it and no other; - deployment-wide rows are per cell: the global blacklist (`org='*'`), runtime settings and overrides, policy rules, rate-limit and budget overrides, signing-key rotation, a subject's revocation. `loom cell each -- ` runs an org-free admin command in every cell with a short-lived credential per cell, records each cell's outcome, resumes the cells that failed, and fails until all succeed; `loom doctor` compares the cells' settings and configuration fingerprints and names what differs; - the code and tracker orgs (`LOOM_CODE_ORG`, `LOOM_TRACKER_ORG`) are each cell's own: each cell indexes its own repositories, at the ingest cost of each; - an operator's platform view and the dashboard are per cell, at the cell's host. ## The router The router is a stateless HTTP proxy, run as several replicas behind the deployment's shared host, released on its own and supporting cells of build N-1 and N. It holds the directory in its own Postgres database: - `cells`: cell, public host, the bearer-token issuers it alone accepts (its own `LOOM_JWT_ISSUER`, its `LOOM_JWT_TRUSTED_ISSUERS`, its end-user issuers), its stores (its deployment id and the bucket name and prefix), its state (`attaching`, `serving`), when attach started (`attach_started_at`, which attach writes under the directory's lock only after all its refusals have passed, before it writes any row in the cell other than its probes and `--revoke-unprovisioned`'s revocations, and which a resumed attach reads), its tenancy mode and when it was set (prepare writes the first, and attach records each it raises or tries to raise), whether it is closed to new orgs and its placement quota (`placements_max`), the SHA-256 of the credential it calls the router with (`current`, and during a rotation `next`), its root-secret fingerprint (`keys_fp`), its `probe_url` (the router's own for the first cell), the names and key thumbprints of its break-glass bots, and its configuration fingerprint (`current` and, during a change, `next`; the fields named under "Checked continuously"), which attach and `loom cell update` write together with the cell's own copy of that fingerprint (`loom.cell_self`); - `placements`: org, cell. One row per org, written once and never deleted; - `hosts`: every cell's host and the shared host's aliases (below). The router has its own operator credential, set in its configuration and never in the directory; every operator change of the directory is made with it, and every change, placements included, is written to the router's audit log. Attaching a cell also takes a platform-admin credential of the cell being attached. The router reports its own liveness and readiness, apart from any cell's. The router is put in front of the existing deployment first, passing every request to it; that deployment becomes the first cell when it is attached, and keeps the shared host as its own host, so its clients, tokens, refresh tokens, OAuth clients and registered callbacks keep working. The router answers its own paths (`/cells/`, `/livez`, `/readyz`) itself, and routes everything else, a cell's `/v1/health` paths included, to `attaching` and `serving` cells alike, in order: 1. **By host.** A request to another cell's own host goes to that cell. The shared host, and any alias of it recorded in `hosts`, are the router's own configuration and are handled by rules 2 to 4 (rule 4's cell is the pass-through upstream, before the first cell is registered and after, since prepare registers it at that address), never answered 421; any other host that no `cells` row names answers 421. Every URL a cell hands out names its own host: its OAuth and OIDC endpoints, the device flow's verification URI, the sign-in callback (`LOOM_OAUTH_ISSUER`, registered at the identity provider per cell), its JWKS, the dashboard's pages and assets, and its MCP resource metadata. MCP clients of a cell other than the first use the cell's host, which the cell's setup lines print. 2. **SCIM** goes by host, as rule 1 does: each cell's identity provider application provisions it at its own host (below); SCIM on the shared host is the first cell's, except a `/scim/v2/Groups` request carrying a JWT, which goes by its issuer as rule 3 does. The Groups routes are tenancy-checked (they write the org's `loom.principal_groups`). 3. **By issuer.** A token-bearing request to the shared host goes to the one cell that accepts its `iss` claim, read unverified; the cell verifies. An issuer no cell accepts answers 401. Until the first cell is `serving`, rules 2 to 4 send every request on the shared host to rule 4's cell, which verifies it, so the deployment behind the router serves the orgs it holds as before through prepare, the `LOOM_CELL` rollout and attach; from the rollout until `serving`, a new org also needs the directory at every process with `LOOM_CELL` set (it answers 503 there while the directory is unreadable). This covers MCP and every op, whatever org a body names, and the federated and end-user issuers' tokens of integrations. 4. **Everything else on the shared host goes to the first cell**: its OAuth and device flows, refreshes, callbacks, password and self-signup requests, health probes, and the sign-in page; a token revocation (`/oauth/revoke`) of a JWT goes by its issuer, as rule 3 does, and of an opaque refresh token to the first cell, since only the first cell's clients use the shared host (`loom logout` revokes at the host it signed in at). The shared host's discovery documents are the first cell's. The router reaches a cell at the `upstream_url` its directory row records, an address inside the deployment's network (the first cell's is `LOOM_ROUTER_UPSTREAM_URL`, written by prepare, so registering it changes no route; a later cell's attach writes), never at the cell's public host, which names the router itself; before the first cell is registered, rule 4's cell is the deployment it was put in front of (`LOOM_ROUTER_UPSTREAM_URL`). The shared host is `LOOM_ROUTER_SHARED_HOST`, the first cell's own host and that cell's `hosts` aliases. It forwards each request as the client sent it (its raw path and query, its own `Host`) with the router's own view of the client's address, scheme and host in `X-Forwarded-For`, `-Proto` and `-Host`, replacing what the client claims there (so each cell lists the router's addresses in `LOOM_TRUSTED_PROXIES`, or it counts every client as the router for its sign-in limits and reads the scheme as the router's), drops the headers that describe one connection (and those `Connection` names), keeps every header line of the answer (a second `Set-Cookie` included), streams both bodies (a server-sent event stream included), answers 502 when the cell cannot be reached, and never forwards a path under `/cells/` (one it does not serve answers 404). A registered first cell with no upstream address answers 503, as any cell's does. It reads the cells, their issuers and hosts once per `LOOM_ROUTER_DIRECTORY_CACHE_S`, answering from the last table while a stale one is read again behind it, so a directory that hangs or cannot be read delays no request; before its first read, it answers 503. An issuer two cells list (which attach refuses) routes to neither. A client finds an org's cell with `GET /cells/lookup?org=`, unauthenticated and rate-limited; an org with no placement answers the first cell with the same body as an org placed there (only a placed org's answer is cached, so timing and an outage can still tell them apart: an org name is not a secret), and before any cell is registered the lookup answers 503 with the code `NO_CELL`; a directory it cannot read for an org it has not cached answers 503 with `BACKEND_UNAVAILABLE`. A client matches the code, never the message: on `NO_CELL`, and on a 404 from a deployment with no router, `loom login --org` keeps the host it was given (the shared host, served as before by rule 4, or the single deployment); on a 429 it waits the `Retry-After` and asks again, for at most `--wait` (default 2 minutes), then refuses as a rate refusal; on any other answer it refuses, naming the router, so no flow starts at a cell that may not hold the org. An org's cell is public, as a workspace's URL is: the lookup tells that an org outside the first cell exists. `loom login --org`, the first cell's sign-in page (which asks for the org first) and the setup lines start every OAuth, device and sign-in flow at the org's cell host, so no flow crosses cells; a browser is redirected only to the start of a fresh flow. Only the first cell is ever in `recording`: a cell whose `first` row is `(false, …)` treats any mode but `enforced` as `enforced` in its org triggers, its mode cache and its CLI, so a later cell's mode row set to `recording` records nothing. A cell in `recording` reads its own state with `GET /cells/v1/cells/`, with its router credential, answered only for the cell the directory's unique index names first and accepted only when the credential's SHA-256 is one of the hashes the directory records for ``, within `LOOM_CELL_ROUTER_TIMEOUT_S` (default 5 s, the placement call's timeout); a refused, failed or late answer counts as unreadable. With the directory unreachable, rules 1 to 4 route from the router's cached cells; a lookup of an org it has not cached and a placement answer 503. The operator's routes, each with the router's operator credential, are under `/cells/v1/operator/cells/`: `limit`, `credential` and `register` (prepare's), the row itself (`GET`, with the name of any other row, which attach reads for its refusals, its done check and its resume), the first cell's attach (`attach/begin`, `attach/place`, `attach/enforced` and `attach/serving`, in that order), and `DELETE`. Each but `register` answers a cell the directory does not hold 404 with the code `NO_SUCH_CELL`, so a 404 without it is a router replica of an earlier build. Every call that succeeds, the read included, is written to the audit log (a registration rerun, which changes nothing, writes none), and every call runs a fixed number of statements, each bounded by the directory's statement timeout (enforced on the directory's server too); the read and the removal carry the derived bounds `loom cell` waits for. Every change takes the directory lock and then the cell's row lock (the order registration, the operator changes and the removal take). Every router replica runs a build with these routes before a first cell's attach starts: an earlier build's placement collides with an attach batch's as a transient 503, and its registration can add a later cell mid-attach, which every attach call then refuses until it is removed. Each attach call refuses unless the row is the first cell's, `attaching`, and records the deployment id the call names, and while any other row exists (registration refuses a later cell until the first is `serving`, and a router replica of an earlier build could still register one): - `attach/begin` carries the cell's fingerprints exactly as `loom.cell_self` stores them, its root-secret fingerprint, the allow lists attach judged the stores by, and fresh nonces. It refuses a fingerprint whose deployment id, bucket, prefix, public host or issuer host differ from the row's (an issuer host other than the cell's own is refused), and one whose live placement body, with an org name at its longest, would pass the router's body bound, naming the largest fields. Outside any directory transaction it runs registration's probe at the row's `probe_url` and asks the row's `upstream_url` for the deployment id, so the stores attach reads are the ones the live cell serves from. Then, under the locks, it writes `attach_started_at` once, the fingerprints only while the row has none (other fingerprints there answer 409: they change with `loom cell update`), and `keys_fp` on every call, and audits the allow lists. It is idempotent. Its body has its own bound, 256 KiB, past which it answers 413. - `attach/place` places a batch of at most 500 orgs (within the 64 KiB body bound) once `begin` has run and the directory mode is `enforced`, past the cell's closed mark and quota. It runs a fixed number of statements: one insert of the batch that skips an org placed already, one read refusing the batch (rolled back, naming the org) when an org is placed in another cell, one count, and one audit row per org it placed and one for the call. A live placement of the same org runs beside it once the mode is `enforced`; both hold the cell's row lock, a live placement reads the winner again once it holds it, and every insert skips an org placed already and counts only what it wrote, so the org is placed and counted once. - `attach/enforced` records the directory mode `enforced`, after which the first cell places new orgs live; it is idempotent. - `attach/serving` runs the probe and the upstream check again, then, under the locks, computes the row's issuers from its fingerprints (`bearer_issuers` of `current` and `next`) and marks the cell `serving`; on a `serving` cell it answers at once, audited. `begin`, `place` and `enforced` on a `serving` cell answer 409. `DELETE` removes the row of a cell that is `attaching` with no placement, whatever its directory mode, with its host rows, audited: a first cell is backed out until its first placement, and a later cell registered by an earlier build stops blocking the first attach. A placement in flight either commits first, and the removal refuses, or finds no row. The router cannot read the cell's stores, so `loom cell remove`, which calls it, checks a first cell's Postgres first ([Operations](#operations)). ## SCIM and sign-in across cells Each cell is its own application at the identity provider: an OIDC client for sign-in at its host and a SCIM application provisioning its `/scim/v2`, both assigned to the same group of people, the people of that cell's orgs. A person the identity provider deactivates, deletes or unassigns is deprovisioned in every cell whose application they were assigned to; Loom cannot see an application set to admit unassigned people or to skip deactivation on unassignment, so the operator configures each application to require assignment and to deactivate on unassignment. Each cell keeps its SCIM users, deactivations and tombstones exactly as a single deployment does ([SSO and SCIM](/docs/operations/sso)); the router holds no identity. A cell in `enforced` with SCIM on admits a person only while its SCIM data qualifies that person's complete identity graph. `scim.refuses_subject` checks the primary subject, token creator, every parent and any acted-for subject together, in the concrete target org before grants or placement. A wildcard token supplies no guessed org; the concrete operation checks the complete graph again. A person's signed email and the verified email from their OIDC sign-in are positive ownership witnesses. In the target org, the check resolves one normalized owner from an active account's owner or its verified contact pair (`VERIFIED_EMAIL_SQL`). Two different owners refuse. An email-shaped canonical owner is both mandatory and a positive witness. Every contact on every active account of that owner is mandatory, including an unlinked password contact; that unverified contact cannot supply a positive witness or resolve another owner. At least one positive witness is required. Every mandatory address needs its own active, undeleted `scim.user_id(email)` row. Only a missing own row may pass as a work address of an active primary row belonging to this person's positive witnesses. An inactive or deleted own row always refuses. One person's verified email never qualifies a different root or service-account ancestor. Exemptions are closed: an active registered bot and its agents, including machine or workload exchanges backed by that registration, and a signed end user whose issuer and end-user metadata were verified. A prefix, an admin role or the absence of email creates no exemption. An actual bearer naming another `sa:` subject uses the current personal service-account row: it must exist, remain unrevoked and unexpired, and have a creator. Its creator and every persisted lineage subject must qualify, even when grant inheritance is disabled. This security read bypasses the grant-inheritance metadata cache. Cycles refuse; a shared ancestor completed on another path is checked once. A trusted caller acts for an `sa:` subject only when it names an active registered bot or its agent; a personal row cannot prove the token's, session's or parent credentials' liveness. One decision allows at most 1,024 supplied roots, distinct subjects, examined lineage edges, account rows and distinct emails in each dimension. Repeated root entries count before deduplication, and repeated lineage edges count as examined work. Input and serialized query parameters each fit 65,536 bytes; account and ancestry bytes transferred across the decision share that bound. SQL returns overflow counts and bounded projections rather than accepting a truncated prefix. Unsupported sizes refuse before admission. The traversal costs O(S + E) for S subjects and E examined edges, plus the bounded account data; resolving an owner still scans that org's account rows. A complete cold decision has one finite 30-second deadline, reduced by a smaller positive `LOOM_CH_TIMEOUT_READ_S`. Setting that field to zero leaves general reads unbounded but does not remove the SCIM deadline. Queries use the remaining decision budget through the normal ClickHouse statement limits; a tighter scoped or query-class limit still applies. A read failure or deadline raises `SignInUnavailable`, which becomes retryable 503 rather than deactivation. The refresh path checks this policy before rotating the provider's credential and puts the same token and family back on an outage. Positive refusal and an unavailable read are different outcomes. Only a completed whole-graph result is memoized, in authorization's existing final memo. Its key includes deployment and cell identity, concrete org, exact primary subject, normalized verified email and canonical additional roots. No inner subject or ancestry cache supplies a security answer. `LOOM_GRANT_CACHE_TTL_SECONDS` is counted from the complete read's start, not its finish or a cache hit. Identity, account, link, machine and lineage writes invalidate through the existing forget hook before the attempt and in `finally`, so an overtaken read cannot install its stale result. Across processes, an already-running decision can observe a change within at most `max(grant_cache_ttl_seconds, decision_s)`, where `decision_s` is the finite complete decision budget. This is not a globally atomic identity snapshot; ordinary revocation checks retain their separate rules. Standalone deployments and cells without the required policy retain deactivation checking without installing a positive-provisioning permit. The global cell gate still refuses unknown or unread identity. **Break-glass.** Every cell holds a key-proof platform-admin bot (`loom bot create --platform-admin`), which has no email and which SCIM never revokes, and a second, separate one for attach and `loom cell each`. Their keys stay in the operator's secret store, read at each use; the directory records only each bot's name and key thumbprint, so the router holds no cell's credential, and every use of the break-glass bot is in the cell's audit log and named by `loom doctor`. Operators are assigned to every cell's applications for the dashboard, and reach a cell whose identity provider application is broken through its bot. **A cell's SCIM tokens are its own by construction.** A cell's name matches `[a-z0-9-]{1,32}` (no `_`, compared exactly; enforced at prepare, attach and boot, and unique in the directory). A token that starts with `lsc_` names a cell and must match `lsc_[a-z0-9-]{1,32}_[0-9a-f]{32,}` in full, or every cell refuses it; only a token without that prefix names no cell. With `LOOM_CELL` set, a SCIM token has the form `lsc__`, as `loom cell scim-token new --cell ` makes it (it runs offline): exactly three fields split on `_`, the middle one equal to `LOOM_CELL`, and a secret of at least 32 lowercase hex characters. The offline command draws 32 random bytes and prints 64 lowercase hex characters; a configured token's length alone does not establish its randomness. The pure parser and configuration policy in `server.core.scim_tokens` share the token splitter exposed as `scim.tokens()`. Core admission and authentication use the same policy without a second identity query or cache. Callers compare the token's name with `LOOM_CELL` and the full immutable `first` tuple (below). `scim_settings_problem` takes both, so boot and `loom doctor` refuse through one function, and with `LOOM_CELL` set they refuse a third configured token (two allow a rotation). One function, `scim.authorized(presented)`, holds the constant-time comparison for both SCIM routes (`_authorized`, `scim_groups._caller`). With `LOOM_CELL` unset it compares against the configured tokens as a single deployment does and reads nothing. With it set it compares against the tokens the parser admits for `LOOM_CELL` and the `first` row; while that row is unread it raises as `AuthUnavailable` does, so the routes answer 503 with `Retry-After` and the identity provider retries. The cell admission gate derives token policy before returning a cached readiness verdict. A late first successful identity read cannot admit an invalid configuration. Server and worker startup check known identity before starting writers; unknown identity keeps the process unready while its deployment probe remains available for prepare. Doctor grades policy from its own bounded state query, including both fields of the first tuple. Unread identity fails the configured SCIM check. Store generated tokens in the operator's secret store and configure the identity provider for that cell's host. To rotate, configure current and replacement tokens, switch the identity provider to the replacement, verify requests, then remove the old entry. Two configured entries are allowed per cell, including duplicate entries in that count. Standalone deployments retain their existing configured-token behavior. - A process refuses to boot with a SCIM token that names another cell, and `/scim/v2` answers 401 to one. - A later cell refuses a token that names no cell. The first cell, which keeps the shared host, also accepts its existing unnamed tokens, only while its `first` row is `(true, LOOM_CELL)`, so its SCIM keeps working through the cutover with no rotation. - A token copied into another cell's settings, or an identity provider application pointed at the wrong cell's host, therefore fails closed, and no cell ever compares its tokens with another's. ## Preparing a cell `loom cell prepare` registers a cell in the directory and writes the rows a cell's processes read. The tenancy check (below) says what it writes and how it resumes; this section says how it proves it was given the right cell. **Which cell is first** is never a setting and never the order of preparation. Prepare grants it only to the cell whose host is the router's shared host and whose deployment id is the one the router's pass-through upstream reports at the upstream's probe address. That address is the router's own configuration (`LOOM_ROUTER_UPSTREAM_PROBE_URL`) and the first cell's `probe_url`, never one of prepare's arguments: the router reads it there at every prepare and rerun, and refuses an answer with another deployment id or none. The router also asks its pass-through upstream's main port (`LOOM_ROUTER_UPSTREAM_URL`, which registration copies into the row) and refuses one that reports another deployment id, so the row never names two deployments. Prepare refuses every other cell until the first is registered and `serving`, under the directory lock, so no later cell appears while the first attaches. **The stores are the live ones.** Before writing anything, prepare writes a random nonce into the target Postgres, under a reserved key of the target ClickHouse's `loom._migration_lock`, and as a probe object under the target bucket prefix. The cell's probe route must echo each back as it reads it from its own connection to the primary on that request. The nonces are then deleted; their rows hold no memory and no org and are classified so. A copy with the same deployment id is refused. Prepare sends the router the three nonces with the registration (`POST /cells/v1/operator/cells//register`, with the operator credential); the router reads the probe listener itself and registers the cell only when it answers the cell's deployment id, those nonces, and the bucket and prefix the registration names (so one naming no bucket cannot pass for a cell that has one). The router answers a listener past its rate (429) as `PROBE_BUSY`, and one it cannot reach or that cannot read a store, or a first cell's upstream main port it cannot reach yet, as `PROBE_UNREACHABLE`, both 503, and prepare waits for them within `--wait`. A rerun whose addresses differ from the row's is refused before the probe. **The probe route**, `GET /v1/health/deployment`, takes no credential and is outside the fingerprint gate: - On the main port it answers only the deployment id each process verified at boot, held in memory, whatever the request's Host. It reads no store and is not rate-limited, so no flood on the main port stalls attach's host check. - In full, with the values under prepare's reserved nonce keys, it is served only on a separate probe listener port (`LOOM_CELL_PROBE_PORT`, `0` for off; it needs the Postgres authority and authentication on, and binds every address of the host): the Postgres row `loom.cell_probe` and the KeeperMap key, each named `cell-probe`, and the object `/_cell_probe`; it also names the bucket and prefix it stores under. None of these values is secret. It answers 429 past a fixed rate per process on that listener. - Only the cell's probe address (`probe_url`) targets the listener: an internal address that no ingress exposes and the router never routes to, which the deployment sends to every live process, ready or not, so prepare and attach reach a process the gate holds unready. - The chart's probe listener is off by default and is turned on, in the existing deployment too, before the first `loom cell prepare`. It renders a Service on that port that publishes unready addresses and changes no NetworkPolicy. Who may reach the port is the operator's network policy, as it is for ClickHouse's: with the chart's own policy on, which admits only the `http` port, the operator adds a policy admitting the probe port from the router's pods (prepare's registration is probed by the router) and from where the CLI runs (policies add up), and without one any pod can reach it. Likewise the cell's egress to the router's placement address and to Postgres is the operator's, through `networkPolicy.extraEgress` where the chart's policy is on. - Prepare retries the router's `PROBE_BUSY` and `PROBE_UNREACHABLE` (a listener starting up is unreachable a while), and attach and `loom cell update --probe-url` a 429 from the listener they probe, for at most `--wait` (default 10 minutes), and then name it. A later cell's `probe_url` is given to prepare, normalised (`http` or `https`, no userinfo), and accepted only when it reports the deployment id prepare reads from the target stores; attach then checks that the cell's own host reports the same id. Prepare refuses a probe address argument for the first cell. `loom cell update --probe-url` replaces a later cell's under the directory lock after the same check and a fresh nonce echo. The first cell's probe and upstream addresses are copied from the router's configuration at registration, and `loom cell update` replaces them from it, once every router replica runs the new values, after the same probe and a check that the new upstream reports the cell's deployment id. The generation/address CAS does not prove all-router agreement: an old router can read fresh expected values and reverse the addresses. Keep old endpoints reachable until every router refreshes its routing table or restarts after the directory write; config rollout alone does not flush the cache, which can persist indefinitely during directory failure. A prepare rerun never moves an address: it refuses while the router replica it reaches is configured with others. **The `first` row.** Prepare writes an explicit, immutable `first` row into every cell's Postgres (`loom.cell_first`: a row trigger refuses its update and delete and a statement trigger its truncate, both created `ENABLE ALWAYS` and checked by attach and `loom doctor` as the org triggers are), `(true, )` for the first cell and `(false, )` for any other, in the same transaction as the tenancy mode, so neither exists without the other. Read together, the two rows give one of four states. Both absent with no tenancy or own row either: open, a single deployment's, with no check; a process with `LOOM_CELL` set stays unready there (no mode row). On a cell the directory registers this happens only when its Postgres is restored to before its prepare (closed by `loom cell restore`) or a prepare stops between its registration and its row write (closed by a prepare rerun), and the triggers and processes with `LOOM_CELL` unset stay open meanwhile, as on a deployment never prepared, since the cell's Postgres, which holds its state, cannot tell the two apart (ClickHouse carries no cell state: adding it would make the write path read a second store for tenancy) and such a process never reads the directory; where every process has `LOOM_CELL` unset, `loom doctor`'s naming of it (which reads the directory, and ships with the router's read-only scope) is the only signal. A `(true, …)` row with `recording` and the own row: the first cell recording. Both present with the own row otherwise: `enforced`, a later cell's mode reading as `enforced` whatever its row says (its triggers, mode cache and CLI treat it so, and `loom cell prepare` names a row that is not). Either row alone, both without the own row, or both absent beside a tenancy or own row (the `partial` states: some state row present but not all of the `first`, mode and own rows), which prepare never leaves: the org triggers, where a cell has them, act as in `enforced` (a boot creates none in it), every process is gated as by an unread row, `loom doctor` names it, and a rerun of `loom cell prepare` writes the missing rows back from the directory while the cell runs. A unique index in the directory allows one first cell, and the value holds no memory content and is classified so. Attach rechecks the host and deployment id. A process reads the value with the mode, and "not yet read", "absent" and "false" are distinct: only a row that has been read makes a process ready, and a row whose cell is not `LOOM_CELL` gates it (below) and is reported by `scim_settings_problem`. Boot refuses on settings alone (`scim_settings_problem` with the row unread checks only the token's form against `LOOM_CELL`); the comparison with the `first` row runs per request once the row is read, and `loom doctor` reads the value from the cell's Postgres or reports it unknown. ## The cell's own row **Checked continuously, not only at attach.** Each process computes its configuration fingerprint: named fields under a schema version (the hosts of its `LOOM_PUBLIC_BASE_URL` and resolved `LOOM_OAUTH_ISSUER`, its OIDC issuer and client id, whether SCIM is on, the bearer issuers it accepts (`trusted_issuers()` and its end-user issuers), its configured orgs, the `orgs` of its `jwt_end_user_issuers_json`, the deployment id it verified at boot, and the bucket name and prefix). Its Postgres and ClickHouse both carry the deployment id (the pairing check a single deployment already runs). The bucket, when one is set, is identified by its name and prefix (a cell without a bucket takes part in no bucket check), which no two cells share on any endpoint: no cell's prefix in a bucket of the same name nests inside another's or holds it, so an endpoint taken from the environment cannot land in another cell's prefix. No store is identified by its address, so a standby replaced, a failover, an address taken from the environment or a restore to a new endpoint changes nothing the cell checks. The deployment id, the bucket name and the prefix never change after prepare: `loom cell update` refuses a change to any of them, adding a bucket to a cell prepared without one included, and moving a cell's data to other stores, or adding one, is a design of its own (Operations). Bots are not in it: `loom bot create` adds them at run time, each with one org, and placement already bounds them. The cell's own row in `loom.cell_self` holds an accepted fingerprint, `current`, and during a change a second, `next`. Its rows, and the cell heartbeat (`loom.cell_heartbeats`, keyed by the process's `loom.instances` row and written with it, since a KeeperMap table takes no new column: the `LOOM_CELL` it runs with, the state its last read makes, its fingerprint and [the keys beside it](#the-heartbeats-keys)), hold no memory content and are classified so for erasure. A process matches a value when every field both know is equal, a field the value lacks counting as equal only at its default, so builds N and N+1 with the same configuration match one row. With `LOOM_CELL` set, while its cell's own row, `first` row or mode row is unread, the state rows are in a `partial` state (the `first` row's rule, above), the cell's own row is absent or matched by neither value, or the `first` row names another cell, every request it receives but its health probes and the probe route answers 503 `AuthUnavailable`: bearer requests (the first check in `verify_token`, before the end-user issuer branch), SCIM, and every route that signs in, mints, refreshes or exchanges a token, signup, the OAuth and device endpoints and the sign-in callback included. It also reports itself unready, and it stands aside from the workers as a drifted process does: it stops its passes, gives up the lease and names no lease in its instance row, in every `LOOM_BACKGROUND_WORKERS` mode (`on` included: with no lease to keep, a cell's `on` process runs the lease loop, which starts and stops the supervisor on the gate within `LOOM_TENANCY_MODE_CACHE_S` and one loop period), and its instance row does not count it as serving, so an older build beside it keeps the workers running. A failed read keeps the last rows for at most `LOOM_JWT_REVOCATION_MAX_STALE_SECONDS`, as the signing keyring and the revocation snapshot do; past it the process is gated until a read lands. The mode (below) has the same bound. A cell configured to accept another cell's issuer, a host it was not attached with or an org pattern it was not granted therefore serves nothing with it, wherever the request reaches it. Its heartbeat reports the fingerprint, the router refuses a placement call whose fields match neither value of the directory's row, and `loom doctor` names a mismatch, a cell whose OIDC client another cell shares, and a cell with SCIM off beside cells with it on. `loom cell prepare` writes `current` into `loom.cell_self` with the `first` and mode rows. Until the directory row holds a fingerprint (before attach), it writes, when the own row is missing, the fingerprint every live process reports in its heartbeat, refusing while any live process runs a build before N, which reports none, or while the fingerprints they report differ; a present own row stands, and a live process running neither its `current` nor its `next` refuses; every run, before it registers, refuses a live process whose deployment id, bucket name or prefix differs from prepare's own configuration (a field it does not report read at its default). Once the directory row holds a fingerprint, a rerun writes `current` and `next` from it, as `loom cell restore` does, refusing only while a live process's fingerprint matches neither. Either way the cell stays ready through the `LOOM_CELL` rollout. A later configuration change, while the cell is `attaching` or `serving`, goes through `loom cell update`; before attach has written the cell's fingerprint to the directory row it writes `next` only to `loom.cell_self`, reserving nothing (and `--finish` and `--revert` then touch only `loom.cell_self`), and a resumed attach runs its overlap refusals on, and writes to the directory, both values of `loom.cell_self`. A prepared cell's issuers and org patterns are reserved nowhere: the router routes no issuer to it and takes no placement from it until attach has run its overlap refusals and written its directory row. A change to what a cell accepts goes through `loom cell update --config ` ([operator procedure](/docs/operations/cell-update)). The nonsecret settings file overlays the CLI's effective settings without installing them. It computes `next` with the same function the processes use and refuses while a different `next` is pending. Under the directory lock, overlap checks count both values of every other cell. Configured placements, their counts, issuer routing and the directory pair commit together before local tenancy repair and acceptance of the pair. `--finish` selects next; `--revert` selects current. Each repairs local tenancy from actual same-cell immutable placement winners for both reserved values, using an operator read fenced by the generation, exact registration and pair, locked root-secret fingerprint, audit and synchronous WAL acknowledgement. First-cell lookup fallback is not evidence of a placement. The attaching first cell may still lack placements for its preexisting configured orgs; other missing placements require directory metadata recovery. Finalization durably narrows local acceptance while the directory keeps both reservations. It then takes a complete post-cutoff participant census and requires permanent guarded retirement or verified exact death for every captured identity, including target processes, and a serving target replacement outside that set. Only then may the directory release its old reservation. Heartbeat expiry, request deadlines, missing participant rows and workers-only replacements do not prove this. Online finalization needs the [lifecycle baseline](#participant-lifecycle-baseline) and controller fencing. For a SCIM-on target, the CLI runs the shared fresh provisioning census before claiming the generation, after durable acceptance, and after participant turnover before reservation release. It uses the target cell's configured SCIM credentials, OIDC login and required authentication. `--revoke-unprovisioned` permits the same reported, irreversible SCIM cutoffs as attach; without it, an unqualified live subject refuses. Revert to SCIM-off current requires no provisioning census. A timeout after cutoff keeps local acceptance single and the directory dual; the command reports incomplete turnover. Repeating the selected action takes a fresh census. An identical `--config` repairs directory-first interruption and can widen local acceptance again; subsequent finalization takes another cutoff and census. A singleton no-op still proves local synchronous durability. Every configured org placed by an update stays placed and retains its tenancy row after revert. A new SCIM token changes no fingerprint and needs no `loom cell update`. A cell changes its identity provider application as a single deployment does ([SSO and SCIM](/docs/operations/sso)), with the same limits; nothing in that is particular to cells. ### The heartbeat's keys A process's cell heartbeat reports, beside the `LOOM_CELL` it runs with, its tenancy mode: the state its last read of the state rows makes (`open`, `recording`, `enforced` or `partial`, a later cell's `recording` read as `enforced`), and `''` only before a read lands or in a process that never reads them. Its `fingerprint` JSON holds the fingerprint's version and fields, and beside them keys that no fingerprint compares: they are never in `loom.cell_self`, the directory's fingerprints or a placement body, and a KeeperMap row needs no column for them (`server.core.instances.cell_row`). Their presence proves the build that reports them; there is no generation key. - `participant_id`: this server's provider participant UUID, for joining its actual process lifecycle to the serving instance row. A workers child publishes no instance row. - `serves`: `LOOM_SERVES_TRAFFIC`. - `marked`: whether this process's pooled Postgres sessions keep the tenancy marker (`loom.tenancy_checked`). The cell refresh reads it with the state rows, after `RESET ALL` in the same transaction: a startup value survives the reset, a `SET` does not, so a pooler, which a cell must not have ([Postgres](/docs/operations/postgres)), reads unmarked whether it strips startup parameters or sends them again with `SET`, and the read runs on the server connection the reset ran on. It costs three round trips more per refresh (`BEGIN`, `RESET ALL` and `COMMIT`), and every process reports a fresh value with no prober. A session the pooler stripped, or a process with `LOOM_CELL` unset under the Postgres authority, reads `false`; `null` means only that no read has landed (a boot with skipped Postgres migrations whose first read failed, or the ClickHouse authority, where nothing is read). The `cell_marker` readiness check of a process with `LOOM_CELL` set reads the same value: it fails in `enforced` and `partial`, where the triggers refuse an unmarked session's writes for an org the cell does not hold and the tenancy row of each newly placed org, and passes with a warning in `recording`, so a first cell behind such a pooler does not stall its rollout before attach, which refuses the process ([troubleshooting](/docs/operations/troubleshooting#the-cell_marker-readiness-check-names-the-tenancy-marker)). - `router` and `router_why`: with `LOOM_CELL` set, `router` is `null` and `router_why` names why until the `first` row is read, and then both are present on a first cell only (a later cell's state route answers 404, so it neither asks nor reports them). `router` is whether this process's last read of `GET /cells/v1/cells/` with its own credential answered 200 naming the cell: `null` until the first read answers (still booting), `true` on such an answer, and `false` for a configuration that never works: a router setting unset (the process never asks), a URL that cannot be requested, a 404, an answer for another cell, or a 401 that persists past one `LOOM_ROUTER_DIRECTORY_CACHE_S`. That is the router's setting, which the cell's processes carry too: a router replica's cached credential hashes answer 401 for a token rotated a moment ago, so until then the last value stands and `router_why` reads "401, possibly a rotation" (a router run with a longer cache can make attach refuse during a rotation; a rerun clears it). A transient failure (a timeout, a connect error, a 503, a 200 that is not a JSON object naming the cell) keeps the last value, and while `router` is `null` `router_why` names the last such cause. One background reader per server process asks the route every `min(LOOM_INSTANCE_HEARTBEAT_SECONDS, LOOM_TENANCY_MODE_CACHE_S)` on a first cell until it has read `serving` (`server/core/cell_router.py`); nothing awaits it, so a slow router delays no beat and no request, and the beat reports what it last read, at most one period plus `LOOM_CELL_ROUTER_TIMEOUT_S` old when a beat writes it. Every uvicorn process runs one, so a thousand pods of eight workers ask up to 1,600 times a second. Each router replica answers the route from its own read of the cell's row, made at most once per `LOOM_ROUTER_DIRECTORY_CACHE_S`, so the directory sees one read per replica per window; a failed read answers 503 for its window, so a down directory is asked no more often and still answers 503. A process with no heartbeat (a CLI, the workers child) asks on demand instead, at most once every `LOOM_TENANCY_MODE_CACHE_S`. The reader keeps the directory's last answer for the tenancy check too, as one of four: `attaching`, `serving`, another state, or unknown while no read has landed, the last one failed, answered for no state of this cell (a 401, a 404, or an answer for another cell), or is late (older than the period this process reads at, the background reader's or the on-demand window, plus `LOOM_CELL_ROUTER_TIMEOUT_S`). Once a process has read `serving` it keeps that for its life and asks no more: only `loom cell restore` lowers it, and that restarts the processes. A first cell in `recording` records a new org only on `attaching`. A platform or `*`-org principal, or a call with no principal, places no org: on a first cell whose directory answers `attaching`, or cannot be read before it has read `serving`, such a call for an org the cell does not hold answers 503 ("attach in progress" or the directory unreadable), since the org's data may be in this cell until attach places it; once `serving`, and on a later cell, it answers 409 `WRONG_CELL`. A process booting after `serving` while the router is down answers those calls 503 until its first read lands. With `LOOM_CELL` set, a non-empty `LOOM_CELL_ROUTER_URL` that is not an http(s) URL with a host, a port at most 65535 and no `?` or `#` refuses the boot (`cell.settings_problem`); an empty one is allowed, for workers-only pods (`LOOM_SERVES_TRAFFIC=false`), whose heartbeat then reports `router` as `false` with the unset settings in `router_why`, logging nothing. ## The tenancy check and placement A process with `LOOM_CELL` unset runs no tenancy check. Under the Postgres authority (`LOOM_STORAGE_AUTHORITY=postgres`, the only one a cell runs) a server process still reads, in one statement, the mode row, the `first` row and whether any `loom.tenancy` or `loom.cell_self` row exists, with the mode cache's rules (below). A CLI command that declares an org reads the same on a bounded session of its own: every state table absent (judged by `to_regclass`, so a role missing a grant still refuses) reads as `open`, and a failed read refuses. An org-free command, such as a token revocation, `loom migrate` or `loom doctor`, is not gated by the mode and runs, a Postgres outage included. Both rows absent with no tenancy or own row, as on a deployment never prepared, or the first cell in `recording`, leave the process serving as a single deployment; every state the `first` row's rule (above) counts as `enforced`, or as a `partial` state, gates it as `enforced` does. `enforced` (which attach sets on the first cell once every live process has `LOOM_CELL` set, and prepare on a later cell, whose processes run with it from their first boot) makes a server process unready, run no worker and answer nothing but its health probes and the probe route (so a prepare rerun can reach it), and makes the CLI command refuse; the readiness reason and the refusal name `LOOM_CELL`. So a pod or an operator's CLI that loses `LOOM_CELL` on an `enforced` cell writes for no org; one that also loses `LOOM_PG_DSN` or `LOOM_STORAGE_AUTHORITY` is refused by the authority check the deployment already runs (ClickHouse's `loom.storage_authority` record). The `loom cell` commands that connect to a cell's stores (prepare, attach, place, restore, update) refuse without `LOOM_CELL`, and, once the directory has a row for `LOOM_CELL`, refuse stores whose deployment id is not the one that row records. A deployment started with `LOOM_CELL` unset is a single deployment until prepared, and pointing it at another deployment's bucket prefix is the misconfiguration it is for any deployment. On the first cell, `loom cell prepare` runs before `LOOM_CELL` is rolled out; a later cell runs with `LOOM_CELL` set from its first boot, so its processes are gated and stand aside from the workers (its blob sweep included) until prepare writes its row, and prepare refuses a later cell while any live process's heartbeat lacks `LOOM_CELL` or names another cell. Prepare does three things, in order: 1. **It refuses a cell whose stores already carry another cell's identity**: a deployment id the directory records, or state the directory has not placed there. These are checked by the router, in the registration's own transaction, from counts prepare sends: a cell the directory has no row for may hold no tenancy, `first`, mode or own row, and a later one no object under its prefix but prepare's probe and no live process without its `LOOM_CELL`. A rerun counts the tenancy and state rows and the prefix's objects as its own; a later cell's processes run with its `LOOM_CELL` on every run, which prepare checks itself. 2. **It registers the cell** in the directory as `attaching`, under the directory lock: its host, the deployment id read from the cell, the SHA-256 of the credential it calls the router with, and its bucket name and prefix, checked against every other cell's, prepared or attached. The credential is `lcr_` and 128 lowercase hex characters (512 bits), as `loom cell credential new` makes it offline, printing the credential and its hash; boot and `loom doctor` refuse a `LOOM_CELL_ROUTER_TOKEN` of any other form. Prepare takes the hash as an argument, 64 lowercase hex characters, so no CLI needs the secret; any other value, the credential or its 128-character secret included, is refused, naming `loom cell credential new`, and stored nowhere. No other cell's row may hold the hash, as its current or next one. 3. **It writes the cell's rows**: the mode (`recording` on the first cell, `enforced` on a later one), the `first` row and `current`. Prepare is resumable. A rerun for the directory row of the same name, deployment id and host writes whichever of the `first` row and the mode row is missing, from the directory's state, and `loom.cell_self` as above (before attach from the heartbeats when it is missing; once the directory holds the fingerprint, `current` and `next` from it, overwriting a present value that differs); before attach, a present own row stands, and a live process running neither its `current` nor its `next` refuses. The directory's state is the `first` value the unique index names and the highest mode it records for the cell: `recording` for the first cell or `enforced` for a later one at registration, in the same transaction as the row, then each mode attach raises, recorded in the directory before attach sets it in the cell's mode row (a refusal reports the mode row as attach reads it back after any return to `recording`, and never lowers the directory's record). A rerun refuses a mode row above the directory's state and a later cell's `recording` row, neither being this cell's, and leaves a first cell's row below it for attach to finish. A rerun refuses a credential hash that is neither the row's `current` nor its `next` (rotation is `loom cell credential`'s), counts the tenancy rows placed in or recorded since its own registration as its own, and skips registration's checks it has already passed (the empty prefix and the prefix overlap), so it runs on a `serving` cell whose prefix holds data. A process with `LOOM_CELL` set and no mode row does not become ready. With it set, each cell's Postgres holds `loom.tenancy` (org, since) and `loom.tenancy_mode` (`recording`, `enforced`); a process reads the mode through a cache of at most `LOOM_TENANCY_MODE_CACHE_S` (default 5 s), keeps the last mode it read when it cannot read it, and keeps serving the orgs it holds, for at most `LOOM_JWT_REVOCATION_MAX_STALE_SECONDS`, past which it is gated until a read lands. Every server process under the Postgres authority, `LOOM_CELL` set or not, reads the rows right after its stores open and migrate, before its first heartbeat and its lease decision; a failed first read fails its boot (with Postgres migrations pending it boots gated and unready until a read lands). After that a process with `LOOM_CELL` set keeps the stale bound above, and one with it unset keeps its verdict through failed reads with no stale bound, as a single deployment rides out a Postgres outage (the first exception under Invariants). A cell's workers child reads its own rows and is gated until a read lands. With `LOOM_CELL` unset absent mode and `first` rows with no tenancy or own row are a deployment never prepared, and a failed read is never taken for an absent row; a process that reads no state (the workers child and a CLI with `LOOM_CELL` unset, and every process under the ClickHouse authority) is not gated by it. In `enforced`, a cell serves exactly the orgs it holds a row for; an org a process read as not held, for a caller acting in another org, is read again after `LOOM_TENANCY_MODE_CACHE_S`. A `recording` row is written by one statement that inserts it only while the mode is `recording`, reading the mode row `FOR SHARE`; it runs at `READ COMMITTED` in its own transaction and commits before the request goes on. Attach's write of `enforced` and these inserts never cross: an insert already running when attach writes the mode is placed by step 4, one that starts after reads `enforced`, a stream of inserts cannot hold the write off. If attach stalls while holding the mode lock, it attempts bounded cleanup. A client abort does not prove that the lock was released; stop and verify the exact holder before retrying. Attach takes `LOCK TABLE loom.tenancy_mode IN EXCLUSIVE MODE` (which waits for running inserts and queues later ones behind it) in short tries, in one transaction with server-side timeouts, then writes the mode and commits on its exact ATTACH backend. Only recognized pre-COMMIT contention can retry, after acknowledged rollback and a check that this backend still holds ATTACH. Unexpected failure or an uncertain COMMIT closes the owned session and ends the run. Attach neither finds nor ends another backend. A fresh run takes the lock and claims again; whether an earlier commit landed is decided by a durable mode read whose COMMIT waits for the standby ([attaching a cell](#attaching-a-cell): step 3 and the durable read). The mode cache reads the mode with a plain `SELECT`, which takes no row lock and never waits on attach. An insert that finds `enforced` (a process whose cache still reads `recording`) writes nothing: the request goes on to the placement call as in `enforced`, and a CLI command refuses as in `enforced`, naming the org. A first attach never lowers the mode once it commits `enforced`. `loom doctor`, with the router's read-only scope, lists any tenancy row the directory does not place. - **It runs after verification, before anything is written for the org.** The op gate (`gates.authorize`) checks the org the transport resolves (`gates.resolve_org`, with its caller defaults and plane orgs) first, before `check_acted_for` and personal-namespace provisioning, for HTTP and MCP alike (over MCP a call for another cell's org answers `isError`, so a batch keeps its other answers, and a call in the token's own org, as `gates.resolve_org` resolves it, is checked before the caller's defaults are read, since they live in that org). The routes outside the registry check through `check_authorized`, `admit_org` or the check itself, and a middleware checks the verified bearer's own org on those that act in it (the routes the census marks `token`; for an org-wide or org-less token on the caller's routes that fall back to it, the sign-up org, checked with no principal, so it is recorded or refused, never placed). A principal that may not act in the org (a token of another org) is refused first, with the gate's 403, so it records, places and learns nothing: not whether the cell holds the org, nor where it is placed. An op whose org field is named otherwise (`from_org`) reaches the same check through `check_authorized`, and a census test lists every such field. A refusal written before the check (malformed JSON, an unknown argument, a validation failure) names no org the cell does not hold in its telemetry or code trace. A unit test lists every route of the app and fails unless it is marked tenancy-checked or org-free. - **The CLI declares its orgs.** Every CLI command that connects goes through `run_connected`, `connect_checked` or `connect_declared` (`server/cli/_ch.py`), which take the orgs the command writes, or why it writes for none. A command that declares an org first checks its deployment (`check_configured`), so under the Postgres authority it needs `LOOM_PG_DSN`. On a cell, before checking a declared org, they read the cell's rows and refuse the command unless the `first` row names its cell and its stores (`deployment_id`, `bucket`, `bucket_prefix`) match a value of the cell's own row: a CLI verifies no token and its fingerprint never reaches the router, so it may run where the transports refuse on another fingerprint field. With `LOOM_CELL` unset the command is refused on a cell past `recording` (above). An org the cell does not hold is recorded on the first cell in `recording`, as a request's org is (reading the cell's state with the cell's router credential, `LOOM_CELL_ROUTER_TOKEN`, in the first cell's CLI configuration while its mode is `recording`, and only while the directory answers `attaching`), and refused in `enforced`; it is never placed. A code-index command declares the org it writes: its `--org`, else `LOOM_CODE_ORG`. A pass over every configured repository declares none, since attach, or the `loom cell update` that changes one, places configured orgs, and a read-only command or a dry run declares none, since a read records nothing. An org-free command says what it does to the stores: it reads, writes (`loom ch-setup`, `secrets`, a settings change, prepare and the rest; a dry run reads) or revokes (`loom revoke-token`, a SQL user's revocation, `loom signing-key retire`, `loom bot disable`, `loom sso unlink`; one that can give access back is a write), per subcommand where one connect serves several (`loom signing-key`: `list` reads, `retire` revokes, `rotate` and `record-root` write). With `LOOM_CELL` set, a write or a revocation checks its ClickHouse against its Postgres (`check_configured`), reads the `first` row on a bounded session of its own and refuses when it names another cell, which a CLI pointed at another cell's stores always finds, or when the read fails; an absent row, or state tables not migrated yet, passes, so a later cell runs these before it is prepared. A revocation runs through an outage (the fourth exception under Invariants); a write refuses during one; a read is not gated. `loom ch-setup`, which sets ClickHouse up on a client of its own, runs the same gate before it writes, a ClickHouse with no record yet passing; `loom migrate` and `loom provider-lock clear` write through the schema runner's own client and are not gated. A census test fails on a connect that declares neither, on an org-free one that does not say which kind it is, on a connect under `server/cli/` outside `_ch.py`, and on a `loom code` command that resolves its org without connecting for it. A holder of the cell's router credential can place orgs for the cell, within the cell's rate and `placements_max`, as the operator credential `loom cell place` uses can for any cell within its `placements_max` (an operator's call is not rate-limited, nor counted toward the cell's rate), and a placement is permanent, so an org name it takes is lost to every other cell: a power over the shared directory that the cell's store credentials lack. So the pods hold it, and a CLI only for the one read that needs it, while the first cell's mode is `recording`: a CLI command that declares an org refuses to run with it set, naming it, unless the cell is the first and its mode reads `recording`, and an org-free command never uses it; a leaked one is stopped by `loom cell limit --closed`, which needs none of the cell's stores, and replaced by `loom cell credential` (below). `loom cell place --cell --org ` (declared org-free: it writes the org's placement and tenancy row, which is how an org comes to be held), with the router's operator credential, places an org for a command that writes a new one (a bot, an import), through the router's placement API and in its order, as attach's placement of configured orgs does: it inserts the placement and reads back the winner, writes the cell's tenancy row only if the winner is this cell (otherwise it refuses and writes nothing), and reports success only once the row commits synchronously. The CLI holds the attach lock on a direct marked Postgres session, requires a full enforced local cell state and the full accepted configuration fingerprint, and checks both again before inserting. A transactional durability message makes even a no-op insert flush an earlier primary-only tenancy row to the standby. Opening the session, initial checks and the local transaction through COMMIT each have a separate client deadline derived from `LOOM_PG_STATEMENT_TIMEOUT_MS`; the directory request keeps its own transport timeout. Each local phase reserves cleanup inside its original deadline. On failure the shared control owner closes the exact backend before cancelling or reaping its work, deferring repeated signals within that same deadline. Successful exit and failures outside a local phase have a separate cleanup allowance derived from the same setting. An unknown outcome names rerunning the same command; the permanent directory winner and idempotent local insert let that rerun finish. The route checks directory state; a direct operator API caller is trusted to check local Postgres mode as the CLI does. For an org the directory does not place yet it passes the placement API's gate (below): refused while the directory is unavailable, for a cell the gate does not accept, closed, or when the fingerprint of the CLI's own configuration of the cell (with the deployment id read from the stores it connects to) matches neither value of the cell's row, or past `placements_max`, and counted toward it. - **Writers older than the check are refused by the stores they write.** A session that ran the tenancy check marks itself with `loom.tenancy_checked = 'on'`: every session of a process with `LOOM_CELL` set sends it as a startup parameter (so the pool's `RESET ALL` keeps it), and the migration session sets it after taking the migration lock, since a migration's data steps only copy or rewrite rows already stored. On each ordinary table of the authority with an `org` column (not `loom.tenancy` itself, nor `loom.idempotency` and `loom.idempotency_fences`, keyed by the caller's token org) a row-level `AFTER INSERT` and `AFTER UPDATE` trigger, enabled as origin triggers, skips a marked session in its `WHEN` (the update one also skips an update that leaves the row's org alone, so an `ON CONFLICT DO UPDATE` that hits an existing row is not refused) and calls one function (migration 011). The function follows the state rule (above): it passes every row while the state is open or a first cell is recording, and in every other state refuses, SQLSTATE `LT001` (503 `TENANCY_REFUSED` to a caller), a row for an org with no tenancy row (never `''`, `'-'` or `'*'`); it reads the state once the row is written, with no row lock, so no write queues behind attach, and step 4 (below) waits out every transaction that could have read `recording`. A boot with migrations on creates the triggers, on every such table it finds in the catalog, only on a fully prepared cell in `enforced`, and, there, sets any it finds not at origin back to origin; each table's DDL waits 100 ms a try for its lock, three tries a second apart (about 2.3 s for a busy table, so a boot that finds every guarded table busy waits that long for each in turn, holding the migration lock other booting pods wait on), and the boot serves past a table whose lock it cannot take, logged with the holders of its locks, or one the role cannot alter, logged as such (the third exception under Invariants). A first cell is `recording` until attach sets `enforced` while it runs, so no boot can have created them: attach creates them with `cell_triggers.ensure_table`, passing `recording_first=True`, before step 2 and again before setting `enforced`. The cell goes `serving` only once `cell_triggers.missing` names no defect. A later cell is `enforced` from prepare and gets them at its first migrating boot after prepare, which its attach requires the same way. `loom doctor` names a disabled or altered one in any state, a missing one on an `enforced` cell, and a partitioned table with an `org` column as unsupported, since it gets no trigger. Origin triggers do not fire for logical replication's apply or under `session_replication_role = replica`, which a cell's scripts do not use. The marker is no privilege boundary: a writer that sets it on purpose passes; the triggers stop writers that do not know it, an older CLI, a pod downgraded past the check, or a script, from adding a row for an org the cell does not hold or moving a row to one; an update that keeps a row's org, and a delete, are not refused. The org triggers' cost is one setting lookup per marked row, and one read of the state and a `loom.tenancy` lookup per unmarked row; the gate they ship under is a `memory.set` p99 rise of at most 10 ms and a delivery pass's rows per second at `LOOM_PG_DELIVERY_BATCH_ROWS` at most 10% lower, in `enforced` with the orgs held. Every Loom write on a cell is marked, so it pays the setting lookup alone, measured on the statements with the triggers on and off (no cost distinguishable from zero: six rounds range from −0.36 to 0.49 µs a row, [benchmark results](/docs/benchmarks/results)). These statement timings do not establish either gate. Both require the end-to-end `memory.set` and delivery-pass acceptance workload on an attached cell. `loom.tenancy` itself has its own guard, since a tenancy row makes an org held: `tenancy_record`, a row-level `AFTER INSERT OR UPDATE OF org` origin trigger with the same marker `WHEN`, calls `loom.tenancy_refuse_unmarked()` (migration 012), which refuses, `LT001`, an unmarked session's tenancy row, or an update that moves one to another org, in every state but a first cell still recording (`open` too, since the row itself would make the state `partial`), so a script cannot make an org held that the directory does not place. Boots and attach create and repair it as they do the org triggers. With attach, `loom doctor` also lists any tenancy row the directory does not place, which names one written before the guard or by a writer that set the marker, and any org in an org-keyed Postgres table with no tenancy row, which names rows written before the org triggers, by a writer that set the marker, or left behind by a deleted tenancy row. Before the first attach the operator rotates the cell's ClickHouse writer credentials (create the new user, roll it out to configurations of builds that check, drop the old one), and attach refuses while any ClickHouse user with `INSERT` on `loom.*` (`system.grants`, with database, global and role grants followed through `system.role_grants`, and users from configuration files or with implicit `ALL` counted) is not one a live process of a checking build or the CLI's configured user reports, so only holders of the rotated credential write ClickHouse; an older CLI given that credential still writes unchecked, and with attach `loom doctor` lists what it wrote: any org found in an org-keyed ClickHouse table with no tenancy row, from the same schema list as attach step 2. - **An org the cell does not hold is placed there or refused.** For a verified principal scoped to the org (a token of that org, or an issuer's or bot's principal whose org it is), the cell calls the router's placement API (`POST /cells/v1/placements` at `LOOM_CELL_ROUTER_URL`, answered with the winning cell and its deployment id) with its own credential (`LOOM_CELL_ROUTER_TOKEN`), and the cell the call names must be the one whose recorded hash the credential matches (a hash names one cell): the router places one org at a time (a transaction-scoped lock on the org, which every path that places takes), answers an org placed already with its cell, and otherwise judges the asking cell on its locked row, inserts the placement and reads the winner back, which the cell compares by its name and recorded deployment id. If the winner is this cell, the cell writes the tenancy row and serves the request; this cell's name under another deployment id than the process verified answers 503 and writes nothing; if another cell's name, the request answers 409 `WRONG_CELL` and nothing is written. This is the one path by which a request brings an org to a cell, whatever created it: a mint, a gateway's or a federated issuer's token, an end-user issuer's `prefix*` org, a bot. A `*`-org or platform principal acts only in orgs the cell already holds and never places one (on a first cell before `serving`, see [the heartbeat's keys](#the-heartbeats-keys)). For an org the directory does not place yet, the router accepts a placement call only from a `serving` cell (or from the first cell while `attaching` once the directory records `enforced`, which attach step 3 writes before it sets the cell's mode), and only with the calling process's configuration fingerprint, whose fields must match a value of the cell's directory row; a prepared cell's row holds no issuers or org patterns until attach writes them. A failed call, one unanswered within `LOOM_CELL_ROUTER_TIMEOUT_S`, a cell not yet attached or closed to new orgs, or a fingerprint that matches neither value answers 503 and writes nothing; a retry is safe, since the read-back makes it idempotent. For an org the directory already places, a cell's call is checked only for its credential (against the cells' hashes the router caches for `LOOM_ROUTER_DIRECTORY_CACHE_S`, default 5 s) and the cell's rate. An operator's `loom cell place` checks its deployment id and fingerprint against the requested cell's locked row even for an org already placed there; an org placed elsewhere answers that winner and the CLI refuses without inserting local tenancy. Existing placements bypass closed and quota checks. Every successful call writes an audit row before its synchronous commit, including a retry of an existing winner, so the returned winner survives failover. A request refused past its cell's rate answers 503 with `Retry-After` (at most a minute), and its retry is admitted by the replica that answers it once the cell's calls there are under the rate. An org the cell already holds needs no call, so serving it never depends on the router. - **Placements are bounded per cell.** Each router replica rate-limits each cell's placement calls per minute (`LOOM_ROUTER_PLACEMENTS_PER_MINUTE`), which bounds their pace to that rate times the replicas, and a cell's directory row can carry a placement quota (`placements_max`, unset by default), which once set bounds their total, counted and inserted under a lock on the cell's directory row, so concurrent calls across router replicas never pass it; past the rate, every placement call of the cell answers 503 with `Retry-After`; past the quota, a call for an org the directory does not place yet answers 503 as for a closed cell (an operator's `loom cell place` is exempt from the rate, as above); and each cell's placements are reported in `/v1/health?include=capacity` and by `loom doctor`, which names a cell with no quota. Every org the first cell's attach places (step 2's snapshot, its configured orgs included, and step 4's) is counted but never refused by quota or a closed cell, since the cell already serves it and refusing it would strand its data (one past `ORG_MAX_BYTES` the directory refuses, below); every other placement of an org the directory does not place yet, a later cell's configured orgs at attach and a changed one at `loom cell update` included, passes the gate, a closed cell and `placements_max` included, so a later cell closed or full before attach refuses the attach, naming the org. - **The first cell records until `enforced` as a single deployment does.** In `recording`, which lasts until step 3 writes `enforced` to the cell's mode (the mode only rises after it), a verified request for a new org writes a tenancy row with no placement call, so the router's rate, `placements_max` and `loom cell limit --closed` do not apply: new orgs arrive as they do on a single deployment, bounded by its own signup, issuer and JIT settings, and step 2 or step 4 places them unrefused. `loom doctor` lists the recorded orgs that hold no data, so the operator sees what attach will place. - **Configured orgs are placed at attach.** The cell's `oidc_jit_org`, the `self_signup_org` of a cell with signup on, and its code orgs (`LOOM_CODE_ORG` and the org of each `LOOM_CODE_REPOS_JSON` entry the code config keeps) and tracker org are placed as its own when it is attached: the first cell's in step 2's snapshot, a later cell's before it is marked `serving`. JIT and self-signup pass the tenancy check as any request does, and nothing refuses at boot: in the first cell's `recording` they record their org while the directory answers `attaching`, and elsewhere a configured org the cell does not hold answers 503 until it is placed (422 for one past `ORG_MAX_BYTES`, which the directory refuses), which `loom doctor` names; every attach, first or later, new or resumed, runs the overlap refusals on and places the configured orgs of both values of `loom.cell_self`, so one an update put in `next` before attach is placed with the rest; once attach has written the cell's directory row, `loom cell update` places a changed one in the directory transaction that writes `next`, through the placement API's gate for an org the directory does not place yet (closed cells and `placements_max` included), refusing, naming it, when another cell holds it, and then writes its tenancy row in the cell; for a later cell still `attaching` after its directory transaction, `loom cell update` refuses a configured-org change until the cell is `serving`. In `enforced`, a worker writes for an org only once the cell holds it (the tenancy check with no principal), so a later cell indexes, imports and sweeps nothing under its configured orgs before attach places them; in `recording`, workers run as before, and step 2's snapshot and step 4's second read find every org they write under. - **Rows are never deleted.** A tenancy row and a placement name an org, not its memory: both are classified for erasure as holding no memory content, as a namespace's claim is, and stay after any erasure, so an org name never comes free for another cell. A process keeps the orgs it has seen held, and a kept org is never wrong to serve. - **One org name limit.** A cell records or places no new org longer than `ORG_MAX_BYTES` (2048 UTF-8 bytes, `server/core/cell.py`, below Postgres's index entry limit): a recording cell's tenancy check refuses one with 422 and writes nothing, and the directory refuses one with 400 (`ORG_TOO_LONG`) before it writes a placement, for every route that places, which a cell's placement turns into the same 422 (over MCP, a tool error counted as the caller's). So every org a cell records can be placed, and an org held or placed before the limit keeps its cell. - **A placed org with no row** (a restore to before its placement) gets its row back from `loom cell restore`, before the restored cell starts ([What each cell runs](#what-each-cell-runs)). ## Attaching a cell `loom cell attach`, run against the router, registers a cell, one attach at a time, and refuses on any failure, naming it: - the cell answers on its own host with the deployment id its `probe_url` reports, every live process has `LOOM_CELL` set to its name, it runs the Postgres authority with a synchronous standby (`LOOM_PG_DURABILITY=synchronous`) and enforced authentication, and records a deployment id no other cell records; - on the first cell, attach's Postgres role can read every backend's transaction state (`pg_read_all_stats`) and the cell's Postgres allows no prepared transactions (`max_prepared_transactions = 0`), so step 4 sees every open transaction; - its keys are its own: no issuer it accepts for bearer tokens is accepted by another cell, and its root-secret fingerprint (`keys_fp`) matches no other cell's. Upstream identity providers and workload issuers may be shared, since a cell mints its own token from them; a gateway (`LOOM_IDENTITY_PROVIDER=gateway`) mints for one cell, so a deployment runs one gateway per cell; - no live process of any other cell reports a fingerprint matching neither value of its directory row, and every live process of the cell being attached matches its `loom.cell_self` `current` or `next` (attach names any that does not); - no other cell records the same (OIDC issuer, client id) pair (the directory row records them, and `loom cell update` counts them in its overlap refusals); - with SCIM on, every SCIM token it holds names it (`lsc__…`), or, on the first cell only, names no cell; a later cell holds no SCIM user row or tombstone (its people are provisioned after attach, in the order `LOOM_CELL`, a named token, then the application's assignment); - its `LOOM_PUBLIC_BASE_URL` is set (a process with `LOOM_CELL` set refuses to boot without it, so no URL it hands out comes from a request's Host), and the hosts of it and of `LOOM_OAUTH_ISSUER` (an empty one resolves to the public base URL) equal its registered host: for the first cell, whose registered host is the shared host, they are the shared host or a recorded alias of it; no later cell's host is the shared host or an alias, which the directory's `hosts` table (host as primary key, normalised by one function, `normalise_host`: lowercase, IDNA to ASCII, no trailing dot or default port, brackets kept on IPv6, used by `hosts`, rule 1, attach and the readiness check; owned by a cell, an alias belonging to the first cell) enforces, written in the same transaction as each check, and from which rule 1 routes; `LOOM_JWT_ISSUER` is an opaque string, needing only to be unique; prepare checks the same; - its configured orgs collide with no org placed in another cell, and no org pattern it trusts (its end-user issuers' `orgs`) overlaps another cell's patterns or configured orgs, nor does another cell's pattern match its configured orgs, by the overlap rule a single deployment applies to its own end-user issuers; - its stores are not another cell's: a probe key written to a reserved name of its `loom._migration_lock` KeeperMap is visible to no other cell and every other cell's probe is invisible to it (a ClickHouse without a Keeper refuses); its bucket prefix is neither a path prefix of another cell's in a bucket of the same name, on any endpoint, nor has one, and probe objects are listed in neither direction; - every live process of every cell runs a build whose predecessor also runs the tenancy check (below), and a heartbeat that reports its tenancy mode, fingerprint and the `LOOM_CELL` it runs with; - with SCIM on, no active account has a contact or verified email without an active SCIM row (password accounts, live refresh sessions and personal service accounts included), and no live service account's creator chain ends in an account with no email (agent-signup tokens made before SSO): attach lists them and refuses, or with `--revoke-unprovisioned` ends their tokens issued before the attach under SCIM's own revocation prefix, so a person the identity provider provisions later is admitted, since it will never deprovision a person it does not count as assigned. The provisioning census reads active accounts, current unexpired refresh families and unrevoked, unexpired personal service accounts in bounded pages of 128 rows and 65,536 bytes of projected string metadata. It uses each table's actual row key to continue, refuses an oversized page, and shares one finite scan budget. The same bounded person and ancestry reader checks every root freshly, including while the cell is recording; an authentication memo or a deactivation-only check cannot establish this precondition. A current refresh family supplies only its own stored verified email. Registered machine identities keep their existing closed exemption; a subject prefix or an absent creator grants nothing. With `--revoke-unprovisioned`, each accepted cutoff uses SCIM's own subject lease and revocation prefix. An outright revocation or a newer cutoff is retained. The command never creates a provisioned user, changes the operator's revocation row, or revokes a registered machine identity. An accepted cutoff is reported before confirmation and audit; a later failure leaves it in force and the census incomplete. Rerun with the same flag to finish. A dry run and a serving rerun never revoke. The first attach (`loom cell attach`, its procedure on [attaching the first cell](/docs/operations/cell-attach)) turns the existing deployment into the first cell. It aliases nothing (an `oauth_issuer_host` on another host refuses at `attach/begin`). With SCIM on, it freshly checks the complete provisioning precondition while still recording, before each mode-commit try, after enforcement and before serving. A serving rerun repeats that check without changing revocations. A run holds an advisory lock, `cell.ATTACH_LOCK_KEY`, on a session of its own for its life (prepare takes the same lock), after checking that the session is one direct backend that keeps the tenancy marker: a lock left on a pooler's server connection would refuse every later run, and attach's tenancy rows would be refused as an unchecked writer's. A lost or unreadable lock session ends the run: it never reconnects or reacquires the lock. Rerun attach to obtain a fresh directory claim and recompute the remaining work. Every local acceptance write uses this exact backend, so losing the lock also ends its authority to change acceptance. The lock serializes prepare, attach and update, and keeps concurrent scans from holding the snapshot horizon that step 4 waits on. It refuses, before any write, naming each: - stores other than the registered ones: the Postgres deployment id, ClickHouse's `loom.storage_authority` and the shared host's `/v1/health/deployment` each name the directory row's deployment id, `loom.cell_first` reads `(true, )`, the row is the first cell's, `attaching`, with no other directory row; - a database encoding other than UTF8 (prepare refuses the same), so a tenancy row within the length limit is always an org a request can name; - a synchronous standby not attached now, a durability profile that would not refuse without one, or a role that may not write the durable read's logical message; a role of attach's own lacking its grants (`pg_read_all_stats` among them) or a server with `max_prepared_transactions` above 0; - **the tenancy-privilege check**: a login role, other than attach's own (the role attach runs as, which the operator runs it with; superusers; and a role that itself owns `loom.tenancy`, `loom.tenancy_mode` or a guarded table) and those named with `--pg-allow-role`, that holds or reaches through any membership a right to make an org held or lower the mode: `INSERT` on any column of `loom.tenancy` or `UPDATE` of its `org`, `INSERT` on `loom.tenancy_mode` or `UPDATE` of its `mode`, `TRIGGER` on a `loom` table, `CREATE` on the database or a schema that is not a system one (a function there can shadow one the servers call unqualified on their marked session), `SET` or `ALTER SYSTEM` on `session_replication_role`, `ALTER SYSTEM` on `loom.tenancy_checked`, membership in `pg_write_server_files` or `pg_execute_server_program`, or ownership of a `loom` table, of the trigger functions or of `loom.cell_first_immutable()`, the database or a schema; - **the unmarked-session check**: a session that sends no marker reads one, or runs as `replica`; a `pg_db_role_setting` entry of `loom.tenancy_checked` or `session_replication_role` for this database or every one, matched case-insensitively; any logical-replication subscription into this database, enabled or not (its apply worker fires no origin trigger); - the heartbeats (both tables, stopped rows included for the widened window, the live window plus a stopping pod's drain and retirement): a live process with `LOOM_CELL` unset or another cell, one without the heartbeat's keys, `marked` false, `router` false where `serves` is true, a fingerprint on neither `loom.cell_self` value, several `keys_fp` values, or none live; a booting process (no cell row yet, no mode, `marked` or `router` null) is waited on within `--wait`; in `recording` a stopped process with `LOOM_CELL` unset refuses too; - the ClickHouse writer check and the scan's table list (`server/cli/cell_writers.py`, `server/cli/cell_scan.py`), and a settings profile or quota that caps what attach's user reads. Then, in order (the step numbers are the ones the rest of this page uses): - **`attach/begin`**, on every run, before any long step: the router probes the stores attach wrote its nonces to, checks the upstream, and writes the fingerprints and `keys_fp`; a directory restored to before it is written again. - **Step 1, the mode**: `recording`, or `enforced` on a resume, which goes from the triggers, through `attach/enforced` again, to the durable read. - **The triggers**: created by attach itself, on every run, before step 2 and again just before step 3 (so a table a migration added during the scan is guarded from the commit on): one table at a time under the migration lock, each DDL waiting 100 ms for its lock and retried a second apart within `--wait`; an autovacuum holding it gets one try just past `deadlock_timeout`, so it yields, and an anti-wraparound vacuum is named. Then `cell_triggers.missing`; any defect refuses. A refused attach in `recording` leaves the triggers, which pass every row there. - **Step 2, the scan**, in `recording`: one statement per table, no long transaction (step 4 reads every source again): the Postgres tables (`loom.tenancy` among them) by skip scans on an `org`-led btree index, then the ClickHouse tables, each flushed and synced first, with the configured orgs of both fingerprints. Log tables (`cell_scan.LOG_TABLES`) are not read: a log row keeps the org a caller typed before any check, so placing a log-only org would let anyone pin an org name to the cell; `loom doctor --stray-orgs` names such orgs. An org longer than `cell.ORG_MAX_BYTES` refuses, naming it, before any tenancy row is written; a name no request can carry is skipped and named. Then the tenancy rows of the orgs found, on a marked session, and no placement: unscoped callers are answered from the tenancy rows, and placing now would move the point of no return earlier. - **The pre-commit checks**: the heartbeats, the tenancy-privilege and unmarked-session checks and the standbys again, and the scan's elapsed time within half of `--scan-budget`, since step 4 reads the same tables again. Each refuses in `recording`, which can still be backed out. - **Step 3, the mode commit**: `attach/enforced`, then on the same ATTACH session an EXCLUSIVE lock on `loom.tenancy_mode`, 2 s a try within `--wait`, the attach lock confirmed and the cheap heartbeat refusals run before each try (a booting process skips the try). Each try, including COMMIT, has a client deadline: the lock wait plus a 3 s statement margin and a 5 s standby allowance. Each mode or trigger try reserves the smaller of one second and one quarter of its original client bound for cleanup. Its independent owner closes the session through the public driver API while query/transaction work is still alive, then cancels and reaps that work within the same absolute deadline. Borrowed checks and trigger DDL leave failed-session cleanup to that owner. Close failure or exhausted cleanup time aborts the transport and preserves the original failure; abort alone does not prove that server locks disappeared. A commit past its deadline has an unknown outcome until the durable read. Only acknowledged pre-COMMIT rollback with ATTACH still held permits another try on that backend. Any other failure ends the run without terminating another backend; rerun to take the lock and claim afresh. From an acknowledged commit on, the mode only rises: every later refusal leaves the cell `enforced` and `attaching`, and a rerun resumes from the durable read. - **The durable read**, in every run that reads `enforced`: the mode and the `first` row read in a transaction that emits a transactional logical message, whose commit waits for the synchronous standbys, with the standbys checked attached just before and after. Then `X`, the snapshot's xmax, which must exceed that message's xid. A READ COMMITTED writer that read `recording` holds an xid below `X`, and a REPEATABLE READ one a snapshot older than `X`: the trigger functions are `VOLATILE`, and the message's xid is assigned after the mode commit. - **The heartbeats** again: a process with `LOOM_CELL` unset or another cell, without the keys, unmarked, or with no router where it serves, refuses at once. No process depends on its cached mode (a request records a new org through `tenancy._RECORD`, which reads the mode `FOR SHARE`), so neither a cache lifetime nor a request deadline is waited out. - **Step 4**: wait, within `--wait`, while any backend of the cell's database but the polling one has an xid older than `X`, or any but an autovacuum a snapshot older than `X` (compared through `age()`, exactly `< X` and wraparound-safe); past `--wait` attach refuses, naming each, and each backend of another database holding the horizon. A prepared transaction, or a row of the cell's database whose state is hidden, refuses at once. Then the cheap checks (the writer check, `missing`, the Postgres checks, the heartbeats with every stopped process with `LOOM_CELL` unset aged out, the standbys); the rescan of every source in full, Postgres before ClickHouse (the outbox and delivery tables move rows to ClickHouse), and the queue and drain tables and the tables a view reads before the others (`cell_scan.MOVE_SOURCES`); the tenancy rows; the placements, in `attach/place` batches; the writer, trigger, Postgres and standby checks again; and the final checks, under a floor of their own (the larger of what `--wait` left and `instances.boot_allowance_s()`): the heartbeats, read through the rescan every half of the time the leader keeps a stopped row (`instances.PRUNE_AFTER_S`), refusing any process that ran with `LOOM_CELL` unset during it, `loom.cell_self` equal to the directory's fingerprints, one `keys_fp` equal to the one `begin` wrote, the mode `enforced`; then `attach/serving`. `--wait` (default 10 minutes) is the wall time the bounded waits share, each lock try included and never longer than what is left, but for a floor of 100 ms: every try runs once before the wait is judged spent, so `--wait 0` is one try of each wait with no retry; `--scan-budget` (default 2 hours) bounds each full scan, which `--wait` does not count. `--dry-run` runs the refusals and the scan, prints what would be placed and skipped and the scan's time. Cell state, tenancy triggers and placements stay unchanged; normal participant enrollment and retirement are still recorded. The router's checks at `attach/begin` do not run. On a `serving` row attach first verifies that the connected authority, configured cell and bucket match the directory registration. It then reads the cell's mode: `enforced` is done (exit 0), and any other mode refuses: the directory and the cell's Postgres disagree, as after a restore of one of them, and attach lowers and repairs neither. A later cell is attached only once the first is `serving`. It must hold no org data (attach refuses otherwise) and starts in `enforced`. Its attach runs, in order: the refusals; one directory transaction, under the directory lock and with the overlap refusals run again inside it, that writes `attach_started_at`, the placements of its configured orgs and its issuers, patterns and fingerprint (both values of `loom.cell_self`), refusing and writing nothing when a read-back names another cell (it names the org); the tenancy rows of its configured orgs and its `loom.cell_self`, in the cell; the SCIM precondition (`--revoke-unprovisioned` if given); and `serving`. A resumed later attach reruns the refusals other than a new cell's and continues from the first of these steps not done; the placements are idempotent through the read-back. Its people are provisioned by its own identity provider application before they sign in. An org's own services are attached as a cell of their own. A new org of people starts with `loom cell place --org`, then its people's assignment to that cell's applications; a cell with SCIM on admits no one until its first provisioning cycle has run. A cell nearing its stores' limits is closed to new orgs: its placement calls answer 503, so its issuers' new orgs wait for capacity rather than spill elsewhere. A resumed first attach reruns every refusal and continues by the directory row and the cell's mode: in `recording` from the scan, in `enforced` from the durable read; whenever the cell reads `enforced` it posts `attach/enforced` again, so a directory restored below the cell's mode is raised. The checks of the stores' writers are point-in-time: a grant, a role setting, a subscription, a ClickHouse writer or object added after `serving` passes them, as does a configuration file attach cannot read (`postgresql.conf`, `postgresql.auto.conf`, a standby's own) or a role that runs code as the server's OS user. `loom doctor` runs the tenancy-privilege and unmarked-session reads again on every run and warns on what it finds (`cell_tenancy_privilege`, `cell_unchecked_writers`); the runbook has the operator confirm the rest. ## What each cell runs Everything a deployment runs, unchanged: its pools, migrations, workers and their leases, health and readiness (a pod's readiness is its cell's), erasure and its census, audit checkpoints, backups and restores. A cell's restore is a single deployment's ([backup and recovery](/docs/operations/backup-and-recovery)), with the same limits: what the backup holds (its keys, revocations, sessions, bots and SCIM rows) comes back as it was. A cell adds one step after the store restore and before anything else that page runs: `loom cell restore`, with the cell stopped, run where the operator runs `loom cell place` and attach, with the router's operator credential, which no cell's configuration holds (a CLI command declared org-free: it writes the cell's own rows), writes back from the directory the rows a restore can take back, so `loom reconcile`'s erasures and redactions pass the tenancy check, and a restore of both stores, which `loom reconcile` refuses, still gets its cell's rows. It refuses while the directory is unavailable, and writes: - a tenancy row for every org the directory places in it; - whichever of the `first` and mode rows is absent, from the directory, as a resumed prepare does; a present `first` row that differs from the directory's is refused, and one that matches is kept; - once the tenancy rows are back, the directory's recorded mode over the mode row, only upward (`recording` to `enforced`), never down; - once the directory row holds the cell's fingerprint (attach writes it), its `loom.cell_self` from it (`current` and `next`); before attach the directory holds none, and the restored `loom.cell_self` stays as the backup holds it (a missing `current` is written by a rerun of `loom cell prepare` once the cell starts, a lost `next` by `loom cell update --config` again). A first cell restored to before its prepare, and not yet attached, serves nothing on the shared host at its processes with `LOOM_CELL` set (one with it unset serves as a single deployment, as before the rollout) until that rerun of `loom cell prepare`, which is the step right after it starts. A cell's readiness never waits for the directory, so an outage of it holds no cell's rollout. A process that reads `recording` records a new org only while the directory answers that its cell is `attaching` ([the heartbeat's keys](#the-heartbeats-keys)); while the directory is unreadable or marks the cell `serving`, a new org answers 503 and the orgs the cell holds keep serving. A restore to before the first attach's step 3 whose `loom cell restore` was skipped therefore serves no org it does not hold; `loom doctor` names such a cell, and `loom cell restore` raises its mode. **The directory is a highly available store.** Its Postgres runs with a synchronous standby and point-in-time recovery to its last commit, as a cell's does, so a failover or a corruption loses nothing committed. Losing it entirely is an outage that fails closed: every cell keeps serving the orgs it holds, routing continues from each router replica's signed snapshot of its last cache (written to shared storage on every directory change), and the placements, lookups of uncached orgs, `loom cell` commands that read or write the directory and the recording cells' state reads answer 503 or refuse until the directory is back, while `loom doctor`, with the router's read-only scope, reports its directory checks as not run and, with `LOOM_CELL` set, exits non-zero; rebuilding a lost directory from the cells is a design of its own. Each cell keeps, in its own Postgres, a copy of its directory row's configuration fingerprint (`loom.cell_self`), which its processes compare their configuration with and attach and `loom cell update` write ([The cell's own row](#the-cells-own-row)). `loom cell restore` rewrites its `loom.cell_self` from the directory; restored stores carry the cell's deployment id, so a restore to a new endpoint needs only the new address in the cell's configuration. Closing a cell or setting its `placements_max` is one command, `loom cell limit --cell [--closed | --open] [--placements-max ( | none)]`, which writes the directory alone, with the router's operator credential and none of the cell's stores, so it works while the cell is down; the router judges a placement from the directory row. An explicit `--open` refuses while the cell is `attaching`, including an already-open row and a combined quota edit. This behavior break preserves the closed, zero-placement boundary used by state cleanup. Close and quota-only edits still work; an attaching cell can complete attach while closed, then reopen once `serving`. ## Control mutation fencing A cell controller holds the session-level attach lock on one direct, marked, UTF8 Postgres connection for its whole run. Every write to `loom.cell_self`, `loom.cell_first` or `loom.tenancy_mode` checks that lock and its observed local state, then writes and commits on that exact connection. Prepare passes its lock connection to its row writer; attach commits mode on its lock connection. A lost connection ends the run. It cannot reconnect and continue an earlier claim. Terminating the client does not prove its server backend ended: another controller must actually acquire the attach lock before it starts, and an unresponsive backend can keep that lock until it is positively ended. The directory stores one opaque UUID, `cells.mutation_generation`, for each cell. `POST /cells/v1/operator/cells//claim` takes the directory advisory lock and cell row lock, compares the full observed registration and exact current/next JSON pair, generates a fresh UUID on the server, audits it and commits synchronously before answering. Every execution generates another UUID, including a repeated HTTP request. The caller never proposes a replacement UUID. Registration assigns a fresh default; a registration rerun reads the existing value without resetting it. Removing and registering the same name therefore cannot restore an earlier generation. Before its first local acceptance write, prepare, attach or a recovery controller claims the generation while holding its local lock. Every subsequent directory mutation carries `expected`: cell, first-cell flag, host, deployment id, bucket, prefix, probe/upstream addresses, exact current/next pair and the claimed generation. The claim carries the same fields without a generation. The directory compares them under its locks before any mutation or no-op success. Canonical JSON comparison distinguishes `false`, `0` and `0.0`. A stale request cannot release a reservation after its local backend dies and another controller claims and widens acceptance, even if the directory pair later returns to its earlier values. A delayed claim can invalidate another controller's work; it cannot let a dead local session write acceptance state. A lost acknowledgement is an unknown outcome. Stop the attempt and rerun: obtain the local lock, read current state and claim a fresh UUID before recomputing the action. Do not copy a latest UUID onto an old action. A successful claim or control transaction waits through synchronous COMMIT. A no-op transaction emits transactional WAL so it also proves an observed earlier write durable. Acquisition, statements, COMMIT and cleanup have explicit bounds; an interrupted or uncertain local transaction never continues on another connection. No operation record, persistent census, phase or lease is added. The UUID is coordination metadata and holds no memory content. One ephemeral owner supervises the command's raw session and child work. Opening keeps its 75-second bound and each local control transaction keeps its 60-second bound, reserving cleanup time inside that bound. On failure it sends public connection close before cancelling child work, so active statements and rollback cannot prevent bounded cleanup. An unexpected transaction error propagates immediately; it never waits for rollback on a session the owner will discard. Uncapped command work retains the existing one-second session-exit allowance, which cannot extend an expired bounded phase. A transport abort remains an unknown outcome, not proof that the server backend ended. Mode-lock contention retries only after an acknowledged pre-COMMIT rollback and a check that the same backend still holds ATTACH. A COMMIT, rollback or ownership-check failure never becomes a busy retry. After attempting the mode update, the diagnostic stays unknown until rollback plus ownership or COMMIT is acknowledged. Placement and cell control bind their cleanup owner synchronously inside the shared Postgres connector, before deployment or codec initialization can wait. A closed owner refuses initialization and closes a late session within its original deadline. Process admission, participant attribution and retirement seals still apply. Callers without an explicit owner retain connector cleanup until initialization finishes. Directory control mutations supervise the complete callback transaction independently, including acquisition and COMMIT. One 131-second bound includes public close, child settlement and pool-context exit, with cleanup time reserved inside it. Both a failed attempt and an acknowledged successful transaction close only their own acquired connection before releasing the pool context. Unexpected errors never wait for rollback on that discarded session. A late acquisition cannot start mutation work or obtain a fresh cleanup allowance; acquisition without a known proxy remains an unknown outcome. Ordinary live placement retains its separate transaction and connection handling. Repeated interruption keeps the same close task and original end; a completed child cancellation remains a terminal failure. Fallback abort errors cannot replace the first operation or cleanup failure. The shared directory pool opens physical sessions only for foreground acquisitions; pool object creation does not establish connectivity. Healthy released sessions are cached under the existing size cap, recycling and idle expiry. A later cold acquisition opens a new session. On fixed JSON codec initialization failure, an uncancelled acquisition awaits the driver's disconnect acknowledgment before locally aborting the never-borrowed raw session and running driver cleanup. An interrupted acquisition starts no new close allowance; an unacknowledged close records that closure is unknown. Native interruptions return to the foreground consumer after driver cleanup, with no autonomous opening or replenishment task. The source census for acceptance and operator directory writes is checked by `tests/unit/test_cell_control_census.py`, including dynamic cleanup tables, guarded entry points and the named exceptions: | Writer | Fence | | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cell_prepare._write_rows` | Fresh claim, observed local rows, exact lock backend | | `cell_attach_pg._mode_transaction` | Attach's claim, supervised mode try, recording/first/fingerprint comparison, exact lock backend | | `cell_control.backout` | Fresh claim, fenced close and zero-placement read, observed local rows, exact lock backend | | `cell_update_pg.write.change` | Fresh directory claim; owner's bounded transaction on the exact ATTACH backend, paired registration and exact observed local identity/pair before tenancy repair and acceptance write | | `directory.attach_begin`, `attach_place`, `attach_enforced`, `attach_serving`, `remove` | Claimed generation, full registration and exact pair, including retries/no-ops | | `directory.update_addresses` | Claimed generation, full registration and exact pair under directory/row locks; commit-time address check, audit and synchronous WAL acknowledgement in one bounded transaction | | `directory.update_configuration`, `_configuration_commit` | Claimed generation, full registration and exact pair under ordered org/directory/row locks; root-secret and reservation checks, placements, audit and acceptance commit in one bounded synchronous transaction | | `directory.configuration_placements` | Claimed generation, full registration and exact pair under directory/row locks; root-secret and actual winner checks with audit and synchronous WAL acknowledgement in one bounded transaction | | `directory.set_limit`, `rotate_credential` | Read and compare the current generation/registration/pair; do not claim or rotate | | `directory.register` | Bootstrap default or immutable rerun lookup; never replaces existing acceptance or generation | | `directory.place` | Immutable placement only; keeps its org/cell locks and quota checks; never writes local acceptance | Ordinary read-only routes are exempt; `configuration_placements` is an audited, WAL-fenced proof before local tenancy repair. Router migrations and an offline directory restore are maintenance operations. Update acceptance writers use the same claim and lock-session helpers; any additional acceptance writer must do so as well. A directory mutation uses the common comparison before its no-op branch. Direct privileged SQL is not an online control writer. The [control upgrade and recovery procedure](/docs/operations/cell-control) defines the required fleet turnover and offline restore of generations. N-1 data-plane builds can read and insert on the additive schema; old control clients and router handlers cannot participate in this protocol. ## Operations - `loom cell restore`, after any store restore and before `loom reconcile`, writes the cell's rows back from the directory ([What each cell runs](#what-each-cell-runs)). - `loom cell which --org ` names an org's cell (erasure, restore and support start there); for an org with no placement it names the first cell, which the lookup does not tell apart. - `loom cell limit --cell --closed` closes a cell to new orgs, `--open` reopens a serving cell, and `--placements-max ` sets its placement quota (`--placements-max none` clears it). - `loom cell remove --cell ` removes the directory row of an `attaching` cell with no placement. For both first and later cells, keep `LOOM_CELL=` and the registered store settings on the control client. Removal takes the direct marked ATTACH backend, verifies the paired deployment and registration, and claims a fresh directory generation before deleting the row. The first cell must also read `open`, enforcing the back-out order: stop or unset `LOOM_CELL` on the accepting processes, complete full-state cleanup, then remove the directory row ([troubleshooting](/docs/operations/troubleshooting#a-process-with-loom_cell-unset-is-gated)). Removing the row first answers every new org 503; clearing the state first gates every accepting process with `LOOM_CELL` set. A first cell with a placement goes forward, never back. Removal leaves the stores' state rows intact; full-state cleanup must precede preparing those stores again. - The router's operator credential is `lco_` and 128 lowercase hex (a router with no `LOOM_ROUTER_OPERATOR_SHA256` answers the operator API 503 with `NO_OPERATOR_CREDENTIAL`), which `loom cell credential new --operator` makes; the router keeps only its SHA-256. The operator API's refusals are not rate-limited: a per-address limit would let one stranger behind a shared ingress lock out every operator, and 512 bits are not guessed online. An operator command knows its outcome only when the connection never opened or the router itself answered, other than `BACKEND_UNAVAILABLE` (a COMMIT can land after its bound); after a timeout, a dropped connection or a gateway's page it says the change may have been made and what a retry shows. The operator credential is rotated by setting the new hash in `LOOM_ROUTER_OPERATOR_SHA256` and restarting the router; while its replicas roll, some still refuse the new credential with 401, and the operator runs the command again until every replica accepts it. The commands call the router at `--router`, else at `LOOM_CELL_ROUTER_URL`, at its root (a path there is refused, since the router forwards one to a cell), and send the operator credential only over https (http on loopback), so an in-network `http` router address serves a cell but not these commands. - `loom cell credential new` makes a router credential offline and prints it with its SHA-256; `loom cell credential --cell --next ` records a new router credential's SHA-256 as the cell's `next` hash; like prepare, it takes the hash as an argument, in the same form. It uses the router's operator credential, writes only the directory and holds the directory lock; it is refused when any cell records that hash as current or next, and while a `next` is pending. The router accepts both on placement calls and state reads, every replica within `LOOM_ROUTER_DIRECTORY_CACHE_S` of `--next`, so the new credential goes into the pods only after that; `loom router migrate` runs before a router that reads the `next` hash, and a rotation starts once every router replica does. A router rolled back to a build that reads the current hash alone refuses a pod on the next one: roll back with no `next` pending (`--revert` first), and not between `--finish` and the old credential leaving the pods. Once the new credential is in the cell's pods and, while the first cell's mode is `recording`, its CLI configuration, `loom cell credential --cell --finish` makes `next` current and drops the old; it checks nothing it cannot see (the router does not know which credential a pod holds), and a cell finished too early fails closed: its placement calls and state reads answer 401, at the latest once the router's cache of the cell's hashes expires (`LOOM_ROUTER_DIRECTORY_CACHE_S`), until its pods hold the new credential, or the old hash is recorded again with `--next` and finished. `loom cell credential --cell --revert` drops a pending `next`, so a wrong or leaked one never has to be finished; `--finish` and `--revert` refuse with no `next` pending. - A new cell's settings name `LOOM_CELL`, its public host (`LOOM_PUBLIC_BASE_URL`, `LOOM_OAUTH_ISSUER`, `LOOM_JWT_ISSUER`), its keys, its bucket prefix, its configured orgs, its identity provider OIDC client and SCIM token, and its router credential (`LOOM_CELL_ROUTER_URL`, `LOOM_CELL_ROUTER_TOKEN`, which its pods hold, and `LOOM_CELL_ROUTER_TIMEOUT_S`). - Each cell reports writes per second, rows per namespace and bytes per key in `/v1/health?include=capacity`, against about 13.6 KB a key in ClickHouse and 6.8 KB in Postgres ([Memory at scale](/docs/benchmarks/results#memory-at-scale)). - **An org stays in its cell.** Moving an org between cells is a design of its own: it needs the org's writes fenced in every process of the cell, a copy of every store that counts nothing twice, and a verified removal. - **A cell's data stays in its stores.** Moving it to other stores (another deployment id, bucket name or prefix), or adding a bucket to a cell prepared without one, is a design of its own: old and new processes would write to different stores during any rollout, so it needs the cell's writes fenced as an org move does. - **A cell stays attached.** Retiring a cell is a design of its own: it needs proof, from the stores themselves, that every copy of its orgs' data is gone, before anything may answer that it is. Until then a cell that is down stays a cell: its orgs answer 503, and its names, issuers, hosts and placements stay reserved. ## Failure modes | Failure | What happens | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | The directory is down | requests by host, by issuer and to the first cell are routed; new orgs and uncached lookups answer 503 | | The router's placement call fails | the request answers 503 and nothing is written; orgs the cell holds are served | | A cell's issuer places orgs in a flood | from `enforced` on, its placement calls answer 503 with `Retry-After` past its rate, and its calls for new orgs answer 503 past its quota if one is set; other cells place as before | | A SCIM token of another cell, or an application at the wrong cell's host | the process does not boot, or `/scim/v2` answers 401 and writes nothing | | A cell's Postgres or ClickHouse | that cell fails as a single deployment does ([storage authority](/docs/architecture/storage-authority#failure)); other cells serve | | A cell's own rows or tenancy mode are unreadable | with `LOOM_CELL` set a process keeps its last rows and mode within the stale bound, then is gated, a server process whose first read fails does not boot (gated and unready with Postgres migrations pending), and a workers child that never read them is gated; with it unset a server process keeps its verdict with no bound, and a failed first read fails its boot (gated until a read lands with Postgres migrations pending) | | A `first` or mode row removed, or both beside a tenancy or own row | the org triggers, where a cell has them, act as in `enforced` and every process is gated; `loom doctor` names it, a prepare rerun writes them back | | No state, tenancy or own row on a cell the directory registers | open; `loom doctor` names it; `loom cell restore` closes it after a restore, a prepare rerun after a stopped prepare | | A cell's `first` value is not yet read | every request but health probes and the probe route answers 503 (SCIM with `Retry-After`); the process is unready and runs no worker (a workers child, or a server process with Postgres migrations pending; any other server process fails its boot) | | A request for another cell's org | 409 `WRONG_CELL` after verification, nothing written | | A platform, `*`-org or principal-less call for an unheld org | on a first cell, 503 while the directory answers `attaching` or cannot be read before a `serving` answer; 409 `WRONG_CELL` once `serving` and on a later cell | | A pooler that strips the tenancy marker from a cell's sessions | the `cell_marker` readiness check fails in `enforced` and `partial` and warns in `recording`; the heartbeat reports `marked` false and attach refuses the process | | A cell restored to an earlier time | `loom cell restore` writes placed orgs' rows back before it starts | | A first cell restored to before its prepare, not yet attached | at processes with `LOOM_CELL` set, every request but health probes and the probe route answers 503 until prepare reruns | | The directory lost | every cell serves the orgs it holds; placements and uncached lookups answer 503, directory commands refuse, until it is back | | A cell in `recording`, the directory unreadable | a new org answers 503; the orgs it holds keep serving | | A process stuck during first attach | before step 3, attach refuses after `--wait` and the cell stays `recording`; after it, attach refuses, leaving the cell `enforced` and `attaching`, and a rerun resumes | | A recording insert held open during first attach | the mode commit's tries wait behind its `FOR SHARE` lock within `--wait`; past it attach refuses and the cell stays `recording`; a rerun resumes | | Attach stalls while it holds the mode table's lock | the client attempts bounded cleanup; if backend or lock release is unproved, stop and verify the exact holder before retrying | | A transaction open since before step 4's snapshot | attach refuses once `--wait` runs out (a prepared one at once), naming what it waited on, and leaves `enforced` | | A CLI command with `LOOM_CELL` unset, started before attach's step 3 | it read the state while the first cell was `recording` and keeps writing ClickHouse after `serving`; the runbook sets `LOOM_CELL` on every CLI before attach, and `loom doctor --stray-orgs` names the orgs it left without a tenancy row | | A CLI of a build before the state read | it is not refused on an `enforced` cell; every CLI and CI image runs a build with the read before attach ([upgrades](/docs/operations/upgrades#upgrade-procedure)) | | An org found only in a log table of the first cell | never placed; once it is placed in another cell, its log rows here (`agent_events` identities among them) are outside its erasure there until they are removed by hand (the runbook's procedure); `loom doctor --stray-orgs` names it | | An org longer than `cell.ORG_MAX_BYTES` written before the limit | the first attach refuses in its scan, naming it, until the runbook's manual procedure removes it; one first found in step 4 is skipped and named | | A writer, grant, role setting or subscription added after `serving` | attach's checks ran once and pass it; `loom doctor` warns on the Postgres ones on every run | | `LOOM_SERVES_TRAFFIC=false` on a pod a load balancer routes to | attach does not require its router answer; its new orgs answer 503 | | A process that changes between attach's last check and the mode commit, or an HA manager that empties `synchronous_standby_names` between the checks around the durable read | not seen by attach: a window of seconds | | A cell process with a longer `LOOM_INSTANCE_HEARTBEAT_SECONDS` than attach's | it can fall outside attach's live window while live; the runbook requires one value | ## Rolling upgrades The tenancy check, the placement call and the cell's state read, the CLI's org declarations, `LOOM_CELL`, `loom cell prepare`, `scim.refuses_subject`, the email a grant stores, `loom.cell_self`, the request gate and readiness check of a process's fingerprint against its own row, the refusal of another cell's SCIM token, the SCIM requirement, and the heartbeat's mode, fingerprint and `LOOM_CELL` ship in one release. The gate on a process with `LOOM_CELL` unset, the session marker and the org triggers ship together in one release; a first cell's prepare admits a process of the release before it, which serves while the cell is `recording`, and `loom cell attach`, which ships in a release after it and reads its own heartbeat key, refuses until every live process runs that release, so the one supported rollback from an attached cell lands on a build that sends the marker. The org triggers' migration is additive, and the triggers do nothing on a deployment never prepared (no state rows, the `first` row's rule). With `LOOM_CELL` unset a process reads only the mode and `first` rows and whether a tenancy or own row exists, and only under the Postgres authority, where a deployment never prepared has none (the tables are created empty), so builds N-1 and N serve side by side unchanged. The router routes by host, issuer and the first cell, never by a cell's ops, so a cell's release does not wait on the router's, but for the one the next paragraph names. The keys beside a heartbeat's fingerprint ([the heartbeat's keys](#the-heartbeats-keys)) are the attach release's own heartbeat keys: a build before them reads only a fingerprint's version and fields, so it takes a newer build's heartbeat as it is, and attach refuses a process that reports none. That release waits on the routers': every router replica runs it before any cell's processes do, since a prepared first cell asks the state route from its first cell-state read until it reads `serving`, and only a router of that release answers it from its cache ([upgrades](/docs/operations/upgrades#upgrade-procedure)). ## Invariants - An org is served by exactly one cell, the one its placement names, and its placement is never deleted or changed. - A process with `LOOM_CELL` set answers nothing but its health probes and the probe route, and runs no worker, unless its configuration matches a value of its cell's own row, which the directory's overlap refusals have checked; a process with `LOOM_CELL` unset on a cell whose state rows count as `enforced` or are in a `partial` state (the `first` row's rule) answers nothing but its health probes and the probe route and runs no worker. - No bearer-token issuer, host, OIDC client, org pattern or bucket prefix is accepted by two cells, and no deployment id or router credential is held by two. - Every security path fails closed, with four exceptions. First, a server process with `LOOM_CELL` unset keeps its verdict through failed reads of the state rows with no stale bound: open in `open` and `recording`, as a single deployment's partial outage is, and gated in every other state; a failed first read fails its boot, or with Postgres migrations pending leaves it gated until a read lands. Second, a registered cell with no state, tenancy or own row (its Postgres restored to before its prepare, or a prepare stopped before its row write), which is open until `loom cell restore` (after a restore) or a prepare rerun (after a stopped prepare) and named by `loom doctor` meanwhile: an unread row, mode or `first` value refuses; with the directory unreachable, placements, uncached lookups, the `loom cell` commands that read or write it and the recording cells' state reads refuse while each cell keeps serving the orgs it holds. Third, a migrating boot that cannot create or enable an org trigger or the `loom.tenancy` guard on a table, or set `loom.cell_first`'s triggers back to always (its lock not taken in three tries of 100 ms, or a table the role cannot alter), logs it and serves, leaving that table unguarded until a later boot succeeds: the triggers are a backstop only against writers that send no marker, refusing the boot would take a cell down for a backstop, and attach refuses a missing trigger. Fourth, an org-free revocation command that cannot give access back (a plain `loom revoke-token`, not one that narrows or lapses, a SQL user's revocation, `loom signing-key retire`, `loom bot disable`, `loom sso unlink`) with `LOOM_CELL` set whose read of the cell's `first` row fails for a Postgres that does not answer runs and prints that the cell was not checked, since a revocation must work through an outage; any other failed read, a missing grant among them, refuses. ## Source entry points - `server/core/cell_probe.py`: the probe route and the probe listener, which every web process accepts on and the workers child never opens; - `server/core/cell.py`: the cell's own state (`loom.cell_first`, `loom.tenancy_mode`, `loom.cell_self`), the deployment's state rule (`state`, over the rows `refresh` reads, whether `loom.tenancy` holds a row among them), its fingerprint and `gate_reason`, the gate on processes with `LOOM_CELL` set or unset, which the request middleware (`server/transport/model_maintenance.py`), `verify_token`, readiness, the workers' lease and the heartbeat read; `server/boot.py`'s `start_cell_gate` is a server process's boot read; - `server/core/cell_triggers.py`: the org triggers' marker, `ensure` (a migrating boot's creation and repair of the triggers and the `loom.tenancy` guard) and `missing` (what `loom doctor` names), with their functions in `schemas/pg_migrations/011_tenancy_triggers.sql` and `012_tenancy_guard.sql`; `server/cli/doctor_cell.py`: `loom doctor`'s cell checks; - `server/cli/cell_attach.py`: `loom cell attach`; `server/cli/cell_attach_pg.py`: its Postgres reads and writes (the session checks, the attach lock, the tenancy-privilege and unmarked-session checks doctor shares, the trigger pass, the mode commit, the durable read, step 4's wait); `server/cli/cell_attach_beats.py`: its judgment of the heartbeats and the rescan's watch; - `server/cli/cell_scan.py`: the first attach's org scan: the tables of both stores with an `org` column, judged by engine and against erasure's classification, every host of a cluster listing the same, and the distinct orgs of each table outside `LOG_TABLES`; `server/cli/cell_writers.py`: the ClickHouse writer check (the users, user directories, objects and replicas outside the operator's allow lists); `server/core/cell_ch.py`: what both share (the cluster's hosts, the per-host reads); - `schemas/pg_migrations/008_cells.sql`, `schemas/pg_migrations/009_cell_probe.sql` and `schemas/migrations/094_cell_heartbeats.sql`: the cell's tables; - `server/auth/tenancy.py` (`ensure_held`): the tenancy check and the placement call, run by the op gate (`server/transport/gates.py`), `check_authorized`, `admit_org` and the routes that name an org; `server/transport/tenancy_gate.py` checks the token's own org on the routes outside the registry that act in it, and `tests/unit/test_cell_tenancy.py` holds the census of every route; - `server/router/app.py` (`loom router serve`): the placement API, the first cell's state read (which `server/core/cell_router.py` makes on a first cell), routing by rules 1 to 4 (`server/router/routing.py`, which decides, and the forward), the org lookup with its cache of placed orgs (which `loom login --org`, `loom.credentials.org_server`, asks), their rate limits (`server/router/limits.py`) and the checks a placement passes; its operator API, with the first cell's attach routes, which `loom cell limit`, `loom cell credential` and `loom cell remove` (`server/cli/cell.py`, with `loom cell which`) call with the router's operator credential (`LOOM_ROUTER_OPERATOR_TOKEN`; the router keeps only `LOOM_ROUTER_OPERATOR_SHA256`); `server/router/directory.py` and `schemas/router_migrations/`: the directory, in the router's own Postgres database (`LOOM_ROUTER_PG_DSN`, `loom router migrate`). The rest of the cell code is added by the pull requests that implement this page. It builds on: - `server/auth/jwt.py` (`verify_token`, `AuthUnavailable`): where the fingerprint gate runs first; - `server/auth/scim.py` (`tokens`) and `server/auth/scim_routes.py` (`scim_settings_problem`, `_authorized`): the SCIM token parser and checks; - `server/core/instances.py`: the heartbeat that reports mode, fingerprint, `LOOM_CELL` and the keys beside the fingerprint; - `server/workers/leader.py`: the lease a gated process stands aside from; - `server/core/pg.py` (`same_deployment`): the deployment id both stores carry; - `server/transport/gates.py` (`resolve_org`, `authorize`): where the tenancy check runs; - `server/cli/_ch.py` (`run_connected`, `connect_checked`, `connect_declared`): the CLI's org declarations, which `tests/unit/test_cell_cli_orgs.py` requires of every connect; - `server/auth/authz.py` (`check_acted_for`, `_check_creator`) and `server/auth/oauth.py` (`_refresh_session`): the SCIM checks on acting and refreshing; - `server/identity/app/scim_groups.py` (`_caller`): the second SCIM route. ## Rejected - **A control plane shared by the cells** (one set of keys, grants and workers, the data split by org): a security check, a worker lease, an erasure, a policy generation and the audit chain would each span stores, and each split needs a protocol of its own. - **Placing an org at its first request, before verification**: anyone could choose an org's cell, and a token minted in one cell could address an org placed in another. - **A list of the paths that create an org, each placing it**: orgs come into being by more paths than a list keeps up with (gateway and federated tokens, bots, imports); the verified check is the one place every request passes. - **Redirecting a flow from one cell to another midway**: a flow's client, codes and refresh tokens live in the cell that started it. - **The router holding the identity provider's users for every cell**: each email's reach into each cell, a version that survives the directory's loss, pushes and pulls would each be a protocol of its own, where the identity provider already deprovisions every application a person is assigned to. - **Every replica reaching every cell's stores**: a pool per replica per cell, the cost [A database per tenant](/docs/architecture/storage-authority#a-database-per-tenant) rejects. - **Routing by namespace within an org**: an org-wide operation (its erasure, ids resolved across namespaces, sharing) would span cells; a large org gets a cell of its own. ## Tests An integration test with two cells and a router in CI's Postgres job: - a verified request for a new org at each cell places it once under concurrent requests, and the other cell answers `WRONG_CELL`; a gateway-minted org, an end-user issuer's `prefix*` org and a bot's org are placed the same way after `enforced`, and a platform principal's request for an unheld org places nothing; - every route, the batch entries of MCP and every CLI command included, refuses another cell's org and writes nothing in its Postgres or ClickHouse (the route, op-field and CLI censuses cover the rest); - the first attach places every org with a row in any table, an org first seen during the attach is placed in step 4, and so is one a direct Postgres insert wrote between step 2's scan and `enforced`, a ClickHouse row an older CLI wrote then and a bucket object catalogued then; a process past `LOOM_JWT_REVOCATION_MAX_STALE_SECONDS` of failed reads of its own rows or mode is gated and serves again once a read lands; a pod with `LOOM_CELL` unset is unready, naming the setting, answers 503 to a bearer request, passes its health probe, answers the probe route and runs no worker on an attached cell and on a later cell between prepare and attach, keeps serving on a first cell in `recording`, and keeps the last mode it read through a failed read, `recording` included; a CLI command declaring an org with it unset is refused on an `enforced` or `partial` cell, an org-free one (a token revocation) runs, also with Postgres down on a deployment never prepared, and a `loom cell` store command refuses; `loom cell limit --closed` succeeds with the cell's Postgres down; after `loom cell credential --cell --next` both credentials place and read state, `--finish` refuses the old credential, for a cell finished before its pods hold the new one the router refuses its calls with 401, its request answers 503 writing nothing, and it recovers by recording the old hash again, `--revert` drops a pending `next`, which is then refused, and the old credential keeps placing, and a second `--next` while one is pending and a hash another cell records as current or next are refused; `loom cell limit` and `loom cell credential --next`, `--finish` and `--revert` refuse while the directory is unavailable; concurrent placements at one under `placements_max` across two router replicas write one; a CLI command declaring an org with `LOOM_CELL_ROUTER_TOKEN` set refuses, naming it, on a first cell once it is `enforced` (`attaching` included) and on a later cell, and on a first cell in `recording` runs and records the org; attach with `placements_max` below the orgs the first cell holds places them all, and a later cell's attach past its quota or closed refuses, naming the org; a first cell with `--closed` and `placements_max` set before step 2 attaches, and an org a request records between step 2 and `enforced` is placed by step 4 with no 503; after step 3's write of the cell's mode, a process whose cache still reads `recording` sends a new org's request to the placement call, which a closed cell answers 503; a CLI command whose insert finds `enforced` refuses, naming the org, and makes no placement call; a refusal after step 3's write leaves the cell `enforced` and `attaching`, where a new org is placed through the gate; each ordering of attach's write of the mode with a recording insert holds as stated above (running, starting during the write, a stream of overlapping inserts each shorter than a try, with attach setting `enforced` within a try or two, held across several tries, held past `--wait` (attach refuses, the cell still `recording`), a stalled attach, a commit cut off by its timeout, and a commit whose connection is lost while it waits for the standby, which the durable read decides); a `REPEATABLE READ` transaction whose first statement ran before `enforced` committed, on attach's role or a second role, holds step 4 until it ends and its write of an unheld org is then placed, one whose first statement ran after is refused by the trigger, a transaction that starts after attach takes the lock but before its commit is visible holds step 4, a transaction opened in `recording` that outlives one run's `--wait` holds the rerun's step 4 after a refusal, an autovacuum worker on a loom table does not hold step 4 and a background worker with a transaction open since `recording` does, a prepared transaction (after a restart with `max_prepared_transactions` raised during the wait) makes step 4 refuse at once, naming it, with the mode still `enforced` and a rerun refused until it is resolved and the setting is back to 0, a write transaction open in a second database on the same server holds step 4 and is named, a long read on the synchronous standby, or on a second standby, with `hot_standby_feedback` on does not hold it, nor does a base backup running across it, a write held open on a `replication=database` connection holds step 4, and so does a `REPEATABLE READ` transaction on one, opened in `recording` and writing nothing before `enforced`, a long logical dump (a `REPEATABLE READ` read-only transaction) on the cell's database past `--wait` makes step 4 refuse, naming it, with the cell left `enforced`, and the first cell's attach without `pg_read_all_stats` or with `max_prepared_transactions` above 0 refuses before step 1 with the mode still `recording`, while a later cell's attach does not require either; a missing or disabled org trigger is refused by attach and named by `loom doctor`, a write for an unheld org on an `enforced` cell whose mode row was deleted is refused and the state named by `loom doctor`; on that cell a pod with `LOOM_CELL` unset is unready and runs no worker, and a CLI command declaring an org with it unset is refused, as a pod is; updating, deleting or truncating the `first` row on an `enforced` cell is refused, also under `session_replication_role = replica`, and a missing or disabled `first`-row trigger is refused by attach and named by `loom doctor`; a running process with `LOOM_CELL` set on a cell whose mode row is removed answers 503 to a bearer request and runs no worker pass, and serves again after a rerun of `loom cell prepare` writes the row back while it runs; a cell the directory registers with no state, tenancy or own row is named by `loom doctor`, its processes with `LOOM_CELL` set stay unready, a process with it unset serves as a single deployment, and `loom cell restore` writes both rows back, an attached cell then serving again and an unattached one after a prepare rerun; a cell with both rows absent beside a tenancy row, and one beside only its own row, has the function refuse an unheld org (a boot creates no trigger there), every process gated and `loom doctor` naming it, and a prepare rerun writes the rows back; a Postgres-only restore of an attached first cell to before its prepare is named by `loom doctor` and closed by `loom cell restore`; a prepare rerun during a pending `loom cell update` on an attached cell, with processes on both values and `loom.cell_self` lost, writes both values back and keeps both sets of processes serving, and one before attach refuses the two configurations; a prepare rerun on an attached cell whose `current` is missing and whose pods' configuration differs from the directory row refuses, and one before attach whose heartbeats report another bucket prefix refuses; a prepare rerun given a credential hash that is neither the row's `current` nor its `next` is refused; a prepare rerun on a `serving` later cell whose prefix holds data writes a removed mode row back; a cell with a mode row and no `first` row has the function refuse an unheld org (a boot creates no trigger there), every process gated and `loom doctor` naming it, and a prepare rerun writes the row back; a later cell whose mode row is set to `recording` records nothing, its trigger refuses an unheld org, a process with `LOOM_CELL` set there serves as in `enforced`, a pod with `LOOM_CELL` unset there is unready and runs no worker, `loom cell prepare` names the row, a CLI command declaring an org with `LOOM_CELL_ROUTER_TOKEN` set refuses, naming it, and the router refuses its state read; a build N-1 process's `memory.set` and delivery pass on a never-prepared deployment after N's migration succeed and write no tenancy row, and on the first cell in `recording` a boot creates no org trigger, and one created by hand reads the state and looks nothing up, a write under `session_replication_role = replica` for an unheld org is skipped (origin triggers), an `INSERT ... ON CONFLICT DO UPDATE` that inserts a row for an unheld org is refused and one that hits an existing row of it is not, a marked session's every write passes, and the triggers on an `enforced` cell cover every table erasure classifies with an `org` column but the three exclusions; and an org-keyed write while attach holds the mode table's lock returns at once, with new-org requests answering within their deadline and mode-cache reads returning at once throughout; a refusal at step 3's lock leaves the cell `recording` with its directory row `enforced`, and the rerun runs step 2 again; a `LOOM_CELL_ROUTER_TOKEN` not of the `lcr_` form is refused at boot and named by `loom doctor`; `loom cell credential new` prints a credential of that form and its SHA-256, with the directory and the stores unreachable; prepare and `--next` refuse an argument that is not 64 lowercase hex characters, the credential and its bare 128-character secret included, storing nothing; orgs a first cell records in `recording` with no data are listed by `loom doctor`; a placement flood with no quota set is held to the rate limit at each router replica, `loom doctor` names the cell as one with no quota, and a call refused past it at one replica answers 503 with a `Retry-After` of at most 60 s, after which its retry at that replica, with no other call of the cell admitted between, is admitted; a cell's first prepare, with no directory row yet, passes the deployment-id check; a pod or CLI that lost `LOOM_PG_DSN` or `LOOM_STORAGE_AUTHORITY` on a cell is refused by the authority check; the first cell's existing tokens, refresh tokens and OAuth clients keep working through the cutover, a logout through the shared host revokes its refresh token; - attach refuses a shared issuer, root secret, Keeper path, nested bucket prefix or configured org, a second cell that holds data, and a second attach while one runs; - an OIDC sign-in, an MCP client's authorization and a device flow for an org in the second cell complete at that cell's host after a lookup; `loom login --org` keeps its host on `NO_CELL` and on a deployment with no router, retries after a 429's `Retry-After` until `--wait` is spent and then refuses as a rate refusal, and, while the directory is down, starts its flow at the cell host of an org the router has cached and refuses, starting no flow, for one it has not; - with SCIM on, a person the identity provider never assigned to a cell cannot sign in, refresh, be acted for or use a gateway token there, a deactivation pushed to a cell's application ends the person there, a platform-admin bot still reaches a cell whose SCIM deactivated everyone, and attach refuses a cell with unprovisioned live subjects or sharing another's OIDC client; - an attach stopped after step 3's commit landed, before the durable read, says the commit's outcome is unknown, and its rerun resumes by the mode it reads; one refused after the durable read resumes from it, the mode still `enforced`; a later attach refused before its directory transaction leaves `attach_started_at` empty, so a rerun checks a new cell's refusals again, and a resumed first attach finds its configured orgs placed in this cell and carries on; - a cell restored to before the first attach's `enforced` gets its mode back from `loom cell restore`; one whose `loom cell restore` was skipped answers 503 for an org it does not hold, another cell's org included, writes no tenancy row for it, and is named by `loom doctor`; a directory outage during the `LOOM_CELL` rollout and between prepare and attach leaves the first cell serving the orgs it holds, a new org answering 503 at every process with `LOOM_CELL` set; the state read is accepted from a first cell that is `attaching` before attach's step 2, and only with the named cell's own credential, and a refused or late answer counts as unreadable; - a grant refreshed at N that was written at N-1 is checked against the person's row, a refresh while SCIM is unreadable answers 503 and keeps the session, and a process with `LOOM_CELL` set before `loom cell prepare` stays unready; - a token delegated during the first attach by a person never provisioned is refused after `enforced`; a gateway acting for a bot is served and for a bare handle refused; - with the directory unavailable, every cell serves the orgs it holds, placements answer 503, and `loom doctor` on a cell reports its directory checks as not run and exits non-zero; - `LOOM_CELL` rolls out after `loom cell prepare` with every pod ready, before attach; - preparing an empty cell before the shared host's deployment is refused, and a cell restored from another cell's snapshot is refused at prepare; - a prepare killed between the directory write and the cell write, with `LOOM_CELL` rolled out, is rerun through `probe_url` against gated processes; a prepare rerun before attach whose heartbeats match neither the present `current` nor `next` refuses; an attached prepare rerun with only `next` lost writes it back, and one whose present `current` differs from the directory overwrites it; a prepare rerun alone after a Postgres-only restore of an attached first cell to before its prepare leaves `loom doctor` naming the missing tenancy rows, and a pod with `LOOM_CELL` unset serves every org there until the rerun and is gated after it, while with `LOOM_CELL` set an org gets its tenancy row back through the placement call; a prepare rerun against `LOOM_CELL`-unset pods in a `partial` state reaches their probe route and writes the missing row back; prepare refuses a later cell's `probe_url` that reports an id other than its stores', attach refuses a cell whose host reports an id other than its `probe_url`'s, and prepare refuses a probe address argument for the first cell, and the router probes only `LOOM_ROUTER_UPSTREAM_PROBE_URL`; a later cell's first prepare succeeds; `loom cell update --probe-url` refuses an address that reports another deployment id or fails the nonce echo, and refuses the first cell; `loom cell update` moves the first cell's probe and upstream addresses only once every router replica runs them, after their probe and the upstream's id check, and a prepare rerun through a replica still on the old values (or the new, before the move) is refused, naming the row's address; `probe_url` with userinfo or another scheme is refused; the main port answers only the in-memory id, with any Host, reading no store; the router probes an https `probe_url` whose certificate a CA in its `SSL_CERT_FILE` signs; the probe listener answers 429 past its rate; and a prepare given a copy of the first cell's stores is refused by the nonce; - the default first cell (`LOOM_JWT_ISSUER=loom`, an empty `LOOM_OAUTH_ISSUER`) attaches; a cell redeployed with the shared host as its public URL becomes unready; - a placement inserted at a cell's quota whose call timed out is retried and answers its winner, and the cell writes the tenancy row; the same on a cell closed meanwhile, and for a `loom cell place` rerun; - an attach that dies between its directory write and its `loom.cell_self` write resumes to `serving`, and its issuers stay reserved meanwhile; a `loom cell place` for an org another cell holds writes no row, and one for an org the directory does not place is refused, writing no row, for a closed cell, past `placements_max`, for a later cell still `attaching`, for a first cell before the directory records `enforced`, with a configuration whose fingerprint matches neither value of the cell's row, and while the directory is unavailable, and is neither refused once the cell's rate is spent nor counted toward it (the cell's own placement calls are still admitted after a run of operator places); one for an org the directory places in this cell writes its tenancy row on a closed or full cell; `loom bot create` for a new org on a first cell in `recording` records the org while the directory answers `attaching` and is refused while it answers `serving` or cannot be read; - an OAuth issuer host that differs from the cell's public host is refused at prepare, and the shared host routes before any cell is attached; a `loom cell place` with no other writes keeps the org in its cell; - a first cell restored to between attach steps 1 and 3 after it is `serving` becomes ready in `enforced` once `loom cell restore` has run; - a cell restored to before a `loom cell update --finish` serves again once `loom cell restore` has rewritten its own row, a cell whose two stores are both restored gets its rows back from `loom cell restore` alone, and a prepared, unattached cell keeps its restored own row; - a first cell restored to before its prepare gets its rows back, answers 503 on the shared host at processes with `LOOM_CELL` set until `loom cell prepare` is rerun, and then serves; SCIM on a deployment with `LOOM_CELL` unset works as before at N, through prepare, the `LOOM_CELL` rollout and attach; - the first cell's SCIM keeps answering its unnamed token through the cutover, a later cell refuses an unnamed token, no cell accepts another cell's token, `lsc_b_…` and a malformed `lsc_` token are refused in the first cell, and a later cell with a SCIM row written before `LOOM_CELL` is refused at attach; a token of cell `a-b` is refused in cell `a`, and a cell name with `_` is refused; - a later cell with `oidc_jit_org` set boots and restarts its pods between prepare and attach, JIT for that org answering 503 until attach places it; a first cell's self-signup into an org no request has recorded, between prepare and attach, records it and signs up; a later cell with indexed repositories writes no code row before attach and then attaches; a first cell in `recording` keeps its worker passes for an org no request has touched since the rollout; a later cell's attach stopped after `attach_started_at` resumes with its configured orgs placed and held; an update between prepare and attach that changes the code org has that org placed by attach, and after `--finish` it indexes; an update after attach refuses a changed configured org another cell holds, naming it, and, for an org the directory does not place yet, is refused for a closed cell and past `placements_max`; an update changing a configured org of a later cell still `attaching` after its directory transaction is refused until the cell is `serving`; `--revert` keeps a configured org the update placed; a later cell's code and tracker orgs serve and index once it is `serving`, a `code.*` op from another org's member included, and so does a configured org `loom cell update` changes; a later attach racing another cell's update that widens an issuer refuses one of them; a configured org another cell places between attach's refusals and its placement refuses the attach, naming it, and writes nothing; prepare refuses a router credential another cell records; a placement call that names another cell with a valid credential of this one places nothing in the other; - a prepared, unattached cell's placement call for an org the directory does not place answers 503, one for an org it places answers the winner even with the old credential still cached after `loom cell credential --finish` or a fingerprint matching neither value, a winner of this cell's name under another deployment id answers 503 and writes no tenancy row, and a process whose configuration differs from its cell's row places nothing; - `loom cell update --config` and `--finish` freshly qualify a SCIM-on target before any generation claim or acceptance write and recheck after local durability and participant turnover; without explicit `--revoke-unprovisioned`, an unqualified live subject refuses with no cutoff write; reverting a SCIM-on pending value to SCIM-off current remains supported; a process configured with another cell's issuer answers 503 to every bearer request, through the router or directly; - during a `loom cell update`, processes on the old and the new configuration both serve, `--finish` releases a narrowed issuer only after no process accepts it, an update that dies after its directory write keeps the widened issuer reserved, and builds N and N+1 with one configuration match the same row; - rotating a SCIM token changes no fingerprint; a process refuses to boot with another cell's SCIM token, an identity provider pointed at the wrong cell's host gets 401 and writes nothing, and a cell rolled back to N still gates on its own row and refuses another cell's SCIM token; a placement flood from one cell's issuer is refused past its quota; - a gateway acting for the personal service account of a person never provisioned is refused, and a cell that starts accepting another cell's issuer takes no placements; - a process matching neither value of its row answers 503 to sign-in, refresh, the OAuth token and device endpoints, the sign-in callback and signup, and its probe route still echoes prepare's nonce; `--revert` requires permanent retirement of every captured participant, including ones already on current; `update --config` refuses while a different `next` is pending, and an update that died before its `loom.cell_self` write resumes forward; prepare refuses while a pre-N process is live; a configuration change while `attaching` goes through `loom cell update` and the resumed attach reserves both values; a process whose configured stores differ from its cell's row answers 503 and stands aside from the workers, so a gated newer build beside an ungated older one leaves the workers running and erasing; `loom cell update` refuses a change to the deployment id, the bucket name or the prefix, adding a bucket included; a gated process in `on` mode runs no worker pass; preparing a clone with the first cell's bucket name and prefix is refused, on its endpoint or any other; a later cell whose prefix holds another deployment's objects is refused at prepare; two concurrent prepares of nested prefixes do not both pass; two cells without a bucket both prepare; prepare refuses a later cell whose process carries another cell's `LOOM_CELL`, and a process whose `first` row names another cell answers 503 and runs no worker; a flood on the main port's id route does not stall attach; and a cell restored onto a new Postgres, ClickHouse or bucket endpoint serves once its configuration names it; a bearer request on the shared host is served before prepare, between prepare and attach, and during attach; - the chart renders no probe listener by default, and with it on renders the probe Service and changes no NetworkPolicy, so with the chart's policy on no rule of its own admits the probe port; prepare names the router's `PROBE_UNREACHABLE` and `PROBE_BUSY` once `--wait` runs out; a flood on the main port leaves the probe listener's rate untouched; - a later cell started from the first cell's environment, with its bucket and prefix, runs gated from its first boot and deletes no original; prepare refuses a later cell while a live process lacks `LOOM_CELL`; - `loom cell limit --closed` makes the cell's placement calls answer 503 while it keeps serving the orgs it holds, `--open` restores them, and `--placements-max` takes effect at the next placement call; - a Postgres restore of an `enforced` cell to before an org's placement, with that org erased after the point, reconciles to exit 0 after `loom cell restore` and then serves the org; - a cell restored from before an org's placement serves it once ready, an erasure leaves the org's placement, and with the directory lost every cell serves the orgs it holds. --- # Claude API memory file tree Source: https://loom.clickhouse.com/docs/architecture/claude-memory-adapter The Claude API memory adapter implements the framework's Python memory-tool bases and TypeScript memory handlers through Loom knowledge documents. The framework SDKs are optional dependencies. Both implementations use the same document URI and store tag, so either language reads files created by the other. A file is `loom-memory:///memories/`. Directories are URI prefixes, with no separate directory rows. Paths are normalized and refused unless they remain under `/memories`. Directory reads use `knowledge.list` with a store tag, a URI prefix and projected URI fields; file reads use `knowledge.get`. Edits use `knowledge.upsert`, and deletion uses bounded `knowledge.bulk_delete` calls. Rename copies each file before deleting its old URI. A failed rename can leave copies, and simultaneous read-modify-write edits keep the later write. ## Source entry points - `sdk/python/loom/integrations/claude_memory.py`: `AsyncLoomMemoryTool` and `LoomMemoryTool`. - `sdk/typescript/src/integrations/claude-memory.ts`: `loomMemoryTool` and `loomMemoryHandlers`. ## Invariants A store groups files; namespace authorization controls access. Private user trees require separate namespaces. The adapter never interprets a store name as an access grant. Actor, source provenance, document revisions, blob cleanup and erasure follow existing knowledge operations. No local persistent state, database or schema is added. Directory operations are not atomic snapshots. --- # ClickHouse Source: https://loom.clickhouse.com/docs/architecture/clickhouse Durable Loom state lives in ClickHouse, except document bytes in an optional S3-compatible bucket and, under the Postgres memory authority, the Postgres tables: live memory, knowledge state and the records beside them. The bucket is used with `LOOM_DOCUMENT_OBJECT_STORE=s3`. ClickHouse holds projections of the live memory and knowledge state Postgres holds; [storage authority](/docs/architecture/storage-authority#the-tables) lists every Postgres table. Loom's ClickHouse databases are `loom` and `loom_telemetry`. The canonical ClickHouse schema is [`schemas/schema.sql`](https://github.com/ClickHouse/loom/blob/main/schemas/schema.sql), dumped from a server with every migration applied; the Postgres schema is the journal in `schemas/pg_migrations/`. The generated [schema reference](/docs/reference/schema) lists every ClickHouse table with its engine, keys, TTL and indexes. This page covers the table families, how Loom uses engines, indexes and views, and how migrations run. ## Goals and non-goals | Goals | Non-goals | | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | One engine for every plane (ClickHouse authority), so a read never joins across stores. | Cross-table transactions. A primary row lands first; derived rows follow. | | Every row names its tenant, writer (`actor`) and content (`content_sha256`). | Transaction-time history on every table. The version mirror covers `loom.memory`. | | Mutable state as append-only versions: a write is an INSERT, a read is deterministic. | In-place updates on the request path. Updates are new versions or batched background folds. | | Nothing that holds memory content expires unless its writer or the operator asked for it. | Default retention on facts, documents, conversations or the graph. | | Every table classified for erasure. | A compliance guarantee. | ## Table families "Written by" names the code or [worker](/docs/reference/workers) that inserts rows. Retention is in [Partitioning and TTL](#partitioning-and-ttl). | Family | Main tables | Written by | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | Memory facts | `memory`, `memory_versions`, `shared`, `working_memory` | `memory.set`, `memory.bulk_set`, lifecycle ops, `working_memory.*`; `memory_versions_mv` fills the history | | Memory embeddings | `memory_embeddings`, `memory_reinforcement`, `memory_term_freq`, `memory_doc_stats` | The same write paths (`build_embedding_row`); `embedding_worker` fills stubs; `usage_fold`; refreshable views for BM25 | | Evidence and chunks | `memory_evidence`, `memory_chunks`, `memory_chunk_sources`, `memory_belief_sources`, `session_summaries`, `derived_facts` | `set_from_messages` projections, consolidation | | Records and taxonomy | `memory_records`, `memory_record_versions`, `memory_record_fields`, `memory_record_conflicts`, `memory_schemas`, `memory_schema_fields`, `categories`, `memory_categories` | `memory.record.*`, `namespace.*`, category assignment | | Write-path state | `memory_extraction_queue`, `memory_projection_failures`, `memory_drops`, `blacklist`, `blacklist_version`, `conflict_allowlist`, `learnings_queue`, `consolidation_runs`, `memory_ask_precedents` | Deferred extraction, fail-open projections, `blacklist.*`, `conflicts.resolve`, `memory.consolidate`, `memory.ask` | | Knowledge | `documents`, `document_blobs` (uploaded originals), `chunks`, `chunk_supersessions`, `chunk_term_freq` | `knowledge.add`; `chunk_term_freq_mv`, `chunk_context_term_freq_mv` | | Conversations | `conversations`, `conversation_threads`, `conversation_embeddings` | `conversation.*`; `conversation_titler` | | Entity graph | `entity_edges`, `entity_degree`, `entity_triples`, `entity_edge_memories`, `entity_edge_rows`, `entity_triple_memories`, `entity_triple_rows`, `entity_vectors`, `entity_summaries`, `entity_canonical_map`, `entity_communities`, `operator_edges` | The `memory.set` after-write projection, `entity_extractor`, `entity_communities`; `entity_degree_mv` | | Code index | `code_files`, `code_chunks`, `code_symbols`, `code_edges`, `code_pr_history` and the other `code_*` tables | `code_ingest`, the `code_scip_*` workers, `code_pr_history`, `code_embed_recovery`, `code_summary`, `code_graph_stats` | | Tracker | `qa_sources`, `qa_item_embeddings`, `qa_link_candidates`, `qa_test_daily`, `qa_rollup_days`, `qa_fail_hours` | `tracker.source.add`, `tracker_embed`, `tracker_links`, `tracker_test_daily` | | Runs, tasks, briefs | `agent_runs`, `agent_turn_usage`, `session_outcomes_by_user`, `procedure_runs`, `tasks`, `task_events`, `task_leases`, `agent_run_claims`, `task_inboxes`, `session_briefs`, `context_blobs` and neighbours | `run.*`, `task.*` / `inbox.*`, `session.brief_*`, `context.offload`, `reflection_distill` | | Namespaces, auth, governance | `namespaces`, `namespace_grants`, `namespace_policies`, `namespace_types`, `namespace_snapshots`, `namespace_calibration_*`, `service_accounts`, `user_state`, `revoked_tokens`, `signing_keys`, `auth_attempts`, `runtime_overrides`, `oauth_state`, `idempotency`, `policy_decisions` and neighbours | `namespace.*`, `grants.*`, sign-up and claim flows, `recalibration`, the idempotency cache | | Telemetry, audit, cost | `events`, `agent_events`, `agent_cost_rollup_daily`, `audit_log`, `audit_checkpoints`, `search_trace_log`, `memory_exposures`, `memory_usage_events`, `memory_usage_totals`, `memory_served_daily`, `code_search_trace`, `worker_status` and neighbours | The events stream, the op ledger, `observability/audit.py`, `audit_verifier`, the supervisor | | Service levels | `loom_telemetry.sli_minute` (its own database: telemetry Loom derives from its tables lives outside `loom`) | `sli_minute_refresh`, once a minute over the `agent_events` request rows with an SLO class | | Erasure | `erasure_requests`, `erasure_reversals` | `erasure.request`, `erasure_recovery`, `memory.restore` | | Provider caches | `embedding_cache`, `llm_response_cache` | The embedder and LLM client wrappers | **Why the SLI rollup has its own database.** `loom` holds what Loom serves; derived operational telemetry stays outside it, so a dashboard or alert user gets `SELECT ON loom_telemetry.*` without any grant on the database that holds memory, and the rollup can be paused (`SYSTEM STOP VIEW` / `SYSTEM START VIEW` on its refresh), truncated and refolded, or given its own retention without touching `loom`. A refold is `SYSTEM STOP VIEW loom_telemetry.sli_minute_refresh`, `TRUNCATE TABLE loom_telemetry.sli_minute` (its sentinel goes with it), then `SYSTEM START VIEW`; stopping first matters, since a refresh that commits after the truncate writes a new sentinel and the refold never starts. It reads the last 31 days of the ledger only, an hour per refresh, so it takes about 12 hours and `loom.sli.rollup_lag_s` shows how far it is; a deployment that wants the longer history backs `loom_telemetry` up too. Do not drop the view: migration 045 is journaled as applied, so nothing recreates it. The cost is one more database: the setup SQL grants the migrating user `CURRENT GRANTS ON loom_telemetry.*`, and preflight names that grant when it is missing. **State outside ClickHouse.** Under the Postgres memory authority, Postgres holds the tables [storage authority](/docs/architecture/storage-authority#the-tables) lists. Uploaded document originals are rows of `document_blobs`, addressed per namespace by SHA-256 (`server/knowledge/store/blobs.py`); with `LOOM_DOCUMENT_OBJECT_STORE=s3` each row is the catalog entry of an object in an S3-compatible bucket, which holds the bytes ([knowledge](/docs/features/knowledge#where-originals-are-stored)). The token signing keys (`signing_keys`), admin runtime overrides of rate limits, latency budgets and live settings (`runtime_overrides`), sign-in attempt counts (`auth_attempts`), graph-walk marks (`graph_projections`: the projections in flight and each namespace's last graph write), each namespace's last write (`namespace_write_keys`) and the supervisor lease are in ClickHouse too, so a new Loom pointed at this ClickHouse (and its Postgres, under the Postgres memory authority), and the document bucket while rows name objects in it, gets every feature back. On the filesystem: the code plane's git mirrors under `var/code_repos`, a cache of the remotes ClickHouse records that a host without them re-clones. The root secret `LOOM_JWT_SECRET`, which seals the signing keys and stored credentials, is in the env. Process caches and file locks are listed in [system overview](/docs/architecture/system-overview#deployment-topology). ## Conventions every table follows - **Identity prefix.** Tenant rows lead the sort key with the identity tuple, and every read filters on it, so the primary index prunes other tenants' granules first. A per-namespace erasure, snapshot or retention override is one key range, not a scan. | Column | Meaning | Default | | ------------ | ------------------------------------- | ------- | | `org` | Tenant boundary; required | — | | `namespace` | Unit of sharing and grants; required | — | | `agent` | Writer agent; required on memory rows | — | | `user_id` | End user the row is about | `'-'` | | `session_id` | Session the row came from | `'-'` | `'-'` means "not applicable" and is stored; `'*'` is a read-time wildcard, never stored. Tables that are not per agent (code index, tasks, namespace config) key on `(org, namespace, …)` or `(org, inbox, …)`. Memory tables add `run_id`. The server stamps `actor` and `source_class` on memory writes ([system overview](/docs/architecture/system-overview#the-identity-tuple)). - **`LowCardinality(String)`** for `org`, `namespace`, `agent`, model names, statuses and event kinds. - **Append, then collapse.** Mutable state is a `ReplacingMergeTree`; writers insert a new row with a higher version and reads use `FINAL`. Mutations stay off the request path. - **Waited inserts.** A write that a later read depends on is sent with `wait_for_async_insert = 1`, so it is written when the insert returns: committed (`async_insert = 0`, the client's session default) or batched ([batched inserts](#batched-inserts)). Fire-and-forget telemetry is sent with `async_insert = 1, wait_for_async_insert = 0`. - **Times are UTC.** `DateTime` columns carry no zone of their own, so the server client and the migration runner pin `session_timezone = 'UTC'` and bind aware params in UTC: a server whose `` is something else reads and writes the same instants. - **Retries never duplicate.** Every insert carries an `insert_deduplication_token` from the batch and a per-batch nonce (`insert_dedup_token`), so a retry after a dropped socket lands the batch once. An async insert is deduplicated by that token only, never by content, so two identical rows in one flush window both land. A caller that passes its own token names the row's identity instead, so two writers of one row land it once: `conversation.save_message` writes a new transcript row this way. ### Batched inserts A committed insert makes one part, so a table written on every request makes parts at the request rate, and merges fall behind ("too many parts"). The rows written on every request or by every process on a short interval are batched inserts, sent with `async_insert = 1, wait_for_async_insert = 1` (`server/core/ch_writes.py`). They fall in two groups: - **Switched by `ch_batched_inserts`** (`batched_insert_settings`): `audit_log`, the `conversations` turns of `conversation.append` and `conversation.compact`'s summary turn, the turn `conversation.save_message` rewrites when deduplication dropped its first write, the `conversation_embeddings` rows (`conversation.append`, `conversation.save_message`, `conversation.compact`; under the width rule below), the `agent_events` flush, `memory_webhook_outbox`, `memory_evidence` and `memory_belief_sources`. `memory_webhook_attempts` stays committed: one worker writes it twice a pass, one insert after the other, so batching would save no parts. - **Waited async inserts either way** (`async_insert_settings`): `auth_attempts`, the policy witness's `agent_events` and `memory_exposures` rows, `memory_projection_failures`, the graph Undo markers, the `namespace_write_marks` flush, the usage-event flush, the carry-acknowledgement publish and withdraw, every waited entity-graph insert (`memory.set`, `memory.bulk_set`; `graph_insert_settings` with `wait=True`), and a follow plan's successor inserts (`entity_triple_memories`, `entity_triple_rows`, `entity_triples`). ClickHouse collects the concurrent inserts into one table in one part per partition and answers each once those parts are written. On return the row is as durable and as visible as a committed insert's, and a caller's next insert lands in a later part, so the order of one caller's writes holds. The buffer is ClickHouse's, so a Loom process that stops loses nothing it acknowledged. A flush that fails as a whole fails every insert waiting on it; a retry of any of them lands once, under its own token. Each insert waits between `ch_batched_insert_wait_min_ms` (writes are sparse) and `ch_batched_insert_wait_max_ms` (under load) for others to join it, and holds its pooled connection for the wait. The insert sends `async_insert_use_adaptive_busy_timeout = 1` so these bounds hold whatever the server profile sets; with it off, every flush waits the full maximum. Under steady load a table gets about 1000 / `ch_batched_insert_wait_max_ms` parts a second per ClickHouse node, insert shape (ClickHouse keeps one buffer per column list and settings) and partition written: more when a buffer fills before the wait ends, at most one per insert when writes are sparse. The insert also sends `async_insert_max_query_number = 10000`, so at high rates the window, not ClickHouse's default of 450 statements, decides the flush. Two windows: the usage-event flusher and shutdown drain and the write-mark flush wait up to `ch_batched_insert_background_wait_max_ms` (200 ms, ClickHouse's own default), so they collect more rows per part. Every other batched or waited async insert waits at most `ch_batched_insert_wait_max_ms` (50 ms), the `agent_events` timer flush included (`flush_now` waits for a flush in flight), and so does a usage-event flush a request makes because the buffer is full. The two windows are two insert shapes, so they fill separate buffers. ClickHouse's own target is about one insert, one part, a second per table, with 1,000 rows or more per insert. These windows stay well short of it; they cut the part rate from one per insert to the rate above. Batching trades latency for parts: each waited insert adds up to its window, and holds its pooled connection meanwhile. A sustained R_request request-path and R_background background batched inserts a second therefore hold at least R_request × `ch_batched_insert_wait_max_ms` / 1000 + R_background × `ch_batched_insert_background_wait_max_ms` / 1000 connections: 100 `conversation.append` a second, two batched inserts each, hold at least 100 × 2 × 50 / 1000 = 10. That is a lower bound: a waiting insert holds its connection for the window and then the flush and part write, which queue up and grow under load. A `memory.set` waits on six or more: the audit row, the outbox row (webhook namespaces), the `entity_edges` and `entity_edge_memories` inserts, the `entity_triples` and `entity_triple_memories` inserts, plus `carry_acks` on a carried write; `memory.set_from_messages` waits on about ten. The entity-graph inserts of both are waited async inserts, so `ch_batched_inserts = false` leaves them holding connections: a process taking mostly memory or bulk writes sizes its pool for them either way, or lowers `ch_batched_insert_wait_max_ms`. One process taking 200 writes a second, two batched inserts each (`bench/write_rate.py --target client`), refused 3,367 of 12,000 writes with 503 `OVERLOADED` at `ch_pool_maxsize = 20`, the formula's bound, and none at 40 or 64; that is one run on one host, so read it as an order of magnitude. Size `ch_pool_maxsize` at three times the bound or more, plus the process's other statements: the default 64 holds three times the bound for about 300 request-path batched inserts a second, with about 20 connections left for other statements. A process above that rate either raises `ch_pool_maxsize` or sets `ch_batched_inserts = false`; lowering `ch_batched_insert_wait_max_ms` also frees connections ([troubleshooting](/docs/operations/troubleshooting)). `ch_batched_inserts` (live, on by default) switches batching off for the first group above: off, those inserts are committed, one part each. The second group waits on the same bounds either way, and fire-and-forget inserts are unchanged. Turn it off (`LOOM_CH_BATCHED_INSERTS=false`) on a process whose write rate exhausts the pool as above and whose pool cannot grow, or on a deployment with little traffic where latency matters more than parts: with writes too sparse to share a part, each insert still waits `ch_batched_insert_wait_min_ms`. ClickHouse keys the async buffer by table, statement shape, settings and user, so one flush can hold rows from several orgs, and one row that fails (a vector of the wrong width, code 190) fails the flush for every caller in it. An embedding row is batched only when its coded width equals `embedding_dim`, and a `conversation_embeddings` row whose shared flush failed with code 190 is sent again, committed; the other batched tables carry no coded vector. These tables stay committed: - **Version rows** of `memory`, `memory_embeddings`, `shared`, `session_summaries` and `entity_summaries`: their fenced `INSERT … SELECT FROM input()` ([rolling upgrades](/docs/architecture/rolling-upgrades)) cannot be buffered. Under the Postgres authority the `memory` and `memory_embeddings` rows of committed writes are batched by Loom instead: each process sends every commit queued since its last flush in one committed insert per table, at most 1000 / `pg_publish_interval_ms` a second, a part for each partition its rows span ([publication](/docs/architecture/storage-authority#publication)). - **`entity_canonical_map`**: it is partitioned by `org`, so a shared flush that spans more than `max_partitions_per_insert_block` orgs would fail every insert waiting on it. - **Rows with a `Quantized`-coded vector** (`entity_vectors`, `memory_chunks`): the codec refuses a vector of another width when the part is written (code 190), so one mis-sized row would fail every other insert in its flush. - **A `conversation_embeddings` row that could be mis-sized** (`embedding_insert_settings`): the row is batched when the column is plain, or when it is coded at the served model's `embedding_dim` and the vector has that width (an empty vector is padded to it). Without a reading of the column, or while the width the column was coded at differs from `embedding_dim` (a model change before its rebuild, or a rebuild this process has not read yet), the row is committed. A batched row whose flush another process's stale-width row failed is sent again, committed. - **A write whose token names the row's identity** (`conversation.save_message`): a replicated table keeps the tokens of committed and of buffered inserts apart, so every writer of one identity sends it the same way. ## Engines and why | Engine | Used for | Why | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | | `ReplacingMergeTree(version)` | Mutable rows: `memory`, `memory_embeddings`, `shared`, `working_memory`, the `code_*` index, tasks, config | An update is an INSERT of a whole row; `FINAL` keeps the newest per key. No locks. | | `ReplacingMergeTree(created_at)` or `(updated_at)` | Rows written once per key: `memory_evidence`, `memory_chunks`, caches, `idempotency`, `namespaces` | The same collapse, versioned by the row's own timestamp. | | `ReplacingMergeTree` with no version | `memory_versions`, `code_symbol_ids`, `code_symbol_names` | `version` or the full identity is in the sort key, so only exact re-inserts collapse. | | `MergeTree` | Append-only logs: `events`, `agent_events`, `audit_log`, `conversations`, `task_events`, `entity_edges`, traces | Rows are facts about a moment. | | `SummingMergeTree` | Counters: `entity_degree`, `memory_usage_totals`, `memory_served_daily`, `code_unit_signal` | A counter is an INSERT of a delta, never a read-modify-write. | | `AggregatingMergeTree` | Non-additive rollups: `memory_term_freq`, `chunk_term_freq`, `code_term_freq`, `agent_cost_rollup_daily`, `memory_exposure_breadth_hourly`, `query_nodes`, `namespace_write_marks`, `subject_last_seen`, `loom_telemetry.sli_minute` | Partial aggregate states (a distinct count cannot be summed), finished with `-Merge`. | | `KeeperMap` | `task_leases`, `agent_run_claims`, `oauth_signin_state` and the migration lock `loom._migration_lock` (also the `workers_supervisor` lease, the claims and the compiler-tier `scip_entry:*` keys) | Linearizable compare-and-swap across processes. | **One `keeper_map_path_prefix` per deployment.** The KeeperMap paths are fixed in the migrations (`/loom/migration_lock`, `/loom/instances`, `/loom/task_leases`, `/loom/agent_run_claims`, `/loom/graph_projections`, `/loom/namespace_write_keys`), and ClickHouse puts them under the server's `keeper_map_path_prefix`. Two deployments whose ClickHouse servers share a Keeper and a prefix share these keys: one workers lease, one migration lock and every claim between them. Give each deployment its own prefix. **Why `ReplacingMergeTree` for mutable state.** `ALTER … UPDATE` rewrites whole parts asynchronously with no read-your-write guarantee. Lightweight `UPDATE` writes patch parts that every later read must apply, and switches off the quantized-codes read ([vector storage](#vector-storage)). A version row is one INSERT, visible to the next `FINAL` read, with its history in the mirror. The price is the write rule below and the `FINAL` cost, which the identity prefix keeps to one tenant's granules. On the memory tables `version` is a wall-clock nanosecond stamp (`server/memory/store/rows.py`, `next_version`), so two replicas' versions compare, at the cost of bounded clock skew. Configuration tables version on `updated_at`, `created_at` or `version`. ## The FINAL write rule An update, tombstone, restore, touch, lock or promotion is an INSERT of a complete row with a higher `version`. **A version row must carry every persisted column.** ClickHouse fills an omitted column with its DDL default, and under `FINAL` that default replaces the real value for every reader. Use the builders in `server/memory/store/rows.py`: | Builder | Table | Behaviour | | ------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `build_memory_version_row(existing, **changes)` | `memory` | Copies every column in `MEMORY_PERSISTED_COLS`, applies the changes, keeps the stored `value` bytes. | | `build_revision_row(existing, new)` | `memory` | A new value over the live row: carries usage, lineage, identity, lock and expiry; resets `REVISION_RESETS`; keeps the attestation. | | `build_first_version_row(new, now=…)` | `memory` | Completes a first write with the DDL defaults (`FIRST_VERSION_DEFAULTS`), so every first version passes the insert funnel's check. | | `insert_memory_versions(rows)` (`inserts.py`) | `memory` | The only `loom.memory` insert: refuses a row missing a persisted column or naming an unknown one, then inserts committed. | | `build_embedding_row(**columns)` | `memory_embeddings` | Full row from `EMBEDDING_PERSISTED_COLS` defaults; an unknown column raises; fills `content_excerpt_lemma` and a fresh `version`. | | `build_session_summary_row`, `build_entity_summary_row` | `session_summaries`, `entity_summaries` | The same pattern. | A new column goes into the builder's column set and every projection that feeds it, in the same change. `MATERIALIZED` columns (`content_excerpt_lc`, `content_excerpt_stem`, `value_preview`, `value_len`) must not appear in an insert. Other versioned tables (`namespaces`, `code_summaries`) read the full row before re-inserting it. Two query rules keep `FINAL` correct: - Filter identity columns in `PREWHERE` or before `FINAL`; keep row-state predicates (`tombstoned_at`, `status`, expiry, validity) in `WHERE` after `FINAL`. A state predicate before the collapse drops the tombstone and brings back the version under it. - Never alias an expression with the name of a column it filters on (`SELECT toString(memory_id) AS memory_id … WHERE memory_id IN …`). The `WHERE` resolves to the alias and silently matches nothing. `tests/unit/test_sql_alias_shadow.py` fails the build on this pattern. ## Content hashes `content_sha256` on `loom.memory` is the SHA-256 of the value's canonical JSON. It is used for: - **Optimistic concurrency.** `memory.set` and `memory.update_by_id` accept `if_match_sha256`; a mismatch answers 409 `PRECONDITION_FAILED`. The hash rides `memory.get`, `memory.get_by_id` and `memory.set` responses. - **Attestation binding.** `verified_sha256` records the bytes someone attested. A revision keeps `verified_by` and `verified_at`, but the hashes no longer match, so readers derive "stale" from the pair. - **Audit.** Every write that creates or changes memory leaves one hash-only `audit_log` row (key, id, hash, actor, source class, verdict; never the value). A code chunk's id is a UUIDv5 over its path, scope and content hash, so an unchanged chunk re-ingests to the same row. ## Sort keys After the identity prefix, a sort key serves the table's dominant read: | Table | `ORDER BY` | Read it serves | | ------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `memory` | `(org, namespace, agent, user_id, session_id, memory_key)` | Point reads by key; the collapse unit is one key per identity. | | `memory_embeddings` | `(org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key)` | Vector legs for one identity and one model; two models' vectors are separate rows. | | `memory_versions` | `(org, namespace, agent, user_id, session_id, memory_key, version)` | History of one key; `version` in the key keeps every row. | | `code_chunks` | `(org, namespace, embedding_model, path, chunk_id)` | All chunks of a path, for re-ingest diffs and file reads. | | `code_edges` | `(org, namespace, tier, to_symbol_id, edge_kind, from_symbol_id, path, line)` | "Who calls X" is a key range. Projections `by_from` and `by_path` serve callees and per-file reads. | | `code_symbols` | `(org, namespace, tier, qualified_name, symbol_id)` | Definition by qualified name; `code_symbol_names_mv` and `code_symbol_ids_mv` re-key it. | | `entity_edges` | `(org, namespace, entity_a, entity_b)` | Neighbours of an entity. | | `task_events` | `(org, inbox, seq)` | An inbox's events in order. | Sort and partition keys are `CREATE`-only. A migration that changes one declares `-- loom: rebuild-if-empty ` above the full `CREATE TABLE`. The runner swaps an empty table for its twin and refuses a table with rows, naming `scripts/ops/table_rebuild.py` (twin, copy, `EXCHANGE TABLES`) (`server/core/schema/table_rebuild.py`). ## Partitioning and TTL Most time-series tables are `PARTITION BY toYYYYMM(
_DAYS`, and tiering with `LOOM_TIERING_
_WARM_DAYS` plus `LOOM_TIERING_WARM_VOLUME_NAME`. Per-namespace `retention_days` or `warm_days` overrides become a `multiIf` in the same TTL expression (`server/storage/retention_overrides.py`). Audit deletion uses only its dedicated `LOOM_RETENTION_AUDIT_LOG_DAYS`; namespace `warm_days` can still tier audit rows. The worker leader applies them at boot and `retention_reconcile` keeps them in step, skipping unchanged tables because each `MODIFY TTL` is a mutation. When the last window on a table is cleared, the same pass issues `ALTER TABLE … REMOVE TTL`; none of these tables has a schema TTL. Every window defaults to 0 (off). ### Merges and skip indexes A part count that keeps rising almost always means merges are failing. A skip index a merge cannot build fails every merge of that table until inserts get `TOO_MANY_PARTS`. Loom keeps such indexes out of merges with `exclude_materialize_skip_indexes_on_merge` (the text indexes `content_text` and `context_text` on `chunks`): inserted parts still build the index, merged parts do without it. The `clickhouse_parts` check of `ops.health` (`_clickhouse_parts_check`) reads `system.part_log` for failed `MergeParts` events in the last quarter hour and reports the error code and this repair; the exception's text stays in `system.part_log`. For the same reason memory-content tables carry no rows TTL. The runbook is in [troubleshooting](/docs/operations/troubleshooting). `memory_embeddings` also names `embedding_hnsw_idx` in that setting, an index no migration declares. The setting does nothing unless an operator adds a vector index of that name by hand, and then keeps merges from rebuilding its graph, so no migration resets it. ## The write → derive loop A write inserts its primary rows and returns. Everything else is derived afterwards, by one of three mechanisms: 1. **Insert-time materialized views** run inside the source INSERT: `memory_versions_mv` copies every `memory` row into `memory_versions`, and `memory_usage_totals_mv` and `entity_degree_mv` fold their source rows into totals. `memory_served_daily` takes no view: an agent read inserts its counts there directly, apart from `memory_usage_events`, whose totals the usage fold turns into ranking, so a served read never moves the reinforcement signal. 2. **Refreshable materialized views** (`REFRESH EVERY 1 MINUTE APPEND`) append rows newer than their high-water mark: BM25 statistics, the daily cost rollup, hourly exposure breadth, last seen per subject, the request SLIs per minute. The SLI rollup's mark is `agent_events.ingested_at`, when ClickHouse took the row, so a delayed flush is not skipped. 3. **Workers** poll for rows that need work and write new versions: stub embeddings (`embedding_worker`, `code_embed_recovery`), entities (`entity_extractor`), usage folds (`usage_fold`), deferred extraction (`extraction_queue`, `observe_extract`), failed projections (`projection_repair`), orphaned vectors (`orphan_vector_reconcile`), expiry (`memory_expiry_sweep`) and TTLs (`retention_reconcile`). There is no queue service. A queue is a table whose rows carry their state: `memory_extraction_queue` rows move `pending → running → done | failed` (or `held` until a model-call hold ends) as versions; an embedding row with `embedding_dim = 0` is a stub waiting for a vector; a `memory_projection_failures` row is a projection to replay. Read paths filter unfinished rows out. ```mermaid flowchart LR W["memory.set / bulk_set"] --> M[(memory)] W --> E[(memory_embeddings)] M -- "memory_versions_mv" --> MV[(memory_versions)] E -- "refresh 1 min" --> BM[(memory_term_freq
memory_doc_stats)] W --> AU[(audit_log)] E -. "stub dim=0" .-> EW[embedding_worker] EW --> E W -. "after-write task" .-> G[(entity_edges
entity_triples)] G -- "entity_degree_mv" --> DEG[(entity_degree)] U[(memory_usage_events)] -- "memory_usage_totals_mv" --> UT[(memory_usage_totals)] UT --> UF[usage_fold] UF --> R[(memory_reinforcement)] UF --> M ``` **Why derive.** A `memory.set` that awaited its graph projection, BM25 update and audit fan-out would pay each round trip and fail when any failed. The response path keeps only what the caller's next read needs: the `memory` row, its `memory_embeddings` row, the same-key supersession and the audit receipt. Projections are fail-open (`memory/app/after_write.py`), and a read of the same namespace in the same process waits for the graph projection (`after_write.settle`). A derived table lags its source by seconds; the BM25 legs merge that lag themselves. An embedding row may land under the refresh watermark when its version is more than 5 s old once it is in (half the views' 10 s lag). A long embed or judge, or slow inserts, do that. Its own write folds such a row into the BM25 tables after the response (`after_write.index_late_rows`), so a slow write does not also wait on two more inserts. ## The memory_versions mirror Merges discard superseded `memory` rows, so the RMT table is not a history. `memory_versions_mv` copies every inserted `memory` row into `memory_versions`, which keeps each version. `memory.history`, `memory.redact`, `namespace.rollback` and the usage fold read it; the erasure saga deletes from it. A new `memory` column goes into `memory_versions` and the view's `SELECT` in the same migration; `tests/unit/test_memory_versions_schema.py` compares the column lists. ## Materialized views | View | Kind | From → to | | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | ----------------------------------------------------- | | `memory_versions_mv` | insert-time | `memory` → `memory_versions` | | `memory_record_versions_mv` | insert-time | `memory_records` → `memory_record_versions` | | `memory_usage_totals_mv` | insert-time | `memory_usage_events` → `memory_usage_totals` | | `entity_degree_mv` | insert-time | `entity_edges` → `entity_degree` | | `session_brief_revisions_mv` | insert-time | `session_briefs` → `session_brief_revisions` | | `chunk_term_freq_mv`, `chunk_context_term_freq_mv`, `code_term_freq_mv`, `code_doc_stats_mv`, `code_symbol_ids_mv`, `code_symbol_names_mv` | insert-time | Chunk and code-index statistics and lookups | | `memory_term_freq_refresh`, `memory_doc_stats_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `memory_embeddings` → BM25 statistics | | `agent_cost_rollup_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `agent_events` → `agent_cost_rollup_daily` | | `memory_exposure_breadth_hourly_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `memory_exposures` → `memory_exposure_breadth_hourly` | | `subject_last_seen_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `agent_events` → `subject_last_seen` | | `loom_telemetry.sli_minute_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `agent_events` → `loom_telemetry.sli_minute` | **Insert-time or refreshable.** An insert-time view writes one part per source insert. That suits a low-rate source or a target read back in the same request (`memory_versions`). A high-rate source uses a refreshable view that appends one part a minute. The BM25 rollups keep their mark in a sentinel row (`org = ''`, `namespace = ''`, `term = ''`) carrying `max(version)` and read only rows at least ten seconds old. They lag a write by about a minute, and `memory.search` merges the newer source rows (`LOOM_MEMORY_SEARCH_BM25_LIVE_TAIL`, on), so BM25 scores are exact. **The events stream.** `loom.events` carries budget violations only: `server/observability/events_stream.py` queues them and writes one committed insert per flush. Every other telemetry writer (audit rows, exposures, search traces, query nodes, code-search outcomes) inserts into its own table directly; no view fans `events` out. The op ledger (`agent_events`) is queued the same way, and each flush is a batched insert (`server/observability/events.py`), so the flushes of every process share parts. A failed flush never fails a request; a crash loses the queue. ## Vector storage - The vector columns of `CODED_TABLES` are `Array(BFloat16)`, coded with `Quantized` or plain depending on the install (the Quantized codes bullet below says which). Loom's migrations code no other vector column; a table named in `LOOM_CODE_VECTOR_TABLES` keeps the layout and width it was created with. `entity_vectors.entity_embedding` keeps `LZ4` because its vectors repeat. Coded, it keeps the `LZ4` after `Quantized` only where `allow_suspicious_codecs` can be on; where it is held at 0, as on a ClickHouse Cloud service by default, the column is stored without it. How to add the chain back is in [recommended settings](/docs/operations/deployment#recommended-clickhouse-settings). Query vectors bind as `Array(Float32)`. A memory carries up to two vectors (value and key), so at 3072 dimensions up to 12 KiB of vectors. - **No table has a vector-similarity (HNSW) index.** Search is a `cosineDistance` scan over the rows the identity predicates leave: exact, or codes first and rescored where codes-first reads (below) apply. The bytes a read scans therefore grow with namespace size, not corpus size. [Why there is no vector index](#why-there-is-no-vector-index) has the measurements. - **Quantized codes.** On ClickHouse 26.8+, a fresh install creates the vector columns of `CODED_TABLES` (`server/core/schema/vector_codec_ddl.py`) with `CODEC(Quantized('rabitq', , 0))` where `enable_quantized_codec` is on, or Loom's ClickHouse user may turn it on. The runner rewrites the `CREATE` at apply time ([Gated ClickHouse settings](#gated-clickhouse-settings)). On a server that holds `enable_quantized_codec` at 0, a fresh install creates the plain layout, and `scripts/ops/vector_codec_rebuild.py` applies the codec once the setting is on. ClickHouse Cloud holds the setting read-only at its default 0 until the operator enables it for the service with a settings-profile override; it then reads 1, still read-only, and coded tables work. An existing table moves with the same tool. - **Codes-first reads.** When a column is coded and its table has no patch parts, reads send `vector_search_use_quantized_codes = 1` (`LOOM_VECTOR_SEARCH_QUANTIZED_CODES`): a pass over the codes keeps `LIMIT × LOOM_VECTOR_SEARCH_QUANTIZED_FETCH_MULTIPLIER` candidates and rescores them at full precision. Coding and patch parts are re-probed every `LOOM_VECTOR_CODES_STATE_PROBE_SECONDS`; a failed probe reads as "not patch-free". A replica that rejects the setting has it dropped and the read retried. The memory fact leg has its own switch, `LOOM_MEMORY_SEARCH_FACT_CODES_FIRST`. Its `auto` follows its own patch-parts probe (every `LOOM_MEMORY_EMBEDDINGS_PATCH_PARTS_PROBE_SECONDS`). Both `on` and `auto` read as off while `LOOM_VECTOR_SEARCH_QUANTIZED_CODES` is false or the replica does not know the setting. Its over-fetch is `LOOM_MEMORY_SEARCH_FACT_CODES_FETCH_MULTIPLIER`. - **Fixed-length placeholders.** Rows awaiting an embedding store zero vectors with `embedding_dim = 0` (`server/core/vectors/placeholders.py`). Every vector leg filters `embedding_dim > 0`. - **No in-place updates on vector tables.** Write, fold, reject and tombstone paths write new versions; reinforcement lives in `memory_reinforcement`. A lightweight `UPDATE` on `memory_embeddings` would leave a patch part, and the patch-parts probe keeps codes-first reads off for the whole table until it merges. - **One model per row.** `embedding_model` is in the sort key, so a search compares only its own model's vectors. `loom reembed` regenerates vectors after a model change (`--in-database` uses `aiEmbed` on 26.7+). **Query shape.** ClickHouse pushes a top-k into the codes-first scan only for the plan `Limit → Sorting → Expression → [Filter] → ReadFromMergeTree` with one ascending sort key that is a bare distance call. `ORDER BY 1 - cosineDistance(…) DESC`, a second sort key, `LIMIT n BY`, a window function or a `JOIN` fall back to a full scan silently. Vector queries order by a bare distance alias and compute similarity in Python. The chunk leg reads candidates with no `FINAL` or `JOIN`, then looks them up by primary key under `FINAL`. `tests/unit/test_vector_search_query_shape.py` guards the shape. ### Why there is no vector index A `vector_similarity` index is one HNSW graph per part. It does not fit Loom's reads, for four reasons. Unless a paragraph says otherwise, the figures come from ClickHouse 26.9 with 1M synthetic 1536-dimension vectors in tables shaped like `memory_embeddings` (its sort key, `ReplacingMergeTree`, `index_granularity = 256`, one merged part per partition), an index built as `vector_similarity('hnsw', 'cosineDistance', 1536, 'bf16', 16, 128)`, and 30 queries per filter; the command is in `bench/vector_index_vs_exact.py`. **A tenant read never uses it.** ClickHouse searches the graph only when the primary-key condition keeps every granule of the part. Every Loom vector read filters on `(org, namespace)`, the prefix of every vector table's sort key. In every vector table but `code_chunks` a part holds many tenants (`memory_embeddings` is partitioned by month), so the read takes the tenant's granules and sorts them exactly: no index search runs (`ProfileEvents['USearchSearchCount'] = 0`) and the read costs what the plain table costs. MiB read and p50 per query, every read under `FINAL`: | Tenant share | Rows | Exact scan | With the index | Codes-first, LIMIT 60 | | ------------ | ---- | ----------------- | ----------------- | --------------------- | | 50% | 500k | 1,478 MiB, 141 ms | 1,478 MiB, 140 ms | 134 MiB, 55 ms | | 10% | 100k | 295 MiB, 491 ms | 295 MiB, 476 ms | 49 MiB, 44 ms | | 1% | 10k | 30 MiB, 57 ms | 30 MiB, 55 ms | 21 MiB, 18 ms | | 0.1% | 1k | 3.2 MiB, 12 ms | 3.2 MiB, 13 ms | 3.4 MiB, 9 ms | Compare the bytes: the 10% tenant's read was slower than the 50% tenant's in both runs, so the milliseconds do not rank by size. The `vector_search_filter_strategy`, `vector_search_index_fetch_multiplier` and `hnsw_candidate_list_size_for_search` settings change nothing here: the index is never opened. The codes-first column reads the fact leg's 60 rows at codes multiplier 1 (the leg's default is 3); recall@10 of those 60 rows against the exact top 10 was 0.95-1.00. **Where it does run, a selective filter loses recall.** With a predicate outside the sort key the graph runs first and the predicate drops its candidates afterwards. recall@10 against the exact answer, by `vector_search_index_fetch_multiplier`: | Rows the filter admits | x1 | x10 | x100 | | ---------------------- | ----- | ----- | ----- | | all | 0.783 | 0.783 | 0.783 | | 10% | 0.200 | 0.820 | 0.933 | | 1% | 0.080 | 0.163 | 0.723 | The unfiltered row is this graph's own recall on this data at `hnsw_candidate_list_size_for_search = 256` (0.847 at 1024). A partition per tenant makes the index run for tenant reads: the 50% tenant's read under `FINAL` then takes 76 ms instead of 141 ms, at recall@10 0.757, and the 10% and 1% tenants get 0.747 and 0.843. `code_chunks` is partitioned by `(org, namespace)`, so an index there would run and read this way; the recall loss and the stale versions below are what rule it out. For `memory_embeddings`, a partition per namespace is not a layout a table with thousands of namespaces can hold. **Under `FINAL` it serves superseded versions.** The graph returns rows of every version before `FINAL` collapses them, so a key's newest version or tombstone loses to an older row. `bench/ann_final_staleness.py` (30k keys, 3 versions each, 18 parts, 128 dimensions, 5 queries) on 26.9: recall@10 0.38 with 6.2 of 10 rows stale, against 1.00 and none for the `prefilter` arm, which leaves the index unused. Its `reread` arm, which takes candidate keys from the graph and reads them again under `FINAL` with skip indexes off, removes the stale rows (recall 0.90-0.98) and takes twice as long as `prefilter` (37-39 ms against 20 ms), so the index then costs more than the scan it replaces. **It doubles storage and slows writes.** The graph took 2.27 GiB beside 2.25 GiB of table data. Copying the 1M rows into the indexed table took 135-166 s over two runs, against 17-51 s into a coded table without an index. With `exclude_materialize_skip_indexes_on_merge` naming the index, a merged part carries no graph at all; without it every merge rebuilds the graph. A graph also has to stay in the vector similarity index cache, or a read loads it from disk. On this server (`vector_similarity_index_cache_size` 5 GiB, `SLRU`), once the partitioned table's graphs had been loaded, all 30 reads of the single-part graph missed the cache (`VectorSimilarityIndexCacheMisses`), reloaded it and took 4.8 s instead of 9 ms. The codes-first read is what cuts a large namespace's scan instead: at 100k rows and more it reads 6-11x fewer bytes than the exact scan, inside the tenant's granules and under `FINAL`. An index becomes worth revisiting when ClickHouse searches it within the primary-key ranges a read selects and resolves versions under `FINAL`. ## Text indexes and lexical search | Table | Index | Indexed expression | Tokenizer | | ------------- | ---------------------------- | ------------------ | ----------------- | | `chunks` | `content_text` | `content_lc` | `splitByNonAlpha` | | `chunks` | `context_text` | `context_lc` | `splitByNonAlpha` | | `code_chunks` | `idx_code_chunks_content_ng` | `lower(content)` | `ngrams(3)` | | `code_chunks` | `idx_code_chunks_lexemes` | `lexemes` | `splitByNonAlpha` | All four use `GRANULARITY 100000000`: one granule per part, a per-part posting list. `memory_embeddings` and `memory_evidence` carry no text index: `hasAnyTokens` and `hasAllTokens` run on their lowercase columns after the key prefix narrows the read. `memory_embeddings` also has `content_excerpt_stem` (`MATERIALIZED`, `stem(…, 'en')`) and `content_excerpt_lemma`, filled by `build_embedding_row` with the query side's lemmatizer, so no server-side dictionary is needed. The lexical legs match lowercase, stem and lemma forms; `bm25_hybrid` computes Okapi BM25 in SQL from the statistics tables. The `code_chunks` 3-gram index answers substring grep: it narrows granules and the exact `position()` or `match()` predicate decides. The query must carry a `lower(content) LIKE '%…%'` guard; a literal under three characters cannot use it. Skip indexes prune the rest: `bloom_filter` on `tags`, `entities`, `files`, `concepts`, `memory_id`, `content_sha256`; `ngrambf_v1` on `memory_key` and code symbol names; `minmax` on `valid_to`, `invalid_at`, `version`; `set` on `status` and `memory_type`. ## Deletes and mutations Loom deletes memory by writing a tombstone version (`tombstoned_at` set, every other column carried). It is visible to the next `FINAL` read, keeps prior versions in `memory_versions`. Only automatic retirement without permanent refusal has a restore window. Physical removal is for erasure with `purge=true`, stale vector caches, runner state, and the supersession rows `knowledge.restore` removes. - **`knowledge.restore`** runs a lightweight `DELETE FROM loom.chunk_supersessions` for the rows one delete wrote: the document's `source_uri`, the ingestions of its revision and the `superseded_at` the delete stamped on its row (`server/knowledge/store/restore.py`). The chunks then read as live through `LIVE_CHUNK_SQL`, on builds N-1 and N alike. No materialized view writes the table, and a row another retirement wrote stays. When it takes itself back under a purge that may cover the document, it also deletes the one `loom.documents` row it wrote (by its `version`), so the purge leaves no copy of the content. - **Counter folds** on `loom.memory` (the usage fold's `evidence_count` / `recall_count`) use batched lightweight `UPDATE`: one statement per chunk of targets, with per-row values as parallel arrays through `transform()` (`server/memory/workers/usage_fold.py`). On ClickHouse Cloud each statement is a patch part and a Keeper entry, so cost is per statement. A pass is skipped while the table has too many unfinished mutations. Only "lightweight update unsupported" errors fall back to `ALTER TABLE … UPDATE`; a transient error is retried next pass. Every batch retains its boundary second because `bumped_at` has second resolution. A cursor ordered by `bumped_at`, SHA-256 digests of `org` and `namespace`, and `memory_id` pages through ties. Fixed-width digests fit supported identity sizes within the cursor limit. `worker_status` stores the cursor when a pass stops at its time budget. A completed scan stores an epoch cursor to reset the scan: an empty cursor tells the supervisor to keep its previous value. A full-version insert can carry counters read before a fold and replace its result. Every pass therefore compares the absolute totals and last-recall time with the live rows, even when the usage high-water mark is unchanged, and rewinds to the earliest discrepancy. Comparisons use the same UInt32 saturation as the counter writes, so an unattainable total cannot keep rewinding the scan. This adds an aggregate join per nonempty pass. Repair is eventual once the competing writes are visible; a read followed by an insert is not atomic. Absolute targets and `greatest` make counter repair idempotent across replicas. The usage events remain authoritative; the counters on `memory` are a derived projection. - **Erasure purges** remove rows. On `erasure/store/mutations.py::LIGHTWEIGHT_PURGE_TABLES` (vector, chunk, summary and evidence tables) a purge uses lightweight `DELETE FROM`, which writes only the row mask: rows vanish from every read at once and bytes leave at the next merge. Narrow tables keep `ALTER TABLE … DELETE`. The saga polls each mutation by an embedded tag, and a residue census checks the result. - **A refused knowledge write's own chunks**: under the Postgres authority, a write refused because an erasure removed the document it was built from deletes the chunk rows it inserted (lightweight `DELETE FROM loom.chunks` by source and version, `chunks.delete_versions`), so its text and author do not outlive the erasure. - **Remaining `ALTER … UPDATE/DELETE` call sites** are listed in `tests/unit/test_clickhouse_mutation_inventory.py`, which fails on a new one until it is classified there. - **Private definition redaction** scrubs all versions of a matching learnings candidate in place, including status copies. A replacement version would leave the redacted text stored in older versions. This runs with the source's historical redaction, under the candidate review lease. An invalidated model attempt instead removes only its own candidate versions through a lightweight `DELETE FROM`, bounded by the claim version, so it cannot remove a later review decision. - **Orphaned vector retirement** deletes cache versions below the caller's cutoff by the complete vector sort key, across all creation partitions. A missing authoritative source or matching erasure policy cannot be represented by a newly inserted marker: even an empty marker would recreate residue after a purge. Admission fences stay held until the synchronous lightweight delete is acknowledged; equal and newer versions stay. - **Shared canonical retirement** uses the same bounded lightweight deletion when its shared head is absent, source identities are unproven or erasure policy matches. The cutoff preserves a later promotion and avoids writing a tombstone after a purge. - **Refused extraction jobs** end through a control-only `ALTER TABLE … UPDATE` on the exact identity, queue id, source version and payload hash. It writes a fixed reason and terminal status without copying transcript bytes or creating a row. Unrelated jobs in the same claim batch can still run. - **Extraction retries** (`memory.extraction_retry_mine`) update failed queue rows in place, asynchronously. The update targets the exact identity and version observed, with the caller's namespace, principal and read scope. Copying the transcript into a new version could restore it after a concurrent erasure; this mutation changes no payload or version and cannot create a row. The request returns when the mutation is accepted, and a retry asked again while its mutation is unfinished in `system.mutations` submits none. - **Provider lock recovery** takes over one `loom._migration_lock` Keeper key with a conditional `UPDATE` under strict mode, once the key expired and the previous owner's participant counts as stopped (retired, or no heartbeat for its `stale_after_s` and no query tagged with its id in `system.processes`). `loom provider-lock clear` deletes the key the same way. Both are Keeper operations, not MergeTree content mutations; an elapsed TTL alone never permits provider-lock takeover. - **Run id claims** (`loom.agent_run_claims`, KeeperMap) live only inside one `run.begin`: claim, read the run row, write it, drop the claim. A later begin that takes the free claim reads the row and goes to a fresh id. `run.complete` and the erasure saga's `agent_runs.delete` step also drop claims, for a key a process that died mid-begin left behind. All are Keeper key drops, not MergeTree mutations. - **Sign-in state** (`loom.oauth_signin_state`, KeeperMap) holds each code, device grant, finished IdP round trip and session's current refresh token. A value changes only by a strict-mode compare-and-set: an `INSERT` for a new key, otherwise an `ALTER … UPDATE` conditioned on the value the writer read. Keys carry their credential's expiry, and a sweep every five minutes drops the expired ones with one `ALTER … DELETE`; all are Keeper key operations, not MergeTree mutations. - **Grant change and account claims** are leases (`server.core.leases`): keys of `loom._migration_lock`. A grant change holds the grant's claim from its read to its write, so a concurrent change of the same grant waits for it. Its reads are sequentially consistent, and it is cut off after 20 s (each statement after 10 s), well before its 60 s claim may be taken over. A repository maintainer's change across branches (a revoke's fan-out, a sync's mirrors) first holds one claim per (repository, subject), `repo:`, then its branches' claims in namespace order, and writes the branches in one insert inside that bound. A change that may remove an admin first holds the namespace's admins claim (the key with no subject) and counts the admins under it. A change that rewrites an account's directory row (`loom.namespaces`), from any plane, holds that account's claim the same way, before any admins claim. `task_claims`, `oauth_claims` and `grant_claims` exist in the schema and no code path writes or reads them. - **Graph projections and graph writes** (`loom.graph_projections`, KeeperMap where the server has a Keeper): a projection holds one of 32 slot keys of its namespace and its end drops it (a begin whose insert failed uncertainly leaves its slot to go stale); a begin that finds a slot older than 15 s (its process died) drops that one first; a graph write raises the namespace's write key with a version-checked UPDATE, one in flight per namespace per process. All are Keeper key operations. On a server without a Keeper the table is a MergeTree and every begin, end and write is a row under a 1-day TTL. - **Dead lease and slot keys.** The leader's hourly `keeper_sweep` worker deletes the `loom._migration_lock` keys (leases and claims) an hour past their expiry and the `loom.graph_projections` slot keys a day old: keys whose holder died before its own delete. One strict-mode Keeper delete per table; a key written meanwhile fails it and the next sweep retries. - **Cell probe nonce.** `loom cell prepare` writes a nonce under the `cell-probe` key of `loom._migration_lock` for the router to read back through the cell's probe listener, then drops that key while it still holds that nonce, as a lease is released: one strict-mode Keeper delete. - **Namespace write keys** (`loom.namespace_write_keys`, KeeperMap, only where the server has a Keeper): a write to a memory plane overwrites its namespace's key in the request tail. One Keeper write, no part, no mutation. **Classification for erasure.** `server/erasure/store/census.py` puts every table in `schemas/schema.sql` in the lists below, and `tests/unit/test_every_table_is_classified.py` fails on a table in none: | List | Holds | | ------------------------ | ---------------------------------------------------------------------------------------------------------- | | `_CENSUS` | One `Substrate(...)` per table that can hold content in scope: live predicate, user predicate, owner step. | | `STEP_ONLY_TABLES` | Tables a saga step clears but the census does not count, with the reason. | | `CANONICAL_OWNER_TABLES` | Authentication registries with an explicit canonical sign-in owner erasure lifecycle. | | `NO_MEMORY_CONTENT` | Tables with no memory content, each with its documented reason. | The owner lifecycle for `loom.connected_accounts` physically erases provider identity and credential history, including sealed personal data. Its canonical sign-in subject is independent of namespace and memory `user_id` erasure scopes. The saga is described in [memory architecture](/docs/architecture/memory-architecture#erasure-saga). ## Query attribution Every statement carries a `log_comment` setting naming its origin, so `system.query_log` groups by operation and joins Loom's ledger. It is a setting, not query text, so plans and query hashes are unaffected. | Origin | `log_comment` | | ------------------- | ----------------------------------------------------- | | HTTP or MCP request | ` ` (for example `memory.search 5f…`) | | Worker pass | `worker.` | | `loom` command | `cli.[.]` (not `loom serve`) | | Anything else | `untagged:.` of the caller | Request statements also send `query_id = "::"`. `n` counts the request's statements and the nonce is drawn once per request, so two requests that carry the same caller id never send the same `query_id`. A carried insert prefixes it with `loom-carry//`. `LOOM_CH_LOG_COMMENT_STATEMENT_DIGEST=true` appends a statement-shape hash and the first 200 characters; a statement that carries a secret, or one run as the analyst, gets the hash alone. A new background loop calls `server.core.ch.set_query_tag(...)`; work scheduled from a request keeps the request's tag. ```sql -- ClickHouse work per operation over the last hour SELECT splitByChar(' ', log_comment)[1] AS op, count() AS queries, sum(read_bytes) AS read_bytes, sum(query_duration_ms) AS ms FROM system.query_log WHERE event_time > now() - INTERVAL 1 HOUR AND type = 'QueryFinish' AND current_database = 'loom' GROUP BY op ORDER BY read_bytes DESC; ``` On ClickHouse Cloud, use `clusterAllReplicas('default', system.query_log)`. ## Statement classes, deadlines and traffic classes Each statement's class comes from its leading keyword (`server/core/ch.py`, `statement_class`): | Class | Statements | Deadline setting | Default | | ------- | ----------------------------------------------------------------------------- | ------------------------- | ------- | | `read` | `SELECT`, `WITH` and anything not listed below | `LOOM_CH_TIMEOUT_READ_S` | 30 s | | `write` | `INSERT`, lightweight `UPDATE` | `LOOM_CH_TIMEOUT_WRITE_S` | 60 s | | `ddl` | `ALTER`, `CREATE`, `DROP`, `OPTIMIZE`, `SYSTEM`, `EXCHANGE`, `DELETE FROM`, … | `LOOM_CH_TIMEOUT_DDL_S` | 300 s | The deadline is applied as `max_execution_time` and as a client-side timeout, so the pool slot is released even when the server never answers. `statement_timeout(seconds)` raises it for one block. A statement that hit its deadline is not re-run; only transient network errors get the one reconnect-retry. A statement that gets no pool slot within `LOOM_CH_POOL_WAIT_MS` fails with 503 `OVERLOADED` (`LOOM_CH_POOL_MAXSIZE` slots per process). Reads also carry per-traffic-class settings from `LOOM_CH_SETTINGS_BY_TRAFFIC_CLASS` (`production`, `interactive`, `bench`, `background`): `priority`, `max_threads`, and for background work a filesystem-cache bypass. They apply only to `SELECT`/`WITH` and never change the rows returned. **Schema guard.** A server built from a branch can be migrations ahead of the database. A statement naming a table a pending migration would create is refused in the client with `SchemaPendingError`; the ledger row says which table the request went without. The pending set is re-read at most once a minute. ## Read-your-writes On a single self-hosted server a committed or batched insert is visible to the next read. On ClickHouse Cloud replicas may lag and the HTTP pool spreads requests over replicas, so Loom adds `select_sequential_consistency = 1` where it matters: - **Point reads after the caller's own write** (working memory, a document, a memory by key, a profile section) run inside `own_write_reads()`. - **Searches of a namespace written recently** (within `LOOM_CH_READ_YOUR_WRITES_WINDOW_S`, 20 s) run under `sequential_reads()`; an empty pool re-runs the search that way (`LOOM_CH_READ_YOUR_WRITES`). A write by this process is known in-process; one by another process through `loom.namespace_write_keys`, one Keeper key per namespace that a write sets, stamped by the server's clock, before it answers. The scope is a context variable, so spawned tasks inherit it. **What sequential consistency covers.** On SharedMergeTree (ClickHouse Cloud) a sequentially consistent read sees every insert acknowledged before it began. On a self-hosted ReplicatedMergeTree it waits only for inserts written with `insert_quorum` and `insert_quorum_parallel = 0`, which ClickHouse refuses for async inserts (and which serializes every insert into a table), so a read on one replica can still miss a row another replica acknowledged a moment ago. Guarantees built on it include the sign-in attempt recounts, the single signing-key retire, `task.create`'s idempotency key (a retry finds the task the first call stored), the single `code.coverage.ready` event, the document bucket's walk and user erasure, a knowledge delete's read after a restore and, under the Postgres authority, three more: the read that drops a knowledge head ClickHouse no longer holds, the erasure's read of the document ids it refuses afterwards ([storage authority](/docs/architecture/storage-authority#knowledge-documents)) and the originals sweep's ClickHouse read after its read of the unpublished commits ([knowledge](/docs/features/knowledge#replacing-editing-and-deleting)). They hold exactly on Cloud and a single server. A self-hosted replicated cluster must send every Loom process to one replica; `loom doctor`'s `replica_consistency` line warns while `loom.auth_attempts`, `loom.signing_keys`, `loom.tasks`, `loom.task_events`, `loom.document_blobs`, `loom.blob_uploads` or `loom.documents` has more than one. **Keeper reads.** The Keeper keys that carry state between replicas (the namespace write keys, graph projections and writes, claims and leases) are read through each replica's own Keeper session. A Keeper node answers reads from its local state, which can trail the leader for a moment, so a key one replica just wrote can be missing from another's read. Writes, and the version checks of compare-and-swap, always go through the leader. For read-after-write across replicas on a self-hosted Keeper ensemble, set `true` in `keeper_server`: every read then goes through the leader too, at a round trip each. A single Keeper node, as in `deploy/clickhouse-config/keeper.xml`, needs nothing. ## Migrations - Files are `schemas/migrations/NNN_.sql`, applied in numeric order by `server/core/schema/migrate.py`. **A merged migration is never edited or deleted**: the ledger checksums every file. - The ledger is `loom._migrations` (`filename`, SHA-256 `checksum`, `applied_at`, `applied_by`). A recorded file is skipped; a changed hash is reported as drift, and `--strict` makes drift or a ledger row with no file exit 1. - A file headed `-- loom: baseline covers N` replaces every migration numbered N or lower that the repository no longer carries. A fresh database applies it; a database that already holds a superseded file records it without running. - The server applies pending migrations at boot (`LOOM_BOOT_MIGRATE`). Set it to `false` for a branch server against a shared database. Every process serialises on the KeeperMap lock `loom._migration_lock`; a server without a Keeper is refused. - Every `ALTER` is sent with `alter_sync`, a mutating one also with `mutations_sync`, where the user may change them. After a file the runner polls `system.mutations`; a failed mutation, or one still running after `LOOM_MIGRATE_MUTATION_WAIT_S`, fails the file. - `-- loom: tolerate-error ` lets a statement that only some servers accept fail with that code (for example `MODIFY SETTING index_granularity` on OSS `ReplacingMergeTree`, code 472). - Fresh-install rewrites (vector codec, `code_chunks` partition key) happen in the runner, so the files stay byte-identical. - `schemas/schema.sql` is regenerated by `scripts/ops/dump_schema.py`; CI checks it. ```bash loom migrate # apply pending migrations (also: make migrate) loom migrate --status # applied and pending, no changes loom migrate --dry-run # what would apply, with hashes and drift loom migrate --dry-run --strict # exit 1 on drift or ledger-only rows loom migrate --target 008 # apply through one migration only make schema-dump # regenerate schemas/schema.sql after a migration change make schema-check # verify schema.sql matches the migrations ``` Writing a migration is covered in [migrations](/docs/development/migrations) and [adding a table](/docs/development/adding-a-table). ## Gated ClickHouse settings Some DDL needs a session setting that ClickHouse gates. The runner sends each flag only with the statements that need it, because some servers reject an unrelated statement that carries it (`server/core/schema/migrate.py`, `_stmt_experimental_settings`): | Setting | Sent with | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `allow_experimental_nlp_functions` | Statements calling `stem(` or `lemmatize(`, and any `ALTER` on `memory_embeddings`. Dropped where read-only, as on ClickHouse Cloud, which runs `stem()` without it. | | `allow_experimental_vector_similarity_index` | Statements naming a `vector_similarity` / HNSW index. | | `allow_experimental_statistics` | Statements with `STATISTICS`. | | `enable_quantized_codec`, `allow_suspicious_codecs` | A coded `CREATE` on 26.8+, where the user may set it to 1 (below); `allow_suspicious_codecs` only when a codec is chained after `Quantized`. | The two codec settings decide the vector layout, so the runner reads their `value`, `readonly`, `min`, `max` and `disallowed_values` from `system.settings` before it sends either (`CodecSettings` in `server/core/schema/vector_codec_ddl.py`). A setting is held when this user may not set it to 1: `readonly = 1` (a `` constraint), or a `0` or `1` constraint, which `system.settings` shows with `readonly = 0`. A held setting is never sent: at 1 it needs no change, and at 0 the server refuses it (code 452). | State in `system.settings` | `enable_quantized_codec` | `allow_suspicious_codecs` | | -------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | settable | vector tables coded; sent with each coded `CREATE` | `entity_vectors` keeps its `LZ4` chain; sent with that `CREATE` | | held at 1 | vector tables coded; not sent | `entity_vectors` keeps its `LZ4` chain; not sent | | held at 0, or absent | vector tables plain | `entity_vectors` coded with `Quantized` alone, since the server refuses the chain without it (code 36) | The provider rebuild's candidate table and `dev/restore_loom.py` follow the same table, but refuse a coded table where the codec cannot be on instead of creating it plain: the restore before it writes anything, the provider rebuild before the candidate's `CREATE` (an owned stale candidate is dropped first). On 26.7 the provider rebuild takes `allow_experimental_codecs` in place of `enable_quantized_codec`. `scripts/ops/vector_codec_rebuild.py` refuses to run where the codec cannot be on, and refuses `--chain` where `allow_suspicious_codecs` cannot be; run with `--chain LZ4` once it can, it adds the chain back. `schemas/schema.sql` is a reference dump, not an install path (its header says to install with `loom migrate`): applied by hand with `clickhouse-client --multiquery`, it needs these flags set in the session first. ## Cloud and self-hosted differences Supported server versions are in [ClickHouse requirements](/docs/operations/deployment#clickhouse-requirements). | Area | Self-hosted (single node) | ClickHouse Cloud | | ---------------------------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Connection | HTTP on 8123 | TLS on 8443 (`LOOM_CH_PORT=8443` or `LOOM_CH_SECURE=true`). Keep `LOOM_CH_KEEPALIVE_TIMEOUT` below the load balancer's idle cutoff. | | Read-your-writes | A waited insert is visible to the next read. | Replicas may lag; see [Read-your-writes](#read-your-writes). | | Rolling upgrades | One version. | Replicas can differ for a while; setting support is probed per replica, and a rejected setting is dropped and the read retried. | | NLP functions | `stem()` available. | `allow_experimental_nlp_functions` is read-only; migrations run without it. The lemma column is filled by the application on both. | | Codecs | `Quantized` needs 26.8+; both codec settings are writable. | Read-only: `enable_quantized_codec` at its default 0 until the operator enables it (plain install), then 1 (coded); `allow_suspicious_codecs` at 0 until enabled for Loom's user (then the LZ4 chain on a fresh install or a rebuild). | | `MODIFY SETTING index_granularity` | Rejected by OSS `ReplacingMergeTree` (code 472); tolerated. | Accepted. | | Lightweight updates | Supported on recent versions; `ALTER UPDATE` fallback otherwise. | Each `UPDATE` is a patch part plus a Keeper entry; statements are batched and back off while mutations are pending. | | `OPTIMIZE … FINAL` | Returns after the merge. | Returns before the merge completes; code compaction polls `system.merges` on every replica. | | Filesystem cache | No effect on a local disk. | The client sends `enable_filesystem_cache = 1` on every session. | | Keeper | Required: the bundled stack runs an embedded one (`deploy/clickhouse-config/keeper.xml`). | Keeper is available. | | Durability | A single node has no replication or backups unless you add them. | Replication and backups are managed by the service. | Before 26.8, a vector-search read with a `WHERE` clause can record wrong entries in the query condition cache, and a later plain `SELECT` with the same condition can return fewer rows. When any replica is older, every Loom session turns the cache off when it connects (`server/core/ch.py`, `condition_cache_unsafe`). ## Invariants - Every tenant read filters on the identity prefix of the sort key; the exceptions are rows addressed by a global id (`erasure_requests`, `oauth_state`) and tables with no tenant columns (caches, `idempotency`, `revoked_tokens`, `worker_status`). - A `ReplacingMergeTree` version row carries every persisted column; row-state predicates run after `FINAL`. - No expression is aliased with the name of a column its `WHERE` filters on. - Vector statements order by a bare ascending distance with one sort key and no `JOIN`, window or `LIMIT BY`; every vector leg filters `embedding_dim > 0`. - Vector tables are written as new versions. - Every statement carries a `log_comment`, a class deadline and a pool slot. - `memory_versions` receives every `memory` row, and the column lists match. - No table that holds memory content has a schema TTL. - Every `loom.*` table is in `_CENSUS`, `STEP_ONLY_TABLES`, `CANONICAL_OWNER_TABLES` or `NO_MEMORY_CONTENT`. - A derived row is never the only copy of a write: the source row lands first and the derivation can be replayed. - A merged migration file is never edited. ## Source entry points - `server/core/ch.py`: `set_query_tag`, `statement_class`, `statement_settings`, `sequential_reads`, `own_write_reads`; `server/core/ch_writes.py`: `batched_insert_settings`, `async_insert_settings`, `committed_insert_settings`, `dedup_settings`, `insert_dedup_token`; `server/core/ch_schema_guard.py`: `pending_tables`. - `server/core/schema/journal.py`: the journal as data (file order, baselines, statements, the objects each file creates or drops). - `server/core/schema/migrate.py`, `server/core/schema/migrate_lease.py`: the runner, ledger, locks and gated settings. - `server/core/schema/vector_codec_ddl.py`, `server/core/schema/table_rebuild.py`: apply-time rewrites and rebuilds. - `server/core/vectors/codes_state.py`, `patch_parts.py`: vector read policy. - `server/memory/store/rows.py`, `inserts.py`: the version-row builders. - `server/erasure/store/census.py`: `_CENSUS`, `STEP_ONLY_TABLES`, `CANONICAL_OWNER_TABLES`, `NO_MEMORY_CONTENT`; `server/erasure/store/mutations.py`: `LIGHTWEIGHT_PURGE_TABLES`. - `server/memory/app/after_write.py`: fail-open projections. - `server/observability/events_stream.py`, `server/observability/audit.py`: telemetry and audit rows. - `server/storage/retention_overrides.py`: TTL composition; `server/knowledge/store/blobs.py`: document originals. - `server/insights/app/ops.py` (`_clickhouse_parts_check`): the parts and merges check. - `scripts/ops/dump_schema.py`, `table_rebuild.py`, `vector_codec_rebuild.py`: operator tools. ## Related - [Schema reference](/docs/reference/schema): every table, generated. - [Memory architecture](/docs/architecture/memory-architecture): the memory plane's write and read paths. - [Code index architecture](/docs/architecture/code-index-architecture): the `code_*` tables. - [Migrations](/docs/development/migrations): writing and testing a migration. - [Troubleshooting](/docs/operations/troubleshooting): too many parts, slow inserts. - [Performance tuning](/docs/guides/performance-tuning): traffic classes, vector knobs. --- # Code index architecture Source: https://loom.clickhouse.com/docs/architecture/code-index-architecture This page is the inside view of the code index: how files become chunks, symbols and edges, and how the two tiers stay current. What each op answers, the languages and their depth, and how to read `as_of` are in the [code index overview](/docs/features/code-index/overview) and [freshness](/docs/features/code-index/freshness). Running it (clones, backfills, the compiler tiers) is in [code index operations](/docs/operations/code-index-operations). ## Goals and non-goals | Goals | Non-goals | | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Per-merge freshness of the fast tier from a poll of a local bare mirror; no inbound webhook. | Indexing a working tree. Uncommitted and unpushed changes are never in the index. | | Exact call, override and inheritance edges where a compiler indexer exists; graded heuristics elsewhere. | Running a compiler in the server process. SCIP producers run in subprocesses of the workers process. | | Idempotent ingest: unchanged bytes yield the same rows and cost no embedding. | A general-purpose code host. The index is read-only reference data keyed by namespace. | | Every answer names the commit and tier it read, and says why an empty answer is empty. | Hiding staleness. A lagging tier is reported. | | A new language lands without re-indexing the others. | Equal depth for every language ([languages](/docs/features/code-index/overview)). | ## One namespace, one branch A code namespace is one repository branch at one commit. It has `kind='code'` in `loom.namespaces` (`code/app/index/registry.py`, `ensure_registered`), holds no memories, and keys every `code_*` row by `(org, namespace)`. Loom keeps one bare git mirror per repository, a cache of the remote recorded in ClickHouse: `code_ingest` clones a missing one (or `loom code init` does, ahead of time) and fetches it on every pass. `server/code/app/index/gitrepo.py` shells out to `git`; it has no working tree and writes nothing except `fetch`. Branches of one repository share the mirror. CLI backfills resolve sibling imports and re-exports from the mirror at the pinned backfill commit, including their edge reconciliation pass. Search chunks can carry doc comments and overlapping context, so their concatenation is not authoritative source text for parsing a sibling module. Sibling text, Python layouts, workspace registries, module indexes, compiler configs and barrel targets cache by tenant and namespace plus the pinned Git directory and commit. Concurrent passes share a pending read only within that source. Indexed-text reads use a separate cache scope. Each cache expires entries and bounds their count; the text cache also bounds the bytes it holds. Python ingestion resolves its layout before chunking and passes the layout snapshot to facet extraction; chunking threads do not access the mutable cache. A history read (`blame_range`, bisect, `first_build`, a lesson's code check) on a host without the mirror clones it once in the background (`server/code/app/index/mirrors.py`, `history_dir`). A read that names its op waits up to 10 s for the clone it started, or what is left of the op's latency budget, whichever is less; the others answer `no_git_mirror` until it lands. After the clone, the ledger's merge commits the clone lacks are fetched by sha and pinned: a merge made on a staging branch upstream has since deleted is in the worker's mirror (never pruned) but not in a fresh clone. A present mirror answers as it is; one that lacks the indexed head fetches the branch in the background. A head that is not the branch's (a PR head) is not fetched. This puts a full copy of every mirror on every serving host asked about it, which is the point (any host answers history reads after a move or a scale-out) and the cost (disk per host: a repository's size each). `LOOM_CODE_HISTORY_CLONE_ON_READ=false` turns it off: only the worker's host clones, and a history read anywhere else answers `no_git_mirror`. Repository entries come from two sources, merged: | Source | Read by | Notes | | ----------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------- | | Environment | `code/domain/index/repos.py` | `LOOM_CODE_REPOS_JSON`, or the scalar `LOOM_CODE_*` settings. | | `loom.code_repos` | `code/app/index/repo_registry.py` | Self-service rows, by `row_kind` (below). A private remote's token is stored encrypted and never returned. | A `loom.code_repos` row's `row_kind` says what it is: - `page`: a branch added from the page. It keeps an operator entry off its namespace, removed or not. - `access`: an operator entry's classification and join policy. - `''`: a row written before the column, read as the access row of an operator entry's namespace and as a branch added from the page elsewhere. `configured_repos()` reads an in-process snapshot refreshed at boot, on every ingest pass and after an add. Until the snapshot's first read it raises `RegistryUnread` (self-service on), since the entries a page namespace skips are not known yet; the modules that decide access read `config_entries()`, which lists the entries before that read with none org-readable (`tests/unit/test_repo_snapshot_contract.py`). An op that needs the full list answers 503 in that window; memory reads, search and `memory.for_file` answer without code links. A code call naming no namespace defaults to `LOOM_CODE_NAMESPACE` only when no member added that namespace from the page. Retiring an entry (`code/app/index/retire.py`) deactivates its rows, runs an erasure saga over every `code_*` table for the namespace, and removes the mirror when no other entry uses it on the host that served the call; every other host's sweep removes its own copy. ## Git mirrors on every replica Every serving process can answer a history read (blame, bisect, citations, PR overlays, commit coverage), so every host keeps its own bare mirrors (`code/app/index/mirrors.py`). A mirror is a cache of its remote: ClickHouse names the remote, and any host can rebuild the mirror from it. - **Warm-up.** At boot each process clones the mirrors of the indexed entries it lacks, `LOOM_CODE_MIRROR_WARMUP_CONCURRENCY` at a time, each after a random wait of up to 30 s, so N replicas starting together do not all clone from GitHub at once. Clones run in the background: readiness does not wait for them. - **The cost of a new disk.** A host with an empty `LOOM_CODE_REPOS_ROOT` makes a full bare clone of every indexed repository (several GB for a large one) before its history reads answer. Warm-up stays on by default because a new replica must build its caches without an operator; put `LOOM_CODE_REPOS_ROOT` on a volume that outlives a rollout to pay it once per volume, not once per pod. The clones are full, not `--filter=blob:none`: a partial clone fetches each missing blob from the remote while `git blame` runs, which makes a history read a network read and would reach the remote outside the repository-job sandbox. - **The gate.** Every history read goes through `mirrors.history_dir`, which returns the mirror or why there is none. Until the mirror is there the read answers `no_git_mirror: cloning ` (or why it will not be cloned here) instead of a git error, and starts the clone if none is running. `LOOM_GIT_HISTORY=none` turns history off on a host: those reads answer `no_git_history`. - **The host loop.** Only the leader asks the remote what changed (`ls-remote` of the extra branches and the PR heads). What its pass fetched is in ClickHouse: each entry's branch tip (`clone_head`), the open PRs' heads (`code_gh_items.head_sha`) and the ledger's merges. Every `LOOM_CODE_MIRROR_FETCH_INTERVAL_S` each host reads those and fetches, by name, only the branches and PR heads its mirror holds at another sha, plus a page of ledger merges it lacks; a host that is current makes no network call. Extra branches are not followed on other hosts: a fresh clone carries every branch the remote had, and the merges on them come through the ledger. One process per host does each mirror's round, and every fetch into a mirror (the pass's, the host loop's, a read's) holds the mirror's `.fetch-lock`; the pass's fetch also counts as the host's round for the interval. The same loop runs `git gc --no-prune` when due and sweeps `LOOM_CODE_REPOS_ROOT`: mirrors, `checkout-*` trees and mirror lock files no active entry names (restricted entries included) and half-done clones. It sweeps nothing when the registry cannot be read. - **Sandbox.** A host without the repository-job sandbox clones or fetches a self-registered entry with a network remote only where `LOOM_CODE_SELF_SERVICE_GIT_UNSANDBOXED` is set, on the read path as in the worker (`compiler_tier.unsandboxed_skip`). The entry's compiler tiers are skipped there either way. - **A forward proxy.** With `LOOM_CODE_GIT_PROXY_URL`, every clone and fetch above (the pass's, the host loop's, a read's), the `ls-remote` before an add and a checkout's submodule update connect through the operator's proxy as the entry's `git_proxy_identity`, else the deployment's default (`code/app/index/git_proxy.py`). The proxy and its password are added where a repository job starts as a plain process (`sandbox.run_job`), to the environment of that one git process: not to `auth_env`, whose git settings a build harness copies, and not to a sandboxed job, where repository code runs. A job that cannot go through the proxy is refused with a fixed reason, so git never connects directly; a host that runs the sandbox, whose egress proxy is not chained through this one, refuses network git while the setting is set. A host round fetches a shared mirror as its first entry ([git through a forward proxy](/docs/operations/code-index-operations#git-through-a-forward-proxy)). - **Merges the remote lost.** A ledger merge the remote no longer serves ("not our ref" in two calls, so one transient refusal does not count) is recorded in the mirror (`loom-unpinned-merges`), never asked for again, and counted in `/v1/health?include=mirrors` (`mirrors.unpinned_merges`) and `loom doctor`. - **The leader** clones a missing mirror in the background too, so one long clone does not hold up the other entries of its pass; an indexed entry keeps its Repositories-card stage while its mirror is cloned again on a new host. - **Erasure.** Mirrors and checkouts hold repository content, not memory content: the erasure census does not count them. A removed repository's copies go with the sweep on each host. `/v1/health?include=mirrors` carries `mirrors`: how many of this host's mirrors are `ready` and `cloning`, and `failed` and `absent` counted by reason. It answers without a token, so it names no entry. Disk use is the size of every mirror on every host: N replicas hold N copies. ## Components ```mermaid flowchart LR GH["Git remote"] -- fetch --> BC[("bare mirror")] BC --> CI["code_ingest
(fast tier)"] CI --> P["parse: treesitter.py,
lang_* lanes"] P --> CH["chunker.py"] P --> ED["edges_treesitter.py,
dependents.py"] CH --> CC[(code_chunks)] P --> CS[(code_symbols)] ED --> CE[(code_edges)] CI --> CF[(code_files)] CI --> ST[(code_index_state)] BC --> SD["code_scip_*_delta
(compiler tier)"] SD --> AP["scip_delta apply"] UP["code.scip_ingest"] --> AP AP --> CS AP --> CE CC -. "stub dim=0" .-> ER[code_embed_recovery] ER --> CC API["GitHub API"] --> PH[code_pr_history] PH --> PRT[(code_pr_history
code_pr_reviews
code_gh_items)] ``` ## Fast tier: `code_ingest` `server/code/workers/ingest.py` polls every `LOOM_CODE_INGEST_INTERVAL_SECONDS`; `code.refresh` triggers a pass from CI. Per entry, each pass: 1. **Fetches** the mirror and walks first-parent commits from the `git_head` watermark in `code_index_state` to the tip, oldest first, at most `LOOM_CODE_INGEST_MAX_COMMITS_PER_PASS`. 2. **Re-indexes exactly the changed files** of each commit (`ingest_file` in `code/app/index/ingest.py`): parse, chunk, symbols, edges, call guards, the file row, and a context pack and review brief for the merged PR the commit names. Then it advances `git_head`. A crash re-runs from the last complete commit. Across entries the pass takes one commit per entry per round, so a long backlog never holds another entry's new commits; a round the budget ends resumes next pass at the entry (org and namespace) it missed. 3. **Walks** with the share `LOOM_CODE_INGEST_WALK_BUDGET_SHARE` leaves: reconciliation heals and extractor re-chunks (below). | Bound | Effect | | --------------------------------------- | --------------------------------------------------------------------------------------------- | | `LOOM_CODE_INGEST_MAX_PASS_SECONDS` | Pass length. | | `LOOM_CODE_INGEST_PASS_BUDGET_FRACTION` | After this share the pass starts no new units, saves cursors and returns `partial: true`. | | `LOOM_CODE_INGEST_SECONDS_PER_FILE` | Predicts a commit's cost; a commit predicted to overrun starts only as the pass's first. | | `LOOM_CODE_INGEST_SLICE_SHARE` | The most of the commit phase one oversized commit may take before it is sliced across passes. | | `LOOM_CODE_INGEST_LANES` | Entries ingested side by side (default 1, up to 8). One entry's commits stay sequential. | | `LOOM_CODE_INGEST_ROUND_FILES` | Files per round inside a commit; reads prefetched in two statements, writes batched. | Lanes help because a lane waits on ClickHouse round trips, not CPU. **Admission.** A file is refused before parsing when it matches the denylist (`code/app/index/denylist.py`, `LOOM_CODE_INGEST_EXCLUDE`, `LOOM_CODE_INGEST_IGNORE_FILE`), is binary, or exceeds `LOOM_CODE_INGEST_MAX_FILE_BYTES`. So `coverage_floor: true` on a grep means every admitted chunk, not every byte. A path the entry's `embed_exclude` globs name (`LOOM_CODE_EMBED_EXCLUDE` for the scalar entry) is admitted, chunked and mapped, but its chunks are neither described nor embedded: they carry the `unembedded by design` marker, which every writer of a vector or a description honours and the coverage counts skip, the `code_summary` pass writes no card for them, and code.search reaches them through the lexical leg only. A changed glob applies to chunks written after it, in both directions (the operations guide's `embed_exclude` notes name the repair). ### Choosing a parser `ingest_parse.parse_for_ingest` tries these in order. The order keeps new file kinds out of the extractor stamp: 1. `treesitter.lang_for_path`: the stamped core (C/C++ with `.h` through the C++ grammar, Python, shell, SQL, doc, config). `ingest_parse._lane_language` then re-files CMake files and TLC configs. 2. Helm and Kubernetes manifests among config files (`lang_gotemplate`, `lang_k8s`). 3. `lang_detect.detect_by_extension` (`LANG_BY_EXTENSION`). 4. A shebang, then shell detection by Linguist names and ShellCheck directives (`lang_detect.detect_shell`). 5. Host files (Dockerfile, Makefile, Jenkinsfile, CI YAML) with `LOOM_CODE_HOST_ISLANDS` (`lang_hosts`). 6. Expected-output fixtures, one unembedded chunk per file (`lang_reference`). 7. Any other text, chunked without symbols (`lang_text`). The parser comes from `ingest_parse._PARSERS`. A failure of that parse, including a missing grammar or a tree-sitter parse past `code_parse_timeout_s` or `code_parse_memory_mb` (`bounded_parse`, one parse at a time), degrades to a chunk-only file with `code_files.index_error` set; `code.index_errors` reports it; a TLA+ spec instead falls back to its regex reader. A parse past its limits anywhere else takes its caller's fallback and records no error. Tree-sitter modules import lazily, so a server with the code workers off boots without the `code` extras. ### Chunks `server/code/domain/extract/chunker.py` cuts semantic units, never fixed windows: | Chunk | Contents | | ---------------- | ----------------------------------------------------------------------------------------------------------- | | `function` | One function body. An oversized one splits at top-level statements, each piece prefixed with the signature. | | `class_skeleton` | A class with method bodies elided. | | `file_header` | Leading comments and includes. | | `other` | The rest, grouped. | Python search responses omit a prefixed class docstring when the skeleton already contains its text. Files without a tree fall back to whole-line windows; lanes without a grammar cut on their symbol spans (`lane_units.span_chunks`). A chunk id is `uuid5("loom://code/{namespace}/{path}#{scope}@{sha16}")`. It is content-addressed, so an unchanged chunk keeps its id and hash and the embed step skips it without a lookup. Identical chunks in one file get an ordinal suffix. Class skeletons carry compacted presentation text, not physical source coordinates. The chunker retains class source outside method chunks as `other` chunks, including documentation, declarations, data members and blank separators. These source runs keep their original line spans even when they are shorter than the general leftover-chunk threshold. Body reconstruction requires every source line; missing separators cause an incomplete read even when all member bodies are present. Skeletons remain available for class summaries, and unmappable chunks still disclose partial grep coverage. Retaining source adds chunk rows and can add embedding work. The shared chunker's stamp moves only the chunk stage, across language families; existing indexes need that stage re-derived before missing source becomes readable. ### Symbols and edges A symbol id is `treesitter.symbol_id(qualified_name, signature)`: the first 128 bits of SHA-256 over the name and a normalized signature (whitespace collapsed, defaults stripped, so overloads differ). The fast tier, the SCIP converter and the read path all call it, so both tiers land a shared symbol under one id. Python and shell qualify names by module path, so the many `main()` functions in a test tree stay distinct. Fast-tier edges (`edges_treesitter.py`, `tier='treesitter'`) are resolved by name and graded: | Confidence | Rule | | ---------- | ----------------------------------------------------------------------- | | 1.0 | Unique definition in the same file | | 0.8 | Method of the enclosing class | | 0.6 | Unique match in the repository-wide symbol name table | | none | Ambiguous or unknown: no edge; recorded in `code_call_sites_unresolved` | A wrong edge is worse than a missing one, so `code.callers` reports how many sites its count leaves out. Constructor calls (`T x(...)`, `new T`, `make_unique`) are calls to `T::T`. Receiver-type modules (`cpp_receivers.py`, `py_receivers.py`, `ts_receivers.py`, `go_receivers.py`) bind member calls. Edge kinds are `calls`, `includes`, `inherits`, `overrides`, `uses_type`, `fixture_use`, `reads` and `writes`. `code.callers` and `code.impact` expand a method to its base declarations through indexed `overrides` edges or a bounded `inherits` walk from its class. A matching method name or signature on an unrelated class does not establish virtual dispatch. Missing relationships leave the graph answer a lower bound, with the missing-dispatch cause disclosed when the compiler tier cannot rule it out. **Dependents.** Edges resolve against a repository-wide name table, so a commit that adds, removes or re-signs a symbol changes the edges of untouched files that name it. `code/app/index/dependents.py` re-extracts only those files' edges at the same commit, up to `LOOM_CODE_INGEST_DEPENDENTS_MAX_FILES`. The overflow waits in `code_index_state` (`dependents_pending`) and drains through reconciliation. ### Embeddings and vector tables `code_ingest` embeds new chunks inline, memoized by content hash (`embed_reuse.py`), with bounded text (`embed_text.py`). With `LOOM_CODE_CONTEXT_DESCRIPTION_ENABLED` (on by default) a chunk gets a one-line LLM description prepended to its embedded text, best-effort and budget-gated. A provider failure leaves an `embedding_dim = 0` stub that `code_embed_recovery` fills, with per-text fallback and poisoning after `LOOM_CODE_EMBED_MAX_ATTEMPTS`. Until `LOOM_CODE_READY_EMBED_COVERAGE` of a namespace's chunks have vectors, `code.search` answers from its lexical legs and says so. | Table | Filled by | Use | | ----------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `code_summaries` | `code_summary` (weekly, off by default) | File and module cards for `code.map`, gated by an inputs hash, with PageRank from `code_graph_stats`. | | second-model tables, `code_chunks_prefix` | `LOOM_CODE_VECTOR_TABLES`; `loom code vector-twin` | The vector leg shortlists on the smaller twin and rescores on served vectors (`prefix_twin.py`). | | `code_answers` | `code.ask` | Answer cache keyed by question embedding; served only if every cited file's hash is current. | The answer-cache policy also keys synthesis prompts, output budget and the prose and chunk-kind ranking settings. Failed retrieval legs, interrupted or refused synthesis, and unavailable synthesis never produce positive or negative cache entries. A returned answer discloses these limits with `partial`, `partial_reason` and `note`; `coverage` is a model self-assessment rather than verified correctness. See [repository questions](/docs/guides/repository-questions) for calibration and mixed source/documentation retrieval. Bulk passes leave extra copies per key until a merge. `code/app/index/compaction.py` runs `OPTIMIZE … FINAL` on the twin tables after a bulk pass. `code_chunks` is compacted only by `loom code compact --table code_chunks --apply`. ## Compiler tier: SCIP The compiler tier holds `tier='scip'` symbols and edges. The server never parses protobuf: a producer converts SCIP output to a versioned JSON delta (`scripts/scip_harness/scip_to_delta.py`) and `code/app/index/scip_delta.py` applies it. Per touched file the apply upserts what the delta emits and tombstones the file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a delta gives the same live set. | Producer | Language | Watermark | Workers | How it runs | | ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | | `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Whole-workspace index per pass, bounded to the window's files by the converter. | | `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | | `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | `code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label and workers per producer; status handlers and the dashboard read it. A delta worker compares its watermark with `git_head`, moves the checkout (fetching from the local mirror, not the network), runs the producer in a subprocess and applies the delta through the same path `code.scip_ingest` uses. One pass covers every merge since the watermark. An external producer such as a CI job can upload a delta in parts with `code.scip_ingest`; parts are staged in `code_scip_batches` / `code_scip_parts` and applied by `code_scip_apply`. Every compiler-tier pass takes a per-entry lock file in `LOOM_CODE_SCIP_LOCK_DIR` and a ClickHouse lease, so a full re-index and a delta never run on one entry at once. `loom code scip-full` rebuilds the C++ tier; `loom code scip-delta` runs one delta pass. Where both tiers hold the same row, reads prefer the compiler row, and every answer names the tier it read (`scip` or `treesitter`). Exact code grep answers can carry the caller's readable code-linked lessons for the matched files. Lessons are read after cached match data, within the request's remaining deadline. Presence queries and uncovered paths carry none; `include_lessons=false` skips the read. `code.enclosing` carries the same file lessons for resolved locations. Repeated locations share one file read; unresolved locations bring no lessons. The caller's readable memory namespaces, narrowed-token refusal, timeout and token cap apply through the shared result enrichment. Resolved symbol names rank matching lessons after constraints and pins; unresolved names contribute no query terms. Empty lesson fields stay off the wire. When several grep hits need implementation source, pass their `path:line` locations to `code.enclosing` with `include_body=true`. It returns complete enclosing definitions together. `code.symbol` resolves a named definition or one location; the batch avoids a separate lookup for every located definition. `code.read` reads several known line ranges in one request. It uses a local Git mirror and checks the blob's hash against each indexed file record. Only files indexed for text search qualify. Projected notebook cells and reference fixtures with omitted text are unavailable. The response gives inclusive line numbers for each window and marks unavailable ranges, including ranges that exceed the request’s source byte limit. Python SCIP identities use the same placeholder for callables of every arity. Definition and enclosing-body responses recover the parameter list from a retained declaration with the matching name. Metadata-only responses leave the signature empty when the index provides only the placeholder. The stored identity and call edges keep their existing keys. Search and grep rank candidate lessons across all selected files by query-term overlap after constraints and pinned rows. English inflections share stems; equal matches keep path order, then the listing's confidence and recency order. The remaining file-lesson reads retain path and listing order. The ranking uses the existing namespace-scoped candidates. On trunk, uncapped grep responses focus lessons on the definitions their matches name. Search focuses a file's lessons when a returned definition has an exact linked lesson. Whole-file search hits use file-level selection. Grep omits a candidate by scope only if its link was checked at the same revision as the matched chunks. Matches outside a named definition also keep candidates with overlapping or unverified link ranges. Read the broader file history with `memory.for_file`. Before omitting a lesson by scope, the enrichment checks its live link set for pending and uncertain links within the request's enrichment deadline. Ranking and focusing add no model calls. File and symbol lessons carry complete memory text, including source references. The internal file listing reads complete values; the pre-edit block keeps its own read and render limits. A configured `code_result_lessons_tokens` budget leaves out whole lessons rather than cutting their conditions. Its default of zero is unlimited. With an explicit symbol request budget, source definitions take precedence; whole linked lessons fit in the remainder and `lessons_left_out` counts omissions. `bench/replay_code_lessons.py` compares recorded lesson order with query-aware order from an evaluation's native memory certificates and grep answers. It retains every timestamp-tie order that reproduces the recorded answer. Cases whose reads cannot be reconstructed remain unknown. This offline replay measures lesson order, not solver success. Python compiler conversion keeps callable and class descriptors distinct from parameters, type parameters and fields. Call edges require a containing function span; a reference at module or class scope does not belong to the preceding function. ## The extractor stamp Content-addressed chunks and hashed symbol ids key on the input, not on the code that produced the rows, so a chunker fix would never reach an existing row. `server/code/domain/extract/extractor_stamp.py` closes the gap. It hashes the code tokens of every extractor module (`logic_tokens`: no comments, blank lines or docstrings, and an import reduced to the names it binds, so moving a module between packages moves no stamp) plus the installed versions of the stamped grammars (`STAMPED_GRAMMARS`: the base library, C++, Python, bash). The stamp is split two ways so a change re-derives as little as possible: - **By stage** (`STAGES`: `chunk`, `symbol`, `edge`, `guard`; `STAGE_MODULES`). A stage's stamp covers its modules and those of the stages it reads (`STAGE_INPUTS`). | Module changed | Stages moved | | --------------------------------- | ----------------------------- | | `chunker.py` | `chunk` | | `edges_treesitter.py` | `edge`, `chunk`, `guard` | | `treesitter.py`, `lang_python.py` | all (`symbol` feeds the rest) | | `call_guards.py` | `guard` | - **By language family** (`LANGUAGE_FAMILIES`: `python`, `shell`, `typescript`, `cpp`, `other`; `MODULE_LANGUAGES`). A Python-only change heals `.py` files and leaves C++ alone. The TypeScript edge modules (`ts_receivers.py`, `ts_reexports.py`, `ts_config.py`, `ts_workspace.py`) move only `typescript`. A stamped module missing from `MODULE_LANGUAGES` moves every family. Each pass compares the running stamps with those in `code_index_state`. A moved stage is re-derived for every file of that family in every indexed namespace, in paced batches (`LOOM_CODE_EXTRACTOR_RECHUNK_PER_PASS`, switch `LOOM_CODE_EXTRACTOR_RECHUNK_ENABLED`). An empty recorded stamp is recorded, never acted on. So: - a code change to a module in `EXTRACTOR_MODULES` re-indexes every repository in the affected families, which takes hours on a large deployment; comments and docstrings can be edited freely; - those files are excluded from the formatters (`pyproject.toml`), and `tests/unit/test_code_extractor_stamp.py` keeps the exclusion list and the module inventory in step: a module in `server/code/domain/extract/` in no stage must be listed in the test's `NON_EXTRACTOR_MODULES` with its reason; - change them only when the extraction changes, and expect the re-derive after deploy. **Lane modules are outside the stamp.** The lane parsers (`lang_typescript.py`, `lang_rust.py`, `lang_go.py`, `lane_units.py`, …), their grammars and the file-selection modules (`lang_detect.py`, `denylist.py`) do not move it; the TypeScript edge modules above are the exception. A lane fix is applied with `loom code backfill --paths-file` over that language's files. ## Reconciliation Watermarks say which commits were walked, not whether every row is current. `code/app/index/reconcile.py` measures drift. A `code_files` row carries `blob_sha` and `indexed_commit`. One `git ls-tree -r ` marks a path stale when its blob differs and gone when it is absent. Rows without a blob fall back to one `git diff --name-only` per distinct commit, up to `LOOM_CODE_RECONCILE_MAX_COMMITS`. The hourly check in `code_ingest` (`LOOM_CODE_RECONCILE_ENABLED`, `LOOM_CODE_RECONCILE_INTERVAL_SECONDS`) re-ingests up to `LOOM_CODE_RECONCILE_HEAL_PER_PASS` stale paths through `ingest_file`; only new content is embedded. By hand: `loom code reconcile --heal`. The `loom.code.stale_files` gauge reports the count. ## Watermarks and coverage `code_index_state` (`ReplacingMergeTree(version)`, keyed `(org, namespace, state_key)`) holds `git_head`, the per-producer SCIP watermarks, the extractor stamps, cursors and `dependents_pending`. The `as_of` block on every answer and `loom.code.tier_lag_seconds{tier}` are computed from these rows and the mirror, not from a producer's log. Per-commit coverage (`code/app/index/commit_coverage.py`) is one `git merge-base --is-ancestor` per tier on the mirror, never a watermark comparison. What callers see is in [freshness](/docs/features/code-index/freshness). ## PR history, backports and tracker links | Table | Writer | Holds | | ------------------------------------------------------ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `code_pr_history`, `code_pr_reviews`, `code_gh_items` | `code_pr_history` (GitHub REST, cursor on `updated_at`) | Merged PRs with files, review comments, issues. A rate limit or 5xx leaves the cursor unmoved. | | `code_context_packs`, `code_review_briefs` | `code_ingest` at the merge commit, or on demand | Per-PR context pack and reviewer's brief. | | `code_backport_gaps` | `code_backport_gaps` (nightly; needs `code_pr_history`) | Per backport-labelled trunk PR, one row per release-branch namespace: covered, owed, not affected. | | `code_test_map`, `code_symbol_stats`, `code_unit_risk` | `code_graph_stats` (weekly), `loom code crossref` | Test↔source map, symbol fan-in, per-unit risk. | | `code_coverage_files` | `code_coverage_import` (daily), `loom code coverage-import` | Per source file, the line ranges a per-test coverage run executed. | | `qa_link_candidates` | `tracker_links` (daily) | Top merged PRs per recent issue, ranked by BM25F, stack frames in the diff and closing mentions. | | `qa_item_embeddings` | `tracker_embed` | Vectors of tracker issues and PRs in the embedding window; keys and filter facts, no text. | `code.repo.set_source` links a repository to its trackers, in order; the first is the primary, whose numbers are the repository's issue and PR numbers. The links are the `qa_binding` row of `code_index_state` and are read by `(org, namespace)`: a code namespace name is derived from the repository and branch, so two orgs can hold the same one. The operator's `LOOM_TRACKER_CODE_NAMESPACE_BINDINGS_JSON` applies only to the operator's own repositories (`LOOM_CODE_REPOS_JSON` or `LOOM_CODE_REPO`), never to a self-service one whose name matches a glob. Tracker workers read each namespace through its own source, so a restricted namespace's rows never land under a standard one. The record contract is in [tracker record contract](/docs/features/tracker/record-contract). `code.repo.add_branch` writes the new branch's `qa_branch_of` row naming the root repository (the source, or the source's own root when the source is a branch) when that root is an operator repository, so a self-service root's branch never starts reading the map if the operator later configures the root's name. A registered branch whose root is an operator repository follows that repository's links at read time, the glob included; a `qa_branch_of` row with no self-service entry beside it is not followed. A source that is not an operator repository has its own `qa_binding` row copied to the branch, a cleared one included. An operator source is its own root. Both rows are written with the source's rows read first and `qa_branch_of` last, so a failure leaves the branch following nothing. `code.repo.remove` empties whichever of the two rows holds a value before the namespace's detached purge. Registering a namespace empties any row a removed one of the same name left and drops the name from its own process's snapshot, so the new namespace follows neither. An emptied `qa_binding` reads as cleared until an admin of the tracker links it. A namespace that had no `qa_binding` row gets none, so the operator's map still reaches an operator entry configured under the same name. An operator entry configured under a removed name gets no such cleanup: until the purge runs, it reads the removed namespace's `qa_binding` row when there is one, the old links after a removal on build N-1 and none after one on N. Other processes keep the rows they read for up to `LOOM_CODE_REPOS_REFRESH_SECONDS`. ## Storage | Table | Engine and key | Notes | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `code_files` | RMT(`version`), `(org, namespace, path)` | Last parse per path: language, `blob_sha`, `indexed_commit`, `index_error`. | | `code_chunks` | RMT(`version`), `(org, namespace, embedding_model, path, chunk_id)`, partitioned by `(org, namespace)` | Content, `lexemes`, vector. Text indexes: 3-gram on `lower(content)`, tokens on `lexemes`. | | `code_symbols` | RMT(`version`), `(org, namespace, tier, qualified_name, symbol_id)` | Definitions with signature, span, doc comment, `scip_symbol`; ngram skip indexes on the name. | | `code_symbol_names`, `code_symbol_ids` | RMT, filled by `code_symbol_names_mv` / `code_symbol_ids_mv` | The symbols re-keyed by short name and by id. | | `code_edges` | RMT(`version`), `(org, namespace, tier, to_symbol_id, edge_kind, from_symbol_id, path, line)` | Callers are a key range; projections `by_from` (callees) and `by_path`. | | `code_call_sites_unresolved`, `code_caller_guards` | RMT(`version`) | Declined call sites by callee name; guards around each caller's call sites. | | `code_term_freq`, `code_doc_stats` | AMT, RMT; filled by `code_term_freq_mv`, `code_doc_stats_mv` | BM25 statistics for the lexical leg. | | `code_unit_signal` | `SummingMergeTree((positive, negative))` | Outcome counters per unit from `code.outcome`. | | `code_search_trace`, `code_search_outcome`, `code_search_memo` | MT with 180-day TTL; RMT with 60-minute TTL | Per-query traces and outcomes; a short-lived memo of served `code.search` responses. | Every column is in the generated [schema reference](/docs/reference/schema). ## Query patterns A file-qualified symbol request (`src/module.py:Type.method` or `src/Type.cpp:Namespace::Type::method`) keeps the filename as a hard constraint. The exact indexed path takes precedence even when it lacks the requested symbol. If it is absent, an unanchored relative path with two or more components can match the complete suffix of one live indexed file in the namespace. A `./` or absolute path keeps the lookup exact. Both symbol reads use the selected path before ranking and limiting. The response includes `resolved_by: file_symbol`, the canonical indexed path, and the stored symbol name and id. The shared resolver applies this spelling to structural code operations. Python import spellings use the bounded short-name candidate read after an exact symbol miss. Read-side matching preserves dotted module scopes and treats a package's `__init__.py` as implicit. Only Python source rows participate; ambiguous or incomplete candidate sets decline. The response discloses `resolved_by: python_module` while retaining stored names and ids. Extraction and its stamp do not change. Memory code links use the same Python import spellings when resolving named definitions. A package-level name such as `pkg.json.dumps` can anchor the definition in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor names remain explicit, and ambiguous matches stay unlinked unless the memory's file scope selects one definition. | Op | Path | How | | -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | | `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | | `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | | `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | | `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the index tokenizer. The score counts only whole app lexemes and rejects partial matches from the gate. Underscore-only lexemes use the exact score within the same tenant, model and path scope because the text index has no token for them. After relevance ranking, per-file saturation spreads broad search results across files. It is skipped for an explicit path, a symbol route, test intent, or a code-shaped identifier named in the query that matches a qualified symbol component in the relevance window. This keeps related definitions together for questions about a named identifier. An unmatched identifier does not disable saturation. Per-symbol deduplication still removes repeated chunks of one definition, and continuation pages retain the final served order. ### Symbol bodies Literal hits, rendered-message matches and symbol mentions use the same retained-source line mapping as definition bodies. Copied doc comments and continuation headers do not become file lines. Compacted class skeletons cannot establish exact hit coordinates. Grep and symbol mentions recover their retained raw chunks under the same tenant, model and path. A summary is replaced only when those chunks cover its span without gaps or disagreements with already-read source. Recovery shares the grep scan's character bound and any caller-supplied deadline. Incomplete or failed recovery leaves grep partial and symbol mentions truncated. A missing hit in that response is not evidence that the file lacks the text. Grep continuation pools retain source-mapping and partial-coverage metadata. A pool with another mapping triggers a disclosed rerun; restart pagination for complete results because its offset can count synthetic hits. Signed cursor formats and stored match shapes are unchanged across rolling builds. Readers that do not use the additive pool metadata can still consume its matches. A definition body covers every declared source line without conflicting overlaps, missing lines or skeleton substitutions. Doc-comment copies and continuation headers are removed from chunk prefixes when placing the retained lines. The read uses live rows under one served embedding label, scoped to one organization, namespace, path and line span, with a bounded row count. An unchanged chunk's introduction commit may differ from its neighbors; it does not establish the current file revision. This read follows live-row publication and does not provide a snapshot across an indexing pass. A compiler declaration alone does not establish a larger function body. Parser coordinates, source chunking and oversized-piece boundaries count LF lines; other Unicode separators inside a string remain source text. A retained prefix ending in an ambiguous non-LF separator cannot establish a complete physical line. Hydration and indexing share provider-free label canonicalization, including explicit local and fake provider overrides. Hydration constructs no embedder, and missing provider credentials do not select a fake label's source chunks. If the retained span cannot be established, exceeds 12,000 characters or needs more than 400 chunk rows, the definition carries `elided: true`, `granularity: card` and a ranged `next` read. HTTP and MCP preserve that omission. Enclosing-body lookups omit unavailable text, and verification cannot use an unread body as negative evidence. No source text is fetched from a network or fabricated to fill a gap. ## Invariants - A code namespace is one branch; every `code_*` row is keyed by `(org, namespace)`. - `git_head` advances only after every file of the commit is written. - `treesitter.symbol_id` is the only symbol-id function, used by both tiers and the read path. - Chunk ids are content-addressed; an unchanged chunk is not re-embedded. - A stamped module's code change re-derives its stages for its language family in every namespace; comments and docstrings never do. - A delta apply is idempotent and tombstones what the producer stopped emitting. - The server never parses SCIP protobuf. - Per-commit coverage is an ancestry check on the mirror, never a watermark. - Retrieval filters `embedding_dim > 0`; a stub chunk is searchable lexically only. - With `LOOM_CODE_GIT_PROXY_URL` set, git reaches a network remote through that proxy or not at all, and the proxy's password is in the environment of that git process only. ## Source entry points | Path | What | | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | `server/code/app/index/ingest_pass.py` | The fast-tier pass. | | `server/code/app/index/ingest.py` | `ingest_file`, the per-file stages. | | `server/code/app/index/ingest_parse.py`, `ingest_chunks.py`, `ingest_edges.py`, `ingest_resolve.py`, `ingest_reconcile.py` | `parse_for_ingest` and `_PARSERS`, chunks, edges, edge-resolution reads, the key-diff writes. | | `server/code/domain/extract/treesitter.py`, `lang_detect.py`, `lang_*.py`, `lane_units.py` | Languages. | | `server/code/domain/extract/chunker.py`, `edges_treesitter.py`, `call_guards.py`; `server/code/app/index/dependents.py` | Chunks and edges. | | `server/code/domain/extract/extractor_stamp.py` | The stamp. | | `server/code/app/index/reconcile.py`, `commit_coverage.py`, `scip_delta.py`; `server/code/domain/index/compiler_tiers.py` | Drift, coverage, tiers. | | `server/code/workers/scip_*.py`, `scripts/scip_harness/` | Compiler tier. | | `server/code/workers/embed_recovery.py`, `summary.py`, `graph_stats.py`, `pr_history.py`, `backport_gaps.py`, `coverage_notify.py` | Background workers. | | `server/code/domain/index/repos.py`; `server/code/app/index/repo_registry.py`, `registry.py`, `retire.py`, `gitrepo.py` | Entries, mirrors, namespaces. | | `server/code/app/index/sandbox.py`, `egress.py`, `git_proxy.py` | Repository jobs and how they reach the network. | | `server/code/app/search/`, `server/code/store/index/` | Reads and writes. | ## Related - [Code index overview](/docs/features/code-index/overview) (languages and tiers), [freshness](/docs/features/code-index/freshness), [history and PRs](/docs/features/code-index/history-and-prs). - [Code index operations](/docs/operations/code-index-operations). - [Adding language support](/docs/development/adding-language-support). - [ClickHouse](/docs/architecture/clickhouse), [operations reference](/docs/reference/operations#code). --- # Cost budgets Source: https://loom.clickhouse.com/docs/architecture/cost-budgets Namespace and named-user caps use the rolling 24-hour cost ledger in `agent_events`. A positive namespace policy overrides its corresponding server default; zero inherits, and zero on both tiers disables that cap. A named user's cap is independent of the namespace ceiling. Admission refuses paid synthesis when either is reached, and model routing uses the larger spend fraction. `memory.ask`, including its whole-document route, `code.ask`, `knowledge.synthesize` and `code.search` query expansion supply the logical user recorded in the ledger. Namespace-wide workers keep their namespace accounting; a token subject is never substituted for an unattributed user. The extraction queue is the exception: a replay's row carries the user the deferred request named, so its spend counts toward that user's cap and can refuse that user's paid synthesis. These soft controls do not reserve spend or establish a billing identity. `cost.budget_status` shares the policy and spend read with the guards. User mode requires a namespace and reports the user's cap and verdict, plus `namespace_over_cap`. Exact user spend and its percentage are `null` unless the caller is a verified platform admin without namespace-role restrictions. This holds even when every event is ordinary; varying the presence of a number would reveal marked activity. Missing auth grants no private spend access. Internal accounting, admission and budget pressure include all spend, including marked requests. Namespace and org totals remain numeric. Transport admission enforces a token's pinned user. Namespace and org modes retain their existing read scopes. The [cost guide](/docs/features/observability/cost-and-usage#daily-spend-caps) describes configuration and warning timing. An optional `budget_alert_inbox` must name an existing inbox owned by the budget's namespace in the same org. Registration validates it and delivery rechecks ownership. Point checks and status polls schedule bounded background warnings through the existing task event stream, with at most 32 pending deliveries per process. Deliveries for one org run serially within the process so a namespace and user warning do not compete with each other. There is no discovery worker. The event ID includes org, namespace, inbox, selected user, cap, warning share and UTC day. A distributed claim and strongly consistent event read serialize the check and insert; a deduplication token plus readback handles an uncertain retry. Notification failures cannot change a cap verdict. User warning payloads carry the selected user, cap and warning share, with `spent_24h_usd: null`. This applies to the inbox, polling, streams and webhook, even when an operator's check triggers delivery: the initiator's authority does not establish the recipient's authority. Namespace warnings retain their namespace spend total. The user cap verdict and warning threshold crossing reveal bounds on spend; an admin who changes caps can infer tighter bounds. This is an accepted policy signal alongside the [marked-spend totals exception](/docs/architecture/document-sources), not full noninterference. It grants no access to marked work, models or outcomes. Task updates and watch streams apply the caller's user and session scope to warnings before pagination. An incomplete scope receives no warnings; ordinary task events stay shared within the inbox. The registered inbox's webhook receives its namespace stream. Every delivery and task-event erasure takes the same org-wide warning-writer lease. Inserts use the existing server-side start deadline and execution bound; the lease TTL exceeds the working window plus the full send bound. An uncertain insert or cancellation leaves that lease to expire, so erasure cannot acquire it until every possible send has finished. Erasure keeps its tagged mutation, polling and resume protocol. Ledger checks before and after publication invalidate an observation reached by erasure; post-write cleanup names only that delivery's exact event and sequence. An unreadable ledger refuses publication. Warning rows carry the full identity tuple, a process actor and derived source class. User erasure deletes their task events and the residue census verifies the deletion; namespace erasure covers both tasks and events. Added columns have defaults for older writers. Warning production waits for every live replica to support the migration, so an older erasure implementation cannot miss user-bearing warning rows during a rolling upgrade. Unknown fleet state defers publication until a later check. ## Activation and rollback User caps and budget warnings require every serving build to support migration 107. Keep `LOOM_DEFAULT_DAILY_USER_COST_CAP_USD` and every namespace's `daily_user_cost_cap_usd` at zero, and `budget_alert_inbox` empty, while any deployment sharing the stores runs an older build or its version is unknown. Do not rely on user caps during that interval. Apply the migration and upgrade every serving process before setting these policies. The warning fleet check defers production on an old or unknown fleet; it does not remove warnings already stored. Save the global user-cap default and each namespace's user cap and alert inbox before rollback. Rollback requires a maintenance interval: 1. Stop all request-serving and background processes that can check budgets or schedule warnings, across every deployment sharing the stores. Stop status polling too. Turning off background workers or clearing an inbox policy alone does not stop deliveries already scheduled with that inbox. 2. Drain scheduled deliveries and settle every in-flight or uncertain write before cleanup. Wait for warning-writer leases to be released or expire and for their bounded late-start and server execution windows to end. An interrupted drain or an empty running-query list does not prove that a delayed send cannot still arrive. 3. Erase only `loom.task_events` rows whose `event` is `budget.warning`. Wait for the deletion to complete on every storage replica and verify that no warning rows remain on any of them before starting the first older process. An unreadable replica or an unsettled write blocks rollback. Namespace or user erasure is not a substitute: it also deletes unrelated data. 4. Keep user caps and warnings disabled while older builds serve. After every serving process supports migration 107 again, restore the saved global default and reapply the namespace user caps and alert inboxes with `namespace.register`. Read the namespace policies and check the effective caps before resuming warning production. This limits activation during mixed-version operation and trades availability for privacy during rollback. Older task readers do not filter private warnings, and older user erasure does not delete them. Older namespace registrations also omit the user-cap and alert-inbox columns; their replacement rows reset these policies to their defaults. The namespace registry does not carry those columns through older writes. The operator must therefore preserve and restore policy rather than rely on it surviving rollback. ## Source entry points - `server/observability/budget.py`: `budget_snapshot` reads policy and rolling spend for the guards and status. - `server/tasks/app/budget_notifications.py`: `deliver` owns warning claims and erasure fences. - `server/tasks/store/repo.py`: `events_since` applies warning scope before cursor pagination. - `server/tasks/app/reads.py` and `server/tasks/app/watch_routes.py`: polling and streaming readers bind that scope. - `server/erasure/store/steps_ledgers.py`: warning-writer leases protect task-event deletion. ## Invariants - A named user's allowance never raises the namespace ceiling, and attribution never guesses a token subject. - A narrowed reader receives no warning outside its user and session scope. - An uncertain warning write keeps erasure fenced until its possible send has finished. - Notification failure never changes the cap decision. --- # Definition drafts Source: https://loom.clickhouse.com/docs/architecture/definition-drafts Needs `knowledge_gaps_enabled` for gap drafts or `knowledge_query_history_enabled` for query history. Both paths put model-written definitions in the admin review queue. The model never publishes a definition. This page describes evidence, private candidates and review; [knowledge gaps](/docs/architecture/knowledge-gaps) describes recording and grouping searches. ## Evidence and access The Library's **Draft definition** action calls `knowledge.gaps.draft`. It rereads the gap's questions against the current seven-day miss window and requires at least `knowledge_gaps_min_askers` distinct askers for each question. It sends only those normalized questions to the model. Capture consent is read uncached, and unavailable consent refuses the draft. A threshold change or a user erasure during work invalidates the evidence and removes that attempt's candidate versions. `knowledge.query_history.add`, `.list` and `.remove` need namespace admin access. In the Library, **Query history** opens the source list and connection form. A registration has a name, host, port, TLS choice, read-only account, database allowlist and optional cluster. Its password is sealed at rest and never returned. The connection reuses the tracker's host checks, pinned address and read-only grant review. A cluster also needs `REMOTE`. Removing a registration stops subsequent turns without deleting an existing draft or definition. Disconnect remains available when the operator disables query history. The worker reads finished, initial `SELECT` queries whose nonempty database list lies entirely in the registration's allowlist. A named cluster uses `clusterAllReplicas`; otherwise only the connected node is read. Groups use `normalized_query_hash` and `normalizedQueryHashKeepNames`, ordered by distinct `initial_user` accounts and recency. The second hash keeps different numbered table names apart without splitting whitespace or literal variants. `normalizeQueryKeepNames` removes comments and replaces literals, preserving identifiers. Only this normalized SQL reaches the model. At least `knowledge_query_history_min_users` accounts must support a group, never fewer than three. Accounts are not people: one shared account counts once, while one person's several accounts count separately. This floor provides no anonymity guarantee. A live threshold increase or history-window change invalidates an in-flight result. Source removal, a changed source UUID, feature disablement and namespace erasure also invalidate it. Candidates use `source_kind = knowledge_gap` or `query_history`. Their model-written text and query-history SQL remain private to namespace admins in `learnings.list`, quality counts and both explicit and inferred lineage. Filtering precedes pagination and aggregation, including org-wide quality reads. Read-narrowed tokens cannot call either operation prefix. ## One model attempt The candidate ID derives from the organization, namespace, kind and evidence resource. A gap uses its gap ID; query history uses the registration UUID and both query hashes. A short candidate lease persists a pending claim before releasing the lease for the model call. Concurrent and later requests return that candidate ID, including after a decision, model error, invalid result or crash. Such failures retain a pending claim whose rationale tells the admin to reject it and write explicitly. A policy hold before generation removes only the unspent claim's versions so a retry can proceed when allowed. The org's model-call switch and namespace daily cap are checked before claiming work; an unreadable cap refuses it. Each attempt permits one bounded JSON completion. The result validates term, aliases, body and table/column list sizes. Gap provenance in `rests_on` holds the gap ID and the model's table/column lists. Eligible questions reach only the model input; the application does not copy them into the candidate. The model may repeat a question in its drafted text. After generation, the draft and gap ID can outlive a user erasure of the source questions. Query-history provenance retains its normalized SQL and the model's table/column lists. A final candidate lease rereads status so completion cannot replace a rejection or restore scrubbed text. Evidence fences run before and after model work and after insertion. The worker limits sources, groups, attempts, query bytes, rows, memory and execution time. It starts no further group after half the pass budget and saves the last source's UUID before its turn, so a failing source does not prevent rotation. The fixed-size UUID also keeps source names out of the persisted cursor. Connection failures use a bounded per-source circuit breaker. Worker cost events retain namespace attribution. ## Review and publication `learnings.review` accepts these candidates only for destination `memory`. Before a write, it checks fleet capability, sensitivity, the shared-definition ceiling and name conflicts. A draft revises the live shared definition whose folded term or alias matches its term; ambiguous matches refuse. A new term uses the random `definition/` key persisted with the claim. The shared rows are reread before writing so a concurrent rename cannot redirect the write to a different term. The review writes a namespace-wide, derived definition through `memory.set`, clearing expiry and validity bounds. An exact, active, unexpired head needs no write, even when pinned or locked. A changed value refuses a pinned or locked head. A revision requires the current source text to match the shared copy; a writer's intervening edit refuses. Retained expired heads use their hash for a conditional rewrite, and an absent head uses `if_match_sha256="absent"`. Conditional callers serialize on the key; ordinary concurrent ClickHouse writes resolve by version. These checks do not make writing and promotion atomic. The review calls `memory.promote` with the approved canonical-value hash. The server supplies candidate provenance internally and stamps the authenticated actor. A client cannot supply trusted provenance or choose the deciding actor through `approver`. Promotion publishes the entire definition, including normalized SQL, to readers of the namespace, so the admin approves that text for all of them. A committed write followed by publication or promotion failure leaves an ordinary namespace-wide definition and a pending candidate. Ordinary retrieval can read that row. A retry promotes an unchanged exact head without rewriting it. Rejecting the candidate leaves the source row intact. There is no automatic undo: it could overwrite a later writer's same-text metadata revision. The admin can restore intended text through memory history and write operations or delete an exact version explicitly. ## Erasure, audit and upgrades Namespace erasure deletes `loom.query_history_sources` through `query_history_sources.delete`. The registration holds configuration and a sealed credential, so it is classified under that step without a memory-content census row. Candidates follow the learnings queue's erasure coverage. A historical definition redact also scrubs matching private candidates by canonical text hash or the redacted version's candidate tags, across every candidate version. It uses the review lease, refuses later review of blank text and preserves a live head that still holds the redacted text. The review audit identifies the authenticated deciding actor and candidate. Internal `memory.set` and `memory.promote` emit their own audit events; the promotion event is also the audit request ID that `memory.lineage` follows. Source mutations audit the scoped registration name, never its password. Private-kind production and promotion require every live server and worker heartbeat to advertise the registration migration. Missing or unreadable fleet state fails closed. Apply the migration and upgrade every server and worker before enabling either drafting path. Keep both paths disabled while any serving build is older or unknown. An older build does not filter private candidates or erase registrations. Fleet checks alone do not protect a rollback: a request can pass its check before an older heartbeat appears. Rollback requires a maintenance window before any older reader starts: 1. Disable both `knowledge_gaps_enabled` and `knowledge_query_history_enabled`. Stop new private drafting, review and source-registration requests and query-history worker turns. Quiesce their queued work and every admitted model call, review, registration and removal. Disabling a flag does not cancel an existing request or review. 2. Let those operations finish or terminate, then settle their uncertain server sends and retained writer leases through their bounds. Do not clean the tables while an admitted operation can still write a candidate, decision or registration. 3. With only a supporting build running for maintenance, remove every version of `knowledge_gap` and `query_history` candidates from `loom.learnings_queue`, and all `loom.query_history_sources` registrations. Wait for deletion to finish and verify both are absent on every storage replica a reader can use. Preserve ordinary candidates and published definitions. Only then start an older reader. Keep private producers disabled throughout the downgrade. Enable them again only after all serving processes support the registration migration. Governed memory and shared rows retain their existing upgrade rules. ## Source entry points - `server/memory/app/definition_drafts.py`: durable claims and bounded generation. - `server/memory/app/definition_review.py`: fleet gate, promotion and candidate redaction. - `server/knowledge/app/gap_drafts.py`: current gap eligibility and consent. - `server/knowledge/app/query_history_sources.py`: registration and credential checks. - `server/knowledge/store/query_history_remote.py`: read-only grouped query-log reads. - `server/knowledge/workers/query_history.py`: bounded source rotation. ## Invariants - Only an admin can read a private candidate or publish it through review. - No model completion replaces a candidate decision or resurrects erased evidence. - A source registration cannot outlive namespace erasure and continue producing drafts. - A refused or interrupted promotion does not undo a writer's row. --- # Dify tools adapter Source: https://loom.clickhouse.com/docs/architecture/dify-adapter The Dify plugin calls Loom through the Python SDK and stores no content locally. Its three native tools map to `memory.set`, `memory.search` and `knowledge.search`. The optional standalone package requires the 0.11 plugin SDK minor series and the Loom 1.x SDK; the server and core SDK do not depend on Dify. ## Invariants Provider credentials bind the endpoint, organization, namespace, token and agent. A required User ID form parameter binds the end user outside the model's arguments. Recall can read that user's memories across Loom agents; documents are shared by the namespace. Both search operations pin `namespace_scope=this`. Separate namespaces and token grants constrain mutually untrusted applications. Loom applies its usual actor, provenance, conflict handling, rolling schema and erasure rules to these calls. The administrator controls the HTTP destination. The plugin checks its URL shape and rejects embedded credentials, queries and fragments; deployment network policy constrains which hosts the plugin runner can reach. Requests have finite timeouts and one attempt. Tool errors expose no credentials or remote response detail. The plugin creates no additional database, cache, model provider or telemetry path. Dify patches Python threading with gevent greenlets. Each request constructs, calls and closes its SDK client inside the current hub's native thread pool, so overlapping clients do not run asyncio loops on the same native thread. Credentials stay local to that request. The SDK call waits at most 30 seconds; pool admission, client setup and close have separate waits rather than a whole-invocation deadline. Dify installs the package from a local `.difypkg`. The official CLI packages source, metadata, runtime requirements, icons, license, README and privacy statement. Its ignore file excludes tests, environments, credentials and build state. CI invokes the native tools against a fake SDK HTTP transport, checks overlapping native calls over loopback HTTP, validates native tool schemas and builds the package. Live tests run only with an explicit private Loom URL and token; platform execution is documented separately from those SDK tests. ## Source entry points - `integrations/dify/client.py`: scoped SDK calls and request failures. - `integrations/dify/provider/loom.py`: credential validation. - `integrations/dify/tools/`: native tool implementations and schemas. - `.github/workflows/dify-plugin.yml`: tests and packaging. --- # Document extraction Source: https://loom.clickhouse.com/docs/architecture/document-extraction An uploaded original is parsed into one shape, the extraction artifact, by an extractor service: a separate process with its own dependencies, never the Loom server. The server sends the original's bytes to the service its format is routed to, reads the artifact back as untrusted input, and cuts structural chunks from its blocks, so a SQL statement, a TOML key and a Markdown section are all cited by a locator into the source. Loom ships a reference extractor (`extractor/loom_extractor/`) for Markdown, HTML, plain text, SQL, TOML, CSV, PDF, DOCX, PPTX, XLSX and, with `pyarrow` installed, Parquet; an operator can run another behind the same [wire contract](/docs/reference/extractor-contract). `knowledge.ingest` extracts an uploaded original this way ([ingestion](#ingestion)), and the document-source sync calls it for the PDFs, `.pptx` and `.docx` files a registered folder holds ([syncing a source](/docs/features/knowledge#syncing-a-source)); `knowledge.add` takes text the caller extracted. ## The service boundary | Side | Holds | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Loom server | the contract (`server/knowledge/domain/extract/`), the checks on what an extractor returns, format routing, the structural chunker and the client (`server/knowledge/app/extractors.py`) | | Extractor service | format detection, strict decoding and every parser; no Loom token, no database credential and no bucket access: it gets bytes and returns JSON | Parsing a file means running a parser over input an uploader controls. Keeping that out of the server's process keeps a parser defect, a pathological input or a parser's dependencies away from the process that holds ClickHouse credentials, signing keys and tenant data, and lets an operator swap in their own utility for a format. `tests/unit/test_package_contracts.py` checks that no server module imports the extractor, sqlglot or pypdf, and that the knowledge plane imports no parser library. **Routing.** The server names the format from what the caller says (a declared format, else the file extension, else the media type, else `text`) without reading the bytes, and sends the original to the service `LOOM_DOCUMENT_EXTRACTORS_JSON` names for that format, or for its media type when the media type names that format, else to `LOOM_DOCUMENT_EXTRACTOR_URL`. A format is extracted only when that service's `/v1/capabilities` declares it; the declaration is read again after a minute. A `.doc`, `.xls` or `.ppt` name is refused before any call. A route key is a format name or a media type that names one, matched without its parameters and case; any other key is refused when the settings load. What a deployment advertises is what these declarations say: `knowledge.formats` reports a format as available when a service a file of it can go to declares it, and as unknown while that service cannot be read (a format served only by a media type's route is read when the upload carries that media type). It reads the services together within 5 s; the formats of one it cannot read within 5 s are unknown for up to a minute, until a capabilities read of it succeeds. **Fail closed.** A format with no configured service, a service that does not declare it, is unreachable, takes longer than `LOOM_DOCUMENT_EXTRACTOR_TIMEOUT_S` for a whole call, refuses the server's token (`401`, `403`, `407`), answers `408`, `429`, `format_unavailable`, a `5xx` or anything else that is neither `200` nor `4xx` (a redirect, a `204`) raises `ExtractorUnavailable`, and the source can be tried again. A source the service refuses raises `ExtractionFailed` with the contract's code (`format_mismatch`, `encoding`, `too_large`, `timeout`, `resource_limit`, ...), as does a response that breaks the contract (`invalid_artifact`). There is no in-process fallback: with no extractor configured, no original is extracted. **Tokens.** The server sends each service the token `LOOM_DOCUMENT_EXTRACTOR_TOKENS_JSON` holds for its URL, else `LOOM_DOCUMENT_EXTRACTOR_TOKEN`, so an operator's own service need not hold the token the reference extractor accepts. **Untrusted output.** The server asks for a response uncompressed (`Accept-Encoding: identity`), treats a compressed one as the service being unavailable, and reads an artifact up to `LOOM_DOCUMENT_EXTRACTOR_MAX_ARTIFACT_BYTES`, refusing a longer one as `resource_limit`. Then `parse_artifact` checks it before anything is chunked, embedded or published: the schema version, the format asked for, each block's type, a unique id and a parent that is an earlier block, at most 10,000 keys of 1,024 characters and 64 section-path entries of 500 characters per block (so the chunks cut from a long block share its keys and per-chunk work stays linear), locator spans that are ranges, coverage counts within their total, strings that are valid Unicode, numbers that are JSON (no `NaN` or `Infinity`; signed 64-bit integers (-2^63 to 2^63-1), other numbers within a double), each table's shape (a unique id, at most 16,384 typed columns named in at most 500 characters, rows as long as its columns of scalars or cell errors, and a sheet and rows that are a locator), and nesting depth in `attrs` and `options` (16; the reference TOML parser leaves out the `attrs.value` of a value nested deeper than 8, whose text the block keeps). `complete` is recomputed from the counts, failures and losses, and an artifact whose flag disagrees is refused. A field the contract does not name is dropped. The server addresses the artifact by the SHA-256 of its own serialization, not the service's bytes. **Isolation in the reference extractor.** Every `/v1` call carries `Authorization: Bearer `; the service refuses to start without a token of at least 16 characters. Each extraction runs in a child process, and before the child reads the source: | The child | How | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | has no environment | started with only `PYTHONPATH`, `PATH` and `LC_ALL`, so the token is not in it | | cannot read the service or another child | the service and every child are non-dumpable (`PR_SET_DUMPABLE`), so a process of the same user cannot read their environment, memory or open files through `/proc` or ptrace | | has bounded resources | address space (`LOOM_EXTRACTOR_MEMORY_MB`), CPU seconds, a file size of 0 (it can create empty files, not write to one), no core dump | | starts no process | `RLIMIT_NPROC` 0, so nothing a parser starts outlives the extraction; a child still running at a timeout, a disconnect or a cancel is killed with its process group before its slot is freed | | opens no socket | a seccomp filter set after no-new-privileges makes `socket`, `socketpair` and `io_uring_setup` fail with EPERM, and `ptrace`, `process_vm_readv`, `process_vm_writev` and `pidfd_getfd` too (x86_64 and aarch64; the service refuses to start on another architecture), so it reaches no address, the Loom server on its network included. A concurrent sibling stays writable through `/proc//mem` until it is non-dumpable, so with `LOOM_EXTRACTOR_CONCURRENCY` above 1 a taken-over child could still patch one before it filters itself | | gains no privilege on exec | `PR_SET_NO_NEW_PRIVS` in the service and in each child, so no setuid binary or file capability raises one | | loads only the package | runs in `/` with `-P`, so no current or script directory is on `sys.path`; the package and its dependencies are installed read-only to the service's user, as a file of its own on `sys.path` could change what every later child imports | | shows no request | its command line holds only its limits; the file's name and options come on stdin | The service kills a child at the wall-clock timeout, when its caller disconnects or when its output passes the artifact bound, and reads a source only once one of its `LOOM_EXTRACTOR_CONCURRENCY` slots is free, so that bound covers the originals held in memory too. The slots are one by default: a child is readable by other processes of its user from its start until it makes itself non-dumpable, so a child a hostile source has taken over could open a concurrent child's source in that moment. Scale with service replicas, not slots. The kernel does not hold root, or a process with `CAP_SYS_RESOURCE` or `CAP_SYS_ADMIN`, to the process limit, so the service refuses to start as root or with either capability permitted. A child is not denied reads of the file system in its process: the container it runs in is what denies those. The service refuses to start on an architecture its socket filter does not cover. The settings are in [`extractor/README.md`](https://github.com/ClickHouse/loom/blob/main/extractor/README.md). ## The artifact | Part | Holds | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `blocks` | the source's structure in order: `heading`, `paragraph`, `list`, `code`, `sql_statement`, `toml_table`, `toml_key`, ...; each with its text, locator, section path and parent | | `tables` | the tables a source holds: each a name, typed columns, its rows of values, a header row count and a locator (CSV, XLSX, PDF, Parquet) | | `coverage` | the unit the format is made of (`lines`, `statements`, `keys`, `chars`, `pages`, `paragraphs`, `slides`, `rows`), how many there are, how many extracted, each failed unit with its reason, and each capability lost | | `warnings` | facts a reader should see, such as an ambiguous SQL dialect | | `options` | the overrides the parse ran with (`sql_dialect` for SQL only, `encoding` by its codec name) | | `attrs` | format facts (`dialect`, `dialect_source`, `dialect_candidates`; an HTML page's or a PDF's `title`; a PDF's `pages` and `furniture`, a deck's `slides`, a workbook's `sheets`; `images_unread`, the PDF pages or PPTX slides of text whose pictures, charts, diagrams or embedded objects are not read) | A block's `id` is `b`, stable within its artifact. `keys` are the exact names a reader can look the block up by: the objects a SQL statement creates, writes and reads, and its columns (for a statement sqlglot cannot parse, every name its tokens hold), every qualified name also by its last part (`events` for `analytics.events`), unquoted (`my.table` for ``db.`my.table` ``; a quoted part keeps its dots); a TOML table's or key's full path and its index-free form. A locator sets only the fields that apply: `line_start`/`line_end` (1-based) on every text format, `char_start`/`char_end` (offsets into the decoded text) on Markdown, plain text, SQL and the text blocks of an invalid TOML file, `key_path` for TOML, `page_start`/`page_end` (1-based) for a PDF's pages and a PPTX deck's slides, and `sheet` and `row_start`/`row_end` (the header counted) for a workbook's sheets and a CSV file's rows, and a PDF table's rows with their pages. A DOCX has no pages of its own (pagination is the renderer's), so its blocks carry no locator and a citation names their section path. A Markdown heading's span covers its source line or lines, markup included, while its text is the cleaned title, so a window of a long heading cites the heading's whole span. A chunk cut from several blocks spans their lines, characters, pages and rows, and keeps a sheet when all of them name one. The artifact is serialized as sorted, compact JSON with a `schema_version` and addressed by the SHA-256 of those bytes. A parser or option change produces a new artifact of the same source revision; an artifact is never edited. A reader refuses a `schema_version` it does not know. `parser_version` names what a parse depends on: sqlglot's version for SQL, pypdf's for PDF (and Tesseract's when OCR read a page or a slide), and the Python version for HTML, TOML, CSV and XLSX, whose parsers ship with it (`csv` and its sniffer; `datetime.fromisoformat` for an XLSX date written as text). ## Formats in the reference extractor How well the PDF, DOCX and PPTX readers keep a document's text, headings, tables and pages, against a layout-model baseline, is measured in the [document-parsing results](/docs/benchmarks/results#document-parsing). `detect_format` reads the bytes before the file name. A PDF, a DOCX, PPTX or XLSX container (by the parts inside the zip) and a Parquet file are recognised by content; a name that claims a format the bytes are not is refused (`format_mismatch`), and a legacy binary Office file is refused (`unsupported_format`), as is a `.doc`, `.xls` or `.ppt` name unless a format is declared. Text is decoded strictly: UTF-8, UTF-16 or UTF-32 by its byte-order mark, or a declared encoding, and a UTF-8 byte-order mark is dropped when the text is UTF-8, declared or not, as is the mark of a declared byte-order codec (`utf-16-le`). An undecodable byte is an `encoding` failure naming its offset, and a NUL byte in undeclared UTF-8 text (behind a byte-order mark or not) is binary; neither is replaced and indexed. | Format | Parser | Blocks | | ---------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | Markdown | a block parser after CommonMark's heading, fence and HTML-block rules | headings, paragraphs, lists, fenced code, front matter | | Plain text | a paragraph splitter | one paragraph per run of non-blank lines (a `#` line is text, not a heading) | | HTML | the standard library's parser | headings, paragraphs, list items, tables, quotes, definitions, `pre` | | SQL | `sqlglot`, never executed | one block per statement | | TOML | `tomllib` and a line scanner | one block per table header and per key | | PDF | `pypdf`: its text runs' positions and the lines it draws; OCR | per page: headings, paragraphs, lists, code, tables; furniture left out | | DOCX | the standard library's zip and XML readers | headings, paragraphs, lists, tables, footnotes and endnotes | | PPTX | the standard library's zip and XML readers | per slide: its title as a heading, each text shape, tables, speaker notes | | CSV | the standard library's `csv` | one table; its rows as blocks of up to 20 rows | | XLSX | the standard library's zip and XML readers | per sheet: a table, its name as a heading, its rows as blocks of up to 20 | | Parquet | `pyarrow`, from the bytes in memory | one table; its rows as blocks of up to 20 rows | **Markdown.** Headings are ATX, setext and one-line ``. A paragraph over a setext underline (indented up to three spaces) is one heading; a list item, a quote or a thematic break over `---` is not. A fenced block keeps its body's lines without the fences; a fence closes on a bare run of its character at least as long, and its language is the info string's first word, the rest kept as `info` (an empty block keeps it too). Inside a paragraph only a bullet or an item numbered 1 starts a list, so a wrapped line that begins `2019.` stays prose. A thematic break (`***`, `- - -`) is markup: it ends the paragraph or list above it and is no block's text. An HTML block is one paragraph block, as written, and never a heading's title (CommonMark's start conditions): one opened by a comment, ``) or a raw-text tag (`
`, `