# 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
Loom is a memory, document and code-index server for AI agents, stored in ClickHouse,
with [Postgres](/docs/architecture/storage-authority#why-two-stores) as an option for live
memory and knowledge state. Agents and people reach it over MCP, HTTP, the Python and
TypeScript SDKs, and the dashboard. This page lists every page in reading order.

## Start here
| Step | Read |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Decide | [Overview](/docs/getting-started/overview) → [Evaluate Loom](/docs/getting-started/evaluate) |
| 2. Install | [Quickstart](/docs/getting-started/quickstart) → [Deployment](/docs/operations/deployment) |
| 3. Connect agents | [Connect a coding agent](/docs/getting-started/connect-a-coding-agent) → [Integrations](/docs/features/integrations) |
| 4. SDK and API | [Your first agent](/docs/getting-started/first-agent) → [Python SDK](/docs/reference/python-sdk) / [HTTP API](/docs/reference/http-api) |
| 5. Namespaces and access | [Identities and namespaces](/docs/concepts/identities-and-namespaces) → [Tokens and grants](/docs/guides/tokens-and-grants) |
| 6. Code index | [Code index](/docs/features/code-index/overview) → [Repositories](/docs/features/code-index/repositories) → [Code-index operations](/docs/operations/code-index-operations) |
| 7. Operate | [Monitoring](/docs/operations/monitoring) · [Troubleshooting](/docs/operations/troubleshooting) · [Upgrades](/docs/operations/upgrades) · [Backup and recovery](/docs/operations/backup-and-recovery) |
## Use cases
One page per need, each saying what Loom does for it and where to start:
[agent memory](/docs/use-cases/agent-memory) ·
[document search and RAG](/docs/use-cases/document-search) ·
[knowledge factory for AI agents](/docs/use-cases/knowledge-factory) ·
[code index for coding agents](/docs/use-cases/code-intelligence) ·
[repository Q&A without a checkout](/docs/guides/repository-questions) ·
[code index by language](/docs/use-cases/code-intelligence-by-language) ·
[memory linked to code](/docs/use-cases/memory-linked-to-code) ·
[coding-agent model cost](/docs/use-cases/coding-agent-cost) ·
[multi-agent shared context](/docs/use-cases/multi-agent) ·
[autonomous agents: recall, audit, erasure](/docs/use-cases/autonomous-agents) ·
[runs, traces and PR history](/docs/use-cases/runs-and-pr-history) ·
[self-hosted on ClickHouse](/docs/use-cases/self-hosted-clickhouse) ·
[all use cases](/docs/use-cases).
## 1. Getting started
- [Overview](/docs/getting-started/overview): what Loom is, when it fits, prerequisites.
- [What's included](/docs/getting-started/whats-included): Loom's main capabilities, each with its page.
- [Quickstart](/docs/getting-started/quickstart): the local stack end to end.
- [Configure models and API keys](/docs/getting-started/models-and-keys): agent subscriptions,
server LLMs, embeddings and single-provider setups.
- [Evaluate Loom](/docs/getting-started/evaluate): smoke test, workload evaluation and
reproducible public benchmarks.
- [Connect a coding agent](/docs/getting-started/connect-a-coding-agent): plugin or MCP entry.
- [Set up Loom with your coding agent](/docs/getting-started/agent-setup): for an agent that
installs a pinned release and proves it works, with a fixed report.
- [Your first agent](/docs/getting-started/first-agent): an SDK tutorial.
## 2. Install and run the server
- [Deployment](/docs/operations/deployment): shapes, environment, providers, identity modes,
proxy, images, production checklist.
- [Single sign-on](/docs/operations/sso): an OIDC identity provider for the dashboard,
`loom login` and MCP clients.
- [Use Loom without the dashboard](/docs/guides/without-the-dashboard): `loom login`, `loom call`
and the SDK call for every dashboard view.
- [Upgrades](/docs/operations/upgrades) · [Supported versions](/docs/operations/supported-versions) ·
[Backup and recovery](/docs/operations/backup-and-recovery) ·
[Monitoring](/docs/operations/monitoring) · [Maintenance](/docs/operations/maintenance) ·
[Runtime settings](/docs/operations/runtime-settings) ·
[Troubleshooting](/docs/operations/troubleshooting) ·
[Code-index operations](/docs/operations/code-index-operations) ·
[Running N replicas](/docs/operations/replicas): identical Looms behind one URL ·
[Postgres](/docs/operations/postgres): the Postgres memory authority ·
[Kubernetes](/docs/operations/kubernetes): the Helm chart, with EKS and kind overlays ·
[ClickHouse Cloud and Managed Postgres](/docs/operations/clickhouse-cloud): the chart over
both managed services ·
[Copying a namespace to another Loom](/docs/operations/okf-sync) ·
[Exporting usage to a data warehouse](/docs/operations/analytics-export)
## 3. Connect agents
[Integrations](/docs/features/integrations) ·
[MCP clients](/docs/features/integrations/mcp-clients) ·
[Agent instructions](/docs/features/integrations/agent-instructions) ·
[Claude Code](/docs/features/integrations/claude-code) ·
[Codex](/docs/features/integrations/codex) · [Cursor](/docs/features/integrations/cursor) ·
[VS Code](/docs/features/integrations/vscode) ·
[Frameworks](/docs/features/integrations/frameworks) ·
[Grep shim](/docs/features/integrations/grep-shim) ·
[Langfuse](/docs/features/integrations/langfuse) ·
[ClickStack](/docs/features/integrations/clickstack) ·
[OKF](/docs/features/integrations/okf)
## 4. SDK and API
[Reference index](/docs/reference) · [HTTP API](/docs/reference/http-api) ·
[MCP](/docs/reference/mcp) · [Python SDK](/docs/reference/python-sdk) ·
[TypeScript SDK](/docs/reference/typescript-sdk) · [Environment](/docs/reference/environment) ·
[Operations](/docs/reference/operations) · [Configuration](/docs/reference/configuration) ·
[Workers](/docs/reference/workers) · [CLI](/docs/reference/cli) · [Errors](/docs/reference/errors) ·
[Status](/docs/reference/status) · [Schema](/docs/reference/schema) ·
[Extractor contract](/docs/reference/extractor-contract). Operations and fields change between releases;
[unknown and removed fields](/docs/reference/http-api#unknown-and-removed-fields) says how a
client sees one the server no longer reads.
## 5. Namespaces, access and the memory model
- [Identities and namespaces](/docs/concepts/identities-and-namespaces): the tuple, roles,
grants and read scope.
- [Memory](/docs/concepts/memory): the row, how a write is judged, time, history,
provenance.
- [Retrieval and ranking](/docs/concepts/retrieval-and-ranking): legs, fusion, abstain,
calibration.
## Guides
[Agent integration](/docs/guides/agent-integration) ·
[Headless bots](/docs/guides/headless-bots) ·
[Tokens and grants](/docs/guides/tokens-and-grants) ·
[Trace and resume long runs](/docs/guides/trace-and-resume) ·
[Choose AI software factory tools](/docs/guides/software-factory-tools) ·
[Optimize a namespace](/docs/guides/optimize-namespace) ·
[Investigation-agent memory](/docs/guides/investigation-agent-memory) ·
[Extraction pipelines](/docs/guides/extraction-pipeline) ·
[Performance tuning](/docs/guides/performance-tuning) · [Debugging](/docs/guides/debugging) ·
[Query Loom from Postgres](/docs/guides/query-from-postgres) ·
[Teaching with Loom](/docs/guides/teaching)
## Features
- Planes: [namespaces and sharing](/docs/features/namespaces-and-sharing) ·
[unified search](/docs/features/unified-search) · [knowledge](/docs/features/knowledge) ·
[entity graph](/docs/features/entity-graph) ·
[conversations and sessions](/docs/features/conversations-and-sessions) ·
[runs](/docs/features/runs) · [tasks and decisions](/docs/features/tasks-and-decisions) ·
[dashboard](/docs/features/dashboard)
- Memory: [writing](/docs/features/memory/writing) ·
[search and ask](/docs/features/memory/search-and-ask) ·
[conflicts and refusal](/docs/features/memory/conflicts-and-refusal) ·
[extraction](/docs/features/memory/extraction) ·
[history and provenance](/docs/features/memory/history-and-provenance) ·
[retention and erasure](/docs/features/memory/retention-and-erasure) ·
[procedures and learnings](/docs/features/memory/procedures-and-learnings) ·
[working memory and profiles](/docs/features/memory/working-memory-and-profiles)
- Observability: [audit](/docs/features/observability/audit) ·
[cost and usage](/docs/features/observability/cost-and-usage) ·
[telemetry](/docs/features/observability/telemetry)
- Tracker: [overview](/docs/features/tracker/overview) ·
[record contract](/docs/features/tracker/record-contract)
## 6. Code index
[Overview](/docs/features/code-index/overview) ·
[Repositories](/docs/features/code-index/repositories) ·
[Freshness](/docs/features/code-index/freshness) ·
[History and PRs](/docs/features/code-index/history-and-prs) ·
[Operations](/docs/features/code-index/operations) ·
[Code-index operations runbook](/docs/operations/code-index-operations)
## Architecture
[System overview](/docs/architecture/system-overview) ·
[Server layout](/docs/architecture/server-layout) ·
[ClickHouse](/docs/architecture/clickhouse) ·
[Memory architecture](/docs/architecture/memory-architecture) ·
[Storage authority](/docs/architecture/storage-authority) ·
[Cells](/docs/architecture/cells) ·
[Storage layout](/docs/architecture/storage-layout) ·
[Code-index architecture](/docs/architecture/code-index-architecture) ·
[Document extraction](/docs/architecture/document-extraction) ·
[Document sources](/docs/architecture/document-sources) ·
[LLM and embeddings](/docs/architecture/llm-architecture) ·
[Security](/docs/architecture/security) ·
[Assistant design](/docs/architecture/assistant) ·
[Failure and recovery](/docs/architecture/failure-and-recovery) ·
[Rolling upgrades](/docs/architecture/rolling-upgrades)
## Benchmarks
[Overview](/docs/benchmarks/overview) · [Coverage](/docs/benchmarks/coverage) ·
[Methodology](/docs/benchmarks/methodology) ·
[Running](/docs/benchmarks/running) · [Results](/docs/benchmarks/results) ·
[Adding a case](/docs/benchmarks/adding-a-case) · [Skill eval](/docs/benchmarks/skill-eval)
## Development
For contributors: [repository guide](/docs/development/repository-guide) ·
[local development](/docs/development/local-development) ·
[testing](/docs/development/testing) · [code generation](/docs/development/code-generation) ·
[migrations](/docs/development/migrations) ·
[release process](/docs/development/release-process) ·
[documentation style](/docs/development/documentation-style) ·
[curation loop design](/docs/development/curation-loop-design) ·
[extending Loom](/docs/development/extending-loom) ·
[add an operation](/docs/development/adding-an-operation) ·
[add a worker](/docs/development/adding-a-worker) ·
[add a table](/docs/development/adding-a-table) ·
[add language support](/docs/development/adding-language-support) ·
[dashboard design](/docs/development/dashboard-design).
[CONTRIBUTING.md](https://github.com/ClickHouse/loom/blob/main/CONTRIBUTING.md) covers the pull-request workflow.
## Also
[Glossary](/docs/glossary): Loom's terms, defined once. [FAQ](/docs/faq): the first questions, one
paragraph each. [`llms.txt`](https://github.com/ClickHouse/loom/blob/main/llms.txt): a generated index of the docs for agents;
[`llms-full.txt`](https://loom.clickhouse.com/docs/llms-full.txt) holds, in one file, the
pages that say what Loom is and how to start.
---
# 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
This page is the design of Loom's assistant, which answers questions about what a
namespace holds and how it is used, with a citation for every claim. It names the
surfaces, how each caller's identity reaches the agent's tools, the analysis op and its
isolation, the deployment, what is stored and erased, and the cost. Every part is built
but the analysis key's rotation, which is design; [the build order](#build-order) lists
the parts.
LibreChat is the assistant: it hosts the agent (its model, instructions and tools) and
runs it headless beside Loom, reachable only from Loom. Loom supplies the agent's tools,
which read under a token of the asker's own subject, and a read-only SQL op that
ClickHouse itself holds to that token's org and namespaces. People chat in the
dashboard's Ask AI panel, opened from the header's Ask AI button beside the search
field, or ask in the header search, which answers a question in place and goes on in the
panel; agents and scripts reach the same agent over HTTP, MCP and both SDKs, through
Loom's origin and as themselves.
## Surfaces
```mermaid
flowchart LR
P["person, signed in"] --> D["dashboard assistant panel"]
A["agent or script"] --> S["SDK / HTTP / MCP"]
D --> B["Loom assistant bridge"]
S --> B
B -->|"agents API: service key + this answer's token"| LC["LibreChat, headless (the Loom agent)"]
LC -->|"MCP, that token"| T["assistant toolset"]
T --> Q["insights.query"]
Q --> U["ClickHouse user loom_analyst column grants + signed row policies"]
```
| Surface | What the caller calls |
| --------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Dashboard | the assistant panel, streaming from `POST /v1/assistant/chat/completions` with the signed-in session |
| HTTP | `POST /v1/assistant/chat/completions`: LibreChat's agents API request and response, OpenAI-compatible, streaming or not |
| SDKs | a thin `assistant` client in Python and TypeScript over that route, with streaming; it holds no agent logic |
| MCP | the `loom_assistant_ask` tool (op `assistant.ask`), which forwards one question and returns the whole answer |
| HTTP, op shaped | `POST /v1/assistant.ask` and the generated `ops.assistant.ask` / `loom.assistant.ask` SDK methods, from the same op |
Each request names its namespace: the `X-Loom-Namespace` header on the chat route (the
token's default namespace when absent), the `namespace` field on `assistant.ask`. The
caller needs `viewer` there, and the answer's model spend is charged there. The chat
route, `assistant.ask` and its MCP tool, the generated SDK methods, the SDKs' streaming
clients (`agent.assistant.stream` in Python, `loom.assistant.stream` in TypeScript) and
the dashboard's chat are built.
`loom_assistant_ask` is in no curated MCP roster and, while `experimental`, not in the
`all` listing either: each call spends model budget, so an agent calls it by name on
purpose, as every unlisted op can be called. It is never in the
[assistant toolset](/docs/reference/mcp#the-assistant-toolset), so the agent cannot call
itself.
LibreChat's web UI and API are not published: LibreChat listens on an internal network
only Loom reaches. A person has one sign-in and one URL, Loom's. The
[LibreChat integration](/docs/features/integrations/librechat), in which each person
runs LibreChat's UI with a pasted token, is a separate, optional client; this
deployment needs none of it.
**Why LibreChat hosts the agent.** One agent definition, versioned in
`integrations/librechat/`, serves every surface. LibreChat runs the model, the tool
loop, streaming and cancellation, which Loom would otherwise build a second time. Loom
keeps what makes an answer trustworthy: authorization on every tool call, the request
ledger, the analysis boundary in the database, and the citation check.
**Why a native chat, not LibreChat's UI in a frame.** A frame would put a second origin,
a second sign-in and LibreChat's look inside the dashboard, and would need LibreChat's
cookies to work in a third-party frame. The dashboard's assistant panel uses Loom's
session and components, and links verified citations into the memory and document views
([the assistant panel](/docs/features/dashboard#ask-ai) has its rules).
## The bridge: each caller's own identity
Before checking model spend, the bridge reads the authorized namespace's public
mirrored-source registrations. Any active registration marks the complete answer,
even when its tools admit no document. The chat route sends `data: {"mirrored":true}`
as its first SSE event, or `mirrored: true` as its whole response's first field.
`assistant.ask` carries the same first field. A marked refusal carries it too. This
decision also routes the answer's cost row to private storage and suppresses public
diagnostics before subsequent model, budget or tool work.
Marked operation results carry the same server-owned flag after their typed output is
serialized. HTTP success responses retain it before post-handler rows. MCP success
responses retain it in the outer envelope, tool result, structured content and canonical
JSON text. The search tool's prose summary follows a separate first JSON marker block,
so consuming its text blocks in order observes protection before the summary. Ordinary
unmarked results keep their existing shapes.
The answer token keeps the caller's `session_protection` promise and a separate
`answer_mirrors` admission bit. Only an already marked answer for a declared caller
receives positive admission. Missing or false admission disables its mirror legs,
including when a source becomes active during an initially ordinary answer. Ordinary
namespace reads retain their authorization. Current ACL checks still decide each
mirrored item; the bit grants no access by itself. Ordinary delegated children omit
both claims and cannot regain mirror admission through a request header. An answer
token or any descendant cannot start another assistant answer.
Streaming output is provisional until `[DONE]`. The response owns its required
accounting lifetime beyond HTTP headers: it closes and joins model and citation work,
captures final usage once, and confirms private cost delivery before sending `[DONE]`
or a terminal error. Disconnects join producer cleanup and required delivery before
propagating cancellation. A failed cost write cannot publish a completed answer.
Whole answers and checked tool responses retain their accounting-before-publication
boundary. Incremental text precedes final usage, so its completion boundary is the
terminal event. A streaming client must reject EOF without `[DONE]` as incomplete.
Mirrored-source creation stays unavailable until every serving build and consumer
implements the admission, first-output marker, session and accounting boundaries.
An older verifier accepting an unknown claim does not enforce it; schema equality
does not establish this capability. The fleet and rollback requirements in
[rolling upgrades](/docs/architecture/rolling-upgrades) still apply.
LibreChat's agents API authenticates a LibreChat API key and runs the agent as that
key's LibreChat user. The agent's tools are Loom's MCP server, and what they may read is
decided by the token on each tool call, never by the LibreChat user. LibreChat v0.8.8
fills an MCP header from three fields of the request body (`ALLOWED_BODY_FIELDS`:
`conversationId`, `parentMessageId`, `messageId`), substituting the value as it is. The
agents API takes `parent_message_id` from the caller as any string and, on a request
with no `conversation_id`, uses it only for that field and as the anchor of a thread of
files, which finds nothing with no stored conversation and the file tools off. So the
bridge sends a token there, and the agent's MCP server sends it back to Loom. The
LibreChat qualification runs this path, so an upgrade of LibreChat that changes it fails
there before it ships:
```yaml
headers:
Authorization: "Bearer {{LIBRECHAT_BODY_PARENTMESSAGEID}}"
X-Loom-Run-Id: "{{LIBRECHAT_BODY_MESSAGEID}}"
```
They go under `headers`, not LibreChat's chat-only `requestHeaders`: those are left off
the connection that lists the tools, whose `tools/list` would then go out without the
token and leave the agent with no tools.
The bridge (`server/assistant/app/bridge.py`, `routes.py`) serves a request in three
steps:
1. Verify the caller's Loom token or dashboard session as on any op, and its `viewer`
role on the request's namespace. The chat route takes the same `Origin` and CSRF
checks as `POST /v1/{op}`. Refused here, before LibreChat is called: a revoked or
expired caller, an assistant answer's own token or one delegated from it
(`ASSISTANT_SELF_CALL`), an org-wide (`*`) token (an answer reads one org), a token
whose reads are narrower than its namespace (as `insights.query` refuses it), a caller
whose token has less life left than one answer may run (a dashboard or `loom login`
caller is not refused for its access token, which a refresh replaces every hour: its
answer's token ends at sign-out instead), an org whose model calls an admin
switched off (`org.set_model_calls`), and a namespace over its assistant budget or
running its most concurrent answers ([Model and cost](#model-and-cost)). A refusal a
client words for its reader carries `detail.reason`: `ASSISTANT_UNAVAILABLE` names
`not_configured` (no LibreChat), `auth_off`, `starting` (this process has not set the
service up yet, or is setting it up again) or `failing` (its last try failed; the setup
loop retries), and `AUTH_INSUFFICIENT` names `org_wide`, `narrowed` or
`token_expires_soon` (with `left_s`); a caller without `viewer` on the namespace
carries none. Where an assistant is configured, `/v1/health/ready` reports an
`assistant` check, never required (a deployment whose assistant is down still serves
the rest), whose reason is `starting`, `failing` or `auth_off`; a missing check means
none is configured.
2. Delegate the answer's token from the caller's (`server/auth/delegation.py`
`delegate`): `viewer` on the request's namespace alone, minted for the caller's own
subject with consumer `loom-assistant` and an id starting with `assistant-answer-`
(so a token delegated from it is told by its `parents`), as a service-account token
when the caller's is one, and expiring when an answer may run no longer
(`LOOM_ASSISTANT_ANSWER_TTL_S`, default ten minutes). Delegation applies every rule a
minted child follows: the creator's live grant, the end user, the ancestor subjects
and their issue times, the chain depth limit, and the caller's token id among the
child's `parents`. The bridge also asks for the caller's sign-in session among the
`parents` (`delegate`'s `ends_with_session`), so a dashboard or `loom login` caller's
answer token ends at sign-out, as a third-party client's already does. The token is
not listed in `loom.service_accounts`: it lives for one answer.
3. Call LibreChat's agents API with Loom's service key, the seeded agent's id in place
of any `model` the caller names, the answer token as `parent_message_id`, and the
text of the caller's `user` and `assistant` messages (no `system` message, which
would override the agent's instructions, and no files or images). Stream the response
back with `Accept-Encoding: identity`. A caller that disconnects, or the chat's stop
button, closes the upstream request, and LibreChat aborts the run. The bridge drops
any `conversation_id` in the caller's body: on this path LibreChat stores no
conversation, so it answers 404 for one it is given.
An answer's token reads no more than the caller's own token, and ends no later than it,
except under a sign-in session: every child of a first-party session takes the lifetime
it asks for, so an answer's token lives one answer's limit
(`LOOM_ASSISTANT_ANSWER_TTL_S`) and may outlive the hour-long access token it was
delegated from, or a session that expires during the answer, by at most that limit. It
is ended with its caller: revoking the caller's token, its subject, its sign-in session
or a subject in its `creator` or `parent_subjects` chain ends the answer's token
too, since delegation puts each of them in its revocation check. LibreChat holds the
token in memory for the one request and stores it nowhere; the deployment sets none of
LibreChat's tracing variables, which would export the run's request body, and the
qualification searches LibreChat's logs for a token it sent.
**One LibreChat user, which reads nothing.** Every answer runs as one LibreChat user,
Loom's service user, which owns the agent definition. Its API key runs the agent, but
the agent's tools read only with the token each request carries: a request without one
gets `401` on every tool call, and a request with one reads as that token. The key is
therefore not a credential that reads anything in Loom. One row of
`loom.assistant_service`, a `ReplacingMergeTree(version)` table, holds the service
user's email, the agent's id, the version and model of the definition last written, and
one sealed value (`server/core/secrets_at_rest.py`) holding a random password and the
agents API key together, so a reseal rewrites both at once. `loom secrets reseal` (which
takes [`analysis.entities`](#provisioning), then `assistant.service`) covers it when the
root secret (`LOOM_JWT_SECRET`) is replaced, and the deployment carries no second
secret.
Setting the service up is one step that a boot runs holding the cluster lease
`assistant.service` (`server/core/leases.py`), so two boots never run it at once; the
holder re-reads the row (as every read of it, with the read-your-writes setting
`own_write_reads` in `server/core/ch.py`) and does only what is missing, storing each
result on the row before the next, and signs in at most once (twice when it registers
the user), at the first step that needs LibreChat:
1. No row: write the email and a sealed random password.
2. No key: sign in, registering first only when LibreChat answers that the email does
not exist (LibreChat words a wrong password the same way but for its text, so the
qualification pins that answer), delete any key of the service user's that a boot cut
short left behind (keys carry the definition's name), then create the key.
3. No agent id: list the service user's agents by the definition's name, keep the oldest
and delete the rest, or create the agent when there is none, and store its id.
4. A stored definition older than this build's, or of the same version with another
model: write it and store its version and model on the row.
A boot that stopped halfway leaves the row at a step the next one finishes, and a boot
over a complete row checks with the stored key that LibreChat still holds the key and
the agent, making either again when it does not ([Deployment](#deployment)). Answers run
on the stored key whatever a sign-in does. Two failures need an operator, and
`/v1/health` names each as `assistant_service_failing`: a row whose sealed value opens
with neither `LOOM_JWT_SECRET` nor `LOOM_JWT_SECRET_PREVIOUS` (set the previous secret
and run `loom secrets reseal`), and a sign-in LibreChat refuses with a 4xx other than
its 429 limit (its database restored from another deployment, say; v0.8.8 answers a
wrong password 404 `Incorrect password.`): empty it and run `TRUNCATE TABLE
loom.assistant_service`, and the next boot recreates both. A 5xx sign-in is LibreChat or
its database being unavailable, which the next try asks again. A try that registers the
service user also makes a new key, since that user cannot own the one the row held.
Until the row has its key and agent id, the assistant answers `ASSISTANT_UNAVAILABLE`.
**Conversations live with the caller.** LibreChat's agents API (the OpenAI-compatible
`/api/agents/v1/chat/completions`) saves no messages: it runs the agent over the
messages in the request and records only token counts in its `transactions` collection.
A multi-turn chat is the caller's message list, which the dashboard keeps in the browser's
storage and an SDK caller sends each time, as with any OpenAI-compatible API. The agent's MCP
connection carries request-time headers, so LibreChat opens it for each answer and
closes it after; each answer pays one MCP `initialize` and `tools/list`.
**Citations.** The agent's instructions require a citation on each claim:
`[memory:@v]`, `[doc: § ]`, `[code::]`,
or a fenced `sql` block in the answer that holds the statement exactly as it ran. The
bridge checks each when the answer ends, inside the answer's slot and for at most ten
seconds in all (`server/assistant/app/citations.py`). A memory citation is verified when
one of the answer's own tool calls was returned its key: the exposure rows
(`loom.memory_exposures`) that the toolset's `memory.search`, `memory.ask`,
`memory.get`, `memory.list` and `memory.inspect` record under the answer's run,
whichever user or session the row is under (a search hit on one of a key's chunks counts
as its key). The assistant toolset drops any `run_id` a call names, so those rows are
filed under the answer's run; on `memory.search` the argument is also a filter to one
run's rows, which the assistant gives up. The exposure rows record keys, not versions,
so a memory citation's version is not compared. Only those reads record exposures: a key
returned by any other call (`memory.history`, `memory.provenance`, an `insights.query`
row) is not seen, and its citation comes back unverified with a reason that names the
reads that count; a fact a query found is cited by the query's `sql` block instead. A
`sql` block is verified when its digest is the `out_sql_digest` of an `insights.query`
call ledgered in this answer (`loom.agent_events`). A document citation's section must
be a heading path of a live document (`knowledge.outline`), and one with no section
verifies when the document is readable. The document is read through Loom's own routes
in process with the answer's token, so every gate a read passes applies to it, in a task
of its own (each check is a task of an `asyncio.gather`) so the read leaves the answer's
request state alone, and under no run id. A code citation is not checked: a code index
is a namespace of its own, which the answer's token (viewer on the answer's namespace
alone) does not reach, so `code.verify_citations` is not called for it. Nor are an
answer's citations past the fiftieth. The agent's MCP server sends the answer's message
id on each tool call as `X-Loom-Run-Id` (the agents API fills
`{{LIBRECHAT_BODY_MESSAGEID}}` with the id every chunk carries). On the assistant
toolset the MCP transport labels the call's ledger row with that header, in
`agent_events.run_id`, as HTTP already does; there the header wins over the session's
run label, and an answer's connection opens no session run, so the bridge reads the
answer's rows by the org, the namespace, that run id and the caller's subject, its
`insights.query` rows also by the consumer `loom-assistant` its token carries. A caller
who knows its answer's run id could plant a row of its own under it; such a row is the
caller's own call, so a citation it makes verified misleads only the caller. The rows
are written in the background and a tool call can land on another replica, so the bridge
waits up to five seconds for them; a citation whose row has not arrived by then, or was
dropped, comes back unverified. A check Loom refuses (a rate limit, an outage), a ledger
that cannot be read, an answer with no run id, a check past the ten seconds, or a
document read whose token expired (an answer that ran to its limit leaves its checks a
token near its end) leaves its citation unverified with the reason "the check could not
run", and never fails the answer. With memory reads not recorded
(`LOOM_MEMORY_EXPOSURE_LEDGER_ENABLED` off) a memory citation's reason is "this
deployment does not record memory reads". Each citation comes back marked
`verified` or not, with the reason and its `ref` (the memory key, document source,
documentation page or code path it names), in a last `loom.citations` event before the
stream's `[DONE]` (and a `citations` field on a whole answer and on `assistant.ask`),
with the answer's [support](#support). A streamed answer sends a `loom.text_done` event
when LibreChat's stream ends, before the checks start, so a client can show the text as
complete while they run (up to ten seconds); the answer's slot is held until
`loom.citations`. The dashboard shows "Checking sources…" under every streamed answer in
that time, since the checks read every streamed answer's run.
A help citation, `[help: § ]` (the section optional, its breadcrumb
starting with the page title as `help.search` returns it), is checked against the
replica's own index of the shipped docs: verified when the page is indexed and the
section is one of its own (its breadcrumb, the breadcrumb without the page title, or a
tail of it no other section of the page shares), with the section's `anchor`, which the
dashboard's Sources link to the Help page (`/help?page=#`). A page that is
not indexed, or a section the page does not have, fails as a document citation does. The
docs are the same for every caller, so the check reads nothing of Loom's. During a
rolling upgrade a bridge of the build before the kind does not parse it, and an answer
resting only on help citations shows as `none` there.
**Names.** The instructions allow an op or setting name only from a tool's result, and
the tool results stay with the agent, so the bridge checks what it can decide: each
backticked dotted name whose first part is an op group (`memory`, `knowledge`, ...) and
each `LOOM_*` name in the answer is known when the build serves it as an op, reads it
as an environment variable (a setting, `NON_SETTINGS_ENV`, a prefix family), or its
docs write it; a name ending in `_` is a family, known when one of those starts with
it. The rest come back in `unknown_names` beside the citations (the event's field and
`assistant.ask`'s), and an answer that writes one is `unsupported`, whatever it cites:
it may have invented the name. With no docs to read, none is reported. A name written
in prose, without backticks or the `LOOM_` prefix, is not checked.
### Support
Each answer comes back with `support` (on the `loom.citations` event, the whole answer
and `assistant.ask`), which says how far it rests on what Loom holds. The server decides
it (`server/assistant/domain/support.py`), from the codes its citation checks ended with
and, for an answer that cites nothing, from what its own tool calls found; the first
that applies wins:
| `support` | When |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `none` | The answer has no text; or it cites nothing and either says the abstention sentence the agent's instructions give ("Nothing stored in Loom answers this.", in any case or emphasis) or it made no call to an op whose rows it could cite and none of its calls found data or failed. A greeting, a capability reply and an abstention make no claim. |
| `supported` | A citation verified. |
| `unsupported` | It names an op or setting the build neither serves nor documents (`unknown_names`); or a citation failed for a reason of its own (its key was not returned to this answer, its document or section is not there, its statement did not run in this answer); or it cites nothing although a call of an op whose rows it could cite found data, or ran and found nothing while no other call found data or failed (a claim nothing backs). |
| `unchecked` | Otherwise: its checks could not say (a read failed or ran past its bound, no run id, memory reads not recorded, code citations, past the 50 checked), or it cites nothing and what found data has no citation form (counts and findings: the ops in `ASSISTANT_UNCITABLE_OPS`, such as `namespace.summary` and `namespace.inventory`), or a call failed. |
The ops whose rows an answer can cite, those whose output has no citation form, and
those that return no namespace data (Loom's own guide, documentation and catalog) are
sets in `server/operations/toolsets.py`, with the output list each op's ledger row
counts as `out_hits` (or its `found` flag) to say whether it found anything. A test
requires every op of the assistant toolset to be in exactly one set and to say how its
row shows it found nothing. The answer's calls are read by its run, its caller's subject
and the consumer `loom-assistant`, with no namespace filter (`ledger.run_rows`): a code
call is ledgered under the code namespace and a refused call under the sentinel. The rows
land in the background, so two patterns read them:
- A whole answer (`assistant.ask`, the chat route asked without `stream`) reads its calls
only when it cites nothing: once, and once more after the ledger's flush interval and
the batched-insert wait unless the first read already found a citable op's data.
- A streamed answer shows what it read under it ([steps](#steps)), so it reads its calls
on every answer, cited or not: once, after the same wait, beside its citation checks.
That one read gives both its support and its steps.
The reads and the waits are bounded at three seconds together, past which the answer is
`unchecked`. One read takes 200 rows; a run with more is cut, and a cut run keeps only an
outcome its first 200 rows decide (`unsupported` when a citable op found data there),
else it is `unchecked`. A presence answer of `code.symbol` finds only where the symbol is
present.
The rule reads no wording beyond the abstention sentence, and accepts these residuals:
- A greeting, capability reply or uncited question back after a citable call is
`unsupported` (`unchecked` when only ops with no citation form found data). The
instructions keep such calls rare: a greeting calls no tool, and a question back lists
each match with its citation.
- An uncited fact with no call at all (a later turn restating an earlier one, or a
first answer from the model's own knowledge, which the instructions forbid), or after
calls whose rows land past the wait or the re-read, or are dropped (the ledger keeps
them at most once), is `none`.
- A run of more than 200 ledger rows is judged on its first 200, so a citable op's data
past them is not seen: such an answer is `unchecked`, never `none`.
- A "not found" answer from a lookup that misses (`memory_get`, `code_symbol`) is
`none` when it ends with the abstention sentence, as the instructions ask for every
read that finds nothing; worded otherwise, it is `unsupported`.
- An abstention that also states a fact is `none`.
- An uncited answer from `help.search` and `help.get` is `none`, but `unsupported` when
a citable call of the same answer found data; the instructions ask for every docs
section used to be cited as `[help:...]`, which verifies.
- A document citation verifies when the document holds the section, whether or not this
answer read it; the instructions ask for a document to be read again before it is
cited on a later turn.
**Rendering.** The answer is model output that stored text can steer, so the dashboard
renders it as text with Markdown emphasis, lists, tables and code only: no HTML, no
images and no links in the answer's text but its citations, each drawn as a number by
where it first appears (`citationNumbers` in
`frontend/src/views/assistant/AnswerText.tsx`), which links to the citation's Sources
row once the check ends; the panel and the header search's card, a preview of the
answer, number an answer alike. The dashboard's `img-src 'self' data: blob:` already
stops a remote image that would carry rows away in its URL. Under a finished answer its
Sources (`frontend/src/views/assistant/Sources.tsx`) list each citation as the server
checked it, under one Sources label, each led by its number and named as the reader
knows it (a memory by its key, its kind and version in the row's tooltip): one found in
Loom opens, a memory in the memory drawer, a document in the Library and a help citation
on the Help page at its section, by the citation's `ref`; any other reads "not
confirmed" with its reason. A label above them says the answer's support in words,
leading with how many sources were found when some were not: "Checked against what Loom
holds", "Partly confirmed: n of m sources found in Loom", "Couldn't confirm: 0 of m
sources found in Loom", "Couldn't confirm: it names …" (an op or setting this Loom does
not have), "Couldn't confirm: it gives no sources", "Sources not checked" or "Not
checked: it cites nothing Loom holds"; an answer whose `loom.citations` never came (the
connection was lost after its text, or the page was left) reads "Check didn't finish".
Each label's "Why this label" note says why it reads as it does; an answer whose support
is `none` has no label. A value the dashboard does not know reads as `unchecked`.
### Steps
While a streamed answer runs, the bridge reads the answer's own calls from
`loom.agent_events` as their rows land and sends them as `loom.step` events, each carrying
the whole list so far (`steps`: `{op, text, ok}` per call, oldest first), so the dashboard
shows the latest as its working line. The read (`server/assistant/store/ledger.py`
`live_rows`) runs at once and then after 1 s, 2 s and every 4 s to the answer's end.
Before the first chunk gives the answer's run id it filters the org, the namespace, the
caller's subject, the consumer `loom-assistant` and the second before the answer started
(a second that takes the streaming replica's, the serving replica's and ClickHouse's
clocks to agree; under more skew a call shows only once the run id is known), so the calls
of the caller's other answers in the namespace that land before the run id is known
(another tab's, say) mix in, which progress text accepts. Once the run id is known it
filters by the run with no namespace (code and refused calls included), so another run's
calls are not read. Each step's words come from a fixed line per op of the toolset
(`server/assistant/domain/steps.py`, "Read the audit", "Couldn't search memories" for a
failed or refused call); a row of any other op is no step. A step shows once its call has
finished and its row has landed, up to four seconds later. A read that fails ends the
steps; the answer goes on. The steps are display only and never decide the label.
The `loom.citations` event then carries `steps` from the one read of the run after the
answer ends (above), which replace the live list: an empty list when the run made no call,
and no `steps` when that read failed or ran past its bound, when the dashboard keeps what
it showed live; and `steps_cut: true` when the run held more than 200 ledger rows. These
events and `loom.text_done` have `choices: []`, the run id (or none yet) as `id`, and no
model or usage, so a client that guards for no choices skips them; both SDKs skip
`loom.step` and `loom.text_done` and expose the final list as the answer's `steps`. A
whole answer and `assistant.ask` carry no steps and no `loom.text_done`.
### Starters and cards
The dashboard's panel lists starters, one per read that answers a question about the
namespace exactly: `namespace.inventory`, `namespace.audit`, `memory.inspect`,
`knowledge.inspect`, `mentor.brief`, `namespace.tune`, and a link to the Graph. A
starter's card is that read, made by the dashboard with the person's own session, not by
the answer: it is gated on the read's own role and scope, works while the assistant cannot
answer, and costs no model call (`frontend/src/views/assistant/cards/`). The starter also
asks the assistant its question when the person keeps "Also ask the model" on; the
question names the arguments the card was first read with (the audit's window, the
mentor's agent; the card's selects read it again with others, which the question then no
longer names), and its answer gets the same [support](#support) label as any other, the
card's own line ("Loom's own read") saying the card is exact. The cards live in the
conversation the browser keeps, a snapshot of up to 32 KB each; a card restored from
History is read again before any action. A draft's action is the person's own click on the
existing op under their own role (registering a category, the guide editor on top of the
guide read now) or a copy of the change; the answer's token stays `viewer` and the
assistant writes nothing. Cards come only from starters: a free-form question's tool calls
carry no arguments the dashboard could read again.
### Asking again
Ask again (Retry on a failed answer), an edit of the last question and "Ask again with
sources" answer the last turn again under its own id
(`frontend/src/views/assistant/chatStore.ts`), so another tab's
stored copy cannot bring the old answer back. The turn keeps its old answer, on screen and
in storage, until the new text begins: an attempt that fails, is refused, is stopped or
ends empty first puts the turn back as it was, as does a reload before then.
- **Try again** follows a refusal whose reason the panel shows, and any such ending of an
edit whose words changed. It answers that turn again with the words, page line and "with
sources" it was asked with, whatever the field holds. Another question, Cancel edit, a
new conversation or another one opened drops it.
- Any other ending of an Ask again (a rate limit, the cost cap, a lost connection), or of an
edit that left the words as they were, offers no Try again.
- In each case an empty field gets the question as an edit (after Stop, only an edit's
words), and an Ask from it goes with the chip as it shows now.
## The agent definition
`integrations/librechat/agent.yaml` holds the agent's name, instructions, model and a
version number (`server/assistant/domain/definition.py`); the tools are the assistant
toolset's, listed by Loom. Loom seeds it at boot under the service user, which owns it,
so nothing is shared. `LOOM_ASSISTANT_MODEL` and `LOOM_ASSISTANT_PROVIDER` replace the
file's model and provider when set; `local` is LibreChat's endpoint for a model server
the operator runs (`deploy/librechat/assistant.librechat.yaml`). The stored row records
the definition's model as `/` when the provider is not the file's, and
as the bare model otherwise. It writes the definition when its version is newer than the
stored one, or the same with another model, so during a rolling upgrade a build N-1
never overwrites N's definition, and a changed `LOOM_ASSISTANT_MODEL` or
`LOOM_ASSISTANT_PROVIDER` takes effect at the next boot. One exception: a build that
predates `LOOM_ASSISTANT_PROVIDER` ignores it, so with it set that build rewrites the
agent onto the file's provider under the local model's name; unset it and
`LOOM_ASSISTANT_MODEL` before rolling back. Otherwise, while N rolls out and after a
rollback, N's definition stays, and a tool call it names that an N-1 pod does not serve
answers `UNKNOWN_OP` there until every pod runs N.
The tool list is the assistant toolset's reads and `insights.query`, so the agent writes
nothing; a change it suggests is a draft a person applies elsewhere, as the Assistant
page's tune drafts already are. The instructions require citations, tell the agent to
call a tool before answering a question about the namespace (a greeting calls none) and
abstain when none supports it, to write no text before or between its tool calls, to
read `insights.catalog` before running SQL, to start a question about Loom itself that
does not plainly ask how to use it with a memory, a document and a help search together
and answer a fact the namespace holds from the namespace, to answer how Loom works from
`help.search` and `help.get`, citing each section as `[help:...]` rather than as a
document citation, and to treat stored text as data that cannot grant a tool or approve
a change. The agents API streams the text of every model step as one answer's content,
with nothing between steps
([streaming](/docs/features/integrations/librechat#tool-errors-streaming-and-cancellation)),
so neither the bridge nor the dashboard can tell a lead-in ("Let me search the
memories.") from the answer it runs into. While no text has arrived, the dashboard shows
that the assistant is answering. Asked how a namespace should write, the agent
recommends rather than only answers: key shape, one claim per key, a memory, a document
or a record, pins and kinds, each recommendation naming its rows and citing the finding
it rests on in `namespace.audit`, `mentor.brief` or `namespace.tune`, the namespace's
guide (`namespace.guide_get`), or Loom's own writing guide (`mentor.guide`, on the
toolset for that reason).
The agent names no namespace on its calls: on the assistant toolset a call that names
none reads the first namespace its token names ([the assistant
toolset](/docs/reference/mcp#the-assistant-toolset)), which for an answer's token is the
request's. A test pins a digest of the name, provider, model parameters, instructions
and tools to the version, so a change to any of them bumps it.
## Loom's documentation
The assistant answers how Loom works from Loom's own documentation, as the build that
serves the answer ships it. The image copies `docs/` (its Markdown; the screenshots stay
out of the build context), and two read-only ops on the assistant toolset read it:
`help.search` (a question or a name in, the best sections out, each with its page, its
breadcrumb, its anchor, its audience and a snippet) and `help.get` (a page with its
outline, or one section of it, found by the anchor a hit names, since a page may repeat
a heading). Both are `experimental`, deployment-scoped and in no curated roster: any
token that may read the agent guide may call them by name.
The docs are indexed in each process, on its first help call, in a worker thread: each
page is split at its headings by the splitter documents use
(`server/knowledge/domain/chunking.py` `detect_sections`), so a section's breadcrumb
starts with the page title as a document citation's does, and the sections are scored
with BM25 (`server/core/bm25.py`). Terms are the words, plurals and simple suffixes
folded, plus every whole identifier (`memory.set`, `LOOM_ASSISTANT_MODEL`), so an exact
op or setting name finds the line that names it. An operator section's score counts
three quarters, since most askers use Loom rather than run it. The index holds about
2,200 sections in about 14 MB and builds in about a second; a search reads only the
postings of its terms, and concurrent first calls share one build. A page that cannot
be read is left out with a warning, and a process with no docs answers
`available: false` until it restarts: the docs change only with the build, so a fault
never rebuilds the index per call. An answer that rests only on `help.search` and
`help.get` and cites nothing carries no support label, as one resting on `mentor.guide`
does: the docs are not the namespace's data. A read returns at most 16,000 characters,
and a cut one names the offset its rest starts at; a page read, or a cut one, adds the
page's outline.
**The page's context.** The dashboard's panel starts a question with one line about the page
it is asked from, `Context: page`, and with the item "Ask about this" named,
`Context: Memories page, memory "" (agent "", user "", session "")`,
`Context: Library page, document "" (title "")` or `Context: Recall page,
result , memory "", for the query ""`: a key or source URI the agent reads
with `memory.get` or `knowledge.get`. A memory's user and session are named when the drawer
read the row under them (a row filed under a user or a session), since `memory.get` takes
`user_id` and `session_id` and misses such a row without them; an answer's token reads the
whole namespace, so naming another user's row is a filter, not a widening. The line quotes
names that others wrote and the person's own query, each as a JSON string literal, so a quote
or a line break in one cannot end it: a key, a source URI, a user or a session exactly as
stored, never cut, and an agent, a title or the query on one line, cut at 200 characters. The
person sees it as a chip and can remove it before it is sent; it grants nothing, and no
server or wire field carries it
([the assistant panel](/docs/features/dashboard#ask-ai)).
**The asker's context.** An answer's token is `viewer` on one namespace, so the agent
cannot tell from it what the person asking may do. The bridge, which holds the caller's
own credential, puts one line in fixed words as the last line of the question it sends
LibreChat: `Loom, for how-to answers only: this question comes with , whose
role in this is .` The credential is `a sign-in session`, `a delegated
token` (one capped by the grant of whoever made it, a client token's included), `a
scoped token` (its role per namespace in its claim) or `a token`. The role is the
highest the gate admits, after the viewer check every answer passes (`admin`, `writer`
or `viewer`), or `unknown` when a check could not read what it needed. The place is
`personal collection`, `collection`, `restricted namespace` (the directory's cached
classification, no read) or `namespace`. The line names no subject and no namespace, so
nothing the caller controls is in it and no identity goes to the model provider through
it. It never refuses an answer. The instructions read it as Loom's only in that place,
treat it as granting nothing, and answer how a role is raised from the documentation for
that credential and place, naming the namespace's admins from `grants.list`. A bridge of
an earlier build sends no line, and an answer that depends on the person's role then
says it does not know it.
**Why not a knowledge source.** Knowledge rows are tenant data: an org and namespace on
every row, erasure coverage, and a copy per org or a read path across tenants. Indexing
them spends embedding calls, and replicas of two builds would share one copy during a
rolling upgrade, so one build would answer from the other's docs. The docs are the
same text for every caller, hold no tenant data and change only with the build, so
help keeps them out of ClickHouse: nothing is written, erased or embedded.
**Nothing is withheld by role.** Every page is in the public source tree, and
`tests/unit/test_public_copy.py` keeps hosts, keys and internal names out of it, so a
page withheld from a viewer would protect nothing. Each hit says its audience instead:
`operator` for running or building Loom (`operations/`, `architecture/`,
`benchmarks/`), `user` for the rest. The contributor pages (`development/`) are not
indexed. Help reads no environment, setting value or secret.
## 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 relation is `loom.analysis_agent_events`. It retains authorized request
participation and neutralizes marked model, spend, work and outcome fields before caller
filters, joins or aggregates. It unions ordinary `loom.agent_events` with
`loom.agent_events_private`; the analyst has no grant on the private table. The
ordinary table retains signed, namespace-scoped access for both serving builds and
rejects marked events and reserved mirror namespaces through its permanent CHECK.
The view's definer query applies the same signed org/namespace predicate as
the physical tables' row policies; it does not use SQL-account grants. The typed projection
is passed from the maintained event reader definition into the pure access-entity builder.
Its shape, signed predicate and security mode are part of 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 [part 2](#build-order) 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 not ClickHouse credentials in LibreChat.** 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 [part 2](#build-order), 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 does not rebuild the reader user. Its live
[event cutover](/docs/architecture/rolling-upgrades#analyst-event-storage-cutover) proves writer,
CHECK and policy visibility before grants. A shared service endpoint can supply
checked sessions for all replicas; separate replica addresses are not required.
If that endpoint cannot reach every writer, `LOOM_CH_ANALYSIS_OBSERVER_URLS` adds
trusted HTTP origins using the configured service credentials. Missing writers
and changes in a checked session refuse provisioning.
`loom ch-setup --print-analyst-sql` refuses with a nonzero result and prints no
statements or secrets. An unchecked SQL file cannot enforce the native access-catalog
proof, including a catalog hidden by its own policies. General `--print-sql` still
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 do not enter either log.
The allowlist lives in code with the column comments that become the agent's catalog, so
the grants, the policies, the masked event view 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 [part 2](#build-order)), 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
[part 2](#build-order), `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 [part 2](#build-order), 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 [part 2](#build-order)
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 [part 2](#build-order), 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, which the citation check reads. 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
`tests/integration/test_analysis_isolation.py`, in the style of
`tests/integration/test_cross_principal_leakage.py`, seeds two orgs, each with a
canary memory and a canary ledger row, and calls `insights.query` with the first org's
viewer token. Each case must be refused or return no canary:
- a filter on the other org, a namespace outside the token, a `JOIN` or subquery over
the same table, `UNION ALL`, `view(...)`, `merge(...)`, and a `throwIf` or
`sleepEachRow` on the other org's rows;
- `system.query_log`, `system.processes`, `system.row_policies`, `system.users`,
`information_schema`, `SHOW CREATE TABLE`, `DESCRIBE`, `KILL QUERY … TEST`,
`loom.signing_keys`, `loom.revoked_tokens` and a column outside the allowlist;
- `EXPLAIN` in each form, also after a `)` or comment that tries to leave the wrapper,
`mergeTreeIndex()`, `url()`, `file()`, `s3()`, `remote()`, `cluster()`,
`executable()`, `input()` and `aiGenerate()` with a named collection;
- on `loom.memory` itself: a deleted memory, a memory tombstoned by an erasure, and a
version a later one replaced, with `SETTINGS final = 0` and
`apply_row_policy_after_final = 0`;
- `SETTINGS send_logs_level`, `use_query_condition_cache` or `max_threads` past the
profile, and statements that set `log_queries_cut_to_length` or
`log_formatted_queries`, whose text stays out of `system.query_log`;
- `toUInt64(memory_key)` in the select list, `WHERE` and `PREWHERE`, also with
short-circuit evaluation off, filters moved or merged, and
`format_display_secrets_in_show_and_select = 1`: each is refused, and its error, in
the answer and in `system.query_log`, quotes only the caller's own row and no
spelling of the key;
- `SETTINGS` that change the scope, the caps, `readonly` or `use_query_cache`, the same
statement text run first by one org with the query cache and then by the other, a
scope sent with an expired or forged signature, and a scope one statement read with
`getSetting` sent with a later one by another org's token;
- a statement that is not a `SELECT`: `INSERT`, `ALTER`, `CREATE TEMPORARY TABLE`;
- both orgs' statements running at once;
- `SETTINGS` that set a scope value to a number, an array or a malformed string: no
answer quotes the policy or its key;
- an extra grant (`GRANT SELECT ON loom.* TO loom_analyst`) and a table with its policy
dropped, each of which the probe turns into `ANALYSIS_UNAVAILABLE` (under the
configuration Loom ships, a dropped policy reads nothing meanwhile; under the server
default, the probe closes the window), with and without access management for Loom's
user; a table taken off the allowlist, which reads nothing whether or not its grant is
still there;
- two boots writing at once (a build N-1 beside N with a table taken off the allowlist),
which the lease serialises, and a build N-1 beside N, which keeps answering on N's
entities and never writes them;
- a statement run while a write replaces the policies, which reads the right rows;
- an extra policy that widens what the analyst reads (`USING 1 TO loom_analyst`), which
the reserved-scope read catches and no write tries to repair; a build N-1 beside an N
that added a column and took a table off the allowlist, which keeps answering; and two
replicas with different cap settings, which write the caps at boot only;
- a canary under another key, which the probe catches, and a secrets row that does not
open or is gone while the user is not, which answers `ANALYSIS_UNAVAILABLE`;
- `--rotate-analysis-key` after a lost row and with `--live` on a healthy one, and, on a
server whose Loom user cannot list users, the printed SQL run in full on a first
install, over a lost row and over a healthy row, each followed by a statement that
answers with the right rows; `--rotate-analysis-key` refused when the CLI's secrets
are not the deployment's, and plain `loom ch-setup` refused over a lost row;
- cut short at every step, the rotation, the printed SQL and a first draw from storing
the row to writing the version, each of which leaves `ANALYSIS_UNAVAILABLE` or a state
the next run finishes with the stored key;
- `loom.analysis_secrets` and `loom.analysis_canary` read directly, and neither the
statement's text nor the key or its pads in `system.query_log` or the server log's
errors;
- reseal races:
- a reseal whose read comes before a printed rotation and whose insert after it, which
leaves the new key;
- one whose insert lands between the printed delete and the printed insert, which
answers the right rows or `ANALYSIS_UNAVAILABLE` (on one server, never an empty
answer), and then the new key;
- a rotation on one server:
- a statement running when it starts, which the `KILL QUERY` ends and which answers
`ANALYSIS_UNAVAILABLE`;
- a statement whose key was read before the delete and sent after the password change,
and one signed from a row a reseal put back, each of which answers
`ANALYSIS_UNAVAILABLE`;
- a lagging server, on the settle-time path:
- an old-credential statement, which reads the rows of the scope it signs until the
server applies the password change and fails to sign in after;
- a server that applies access changes within the settle time, which answers no wrong
row, and one slower than it, where a statement it serves returns no rows or fails to
sign in and a probe that reaches it answers `ANALYSIS_UNAVAILABLE`;
- the `clusterAllReplicas` confirmation:
- a rotation that stores its row only once every server's policy carries the new key;
- an old-key statement a lagging server started before its policy changed and still
running then, which the second `KILL QUERY` ends before the row is stored;
- a server down during the wait, which leaves the row unstored and analysis
unavailable;
- `loom doctor` and the probe's repair:
- within three settle times of the row's stored time, a finished rotation seen through
a lagging server, for which doctor names a longer settle time and the probe defers
its canary repair;
- past that, some probes passing and others failing, which it names as those servers'
problem, with the servers where the policy read shows them;
- a rotation stopped after the password change with a row a reseal put back, where
every probe fails to sign in:
- stopped before the policies, every server on the row's key: with the policy read,
on a cluster and on a single server, doctor names `--live`;
- stopped after them, every server on one other key: it names `--live`;
- without the policy read: it names both causes;
- every probe failing with servers on two keys, the row's and another, on any split
and behind a load balancer that pins every probe to one of them: it names the
admin's problem with both groups and asks to be run again once they agree;
- a load balancer that pins every probe to one server, with no policy read, where
every probe fails, for which it names both causes.
The cases for the key's rotation, the reseal races, lagging servers, `loom doctor`, two
builds side by side and a Loom user without access management come with part 2 of
[the build order](#build-order).
The same file shows that a revoked token stops new calls and that an erased memory
is gone from the next statement. A unit test pins the generated grants and policies to
the allowlist. The bridge's tests (`tests/unit/test_assistant_bridge.py`,
`test_delegation.py`, `test_assistant_service.py`, and `test_mcp_unauthenticated.py` for
the MCP endpoint) show that:
- an answer's token is never wider than the caller's token, never outlives it (under a
sign-in session, the answer's limit instead), and ends with the caller's token,
subject, creator or sign-out; a dashboard caller in the last minutes of its access
token is answered;
- a request to LibreChat without a token reads nothing, and one with a token reads as
it;
- a revoked caller, an answer token or its child, an org-wide token, a narrowed
`read_scope`, a caller about to expire and an org with model calls switched off are
refused before LibreChat is called;
- two replicas booting at once register one service user and keep one key, a service row
its maker left at any step is finished by the next boot, registration never runs where
LibreChat would log the password, `loom secrets reseal` rewrites both sealed rows
while a boot waits for the lease, and a boot whose read of the service row hits a
lagging replica still sees the row.
Not yet tested: a `sql` citation in a restricted namespace, and one whose tool call
landed on another replica (the five-second wait is what covers the second).
A probe of this boundary on ClickHouse 26.9, with a scratch table, user and policy of
this shape, showed each refusal in the table above, the query cache keeping the two
orgs' results apart, `EXPLAIN PLAN` printing the folded filter
(`has(['a1'], namespace) AND org = 'acme'`) with no key, and `aiGenerate()` refused for
want of a `NAMED COLLECTION` grant. On a `ReplacingMergeTree(version)` table with
`tombstoned_at`, as `loom.memory` is, the live predicate under forced `FINAL` hid a key
whose latest version was a tombstone and a key an `ALTER … UPDATE tombstoned_at` erased
on every version, brought back neither's earlier version, and refused
`SETTINGS apply_row_policy_after_final = 0`. Loom's own user kept ClickHouse's trivial
count optimization on a table with the `USING 1` policy. With the policy after `FINAL`,
one org of a thousand in a five-million-row table read 49,152 rows: the policy's `org`
filter still selects the parts and granules to read. The profile's `CONST` and `MAX`
pins refused `send_logs_level = 'trace'`, `use_query_condition_cache = 1` and a
`max_threads` above the cap, and admitted a lower one.
## Deployment
LibreChat runs beside Loom with its MongoDB in every deployment shape, reachable only
from Loom, and both run its v0.8.8 configuration,
`deploy/librechat/assistant.librechat.yaml`:
- **Compose:** the `assistant` profile starts `librechat` and `librechat-mongo`; neither
publishes a port. LibreChat shares the internal `assistant` network with the `loom`
service and the internal `assistant-db` network with MongoDB alone, so the `loom`
container, which builds repository code, cannot reach the database. LibreChat alone is
also on `assistant-egress`, a network of its own with a route out, for its model
provider (with `LOOM_ASSISTANT_PROVIDER=local`, a model server on the Docker host,
reached as `host.docker.internal`). Its secrets and model key come from `.env` beside
`compose.yaml` (`LIBRECHAT_CREDS_KEY`, `LIBRECHAT_CREDS_IV`, `LIBRECHAT_JWT_SECRET`,
`LIBRECHAT_JWT_REFRESH_SECRET`, `LIBRECHAT_ANTHROPIC_API_KEY`,
`LIBRECHAT_LOCAL_LLM_BASE_URL`, each named apart from
anything Loom reads, since the `loom` service loads the same `.env`), and its
configuration from
`deploy/librechat/assistant.librechat.yaml`, which the release's stack bundle ships.
- **Helm:** `assistant.enabled` adds LibreChat's Deployment and Service and a MongoDB
StatefulSet (`templates/assistant.yaml`), with the same configuration in a ConfigMap
naming the release's Loom Service, and the secrets from `assistant.existingSecret`.
LibreChat's NetworkPolicy admits only Loom's pods and lets it reach DNS, its MongoDB,
Loom's pods and TCP 443; MongoDB's admits only LibreChat and reaches nothing, and
Loom's own policy admits LibreChat when it names its peers. LibreChat runs one pod,
replaced rather than rolled, and restarts when its configuration changes. Both run
non-root on a read-only root filesystem; LibreChat writes its logs and uploads to
`emptyDir` volumes (`scripts/gates/helm_assistant_isolation.py` checks the render).
- **Settings:** `LOOM_ASSISTANT_LIBRECHAT_URL` names LibreChat's internal address; unset,
Loom sets up nothing, and the dashboard, which learns it from its boot snippet
(`window.__LOOM_ASSISTANT`), shows the panel without its chat: the starters still read.
`LOOM_ASSISTANT_MODEL` and `LOOM_ASSISTANT_PROVIDER` replace the definition's model and
provider.
Each replica sets the service up in its background at boot. Over a row that has its key
and agent, a boot asks LibreChat, with the stored key and no sign-in, whether the agent
is still there (`GET /api/agents/v1/models/`): a key LibreChat no longer knows
(`401`, its database replaced) makes the key step again, and a missing agent (`404`) the
agent step, so the next boot repairs either. A failed try is tried again after
`LOOM_ASSISTANT_SETUP_RETRY_S`, the wait doubling after each next failure up to 16 times
as long; from the first failed try until one succeeds `/v1/health` shows
`assistant_service_failing`, with the failure's kind and the text in the log only. Each
try signs in at most once (twice on the boot that registers the service user), every
process of a replica counts toward LibreChat's limit of
seven sign-ins per address in five minutes, and a sign-in refused for that limit is named
as such. LibreChat's signed-in routes refuse a client that is not a browser (they answer
status 200 with an `Illegal request` event), so the setup sends a browser user agent,
and its service user is named `loom-assistant` (LibreChat wants three characters).
LibreChat's configuration keeps the integration's memory off and search index out, and
gives the agents endpoint no capability but tools (no actions, which call any URL, and
no code execution, file search, skills, subagents or web search), so the agent's only
way out is Loom's tools. Its MCP server instructions are off: LibreChat reads them once,
at its own start and with no answer's token, so the agent's instructions carry the
rules. Its log level stays at `info`, which writes no message text. The deployment turns
violation bans off (`BAN_VIOLATIONS=false`) and the unverified-user expiry off
(`ALLOW_UNVERIFIED_EMAIL_LOGIN=true`, so LibreChat never deletes the service user it
registered without a mail server), so a burst of replica restarts cannot lock Loom out;
only Loom reaches LibreChat, so the bans protect nothing there, and registration stays
on (`ALLOW_REGISTRATION=true`) because only Loom can register. Within Loom, repository
code runs sandboxed with no route to LibreChat (`--unshare-net`; a job's egress proxy
reaches public hosts on ports 443 and 22 alone), except an operator repository's build
on a host without the sandbox, which already runs with Loom's own environment
([the repository-job sandbox](/docs/operations/code-index-operations#repository-job-sandbox)).
The configuration's agent and remote-agent permissions apply to every LibreChat role, so
the service user needs no particular one. LibreChat runs without Redis, so one replica
runs, and its run bookkeeping (each run's agent, model and ids, never the request) stays
in its own memory. LibreChat's registration logs its request, password included, when
the email is already in use or the request is malformed; Loom registers only under the
lease and only after LibreChat said the email does not exist, and the qualification
searches LibreChat's logs and database for the service user's password as it does for a
token.
## Stored data and erasure
| Where | What the assistant leaves | How it is deleted |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `loom.assistant_service` | one row: the service user's email and agent id, its sealed password and agents API key | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
| `loom.analysis_secrets` | one row: the analysis key and the analyst's password, sealed | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
| `loom.analysis_canary` | one constant row in a reserved scope, which the probe reads | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
| `loom.agent_events` | one row per bridge request and per tool call, under the answer's token | as every ledger row |
| LibreChat users, API keys, agents, sessions | the service user, its key, the agent definition and the sign-in sessions of each boot that signs in | kept; no memory content |
| LibreChat `transactions` | token counts per answer and its message id, no content | kept, a few hundred bytes per answer |
| LibreChat logs | the service user's id and email and request ids, no message text, token or password | LibreChat's default: one file per day, kept 14 days |
| ClickHouse's `system.query_log`, server log | each analyst statement without its text; a refused one's error, which can quote an allowlisted value | `system.query_log` and `system.text_log`: 30 days on the bundled and dev ClickHouse, no TTL in ClickHouse's default configuration; the file log rotates by size; erasure reaches neither |
| the dashboard | the person's conversations, in the browser's local storage | 30 days from last use; deleted at sign-out, by another person's sign-in, or by Delete |
An error ClickHouse raises on a statement can quote the value it failed on: a
`toUInt64(title)` refused on a title quotes the title. That value is one of the caller's
own allowlisted metadata columns (a key, a title, a user id), never a memory value or
document text. It is kept in `system.query_log`'s `exception` column and in the server
log (`system.text_log` included), which records every error whatever `log_queries` says,
on every install. ClickHouse Cloud pins `log_queries_min_type`, so the error rows cannot
be left out of `system.query_log` there, and Loom writes one profile for every install.
Erasure does not reach either log. The bundled ClickHouse and the Helm chart's dev
ClickHouse keep 30 days of `system.query_log` and `system.text_log`
(`deploy/clickhouse-config/system_logs.xml`).
ClickHouse's default configuration sets no TTL on either one, so on a self-managed server
the rows stay until an operator bounds them
([log retention](/docs/operations/deployment#log-retention)). Both are
read only by whoever administers ClickHouse and by Loom's own user.
The agents API stores no questions, answers or tool outputs, so LibreChat holds nothing
an erasure must reach. An answer is computed from the rows the answer's token reads at
that moment, so an erased memory is absent from every answer that starts after the
erasure. An answer streaming while an erasure runs can quote a row it read before; it
goes to its caller only and is stored nowhere, as any read in flight.
## Model and cost
The model is the agent definition's: `LOOM_ASSISTANT_MODEL` when set (Loom writes
it into the definition when it seeds), `claude-haiku-4-5` otherwise. The model runs in
LibreChat, on its own Anthropic key or on the operator's model server
(`LOOM_ASSISTANT_PROVIDER=local`), so Loom's provider layer does not call it, but Loom
holds its spend to the same budget as its own model calls:
- Before calling LibreChat, the bridge checks the namespace's daily model cost cap
(`server/observability/budget.py`, `daily_cost_cap_usd`, default
`LOOM_DEFAULT_DAILY_COST_CAP_USD`) through `operation_over_share`, which raises on a
failed read: an unreadable spend refuses as `BACKEND_UNAVAILABLE` with a one-second
retry, apart from a spent share (`RATE_LIMITED`). The assistant is held to its own
share of the cap (`LOOM_ASSISTANT_BUDGET_SHARE`, default half), so questions cannot
spend what extraction and the conflict resolver need. Both surfaces record their
spend under one operation, `assistant.ask`, which the share check sums.
- The check reads spend already recorded, so answers running at once could each pass it;
each web process runs at most a set number of answers per namespace at once
(`LOOM_ASSISTANT_CONCURRENT_ANSWERS`, default 2), which bounds the overshoot to that
many answers per web process: replicas × `LOOM_WEB_WORKERS` × the setting in all. One
answer's cost is its own usage: a request carries at most 50 turns of history and a
question, each at most 20,000 characters, and runs for at most
`LOOM_ASSISTANT_ANSWER_TTL_S`.
- When the answer ends, the bridge prices the token usage of the agents API's final
chunk with the model's rate and records it as `upstream_cost_usd` on the answer's
`agent_events` row, where every model spend is counted. An answer cut before its final
chunk (a disconnect, the stop button, a timeout), or on a model Loom has no rate for,
is charged a per-answer ceiling (`LOOM_ASSISTANT_ANSWER_CEILING_USD`, default $0.10)
instead. `0` charges nothing, which is what the local-model preset sets
([a model server on your machine](/docs/getting-started/models-and-keys#a-model-server-on-your-machine-no-api-key)).
At the default cap of $1 a day, half of it buys about 15 answers at the mean of $0.033
per answer that the [qualification](/docs/features/integrations/librechat#qualification)
of the assistant toolset measured on that model, and 11 at its maximum of $0.043; a
namespace that asks more raises its `daily_cost_cap_usd`. The deployed agent's
qualification measured a mean of $0.033 and a maximum of $0.048 per answer over its 28
cases asked of LibreChat directly, and a mean of $0.027 and a maximum of $0.047 asked
through the chat route ([the deployed assistant](/docs/features/integrations/librechat#the-deployed-assistant)).
## Who can use it
Any token with `viewer` or higher on the namespace, and any person signed in to the
dashboard with that role. Every tool call checks the answer's token again, and that
token never reads more than the caller's own.
## Rolling upgrades
`insights.query`, `insights.catalog`, `help.search`, `help.get` and `assistant.ask` are
ops, and `/v1/assistant/chat/completions` a route, that a build before them does not
know: it answers `UNKNOWN_OP` or 404, so a client points at them once every replica
serves them. The agent's tools come from the definition the newest build writes, so
during an upgrade a help call that reaches an older replica answers `UNKNOWN_OP`, and
that answer goes without the docs. The analyst user, its grants and policies,
`loom.analysis_secrets`, `loom.analysis_canary` and `loom.assistant_service` live in
ClickHouse and are shared by every replica; the agent definition is written as
[the agent definition](#the-agent-definition) says, never by an older build.
A streamed answer from an older replica sends no `loom.step` events, no `steps` and no
`loom.text_done`, and its mentor hints no `plane`: the dashboard then shows "Answering…"
until the text comes, no "What it read" list, keeps Stop until `loom.citations` lands, and
shows a hint without a page link. An older dashboard or SDK skips `loom.step` and
`loom.text_done` as events it does not know and ignores the fields. A dashboard tab of the
older build that shares the browser's stored conversations reads a starter's card-only
turn as a question with no answer: it shows an empty answer and sends that question as
history, until the tab is reloaded on the new build. Such a tab also leaves out a turn
stored while its sources were checked, as any turn still answering, and reads it as
stopped once it is cut off; shows a turn whose check was cut off (`checkLost`) as done
with no label; sends a question asked with sources without " Cite your sources." in its
history and shows no "With sources" tag; and offers no Retry, ignoring a turn's
`retryable` and a card's `again` mark, so a starter's turn asked again shows its stored
card there.
An `/assistant` entry an older dashboard pushed opens the assistant over the landing page
on Back ([rolling upgrades](/docs/architecture/rolling-upgrades), rule 46).
## Build order
1. `insights.query`, `insights.catalog` and the analyst user, written at boot and by
`loom ch-setup` and probed, with the isolation proof's cases for them, and
`users_without_row_policies_can_read_rows = false` in the ClickHouse Loom configures:
`deploy/clickhouse-config/access_control.xml`, mounted by `compose.yaml` and
`dev/ci_start_clickhouse.sh`, and a key of the chart's development ClickHouse
ConfigMap with its `volumeMount`. The dropped-policy case reads the setting from the
server's behaviour and runs on either. Built.
2. The key's rotation: `loom ch-setup --rotate-analysis-key` and `--live`, the printed
SQL as a complete rotation, the key read from the row before each statement, the
probe's deferral within three settle times, the policy read and `loom doctor`'s
outcomes, and the isolation proof's cases for them, for two builds side by side and
for a Loom user without access management, with CI running the dropped-policy case
on a second ClickHouse with the server default.
3. LibreChat deployed headless, the seeded agent definition, re-qualified with analysis
and recommendation questions
([the deployed assistant](/docs/features/integrations/librechat#the-deployed-assistant)).
Built.
4. The bridge: the chat route and `assistant.ask`, with the answer's token, the
refusals, the budget share, the per-process limit, the spend on the answer's ledger
row, the answer's id on its tool calls' rows, the citation check and the SDKs'
streaming clients. Built.
5. The dashboard's Ask AI panel, on the signed-in session and the header's namespace,
with a Stop button that closes the request, Copy, Ask again and an edit of the last
question, each answer's checked citations under it, the reasons it cannot answer, the
conversations kept in the browser, the page's chip on each question and "Ask about
this" on a memory, a document and a Recall result
([Ask AI](/docs/features/dashboard#ask-ai)). Built.
6. Loom's documentation in the image, `help.search` and `help.get` on the toolset
([Loom's documentation](#looms-documentation)). Built.
Each part moves its section of this page from design to the description of what is
built.
## Source entry points
- `server/operations/toolsets.py` (`MCP_ASSISTANT_OPS`, `ASSISTANT_FORCED_ARGS`): the
assistant toolset the agent's tools come from.
- `server/core/ch.py` (`caller_shaped`, `_reader_auth`): how a read runs as another
ClickHouse user under caps.
- `server/cli/ch_setup.py`: provisioning of the reader user, which the analyst user
follows.
- `server/auth/delegation.py` (`delegate`): how an answer's token is derived from the
caller's and inherits its revocation.
- `server/observability/budget.py`: the namespace cost cap the assistant's spend counts
toward.
- `server/assistant/app/citations.py` (`verify`) and `server/assistant/app/support.py`
(`answer_support`, `streamed_calls`), with the rule in
`server/assistant/domain/support.py`: an answer's checked citations and its support.
- `server/assistant/app/bridge.py` (`stream`) and `server/assistant/domain/steps.py`: a
streamed answer's steps.
- `server/assistant/app/service.py`: the service user and agent set up at boot;
`server/assistant/store/service.py`: `loom.assistant_service`.
- `integrations/librechat/`: the agent definition (`agent.yaml`) and the qualification
harness.
- `server/help/`: `help.search` and `help.get`, and the index over the shipped docs.
- `deploy/librechat/assistant.librechat.yaml`: the deployed LibreChat's configuration.
## Invariants
- The analysis boundary is ClickHouse's: grants, the settings profile and signed row
policies.
- Every tool call the agent makes reads under a token delegated from the caller's, never
wider than it, never longer-lived except under a sign-in session, and then by at most
`LOOM_ASSISTANT_ANSWER_TTL_S`, and revoked with it, and is ledgered as consumer
`loom-assistant`.
- LibreChat stores no Loom token: each answer carries its own, and the service user's
key reads nothing without one.
- LibreChat stores no question, answer or tool output.
- The assistant writes no memory, document or grant.
- The assistant never calls itself: calls between Loom and LibreChat go one way per hop,
and only the assistant's two entry points (the `assistant.ask` op and
`POST /v1/assistant/chat/completions`) ask LibreChat for an answer; boot setup
(`server/assistant/app/service.py`) only registers the service user, its key and the
agent. Both entry points refuse an answer's own token (consumer `loom-assistant`) and
any token delegated from one with `ASSISTANT_SELF_CALL` (403), ledgered as a refused
answer, on every transport and toolset: an answer token's id starts with
`assistant-answer-`, so a descendant is told by its parents. No model endpoint Loom
serves for LibreChat's model calls may be an assistant op or call the assistant.
- The headless LibreChat's configuration keeps LibreChat's own memory off
(`memory: disabled: true` in `deploy/librechat/assistant.librechat.yaml` and the Helm
copy), so what a person tells the assistant is not kept a second time outside Loom.
## Related
- [The assistant toolset](/docs/reference/mcp#the-assistant-toolset)
- [LibreChat integration](/docs/features/integrations/librechat)
- [Security](/docs/architecture/security)
- [Rolling upgrades](/docs/architecture/rolling-upgrades)
---
# 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(