Diffinery

homeflare/celldpublic

celld/docs/guarantees.md
378 lines · 20.1 KBRaw History
1# What celld guarantees
2
3celld makes two promises. Exactly one node serves a cell at a time, so two
4machines never write the same database. celld does not acknowledge a write
5until the write survives a failure, so an acknowledged write is never lost. Both
6promises require a bucket with working conditional writes and ranged reads, and
7a supervisor that restarts the process.
8
9## What the bucket must provide
10
11- A conditional create: the write must fail when the object exists.
12- A conditional overwrite: the write must fail when the object changed after the
13 read.
14- Read-after-write consistency: a read after a successful write must return that
15 write.
16- Ranged reads: a read must return the requested byte range and the bytes from
17 that range.
18- For epoch GC (`CELLD_LTX_RETENTION_SECS`) only, list-after-write consistency:
19 a listing after a successful write must include the written object. Amazon
20 S3, Cloudflare R2, Google Cloud Storage, and Azure Blob Storage provide it. A
21 Tigris Global or Dual-region bucket provides it only in the region of the
22 write, so do not enable epoch GC on one when fleet nodes are in more than one
23 region.
24
25The qualified stores are Amazon S3, Cloudflare R2, Tigris, Google Cloud Storage,
26and Azure Blob Storage. The release tests run against R2; the S3 path uses the
27same client and headers. Azure was qualified on 2026-08-18, single-node, under
28an account key, a VM managed identity, and an AKS workload identity. A managed
29identity on Azure App Service or Azure Container Apps does not work; see
30[limitations](limitations.md).
31
32Backblaze B2, Hetzner Object Storage, and DigitalOcean Spaces do not implement
33the required conditional writes, so two nodes can own one cell on them. A store
34that accepts the conditional headers but ignores the condition fails late and
35silently, so run the storage test.
36
37MinIO (the community edition) passes the storage test but is not qualified for
38production. RELEASE.2025-09-06T17-38-46Z answers the conditional create of an
39absent object with `NoSuchKey`, so the first deploy fails (denoland/celld#162).
40Use RELEASE.2025-09-07T16-13-09Z or later.
41
42A `gs://` bucket uses the Cloud Storage XML API with
43`x-goog-if-generation-match` and OAuth credentials, because Cloud Storage does
44not apply `If-Match` to a PUT. For an `az://` bucket, the NAME is the container.
45
46## The storage test
47
48`celld diagnose` sends four conditional writes to the bucket:
49
50```
51ok bucket conditional write (create, reject-create, update, reject-stale)
52```
53
54Two of the four must fail; if the store accepts either, the command exits with
55an error that names the store. Use `celld diagnose --read-only` with a
56credential that cannot write.
57
58Each node runs the same writes before it serves, then reads a range of a second
59object and verifies the range and bytes. A node cannot disable this test. It
60makes at most three attempts, with new objects, when an operation fails without
61a clear cause; then the node starts with a warning, because a temporary outage
62can end. The node stops immediately when a required conditional write or ranged
63read is unsupported, when the store ignores a condition or the `Range` header,
64or when it returns a wrong range or wrong bytes.
65
66A process that stops mid-test can leave a small object under `probe/`; celld
67never reads it.
68
69celld reserves `probe/`, `cells/`, `nodes/`, `node-cells/`, `fleet/`, `deploy/`,
70`deploy-blobs/`, `log/`, `wake/`, and `telemetry/`, and deletes objects under
71some of them. An application must not write under any of them.
72
73An operator must not delete, expire, or overwrite an object under these
74prefixes, except under `probe/` and `telemetry/`. celld reads these objects to
75fence and restore cells, and celld deletes the objects that it no longer needs.
76A bucket lifecycle rule therefore must not select an object under another
77reserved prefix. With a key prefix, each reserved prefix follows the key prefix,
78for example `PREFIX/telemetry/`.
79
80## The supervisor
81
82Run celld under a supervisor that restarts the process, such as systemd, Docker
83with a restart policy, or Kubernetes. A node that loses its lease fences itself
84and exits, and without a restart the fleet loses that capacity. The supervisor
85must restart without an attempt limit and wait at least one lease lifetime
86between attempts.
87
88## The mechanism
89
90### The ownership record
91
92Each cell has one ownership record in the bucket. It names the owner node's
93session and carries a fencing epoch. A node acquires a cell with a conditional
94create when no record exists, or a compare-and-swap on an existing record, so
95two nodes cannot acquire the same cell. Every activation, a takeover or a local
96wake, advances the epoch, so an epoch never has two writers.
97
98The record is `cells/<cell>/own.json`. celld never deletes it, and it must stay
99in the bucket for the life of the cell. A missing record next to LTX under
100`cells/<cell>/ltx/` means that the record was lost, for example to a lifecycle
101rule. celld then refuses to acquire the cell, because a new record at epoch 1
102would start it with an empty database. Each request that must read the record,
103to acquire the cell or to find its owner, fails, and the node writes
104`celld ownership record lost` to stderr. The node then refuses the cell for 10
105seconds without a bucket request, so it writes the line at most once in that
106interval. A node that still serves the cell keeps serving it and keeps writing
107LTX until it stops. That node cannot acknowledge a write that a bucket proof
108covers, because the record no longer names it, so the write fails and the node
109writes `celld output gate` to stderr. With `CELLD_DURABILITY=bucket`, every
110write takes a bucket proof. celld detects the loss only from LTX under
111`cells/<cell>/ltx/`. A new cell can keep its first writes in a node bundle under
112`log/` until the tiering path drains them, so a loss before that drain starts
113the cell empty.
114
115To restore the cell, first stop each node that served the cell with SIGTERM, not
116with `POST /shutdown?handoff=preserve`. A preserved restart resumes its cells
117without a read of the record, so the node keeps serving the cell. No peer can
118acquire the cell, so its handoff cannot complete: the stop can take the whole
119`CELLD_SHUTDOWN_TOTAL_MS` and log `shutdown_handoff_stalled`.
120
121A stopped process can still hold acknowledged writes in its node log, outside
122the per-cell prefixes, so wait until that log is recovered. A new process with
123the same `CELLD_NODE` recovers it during startup, so the log is recovered when
124that process reports healthy. Without the same `CELLD_NODE`, a running node
125with `CELLD_DURABILITY=fleet`, the default, recovers it after the lease of the
126stopped process expires. In that case, wait until `nodes/<node>.json` of the
127stopped process is absent, has no `log` object, or shows `"state": "sealed"` in
128it. A stop that logs `node-log close: sealed epoch` has already sealed its log.
129
130Then write a released record, which names no node, at the newest epoch: the
131numerically highest `e<epoch>` prefix under `cells/<cell>/ltx/`. For a newest
132epoch of 7, the record is `{"node": "", "epoch": 7}`. After the refusal interval
133ends, the next request acquires the cell at the next epoch and restores it from
134the bucket. A released record skips the recovery of the node log of the
135previous owner. A record that is written before these logs are recovered can
136therefore lose acknowledged writes, and a node that still serves the cell
137becomes a second writer.
138
139### The epoch prefix
140
141The replicator copies each cell's SQLite data to `cells/<cell>/ltx/e<epoch>/`
142with unconditional PUTs. The epoch in the key is the fence: a node that lost
143ownership can keep writing, but only into a superseded prefix, and a restore
144selects the current lineage. The tiering path can first combine segments from
145many cells into a node bundle and drain each segment into its per-cell prefix
146later. A bundle is deleted only when the per-cell prefixes cover every segment
147in it. A failed compaction retries after 30 seconds, backing off to at most 300
148seconds.
149
150### The acknowledgement rule (RPO=0)
151
152A gate holds each response until a durability proof covers every write it can
153reveal: a write response; a read-only response when the object has an uncovered
154committed write; an error response, because a thrown message can carry a value
155the handler read; an R2 mutation, so it cannot change the application bucket
156before the source write is durable; a raw TCP connect, write, TLS upgrade, or
157shutdown; and each chunk of a streamed body. A client therefore cannot act on a
158value that a crash can still lose.
159
160After a bucket proof, celld reads the ownership record once and acknowledges
161only if it still names this node at this epoch. A partitioned node can commit
162locally and replicate into its superseded prefix, but it does not acknowledge.
163The check reads the record instead of a clock, so a paused process or a skewed
164clock cannot pass it.
165
166A fleet proof needs no such read. The owner sends each write to one or two other
167nodes, its followers (together, the ensemble), and every follower must fsync it.
168A takeover seals the prior node-log session before it restores, so a stale owner
169cannot complete another fleet proof.
170
171An unfinished SQL write cursor can return rows before SQLite commits. Outside an
172explicit transaction, the application must consume those rows before output or
173`storage.sync()`; celld rejects output while a write cursor is unfinished.
174
175### The ensemble needs two nodes
176
177A node never counts itself as a follower, and one follower is enough, therefore
178a fleet needs two running celld nodes before any node can complete a fleet
179proof. `CELLD_DURABILITY=fleet` is the default, so a one-node fleet requests the
180fleet posture and does not get it.
181
182A node recruits up to two followers, so a fleet of three or more nodes holds
183three copies of an acknowledged write. The ensemble keeps acknowledging while
184one follower remains. A node with one follower recruits a second one when
185another node becomes available. Until then, a write that is not yet in the
186bucket is only on the owner and on that one follower.
187
188A node without an ensemble stays correct. It acknowledges each write on a bucket
189proof instead, at the cost of latency: an object store round trip is much slower
190than a follower fsync.
191
192### The takeover recovery gate
193
194In fleet mode, celld can acknowledge a write before its bucket upload completes.
195Each process session therefore creates a conditional node-log record before its
196first fleet-durable acknowledgement.
197
198A cold activation checks the prior owner's log records before it reads the
199bucket. An absent record proves that the session never acknowledged past the
200bucket; a sealed record proves that recovery completed. An open or recovering
201record forces recovery before the restore: compare-and-swap the record to fence
202it, seal the reachable followers, upload their retained segments and bundles
203into the per-cell prefixes, and mark the record sealed.
204
205A cell can stop while its node session stays open; its next activation gathers
206any acknowledged tail outside its per-cell prefix. Once the log epoch is
207active (before its first fleet proof), at least one current follower must
208return its complete retained range, or the activation fails and keeps the
209recovery requirement.
210
211Recovery has these limits:
212
213- A follower's HTTP error does not prove its data is absent, even when its
214 lease has expired, so persistent errors can block recovery and startup.
215- A restarted follower cannot certify a range with a damaged batch or a gap
216 until valid data covers it.
217- An older node's entries-only tail (`CLT1`) proves neither completeness nor
218 loss, so recovery or startup can stall during a mixed-version update.
219- A deleted final batch is undetectable if no later batch or persisted end
220 records its range.
221- A torn batch with an unacknowledged write looks like damage after an
222 acknowledgement, so the loss record can report an uncertified range when no
223 acknowledged write is missing.
224
225A restarting node serves authenticated follower seal and tail requests before
226its own predecessor recovery completes, so nodes that restart together can
227recover acknowledged writes from surviving follower disks. It accepts
228application requests and new follower appends only after startup completes.
229
230Recovery of a large dead node can take minutes. It reads retained bundles in
231windows of at most 512 MiB and uploads and releases each window before the next,
232so memory does not grow with the session; a cell with rows in several windows
233receives one object per window. A failed or timed-out attempt does not fail
234waiting requests: the cell retries with a backoff (`CELLD_RECOVERY_RETRY_MS`,
235default 1000), and the requests fail with a resolve error only after
236`CELLD_RECOVERY_RETRIES` (default 240) attempts.
237
238### Epoch-chain restore
239
240A restore chains the epoch prefixes that contain LTX data, from the newest down
241to an epoch that opened with a whole-database snapshot. An epoch that paged in
242continues its predecessor from the cut it paged from, and a predecessor that
243does not end exactly at that cut is not part of the chain. A legacy
244`e<epoch>.seal.json` object does not limit the chain.
245
246A paged cell reads no chain up front. It opens over a sparse local file, reads
247each page from the objects on first use, and fills the rest in the background; a
248filled cell reads only its local file. A chain smaller than
249`CELLD_LTX_PAGED_MIN_MB` is downloaded whole.
250
251### Epoch GC
252
253When `CELLD_LTX_RETENTION_SECS` is positive, the owner of a cell deletes the
254epoch prefixes that no restore reads, in both `CELLD_DURABILITY` modes:
255
2561. It builds the chain over every epoch prefix and continues only when the
257 newest epoch is its own. Its first object is then in the listing, so a later
258 owner restores from a base at the same epoch or higher.
2592. A paged cell waits until its local file is complete.
2603. It continues only when the ownership record names this node at this epoch.
2614. It writes `retired.json` with the base and deletes the prefixes below it,
262 keeping its own epoch, the one before, and each epoch younger than the
263 configured time.
264
265The order matters: otherwise a fenced owner could delete its successor's base.
266A late delete is safe because an epoch below the base never rejoins a chain.
267This relies on list-after-write consistency.
268
269A fenced node can append an unacknowledged tail to an older prefix. After a
270snapshot successor, a later restore can expose that tail; this does not violate
271the contract, because a missing acknowledgement does not prove a write absent.
272After a paged successor, the chain clips the older prefix at the cut, and the
273takeover recovery gate seals the prior node-log session before the successor
274restores, so no write past the cut can be acknowledged.
275
276### Self-fencing
277
278Each node holds a lease in the bucket with an expiry, renewed after one third of
279the lifetime (`CELLD_TTL_MS`, default 10000 ms). A failed renewal is retried
280while the published expiry has not passed.
281
282When the expiry passes, the node fences itself: it stops each active cell and
283fails every incomplete request. It also fences at once when its lease record is
284gone or no longer matches what it published. The fence writes nothing; peers
285already read the lease as dead or replaced and acquire the cells through the
286ownership records. celld checks the published expiry on every routed request,
287so a request is safe even before the fence runs.
288
289An ingress checks a cached remote route against the observed lease deadline on
290each new request and rereads ownership at the deadline, even if the old owner
291holds connections open. Recovery still needs the bucket and the required durable
292data. A draining ingress can forward to a live remote owner but refuses new
293ownership of an unowned cell or one with an expired owner. The ingress does not
294replay a request already sent to the old owner, because the handler can have
295committed a write; the caller can cancel it.
296
297A fenced node logs a line starting with `SELF-FENCE:` and exits with code 3.
298Other internal failures share the prefix and code; the line names the cause:
299`node_lease_watchdog_fence` (expired), `node_lease_record_missing_fence`, or
300`node_lease_record_mismatch_fence` (which names no author, because the node
301cannot prove who wrote the record). The fenced state is terminal: only a restart
302returns the node, through the normal cold-activation path. The
303[testing page](testing.md) shows the kill tests for this path.
304
305`RUST_LOG=celld=info,store=debug` logs a `node_lease_read` or `node_lease_write`
306event for each store request against the node's own lease record, with an
307`outcome` of `found`, `missing`, `applied`, `rejected`, or `error`. An `error`
308carries the store failure in an `error` field; a `found` carries the record's
309`generation`. The target costs nothing at other filters.
310
311## Alarm discovery and the wake format
312
313SQLite stores the alarm deadline, consumption, retry state, and installation
314identity. An alarm hint only makes celld read SQLite; it never authorizes a
315handler to run.
316
317Each committed installation has an object under `wake/entries/`, identified by
318the ownership epoch and a persistent SQLite sequence. An alarm response waits
319for its publication PUT and the output proof; an update within the same minute
320also needs a new PUT.
321
322Cleanup publishes a retirement record under `wake/retired/` with conditional
323writes. The record needs a durability proof, a current owner, and, if an alarm
324remains armed, a confirmed replacement publication. Cleanup deletes only older
325identities or a proven consumed one, so an old DELETE cannot remove a later
326installation and the bucket needs no conditional DELETE. Deletes of obsolete
327publications do not block an alarm response.
328
329Each cleanup pass lists at most 128 objects and processes at most eight cells
330concurrently, continuing the listing on the next pass and restarting after the
331last page. A failed DELETE or a late PUT can need another full scan. The
332interval defaults to 60 seconds; `CELLD_WAKER_TICK_MS` sets it and the due-scan
333interval. A large inventory can take many intervals, and each extra node can
334repeat the same reads and deletes.
335
336`wake/format.json` selects format 2; `wake/waker.json` holds the advisory lease
337for the waker role. A new node initializes an empty fleet or upgrades a stopped
338v0.4.1 fleet automatically. An unsupported format, or the old
339`wake-format.json`, `wake-v2/`, or `wake-retired-v2/` names, prevents startup.
340Application objects outside the reserved namespaces do not.
341
342### Start a fleet with this format
343
344An empty fleet initializes this format automatically. An upgrade from v0.4.1
345keeps the bucket and node data directories but needs a stopped fleet, because
346v0.4.1 cannot read the new discovery entries.
347
3481. Stop application traffic and deployment writers. Stop every old node and its
349 supervisor, then wait for every node lease to expire.
3502. Back up the bucket and node data. Keep the node names, peer addresses, and
351 data directories. A follower disk can hold acknowledged writes that the
352 bucket does not yet hold.
3533. Prevent the old binaries from restarting or writing to the bucket: revoke
354 their credentials or access. The format marker cannot stop them.
3554. Start the new binary on every node with the same configuration, data, and
356 addresses. Wait for the fleet to become healthy, then resume traffic.
357
358The nodes can start together. A live node lease blocks the migration, and the
359operator must keep old writers from returning.
360
361The migration preserves databases, node logs, ownership records, deployments,
362and application objects. It creates a discovery seed for each stored cell, in
363pages of at most 128 entries. A seed makes recovery derive the installation
364identity from SQLite without changing the deadline or retry state, and it is
365removed only after durable recovery, so an interrupted migration cannot discard
366an alarm. Recovery can load cells with future alarms while it processes seeds.
367
368If a node stops mid-migration, another starting node resumes it. No node serves
369until the full inventory succeeds, so alarms can run late. Later starts do not
370migrate again.
371
372To roll back, restore the full stopped-fleet backup; never start an old binary
373against the upgraded fleet. The restore loses writes made after the backup, so
374preserve those separately.
375
376Restarts and ownership transfers preserve alarm history. Each restored writer
377takes a new epoch and keeps the stored sequence and consumed state, so an old
378mutation cannot target a later installation.