Diffinery

homeflare/celldpublic

celld/docs/guarantees.md
330 lines · 17.0 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
73## The supervisor
74
75Run celld under a supervisor that restarts the process, such as systemd, Docker
76with a restart policy, or Kubernetes. A node that loses its lease fences itself
77and exits, and without a restart the fleet loses that capacity. The supervisor
78must restart without an attempt limit and wait at least one lease lifetime
79between attempts.
80
81## The mechanism
82
83### The ownership record
84
85Each cell has one ownership record in the bucket. It names the owner node's
86session and carries a fencing epoch. A node acquires a cell with a conditional
87create when no record exists, or a compare-and-swap on an existing record, so
88two nodes cannot acquire the same cell. Every activation, a takeover or a local
89wake, advances the epoch, so an epoch never has two writers.
90
91### The epoch prefix
92
93The replicator copies each cell's SQLite data to `cells/<cell>/ltx/e<epoch>/`
94with unconditional PUTs. The epoch in the key is the fence: a node that lost
95ownership can keep writing, but only into a superseded prefix, and a restore
96selects the current lineage. The tiering path can first combine segments from
97many cells into a node bundle and drain each segment into its per-cell prefix
98later. A bundle is deleted only when the per-cell prefixes cover every segment
99in it. A failed compaction retries after 30 seconds, backing off to at most 300
100seconds.
101
102### The acknowledgement rule (RPO=0)
103
104A gate holds each response until a durability proof covers every write it can
105reveal: a write response; a read-only response when the object has an uncovered
106committed write; an error response, because a thrown message can carry a value
107the handler read; an R2 mutation, so it cannot change the application bucket
108before the source write is durable; a raw TCP connect, write, TLS upgrade, or
109shutdown; and each chunk of a streamed body. A client therefore cannot act on a
110value that a crash can still lose.
111
112After a bucket proof, celld reads the ownership record once and acknowledges
113only if it still names this node at this epoch. A partitioned node can commit
114locally and replicate into its superseded prefix, but it does not acknowledge.
115The check reads the record instead of a clock, so a paused process or a skewed
116clock cannot pass it.
117
118A fleet proof needs no such read. The owner sends each write to one or two other
119nodes, its followers (together, the ensemble), and every follower must fsync it.
120A takeover seals the prior node-log session before it restores, so a stale owner
121cannot complete another fleet proof.
122
123An unfinished SQL write cursor can return rows before SQLite commits. Outside an
124explicit transaction, the application must consume those rows before output or
125`storage.sync()`; celld rejects output while a write cursor is unfinished.
126
127### The ensemble needs two nodes
128
129A node never counts itself as a follower, and one follower is enough, therefore
130a fleet needs two running celld nodes before any node can complete a fleet
131proof. `CELLD_DURABILITY=fleet` is the default, so a one-node fleet requests the
132fleet posture and does not get it.
133
134A node recruits up to two followers, so a fleet of three or more nodes holds
135three copies of an acknowledged write. The ensemble keeps acknowledging while
136one follower remains. A node with one follower recruits a second one when
137another node becomes available. Until then, a write that is not yet in the
138bucket is only on the owner and on that one follower.
139
140A node without an ensemble stays correct. It acknowledges each write on a bucket
141proof instead, at the cost of latency: an object store round trip is much slower
142than a follower fsync.
143
144### The takeover recovery gate
145
146In fleet mode, celld can acknowledge a write before its bucket upload completes.
147Each process session therefore creates a conditional node-log record before its
148first fleet-durable acknowledgement.
149
150A cold activation checks the prior owner's log records before it reads the
151bucket. An absent record proves that the session never acknowledged past the
152bucket; a sealed record proves that recovery completed. An open or recovering
153record forces recovery before the restore: compare-and-swap the record to fence
154it, seal the reachable followers, upload their retained segments and bundles
155into the per-cell prefixes, and mark the record sealed.
156
157A cell can stop while its node session stays open; its next activation gathers
158any acknowledged tail outside its per-cell prefix. Once the log epoch is
159active (before its first fleet proof), at least one current follower must
160return its complete retained range, or the activation fails and keeps the
161recovery requirement.
162
163Recovery has these limits:
164
165- A follower's HTTP error does not prove its data is absent, even when its
166 lease has expired, so persistent errors can block recovery and startup.
167- A restarted follower cannot certify a range with a damaged batch or a gap
168 until valid data covers it.
169- An older node's entries-only tail (`CLT1`) proves neither completeness nor
170 loss, so recovery or startup can stall during a mixed-version update.
171- A deleted final batch is undetectable if no later batch or persisted end
172 records its range.
173- A torn batch with an unacknowledged write looks like damage after an
174 acknowledgement, so the loss record can report an uncertified range when no
175 acknowledged write is missing.
176
177A restarting node serves authenticated follower seal and tail requests before
178its own predecessor recovery completes, so nodes that restart together can
179recover acknowledged writes from surviving follower disks. It accepts
180application requests and new follower appends only after startup completes.
181
182Recovery of a large dead node can take minutes. It reads retained bundles in
183windows of at most 512 MiB and uploads and releases each window before the next,
184so memory does not grow with the session; a cell with rows in several windows
185receives one object per window. A failed or timed-out attempt does not fail
186waiting requests: the cell retries with a backoff (`CELLD_RECOVERY_RETRY_MS`,
187default 1000), and the requests fail with a resolve error only after
188`CELLD_RECOVERY_RETRIES` (default 240) attempts.
189
190### Epoch-chain restore
191
192A restore chains the epoch prefixes that contain LTX data, from the newest down
193to an epoch that opened with a whole-database snapshot. An epoch that paged in
194continues its predecessor from the cut it paged from, and a predecessor that
195does not end exactly at that cut is not part of the chain. A legacy
196`e<epoch>.seal.json` object does not limit the chain.
197
198A paged cell reads no chain up front. It opens over a sparse local file, reads
199each page from the objects on first use, and fills the rest in the background; a
200filled cell reads only its local file. A chain smaller than
201`CELLD_LTX_PAGED_MIN_MB` is downloaded whole.
202
203### Epoch GC
204
205When `CELLD_LTX_RETENTION_SECS` is positive, the owner of a cell deletes the
206epoch prefixes that no restore reads, in both `CELLD_DURABILITY` modes:
207
2081. It builds the chain over every epoch prefix and continues only when the
209 newest epoch is its own. Its first object is then in the listing, so a later
210 owner restores from a base at the same epoch or higher.
2112. A paged cell waits until its local file is complete.
2123. It continues only when the ownership record names this node at this epoch.
2134. It writes `retired.json` with the base and deletes the prefixes below it,
214 keeping its own epoch, the one before, and each epoch younger than the
215 configured time.
216
217The order matters: otherwise a fenced owner could delete its successor's base.
218A late delete is safe because an epoch below the base never rejoins a chain.
219This relies on list-after-write consistency.
220
221A fenced node can append an unacknowledged tail to an older prefix. After a
222snapshot successor, a later restore can expose that tail; this does not violate
223the contract, because a missing acknowledgement does not prove a write absent.
224After a paged successor, the chain clips the older prefix at the cut, and the
225takeover recovery gate seals the prior node-log session before the successor
226restores, so no write past the cut can be acknowledged.
227
228### Self-fencing
229
230Each node holds a lease in the bucket with an expiry, renewed after one third of
231the lifetime (`CELLD_TTL_MS`, default 10000 ms). A failed renewal is retried
232while the published expiry has not passed.
233
234When the expiry passes, the node fences itself: it stops each active cell and
235fails every incomplete request. It also fences at once when its lease record is
236gone or no longer matches what it published. The fence writes nothing; peers
237already read the lease as dead or replaced and acquire the cells through the
238ownership records. celld checks the published expiry on every routed request,
239so a request is safe even before the fence runs.
240
241An ingress checks a cached remote route against the observed lease deadline on
242each new request and rereads ownership at the deadline, even if the old owner
243holds connections open. Recovery still needs the bucket and the required durable
244data. A draining ingress can forward to a live remote owner but refuses new
245ownership of an unowned cell or one with an expired owner. The ingress does not
246replay a request already sent to the old owner, because the handler can have
247committed a write; the caller can cancel it.
248
249A fenced node logs a line starting with `SELF-FENCE:` and exits with code 3.
250Other internal failures share the prefix and code; the line names the cause:
251`node_lease_watchdog_fence` (expired), `node_lease_record_missing_fence`, or
252`node_lease_record_mismatch_fence` (which names no author, because the node
253cannot prove who wrote the record). The fenced state is terminal: only a restart
254returns the node, through the normal cold-activation path. The
255[testing page](testing.md) shows the kill tests for this path.
256
257`RUST_LOG=celld=info,store=debug` logs a `node_lease_read` or `node_lease_write`
258event for each store request against the node's own lease record, with an
259`outcome` of `found`, `missing`, `applied`, `rejected`, or `error`. An `error`
260carries the store failure in an `error` field; a `found` carries the record's
261`generation`. The target costs nothing at other filters.
262
263## Alarm discovery and the wake format
264
265SQLite stores the alarm deadline, consumption, retry state, and installation
266identity. An alarm hint only makes celld read SQLite; it never authorizes a
267handler to run.
268
269Each committed installation has an object under `wake/entries/`, identified by
270the ownership epoch and a persistent SQLite sequence. An alarm response waits
271for its publication PUT and the output proof; an update within the same minute
272also needs a new PUT.
273
274Cleanup publishes a retirement record under `wake/retired/` with conditional
275writes. The record needs a durability proof, a current owner, and, if an alarm
276remains armed, a confirmed replacement publication. Cleanup deletes only older
277identities or a proven consumed one, so an old DELETE cannot remove a later
278installation and the bucket needs no conditional DELETE. Deletes of obsolete
279publications do not block an alarm response.
280
281Each cleanup pass lists at most 128 objects and processes at most eight cells
282concurrently, continuing the listing on the next pass and restarting after the
283last page. A failed DELETE or a late PUT can need another full scan. The
284interval defaults to 60 seconds; `CELLD_WAKER_TICK_MS` sets it and the due-scan
285interval. A large inventory can take many intervals, and each extra node can
286repeat the same reads and deletes.
287
288`wake/format.json` selects format 2; `wake/waker.json` holds the advisory lease
289for the waker role. A new node initializes an empty fleet or upgrades a stopped
290v0.4.1 fleet automatically. An unsupported format, or the old
291`wake-format.json`, `wake-v2/`, or `wake-retired-v2/` names, prevents startup.
292Application objects outside the reserved namespaces do not.
293
294### Start a fleet with this format
295
296An empty fleet initializes this format automatically. An upgrade from v0.4.1
297keeps the bucket and node data directories but needs a stopped fleet, because
298v0.4.1 cannot read the new discovery entries.
299
3001. Stop application traffic and deployment writers. Stop every old node and its
301 supervisor, then wait for every node lease to expire.
3022. Back up the bucket and node data. Keep the node names, peer addresses, and
303 data directories. A follower disk can hold acknowledged writes that the
304 bucket does not yet hold.
3053. Prevent the old binaries from restarting or writing to the bucket: revoke
306 their credentials or access. The format marker cannot stop them.
3074. Start the new binary on every node with the same configuration, data, and
308 addresses. Wait for the fleet to become healthy, then resume traffic.
309
310The nodes can start together. A live node lease blocks the migration, and the
311operator must keep old writers from returning.
312
313The migration preserves databases, node logs, ownership records, deployments,
314and application objects. It creates a discovery seed for each stored cell, in
315pages of at most 128 entries. A seed makes recovery derive the installation
316identity from SQLite without changing the deadline or retry state, and it is
317removed only after durable recovery, so an interrupted migration cannot discard
318an alarm. Recovery can load cells with future alarms while it processes seeds.
319
320If a node stops mid-migration, another starting node resumes it. No node serves
321until the full inventory succeeds, so alarms can run late. Later starts do not
322migrate again.
323
324To roll back, restore the full stopped-fleet backup; never start an old binary
325against the upgraded fleet. The restore loses writes made after the backup, so
326preserve those separately.
327
328Restarts and ownership transfers preserve alarm history. Each restored writer
329takes a new epoch and keeps the stored sequence and consumed state, so an old
330mutation cannot target a later installation.