Diffinery

homeflare/celldpublic

v0.6.2

Upgrading from v0.6.1 can use a rolling update.

- A Durable Object `stub.fetch()` that a peer forwards now rejects when the handler fails on the owner, as it does locally, and the handler does not run again.
- A Worker that returns a WebSocket response to a request without `Upgrade: websocket` now fails with a `TypeError` and a 500.
- `celld dev` accepts `export NAME=value` lines and multi-line quoted values in `.env` files, and skips an entry that cannot be a binding with a warning.
- Epoch GC (`CELLD_LTX_RETENTION_SECS`) also runs on nodes with bucket durability.
- LTX capture recovers a torn WAL header when a database opens, so capture no longer skips commits after a crash.
- A failed or abandoned eviction no longer stops compaction for the rest of a cell's activation.

Issues fixed:

- #243: `celld dev` reads `.env` and `.env.local` when there is no `.dev.vars`, as `wrangler dev` does.
- #245: A fleet with one follower recruits a second one when a peer becomes available.
- #246: Follower disk use stays bounded after a snapshot eviction or a deleted facet.
- #247: `self` is defined in Worker, Durable Object, and Worker Loader isolates.
- #248: `getDurableObjectClass()` accepts a plain class that extends no runtime base.
- #252: WebSockets work in Durable Object facets, including outbound sockets that a facet opens.
- #255: A deploy no longer deadlocks a Durable Object handler.
- #257: A fetch to a loaded Worker honors the caller's `AbortSignal`, including `AbortSignal.timeout()`.

Co-authored-by: Ryan Dahl <[email protected]>
Co-authored-by: Yusuke "Taka" Tanaka <[email protected]>
Co-authored-by: Josh Collinsworth <[email protected]>
Co-authored-by: Bert Belder <[email protected]>
Bartek Iwańczuk authored signed1 parent f2bf648commit 90b43017241f81189453d326d05948f388b34652Browse files
63 files changed+4555−5338
Files (63)
modified.github/workflows/release.yml+5−3View file
@@ -126,12 +126,14 @@
126126 path: assets
127127 merge-multiple: true
128128
129- # Assets are minimal: the binaries, nothing else. Integrity is the
130- # attestation plus GitHub's own immutable per-asset digests; gzip's
131- # CRC catches corruption in transit.
129+ # Assets are minimal: the binaries plus LICENSE and NOTICE, which
130+ # the third-party licenses require to travel with them. Integrity is
131+ # the attestation plus GitHub's own immutable per-asset digests;
132+ # gzip's CRC catches corruption in transit.
132133 - name: Check assets
133134 run: |
134135 set -euo pipefail
136+ cp LICENSE NOTICE assets/
135137 cd assets
136138 for target in \
137139 x86_64-unknown-linux-gnu \
modifiedCargo.lock+1−1View file
@@ -285,7 +285,7 @@
285285
286286 [[package]]
287287 name = "celld"
288-version = "0.6.1"
288+version = "0.6.2"
289289 dependencies = [
290290 "aes",
291291 "aes-gcm",
modifiedDockerfile+1−0View file
@@ -42,5 +42,6 @@
4242 LABEL org.opencontainers.image.title="celld" \
4343 org.opencontainers.image.revision="${CELLD_COMMIT}" \
4444 org.opencontainers.image.version="${CELLD_VERSION}"
45+COPY LICENSE NOTICE /usr/share/doc/celld/
4546 COPY --from=test /out/celld /usr/local/bin/celld
4647 ENTRYPOINT ["/usr/local/bin/celld"]
deletedLICENSE.tokio+0−21
@@ -1,21 +1,0 @@
1-MIT License
2-
3-Copyright (c) Tokio Contributors
4-
5-Permission is hereby granted, free of charge, to any person obtaining a copy
6-of this software and associated documentation files (the "Software"), to deal
7-in the Software without restriction, including without limitation the rights
8-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9-copies of the Software, and to permit persons to whom the Software is
10-furnished to do so, subject to the following conditions:
11-
12-The above copyright notice and this permission notice shall be included in all
13-copies or substantial portions of the Software.
14-
15-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21-SOFTWARE.
addedNOTICE+28−0View file
@@ -1,0 +1,28 @@
1+celld
2+Copyright 2026 Deno Land Inc.
3+
4+celld is licensed under the Apache License 2.0; see LICENSE. Code adapted
5+from Tokio is under the MIT License; see the header of
6+crates/celld/tokio_select.rs.
7+
8+Third-party software
9+--------------------
10+
11+celld uses lol_html, Cloudflare's HTML rewriting library (BSD-3-Clause,
12+https://github.com/cloudflare/lol-html), to implement the HTMLRewriter
13+API. lol_html depends on the following crates from the Servo project,
14+which are licensed under the Mozilla Public License 2.0
15+(https://mozilla.org/MPL/2.0/). celld binaries include them unmodified;
16+cssparser-macros runs only at build time. Their source code is available
17+at:
18+
19+ cssparser https://crates.io/crates/cssparser
20+ cssparser-macros https://crates.io/crates/cssparser-macros
21+ dtoa-short https://crates.io/crates/dtoa-short
22+ selectors https://crates.io/crates/selectors
23+
24+The exact versions are recorded in Cargo.lock.
25+
26+All other dependencies are under permissive licenses (Apache-2.0, MIT,
27+BSD-3-Clause, ISC, Unicode-3.0, Zlib, BSL-1.0, CC0-1.0,
28+CDLA-Permissive-2.0); Cargo.lock lists them.
modifiedcrates/celld/Cargo.toml+1−1View file
@@ -1,6 +1,6 @@
11 [package]
22 name = "celld"
3-version = "0.6.1"
3+version = "0.6.2"
44 edition = "2021"
55 rust-version = "1.94.1"
66 license = "Apache-2.0"
modifiedcrates/celld/actor.rs+40−12View file
@@ -390,6 +390,17 @@
390390 }
391391 }
392392
393+/// The identity that lets a request finish on a quiescing resident, where an
394+/// ordinary request waits for the successor route. One field holds it, so a
395+/// request cannot claim two identities.
396+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
397+pub enum ResidentWork {
398+ /// An event from this exact registered WebSocket.
399+ WebSocket(u64),
400+ /// The output gate for an effect that the cell's running work raised.
401+ OutputGate,
402+}
403+
393404 pub enum Message {
394405 /// A periodic resource sample. The measuring is the shell's job; every
395406 /// decision that follows belongs to the core.
@@ -436,10 +447,9 @@
436447 /// settles this channel as soon as the ownership CAS is authoritative;
437448 /// the ordinary route reply remains pending until it is cancelled.
438449 handoff_accept: Option<HandoffAcceptWaiter>,
439- /// An event from this exact registered WebSocket can finish on a
440- /// quiescing resident. Ordinary requests carry no identity and wait
441- /// for the successor route.
442- websocket: Option<u64>,
450+ /// Work that can finish on a quiescing resident. Ordinary requests
451+ /// carry none and wait for the successor route.
452+ resident_work: Option<ResidentWork>,
443453 reply: oneshot::Sender<Result<Routed, RequestError>>,
444454 },
445455 /// A caller disappeared before routing finished. The request identity is
@@ -1281,6 +1291,13 @@
12811291 self.request_with_mode(cell, false, None).await
12821292 }
12831293
1294+ /// Route the output gate for an effect raised inside one of `cell`'s
1295+ /// handlers. See `ResidentWork::OutputGate`.
1296+ pub async fn gate_request(&self, cell: String) -> Result<Routed, RequestError> {
1297+ self.request_with_mode(cell, false, Some(ResidentWork::OutputGate))
1298+ .await
1299+ }
1300+
12841301 /// Route one test request and retain which asynchronous seam produced the
12851302 /// result. The shipping method keeps its compact public result, while this
12861303 /// receipt prevents an inference from `NodeFenced` or an error string.
@@ -1313,16 +1330,21 @@
13131330 cell: String,
13141331 websocket: u64,
13151332 ) -> Result<Routed, RequestError> {
1316- self.request_with_mode(cell, false, Some(websocket)).await
1333+ self.request_with_mode(cell, false, Some(ResidentWork::WebSocket(websocket)))
1334+ .await
13171335 }
13181336
13191337 async fn request_with_mode(
13201338 &self,
13211339 cell: String,
13221340 capacity_handoff: bool,
1323- websocket: Option<u64>,
1341+ resident_work: Option<ResidentWork>,
13241342 ) -> Result<Routed, RequestError> {
1325- match self.request_path(cell, capacity_handoff, websocket).await.1 {
1343+ match self
1344+ .request_path(cell, capacity_handoff, resident_work)
1345+ .await
1346+ .1
1347+ {
13261348 RequestPathOutcome::Returned(result) => result,
13271349 RequestPathOutcome::SubmissionFailure | RequestPathOutcome::ReplyChannelClosed => {
13281350 Err(RequestError::NodeFenced)
@@ -1334,7 +1356,7 @@
13341356 &self,
13351357 cell: String,
13361358 capacity_handoff: bool,
1337- websocket: Option<u64>,
1359+ resident_work: Option<ResidentWork>,
13381360 ) -> (u64, RequestPathOutcome) {
13391361 let request = crate::asyncrt::next_core_request();
13401362 let (reply, receive) = oneshot::channel();
@@ -1345,7 +1367,7 @@
13451367 cell,
13461368 capacity_handoff,
13471369 handoff_accept: None,
1348- websocket,
1370+ resident_work,
13491371 reply,
13501372 })
13511373 .is_err()
@@ -1383,7 +1405,7 @@
13831405 released_epoch,
13841406 reply: accept_reply,
13851407 }),
1386- websocket: None,
1408+ resident_work: None,
13871409 reply: route_reply,
13881410 })
13891411 .is_err()
@@ -2684,7 +2706,7 @@
26842706 cell,
26852707 capacity_handoff,
26862708 handoff_accept,
2687- websocket,
2709+ resident_work,
26882710 reply,
26892711 } => {
26902712 self.pending.insert(request, reply);
@@ -2695,7 +2717,7 @@
26952717 self.begin_route_if_cold(&cell);
26962718 self.request_cells.insert(request, cell.clone());
26972719 self.drive(
2698- if let Some(websocket) = websocket {
2720+ if let Some(ResidentWork::WebSocket(websocket)) = resident_work {
26992721 Event::WebSocketRequestAt {
27002722 request,
27012723 cell: cell.clone(),
@@ -2703,6 +2725,12 @@
27032725 now_ms: now_ms(),
27042726 now_mono_ms: crate::asyncrt::mono_ms(),
27052727 }
2728+ } else if resident_work == Some(ResidentWork::OutputGate) {
2729+ Event::GateRequestAt {
2730+ request,
2731+ cell: cell.clone(),
2732+ now_mono_ms: crate::asyncrt::mono_ms(),
2733+ }
27062734 } else if ownership_handoff {
27072735 Event::HandoffRequestAt {
27082736 request,
modifiedcrates/celld/cell_cli.rs+8−7View file
@@ -344,7 +344,7 @@
344344 if !dry_run {
345345 bail!(
346346 "celld cell gc deletes nothing itself; pass --dry-run to report what the owners \
347- would delete, and give CELLD_LTX_RETENTION_SECS a positive value on the fleet to \
347+ would delete, and give CELLD_LTX_RETENTION_SECS a positive value on the nodes to \
348348 let them"
349349 );
350350 }
@@ -366,12 +366,13 @@
366366 newest epoch, the epoch before it, and each epoch whose newest object is
367367 younger than the grace. This command reads the bucket and writes nothing.
368368
369-The owners delete fewer, later, or none: only a fleet node with a
370-positive CELLD_LTX_RETENTION_SECS deletes, with that grace instead of
371---grace-secs; a paged cell waits until its local file is complete; an
372-inactive cell waits until it is active again; a cell that is not paged
373-waits until its activation has a write, so a cell that is only read
374-deletes nothing; and one pass deletes at most 64 epochs of a cell.
369+The owners delete fewer, later, or none: only a node with a positive
370+CELLD_LTX_RETENTION_SECS deletes, in either CELLD_DURABILITY mode, with
371+that grace instead of --grace-secs; a paged cell waits until its local
372+file is complete; an inactive cell waits until it is active again; a cell
373+that is not paged waits until its activation has a write, so a cell that
374+is only read deletes nothing; and one pass deletes at most 64 epochs of a
375+cell.
375376
376377 OPTIONS:
377378 --dry-run Required; report without deleting
modifiedcrates/celld/cell_dispatch.rs+67−31View file
@@ -42,11 +42,11 @@
4242 /// handler's own response.
4343 ///
4444 /// Every in-handler channel arrives here holding a `GateReq`. Reuses the routed
45-/// machinery: `request` pins the cell (no eviction mid-wait) and the core gate
46-/// decides. `Ok` releases the held effect; `Err` breaks the call, as a routed
47-/// gate failure would.
45+/// machinery: `gate_request` pins the cell (no eviction mid-wait) and the core
46+/// gate decides. `Ok` releases the held effect; `Err` breaks the call, as a
47+/// routed gate failure would.
4848 pub async fn dispatch_gate(app: AppHandle, req: crate::js::GateReq) {
49- let routed = match app.request(req.scope.clone()).await {
49+ let routed = match app.gate_request(req.scope.clone()).await {
5050 Ok(routed) => routed,
5151 Err(error) => {
5252 let _ = req.reply.send(Err(error));
@@ -181,6 +181,15 @@
181181 /// result. A missing runtime or a refused admission can end it before
182182 /// the handler starts.
183183 Local(anyhow::Result<HttpResponse>),
184+ /// The route was local, and the call failed after the cell accepted a
185+ /// WebSocket. The host registry holds the socket until the dispatcher
186+ /// releases it, and only the binary can deliver the close event that the
187+ /// release includes. A separate variant makes every dispatcher handle the
188+ /// socket, which an error that carried the target could silently drop.
189+ RefusedWebSocket {
190+ error: anyhow::Error,
191+ websocket: crate::js::WsTarget,
192+ },
184193 /// The route left this node. The payload comes back unconsumed for the
185194 /// peer forwarder.
186195 Remote {
@@ -257,26 +266,24 @@
257266 body,
258267 headers,
259268 } = payload;
260- CallAttempt::Local(
261- dispatch_local_fetch(
262- app,
263- request,
264- call.scope.clone(),
265- name,
266- RuntimeFetch {
267- url,
268- method,
269- body,
270- headers,
271- request_id: call.request_id,
272- order: call.order.take(),
273- parent: call.parent,
274- },
275- call.cancel.take(),
276- &mut call.body_guard,
277- )
278- .await,
269+ dispatch_local_fetch(
270+ app,
271+ request,
272+ call.scope.clone(),
273+ name,
274+ RuntimeFetch {
275+ url,
276+ method,
277+ body,
278+ headers,
279+ request_id: call.request_id,
280+ order: call.order.take(),
281+ parent: call.parent,
282+ },
283+ call.cancel.take(),
284+ &mut call.body_guard,
279285 )
286+ .await
280287 }
281288 Route::Remote {
282289 node,
@@ -293,7 +300,27 @@
293300 }
294301 }
295302
303+/// workerd's `TypeError` text for a WebSocket response to a request that did
304+/// not ask to upgrade (`Response::send` in workerd's `api/http.c++`).
305+pub const WEBSOCKET_WITHOUT_UPGRADE: &str =
306+ "Worker tried to return a WebSocket in a response to a \
307+ request which did not contain the header \"Upgrade: websocket\".";
308+
309+/// Whether a request asks for a WebSocket, by the rule workerd applies before
310+/// a response can carry one: an `Upgrade` field equal to `websocket`.
311+pub fn requests_websocket_upgrade(headers: &[(String, String)]) -> bool {
312+ headers.iter().any(|(name, value)| {
313+ name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket")
314+ })
315+}
316+
296317 /// Execute an admitted local call and retain its activity through the response.
318+///
319+/// The response is the only owner of a socket that the cell accepted, and
320+/// `WsTarget` is plain data. Every failure after the cell returns a socket
321+/// therefore hands the target back in [`CallAttempt::RefusedWebSocket`]: a
322+/// request that did not ask to upgrade, a failed core registration, and an
323+/// output-gate verdict that discards the response.
297324 async fn dispatch_local_fetch(
298325 app: &AppHandle,
299326 request: u64,
@@ -302,9 +329,11 @@
302329 mut fetch: RuntimeFetch,
303330 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
304331 body_guard: &mut RequestBodyGuard,
305-) -> anyhow::Result<HttpResponse> {
332+) -> CallAttempt {
306333 let local_request_id = local_dispatch_request_id(fetch.request_id);
307334 fetch.request_id = local_request_id;
335+ let upgrade = requests_websocket_upgrade(&fetch.headers);
336+ let mut accepted = None;
308337 let local = app.local_request(request, scope.clone(), local_request_id, "local");
309338 let completed = local
310339 .run(async {
@@ -315,20 +344,24 @@
315344 // owns an unread tail through its waitUntil work.
316345 body_guard.disarm();
317346 if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket {
318- let kind = if crate::js::ws_hibernatable(target.id).unwrap_or(false) {
347+ accepted = Some(target.clone());
348+ // workerd applies this check in the object's own response
349+ // path, so the caller's `stub.fetch()` rejects whichever
350+ // node the caller runs on.
351+ anyhow::ensure!(upgrade, "TypeError: {WEBSOCKET_WITHOUT_UPGRADE}");
352+ let (cell, hibernatable) = crate::js::ws_core_registration(target);
353+ let kind = if hibernatable {
319354 WebSocketKind::Hibernatable
320355 } else {
321356 WebSocketKind::Regular
322357 };
323- app.websocket_opened(target.scope.clone(), target.id, kind)
324- .await?;
358+ app.websocket_opened(cell, target.id, kind).await?;
325359 }
326360 Ok(response)
327361 })
328362 .await;
329363 let activity = completed.activity;
330- let result = completed.result.map_err(local_request_error);
331- match result {
364+ match completed.result.map_err(local_request_error) {
332365 Ok(mut response) => {
333366 let body_active = response.stream.is_some();
334367 activity.set_phase("response_body", true, body_active);
@@ -337,9 +370,12 @@
337370 } else {
338371 drop(activity);
339372 }
340- Ok(response)
373+ CallAttempt::Local(Ok(response))
341374 }
342- Err(error) => Err(error),
375+ Err(error) => match accepted {
376+ Some(websocket) => CallAttempt::RefusedWebSocket { error, websocket },
377+ None => CallAttempt::Local(Err(error)),
378+ },
343379 }
344380 }
345381
modifiedcrates/celld/deploy.rs+54−15View file
@@ -202,15 +202,33 @@
202202 pub dry_run: bool,
203203 pub json: bool,
204204 /// Worker variables that override the `vars` of the config. `celld dev`
205- /// reads them from `.dev.vars`; `celld deploy` supplies none, so a local
206- /// credential cannot reach a fleet.
207- pub vars: BTreeMap<String, String>,
205+ /// reads them from `.dev.vars` or the dotenv files; `celld deploy`
206+ /// supplies none, so a local credential cannot reach a fleet.
207+ pub vars: VarOverrides,
208208 /// Keep container images in the local engine instead of saving them to
209209 /// the bucket. `celld dev` runs its node on the same engine that built
210210 /// them; a fleet needs the tar.
211211 pub local_images: bool,
212212 }
213213
214+/// Local Worker variables, tagged with the kind of file that supplied them.
215+/// The kind decides what an entry that cannot become a var binding does, so
216+/// it travels with the entries instead of beside them.
217+#[derive(Default)]
218+pub enum VarOverrides {
219+ #[default]
220+ None,
221+ /// `.dev.vars` exists only for the Worker, so an entry that cannot become
222+ /// a binding is a mistake, and it fails the build.
223+ DevVars(BTreeMap<String, String>),
224+ /// `.env` and `.env.local` also serve other tools, such as a bundler or an
225+ /// ORM. An entry with a name that is not a valid binding, or a name that
226+ /// another binding of the config uses, is skipped with a warning. Failing
227+ /// instead stops a `celld dev` that `wrangler dev` runs, and the only
228+ /// workaround is an empty `.dev.vars`.
229+ DotEnv(BTreeMap<String, String>),
230+}
231+
214232 pub fn print_help() {
215233 let text = "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\
216234 USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]\n\n\
@@ -244,7 +262,7 @@
244262 dry_run: false,
245263 local_images: false,
246264 json: false,
247- vars: BTreeMap::new(),
265+ vars: VarOverrides::None,
248266 };
249267 let mut arguments = arguments.into_iter();
250268 while let Some(argument) = arguments.next() {
@@ -1266,11 +1284,7 @@
12661284 )
12671285 }
12681286
1269-fn read_project(
1270- path: &Path,
1271- root: &Path,
1272- overrides: &BTreeMap<String, String>,
1273-) -> anyhow::Result<Project> {
1287+fn read_project(path: &Path, root: &Path, overrides: &VarOverrides) -> anyhow::Result<Project> {
12741288 let source =
12751289 std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
12761290 let config: Value = serde_json::from_str(&strip_jsonc(&source))
@@ -1875,15 +1889,40 @@
18751889 Some(_) => bail!("config `vars` must be an object"),
18761890 }
18771891 // An asset-only project has no Worker to hand a variable to, so a
1878- // `.dev.vars` beside it is residue, not a binding the guard below
1892+ // `.dev.vars` or `.env` beside it is residue, not a binding the guard below
18791893 // should refuse in the config's name.
18801894 let declared_vars = !vars.is_empty();
18811895 if main.is_some() {
1882- vars.extend(
1883- overrides
1884- .iter()
1885- .map(|(name, value)| (name.as_str(), value.as_str())),
1886- );
1896+ match overrides {
1897+ VarOverrides::None => {}
1898+ VarOverrides::DevVars(entries) => vars.extend(
1899+ entries
1900+ .iter()
1901+ .map(|(name, value)| (name.as_str(), value.as_str())),
1902+ ),
1903+ VarOverrides::DotEnv(entries) => {
1904+ // A config var of the same name is the override the entry
1905+ // exists for; every other binding owns its name.
1906+ let taken = bindings
1907+ .iter()
1908+ .filter_map(|binding| binding.get("name").and_then(Value::as_str))
1909+ .chain(
1910+ assets
1911+ .as_ref()
1912+ .and_then(|assets| assets.config.binding.as_deref()),
1913+ )
1914+ .collect::<BTreeSet<_>>();
1915+ for (name, value) in entries {
1916+ if !valid_binding(name) {
1917+ note!("warning: skipped the dotenv entry {name:?}, which is not a valid binding name");
1918+ } else if taken.contains(name.as_str()) {
1919+ note!("warning: skipped the dotenv entry {name:?}, whose name another binding uses");
1920+ } else {
1921+ vars.insert(name, value);
1922+ }
1923+ }
1924+ }
1925+ }
18871926 }
18881927 for (name, value) in &vars {
18891928 if !valid_binding(name) {
modifiedcrates/celld/dev.rs+94−23View file
@@ -340,7 +340,9 @@
340340 state, so a cell can keep a value that the new configuration rejects. Use\n\
341341 --clean to start from an empty local state.\n\n\
342342 A .dev.vars file beside the config supplies Worker variables in dotenv form,\n\
343-as for wrangler dev. Its entries override the vars of the config.\n\n\
343+as for wrangler dev. Without one, .env and then .env.local supply them, and\n\
344+an entry of these files that cannot be a binding is skipped with a warning.\n\
345+The entries override the vars of the config.\n\n\
344346 OPTIONS:\n --host IP Worker listener host (default: 127.0.0.1)\n --port PORT Worker listener port (default: {DEFAULT_PORT})\n --clean Delete PROJECT/.celld/dev before the server starts\n --logs Show the node warning and information logs\n --no-watch Do not rebuild when a project file changes\n --watch-ignore PATTERN Ignore a project-relative glob; repeat as needed\n -h, --help Show this help"
345347 ),
346348 )
@@ -481,36 +483,105 @@
481483 Ok(Store { database })
482484 }
483485
484-/// The Worker variables of `.dev.vars` beside the config, in the dotenv form
485-/// `wrangler dev` reads. They override the `vars` of the config. Only
486-/// `celld dev` reads the file, so a local credential cannot reach a fleet.
486+/// The Worker variables for `celld dev`, from the files that `wrangler dev`
487+/// reads beside the config (Wrangler getVarsForDev()). A `.dev.vars` file
488+/// wins outright. Without one, `.env` and then `.env.local` apply, and a later
489+/// file overrides an earlier one. Each entry overrides the `vars` of the
490+/// config. Only `celld dev` reads the files, so a local credential cannot
491+/// reach a fleet.
492+fn read_dev_vars(config: &Path) -> anyhow::Result<deploy::VarOverrides> {
493+ // A present `.dev.vars` replaces the dotenv files even when it is empty,
494+ // as in Wrangler, so an entry that the project keeps in `.env` for
495+ // another tool does not reach the Worker beside it.
496+ if let Some(contents) = read_optional(&config.with_file_name(".dev.vars"))? {
497+ return Ok(deploy::VarOverrides::DevVars(parse_dotenv(&contents)));
498+ }
499+ let mut vars = BTreeMap::new();
500+ for name in [".env", ".env.local"] {
501+ if let Some(contents) = read_optional(&config.with_file_name(name))? {
502+ vars.extend(parse_dotenv(&contents));
503+ }
504+ }
505+ Ok(deploy::VarOverrides::DotEnv(vars))
506+}
507+
508+/// The contents of `path`, or `None` when it does not exist. One read, not an
509+/// existence probe and then a read, so a file that vanishes between the two
510+/// cannot fail the build.
487511 #[allow(clippy::disallowed_methods)] // The project is on the operator's host filesystem.
488-fn read_dev_vars(config: &Path) -> anyhow::Result<BTreeMap<String, String>> {
489- let path = config.with_file_name(".dev.vars");
490- if !path.exists() {
491- return Ok(BTreeMap::new());
512+fn read_optional(path: &Path) -> anyhow::Result<Option<String>> {
513+ match std::fs::read_to_string(path) {
514+ Ok(contents) => Ok(Some(contents)),
515+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
516+ Err(error) => Err(error).with_context(|| format!("read {}", path.display())),
492517 }
493- let contents =
494- std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
495- Ok(contents
496- .lines()
497- .map(str::trim)
498- .filter(|line| !line.is_empty() && !line.starts_with('#'))
499- .filter_map(|line| line.split_once('='))
500- .map(|(name, value)| (name.trim(), value.trim()))
501- .filter(|(name, _)| !name.is_empty())
502- .map(|(name, value)| {
518+}
519+
520+fn parse_dotenv(contents: &str) -> BTreeMap<String, String> {
521+ let mut vars = BTreeMap::new();
522+ let mut lines = contents.lines();
523+ while let Some(line) = lines.next() {
524+ let line = line.trim();
525+ if line.is_empty() || line.starts_with('#') {
526+ continue;
527+ }
528+ // dotenv accepts the `export NAME=value` form of a shell-sourced
529+ // file. Without the strip, the name `export NAME` fails binding
530+ // validation, and a `.env` that loaded before stops the build.
531+ let line = line.strip_prefix("export ").map_or(line, str::trim_start);
532+ let Some((name, value)) = line.split_once('=') else {
533+ continue;
534+ };
535+ let (name, value) = (name.trim(), value.trim());
536+ if name.is_empty() {
537+ continue;
538+ }
539+ let value = match quoted_lines(value, &mut lines) {
540+ Some(value) => value,
503541 // One matched pair of quotes comes off; a lone quote is part of
504542 // the value, as in dotenv, so a secret that ends in one survives.
505- let value = ['"', '\'']
543+ None => ['"', '\'']
506544 .into_iter()
507545 .find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote))
508- .unwrap_or(value);
509- (name.to_string(), value.to_string())
510- })
511- .collect())
546+ .unwrap_or(value)
547+ .to_string(),
548+ };
549+ vars.insert(name.to_string(), value);
550+ }
551+ vars
512552 }
513553
554+/// A quoted value that continues on the following lines, as dotenv reads a
555+/// PEM key, joined by newlines without its quotes. Line by line, each base64
556+/// line of the key became a variable of its own or a name that fails binding
557+/// validation. `None` leaves `lines` untouched: the value ends on its own
558+/// line, or no later line closes the quote, so the opening quote is a lone
559+/// character of a one-line value.
560+fn quoted_lines(value: &str, lines: &mut std::str::Lines<'_>) -> Option<String> {
561+ let quote = value
562+ .chars()
563+ .next()
564+ .filter(|quote| matches!(quote, '"' | '\''))?;
565+ let first = &value[1..];
566+ if first.ends_with(quote) {
567+ return None;
568+ }
569+ let mut rest = lines.clone();
570+ let mut joined = first.to_string();
571+ while let Some(line) = rest.next() {
572+ joined.push('\n');
573+ match line.trim_end().strip_suffix(quote) {
574+ Some(last) => {
575+ joined.push_str(last);
576+ *lines = rest;
577+ return Some(joined);
578+ }
579+ None => joined.push_str(line),
580+ }
581+ }
582+ None
583+}
584+
514585 async fn deploy_project(config: &Path, store: &Store, logs: bool) -> anyhow::Result<()> {
515586 let bucket = open_local_bucket(&store.database)?;
516587 let built = deploy::build(&deploy::Options {
modifiedcrates/celld/facet_streams.rs+1−1View file
@@ -182,7 +182,7 @@
182182 match replication {
183183 Some(replication) => {
184184 for stream in &doomed {
185- replication.ltx().discard(stream, epoch);
185+ replication.ltx().delete_local(stream, epoch);
186186 }
187187 replication.ltx().delete_streams(&facet).await
188188 }
modifiedcrates/celld/js.rs+400−112View file
@@ -607,12 +607,17 @@
607607 WsOpen {
608608 scope: String,
609609 ws_id: u64,
610+ /// As on `WsMessage`, for a socket that a facet dialed.
611+ facet_opening: Option<u64>,
610612 protocol: String,
611613 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
612614 },
613615 WsMessage {
614616 scope: String,
615617 ws_id: u64,
618+ /// The opening of the facet that accepted the socket, for an event of
619+ /// a facet's socket. See `facet_socket_refusal`.
620+ facet_opening: Option<u64>,
616621 data: WsIn,
617622 /// Released after the first turn, so the socket can deliver the next
618623 /// message in order without waiting for this handler's async work.
@@ -622,6 +627,8 @@
622627 WsClosed {
623628 scope: String,
624629 ws_id: u64,
630+ /// As on `WsMessage`.
631+ facet_opening: Option<u64>,
625632 code: u16,
626633 reason: String,
627634 was_clean: bool,
@@ -5202,6 +5209,24 @@
52025209 }
52035210 }
52045211
5212+/// Why an event of a facet's socket must not run, if it must not.
5213+///
5214+/// The check runs in the turn that would start the handler, so no abort or
5215+/// give-back can close the facet between the check and the dispatch. An
5216+/// event for a facet that is not open would otherwise reach `_instance`,
5217+/// which constructs a missing instance: the class would run under the
5218+/// facet's scope with no storage and outside its root's lifetime.
5219+///
5220+/// The check compares the opening, not the root epoch. A facet that its root
5221+/// reopened is a new actor that never accepted the socket, and a generation
5222+/// swap reopens a facet at the same epoch. The new isolate's owner counter
5223+/// starts again, so the facet's scope can repeat too.
5224+fn facet_socket_refusal(scope: &str, facet_opening: Option<u64>) -> Option<anyhow::Error> {
5225+ let opening = facet_opening?;
5226+ (storage::facet_opening(scope) != Some(opening))
5227+ .then(|| anyhow!("the Durable Object facet that holds this WebSocket is no longer running"))
5228+}
5229+
52055230 /// Start a cell event's first turn.
52065231 ///
52075232 /// The counterpart of `begin` for the events a cell receives. Where the
@@ -5303,68 +5328,96 @@
53035328 CellJob::WsOpen {
53045329 scope,
53055330 ws_id,
5331+ facet_opening,
53065332 protocol,
53075333 reply,
5308- } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5309- let f = internal_function(tc, "__wsOpen")?;
5310- let arguments = [
5311- v8::String::new(tc, &scope).unwrap().into(),
5312- v8::Number::new(tc, ws_id as f64).into(),
5313- v8::String::new(tc, &protocol).unwrap().into(),
5314- ];
5315- let recv = v8::undefined(tc).into();
5316- f.call(tc, recv, &arguments)
5317- .ok_or_else(|| anyhow!("wsOpen threw"))
5318- }),
5319- CellJob::WsMessage {
5320- scope,
5321- ws_id,
5322- data,
5323- reply,
5324- ..
5325- } => start_cell_event(
5326- tc,
5327- &scope,
5328- Answer::WsMessage(reply),
5329- None,
5330- None,
5331- true,
5332- |tc| {
5333- let (name, data) = match data {
5334- WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
5335- WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
5336- };
5337- let f = internal_function(tc, name)?;
5334+ } => {
5335+ // The dial fails rather than open a socket that no handler of
5336+ // the facet can receive.
5337+ if let Some(refusal) = facet_socket_refusal(&scope, facet_opening) {
5338+ let _ = reply.send(Err(refusal));
5339+ return Begun::Nothing;
5340+ }
5341+ start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5342+ let f = internal_function(tc, "__wsOpen")?;
53385343 let arguments = [
53395344 v8::String::new(tc, &scope).unwrap().into(),
53405345 v8::Number::new(tc, ws_id as f64).into(),
5341- data,
5346+ v8::String::new(tc, &protocol).unwrap().into(),
53425347 ];
53435348 let recv = v8::undefined(tc).into();
53445349 f.call(tc, recv, &arguments)
5345- .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
5346- },
5347- ),
5350+ .ok_or_else(|| anyhow!("wsOpen threw"))
5351+ })
5352+ }
5353+ CellJob::WsMessage {
5354+ scope,
5355+ ws_id,
5356+ facet_opening,
5357+ data,
5358+ reply,
5359+ ..
5360+ } => {
5361+ if let Some(refusal) = facet_socket_refusal(&scope, facet_opening) {
5362+ let _ = reply.send(Err(refusal));
5363+ return Begun::Nothing;
5364+ }
5365+ start_cell_event(
5366+ tc,
5367+ &scope,
5368+ Answer::WsMessage(reply),
5369+ None,
5370+ None,
5371+ true,
5372+ |tc| {
5373+ let (name, data) = match data {
5374+ WsIn::Text(text) => {
5375+ ("__wsMessage", v8::String::new(tc, &text).unwrap().into())
5376+ }
5377+ WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
5378+ };
5379+ let f = internal_function(tc, name)?;
5380+ let arguments = [
5381+ v8::String::new(tc, &scope).unwrap().into(),
5382+ v8::Number::new(tc, ws_id as f64).into(),
5383+ data,
5384+ ];
5385+ let recv = v8::undefined(tc).into();
5386+ f.call(tc, recv, &arguments)
5387+ .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
5388+ },
5389+ )
5390+ }
53485391 CellJob::WsClosed {
53495392 scope,
53505393 ws_id,
5394+ facet_opening,
53515395 code,
53525396 reason,
53535397 was_clean,
53545398 reply,
5355- } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5356- let f = internal_function(tc, "__wsClosed")?;
5357- let arguments = [
5358- v8::String::new(tc, &scope).unwrap().into(),
5359- v8::Number::new(tc, ws_id as f64).into(),
5360- v8::Number::new(tc, f64::from(code)).into(),
5361- v8::String::new(tc, &reason).unwrap().into(),
5362- v8::Boolean::new(tc, was_clean).into(),
5363- ];
5364- let recv = v8::undefined(tc).into();
5365- f.call(tc, recv, &arguments)
5366- .ok_or_else(|| anyhow!("wsClosed threw"))
5367- }),
5399+ } => {
5400+ // A facet that stopped is not told that its socket closed, as an
5401+ // aborted actor in workerd is not: the socket closed because the
5402+ // facet stopped, and no handler is left to run.
5403+ if facet_socket_refusal(&scope, facet_opening).is_some() {
5404+ let _ = reply.send(Ok(None));
5405+ return Begun::Nothing;
5406+ }
5407+ start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5408+ let f = internal_function(tc, "__wsClosed")?;
5409+ let arguments = [
5410+ v8::String::new(tc, &scope).unwrap().into(),
5411+ v8::Number::new(tc, ws_id as f64).into(),
5412+ v8::Number::new(tc, f64::from(code)).into(),
5413+ v8::String::new(tc, &reason).unwrap().into(),
5414+ v8::Boolean::new(tc, was_clean).into(),
5415+ ];
5416+ let recv = v8::undefined(tc).into();
5417+ f.call(tc, recv, &arguments)
5418+ .ok_or_else(|| anyhow!("wsClosed threw"))
5419+ })
5420+ }
53685421 CellJob::Alarm {
53695422 request_id,
53705423 scope,
@@ -6111,15 +6164,15 @@
61116164 id_sc: Vec<u8>,
61126165 props_sc: Vec<u8>,
61136166 file: (std::path::PathBuf, bool),
6114- ) -> Result<Option<i64>> {
6167+ ) -> Result<u64> {
61156168 let compat = self.inner.as_ref().expect("live worker isolate").compat;
61166169 let (mut locker, _cells) = self.lock();
6117- if storage::activation_epoch(cell).is_some() {
6170+ if let Some(opening) = storage::facet_opening(cell) {
61186171 // The facet is already open, but this call carries a newer sample
61196172 // of the root cell. Take it: the egress of this call must wait for
61206173 // what the root cell had committed when the call left it.
61216174 storage::refresh_embedded_root(cell, parent);
6122- return Ok(None);
6175+ return Ok(opening);
61236176 }
61246177 v8::scope!(let hs, &mut *locker);
61256178 let realm = self.realm(hs);
@@ -6140,9 +6193,50 @@
61406193 restored,
61416194 },
61426195 compat,
6143- )
6196+ )?;
6197+ storage::facet_opening(cell).context("the facet opened without an embedded backing")
61446198 }
61456199
6200+ /// The opening of the facet `scope` in this isolate, for a test that
6201+ /// addresses a facet's socket event to it.
6202+ #[cfg(all(test, celld_internal_tests))]
6203+ pub(crate) fn facet_opening_for_test(&mut self, scope: &str) -> Option<u64> {
6204+ let (_locker, _cells) = self.lock();
6205+ storage::facet_opening(scope)
6206+ }
6207+
6208+ /// Close the facet `cell` at `facet_path` of `root`, and every facet
6209+ /// below it that this isolate runs, deepest first. Answers each scope it
6210+ /// closed, including those whose close failed.
6211+ ///
6212+ /// workerd aborts a facet's children with it. A child left open keeps
6213+ /// its stream and its sockets, and the root can reopen the parent and
6214+ /// start a second instance of the same child stream.
6215+ fn close_facet_tree(
6216+ &mut self,
6217+ cell: &str,
6218+ root: &str,
6219+ facet_path: &[String],
6220+ ) -> (Vec<String>, Result<()>) {
6221+ let compat = self.inner.as_ref().expect("live worker isolate").compat;
6222+ let (mut locker, _cells) = self.lock();
6223+ v8::scope!(let hs, &mut *locker);
6224+ let realm = self.realm(hs);
6225+ let context = realm.context;
6226+ let cs = &mut v8::ContextScope::new(hs, context);
6227+ let tc = std::pin::pin!(v8::TryCatch::new(cs));
6228+ let tc = &mut tc.init();
6229+ let mut closed = storage::embedded_facets_below(root, facet_path);
6230+ closed.push(cell.to_string());
6231+ let mut outcome = Ok(());
6232+ for scope in &closed {
6233+ if let Err(error) = adopt_cell(tc, scope, None, compat) {
6234+ outcome = outcome.and(Err(error));
6235+ }
6236+ }
6237+ (closed, outcome)
6238+ }
6239+
61466240 /// Drain the alarm moves the last turn committed in this isolate.
61476241 ///
61486242 /// An alarm move is a turn output, exactly like the ops a turn starts:
@@ -7595,7 +7689,7 @@
75957689 );
75967690 handle.spawn(async move {
75977691 let state = match tokio::task::spawn_blocking(move || Worker::load_config(config)).await {
7598- Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)),
7692+ Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::loaded_worker(worker)),
75997693 Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))),
76007694 Err(error) => LoaderState::Failed(Arc::from(format!(
76017695 "worker loader: load task failed: {error}"
@@ -7607,7 +7701,7 @@
76077701 }
76087702
76097703 /// `__loader_fetch(id, url, method, body, headersJson, streamId, entrypoint,
7610-/// propsSc, limitsJson, tailReporting)` -> Promise<json> or
7704+/// propsSc, limitsJson, tailReporting, cancellable)` -> Promise<json> or
76117705 /// [Promise<json>, Promise<json>].
76127706 /// The loaded-worker analog of `__svc_call`: it encodes the response the same
76137707 /// way and can return a separate report after the invocation finishes.
@@ -7667,6 +7761,25 @@
76677761 }
76687762 };
76697763 let want_tail_report = args.get(9).boolean_value(scope);
7764+ // The caller's AbortSignal cancels through the registry that
7765+ // `__do_call_cancel` already reads, as a service-binding call does. Only a
7766+ // call with a signal registers, because nothing else can name the id.
7767+ let cancellable = args.get(10).boolean_value(scope);
7768+ let (cancel_id, cancel, cancel_guard) = if cancellable {
7769+ let request_id = next_do_request_id();
7770+ let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
7771+ do_call_cancels()
7772+ .lock()
7773+ .unwrap()
7774+ .insert(request_id, cancel_sender);
7775+ (
7776+ Some(request_id),
7777+ Some(cancel_receiver),
7778+ Some(DoCallCancelGuard::new(request_id)),
7779+ )
7780+ } else {
7781+ (None, None, None)
7782+ };
76707783 let (tail_report, tail_receive) = if want_tail_report {
76717784 let (send, receive) = tokio::sync::oneshot::channel();
76727785 (Some(send), Some(receive))
@@ -7688,6 +7801,7 @@
76887801 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
76897802 let stream_service = http_stream_service();
76907803 let async_id = asyncrt::enqueue(async move {
7804+ let mut cancel_guard = cancel_guard;
76917805 // The child's own `IoContext` has an empty egress stack, so nothing
76927806 // inside it gates what it sends onward. Holding the call until the
76937807 // caller's writes are proven makes every effect of the loaded worker
@@ -7705,29 +7819,43 @@
77057819 body,
77067820 headers,
77077821 // A loaded Worker receives an incoming request like a service
7708- // target does. The id selects the stream-aware construction path
7709- // and gives an abandoned request a lifecycle owner.
7710- request_id: Some(next_request_id()),
7822+ // target does. The lifetime below supplies the id, which selects
7823+ // the stream-aware construction path and gives an abandoned
7824+ // request a lifecycle owner.
7825+ request_id: None,
77117826 tail_report,
77127827 reply,
77137828 };
7714- let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
7715- match receive.await {
7716- Ok(Ok(response)) => {
7717- // The response proves that the loaded Worker installed its
7718- // request context. That context owns an unread body tail
7719- // through its waitUntil work.
7720- body_guard.disarm();
7721- encode_http_response(response, false, &stream_service)
7829+ // Without this shared lifetime, a caller's abort rejected only the
7830+ // caller's promise and the child ran to completion with a live
7831+ // `request.signal` (denoland/celld#257).
7832+ let cancellation = crate::runtime::RequestCancellationLifetime::stateless();
7833+ let driving = tokio::spawn(cancellation.clone().drive_fetch_job(slot, job));
7834+ let response = async {
7835+ match receive.await {
7836+ Ok(response) => response,
7837+ Err(_) => Err(match driving.await {
7838+ Err(error) => anyhow::anyhow!("loaded worker task died: {error}"),
7839+ Ok(()) => anyhow::anyhow!("loaded worker dropped response"),
7840+ }),
77227841 }
7723- Ok(Err(error)) => Err(format!("{error}")),
7724- Err(_) => match driving.await {
7725- Err(error) => Err(format!("loaded worker task died: {error}")),
7726- Ok(()) => Err("loaded worker dropped response".to_string()),
7727- },
7842+ };
7843+ let response =
7844+ crate::runtime::receive_service_fetch_response(response, cancellation, cancel).await;
7845+ if let Some(cancel_guard) = cancel_guard.as_mut() {
7846+ cancel_guard.disarm();
77287847 }
7848+ let response = response.map_err(|error| format!("{error}"))?;
7849+ // The response proves that the loaded Worker installed its request
7850+ // context. That context owns an unread body tail through its
7851+ // waitUntil work.
7852+ body_guard.disarm();
7853+ encode_http_response(response, false, &stream_service)
77297854 });
77307855 let response = promise_for(scope, async_id);
7856+ if let Some(request_id) = cancel_id {
7857+ attach_cancel_id(scope, response, request_id);
7858+ }
77317859 let Some(tail_receive) = tail_receive else {
77327860 rv.set(response);
77337861 return;
@@ -7865,11 +7993,55 @@
78657993 struct LoadedFacet {
78667994 slot: Arc<crate::pool::Slot>,
78677995 scope: String,
7996+ /// The cell whose database holds the facet's, which owns the facet.
7997+ root: String,
78687998 stream: String,
78697999 epoch: u64,
8000+ /// See `storage::facet_opening`.
8001+ opening: u64,
78708002 }
78718003
78728004 impl LoadedFacet {
8005+ /// Route the socket of a facet's upgrade through the facet's root.
8006+ ///
8007+ /// Recorded here, where the host knows which facet answered, because the
8008+ /// response's target names only the facet's scope. A target that the
8009+ /// facet did not accept keeps its own route.
8010+ fn attach_websocket(&self, response: &HttpResponse) {
8011+ if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket {
8012+ ws_attach_facet(
8013+ target.id,
8014+ &self.scope,
8015+ FacetSocket {
8016+ root: self.root.clone(),
8017+ stream: self.stream.clone(),
8018+ epoch: self.epoch,
8019+ opening: self.opening,
8020+ },
8021+ );
8022+ }
8023+ }
8024+
8025+ /// Prove the facet's stream before its response leaves, and release a
8026+ /// socket that the facet accepted for a response that fails this proof.
8027+ ///
8028+ /// The response carries the only reference the host has to that socket.
8029+ /// A dropped response would keep the registration and its regular-socket
8030+ /// count for the life of the process. Only the proof is covered: the
8031+ /// later encode fails only when the stream service has closed, and the
8032+ /// facet's own response read fails first on that service.
8033+ ///
8034+ /// Takes the socket's id rather than the response: a response with a
8035+ /// body stream is not `Sync`, so a borrow of it across the proof would
8036+ /// make the op's future not `Send`.
8037+ async fn gate_response(&self, socket: Option<u64>) -> Result<(), String> {
8038+ let gated = self.gate_reply().await;
8039+ if let (Err(_), Some(id)) = (&gated, socket) {
8040+ ws_release_unanswered(id, &self.scope);
8041+ }
8042+ gated
8043+ }
8044+
78738045 /// A facet's reply leaves as workerd's facet output gate lets it: after
78748046 /// every write the facet committed is durable on its own stream. That
78758047 /// covers an earlier call's write this reply can reveal as well as the
@@ -7914,10 +8086,21 @@
79148086 Self::Own(slot) => Ok(slot),
79158087 }
79168088 }
8089+
8090+ /// Whether the facet runs in a loaded Worker's isolate, which the root's
8091+ /// give-back must close and which `ROOT_FACETS` records. A facet of a
8092+ /// loaded Worker's own class runs in that Worker's isolate too.
8093+ fn is_loaded_worker(&self) -> bool {
8094+ match self {
8095+ Self::Loaded(_) => true,
8096+ Self::Own(slot) => slot.is_loaded_worker(),
8097+ }
8098+ }
79178099 }
79188100
79198101 /// The facets that each root runs in loaded Workers' isolates, by the root's
7920-/// cell and epoch.
8102+/// cell and epoch. A facet of a loaded Worker's own class counts, because it
8103+/// runs in that Worker's isolate.
79218104 ///
79228105 /// A loaded Worker can outlive a root through another stub or until garbage
79238106 /// collection. Neither lifetime tells the loaded isolate when a root stops,
@@ -7928,9 +8111,10 @@
79288111 /// state. The adoption turn records each facet here, and the root's
79298112 /// give-back closes them.
79308113 ///
7931-/// A facet of the root's own class is not recorded: `finish_cell_adoption`
7932-/// closes it in the root's give-back turn, and its slot can be freed while a
7933-/// reference is held, so a later turn on it would panic.
8114+/// A facet that runs in the root's own isolate is not recorded:
8115+/// `finish_cell_adoption` closes it in the root's give-back turn, and its
8116+/// slot can be freed while a reference is held, so a later turn on it would
8117+/// panic.
79348118 static ROOT_FACETS: OnceLock<Mutex<HashMap<(String, u64), RootFacets>>> = OnceLock::new();
79358119
79368120 fn root_facets() -> std::sync::MutexGuard<'static, HashMap<(String, u64), RootFacets>> {
@@ -7951,9 +8135,18 @@
79518135 stopped: bool,
79528136 /// Each slot keeps its loaded isolate alive until the release closes
79538137 /// the facet in it.
7954- open: Vec<(Arc<crate::pool::Slot>, String)>,
8138+ open: Vec<RecordedFacet>,
79558139 }
79568140
8141+/// A facet that a root runs in a loaded Worker's isolate.
8142+struct RecordedFacet {
8143+ slot: Arc<crate::pool::Slot>,
8144+ scope: String,
8145+ /// The facet names from the root down to this facet, which find the
8146+ /// facets below an aborted one.
8147+ path: Vec<String>,
8148+}
8149+
79578150 /// One facet call of a root, from its start until its adoption turn.
79588151 struct PendingFacet {
79598152 key: (String, u64),
@@ -7974,7 +8167,12 @@
79748167 /// Record the facet before its adoption. Call inside the adoption turn:
79758168 /// a release that takes the record queues its close behind this turn on
79768169 /// the same slot, and a release that came first makes this refuse.
7977- fn record(&self, slot: &Arc<crate::pool::Slot>, scope: &str) -> Result<(), String> {
8170+ fn record(
8171+ &self,
8172+ slot: &Arc<crate::pool::Slot>,
8173+ scope: &str,
8174+ path: &[String],
8175+ ) -> Result<(), String> {
79788176 let mut roots = root_facets();
79798177 let entry = roots
79808178 .get_mut(&self.key)
@@ -7985,9 +8183,13 @@
79858183 if !entry
79868184 .open
79878185 .iter()
7988- .any(|(open, name)| Arc::ptr_eq(open, slot) && name == scope)
8186+ .any(|open| Arc::ptr_eq(&open.slot, slot) && open.scope == scope)
79898187 {
7990- entry.open.push((slot.clone(), scope.to_string()));
8188+ entry.open.push(RecordedFacet {
8189+ slot: slot.clone(),
8190+ scope: scope.to_string(),
8191+ path: path.to_vec(),
8192+ });
79918193 }
79928194 Ok(())
79938195 }
@@ -8043,13 +8245,57 @@
80438245 open
80448246 };
80458247 // A nested facet records after its parent, so it closes first.
8046- for (slot, scope) in open.into_iter().rev() {
8248+ for RecordedFacet { slot, scope, .. } in open.into_iter().rev() {
80478249 if let Err(error) = slot.turn(|worker| worker.own_cell(&scope, None)).await {
80488250 tracing::warn!(root, epoch, facet = %scope, %error, "a facet did not close with its root");
80498251 }
8252+ ws_close_facet(&scope, "the parent Durable Object was released");
80508253 }
80518254 }
80528255
8256+/// Take the records of the facets below the facet at `path`, deepest first.
8257+/// Their isolates can differ from the aborted facet's: a child of a loaded
8258+/// class runs in its own loaded Worker.
8259+fn take_recorded_facets_below(root: &str, epoch: u64, path: &[String]) -> Vec<RecordedFacet> {
8260+ let key = (root.to_string(), epoch);
8261+ let mut roots = root_facets();
8262+ let Some(entry) = roots.get_mut(&key) else {
8263+ return Vec::new();
8264+ };
8265+ let (mut below, kept) = std::mem::take(&mut entry.open)
8266+ .into_iter()
8267+ .partition::<Vec<_>, _>(|open| open.path.len() > path.len() && open.path.starts_with(path));
8268+ entry.open = kept;
8269+ if entry.pending == 0 && entry.open.is_empty() {
8270+ roots.remove(&key);
8271+ }
8272+ below.sort_by_key(|open| std::cmp::Reverse(open.path.len()));
8273+ below
8274+}
8275+
8276+/// The loaded isolate that runs the facet `scope` of `root` at `epoch`, while
8277+/// the root's give-back has not closed it. `None` also answers for a facet in
8278+/// the root's own isolate, which the root's residency pins instead.
8279+pub(crate) fn recorded_facet_slot(
8280+ root: &str,
8281+ epoch: u64,
8282+ scope: &str,
8283+) -> Option<Arc<crate::pool::Slot>> {
8284+ root_facets()
8285+ .get(&(root.to_string(), epoch))?
8286+ .open
8287+ .iter()
8288+ .find(|open| open.scope == scope)
8289+ .map(|open| open.slot.clone())
8290+}
8291+
8292+/// Prove every write that a facet committed on its own stream.
8293+pub(crate) async fn prove_facet_stream(stream: String, epoch: u64) -> anyhow::Result<()> {
8294+ prove_facet(stream, epoch)
8295+ .await
8296+ .map_err(|refusal| anyhow!("facet output: {refusal}"))
8297+}
8298+
80538299 /// Drop an aborted facet's record, which its abort closed already.
80548300 fn forget_root_facet(root: &str, epoch: u64, slot: &Arc<crate::pool::Slot>, scope: &str) {
80558301 let key = (root.to_string(), epoch);
@@ -8057,7 +8303,7 @@
80578303 if let Some(entry) = roots.get_mut(&key) {
80588304 entry
80598305 .open
8060- .retain(|(open, name)| !(Arc::ptr_eq(open, slot) && name == scope));
8306+ .retain(|open| !(Arc::ptr_eq(&open.slot, slot) && open.scope == scope));
80618307 if entry.pending == 0 && entry.open.is_empty() {
80628308 roots.remove(&key);
80638309 }
@@ -8065,12 +8311,13 @@
80658311 }
80668312
80678313 async fn prepare_facet(host: FacetHost, start: FacetStart) -> Result<LoadedFacet, String> {
8068- let pending = match host {
8069- FacetHost::Loaded(_) => Some(PendingFacet::begin(
8314+ let pending = if host.is_loaded_worker() {
8315+ Some(PendingFacet::begin(
80708316 &start.parent.root_scope,
80718317 start.parent.epoch,
8072- )?),
8073- FacetHost::Own(_) => None,
8318+ )?)
8319+ } else {
8320+ None
80748321 };
80758322 let slot = host.slot().await?;
80768323 let file = open_facet_file(&start.parent, &start.name).await?;
@@ -8084,28 +8331,31 @@
80848331 &start.owner,
80858332 &start.name,
80868333 );
8087- slot.turn(|worker| {
8088- if let Some(pending) = &pending {
8089- pending.record(&slot, &scope)?;
8090- }
8091- worker
8092- .own_embedded_cell(
8093- &scope,
8094- &start.parent,
8095- &start.name,
8096- start.id_sc,
8097- start.props_sc,
8098- file,
8099- )
8100- .map_err(|error| format!("{error}"))
8101- })
8102- .await
8103- .map_err(|error| format!("worker loader facet: {error}"))?;
8334+ let opening = slot
8335+ .turn(|worker| {
8336+ if let Some(pending) = &pending {
8337+ pending.record(&slot, &scope, &names)?;
8338+ }
8339+ worker
8340+ .own_embedded_cell(
8341+ &scope,
8342+ &start.parent,
8343+ &start.name,
8344+ start.id_sc,
8345+ start.props_sc,
8346+ file,
8347+ )
8348+ .map_err(|error| format!("{error}"))
8349+ })
8350+ .await
8351+ .map_err(|error| format!("worker loader facet: {error}"))?;
81048352 Ok(LoadedFacet {
81058353 slot,
81068354 scope,
8355+ root: start.parent.root_scope,
81078356 stream,
81088357 epoch,
8358+ opening,
81098359 })
81108360 }
81118361
@@ -8277,14 +8527,19 @@
82778527 trace,
82788528 ));
82798529 let replied = receive.await;
8280- if replied.is_ok() {
8530+ if let Ok(Err(_)) = &replied {
82818531 facet.gate_reply().await?;
82828532 }
82838533 match replied {
82848534 Ok(Ok(response)) => {
82858535 body_guard.disarm();
8286- facet.gate_reply().await?;
8287- encode_http_response(response, false, &stream_service)
8536+ let socket = match &response.websocket {
8537+ Some(HttpResponseWebSocket::Cell(target)) => Some(target.id),
8538+ _ => None,
8539+ };
8540+ facet.gate_response(socket).await?;
8541+ facet.attach_websocket(&response);
8542+ encode_http_response(response, true, &stream_service)
82888543 }
82898544 Ok(Err(error)) => Err(format!("{error}")),
82908545 Err(_) => match driving.await {
@@ -8308,22 +8563,55 @@
83088563 let name = args.get(4).to_rust_string_lossy(scope);
83098564 let host = FacetHost::of(loader);
83108565 let facet_scope = facet_scope(&class_name, &parent_scope, &owner, &name);
8311- // The root that recorded the facet. A parent without storage has no
8312- // record to drop.
8566+ // The root that recorded the facet, and the facet's place below it. A
8567+ // parent without storage has no record to drop and no facet below.
83138568 let root = storage::storage_identity(&parent_scope)
83148569 .ok()
83158570 .flatten()
8316- .map(|parent| (parent.root_scope, parent.epoch));
8571+ .map(|parent| {
8572+ let mut path = parent.facet_path;
8573+ path.push(name.clone());
8574+ (parent.root_scope, parent.epoch, path)
8575+ });
83178576 let async_id = asyncrt::enqueue(async move {
83188577 let host = host?;
8319- let loaded = matches!(host, FacetHost::Loaded(_));
8578+ let recorded = host.is_loaded_worker();
83208579 let slot = host.slot().await?;
8321- slot.turn(|worker| worker.own_cell(&facet_scope, None))
8322- .await
8323- .map_err(|error| format!("abort facet: {error}"))?;
8324- if let (true, Some((root, epoch))) = (loaded, root) {
8325- forget_root_facet(&root, epoch, &slot, &facet_scope);
8580+ const ABORTED: &str = "the Durable Object facet was aborted";
8581+ // A facet below this one can run in another loaded Worker, which
8582+ // only its root's record names.
8583+ let below = match &root {
8584+ Some((root, epoch, path)) => take_recorded_facets_below(root, *epoch, path),
8585+ None => Vec::new(),
8586+ };
8587+ for RecordedFacet { slot, scope, .. } in below {
8588+ if let Err(error) = slot.turn(|worker| worker.own_cell(&scope, None)).await {
8589+ tracing::warn!(facet = %scope, %error, "a facet did not close with its parent");
8590+ }
8591+ ws_close_facet(&scope, ABORTED);
83268592 }
8593+ let (closed, outcome) = match &root {
8594+ Some((root, _, path)) => {
8595+ slot.turn(|worker| worker.close_facet_tree(&facet_scope, root, path))
8596+ .await
8597+ }
8598+ None => {
8599+ let outcome = slot
8600+ .turn(|worker| worker.own_cell(&facet_scope, None))
8601+ .await
8602+ .map(|_| ());
8603+ (vec![facet_scope.clone()], outcome)
8604+ }
8605+ };
8606+ // Close the sockets whether or not the close turn succeeded: no
8607+ // later event can reach a facet that its parent aborted.
8608+ for scope in &closed {
8609+ ws_close_facet(scope, ABORTED);
8610+ }
8611+ if let (true, Some((root, epoch, _))) = (recorded, &root) {
8612+ forget_root_facet(root, *epoch, &slot, &facet_scope);
8613+ }
8614+ outcome.map_err(|error| format!("abort facet: {error}"))?;
83278615 Ok(Vec::new())
83288616 });
83298617 rv.set(promise_for(scope, async_id));
modifiedcrates/celld/js/bootstrap.rs+17−2View file
@@ -736,8 +736,10 @@
736736 /// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
737737 /// resolve it, and every export deriving from `DurableObject` in
738738 /// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
739-/// reported as such (Workerd getExportedHandler()). Runs once per load; the
740-/// check is a prototype walk, not a call into user code.
739+/// reported as such (Workerd getExportedHandler()). Every class export that
740+/// is not an entrypoint or a workflow also lands in `__cell.classes`, so a
741+/// facet can start it. Runs once per load; the check is a prototype walk, not a
742+/// call into user code.
741743 pub(super) fn register_entrypoints(
742744 scope: &mut v8::PinScope,
743745 ns: v8::Local<v8::Object>,
@@ -772,6 +774,10 @@
772774 let durable_base = cf
773775 .get(scope, key.into())
774776 .ok_or_else(|| anyhow!("missing DurableObject base"))?;
777+ let key = v8::String::new(scope, "WorkflowEntrypoint").unwrap();
778+ let workflow_base = cf
779+ .get(scope, key.into())
780+ .ok_or_else(|| anyhow!("missing WorkflowEntrypoint base"))?;
775781 let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
776782 return Ok(());
777783 };
@@ -801,6 +807,14 @@
801807 } else if call_extends(scope, extends, value, durable_base)? {
802808 do_exports.set(scope, name, yes.into());
803809 classes.set(scope, name, value);
810+ } else if !call_extends(scope, extends, value, workflow_base)? {
811+ // Workerd processEntrypointClass(): a class that extends none of
812+ // the runtime bases is a Durable Object class (missingSuperclass).
813+ // A loaded Worker's facet class reaches `_instance` only through
814+ // this registry, so without it a plain class fails with "no DO
815+ // class". It stays out of `doExports`: that entry grants RPC
816+ // without the js_rpc flag, which workerd gives only a subclass.
817+ classes.set(scope, name, value);
804818 }
805819 }
806820 Ok(())
@@ -1001,6 +1015,7 @@
10011015 let source = format!("__celld.__cell.release({facet:?});");
10021016 run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("release failed"))?;
10031017 storage::close(&facet);
1018+ crate::ws_registry::ws_close_facet(&facet, "the parent Durable Object was released");
10041019 }
10051020 storage::close(cell);
10061021 return Ok(None);
modifiedcrates/celld/js/harness.js+17−2View file
@@ -2215,9 +2215,13 @@
22152215 ? new CelldHttpBodyStream(response.streamId)
22162216 : response.body !== undefined ? response.body
22172217 : Uint8Array.from(response.bodyBytes || []);
2218+ // The facet's socket lives in the facet's isolate. The target lets
2219+ // the root return the upgrade, or accept the client end that the
2220+ // wrapper binds to the facet's socket.
22182221 return __wrapServiceResponse(new Response(responseBody, {
22192222 status: response.status,
22202223 headers: response.headers,
2224+ __wsTarget: response.wsTarget,
22212225 }), req.url);
22222226 });
22232227 };
@@ -3237,6 +3241,10 @@
32373241 async fetch(input, init) {
32383242 const { id, tails } = await loadPromise;
32393243 const req = new Request(input, init);
3244+ // The caller's signal, never the incoming request's own, as for a
3245+ // service binding.
3246+ const signal = req._signalForSubrequests;
3247+ if (signal?.aborted) throw signal.reason;
32403248 // The verbatim header list; see the note on the outbound `fetch`.
32413249 // The loaded worker rebuilds a `Headers` from these pairs, so a
32423250 // repeat and its casing survive the isolate boundary.
@@ -3245,8 +3253,11 @@
32453253 const loaded = __loader_fetch(
32463254 id, req.url, req.method, body, headers, streamId, entrypoint,
32473255 propsSc === undefined ? new Uint8Array() : propsSc,
3248- limitsJson, tails.length !== 0);
3249- const response = tails.length === 0 ? loaded : loaded[0];
3256+ limitsJson, tails.length !== 0, signal != null);
3257+ const dispatch = tails.length === 0 ? loaded : loaded[0];
3258+ const response = signal
3259+ ? __awaitCancellableDoCall(dispatch, signal)
3260+ : dispatch;
32503261 if (tails.length !== 0) {
32513262 const delivery = loaded[1]
32523263 .then((report) => JSON.parse(report))
@@ -10782,6 +10793,10 @@
1078210793 __celld.__advanceIoTime = (timestamp) => {
1078310794 __ioTimestamp = timestamp;
1078410795 };
10796+// Workerd ServiceWorkerGlobalScope: `self` is the global scope, as a writable,
10797+// enumerable data property. Libraries probe it to find the global, and
10798+// @cloudflare/worker-bundler throws when it is absent.
10799+globalThis.self = globalThis;
1078510800 if (!globalThis.navigator) globalThis.navigator = {
1078610801 userAgent: "Cloudflare-Workers", hardwareConcurrency: 1,
1078710802 language: "en", languages: ["en"],
modifiedcrates/celld/js/websocket.rs+61−2View file
@@ -22,7 +22,7 @@
2222 fn prepare_worker_websocket_handoff(id: u64) {
2323 let (inbound, receiver) = ws_pull_channel();
2424 ws_pull_register(id, receiver);
25- ws_register_outbound(id, "");
25+ ws_register_outbound(id, "", None);
2626 ws_track_request_socket(id);
2727 let registry = ws_registry();
2828 let replaced = registry.lock().unwrap().worker_handoffs.insert(id, inbound);
@@ -301,6 +301,43 @@
301301 .unwrap_or(0);
302302 prepare_worker_websocket_handoff(id);
303303 }
304+/// The facet record of an outbound socket that `cell` opens, when the running
305+/// event belongs to a Durable Object facet.
306+///
307+/// A facet is not a cell. A socket that names the facet's scope as its cell
308+/// starts an activation of a class that no Worker exports, so the upgrade
309+/// fails with `RuntimeFailed`. The socket must route, register, and gate
310+/// through the facet's root instead. The record comes from the frame that
311+/// the host installed when the event started, not from `cell`, because the
312+/// scope crosses application JavaScript.
313+fn dialing_facet(scope: &mut v8::PinScope, cell: &str) -> Result<Option<FacetSocket>, String> {
314+ if cell.is_empty() {
315+ return Ok(None);
316+ }
317+ let Some(EgressFrame {
318+ storage,
319+ root: Some(root),
320+ ..
321+ }) = current_cell_event(&event_context(scope))
322+ else {
323+ return Ok(None);
324+ };
325+ if storage != cell {
326+ return Err(format!(
327+ "websocket: the socket names {cell}, but the running Durable Object facet is {storage}"
328+ ));
329+ }
330+ let opening = storage::facet_opening(&storage).ok_or(
331+ "websocket: the Durable Object facet that opened this socket is no longer running",
332+ )?;
333+ Ok(Some(FacetSocket {
334+ root: root.cell,
335+ stream: root.stream,
336+ epoch: root.epoch,
337+ opening,
338+ }))
339+}
340+
304341 /// `fetch(url, { headers: { Upgrade: "websocket" } })`. Returns a JSON
305342 /// envelope: either an upgraded socket, or the ordinary response a server sent
306343 /// instead, which the caller returns unchanged.
@@ -330,6 +367,10 @@
330367 .map(|n| n.value() as u64)
331368 .unwrap_or(0);
332369 let cell = args.get(1).to_rust_string_lossy(scope);
370+ let facet = match dialing_facet(scope, &cell) {
371+ Ok(facet) => facet,
372+ Err(error) => return loader_throw(scope, &error),
373+ };
333374 let url = args.get(2).to_rust_string_lossy(scope);
334375 // The subprotocol list is read back out of these headers, so a silent
335376 // default opened the socket with no headers and no subprotocol at all.
@@ -366,6 +407,7 @@
366407 headers,
367408 want_response: true,
368409 target: None,
410+ facet,
369411 reply: tx,
370412 })
371413 .is_ok()
@@ -451,6 +493,10 @@
451493 .map(|n| n.value() as u64)
452494 .unwrap_or(0);
453495 let cell = args.get(1).to_rust_string_lossy(scope);
496+ let facet = match dialing_facet(scope, &cell) {
497+ Ok(facet) => facet,
498+ Err(error) => return loader_throw(scope, &error),
499+ };
454500 let url = args.get(2).to_rust_string_lossy(scope);
455501 let protocols: Vec<String> =
456502 match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) {
@@ -482,6 +528,7 @@
482528 headers: Vec::new(),
483529 want_response: false,
484530 target: None,
531+ facet,
485532 reply: tx,
486533 })
487534 .is_ok()
@@ -526,6 +573,14 @@
526573 // accounted against the isolate holding it, exactly as `op_ws_connect`
527574 // accounts an outbound one.
528575 let cell = args.get(2).to_rust_string_lossy(scope);
576+ // The caller end's frames reach this isolate through its pull queue, so
577+ // they never route by `cell`. The record still matters: a facet that
578+ // stops closes its sockets by it, and this end would otherwise keep the
579+ // other Durable Object's socket open after the facet is gone.
580+ let facet = match dialing_facet(scope, &cell) {
581+ Ok(facet) => facet,
582+ Err(error) => return loader_throw(scope, &error),
583+ };
529584 let (pull_tx, pull_rx) = ws_pull_channel();
530585 ws_pull_register(id, pull_rx);
531586 if cell.is_empty() {
@@ -535,7 +590,7 @@
535590 // the pipe task buffers as a pending frame instead of being dropped for
536591 // a socket the registry has never heard of. `accept()` opens the socket
537592 // synchronously, so that window is reachable by an ordinary `send()`.
538- ws_register_outbound(id, &cell);
593+ ws_register_outbound(id, &cell, facet);
539594 let (tx, rx) = tokio::sync::oneshot::channel();
540595 let sent = outbound_ws_tx().is_some_and(|sender| {
541596 sender
@@ -548,6 +603,8 @@
548603 headers: Vec::new(),
549604 want_response: false,
550605 target: Some(target),
606+ // `scope` names the target, which keeps its own route.
607+ facet: None,
551608 reply: tx,
552609 })
553610 .is_ok()
@@ -613,6 +670,7 @@
613670 attachment: None,
614671 pending: Vec::new(),
615672 auto_response_at: None,
673+ facet: None,
616674 });
617675 replaced_regular_scope
618676 };
@@ -644,6 +702,7 @@
644702 attachment: None,
645703 pending: Vec::new(),
646704 auto_response_at: None,
705+ facet: None,
647706 });
648707 true
649708 } else {
modifiedcrates/celld/lib.rs+2−286View file
@@ -8,294 +8,10 @@
88 //! `celld_logic::on_event`. Adapter futures never borrow core state; they send
99 //! versioned completion events back through its mailbox.
1010
11-// This implementation is substantially adapted from Tokio 1.53.1 select.rs.
12-// Copyright (c) Tokio Contributors. MIT license. See ../../LICENSE.tokio.
13-//
14-// Every `tokio::` item re-exported below is `doc(hidden)` upstream, so none of
15-// them carries a compatibility guarantee. Tokio can rename, reshape, or delete
16-// any of them in a patch release without breaking its own semver promise, and
17-// the `tokio = "1"` caret range in ../../Cargo.toml does not prevent that. A
18-// Tokio version bump must therefore re-check this facade against the select.rs
19-// of the new version.
20-//
21-// The failure mode is a compile error in celld, not a behavior change, so
22-// nothing broken ships and no test passes wrongly. Without this note the person
23-// who runs `cargo update` sees a macro that no longer resolves and gets no
24-// pointer to the cause.
25-//
26-// Rejected: narrowing the `tokio` constraint to the range this facade is known
27-// to work with. That blocks unrelated Tokio fixes for the whole dependency tree
28-// to guard against a break the compiler already makes un-missable. Do not
29-// "fix" this by pinning.
11+mod tokio_select;
3012 #[doc(hidden)]
31-pub mod __asyncrt_select_support {
32- pub use std::future::{poll_fn, Future, IntoFuture};
33- pub use std::pin::Pin;
34- pub use std::task::{ready, Poll};
35- pub use tokio::macros::support::poll_budget_available;
36- pub use tokio::{
37- count, count_field, select_priv_clean_pattern, select_priv_declare_output_enum,
38- select_variant,
39- };
40-}
13+pub use tokio_select::__asyncrt_select_support;
4114
42-#[macro_export]
43-macro_rules! __celld_domain_select {
44- (@reason $reason:literal) => {{
45- const _: () = {
46- let reason: &str = $reason;
47- assert!(
48- !reason.is_empty(),
49- "select_biased! requires a non-empty reason string"
50- );
51- };
52- }};
53- (@start fair $branches:expr) => {
54- $crate::asyncrt::select_start($branches)
55- };
56- (@start (biased $reason:literal) $_branches:expr) => {{
57- $crate::__celld_domain_select!(@reason $reason);
58- 0_u32
59- }};
60- (@ {
61- mode=$mode:tt;
62- ( $($count:tt)* )
63- $( ( $($skip:tt)* ) $bind:pat = $future:expr, if $condition:expr => $handler:expr, )+
64- ; $else:expr
65- }) => {{
66- #[doc(hidden)]
67- mod __celld_select_util {
68- $crate::__asyncrt_select_support::select_priv_declare_output_enum!(
69- ( $($count)* )
70- );
71- }
72-
73- const BRANCHES: u32 = $crate::__asyncrt_select_support::count!($($count)*);
74- let mut disabled: __celld_select_util::Mask = Default::default();
75-
76- $(
77- if !$condition {
78- let mask: __celld_select_util::Mask =
79- 1 << $crate::__asyncrt_select_support::count!($($skip)*);
80- disabled |= mask;
81- }
82- )*
83-
84- #[allow(unused_mut)]
85- let mut output = {
86- let futures_init = ($($future,)+);
87- let mut futures = ($(
88- $crate::__asyncrt_select_support::IntoFuture::into_future(
89- $crate::__asyncrt_select_support::count_field!(
90- futures_init.$($skip)*
91- )
92- ),
93- )+);
94- #[allow(unused_mut)]
95- let mut futures = &mut futures;
96-
97- $crate::__asyncrt_select_support::poll_fn(|context| {
98- $crate::__asyncrt_select_support::ready!(
99- $crate::__asyncrt_select_support::poll_budget_available(context)
100- );
101-
102- let mut is_pending = false;
103- let start = $crate::__celld_domain_select!(@start $mode BRANCHES);
104-
105- for offset in 0..BRANCHES {
106- let branch;
107- #[allow(clippy::modulo_one)]
108- {
109- branch = (start + offset) % BRANCHES;
110- }
111- match branch {
112- $(
113- #[allow(unreachable_code)]
114- $crate::__asyncrt_select_support::count!($($skip)*) => {
115- let mask = 1 << branch;
116- if disabled & mask == mask {
117- continue;
118- }
119-
120- let ($($skip,)* future, ..) = &mut *futures;
121- // SAFETY: The tuple stays on the stack and no future moves.
122- let future = unsafe {
123- $crate::__asyncrt_select_support::Pin::new_unchecked(future)
124- };
125- let value = match $crate::__asyncrt_select_support::Future::poll(
126- future,
127- context,
128- ) {
129- $crate::__asyncrt_select_support::Poll::Ready(value) => value,
130- $crate::__asyncrt_select_support::Poll::Pending => {
131- is_pending = true;
132- continue;
133- }
134- };
135-
136- disabled |= mask;
137- #[allow(unreachable_patterns, unused_variables, unused_mut)]
138- match &value {
139- $crate::__asyncrt_select_support::select_priv_clean_pattern!(
140- $bind
141- ) => {}
142- _ => continue,
143- }
144-
145- return $crate::__asyncrt_select_support::Poll::Ready(
146- $crate::__asyncrt_select_support::select_variant!(
147- __celld_select_util::Out,
148- ($($skip)*)
149- )(value),
150- );
151- }
152- )*
153- _ => unreachable!("the select branch index is out of range"),
154- }
155- }
156-
157- if is_pending {
158- $crate::__asyncrt_select_support::Poll::Pending
159- } else {
160- $crate::__asyncrt_select_support::Poll::Ready(
161- __celld_select_util::Out::Disabled,
162- )
163- }
164- })
165- .await
166- };
167-
168- #[allow(unreachable_patterns)]
169- match output {
170- $(
171- $crate::__asyncrt_select_support::select_variant!(
172- __celld_select_util::Out,
173- ($($skip)*) ($bind)
174- ) => $handler,
175- )*
176- __celld_select_util::Out::Disabled => $else,
177- _ => unreachable!("the select output does not match a branch"),
178- }
179- }};
180-
181- (@ { mode=$mode:tt; $($tokens:tt)* }) => {
182- $crate::__celld_domain_select!(@ {
183- mode=$mode;
184- $($tokens)*;
185- panic!("all branches are disabled and there is no else branch")
186- })
187- };
188- (@ { mode=$mode:tt; $($tokens:tt)* } else => $else:expr $(,)?) => {
189- $crate::__celld_domain_select!(@ { mode=$mode; $($tokens)*; $else })
190- };
191- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
192- $pattern:pat = $future:expr, if $condition:expr => $handler:block, $($rest:tt)*) => {
193- $crate::__celld_domain_select!(@ {
194- mode=$mode;
195- ($($skip)* _)
196- $($tokens)*
197- ($($skip)*) $pattern = $future, if $condition => $handler,
198- } $($rest)*)
199- };
200- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
201- $pattern:pat = $future:expr => $handler:block, $($rest:tt)*) => {
202- $crate::__celld_domain_select!(@ {
203- mode=$mode;
204- ($($skip)* _)
205- $($tokens)*
206- ($($skip)*) $pattern = $future, if true => $handler,
207- } $($rest)*)
208- };
209- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
210- $pattern:pat = $future:expr, if $condition:expr => $handler:block $($rest:tt)*) => {
211- $crate::__celld_domain_select!(@ {
212- mode=$mode;
213- ($($skip)* _)
214- $($tokens)*
215- ($($skip)*) $pattern = $future, if $condition => $handler,
216- } $($rest)*)
217- };
218- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
219- $pattern:pat = $future:expr => $handler:block $($rest:tt)*) => {
220- $crate::__celld_domain_select!(@ {
221- mode=$mode;
222- ($($skip)* _)
223- $($tokens)*
224- ($($skip)*) $pattern = $future, if true => $handler,
225- } $($rest)*)
226- };
227- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
228- $pattern:pat = $future:expr, if $condition:expr => $handler:expr) => {
229- $crate::__celld_domain_select!(@ {
230- mode=$mode;
231- ($($skip)* _)
232- $($tokens)*
233- ($($skip)*) $pattern = $future, if $condition => $handler,
234- })
235- };
236- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
237- $pattern:pat = $future:expr => $handler:expr) => {
238- $crate::__celld_domain_select!(@ {
239- mode=$mode;
240- ($($skip)* _)
241- $($tokens)*
242- ($($skip)*) $pattern = $future, if true => $handler,
243- })
244- };
245- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
246- $pattern:pat = $future:expr, if $condition:expr => $handler:expr, $($rest:tt)*) => {
247- $crate::__celld_domain_select!(@ {
248- mode=$mode;
249- ($($skip)* _)
250- $($tokens)*
251- ($($skip)*) $pattern = $future, if $condition => $handler,
252- } $($rest)*)
253- };
254- (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
255- $pattern:pat = $future:expr => $handler:expr, $($rest:tt)*) => {
256- $crate::__celld_domain_select!(@ {
257- mode=$mode;
258- ($($skip)* _)
259- $($tokens)*
260- ($($skip)*) $pattern = $future, if true => $handler,
261- } $($rest)*)
262- };
263-
264- (biased; $($tokens:tt)*) => {
265- compile_error!(
266- "select! is fair and does not accept `biased;`; use select_biased! with a reason"
267- )
268- };
269- (else => $else:expr $(,)?) => {{ $else }};
270- ($pattern:pat = $($tokens:tt)*) => {
271- $crate::__celld_domain_select!(@ {
272- mode=fair;
273- ()
274- } $pattern = $($tokens)*)
275- };
276- () => {
277- compile_error!("select! requires at least one branch")
278- };
279-}
280-
281-#[doc(hidden)]
282-#[macro_export]
283-macro_rules! __celld_domain_select_biased {
284- ($reason:literal; else => $else:expr $(,)?) => {{
285- $crate::__celld_domain_select!(@reason $reason);
286- $else
287- }};
288- ($reason:literal; $pattern:pat = $($tokens:tt)*) => {{
289- $crate::__celld_domain_select!(@ {
290- mode=(biased $reason);
291- ()
292- } $pattern = $($tokens)*)
293- }};
294- ($($tokens:tt)*) => {
295- compile_error!("select_biased! requires a non-empty reason string as its first token")
296- };
297-}
298-
29915 pub mod actor;
30016 #[cfg(all(test, celld_internal_tests))]
30117 mod conformance_core_loop_tests {
modifiedcrates/celld/ltx_repl.rs+365−73View file
@@ -629,6 +629,86 @@
629629 pub concurrency: usize,
630630 }
631631
632+/// The node settings that [`LtxRepl`] fixes at construction from the
633+/// environment, after parsing. [`LtxConfig::from_env`] is their only reader.
634+///
635+/// The settings travel as one value because a test process has one
636+/// environment. Every node of a simulated fleet runs in that process, so a
637+/// constructor that read the environment itself gave every node the same
638+/// values. A test that needed one node with its own value for a setting
639+/// such as the grace then needed a builder that overwrote a field after
640+/// construction, one per setting, and that test entered through a path
641+/// production never takes. Here production and a test both pass a config
642+/// to the same constructor body; only the source of the values differs.
643+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644+pub(crate) struct LtxConfig {
645+ /// How old the newest object of a superseded epoch must be before epoch
646+ /// GC deletes the epoch, or `None` when epoch GC is off
647+ /// (`CELLD_LTX_RETENTION_SECS`, unset or `0`). `Some(0)` is on with no
648+ /// grace, a value the environment cannot express.
649+ pub(crate) epoch_gc_grace_ms: Option<u64>,
650+ /// Bytes per second a paged cell hydrates in the background, 0 for none
651+ /// (`CELLD_LTX_HYDRATE_MBPS`).
652+ pub(crate) hydrate_bytes_per_s: u64,
653+ /// The operator's switch for paged restore (`CELLD_LTX_PAGED`).
654+ pub(crate) paged_restore: bool,
655+ /// The chain size, in bytes, from which a restore pages instead of
656+ /// cloning (`CELLD_LTX_PAGED_MIN_MB`).
657+ pub(crate) paged_min_bytes: u64,
658+ /// The TRUNCATE checkpoint threshold of a non-Queue cell, 0 to disable
659+ /// truncation (`CELLD_LTX_TRUNCATE_PAGES`).
660+ pub(crate) truncate_pages: u32,
661+}
662+
663+impl LtxConfig {
664+ /// Read the settings from the process environment.
665+ pub(crate) fn from_env() -> Self {
666+ Self::from_lookup(crate::env_vars::value)
667+ }
668+
669+ /// Read the settings through `lookup`, which answers like
670+ /// [`crate::env_vars::value`]. A test supplies values here without
671+ /// mutating the process environment, which every parallel test shares.
672+ ///
673+ /// An unreadable or unparsable value falls back to the default instead
674+ /// of failing construction. `env_vars::validate` rejects some of these
675+ /// values at startup, but not all of them: it does not check
676+ /// `CELLD_LTX_HYDRATE_MBPS` or `CELLD_LTX_PAGED_MIN_MB`, and it checks
677+ /// `CELLD_LTX_TRUNCATE_PAGES` as a `u64`. A production node can
678+ /// therefore reach a fallback.
679+ fn from_lookup(lookup: impl Fn(&str) -> anyhow::Result<Option<String>>) -> Self {
680+ let optional_u64 = |name: &str| {
681+ lookup(name).and_then(|value| crate::env_vars::parse_optional::<u64>(name, value))
682+ };
683+ Self {
684+ epoch_gc_grace_ms: optional_u64("CELLD_LTX_RETENTION_SECS")
685+ .unwrap_or(None)
686+ .filter(|secs| *secs > 0)
687+ .map(|secs| secs.saturating_mul(1000)),
688+ hydrate_bytes_per_s: optional_u64("CELLD_LTX_HYDRATE_MBPS")
689+ .unwrap_or(None)
690+ .unwrap_or(DEFAULT_HYDRATE_MBPS)
691+ .saturating_mul(1 << 20),
692+ paged_restore: lookup("CELLD_LTX_PAGED")
693+ .and_then(|value| {
694+ crate::env_vars::parse_flag("CELLD_LTX_PAGED", value.as_deref(), true)
695+ })
696+ .unwrap_or(true),
697+ paged_min_bytes: optional_u64("CELLD_LTX_PAGED_MIN_MB")
698+ .unwrap_or(None)
699+ .unwrap_or(DEFAULT_PAGED_MIN_MB)
700+ .saturating_mul(1 << 20),
701+ truncate_pages: lookup("CELLD_LTX_TRUNCATE_PAGES")
702+ .and_then(|value| {
703+ crate::env_vars::parse_optional::<u32>("CELLD_LTX_TRUNCATE_PAGES", value)
704+ })
705+ .ok()
706+ .flatten()
707+ .unwrap_or(DEFAULT_TRUNCATE_PAGES),
708+ }
709+ }
710+}
711+
632712 struct CellCompaction {
633713 cell: String,
634714 epoch: u64,
@@ -649,19 +729,80 @@
649729 retry_after_ms: AtomicU64,
650730 failures: AtomicU64,
651731 queued: AtomicBool,
732+ /// Set for good when the replica closes or a handoff completes. Nothing
733+ /// clears it.
652734 cancelled: AtomicBool,
735+ /// Set while a handoff snapshot holds compaction off, and cleared when
736+ /// that handoff attempt ends. See `HandoffCompactionPause`.
737+ handoff_paused: AtomicBool,
653738 cancel: Notify,
654739 #[cfg(all(test, celld_internal_tests))]
655740 finish_pause: Mutex<Option<Arc<CompactionFinishPauseForWorld>>>,
656741 /// Serializes threshold compaction with the final handoff snapshot. The
657- /// handoff path cancels background work, then waits here before it reads
742+ /// handoff path pauses background work, then waits here before it reads
658743 /// the quiesced database image.
659744 run: tokio::sync::Mutex<()>,
660745 }
661746
747+impl CellCompaction {
748+ /// Whether a round must not start or continue: the replica closed, or a
749+ /// handoff snapshot holds compaction off.
750+ fn halted(&self) -> bool {
751+ self.cancelled.load(Ordering::SeqCst) || self.handoff_paused.load(Ordering::SeqCst)
752+ }
753+}
754+
755+/// Compaction held off for one handoff attempt, from the snapshot's start
756+/// until `evict` returns.
757+///
758+/// The pause is scoped to the attempt because the attempt can end without a
759+/// handoff. An abandoned eviction, or one whose release retries run past the
760+/// eviction deadline, restarts the cell in place on the same handle
761+/// (`StartRuntime` with no `Restore`). Any other failed attempt is retried,
762+/// and each retry takes a new pause. The pause used to be the permanent
763+/// `cancelled` flag, which nothing cleared, so the cell refused every
764+/// threshold fold and every epoch GC opener fold for the rest of its
765+/// activation. A reset at each failing return was rejected because a
766+/// new return path can forget it. The pause has its own flag so that its drop
767+/// cannot undo a `close_replica` cancel that raced the eviction.
768+///
769+/// A round that waited on the run lock behind the pause can still see a
770+/// stale cancel wake after an abandoned attempt and end `Cancelled` without
771+/// a requeue. Its fold then waits for the next threshold crossing or the
772+/// next epoch GC pass, instead of the rest of the activation.
773+struct HandoffCompactionPause(CellHandle);
774+
775+impl HandoffCompactionPause {
776+ fn new(handle: &CellHandle) -> Option<Self> {
777+ let compaction = handle.compaction.as_ref()?;
778+ compaction.handoff_paused.store(true, Ordering::SeqCst);
779+ compaction.cancel.notify_waiters();
780+ Some(Self(handle.clone()))
781+ }
782+
783+ /// End the pause with the handoff. Compaction stays cancelled for good,
784+ /// because a fold after the handoff would upload into an epoch that a
785+ /// successor has already superseded.
786+ fn handed_off(self) {
787+ cancel_compaction(&self.0);
788+ }
789+}
790+
791+impl Drop for HandoffCompactionPause {
792+ fn drop(&mut self) {
793+ if let Some(compaction) = &self.0.compaction {
794+ compaction.handoff_paused.store(false, Ordering::SeqCst);
795+ }
796+ }
797+}
798+
662799 struct CompactionWork {
663800 cell: Weak<Cell>,
664801 queued_at_mono_ms: u64,
802+ /// The `trigger` label of the round's log event. It travels with the
803+ /// work, so an operator can tell a forced epoch opener from a threshold
804+ /// round.
805+ trigger: &'static str,
665806 }
666807
667808 struct RemoteRestoreTiming {
@@ -831,6 +972,27 @@
831972 )
832973 }
833974
975+/// Credit an upload that the per-cell prefix holds through `txid`. A per-cell
976+/// object is also bucket coverage, so both watermarks move together. Per-cell
977+/// coverage is published first: a concurrent stop reads the bucket credit
978+/// before coverage, and the reverse order can invent an undrained tail in a
979+/// bucket-only session with no log record, which makes its next restore fail.
980+fn credit_percell_upload(handle: &Cell, txid: u64) {
981+ handle.percell_txid.fetch_max(txid, Ordering::SeqCst);
982+ handle.durable_txid.fetch_max(txid, Ordering::SeqCst);
983+}
984+
985+/// Whether the bucket covers every cell row in one shipped batch, so that
986+/// followers can truncate it. The ledger holds each handle after the cell
987+/// stops, so every path that leaves rows only in the bucket, and every path
988+/// that deletes them, must credit `durable_txid`, or this batch and every
989+/// later batch stay on follower disks until the next epoch.
990+fn ship_batch_covered(cells: &[(CellHandle, u64)]) -> bool {
991+ cells
992+ .iter()
993+ .all(|(handle, txid)| handle.durable_txid.load(Ordering::SeqCst) >= *txid)
994+}
995+
834996 /// A capture covering tickets up to `captured` has begun for this cell. Only
835997 /// a capture that reaches new tickets moves the start: a retry of the same
836998 /// tickets keeps the budget it has already spent.
@@ -1199,7 +1361,8 @@
11991361 Self::start_with_store(watch, store, None, 0)
12001362 }
12011363
1202- /// Build the production loop topology over an injected object store.
1364+ /// Build the production loop topology over an injected object store,
1365+ /// with the settings that production reads from the environment.
12031366 #[cfg(celld_internal_tests)]
12041367 pub fn start_with_store(
12051368 watch: &Path,
@@ -1207,17 +1370,26 @@
12071370 compaction: Option<CompactionConfig>,
12081371 flush_ms: u64,
12091372 ) -> Self {
1210- Self::start_with_store_and_optional_vfs(watch, store, compaction, flush_ms, None)
1373+ Self::start_with_store_and_optional_vfs(
1374+ watch,
1375+ store,
1376+ compaction,
1377+ flush_ms,
1378+ None,
1379+ LtxConfig::from_env(),
1380+ )
12111381 }
12121382
1213- /// Build the same loop topology and route managed SQLite through `vfs`.
1383+ /// Build the same loop topology with `config`, and route managed SQLite
1384+ /// through `vfs`. A simulated fleet passes each node its own config.
12141385 #[cfg(celld_internal_tests)]
1215- pub fn start_with_store_on_vfs(
1386+ pub(crate) fn start_with_store_on_vfs(
12161387 watch: &Path,
12171388 store: Arc<dyn ObjectStore>,
12181389 compaction: Option<CompactionConfig>,
12191390 flush_ms: u64,
12201391 vfs: &str,
1392+ config: LtxConfig,
12211393 ) -> Self {
12221394 Self::start_with_store_and_optional_vfs(
12231395 watch,
@@ -1225,6 +1397,7 @@
12251397 compaction,
12261398 flush_ms,
12271399 Some(vfs.to_string()),
1400+ config,
12281401 )
12291402 }
12301403
@@ -1235,6 +1408,7 @@
12351408 compaction: Option<CompactionConfig>,
12361409 flush_ms: u64,
12371410 vfs_name: Option<String>,
1411+ config: LtxConfig,
12381412 ) -> Self {
12391413 Self::assemble(
12401414 watch,
@@ -1250,6 +1424,7 @@
12501424 deterministic_ltx_host(),
12511425 vfs_name,
12521426 DEFAULT_DURABILITY_TIMEOUT_SECS * 1_000,
1427+ config,
12531428 )
12541429 }
12551430
@@ -1279,6 +1454,7 @@
12791454 deterministic_ltx_host(),
12801455 None,
12811456 DEFAULT_DURABILITY_TIMEOUT_SECS * 1_000,
1457+ LtxConfig::from_env(),
12821458 )
12831459 }
12841460
@@ -1342,6 +1518,7 @@
13421518 production_ltx_host(),
13431519 None,
13441520 durability_timeout_ms,
1521+ LtxConfig::from_env(),
13451522 ))
13461523 }
13471524
@@ -1361,6 +1538,7 @@
13611538 ltx_host: LtxHost,
13621539 vfs_name: Option<String>,
13631540 durability_timeout_ms: u64,
1541+ config: LtxConfig,
13641542 ) -> Self {
13651543 let cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>> = Arc::default();
13661544 let dirty = Arc::new(Notify::new());
@@ -1427,20 +1605,10 @@
14271605 compaction_queue,
14281606 compaction_min_txids: compaction.map_or(0, |config| config.min_txids),
14291607 compaction_min_bytes: compaction.map_or(u64::MAX, |config| config.min_bytes),
1430- paged_restore: AtomicBool::new(
1431- crate::env_vars::flag("CELLD_LTX_PAGED", true).unwrap_or(true),
1432- ),
1608+ paged_restore: AtomicBool::new(config.paged_restore),
14331609 paged_fleet: AtomicBool::new(false),
1434- paged_min_bytes: AtomicU64::new(
1435- crate::env_vars::optional::<u64>("CELLD_LTX_PAGED_MIN_MB")
1436- .unwrap_or(None)
1437- .unwrap_or(DEFAULT_PAGED_MIN_MB)
1438- .saturating_mul(1 << 20),
1439- ),
1440- hydrate_bytes_per_s: crate::env_vars::optional::<u64>("CELLD_LTX_HYDRATE_MBPS")
1441- .unwrap_or(None)
1442- .unwrap_or(DEFAULT_HYDRATE_MBPS)
1443- .saturating_mul(1 << 20),
1610+ paged_min_bytes: AtomicU64::new(config.paged_min_bytes),
1611+ hydrate_bytes_per_s: config.hydrate_bytes_per_s,
14441612 hydrations: Arc::new(Semaphore::new(1)),
14451613 preserved,
14461614 dirty_ship,
@@ -1464,16 +1632,8 @@
14641632 ),
14651633 covered_by_cell: Mutex::new(BTreeMap::new()),
14661634 retired_marks: Mutex::new(BTreeMap::new()),
1467- epoch_gc_grace_ms: crate::env_vars::optional::<u64>("CELLD_LTX_RETENTION_SECS")
1468- .unwrap_or(None)
1469- .filter(|secs| *secs > 0)
1470- .map(|secs| secs.saturating_mul(1000)),
1471- truncate_pages: Some(
1472- crate::env_vars::optional::<u32>("CELLD_LTX_TRUNCATE_PAGES")
1473- .ok()
1474- .flatten()
1475- .unwrap_or(DEFAULT_TRUNCATE_PAGES),
1476- ),
1635+ epoch_gc_grace_ms: config.epoch_gc_grace_ms,
1636+ truncate_pages: Some(config.truncate_pages),
14771637 }
14781638 }
14791639
@@ -1909,9 +2069,20 @@
19092069 /// run measured that. The fold opens at TXID 1, so it makes the owner's
19102070 /// epoch the chain's base, and the next pass decides. A paged epoch
19112071 /// already lists its marker, and a cell without a durable row has
1912- /// nothing to fold. Publishing a handoff snapshot instead would cancel
1913- /// compaction for the rest of the activation, and rows after the image
1914- /// would reach no per-cell object.
2072+ /// nothing to fold. A handoff snapshot would upload the whole database
2073+ /// where the fold uploads only the rows the activation wrote, and it
2074+ /// would pause compaction and wait out a running round while it reads
2075+ /// the image.
2076+ ///
2077+ /// A failed forced fold retries only on the next epoch GC pass that runs
2078+ /// after the failure backoff; a pass inside the backoff enqueues nothing.
2079+ /// The failure requeue in `compact_cell` goes through the threshold
2080+ /// check, which a cell below the threshold does not pass, and that is
2081+ /// intended; a threshold round after the backoff can also produce the
2082+ /// opener. An unconditional requeue would turn one GC pass into a
2083+ /// standing retry loop on the failure backoff, whether or not a pass
2084+ /// still wants the opener, so a store fault would put every such cell
2085+ /// into that loop.
19152086 fn queue_epoch_opener(&self, cell: &str, epoch: u64) {
19162087 let Some(handle) = self
19172088 .cells
@@ -1929,7 +2100,7 @@
19292100 && compaction.compacted_txid.load(Ordering::SeqCst) == 0
19302101 && handle.durable_txid.load(Ordering::SeqCst) > 0
19312102 {
1932- enqueue_compaction(&handle);
2103+ enqueue_compaction(&handle, "epoch_opener");
19332104 }
19342105 }
19352106
@@ -2415,6 +2586,9 @@
24152586 // The paged VFS (this activation) takes precedence over the fault VFS.
24162587 let vfs_name = paged_vfs_name.clone().or_else(|| self.vfs_name.clone());
24172588 let truncate_pages = self.truncate_pages_for_cell(cell);
2589+ // Capture must finish opening before the application's SQLite connection
2590+ // or schema setup runs. An earlier write can hide a torn WAL header and
2591+ // let capture resume from a stale LTX cursor after a crash.
24182592 let (db, mut seed, marker) = asyncrt::blocking(move || {
24192593 let open_db = |ltx_host: LtxHost| match vfs_name.as_deref() {
24202594 Some(vfs_name) => Db::open_with_host_and_vfs(&dst_, ltx_host, vfs_name),
@@ -2558,6 +2732,7 @@
25582732 failures: AtomicU64::new(0),
25592733 queued: AtomicBool::new(false),
25602734 cancelled: AtomicBool::new(false),
2735+ handoff_paused: AtomicBool::new(false),
25612736 cancel: Notify::new(),
25622737 #[cfg(all(test, celld_internal_tests))]
25632738 finish_pause: Mutex::new(None),
@@ -2758,13 +2933,21 @@
27582933 /// A second SQLite connection keeps the managed reader's lock held and
27592934 /// cannot exercise its truncate path. The test driver selects timing;
27602935 /// the shipping Db still owns capture, lock release, and checkpoint order.
2936+ /// Observe the result on the native lane before waking its async caller.
2937+ /// A later writer can repair a failed WAL header before that caller runs,
2938+ /// so delayed classification against the current image loses the cause.
27612939 #[cfg(all(test, celld_internal_tests))]
2762- pub(crate) async fn checkpoint_for_world(
2940+ pub(crate) async fn checkpoint_for_world<T, F>(
27632941 &self,
27642942 cell: &str,
27652943 epoch: u64,
27662944 mode: celld_ltx::CheckpointMode,
2767- ) -> anyhow::Result<()> {
2945+ observe: F,
2946+ ) -> anyhow::Result<T>
2947+ where
2948+ T: Send + 'static,
2949+ F: FnOnce(anyhow::Result<()>) -> anyhow::Result<T> + Send + 'static,
2950+ {
27682951 let handle = self
27692952 .cells
27702953 .lock()
@@ -2774,9 +2957,10 @@
27742957 .ok_or_else(|| anyhow!("checkpoint requires a resident {cell} epoch {epoch}"))?;
27752958 asyncrt::blocking(move || {
27762959 let mut replica = handle.replica.lock().unwrap();
2777- let db = managed_db_mut(&mut replica)
2778- .ok_or_else(|| anyhow!("checkpoint lost its managed database"))?;
2779- db.checkpoint(mode).map_err(anyhow::Error::new)
2960+ let result = managed_db_mut(&mut replica)
2961+ .ok_or_else(|| anyhow!("checkpoint lost its managed database"))
2962+ .and_then(|db| db.checkpoint(mode).map_err(anyhow::Error::new));
2963+ observe(result)
27802964 })
27812965 .await
27822966 .map_err(|error| anyhow!("checkpoint task failed: {error}"))?
@@ -3204,7 +3388,7 @@
32043388 if abandon.is_some_and(EvictionAbandon::requested) {
32053389 return Err(abandoned());
32063390 }
3207- let snapshot = self.prepare_handoff_snapshot(&handle).await?;
3391+ let (snapshot, compaction_pause) = self.prepare_handoff_snapshot(&handle).await?;
32083392 if abandon.is_some_and(EvictionAbandon::requested) {
32093393 return Err(abandoned());
32103394 }
@@ -3217,6 +3401,16 @@
32173401 )
32183402 .await;
32193403 if matches!(published, Ok(Ok(()))) && self.epoch_replicated(cell, epoch).await {
3404+ // The snapshot is a per-cell object through its txid, so it
3405+ // covers every fleet-acked row of this closed database. No
3406+ // later sync or bundle flush credits a removed handle, so
3407+ // without this credit the ship ledger's batch for these rows
3408+ // never counts as covered and followers keep it, and every
3409+ // later batch, until the next epoch. Removal below also
3410+ // records a false undrained tail without the per-cell credit.
3411+ // A failed snapshot does not credit: the L0 fallback reads
3412+ // `durable_txid` to choose which rows to upload.
3413+ credit_percell_upload(&handle, snapshot.max_txid.0);
32203414 artifact = Some(EvictionRestoreArtifact::Snapshot);
32213415 } else {
32223416 handle.snapshot_declined.store(true, Ordering::Relaxed);
@@ -3260,7 +3454,13 @@
32603454
32613455 // Keep the local Db until one authoritative restore artifact is
32623456 // remotely visible. A failed snapshot and failed L0 fallback retain
3263- // the handle, so the actor cannot release ownership.
3457+ // the handle, so the actor cannot release ownership. Every such
3458+ // return drops the compaction pause, so a cell that the actor
3459+ // restarts in place folds again, and a retried attempt takes a new
3460+ // pause. Only this handoff keeps compaction off for good.
3461+ if let Some(pause) = compaction_pause {
3462+ pause.handed_off();
3463+ }
32643464 self.remove_local(cell, epoch, preserve_local);
32653465 Ok(artifact)
32663466 }
@@ -3290,11 +3490,12 @@
32903490
32913491 /// Remove a stream and every stream nested below it, in the bucket and
32923492 /// locally: `ctx.facets.delete()` of a facet and its descendants. The
3293- /// caller has discarded their resident handles.
3493+ /// caller has removed their resident handles with [`Self::delete_local`].
32943494 pub(crate) async fn delete_streams(&self, cell: &str) -> anyhow::Result<()> {
32953495 use celld_ltx::object_store::path::Path as ObjPath;
32963496 use futures_util::StreamExt as _;
32973497 use futures_util::TryStreamExt as _;
3498+ self.forget_deleted_tails(cell);
32983499 let base = ObjPath::from(format!("{}cells/{cell}", self.prefix));
32993500 let locations: Vec<_> = self
33003501 .store
@@ -3315,11 +3516,28 @@
33153516 Ok(())
33163517 }
33173518
3318- /// Discard a reset runtime without another durability attempt.
3319- ///
3320- /// The proof that triggered Reset already failed. Retrying it here can keep
3321- /// the unproved database resident and contradicts Reset's keep-nothing
3322- /// contract, so this path removes the handle and every live local file.
3519+ /// Drop the undrained tails of a deleted stream and every stream below it.
3520+ /// A tail names rows that the next activation folds into the bucket, so a
3521+ /// kept tail restores deleted rows into a recreated facet of the same
3522+ /// name. Its live bucket watermark also stays in each shipped batch that
3523+ /// carried those rows, and no fold will credit it now, so the deletion
3524+ /// credits the ending's acknowledged bound.
3525+ fn forget_deleted_tails(&self, cell: &str) {
3526+ let below = format!("{cell}/");
3527+ self.dirty_tails.lock().unwrap().retain(|stream, epochs| {
3528+ let deleted = stream == cell || stream.starts_with(&below);
3529+ if deleted {
3530+ for tail in epochs.values() {
3531+ let acked = tail
3532+ .acked_txid
3533+ .max(tail.shipped_txid.load(Ordering::SeqCst));
3534+ tail.durable_txid.fetch_max(acked, Ordering::SeqCst);
3535+ }
3536+ }
3537+ !deleted
3538+ });
3539+ }
3540+
33233541 /// Whether a stream is resident: a stop that is retried after the stream
33243542 /// stopped must not stop it again.
33253543 pub(crate) fn is_resident(&self, cell: &str, epoch: u64) -> bool {
@@ -3329,12 +3547,64 @@
33293547 .contains_key(&(cell.to_string(), epoch))
33303548 }
33313549
3550+ /// Discard a reset runtime without another durability attempt.
3551+ ///
3552+ /// The proof that triggered Reset already failed. Retrying it here can keep
3553+ /// the unproved database resident and contradicts Reset's keep-nothing
3554+ /// contract, so this path removes the handle and every live local file.
3555+ /// Its fleet-acked rows are still acknowledged writes, so it keeps them
3556+ /// uncredited behind an undrained tail until a successor fold uploads them.
33323557 pub(crate) fn discard(&self, cell: &str, epoch: u64) {
33333558 self.remove_local(cell, epoch, false);
33343559 }
33353560
3561+ /// Remove the handle of a stream that `ctx.facets.delete()` destroys.
3562+ ///
3563+ /// No upload or successor fold covers a deleted stream's rows, but each
3564+ /// shipped batch that carries them still names this handle. Without a
3565+ /// credit, the ship ledger never releases that batch, and followers keep it
3566+ /// and every later batch until the next epoch (denoland/celld#246). The
3567+ /// position staged at the close bounds every row a capture can ship from
3568+ /// this handle, so crediting it releases every such batch. No undrained
3569+ /// tail is recorded, because a fold would restore the deleted rows into a
3570+ /// recreated facet. [`Self::discard`] must not credit the same way: a reset
3571+ /// cell's acknowledged rows still need that fold.
3572+ pub(crate) fn delete_local(&self, cell: &str, epoch: u64) {
3573+ let removed = self
3574+ .cells
3575+ .lock()
3576+ .unwrap()
3577+ .remove(&(cell.to_string(), epoch));
3578+ let Some(handle) = removed.clone() else {
3579+ return;
3580+ };
3581+ match self.close_removed(cell, epoch, removed, false) {
3582+ Some(staged) => {
3583+ handle.durable_txid.fetch_max(staged, Ordering::SeqCst);
3584+ }
3585+ // Crediting a guess could release a batch above it. Keeping the
3586+ // batch costs follower disk until the next epoch, never a row.
3587+ None => warn!(
3588+ cell,
3589+ epoch, "deleted stream has no staged position; its shipped batches stay retained"
3590+ ),
3591+ }
3592+ }
3593+
33363594 fn remove_local(&self, cell: &str, epoch: u64, preserve_local: bool) {
33373595 let removed = self.remove_active_and_record_tail(cell, epoch);
3596+ self.close_removed(cell, epoch, removed, preserve_local);
3597+ }
3598+
3599+ /// Close a handle that has left the active map, and return the position
3600+ /// staged at the close.
3601+ fn close_removed(
3602+ &self,
3603+ cell: &str,
3604+ epoch: u64,
3605+ removed: Option<CellHandle>,
3606+ preserve_local: bool,
3607+ ) -> Option<u64> {
33383608 if let Some(handle) = &removed {
33393609 self.note_covered(cell, epoch, percell_coverage(handle));
33403610 }
@@ -3350,11 +3620,13 @@
33503620 {
33513621 hydration.cancelled.store(true, Ordering::SeqCst);
33523622 }
3353- let close_result = removed.map_or(Ok(()), |handle| close_replica(&handle));
3623+ let (staged, close_result) =
3624+ removed.map_or((None, Ok(())), |handle| close_replica_staged(&handle));
33543625 if let Some(name) = paged_vfs {
33553626 let _ = celld_ltx::paged_vfs::unregister_paged_vfs(&name);
33563627 }
33573628 self.finish_remove_local(cell, epoch, preserve_local, close_result);
3629+ staged
33583630 }
33593631
33603632 /// Move an active handle out only after its undrained-tail marker is
@@ -3460,23 +3732,36 @@
34603732 ///
34613733 /// A retry reuses these bytes. Recreating the image for each failed PUT
34623734 /// would spend local I/O without changing the closed database.
3735+ ///
3736+ /// The returned pause holds compaction off until the caller drops it or
3737+ /// hands the cell off. It comes back with the snapshot because a
3738+ /// snapshot read without the pause can race a fold of the same rows.
34633739 async fn prepare_handoff_snapshot(
34643740 &self,
34653741 handle: &CellHandle,
3466- ) -> anyhow::Result<Option<HandoffSnapshot>> {
3742+ ) -> anyhow::Result<(Option<HandoffSnapshot>, Option<HandoffCompactionPause>)> {
34673743 // A paged activation's local file is sparse. The snapshot page
34683744 // collector reads non-WAL pages from the file directly, so a handoff
34693745 // snapshot built here would publish hole-zeros as authoritative data.
34703746 // Skip it; the eviction then proves durability through the L0 chain,
34713747 // which is complete by construction (every write synced through WAL).
3472- if handle.paged_vfs.is_some() || handle.snapshot_declined.load(Ordering::Relaxed) {
3473- return Ok(None);
3748+ if handle.paged_vfs.is_some() {
3749+ return Ok((None, None));
34743750 }
3475- cancel_compaction(handle);
3751+ let pause = HandoffCompactionPause::new(handle);
34763752 let _compaction_run = match &handle.compaction {
34773753 Some(compaction) => Some(compaction.run.lock().await),
34783754 None => None,
34793755 };
3756+ // A declined snapshot still pauses compaction and waits out a running
3757+ // round, so the retry of a failed attempt, or a later eviction after
3758+ // an abandoned one, holds compaction off exactly as the first attempt
3759+ // did. The first attempt's permanent cancel used to cover these
3760+ // attempts. Returning before the run lock would let a round that was
3761+ // already folding keep running into the L0-chain proof.
3762+ if handle.snapshot_declined.load(Ordering::Relaxed) {
3763+ return Ok((None, pause));
3764+ }
34803765
34813766 let snapshot_handle = handle.clone();
34823767 // The deadline covers the snapshot's upload. A database the deadline
@@ -3485,7 +3770,7 @@
34853770 // retry; the L0 chain is its restore artifact, as for a paged cell.
34863771 let budget = usize::try_from(self.snapshot_budget_bytes.load(Ordering::Relaxed))
34873772 .unwrap_or(usize::MAX);
3488- asyncrt::blocking(move || -> anyhow::Result<Option<HandoffSnapshot>> {
3773+ let snapshot = asyncrt::blocking(move || -> anyhow::Result<Option<HandoffSnapshot>> {
34893774 let mut replica_slot = snapshot_handle.replica.lock().unwrap();
34903775 let replica = replica_slot
34913776 .as_mut()
@@ -3525,7 +3810,8 @@
35253810 }))
35263811 })
35273812 .await
3528- .map_err(|error| anyhow!("join handoff snapshot task: {error}"))?
3813+ .map_err(|error| anyhow!("join handoff snapshot task: {error}"))??;
3814+ Ok((snapshot, pause))
35293815 }
35303816
35313817 /// Publish one full L9 snapshot of a closed cell. A successful visibility
@@ -3912,12 +4198,7 @@
39124198 if let Some(replica) = handle.replica.lock().unwrap().as_mut() {
39134199 replica.seed_pos(Pos::new(TXID(last), 0));
39144200 }
3915- // Publish per-cell coverage before the aggregate bucket credit. A
3916- // concurrent stop reads the credit before coverage; the reverse
3917- // publication order can invent an undrained tail in a bucket-only
3918- // session with no log record, which makes its next restore fail.
3919- handle.percell_txid.fetch_max(last, Ordering::SeqCst);
3920- handle.durable_txid.fetch_max(last, Ordering::SeqCst);
4201+ credit_percell_upload(&handle, last);
39214202 #[cfg(all(test, celld_internal_tests))]
39224203 handle.pause_after_sync_credit_for_world().await;
39234204 }
@@ -3940,17 +4221,17 @@
39404221 >= compaction.min_txids;
39414222 let due_by_bytes = compaction.pending_bytes.load(Ordering::SeqCst) >= compaction.min_bytes;
39424223 if due_by_txids || due_by_bytes {
3943- enqueue_compaction(handle);
4224+ enqueue_compaction(handle, "threshold");
39444225 }
39454226 }
39464227
39474228 /// Queues one round regardless of the thresholds, behind the same
39484229 /// cancellation, backoff and single-flight guards as a threshold round.
3949-fn enqueue_compaction(handle: &CellHandle) {
4230+fn enqueue_compaction(handle: &CellHandle, trigger: &'static str) {
39504231 let Some(compaction) = &handle.compaction else {
39514232 return;
39524233 };
3953- if compaction.cancelled.load(Ordering::SeqCst)
4234+ if compaction.halted()
39544235 || asyncrt::mono_ms() < compaction.retry_after_ms.load(Ordering::SeqCst)
39554236 || compaction
39564237 .queued
@@ -3964,6 +4245,7 @@
39644245 .send(CompactionWork {
39654246 cell: Arc::downgrade(handle),
39664247 queued_at_mono_ms: asyncrt::mono_ms(),
4248+ trigger,
39674249 })
39684250 .is_err()
39694251 {
@@ -4013,7 +4295,7 @@
40134295 compact_cell(
40144296 cell,
40154297 work.queued_at_mono_ms,
4016- "threshold",
4298+ work.trigger,
40174299 true,
40184300 Some(requeues),
40194301 )
@@ -4044,12 +4326,12 @@
40444326 };
40454327 let cancelled = compaction.cancel.notified();
40464328 tokio::pin!(cancelled);
4047- if cancellable && compaction.cancelled.load(Ordering::SeqCst) {
4329+ if cancellable && compaction.halted() {
40484330 compaction.queued.store(false, Ordering::SeqCst);
40494331 return CompactionOutcome::Cancelled;
40504332 }
40514333 let _run = compaction.run.lock().await;
4052- if cancellable && compaction.cancelled.load(Ordering::SeqCst) {
4334+ if cancellable && compaction.halted() {
40534335 compaction.queued.store(false, Ordering::SeqCst);
40544336 return CompactionOutcome::Cancelled;
40554337 }
@@ -4211,6 +4493,10 @@
42114493 CompactionOutcome::Current => source_position() != source_at_start,
42124494 CompactionOutcome::Cancelled => false,
42134495 };
4496+ // Only the permanent cancel drops the requeue. A handoff pause can lift
4497+ // before the requeue fires, and `enqueue_compaction` re-checks `halted`
4498+ // then, so gating on the pause here would lose a round that completed
4499+ // during an abandoned eviction.
42144500 if requeue && !compaction.cancelled.load(Ordering::SeqCst) {
42154501 // Pace consecutive rounds for one cell: a restart with a large tail
42164502 // otherwise drains back-to-back for minutes. The pause matches the
@@ -4911,11 +5197,7 @@
49115197 if credits.is_empty() {
49125198 continue;
49135199 }
4914- ledger.advance(|cells| {
4915- cells
4916- .iter()
4917- .all(|(handle, txid)| handle.durable_txid.load(Ordering::SeqCst) >= *txid)
4918- });
5200+ ledger.advance(|cells| ship_batch_covered(cells));
49195201 let covered_seq = ledger.covered_seq();
49205202 let captured_ms = asyncrt::mono_ms().saturating_sub(round);
49215203 capture_us += lap_us(&mut lap);
@@ -5247,12 +5529,22 @@
52475529 /// the `Cell` alive after registry removal, but none can keep the database once
52485530 /// this function takes it through the same mutex used by every capture.
52495531 fn close_replica(handle: &CellHandle) -> anyhow::Result<()> {
5532+ close_replica_staged(handle).1
5533+}
5534+
5535+/// Close the managed database, and return the position staged at the close
5536+/// with the close result. Every capture syncs and reads its position under the
5537+/// replica mutex that the close takes the database from, so no capture can
5538+/// ship a later position from this handle. A failed close still returns the
5539+/// position, because no capture can reach the database after the take.
5540+fn close_replica_staged(handle: &CellHandle) -> (Option<u64>, anyhow::Result<()>) {
52505541 cancel_compaction(handle);
52515542 let replica = handle.replica.lock().unwrap().take();
5252- if let Some(db) = replica.and_then(Replica::into_db) {
5253- db.close().map_err(|error| anyhow!(error))?;
5254- }
5255- Ok(())
5543+ let Some(mut db) = replica.and_then(Replica::into_db) else {
5544+ return (None, Ok(()));
5545+ };
5546+ let staged = db.pos().ok().map(|pos| pos.txid.0);
5547+ (staged, db.close().map_err(|error| anyhow!(error)))
52565548 }
52575549
52585550 impl Drop for LtxRepl {
modifiedcrates/celld/main.rs+107−23View file
@@ -16,7 +16,8 @@
1616 use celld::bucket::Bucket;
1717 use celld::cell_dispatch::{
1818 dispatch_call_attempt, dispatch_gate, local_dispatch_request_id, local_request_error,
19- local_response_stream, split_do_call, CallAttempt, CallPayload, RoutedRequestError,
19+ local_response_stream, requests_websocket_upgrade, split_do_call, CallAttempt, CallPayload,
20+ RoutedRequestError, WEBSOCKET_WITHOUT_UPGRADE,
2021 };
2122 use celld::fleet;
2223 use celld::generation::{
@@ -247,6 +248,24 @@
247248
248249 const STALE_ROUTE_HEADER: &str = "x-cells-route-error";
249250 const STALE_ROUTE_VALUE: &str = "stale-owner";
251+/// Marks a forwarded fetch whose handler failed on the owner, so the caller's
252+/// `stub.fetch()` rejects as it does for a local owner. Without the marker a
253+/// remote handler failure looks like an application 500 response.
254+const HANDLER_FAILURE_HEADER: &str = "x-cells-handler-failure";
255+const HANDLER_FAILURE_PREFIX: &str = "cell Worker failed: ";
256+
257+/// A handler failure that the owner reported for a forwarded fetch. The owner
258+/// ran the handler, so a retry would run it a second time.
259+#[derive(Debug)]
260+struct RemoteHandlerFailure(String);
261+
262+impl std::fmt::Display for RemoteHandlerFailure {
263+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264+ formatter.write_str(&self.0)
265+ }
266+}
267+
268+impl std::error::Error for RemoteHandlerFailure {}
250269 const DURABLE_OBJECT_ROUTING_ERROR_MARKER: &str = "__CELLD_DO_ROUTING_ERROR__:";
251270
252271 fn owner_unreachable(scope: &str, owner: &str, source: anyhow::Error) -> anyhow::Error {
@@ -1037,13 +1056,8 @@
10371056
10381057 async fn dispatch_do_call(app: AppHandle, call: DoCallReq) {
10391058 let (mut call, mut payload, reply) = split_do_call(call);
1040- let mut websocket_timing = payload
1041- .headers
1042- .iter()
1043- .any(|(name, value)| {
1044- name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket")
1045- })
1046- .then(|| WebSocketRouteTiming {
1059+ let mut websocket_timing =
1060+ requests_websocket_upgrade(&payload.headers).then(|| WebSocketRouteTiming {
10471061 started: Instant::now(),
10481062 route_resolution_us: 0,
10491063 dispatch_us: 0,
@@ -1097,6 +1111,24 @@
10971111 }
10981112 break result;
10991113 }
1114+ CallAttempt::RefusedWebSocket { error, websocket } => {
1115+ websocket::reject_accepted_websocket(&app, &websocket, &error.to_string())
1116+ .await;
1117+ if let Some(timing) = websocket_timing.as_mut() {
1118+ timing.dispatch_us = timing
1119+ .dispatch_us
1120+ .saturating_add(dispatch_started.elapsed().as_micros() as u64);
1121+ timing.emit(
1122+ &app,
1123+ &call.scope,
1124+ call.request_id,
1125+ "error",
1126+ "local",
1127+ app.runtime.as_ref().map_or("", |runtime| runtime.node()),
1128+ );
1129+ }
1130+ break Err(error);
1131+ }
11001132 CallAttempt::Remote {
11011133 node,
11021134 addr,
@@ -1249,6 +1281,22 @@
12491281 observed_position: None,
12501282 });
12511283 }
1284+ if response.headers().contains_key(HANDLER_FAILURE_HEADER) {
1285+ // The owner ran the handler, so the attempt is
1286+ // complete: the owner needs no abort, and the error
1287+ // must not reach the redispatch policy below.
1288+ abort.disarm();
1289+ let body = Limited::new(response.into_body(), MAX_PEER_CONTROL_BODY_BYTES)
1290+ .collect()
1291+ .await
1292+ .map(|body| body.to_bytes())
1293+ .unwrap_or_default();
1294+ let body = String::from_utf8_lossy(&body);
1295+ let message = body.strip_prefix(HANDLER_FAILURE_PREFIX).unwrap_or(&body);
1296+ return Err(anyhow::Error::new(RemoteHandlerFailure(
1297+ message.to_string(),
1298+ )));
1299+ }
12521300 let response_headers = response
12531301 .headers()
12541302 .iter()
@@ -1296,6 +1344,12 @@
12961344 }
12971345 break Ok(response);
12981346 }
1347+ Err(error) if error.downcast_ref::<RemoteHandlerFailure>().is_some() => {
1348+ if let Some(timing) = websocket_timing.as_ref() {
1349+ timing.emit(&app, scope, request_id, "error", "remote", &node);
1350+ }
1351+ break Err(error);
1352+ }
12991353 Err(error) => {
13001354 // A streamed upload is not replayable after the HTTP
13011355 // client starts pulling it. Retrying would send only the
@@ -1617,10 +1671,15 @@
16171671 if cell_overload_error(&error) {
16181672 return cell_overload_response();
16191673 }
1620- response(
1674+ let mut failed = response(
16211675 StatusCode::INTERNAL_SERVER_ERROR,
1622- format!("cell Worker failed: {error:#}"),
1623- )
1676+ format!("{HANDLER_FAILURE_PREFIX}{error:#}"),
1677+ );
1678+ failed.headers_mut().insert(
1679+ hyper::header::HeaderName::from_static(HANDLER_FAILURE_HEADER),
1680+ hyper::header::HeaderValue::from_static("1"),
1681+ );
1682+ failed
16241683 }
16251684
16261685 /// Divide an ingress request into its metadata and a body that the Worker
@@ -1859,6 +1918,7 @@
18591918 /// rather than only the node it connected to. `/do/` and `/runtime/` share this:
18601919 /// they differ in what they authenticate, not in how they reach a cell.
18611920 async fn dispatch_cell_fetch(
1921+ app: &AppHandle,
18621922 cell: String,
18631923 name: Option<String>,
18641924 url: String,
@@ -1899,7 +1959,7 @@
18991959 let _hangup = HangUp(Some(cancel_tx));
19001960 match receive.await {
19011961 Ok(Ok(worker_response)) => {
1902- runtime_response(worker_response, preserve_representation_length)
1962+ reply_without_upgrade(app, worker_response, preserve_representation_length).await
19031963 }
19041964 Ok(Err(error)) if request_body_limit_error(&error) => {
19051965 response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large")
@@ -1990,6 +2050,8 @@
19902050 drain_pins: app.drain_pins.clone(),
19912051 handler_active: true,
19922052 };
2053+ let upgrade = requests_websocket_upgrade(&headers);
2054+ let mut accepted = None;
19932055 let completed = local
19942056 .run(async {
19952057 let result = runtime
@@ -2014,10 +2076,28 @@
20142076 // gate wait below cancels the request's remaining work, not a
20152077 // handler that is still running.
20162078 abort.handler_answered();
2017- result
2079+ let response = result?;
2080+ if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket {
2081+ accepted = Some(target.clone());
2082+ // The same object-level check as a local call, so a
2083+ // caller sees one answer whichever node owns the cell.
2084+ anyhow::ensure!(upgrade, "TypeError: {WEBSOCKET_WITHOUT_UPGRADE}");
2085+ }
2086+ Ok(response)
20182087 })
20192088 .await;
20202089 let activity = completed.activity;
2090+ // A failure after the cell returned a socket discards the response,
2091+ // which is the socket's only owner.
2092+ if let (Err(failure), Some(target)) = (&completed.result, accepted.as_ref()) {
2093+ let reason = match failure {
2094+ LocalRequestFailure::Handler(error) => error.to_string(),
2095+ LocalRequestFailure::OutputGate { verdict, .. } => {
2096+ RoutedRequestError(*verdict).to_string()
2097+ }
2098+ };
2099+ websocket::reject_accepted_websocket(&app, target, &reason).await;
2100+ }
20212101 let result = match completed.result {
20222102 Ok(answer) => Ok(answer),
20232103 Err(LocalRequestFailure::Handler(error)) => Err(error),
@@ -2031,18 +2111,18 @@
20312111 match result {
20322112 Ok(mut worker_response) => {
20332113 if let Some(HttpResponseWebSocket::Cell(target)) = &worker_response.websocket {
2034- let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) {
2114+ let (cell, hibernatable) = celld::js::ws_core_registration(target);
2115+ let kind = if hibernatable {
20352116 WebSocketKind::Hibernatable
20362117 } else {
20372118 WebSocketKind::Regular
20382119 };
2039- if let Err(error) = app
2040- .websocket_opened(target.scope.clone(), target.id, kind)
2041- .await
2042- {
2120+ if let Err(error) = app.websocket_opened(cell, target.id, kind).await {
2121+ let reason = format!("WebSocket core registration failed: {error:#}");
2122+ websocket::reject_accepted_websocket(&app, target, &reason).await;
20432123 return ForwardedFetchOutcome::Reply(peer_response(response(
20442124 StatusCode::SERVICE_UNAVAILABLE,
2045- format!("WebSocket core registration failed: {error:#}"),
2125+ reason,
20462126 )));
20472127 }
20482128 }
@@ -2067,7 +2147,8 @@
20672147 abort.disarm();
20682148 drop(activity);
20692149 }
2070- runtime_response(worker_response, preserve_representation_length)
2150+ reply_without_upgrade(&app, worker_response, preserve_representation_length)
2151+ .await
20712152 }
20722153 Err(error) => internal_do_worker_error(error),
20732154 }
@@ -2242,7 +2323,7 @@
22422323 mod peer_tunnel;
22432324 #[path = "main/websocket.rs"]
22442325 mod websocket;
2245-use websocket::{handle_websocket, outbound_websocket_task};
2326+use websocket::{handle_websocket, outbound_websocket_task, reply_without_upgrade};
22462327
22472328 async fn handle_ingress(
22482329 request: Request<Incoming>,
@@ -2294,7 +2375,9 @@
22942375 .fetch_worker(url, method, body, headers, connection)
22952376 .await
22962377 {
2297- Ok(worker_response) => runtime_response(worker_response, preserve_representation_length),
2378+ Ok(worker_response) => {
2379+ reply_without_upgrade(&app, worker_response, preserve_representation_length).await
2380+ }
22982381 Err(error) if request_body_limit_error(&error) => {
22992382 response(StatusCode::PAYLOAD_TOO_LARGE, "request body too large")
23002383 }
@@ -2909,6 +2992,7 @@
29092992 // consumer. The runtime also proves that this name hashes to the
29102993 // requested scope before it exposes the identity to JavaScript.
29112994 dispatch_cell_fetch(
2995+ &app,
29122996 scope,
29132997 name,
29142998 "http://cell/".to_string(),
@@ -2958,7 +3042,7 @@
29583042 Ok(payload) => payload,
29593043 Err(response) => return Ok(*response),
29603044 };
2961- dispatch_cell_fetch(cell, None, url, method, body, headers).await
3045+ dispatch_cell_fetch(&app, cell, None, url, method, body, headers).await
29623046 }
29633047 _ if cell_scope.is_some() => {
29643048 let cell = cell_scope.expect("checked prefix");
modifiedcrates/celld/main/peer_tunnel.rs+11−4View file
@@ -247,10 +247,17 @@
247247 ForwardedFetchOutcome::WebSocket { target, headers } => (target, headers),
248248 };
249249 let Some((accept, upgrade)) = client_upgrade else {
250- return Ok(peer_response(response(
251- StatusCode::BAD_GATEWAY,
252- "the cell accepted a WebSocket for a request that did not upgrade",
253- )));
250+ // `dispatch_forwarded_fetch` refuses a request without
251+ // `Upgrade: websocket`, so this branch sees only a request
252+ // that names the upgrade but is not a valid handshake. The
253+ // socket is registered with the core by now, and the refusal
254+ // must release it.
255+ let refusal = super::websocket::refuse_websocket_without_upgrade(
256+ &app,
257+ HttpResponseWebSocket::Cell(target),
258+ )
259+ .await;
260+ return Ok(peer_response(refusal));
254261 };
255262 // The cell accepted: hand the inner stream to the same socket
256263 // task a local client gets, and answer with the real 101. The
modifiedcrates/celld/main/websocket.rs+204−61View file
@@ -9,12 +9,63 @@
99 //! outbound — and they differ only in what sits on the far end.
1010 use super::*;
1111
12+/// Where the events of one socket go.
13+///
14+/// Resolved once, when the socket's task starts, and passed to every event of
15+/// the socket. The core's cancel path closes a socket and unregisters it
16+/// before the socket task dispatches the close, so a route read again at
17+/// that point would find no facet record and name the facet's scope as a
18+/// cell. Routing a request to that scope starts an activation for a cell
19+/// that no Worker exports.
20+#[derive(Clone)]
21+enum SocketRoute {
22+ /// A socket that a cell accepted.
23+ Cell(String),
24+ /// A socket that a Durable Object facet accepted. Routing, activity, and
25+ /// the output gate belong to the root cell. Only the handler runs in
26+ /// the facet.
27+ Facet {
28+ scope: String,
29+ facet: celld::js::FacetSocket,
30+ },
31+}
32+
33+impl SocketRoute {
34+ /// Read the route of `target` while it is still registered.
35+ fn of(target: &celld::js::WsTarget) -> Self {
36+ match celld::js::ws_facet(target.id) {
37+ Some(facet) => Self::Facet {
38+ scope: target.scope.clone(),
39+ facet,
40+ },
41+ None => Self::Cell(target.scope.clone()),
42+ }
43+ }
44+
45+ /// The scope that accepted the socket: the cell, or the facet.
46+ fn scope(&self) -> &str {
47+ match self {
48+ Self::Cell(cell) => cell,
49+ Self::Facet { scope, .. } => scope,
50+ }
51+ }
52+
53+ /// The cell that owns the socket.
54+ fn cell(&self) -> &str {
55+ match self {
56+ Self::Cell(cell) => cell,
57+ Self::Facet { facet, .. } => &facet.root,
58+ }
59+ }
60+}
61+
1262 async fn dispatch_ws_message(
1363 app: &AppHandle,
14- scope: &str,
64+ socket: &SocketRoute,
1565 ws_id: u64,
1666 data: celld::js::WsIn,
1767 ) -> anyhow::Result<()> {
68+ let scope = socket.scope();
1869 // The auto-response short circuit: a matched text frame is answered here
1970 // in the shell and never becomes a `webSocketMessage`. No routing, no
2071 // activity, no wake — a hibernated cell stays hibernated, which is the
@@ -26,7 +77,7 @@
2677 }
2778 }
2879 let Routed { request, route } = app
29- .websocket_request(scope.to_string(), ws_id)
80+ .websocket_request(socket.cell().to_string(), ws_id)
3081 .await
3182 .map_err(|error| anyhow::anyhow!("route WebSocket {scope}: {error:?}"))?;
3283 anyhow::ensure!(route == Route::Local, "WebSocket owner moved off node");
@@ -40,10 +91,10 @@
4091 // above it: a message the cell never received has no output to lose.
4192 let app = app.clone();
4293 let scope = scope.to_string();
94+ let socket = socket.clone();
4395 let (started, receive) = tokio::sync::oneshot::channel();
44- let delivery_scope = scope.clone();
4596 let delivery = celld::asyncrt::spawn(async move {
46- deliver_ws_message(&app, &delivery_scope, request, ws_id, data, started).await
97+ deliver_ws_message(&app, &socket, request, ws_id, data, started).await
4798 });
4899 // The reader waits only until the first turn. Keep observing completion:
49100 // ignoring the detached task would hide failures and leave a broken
@@ -65,28 +116,40 @@
65116 /// Run `webSocketMessage` and hand its output to the cell's barrier queue.
66117 async fn deliver_ws_message(
67118 app: &AppHandle,
68- scope: &str,
119+ socket: &SocketRoute,
69120 request: u64,
70121 ws_id: u64,
71122 data: celld::js::WsIn,
72123 started: tokio::sync::oneshot::Sender<()>,
73124 ) -> anyhow::Result<()> {
125+ let scope = socket.cell();
74126 let activity = app.activity(request, scope.to_string());
75- let dispatch = match app
76- .runtime
77- .as_ref()
78- .context("no cell runtime")?
79- .ws_message(scope.to_string(), ws_id, data, started)
80- .await
81- {
127+ let runtime = app.runtime.as_ref().context("no cell runtime")?;
128+ let dispatched = match socket {
129+ SocketRoute::Cell(cell) => runtime.ws_message(cell.clone(), ws_id, data, started).await,
130+ SocketRoute::Facet { scope, facet } => {
131+ runtime
132+ .facet_ws_message(scope.clone(), facet, ws_id, data, started)
133+ .await
134+ }
135+ };
136+ let dispatch = match dispatched {
82137 Ok(dispatch) => dispatch,
83138 // A handler that failed after it committed opens the barrier a
84139 // successful writer's batch opens, with no frames behind it: the
85140 // commit is as unproven either way, and a read-only batch or response
86141 // that followed would otherwise trail nothing and reveal it (#715).
87142 // The frames it captured before it failed are dropped, as before.
143+ //
144+ // A facet's failed handler opens no barrier. Its position counts in
145+ // the facet's stream, which the root cell's gate would read as its
146+ // own, and the facet's next output proves that whole stream anyway.
88147 Err(error) => {
89- if let Some(position) = celld::js::failed_write_position(&error) {
148+ let position = match socket {
149+ SocketRoute::Cell(_) => celld::js::failed_write_position(&error),
150+ SocketRoute::Facet { .. } => None,
151+ };
152+ if let Some(position) = position {
90153 // The barrier is registered before the activity guard
91154 // drops: the core reads the still-pinned request when it
92155 // opens the barrier, and a guard dropped first would let
@@ -124,26 +187,36 @@
124187
125188 async fn dispatch_ws_closed(
126189 app: &AppHandle,
127- scope: &str,
190+ socket: &SocketRoute,
128191 ws_id: u64,
129192 code: u16,
130193 reason: String,
131194 was_clean: bool,
132195 ) -> anyhow::Result<()> {
196+ let scope = socket.scope();
133197 let Routed { request, route } = app
134- .websocket_request(scope.to_string(), ws_id)
198+ .websocket_request(socket.cell().to_string(), ws_id)
135199 .await
136200 .map_err(|error| anyhow::anyhow!("route WebSocket close {scope}: {error:?}"))?;
137201 anyhow::ensure!(route == Route::Local, "WebSocket owner moved off node");
138- let _activity = app.activity(request, scope.to_string());
139- let answer = app
140- .runtime
141- .as_ref()
142- .context("no cell runtime")?
143- .ws_closed(scope.to_string(), ws_id, code, reason, was_clean)
144- .await;
145- gate_lifecycle_write(app, request, scope, &answer).await;
146- answer.map(|_| ())
202+ let _activity = app.activity(request, socket.cell().to_string());
203+ let runtime = app.runtime.as_ref().context("no cell runtime")?;
204+ match socket {
205+ SocketRoute::Cell(cell) => {
206+ let answer = runtime
207+ .ws_closed(cell.clone(), ws_id, code, reason, was_clean)
208+ .await;
209+ gate_lifecycle_write(app, request, cell, &answer).await;
210+ answer.map(|_| ())
211+ }
212+ // No lifecycle barrier, for the reason a failed facet message opens
213+ // none.
214+ SocketRoute::Facet { scope, facet } => {
215+ runtime
216+ .facet_ws_closed(scope.clone(), facet, ws_id, code, reason, was_clean)
217+ .await
218+ }
219+ }
147220 }
148221
149222 /// Open the barrier a lifecycle handler's write needs.
@@ -186,8 +259,9 @@
186259 reason: String,
187260 was_clean: bool,
188261 ) {
189- let _ = dispatch_ws_closed(app, &target.scope, target.id, code, reason, was_clean).await;
190- app.websocket_closed(target.scope.clone(), target.id);
262+ let socket = SocketRoute::of(target);
263+ let _ = dispatch_ws_closed(app, &socket, target.id, code, reason, was_clean).await;
264+ app.websocket_closed(socket.cell().to_string(), target.id);
191265 celld::js::ws_unregister(target.id);
192266 }
193267
@@ -201,12 +275,56 @@
201275 /// the owner node instead, so the entry node has nothing to release — the same
202276 /// split that the upgrade-failure path makes. 1006 is the code for a connection
203277 /// that closed without a close frame, which is exactly what happened.
204-async fn reject_accepted_websocket(app: &AppHandle, target: &celld::js::WsTarget, reason: &str) {
278+pub(super) async fn reject_accepted_websocket(
279+ app: &AppHandle,
280+ target: &celld::js::WsTarget,
281+ reason: &str,
282+) {
205283 if target.tunnel.is_none() {
206284 finish_websocket(app, target, 1006, reason.to_string(), false).await;
207285 }
208286 }
209287
288+/// Answer a Worker response on a connection that did not upgrade.
289+///
290+/// A response with a socket reaches a client only through `handle_websocket`
291+/// or a tunneled upgrade, so every other response path answers through this
292+/// function. workerd checks each response against the request it answers and
293+/// throws a `TypeError`, which an HTTP client receives as a 500. The object
294+/// that answers a Durable Object call applies the same check in
295+/// `dispatch_local_fetch` and `dispatch_forwarded_fetch`. This check therefore
296+/// covers the top-level Worker's own response, and a path such as `/do/` that
297+/// cannot upgrade at all.
298+pub(super) async fn reply_without_upgrade(
299+ app: &AppHandle,
300+ mut worker_response: HttpResponse,
301+ preserve_representation_length: bool,
302+) -> HttpReply {
303+ let Some(websocket) = worker_response.websocket.take() else {
304+ return runtime_response(worker_response, preserve_representation_length);
305+ };
306+ refuse_websocket_without_upgrade(app, websocket).await
307+}
308+
309+/// Release a socket on a path that cannot upgrade, and answer with a 500.
310+///
311+/// Dropping a Worker socket or a tunnel claim releases it, and a local cell
312+/// socket needs the explicit close. workerd's 500 has an empty body; celld
313+/// names the `TypeError` in the body, as it does for any other Worker failure.
314+pub(super) async fn refuse_websocket_without_upgrade(
315+ app: &AppHandle,
316+ websocket: HttpResponseWebSocket,
317+) -> HttpReply {
318+ let error = format!("TypeError: {WEBSOCKET_WITHOUT_UPGRADE}");
319+ if let Ok(PendingWebSocket::Cell(target)) = PendingWebSocket::new(websocket) {
320+ reject_accepted_websocket(app, &target, &error).await;
321+ }
322+ response(
323+ StatusCode::INTERNAL_SERVER_ERROR,
324+ format!("Worker failed: {error}"),
325+ )
326+}
327+
210328 /// One accepted WebSocket response after it returns from JavaScript.
211329 ///
212330 /// Keep the response shape in one value through every validation and executor
@@ -245,36 +363,51 @@
245363 }
246364
247365 enum OutboundWebSocketSink {
248- Cell { app: Box<AppHandle>, scope: String },
366+ /// A socket that a Durable Object dialed. A facet's socket routes,
367+ /// registers, and gates through the facet's root, as an accepted facet
368+ /// socket does.
369+ Cell {
370+ app: Box<AppHandle>,
371+ socket: SocketRoute,
372+ },
249373 Isolate(celld::js::WsPullSender),
250374 }
251375
252376 impl OutboundWebSocketSink {
253377 async fn open(&self, websocket: u64, protocol: String) -> anyhow::Result<()> {
254378 match self {
255- Self::Cell { app, scope } => {
379+ Self::Cell { app, socket } => {
380+ let cell = socket.cell();
256381 let Routed { request, route } = app
257- .request(scope.clone())
382+ .request(cell.to_string())
258383 .await
259384 .map_err(|error| anyhow::anyhow!("route outbound WebSocket: {error:?}"))?;
260385 anyhow::ensure!(
261386 route == Route::Local,
262387 "outbound WebSocket cell moved off node"
263388 );
264- let _activity = app.activity(request, scope.clone());
265- app.websocket_opened(scope.clone(), websocket, WebSocketKind::Outbound)
389+ let _activity = app.activity(request, cell.to_string());
390+ app.websocket_opened(cell.to_string(), websocket, WebSocketKind::Outbound)
266391 .await?;
267- let answer = app
268- .runtime
269- .as_ref()
270- .context("no cell runtime")?
271- .ws_open(scope.clone(), websocket, protocol)
272- .await;
273- gate_lifecycle_write(app, request, scope, &answer).await;
392+ let runtime = app.runtime.as_ref().context("no cell runtime")?;
393+ let answer = match socket {
394+ SocketRoute::Cell(cell) => {
395+ let answer = runtime.ws_open(cell.clone(), websocket, protocol).await;
396+ gate_lifecycle_write(app, request, cell, &answer).await;
397+ answer.map(|_| ())
398+ }
399+ // No lifecycle barrier, for the reason a failed facet
400+ // message opens none.
401+ SocketRoute::Facet { scope, facet } => {
402+ runtime
403+ .facet_ws_open(scope.clone(), facet, websocket, protocol)
404+ .await
405+ }
406+ };
274407 if answer.is_err() {
275- app.websocket_closed(scope.clone(), websocket);
408+ app.websocket_closed(cell.to_string(), websocket);
276409 }
277- answer.map(|_| ())
410+ answer
278411 }
279412 Self::Isolate(tx) => tx
280413 .send(celld::js::WsPull::Open(protocol))
@@ -285,7 +418,7 @@
285418
286419 async fn message(&self, websocket: u64, data: celld::js::WsIn) -> anyhow::Result<()> {
287420 match self {
288- Self::Cell { app, scope } => dispatch_ws_message(app, scope, websocket, data).await,
421+ Self::Cell { app, socket } => dispatch_ws_message(app, socket, websocket, data).await,
289422 Self::Isolate(tx) => tx
290423 .send(data.into())
291424 .await
@@ -301,10 +434,10 @@
301434 was_clean: bool,
302435 ) -> anyhow::Result<()> {
303436 match self {
304- Self::Cell { app, scope } => {
437+ Self::Cell { app, socket } => {
305438 let result =
306- dispatch_ws_closed(app, scope, websocket, code, reason, was_clean).await;
307- app.websocket_closed(scope.clone(), websocket);
439+ dispatch_ws_closed(app, socket, websocket, code, reason, was_clean).await;
440+ app.websocket_closed(socket.cell().to_string(), websocket);
308441 result
309442 }
310443 Self::Isolate(tx) => tx
@@ -313,10 +446,16 @@
313446 }
314447 }
315448
316- fn scope(&self) -> &str {
317- match self {
318- Self::Cell { scope, .. } => scope,
319- Self::Isolate(_) => "",
449+ /// Register the socket before any event of it can be dispatched. A
450+ /// facet's socket takes its record in the same insertion, so the
451+ /// registry never holds it under the facet's scope without the route.
452+ fn register(&self, websocket: u64) {
453+ if let Self::Cell { socket, .. } = self {
454+ let facet = match socket {
455+ SocketRoute::Cell(_) => None,
456+ SocketRoute::Facet { facet, .. } => Some(facet.clone()),
457+ };
458+ celld::js::ws_register_outbound(websocket, socket.scope(), facet);
320459 }
321460 }
322461 }
@@ -349,6 +488,7 @@
349488 // anywhere to send: the cell's greeting frame is queued while its own
350489 // fetch handler still runs, and the caller can send the moment it
351490 // accepts.
491+ let socket = SocketRoute::of(&target);
352492 let (caller_tx, mut from_caller) = mpsc::unbounded_channel();
353493 let (cell_tx, mut from_cell) = mpsc::unbounded_channel();
354494 celld::js::ws_register(id, caller_tx);
@@ -366,7 +506,7 @@
366506 frame = from_caller.recv() => match frame {
367507 Some(celld::js::WsOut::Text(text)) => {
368508 if let Err(error) = dispatch_ws_message(
369- &app, &target.scope, target.id, celld::js::WsIn::Text(text),
509+ &app, &socket, target.id, celld::js::WsIn::Text(text),
370510 ).await {
371511 tracing::warn!(%error, scope = %target.scope, "kept WebSocket message failed");
372512 break;
@@ -374,7 +514,7 @@
374514 }
375515 Some(celld::js::WsOut::Binary(bytes)) => {
376516 if let Err(error) = dispatch_ws_message(
377- &app, &target.scope, target.id, celld::js::WsIn::Binary(bytes),
517+ &app, &socket, target.id, celld::js::WsIn::Binary(bytes),
378518 ).await {
379519 tracing::warn!(%error, scope = %target.scope, "kept WebSocket message failed");
380520 break;
@@ -403,9 +543,9 @@
403543 }
404544 }
405545 if let Some((code, reason)) = caller_close {
406- let _ = dispatch_ws_closed(&app, &target.scope, target.id, code, reason, true).await;
546+ let _ = dispatch_ws_closed(&app, &socket, target.id, code, reason, true).await;
407547 }
408- app.websocket_closed(target.scope.clone(), target.id);
548+ app.websocket_closed(socket.cell().to_string(), target.id);
409549 celld::js::ws_unregister(target.id);
410550 celld::js::ws_unregister(id);
411551 celld::js::ws_pull_unregister(id);
@@ -427,6 +567,7 @@
427567 headers,
428568 want_response,
429569 target,
570+ facet,
430571 reply,
431572 } = request;
432573 if let Some(target) = target {
@@ -436,7 +577,10 @@
436577 Some(pull) => OutboundWebSocketSink::Isolate(pull),
437578 None => OutboundWebSocketSink::Cell {
438579 app: Box::new(app),
439- scope: scope.clone(),
580+ socket: match facet {
581+ Some(facet) => SocketRoute::Facet { scope, facet },
582+ None => SocketRoute::Cell(scope),
583+ },
440584 },
441585 };
442586 let mut handshake = HeaderMap::new();
@@ -521,9 +665,7 @@
521665 }
522666
523667 let (outbound, mut outputs) = mpsc::unbounded_channel();
524- if matches!(sink, OutboundWebSocketSink::Cell { .. }) {
525- celld::js::ws_register_outbound(id, sink.scope());
526- }
668+ sink.register(id);
527669 celld::js::ws_register(id, outbound);
528670 if let Err(error) = sink
529671 .open(id, protocol.as_deref().unwrap_or_default().to_string())
@@ -821,6 +963,7 @@
821963 S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
822964 {
823965 socket.set_auto_close(false);
966+ let route = SocketRoute::of(&target);
824967 let (outbound, mut outputs) = mpsc::unbounded_channel();
825968 celld::js::ws_register(target.id, outbound);
826969 // A close the cell sends does not become the close state here: the echo
@@ -828,16 +971,16 @@
828971 // close was clean.
829972 let (close, writer) = {
830973 let app = &app;
831- let scope = target.scope.as_str();
974+ let route = &route;
832975 let id = target.id;
833976 pump_cell_socket(socket, &mut outputs, false, move |data| {
834- dispatch_ws_message(app, scope, id, data)
977+ dispatch_ws_message(app, route, id, data)
835978 })
836979 .await
837980 };
838981 if let Err(error) = dispatch_ws_closed(
839982 &app,
840- &target.scope,
983+ &route,
841984 target.id,
842985 close.state.0,
843986 close.state.1.clone(),
@@ -896,7 +1039,7 @@
8961039 }
8971040 }
8981041 echo_websocket_close(&writer, &close.state, handler_sent_close).await;
899- app.websocket_closed(target.scope.clone(), target.id);
1042+ app.websocket_closed(route.cell().to_string(), target.id);
9001043 celld::js::ws_unregister(target.id);
9011044 }
9021045
modifiedcrates/celld/node_log.rs+80−28View file
@@ -272,6 +272,11 @@
272272 }
273273 }
274274
275+/// Followers a node recruits: three copies of an acknowledged write. The
276+/// ensemble keeps acknowledging on fewer (`NodeLogManager::healthy`), and
277+/// `maintain` grows it back to this width when peers allow.
278+const RECRUIT_FOLLOWERS: usize = 2;
279+
275280 /// Concurrent per-cell upload lanes during node-log recovery. The
276281 /// sequential version cost ~47 s for 180 entries on the lab fleet; more
277282 /// than a few lanes multiplied across RACING recoverers (self-recovery
@@ -3892,17 +3897,22 @@
38923897
38933898 /// The wait before epoch GC retries a cell whose last pass decided nothing
38943899 /// or left an epoch inside the grace.
3895-const EPOCH_GC_RETRY_MS: u64 = 5 * 60 * 1000;
3900+pub(crate) const EPOCH_GC_RETRY_MS: u64 = 5 * 60 * 1000;
38963901
3902+/// The period of the node-log maintenance loop, which runs epoch GC.
3903+pub(crate) const LOG_MAINTENANCE_TICK_MS: u64 = 30 * 1000;
3904+
38973905 /// The wait before epoch GC looks again at a cell whose last pass deleted
38983906 /// everything it could.
38993907 const EPOCH_GC_SETTLED_RETRY_MS: u64 = 60 * 60 * 1000;
39003908
39013909 /// The most cells one maintenance pass examines for epoch GC. Each costs a
3902-/// few bucket listings, and the pass shares the 30 s tick with the lease
3903-/// and log maintenance, so a node holding thousands of cells spreads them
3904-/// over several ticks instead of stalling the others behind one pass.
3905-const EPOCH_GC_CELLS_PER_PASS: usize = 32;
3910+/// few bucket listings, and on a fleet node the pass shares the 30 s tick
3911+/// with the lease and log maintenance, so a node holding thousands of cells
3912+/// spreads them over several ticks instead of stalling the others behind
3913+/// one pass. A bucket node runs the pass alone on the tick, and the bound
3914+/// still keeps one tick from listing the bucket thousands of times.
3915+pub(crate) const EPOCH_GC_CELLS_PER_PASS: usize = 32;
39063916
39073917 /// Everything node-log recovery needs from the node: the bucket, the signed
39083918 /// peer client, address resolution, and the raw per-cell upload.
@@ -3937,7 +3947,8 @@
39373947 /// Process-local; a restart re-confirms once.
39383948 gc_confirmed_empty: Mutex<std::collections::HashSet<String>>,
39393949 /// When each resident (cell, epoch) pair is next due for an epoch-GC
3940- /// attempt, in monotonic milliseconds. A
3950+ /// attempt, in monotonic milliseconds. A pair enters at the time a pass
3951+ /// first sees it, so it waits behind the overdue pairs. A
39413952 /// pass that decides nothing (an idle cell whose opener is not listed
39423953 /// yet, a paged cell still filling, an epoch inside the grace) waits
39433954 /// [`EPOCH_GC_RETRY_MS`] instead of listing the bucket every tick.
@@ -4152,13 +4163,16 @@
41524163 stack.node_log_tasks.roots.is_empty(),
41534164 "node-log background tasks were already started"
41544165 );
4155- if stack.fleet {
4156- spawn_maintenance(
4157- stack.manager.clone(),
4158- stack.node_log_tasks.stop.clone(),
4159- &stack.node_log_tasks.roots,
4160- );
4161- }
4166+ // Every posture runs the maintenance loop, because epoch GC
4167+ // (denoland/celld#240) does not depend on the posture: every
4168+ // activation adds a whole-database image in either one. The loop
4169+ // runs the fleet phases only on a fleet node.
4170+ spawn_maintenance(
4171+ stack.manager.clone(),
4172+ stack.node_log_tasks.stop.clone(),
4173+ &stack.node_log_tasks.roots,
4174+ stack.fleet,
4175+ );
41624176 if let Some(follower) = follower {
41634177 assert!(
41644178 self.follower_tasks.store.is_none(),
@@ -5637,6 +5651,15 @@
56375651 }
56385652 }
56395653
5654+ /// Followers in the installed ensemble, whether or not it is active.
5655+ fn ensemble_width(&self) -> usize {
5656+ self.inner
5657+ .lock()
5658+ .unwrap()
5659+ .as_ref()
5660+ .map_or(0, |shipper| shipper.members.len())
5661+ }
5662+
56405663 pub fn healthy(&self) -> bool {
56415664 self.inner
56425665 .lock()
@@ -5668,7 +5691,14 @@
56685691 if self.task_stop.is_stopped() {
56695692 return Ok(());
56705693 }
5671- if self.healthy() {
5694+ // A healthy ensemble below the recruitment target still reads peers.
5695+ // Returning on `healthy` alone kept a one-follower ensemble at one
5696+ // forever, because one follower is healthy: a third node that was not
5697+ // live when the ensemble formed never joined, and the acknowledged
5698+ // tail had one witness on a three-node fleet (denoland/celld#245).
5699+ // The width check below returns before any change when no further
5700+ // peer is eligible, so the cost is one peer listing per tick.
5701+ if self.healthy() && self.ensemble_width() >= RECRUIT_FOLLOWERS {
56725702 return Ok(());
56735703 }
56745704 // Self-suspicion parks recruitment: opening epochs into our own
@@ -5695,10 +5725,9 @@
56955725 // latency rule can judge it again and the swap rate cap is what
56965726 // bounds flapping.
56975727 .filter(|peer| !self.health.lock().unwrap().quarantined(&peer.node, mono))
5698- // Recruit up to two followers — three copies — while the ensemble
5699- // may serve on one. Replication factor and the in-sync floor are
5700- // separate numbers.
5701- .take(2)
5728+ // Replication factor and the in-sync floor are separate numbers:
5729+ // recruit to the target, serve on one.
5730+ .take(RECRUIT_FOLLOWERS)
57025731 .map(|peer| Member {
57035732 node: peer.node,
57045733 addr: peer.addr,
@@ -6185,15 +6214,20 @@
61856214 };
61866215 let resident: BTreeSet<(String, u64)> = self.ltx.resident_epochs().into_iter().collect();
61876216 let now = mono_ms();
6188- // The longest-waiting cells go first, so a set of cells that never
6189- // decide anything cannot hold the pass's budget ahead of the rest.
6217+ // The cells that have been due longest go first. A cell this pass
6218+ // sees for the first time is due from now, so it queues behind every
6219+ // overdue cell and ages like them. Due time 0 for an unseen cell put
6220+ // a node that gains more than `EPOCH_GC_CELLS_PER_PASS` cells per
6221+ // tick ahead of every overdue cell for as long as the arrivals lasted.
6222+ // Stamping `now` without recording it would restart the
6223+ // wait of an unexamined cell on every pass, so the stamp is kept.
61906224 let due: Vec<(String, u64)> = {
61916225 let mut schedule = self.epoch_gc_due.lock().unwrap();
61926226 schedule.retain(|key, _| resident.contains(key));
61936227 let mut due: Vec<(u64, (String, u64))> = resident
61946228 .into_iter()
61956229 .filter(|(cell, _)| !crate::engine_api::is_facet_cell(cell))
6196- .map(|key| (schedule.get(&key).copied().unwrap_or(0), key))
6230+ .map(|key| (*schedule.entry(key.clone()).or_insert(now), key))
61976231 .filter(|(at, _)| *at <= now)
61986232 .collect();
61996233 due.sort();
@@ -6469,16 +6503,29 @@
64696503 /// gray-follower detection cannot wait thirty seconds when one slow fsync
64706504 /// tail is every ack's tail, so verdicts poll at a sub-second cadence and
64716505 /// an eviction repairs the ensemble immediately.
6506+///
6507+/// Without `fleet`, the tick runs only epoch GC, and no eviction watch
6508+/// starts. A bucket node installs no registration, so it has no ensemble
6509+/// to recruit or repair, no bundles to collect, and no posture to watch.
6510+/// Its acks wait for per-cell uploads, so its restore chain base already
6511+/// holds every acknowledged row when epoch GC deletes below it. A fleet
6512+/// predecessor's follower-only rows reach the bucket before this node can
6513+/// hold the cell: the boot runs `recover_self` before it builds the owner
6514+/// and starts this loop, and a takeover runs `ensure_recovered` before the
6515+/// restore. The actor reaches that interlock through the manager in every
6516+/// posture, so neither step depends on the fleet phases here.
64726517 fn spawn_maintenance(
64736518 manager: Arc<NodeLogManager>,
64746519 stop: crate::ltx_repl::StopToken,
64756520 roots: &crate::ltx_repl::TaskGroup,
6521+ fleet: bool,
64766522 ) {
64776523 let maintenance_manager = Arc::downgrade(&manager);
64786524 let watcher = Arc::downgrade(&manager);
64796525 let maintenance_stop = stop.clone();
64806526 roots.spawn_owned("node_log_maintenance", async move {
6481- let mut tick = crate::asyncrt::interval(std::time::Duration::from_secs(30));
6527+ let mut tick =
6528+ crate::asyncrt::interval(std::time::Duration::from_millis(LOG_MAINTENANCE_TICK_MS));
64826529 tick.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay);
64836530 loop {
64846531 crate::asyncrt::select_biased! {
@@ -6498,12 +6545,14 @@
64986545 // archaeology session. The pass still runs to completion —
64996546 // this observes, it does not cancel: an aborted maintenance
65006547 // phase could orphan a half-installed ensemble.
6501- for (phase, work) in [
6502- ("maintain", manager.maintain().boxed()),
6503- ("dead-leader sweep", manager.sweep_dead_leaders().boxed()),
6504- ("bundle GC", manager.gc_bundles().boxed()),
6505- ("epoch GC", manager.gc_superseded_epochs().boxed()),
6506- ] {
6548+ let mut phases = Vec::with_capacity(4);
6549+ if fleet {
6550+ phases.push(("maintain", manager.maintain().boxed()));
6551+ phases.push(("dead-leader sweep", manager.sweep_dead_leaders().boxed()));
6552+ phases.push(("bundle GC", manager.gc_bundles().boxed()));
6553+ }
6554+ phases.push(("epoch GC", manager.gc_superseded_epochs().boxed()));
6555+ for (phase, work) in phases {
65076556 let started = mono_ms();
65086557 let mut work = work;
65096558 loop {
@@ -6528,6 +6577,9 @@
65286577 }
65296578 }
65306579 });
6580+ if !fleet {
6581+ return;
6582+ }
65316583 roots.spawn_owned("node_log_posture_watch", async move {
65326584 let mut tick = crate::asyncrt::interval(std::time::Duration::from_millis(250));
65336585 tick.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay);
modifiedcrates/celld/pool.rs+18−2View file
@@ -190,6 +190,9 @@
190190 /// drained. `None` for a standalone slot: nothing frees or replaces it,
191191 /// so [`Slot::condemn`] cannot apply to it.
192192 reclaim: Option<Arc<tokio::sync::Notify>>,
193+ /// The slot holds a Worker Loader's Worker, so the facets it runs belong
194+ /// to the root that started them rather than to this isolate.
195+ loaded_worker: bool,
193196 /// Cells whose realm lives in this isolate. Not a count of live work: a
194197 /// cell stays until it is evicted or handed to another node, which is
195198 /// why `retire` refuses an isolate holding any.
@@ -306,11 +309,16 @@
306309 Affiliation(self.clone())
307310 }
308311
312+ /// A slot holding a Worker Loader's Worker.
313+ pub(crate) fn loaded_worker(worker: js::Worker) -> Arc<Self> {
314+ Self::outside_pool(worker, true)
315+ }
316+
309317 /// A slot holding a Worker outside a placement pool.
310318 ///
311319 /// A dynamic Worker owns exactly one isolate, so it needs no
312320 /// admission, growth, or retirement policy.
313- pub(crate) fn standalone(worker: js::Worker) -> Arc<Self> {
321+ fn outside_pool(worker: js::Worker, loaded_worker: bool) -> Arc<Self> {
314322 Arc::new_cyclic(|me| Slot {
315323 me: me.clone(),
316324 id: 0,
@@ -322,6 +330,7 @@
322330 requests: AtomicUsize::new(0),
323331 freed: Arc::new(tokio::sync::Notify::new()),
324332 reclaim: None,
333+ loaded_worker,
325334 cells: AtomicUsize::new(0),
326335 adopted_cells: AtomicUsize::new(0),
327336 retiring: AtomicBool::new(false),
@@ -330,9 +339,14 @@
330339 })
331340 }
332341
342+ /// Whether this slot holds a Worker Loader's Worker.
343+ pub(crate) fn is_loaded_worker(&self) -> bool {
344+ self.loaded_worker
345+ }
346+
333347 #[cfg(celld_internal_tests)]
334348 pub fn for_test(worker: js::Worker) -> Arc<Self> {
335- Self::standalone(worker)
349+ Self::outside_pool(worker, false)
336350 }
337351
338352 #[cfg(all(test, celld_internal_tests))]
@@ -348,6 +362,7 @@
348362 requests: AtomicUsize::new(0),
349363 freed: Arc::new(tokio::sync::Notify::new()),
350364 reclaim: None,
365+ loaded_worker: false,
351366 cells: AtomicUsize::new(0),
352367 adopted_cells: AtomicUsize::new(0),
353368 retiring: AtomicBool::new(false),
@@ -617,6 +632,7 @@
617632 requests: AtomicUsize::new(0),
618633 freed: self.freed.clone(),
619634 reclaim: Some(self.reclaim.clone()),
635+ loaded_worker: false,
620636 cells: AtomicUsize::new(0),
621637 adopted_cells: AtomicUsize::new(0),
622638 retiring: AtomicBool::new(self.retired.load(Ordering::Relaxed)),
modifiedcrates/celld/runtime.rs+164−5View file
@@ -132,6 +132,24 @@
132132 let job = stateless_fetch_job_factory(None, url, method, body, headers, Some(self))(reply);
133133 drive_affiliated(slot.affiliate(), job, None)
134134 }
135+
136+ /// Drive a fully built fetch job, such as a loaded Worker's, with this
137+ /// lifetime. The job's request id is overwritten from the lifetime, so the
138+ /// caller cannot pair an abort publisher with a different request.
139+ pub(crate) fn drive_fetch_job(
140+ self: Arc<Self>,
141+ slot: Arc<crate::pool::Slot>,
142+ mut job: crate::WorkerJob,
143+ ) -> impl std::future::Future<Output = ()> + Send + 'static {
144+ if let crate::WorkerJob::Fetch { request_id, .. } = &mut job {
145+ *request_id = Some(self.request_id);
146+ }
147+ let job = StatelessWorkerJob {
148+ job,
149+ cancellation: RequestCancellationGuard::shared(self),
150+ };
151+ drive_affiliated(slot.affiliate(), job, None)
152+ }
135153 }
136154
137155 /// A stateless job and the only cancellation lifetime that can name it.
@@ -663,7 +681,7 @@
663681 received.context("cell isolate dropped response")?
664682 }
665683
666-async fn receive_service_fetch_response(
684+pub(crate) async fn receive_service_fetch_response(
667685 response: impl std::future::Future<Output = anyhow::Result<HttpResponse>>,
668686 cancellation: Arc<RequestCancellationLifetime>,
669687 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
@@ -1771,6 +1789,7 @@
17711789 let job = CellJob::WsOpen {
17721790 scope: cell.clone(),
17731791 ws_id,
1792+ facet_opening: None,
17741793 protocol,
17751794 reply,
17761795 };
@@ -1778,6 +1797,35 @@
17781797 .await
17791798 }
17801799
1800+ /// Run `webSocketOpen` in the facet `scope` that dialed `ws_id`. A write
1801+ /// of the handler is proved by the facet's next output, as for
1802+ /// `facet_ws_closed`.
1803+ pub async fn facet_ws_open(
1804+ &self,
1805+ scope: String,
1806+ facet: &js::FacetSocket,
1807+ ws_id: u64,
1808+ protocol: String,
1809+ ) -> anyhow::Result<()> {
1810+ let (reply, receive) = tokio::sync::oneshot::channel();
1811+ let job = CellJob::WsOpen {
1812+ scope: scope.clone(),
1813+ ws_id,
1814+ facet_opening: Some(facet.opening),
1815+ protocol,
1816+ reply,
1817+ };
1818+ self.facet_event(
1819+ &scope,
1820+ facet,
1821+ job,
1822+ receive,
1823+ "facet isolate dropped WebSocket open",
1824+ )
1825+ .await
1826+ .map(|_| ())
1827+ }
1828+
17811829 pub async fn rpc(
17821830 &self,
17831831 cell: String,
@@ -1810,6 +1858,7 @@
18101858 let job = CellJob::WsMessage {
18111859 scope: cell.clone(),
18121860 ws_id,
1861+ facet_opening: None,
18131862 data,
18141863 started: Some(started),
18151864 reply,
@@ -1837,6 +1886,7 @@
18371886 let job = CellJob::WsClosed {
18381887 scope: cell.clone(),
18391888 ws_id,
1889+ facet_opening: None,
18401890 code,
18411891 reason,
18421892 was_clean,
@@ -1846,6 +1896,101 @@
18461896 .await
18471897 }
18481898
1899+ /// Run `webSocketMessage` in the facet `scope` that accepted `ws_id`.
1900+ ///
1901+ /// The frames leave only after the facet's stream proves every write the
1902+ /// facet committed, as a facet's reply waits in `op_facet_fetch`. The
1903+ /// answer carries no position: a facet's write positions count in the
1904+ /// facet's stream, and the root cell's gate would read them as its own.
1905+ pub async fn facet_ws_message(
1906+ &self,
1907+ scope: String,
1908+ facet: &js::FacetSocket,
1909+ ws_id: u64,
1910+ data: js::WsIn,
1911+ started: tokio::sync::oneshot::Sender<()>,
1912+ ) -> anyhow::Result<js::WsDispatch> {
1913+ let (reply, receive) = tokio::sync::oneshot::channel();
1914+ let job = CellJob::WsMessage {
1915+ scope: scope.clone(),
1916+ ws_id,
1917+ facet_opening: Some(facet.opening),
1918+ data,
1919+ started: Some(started),
1920+ reply,
1921+ };
1922+ let dispatch = self
1923+ .facet_event(
1924+ &scope,
1925+ facet,
1926+ job,
1927+ receive,
1928+ "facet isolate dropped WebSocket message",
1929+ )
1930+ .await?;
1931+ js::prove_facet_stream(facet.stream.clone(), facet.epoch).await?;
1932+ Ok(js::WsDispatch {
1933+ frames: dispatch.frames,
1934+ write_position: None,
1935+ observed_position: None,
1936+ })
1937+ }
1938+
1939+ /// Run `webSocketClose` in the facet `scope` that accepted `ws_id`. A
1940+ /// write of the handler is proved by the facet's next output, which
1941+ /// waits for the facet's whole stream.
1942+ pub async fn facet_ws_closed(
1943+ &self,
1944+ scope: String,
1945+ facet: &js::FacetSocket,
1946+ ws_id: u64,
1947+ code: u16,
1948+ reason: String,
1949+ was_clean: bool,
1950+ ) -> anyhow::Result<()> {
1951+ let (reply, receive) = tokio::sync::oneshot::channel();
1952+ let job = CellJob::WsClosed {
1953+ scope: scope.clone(),
1954+ ws_id,
1955+ facet_opening: Some(facet.opening),
1956+ code,
1957+ reason,
1958+ was_clean,
1959+ reply,
1960+ };
1961+ self.facet_event(
1962+ &scope,
1963+ facet,
1964+ job,
1965+ receive,
1966+ "facet isolate dropped WebSocket close",
1967+ )
1968+ .await
1969+ .map(|_| ())
1970+ }
1971+
1972+ /// Start one event of a facet's socket and wait for its answer.
1973+ ///
1974+ /// A loaded Worker's isolate stays alive while its root's record holds
1975+ /// it. Any other facet runs in the root's own isolate, which the root's
1976+ /// residency pins. A facet that closed in either place is refused by the
1977+ /// event's own first turn (`facet_socket_refusal`).
1978+ async fn facet_event<T>(
1979+ &self,
1980+ scope: &str,
1981+ facet: &js::FacetSocket,
1982+ job: CellJob,
1983+ receive: tokio::sync::oneshot::Receiver<anyhow::Result<T>>,
1984+ dropped: &'static str,
1985+ ) -> anyhow::Result<T> {
1986+ let isolate = match js::recorded_facet_slot(&facet.root, facet.epoch, scope) {
1987+ Some(slot) => slot.affiliate(),
1988+ None => self.cell_isolate(&facet.root)?,
1989+ };
1990+ // No alarm reporter: a facet cannot set an alarm.
1991+ run_cell_event(isolate, job, None, receive, dropped).await
1992+ }
1993+
18491994 /// The isolate a published cell's events run in.
18501995 fn cell_isolate(&self, cell: &str) -> anyhow::Result<crate::pool::Affiliation> {
18511996 // The affiliation is taken UNDER the registry lock, while the
@@ -1909,16 +2054,30 @@
19092054 dropped: &'static str,
19102055 ) -> anyhow::Result<T> {
19112056 let isolate = self.cell_isolate(cell)?;
1912- tokio::spawn(drive_cell(
2057+ run_cell_event(
19132058 isolate,
19142059 job,
19152060 Some(self.alarm_reporter.clone()),
1916- None,
1917- ));
1918- receive.await.context(dropped)?
2061+ receive,
2062+ dropped,
2063+ )
2064+ .await
19192065 }
19202066 }
19212067
2068+/// Drive one cell event in `isolate` on a task of its own, and wait for its
2069+/// answer.
2070+async fn run_cell_event<T>(
2071+ isolate: crate::pool::Affiliation,
2072+ job: CellJob,
2073+ report: Option<AlarmReporter>,
2074+ receive: tokio::sync::oneshot::Receiver<anyhow::Result<T>>,
2075+ dropped: &'static str,
2076+) -> anyhow::Result<T> {
2077+ tokio::spawn(drive_cell(isolate, job, report, None));
2078+ receive.await.context(dropped)?
2079+}
2080+
19222081 fn restored_alarm_from_persisted(
19232082 _cell: &str,
19242083 persisted: Option<(i64, i64, u32, u32)>,
modifiedcrates/celld/storage.rs+40−0View file
@@ -104,6 +104,10 @@
104104 root_path: String,
105105 root_scope: String,
106106 facet_path: Vec<String>,
107+ /// Unique to this opening of the facet within the process. A facet
108+ /// that its root reopens, even at the same scope and epoch after a
109+ /// generation swap, is a new actor and takes a new value.
110+ opening: u64,
107111 /// The root cell's gate sample, see [`StorageIdentity::root_position`].
108112 root_position: u64,
109113 root_observed: Option<u64>,
@@ -1006,6 +1010,40 @@
10061010 })
10071011 }
10081012
1013+/// The opening of the facet `scope` in this isolate, while it is open.
1014+pub(crate) fn facet_opening(scope: &str) -> Option<u64> {
1015+ dbs(|databases| match &databases.borrow().get(scope)?.backing {
1016+ StorageBacking::Embedded { opening, .. } => Some(*opening),
1017+ StorageBacking::File { .. } => None,
1018+ })
1019+}
1020+
1021+/// The facets open in this isolate below the facet at `facet_path` of `root`,
1022+/// deepest first, so each closes before its parent.
1023+pub(crate) fn embedded_facets_below(root: &str, facet_path: &[String]) -> Vec<String> {
1024+ dbs(|databases| {
1025+ let databases = databases.borrow();
1026+ let mut below: Vec<(usize, String)> = databases
1027+ .iter()
1028+ .filter_map(|(scope, cell)| match &cell.backing {
1029+ StorageBacking::Embedded {
1030+ root_scope,
1031+ facet_path: path,
1032+ ..
1033+ } if root_scope == root
1034+ && path.len() > facet_path.len()
1035+ && path.starts_with(facet_path) =>
1036+ {
1037+ Some((path.len(), scope.clone()))
1038+ }
1039+ _ => None,
1040+ })
1041+ .collect();
1042+ below.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
1043+ below.into_iter().map(|(_, scope)| scope).collect()
1044+ })
1045+}
1046+
10091047 /// Take the root cell's gate sample of a facet that is already open, so the
10101048 /// egress of this call is held against what the root cell had committed when
10111049 /// the call left it, not against what it had committed when the facet first
@@ -1104,6 +1142,7 @@
11041142 sqlite_vec,
11051143 StorageBacking::Embedded {
11061144 stream,
1145+ opening: NEXT_FACET_OPENING.fetch_add(1, Ordering::Relaxed),
11071146 root_path: parent.root_path.clone(),
11081147 root_scope: parent.root_scope.clone(),
11091148 facet_path,
@@ -1139,6 +1178,7 @@
11391178 }
11401179
11411180 static NEXT_BATCH_SAVEPOINT: AtomicU64 = AtomicU64::new(1);
1181+static NEXT_FACET_OPENING: AtomicU64 = AtomicU64::new(1);
11421182 static NEXT_SYNC_LIST_CURSOR: AtomicU64 = AtomicU64::new(1);
11431183 static NEXT_SQL_CURSOR: AtomicU64 = AtomicU64::new(1);
11441184
addedcrates/celld/tokio_select.rs+311−0View file
@@ -1,0 +1,311 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+//
3+// This file is substantially adapted from Tokio 1.53.1
4+// tokio/src/macros/select.rs, which carries this license:
5+//
6+// MIT License
7+//
8+// Copyright (c) Tokio Contributors
9+//
10+// Permission is hereby granted, free of charge, to any person obtaining a copy
11+// of this software and associated documentation files (the "Software"), to deal
12+// in the Software without restriction, including without limitation the rights
13+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14+// copies of the Software, and to permit persons to whom the Software is
15+// furnished to do so, subject to the following conditions:
16+//
17+// The above copyright notice and this permission notice shall be included in all
18+// copies or substantial portions of the Software.
19+//
20+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26+// SOFTWARE.
27+
28+// Every `tokio::` item re-exported below is `doc(hidden)` upstream, so none of
29+// them carries a compatibility guarantee. Tokio can rename, reshape, or delete
30+// any of them in a patch release without breaking its own semver promise, and
31+// the `tokio = "1"` caret range in ../../Cargo.toml does not prevent that. A
32+// Tokio version bump must therefore re-check this facade against the select.rs
33+// of the new version.
34+//
35+// The failure mode is a compile error in celld, not a behavior change, so
36+// nothing broken ships and no test passes wrongly. Without this note the person
37+// who runs `cargo update` sees a macro that no longer resolves and gets no
38+// pointer to the cause.
39+//
40+// Rejected: narrowing the `tokio` constraint to the range this facade is known
41+// to work with. That blocks unrelated Tokio fixes for the whole dependency tree
42+// to guard against a break the compiler already makes un-missable. Do not
43+// "fix" this by pinning.
44+#[doc(hidden)]
45+pub mod __asyncrt_select_support {
46+ pub use std::future::{poll_fn, Future, IntoFuture};
47+ pub use std::pin::Pin;
48+ pub use std::task::{ready, Poll};
49+ pub use tokio::macros::support::poll_budget_available;
50+ pub use tokio::{
51+ count, count_field, select_priv_clean_pattern, select_priv_declare_output_enum,
52+ select_variant,
53+ };
54+}
55+
56+#[macro_export]
57+macro_rules! __celld_domain_select {
58+ (@reason $reason:literal) => {{
59+ const _: () = {
60+ let reason: &str = $reason;
61+ assert!(
62+ !reason.is_empty(),
63+ "select_biased! requires a non-empty reason string"
64+ );
65+ };
66+ }};
67+ (@start fair $branches:expr) => {
68+ $crate::asyncrt::select_start($branches)
69+ };
70+ (@start (biased $reason:literal) $_branches:expr) => {{
71+ $crate::__celld_domain_select!(@reason $reason);
72+ 0_u32
73+ }};
74+ (@ {
75+ mode=$mode:tt;
76+ ( $($count:tt)* )
77+ $( ( $($skip:tt)* ) $bind:pat = $future:expr, if $condition:expr => $handler:expr, )+
78+ ; $else:expr
79+ }) => {{
80+ #[doc(hidden)]
81+ mod __celld_select_util {
82+ $crate::__asyncrt_select_support::select_priv_declare_output_enum!(
83+ ( $($count)* )
84+ );
85+ }
86+
87+ const BRANCHES: u32 = $crate::__asyncrt_select_support::count!($($count)*);
88+ let mut disabled: __celld_select_util::Mask = Default::default();
89+
90+ $(
91+ if !$condition {
92+ let mask: __celld_select_util::Mask =
93+ 1 << $crate::__asyncrt_select_support::count!($($skip)*);
94+ disabled |= mask;
95+ }
96+ )*
97+
98+ #[allow(unused_mut)]
99+ let mut output = {
100+ let futures_init = ($($future,)+);
101+ let mut futures = ($(
102+ $crate::__asyncrt_select_support::IntoFuture::into_future(
103+ $crate::__asyncrt_select_support::count_field!(
104+ futures_init.$($skip)*
105+ )
106+ ),
107+ )+);
108+ #[allow(unused_mut)]
109+ let mut futures = &mut futures;
110+
111+ $crate::__asyncrt_select_support::poll_fn(|context| {
112+ $crate::__asyncrt_select_support::ready!(
113+ $crate::__asyncrt_select_support::poll_budget_available(context)
114+ );
115+
116+ let mut is_pending = false;
117+ let start = $crate::__celld_domain_select!(@start $mode BRANCHES);
118+
119+ for offset in 0..BRANCHES {
120+ let branch;
121+ #[allow(clippy::modulo_one)]
122+ {
123+ branch = (start + offset) % BRANCHES;
124+ }
125+ match branch {
126+ $(
127+ #[allow(unreachable_code)]
128+ $crate::__asyncrt_select_support::count!($($skip)*) => {
129+ let mask = 1 << branch;
130+ if disabled & mask == mask {
131+ continue;
132+ }
133+
134+ let ($($skip,)* future, ..) = &mut *futures;
135+ // SAFETY: The tuple stays on the stack and no future moves.
136+ let future = unsafe {
137+ $crate::__asyncrt_select_support::Pin::new_unchecked(future)
138+ };
139+ let value = match $crate::__asyncrt_select_support::Future::poll(
140+ future,
141+ context,
142+ ) {
143+ $crate::__asyncrt_select_support::Poll::Ready(value) => value,
144+ $crate::__asyncrt_select_support::Poll::Pending => {
145+ is_pending = true;
146+ continue;
147+ }
148+ };
149+
150+ disabled |= mask;
151+ #[allow(unreachable_patterns, unused_variables, unused_mut)]
152+ match &value {
153+ $crate::__asyncrt_select_support::select_priv_clean_pattern!(
154+ $bind
155+ ) => {}
156+ _ => continue,
157+ }
158+
159+ return $crate::__asyncrt_select_support::Poll::Ready(
160+ $crate::__asyncrt_select_support::select_variant!(
161+ __celld_select_util::Out,
162+ ($($skip)*)
163+ )(value),
164+ );
165+ }
166+ )*
167+ _ => unreachable!("the select branch index is out of range"),
168+ }
169+ }
170+
171+ if is_pending {
172+ $crate::__asyncrt_select_support::Poll::Pending
173+ } else {
174+ $crate::__asyncrt_select_support::Poll::Ready(
175+ __celld_select_util::Out::Disabled,
176+ )
177+ }
178+ })
179+ .await
180+ };
181+
182+ #[allow(unreachable_patterns)]
183+ match output {
184+ $(
185+ $crate::__asyncrt_select_support::select_variant!(
186+ __celld_select_util::Out,
187+ ($($skip)*) ($bind)
188+ ) => $handler,
189+ )*
190+ __celld_select_util::Out::Disabled => $else,
191+ _ => unreachable!("the select output does not match a branch"),
192+ }
193+ }};
194+
195+ (@ { mode=$mode:tt; $($tokens:tt)* }) => {
196+ $crate::__celld_domain_select!(@ {
197+ mode=$mode;
198+ $($tokens)*;
199+ panic!("all branches are disabled and there is no else branch")
200+ })
201+ };
202+ (@ { mode=$mode:tt; $($tokens:tt)* } else => $else:expr $(,)?) => {
203+ $crate::__celld_domain_select!(@ { mode=$mode; $($tokens)*; $else })
204+ };
205+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
206+ $pattern:pat = $future:expr, if $condition:expr => $handler:block, $($rest:tt)*) => {
207+ $crate::__celld_domain_select!(@ {
208+ mode=$mode;
209+ ($($skip)* _)
210+ $($tokens)*
211+ ($($skip)*) $pattern = $future, if $condition => $handler,
212+ } $($rest)*)
213+ };
214+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
215+ $pattern:pat = $future:expr => $handler:block, $($rest:tt)*) => {
216+ $crate::__celld_domain_select!(@ {
217+ mode=$mode;
218+ ($($skip)* _)
219+ $($tokens)*
220+ ($($skip)*) $pattern = $future, if true => $handler,
221+ } $($rest)*)
222+ };
223+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
224+ $pattern:pat = $future:expr, if $condition:expr => $handler:block $($rest:tt)*) => {
225+ $crate::__celld_domain_select!(@ {
226+ mode=$mode;
227+ ($($skip)* _)
228+ $($tokens)*
229+ ($($skip)*) $pattern = $future, if $condition => $handler,
230+ } $($rest)*)
231+ };
232+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
233+ $pattern:pat = $future:expr => $handler:block $($rest:tt)*) => {
234+ $crate::__celld_domain_select!(@ {
235+ mode=$mode;
236+ ($($skip)* _)
237+ $($tokens)*
238+ ($($skip)*) $pattern = $future, if true => $handler,
239+ } $($rest)*)
240+ };
241+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
242+ $pattern:pat = $future:expr, if $condition:expr => $handler:expr) => {
243+ $crate::__celld_domain_select!(@ {
244+ mode=$mode;
245+ ($($skip)* _)
246+ $($tokens)*
247+ ($($skip)*) $pattern = $future, if $condition => $handler,
248+ })
249+ };
250+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
251+ $pattern:pat = $future:expr => $handler:expr) => {
252+ $crate::__celld_domain_select!(@ {
253+ mode=$mode;
254+ ($($skip)* _)
255+ $($tokens)*
256+ ($($skip)*) $pattern = $future, if true => $handler,
257+ })
258+ };
259+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
260+ $pattern:pat = $future:expr, if $condition:expr => $handler:expr, $($rest:tt)*) => {
261+ $crate::__celld_domain_select!(@ {
262+ mode=$mode;
263+ ($($skip)* _)
264+ $($tokens)*
265+ ($($skip)*) $pattern = $future, if $condition => $handler,
266+ } $($rest)*)
267+ };
268+ (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
269+ $pattern:pat = $future:expr => $handler:expr, $($rest:tt)*) => {
270+ $crate::__celld_domain_select!(@ {
271+ mode=$mode;
272+ ($($skip)* _)
273+ $($tokens)*
274+ ($($skip)*) $pattern = $future, if true => $handler,
275+ } $($rest)*)
276+ };
277+
278+ (biased; $($tokens:tt)*) => {
279+ compile_error!(
280+ "select! is fair and does not accept `biased;`; use select_biased! with a reason"
281+ )
282+ };
283+ (else => $else:expr $(,)?) => {{ $else }};
284+ ($pattern:pat = $($tokens:tt)*) => {
285+ $crate::__celld_domain_select!(@ {
286+ mode=fair;
287+ ()
288+ } $pattern = $($tokens)*)
289+ };
290+ () => {
291+ compile_error!("select! requires at least one branch")
292+ };
293+}
294+
295+#[doc(hidden)]
296+#[macro_export]
297+macro_rules! __celld_domain_select_biased {
298+ ($reason:literal; else => $else:expr $(,)?) => {{
299+ $crate::__celld_domain_select!(@reason $reason);
300+ $else
301+ }};
302+ ($reason:literal; $pattern:pat = $($tokens:tt)*) => {{
303+ $crate::__celld_domain_select!(@ {
304+ mode=(biased $reason);
305+ ()
306+ } $pattern = $($tokens)*)
307+ }};
308+ ($($tokens:tt)*) => {
309+ compile_error!("select_biased! requires a non-empty reason string as its first token")
310+ };
311+}
modifiedcrates/celld/ws_registry.rs+140−5View file
@@ -32,6 +32,10 @@
3232 /// to run and no connection to open: the host only has to carry frames
3333 /// between two isolates.
3434 pub target: Option<WsTarget>,
35+ /// The facet that dialed, when `scope` names a Durable Object facet. The
36+ /// op derives it from the running event, so the socket routes through
37+ /// the facet's root and never names the facet as a cell.
38+ pub facet: Option<FacetSocket>,
3539 pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
3640 }
3741
@@ -503,7 +507,31 @@
503507 /// unix ms. Lives here rather than in the isolate because the reply is
504508 /// sent while the cell may not be resident at all.
505509 pub auto_response_at: Option<f64>,
510+ /// The root cell and facet stream behind a socket that a Durable Object
511+ /// facet accepted, dialed, or bound. `None` for a socket of an ordinary
512+ /// cell. `scope` then names the facet.
513+ pub facet: Option<FacetSocket>,
506514 }
515+
516+/// Where the events of a facet's socket go, and what proves their output.
517+///
518+/// A facet is not a cell: no Worker exports its class under the facet's
519+/// scope, so routing an event by that scope activated a cell that cannot
520+/// start (denoland/celld#252). The root cell owns the facet, its residency,
521+/// and its gate, so the socket routes and registers under `root`. The facet's
522+/// own writes are proved on `stream` at `epoch`.
523+///
524+/// Recorded by the host, never read from a `WsTarget`. A target crosses
525+/// application JavaScript, which could otherwise name another root.
526+#[derive(Clone, Debug)]
527+pub struct FacetSocket {
528+ pub root: String,
529+ pub stream: String,
530+ pub epoch: u64,
531+ /// The opening of the facet that holds the socket. An event reaches
532+ /// that opening only, never a later one at the same scope.
533+ pub opening: u64,
534+}
507535 #[derive(Default)]
508536 #[doc(hidden)]
509537 pub struct WsRegistry {
@@ -642,14 +670,78 @@
642670 asyncrt::wall_ms() as f64
643671 }
644672
645-pub fn ws_hibernatable(id: u64) -> Option<bool> {
673+/// Mark a socket as accepted by the facet `scope`, so its events reach the
674+/// facet through `facet.root`. A socket that `scope` did not accept keeps its
675+/// own route: a facet can return a socket that another cell accepted.
676+pub(crate) fn ws_attach_facet(id: u64, scope: &str, facet: FacetSocket) {
677+ if let Some(meta) = ws_registry().lock().unwrap().metadata.get_mut(&id) {
678+ if meta.scope == scope {
679+ meta.facet = Some(facet);
680+ }
681+ }
682+}
683+
684+/// The facet route of a socket, when a facet accepted it.
685+pub fn ws_facet(id: u64) -> Option<FacetSocket> {
646686 ws_registry()
647687 .lock()
648688 .unwrap()
649689 .metadata
650690 .get(&id)
651- .map(|meta| meta.hibernatable)
691+ .and_then(|meta| meta.facet.clone())
652692 }
693+
694+/// The cell the core holds `target` under, and whether that registration can
695+/// hibernate.
696+///
697+/// A facet's socket registers under its root, as a socket that cannot
698+/// hibernate. A root that hibernated would close its facets, and nothing can
699+/// restart a facet without the root's code: the class came from the root's
700+/// startup callback. The socket therefore keeps the root resident, as a
701+/// regular socket does.
702+pub fn ws_core_registration(target: &WsTarget) -> (String, bool) {
703+ let registry = ws_registry();
704+ let registry = registry.lock().unwrap();
705+ match registry.metadata.get(&target.id) {
706+ Some(WsMeta {
707+ facet: Some(facet), ..
708+ }) => (facet.root.clone(), false),
709+ meta => (
710+ target.scope.clone(),
711+ meta.is_some_and(|meta| meta.hibernatable),
712+ ),
713+ }
714+}
715+
716+/// Remove the registration of a socket that the facet `scope` accepted for a
717+/// response that never left. No socket task exists for it, so nothing else
718+/// would remove it.
719+pub(crate) fn ws_release_unanswered(id: u64, scope: &str) {
720+ let accepted = ws_registry()
721+ .lock()
722+ .unwrap()
723+ .metadata
724+ .get(&id)
725+ .is_some_and(|meta| meta.scope == scope);
726+ if accepted {
727+ ws_unregister(id);
728+ }
729+}
730+
731+/// Register a socket that a facet accepted, through a cfg-gated execution
732+/// backend that has no facet call to record it.
733+#[cfg(celld_internal_tests)]
734+#[doc(hidden)]
735+pub fn ws_register_facet_for_test(
736+ id: u64,
737+ scope: &str,
738+ facet: FacetSocket,
739+ tx: tokio::sync::mpsc::UnboundedSender<WsOut>,
740+) {
741+ ws_register_hibernatable_for_test(id, scope, tx);
742+ ws_attach_facet(id, scope, facet);
743+}
744+
653745 pub fn ws_next_id() -> u64 {
654746 asyncrt::services()
655747 .websockets()
@@ -679,10 +771,14 @@
679771 attachment: None,
680772 pending: Vec::new(),
681773 auto_response_at: None,
774+ facet: None,
682775 },
683776 );
684777 }
685-pub fn ws_register_outbound(id: u64, scope: &str) {
778+/// Register an outbound socket of `scope`. A socket that a facet opened
779+/// takes its facet record in the same insertion, so no event, close, or
780+/// `ws_close_facet` can find the entry without it.
781+pub fn ws_register_outbound(id: u64, scope: &str, facet: Option<FacetSocket>) {
686782 let inserted = {
687783 let registry = ws_registry();
688784 let mut registry = registry.lock().unwrap();
@@ -694,6 +790,7 @@
694790 attachment: None,
695791 pending: Vec::new(),
696792 auto_response_at: None,
793+ facet,
697794 });
698795 true
699796 } else {
@@ -1207,19 +1304,57 @@
12071304 /// Break a cell's sockets: the output gate could not prove a write durable, so
12081305 /// close every socket the cell owns rather than let a client keep a connection
12091306 /// whose acknowledged effects may not have persisted (a reset DO).
1307+///
1308+/// The sockets of the cell's facets close too. A facet's writes trail the
1309+/// root cell's gate, and the facet does not outlive its root.
12101310 pub fn ws_close_scope(scope: &str, code: u16, reason: &str) {
1311+ let mut scopes = vec![scope.to_string()];
1312+ {
1313+ let registry = ws_registry();
1314+ let mut registry = registry.lock().unwrap();
1315+ let ids: Vec<u64> = registry
1316+ .metadata
1317+ .iter()
1318+ .filter(|(_, meta)| {
1319+ let facet_of_scope = meta.facet.as_ref().is_some_and(|facet| facet.root == scope);
1320+ if facet_of_scope && !scopes.contains(&meta.scope) {
1321+ scopes.push(meta.scope.clone());
1322+ }
1323+ meta.scope == scope || facet_of_scope
1324+ })
1325+ .map(|(id, _)| *id)
1326+ .collect();
1327+ for id in ids {
1328+ registry.emit(id, WsOut::Close(code, reason.to_string()));
1329+ }
1330+ }
12111331 // A reset cell is a new actor; workerd's hibernation manager dies with
12121332 // the old one and takes the auto-response pair with it.
1333+ let pairs = ws_auto_responses();
1334+ let mut pairs = pairs.lock().unwrap();
1335+ for scope in &scopes {
1336+ pairs.remove(scope);
1337+ }
1338+}
1339+
1340+/// Close the sockets of a facet that stopped: an abort, a delete, or its
1341+/// root's give-back.
1342+///
1343+/// No later event can reach the facet, and a facet restarted under the same
1344+/// name is a new actor that never accepted these sockets. Leaving them open
1345+/// would accept frames that no handler can receive. 1001 is the code for an
1346+/// endpoint that is going away.
1347+pub(crate) fn ws_close_facet(scope: &str, reason: &str) {
12131348 ws_auto_responses().lock().unwrap().remove(scope);
12141349 let registry = ws_registry();
12151350 let mut registry = registry.lock().unwrap();
12161351 let ids: Vec<u64> = registry
12171352 .metadata
12181353 .iter()
1219- .filter(|(_, meta)| meta.scope == scope)
1354+ .filter(|(_, meta)| meta.scope == scope && meta.facet.is_some())
12201355 .map(|(id, _)| *id)
12211356 .collect();
12221357 for id in ids {
1223- registry.emit(id, WsOut::Close(code, reason.to_string()));
1358+ registry.emit(id, WsOut::Close(1001, reason.to_string()));
12241359 }
12251360 }
modifiedcrates/logic/lib.rs+81−0View file
@@ -683,6 +683,13 @@
683683 /// resident cell — the product wedged cold-cell activation, the rate
684684 /// falling with the cell count (engine/pathological-load.md).
685685 active_cells: BTreeMap<CellId, usize>,
686+ /// The active requests that `gate_request` admitted past a quiescing
687+ /// cell, and how many each cell holds. A gate cannot admit the next gate:
688+ /// counted as the work that raises gates, a background chain of
689+ /// overlapping gates admitted its own successor after every handler had
690+ /// ended, so the cell never reached its swap safe point.
691+ admitted_gates: BTreeSet<RequestId>,
692+ admitted_gate_cells: BTreeMap<CellId, usize>,
686693 /// Local write responses withheld by the output gate until their cell is
687694 /// proven durable to the written position, keyed by the durability op. An
688695 /// open gate makes its cell active, so the cell cannot be evicted
@@ -856,6 +863,8 @@
856863 request_cells: BTreeMap::new(),
857864 active_requests: BTreeMap::new(),
858865 active_cells: BTreeMap::new(),
866+ admitted_gates: BTreeSet::new(),
867+ admitted_gate_cells: BTreeMap::new(),
859868 barriers: BTreeMap::new(),
860869 gate_pinned: BTreeSet::new(),
861870 worker_cursor: None,
@@ -1603,6 +1612,19 @@
16031612 self.active_cells, recount
16041613 ));
16051614 }
1615+ let mut gate_recount: BTreeMap<CellId, usize> = BTreeMap::new();
1616+ for request in &self.admitted_gates {
1617+ let Some(id) = self.active_requests.get(request) else {
1618+ return Err(format!("admitted gate {request} is not active"));
1619+ };
1620+ *gate_recount.entry(id.clone()).or_insert(0) += 1;
1621+ }
1622+ if gate_recount != self.admitted_gate_cells {
1623+ return Err(format!(
1624+ "admitted_gate_cells index {:?} disagrees with admitted_gates {:?}",
1625+ self.admitted_gate_cells, gate_recount
1626+ ));
1627+ }
16061628 for (request, id) in &self.active_requests {
16071629 if self.request_cells.contains_key(request) {
16081630 return Err(format!("request {request} is both pending and active"));
@@ -1747,9 +1769,24 @@
17471769 self.active_cells.remove(&cell);
17481770 }
17491771 }
1772+ if self.admitted_gates.remove(&request) {
1773+ if let Some(count) = self.admitted_gate_cells.get_mut(&cell) {
1774+ *count -= 1;
1775+ if *count == 0 {
1776+ self.admitted_gate_cells.remove(&cell);
1777+ }
1778+ }
1779+ }
17501780 Some(cell)
17511781 }
17521782
1783+ /// Whether `id` runs active work other than an admitted gate.
1784+ fn runs_gate_source(&self, id: &str) -> bool {
1785+ let active = self.active_cells.get(id).copied().unwrap_or(0);
1786+ let gates = self.admitted_gate_cells.get(id).copied().unwrap_or(0);
1787+ active > gates
1788+ }
1789+
17531790 /// Hibernated (Durable Objects state 4): out of memory, still on this
17541791 /// host, with WebSocket clients parked at the network layer. Nothing in
17551792 /// memory survives -- the next event runs the constructor again, exactly
@@ -3543,6 +3580,44 @@
35433580 }
35443581 }
35453582
3583+ /// Admit an output gate on a resident cell even while it quiesces.
3584+ ///
3585+ /// A swap quiesces a cell so new traffic queues for the restarted runtime,
3586+ /// and it waits for admitted work to finish. A gate is part of that work:
3587+ /// the handler holding the effect cannot finish until the gate answers.
3588+ /// Queued like new traffic, the gate waited for the swap, the swap waited
3589+ /// for the handler, and only the swap's maximum age broke the cycle by
3590+ /// cancelling the handler (denoland/celld#255). The ticket's epoch check
3591+ /// still refuses a gate whose write a restart discarded.
3592+ ///
3593+ /// The cell must have the work that raised the gate: an active request
3594+ /// that is not itself an admitted gate, or a firing alarm. Otherwise the
3595+ /// gate takes the ordinary route. A drain cancels the cell's work instead
3596+ /// of waiting for it, so it has no cycle to break.
3597+ ///
3598+ /// A forced swap admits no further gate. It cancels the cell's activity
3599+ /// once, from a snapshot of the active requests, so a gate admitted after
3600+ /// that snapshot is work nothing cancels, and the swap's maximum age would
3601+ /// no longer bound it. The cancelled handler fails anyway, so its queued
3602+ /// gate costs nothing.
3603+ fn gate_request(&mut self, request: RequestId, id: CellId, effects: &mut Vec<Effect>) {
3604+ let admitted = self.node_authoritative()
3605+ && !self.draining
3606+ && self.cells.get(&id).is_some_and(|cell| {
3607+ matches!(cell.phase, Phase::Resident { .. })
3608+ && !cell.swap_cancelled
3609+ && (self.runs_gate_source(&id)
3610+ || matches!(cell.alarm, Some(AlarmState::Firing { .. })))
3611+ });
3612+ if admitted {
3613+ self.complete_request(&id, request, Ok(Route::Local), effects);
3614+ self.admitted_gates.insert(request);
3615+ *self.admitted_gate_cells.entry(id).or_insert(0) += 1;
3616+ } else {
3617+ self.request(request, id, false, false, effects);
3618+ }
3619+ }
3620+
35463621 fn request_authorized(&mut self, request: RequestId, id: CellId, effects: &mut Vec<Effect>) {
35473622 let mut cell = self.cells.remove(&id).unwrap_or_default();
35483623 match &cell.phase {
@@ -6498,6 +6573,8 @@
64986573 self.adopting_cells.clear();
64996574 self.active_requests.clear();
65006575 self.active_cells.clear();
6576+ self.admitted_gates.clear();
6577+ self.admitted_gate_cells.clear();
65016578 // Any write still waiting on the output gate loses its cell here, so it
65026579 // must fail rather than be acknowledged — the fence and the fail are
65036580 // atomic. A late DurableReached for a drained op is ignored.
@@ -6633,6 +6710,7 @@
66336710 | Event::CapacityRequestAt { now_mono_ms, .. }
66346711 | Event::HandoffRequestAt { now_mono_ms, .. }
66356712 | Event::WebSocketRequestAt { now_mono_ms, .. }
6713+ | Event::GateRequestAt { now_mono_ms, .. }
66366714 | Event::OutputAt { now_mono_ms, .. }
66376715 | Event::WakeHintAt { now_mono_ms, .. }
66386716 | Event::TimerFired { now_mono_ms, .. }
@@ -6718,6 +6796,9 @@
67186796 websocket,
67196797 ..
67206798 } => state.websocket_request(request, cell, websocket, &mut effects),
6799+ Event::GateRequestAt { request, cell, .. } => {
6800+ state.gate_request(request, cell, &mut effects)
6801+ }
67216802 Event::WorkerRequest { request } => state.worker_request(request, &mut effects),
67226803 Event::BeginPreserve => state.begin_preserve(&mut effects),
67236804 Event::Cancel { request } => state.cancel(request, &mut effects),
modifiedcrates/logic/types.rs+9−0View file
@@ -600,6 +600,15 @@
600600 now_ms: u64,
601601 now_mono_ms: u64,
602602 },
603+ /// The output gate for an effect that work already running on this cell
604+ /// raised. Only the cell's own isolate raises one, so it belongs to
605+ /// admitted work and must not queue behind a swap that waits for that
606+ /// same work to finish.
607+ GateRequestAt {
608+ request: RequestId,
609+ cell: CellId,
610+ now_mono_ms: u64,
611+ },
603612 /// Reserve an idle resident isolate for a top-level Worker request. The
604613 /// shell falls back to the stateless pool when no resident is available;
605614 /// choosing and pinning a resident is lifecycle policy and therefore
modifiedcrates/ltx/src/db.rs+74−7View file
@@ -48,7 +48,7 @@
4848
4949 use crate::error::{new_ltx_error, Error, Result};
5050 use crate::ltx::{self, lock_pgno, Crc64};
51-use crate::wal::WalReader;
51+use crate::wal::{WalError, WalReader};
5252 use crate::{
5353 ltx_file_path, ltx_level_dir, Pos, CHECKPOINT_MODE_PASSIVE, CHECKPOINT_MODE_RESTART,
5454 CHECKPOINT_MODE_TRUNCATE, META_DIR_SUFFIX, TXID, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE,
@@ -383,6 +383,13 @@
383383 /// Opens and initializes the database with litestream's WAL-mode setup and
384384 /// acquires the long-running read lock.
385385 ///
386+ /// The host must complete this call successfully before opening any
387+ /// other SQLite connection that can write to this database. After a
388+ /// crash, an earlier write can hide a torn WAL header, so resumed capture
389+ /// can skip new commits when existing LTX files retain the previous
390+ /// capture position. An incomplete recovery checkpoint returns an error,
391+ /// including when another connection keeps the checkpoint busy.
392+ ///
386393 /// Ported from `DB.init` (db.go:795-911) — the connection-setup half plus the
387394 /// read-lock acquire and `ensureWALExists`.
388395 pub fn open(path: impl AsRef<Path>) -> Result<Db> {
@@ -390,12 +397,18 @@
390397 }
391398
392399 /// Opens the database with an injected clock and executor host.
400+ ///
401+ /// This call must succeed before another writer opens the database.
402+ /// See [`Db::open`] for the startup ordering requirement.
393403 pub fn open_with_host(path: impl AsRef<Path>, host: crate::LtxHost) -> Result<Db> {
394404 Self::open_with_host_and_optional_vfs(path, host, None)
395405 }
396406
397407 /// Opens both managed connections through a named SQLite VFS. Used by the
398408 /// fault-injection VFS in tests and by paged restore's fault-in VFS.
409+ ///
410+ /// This call must succeed before another writer opens the database.
411+ /// See [`Db::open`] for the startup ordering requirement.
399412 pub fn open_with_host_and_vfs(
400413 path: impl AsRef<Path>,
401414 host: crate::LtxHost,
@@ -451,8 +464,6 @@
451464 ));
452465 }
453466
454- conn.execute_batch(CONTROL_TABLES_DDL).map_err(sql_err)?;
455-
456467 // Dedicated read-lock connection (mirrors a second pooled connection).
457468 let rtx_conn = open(&path).map_err(sql_err)?;
458469 disable_lookaside(&rtx_conn)?;
@@ -494,6 +505,11 @@
494505 max_l0_file_info: None,
495506 };
496507
508+ // Recover before any DDL can rewrite a torn header with reused salts,
509+ // and before our long-lived reader can block the checkpoint.
510+ db.recover_wal_header()?;
511+ db.conn.execute_batch(CONTROL_TABLES_DDL).map_err(sql_err)?;
512+
497513 // Start the long-running read transaction (db.go:867-871).
498514 db.acquire_read_lock()?;
499515
@@ -674,10 +690,6 @@
674690 Ok(())
675691 }
676692
677- /// Ensures the real WAL exists and has a header.
678- ///
679- /// Ported from `ensureWALExists` (db.go:1199-1209): exit early if the WAL
680- /// header is present; otherwise force a write to `_litestream_seq`.
681693 /// Runs `op` on the held WAL handle, opening it on first use. A WAL that
682694 /// SQLite recreated, or that a truncation shortened under a read, surfaces
683695 /// as `NotFound` or `UnexpectedEof`; the handle is dropped and `op` runs
@@ -726,6 +738,61 @@
726738 Ok(self.with_wal_file(|file| file.read_exact_at(offset as u64, n as usize))?)
727739 }
728740
741+ /// Resets a WAL with an invalid header checksum before initialization writes.
742+ fn recover_wal_header(&mut self) -> Result<()> {
743+ let header = match self.wal_header_bytes() {
744+ Ok(header) => header,
745+ // The later ensure_wal_exists call initializes missing or
746+ // short WALs. Other I/O errors must remain visible to the caller.
747+ Err(Error::Io(error))
748+ if matches!(
749+ error.kind(),
750+ std::io::ErrorKind::NotFound | std::io::ErrorKind::UnexpectedEof
751+ ) =>
752+ {
753+ return Ok(())
754+ }
755+ Err(error) => return Err(error),
756+ };
757+ match WalReader::new(&header) {
758+ Ok(_) => return Ok(()),
759+ Err(WalError::Eof) => {}
760+ // SQLite rejects invalid magic before copying the salts or nCkpt.
761+ // With nCkpt still zero, its next write chooses fresh salts, so
762+ // verify detects the new generation without this checkpoint.
763+ // Capture still rejects the invalid header until that write.
764+ Err(WalError::InvalidMagic(_)) => return Ok(()),
765+ // SQLite normally rejects an unsupported version while enabling
766+ // WAL; keep any remaining header-reader errors visible.
767+ Err(error) => return Err(error.into()),
768+ }
769+
770+ // The host must open capture before other SQLite writers. After a
771+ // crash, an earlier write can reuse salts and hide the torn header.
772+ // SQLite rejects the torn WAL contents but retains the header's
773+ // salts and checkpoint sequence. A bootstrap write alone can reuse
774+ // those salts. The stale tail then lets an existing LTX cursor skip
775+ // new commits. SQLite's TRUNCATE checkpoint changes the salts and
776+ // removes that tail even if this process stops before its first
777+ // capture. No volatile recovery flag can protect that gap.
778+ // If control-table DDL is a no-op, ensure_wal_exists supplies the
779+ // first write in the new generation.
780+ // Only open checks the header, so live syncs keep their cheap check.
781+ let checkpoint = self.run_checkpoint_pragma(CheckpointMode::Truncate)?;
782+ if checkpoint.busy != 0 {
783+ // A busy checkpoint leaves recovery incomplete, so opening must fail.
784+ return Err(sql_err(rusqlite::Error::SqliteFailure(
785+ ffi::Error::new(ffi::SQLITE_BUSY),
786+ Some("torn WAL recovery checkpoint is busy".to_string()),
787+ )));
788+ }
789+ Ok(())
790+ }
791+
792+ /// Ensures the real WAL exists and has a header.
793+ ///
794+ /// Ported from `ensureWALExists` (db.go:1199-1209): exit early if the WAL
795+ /// header is present; otherwise force a write to `_litestream_seq`.
729796 fn ensure_wal_exists(&mut self) -> Result<()> {
730797 if self.wal_file_size()? >= WAL_HEADER_SIZE as i64 {
731798 return Ok(());
modifiedcrates/ltx/src/replica.rs+53−24View file
@@ -77,17 +77,53 @@
7777 /// transient store or IO error is not one of these: a fenced single writer's
7878 /// position is still valid, and its re-upload is an idempotent overwrite. See
7979 /// [`Replica::sync`] for why celld narrows Litestream's clear-on-any-error.
80+///
81+/// The walk follows `source()` the way Go's `errors.Is` follows `%w`, and it
82+/// also steps into a [`SyncStepError`], which hides its cause from `source()`.
83+/// Matching only the outer variant made the reset unreachable: every sync
84+/// error was already `Other`.
8085 fn pos_untrustworthy(err: &Error) -> bool {
81- matches!(
82- err,
83- Error::NoSnapshots
84- | Error::ChecksumMismatch
85- | Error::LTXCorrupted
86- | Error::LTXMissing
87- | Error::TxNotAvailable
88- )
86+ let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(err);
87+ while let Some(error) = cause {
88+ if matches!(
89+ error.downcast_ref::<Error>(),
90+ Some(
91+ Error::NoSnapshots
92+ | Error::ChecksumMismatch
93+ | Error::LTXCorrupted
94+ | Error::LTXMissing
95+ | Error::TxNotAvailable
96+ )
97+ ) {
98+ return true;
99+ }
100+ cause = match error.downcast_ref::<SyncStepError>() {
101+ Some(step) => Some(&step.cause),
102+ None => error.source(),
103+ };
104+ }
105+ false
89106 }
90107
108+/// A sync step's error, named for the step and keeping the original error so
109+/// that [`pos_untrustworthy`] can classify it. Formatting the original into a
110+/// string, as the port first did, discarded that variant.
111+///
112+/// The message already prints the cause, so `source()` does not return it.
113+/// Returning it too makes a reporter that walks the chain print the cause a
114+/// second time, after the step line.
115+#[derive(Debug, thiserror::Error)]
116+#[error("{step}: {cause}")]
117+struct SyncStepError {
118+ step: &'static str,
119+ cause: Error,
120+}
121+
122+/// Wraps an error from the named sync step, the Go `fmt.Errorf("step: %w")`.
123+fn sync_step(step: &'static str) -> impl FnOnce(Error) -> Error {
124+ move |cause| Error::Other(Box::new(SyncStepError { step, cause }))
125+}
126+
91127 /// Connects a database to a replication destination via a [`ReplicaClient`].
92128 ///
93129 /// Ported from `Replica` (replica.go:30-59). The Go type also owns the
@@ -183,9 +219,10 @@
183219
184220 /// Copies new L0 LTX files from the local capture directory to the replica.
185221 ///
186- /// Ported from `Replica.Sync` (replica.go:132-180). On any error the cached
187- /// position is cleared so the next sync recomputes it from the replica
188- /// (replica.go:137-143). Requires an attached database.
222+ /// Ported from `Replica.Sync` (replica.go:132-180). A divergence error clears
223+ /// the cached position so the next sync recomputes it from the replica; a
224+ /// transient error keeps it (see [`pos_untrustworthy`]). Requires an
225+ /// attached database.
189226 pub async fn sync(&mut self) -> Result<()> {
190227 match self.sync_inner().await {
191228 Ok(()) => Ok(()),
@@ -216,10 +253,7 @@
216253 // never runs on the hot path, and a fresh cell's pointless list of an
217254 // empty prefix is skipped entirely.
218255 if !self.pos_known {
219- let pos = self
220- .calc_pos()
221- .await
222- .map_err(|e| Error::Other(format!("calc pos: {e}").into()))?;
256+ let pos = self.calc_pos().await.map_err(sync_step("calc pos"))?;
223257 self.set_pos(pos);
224258 self.pos_known = true;
225259 }
@@ -230,9 +264,8 @@
230264 .db
231265 .as_mut()
232266 .ok_or_else(|| Error::Other("no database attached to replica".into()))?;
233- db.pos().map_err(|e| {
234- Error::Other(format!("cannot determine current position: {e}").into())
235- })?
267+ db.pos()
268+ .map_err(sync_step("cannot determine current position"))?
236269 };
237270 if dpos.is_zero() {
238271 return Err(Error::Other("no position, waiting for data".into()));
@@ -278,7 +311,7 @@
278311 self.client
279312 .write_ltx_file(level, min_txid, max_txid, &data)
280313 .await
281- .map_err(|e| Error::Other(format!("write ltx file: {e}").into()))?;
314+ .map_err(sync_step("write ltx file"))?;
282315
283316 Ok(())
284317 }
@@ -291,7 +324,7 @@
291324 let info = self
292325 .max_ltx_file_info(0)
293326 .await
294- .map_err(|e| Error::Other(format!("max ltx file: {e}").into()))?;
327+ .map_err(sync_step("max ltx file"))?;
295328 Ok(Pos::new(info.max_txid, info.post_apply_checksum))
296329 }
297330
@@ -1028,8 +1061,4 @@
10281061 pub fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> {
10291062 super::build_database_image(files)
10301063 }
1031-
1032- pub fn pos_untrustworthy(error: &Error) -> bool {
1033- super::pos_untrustworthy(error)
1034- }
10351064 }
modifieddocs/README.md+686−1164View file
@@ -10,1167 +10,689 @@
1010
1111 In Cloudflare terms, a cell is a Durable Object: a small server with a
1212 name and a private SQLite database. You make one cell for each user,
13-document, chat room, or AI agent. A cell serves HTTP, holds
14-WebSocket connections, sets alarms, and makes outbound connections. Cells
15-share no database, so the application divides into cells from the start.
16-Each cell runs on one thread: a second request interleaves only while the
17-first awaits, and storage operations are synchronous and never interleave,
18-so the data in a cell stays consistent.
19-
20-You run celld as one process on each machine. That process is a **node**,
21-and the nodes that share one bucket are a **fleet**. Any node can serve
22-any cell, so you add capacity by starting another node against the same
23-bucket.
24-
25-## Cell lifecycle
26-
27-A cell has the same states as a Durable Object. A **resident** cell is in
28-memory: it is **active** while it does work, and **idle** when it waits.
29-celld removes an idle cell from memory after `CELLD_IDLE_EVICT_S` seconds
30-without work, and earlier under memory pressure or at the residency cap.
31-Without `CELLD_IDLE_EVICT_S`, an idle cell stays in memory until pressure
32-or the cap removes it. A cell that then keeps its
33-hibernatable WebSocket clients, and stays on its node, is **hibernated**.
34-A cell that no node holds is **inactive**. An inactive cell is only an
35-object in the bucket, so it costs almost zero, and every cell starts in
36-this state. A paged activation adds its epoch prefix to the bucket
37-immediately, when it uploads its marker. An activation that is not paged
38-adds the prefix at its first per-cell upload. With fleet durability, a
39-write goes first to the log bundles of the node. The first per-cell
40-upload is therefore the first L1 compaction of the activation, a handoff
41-snapshot, or a direct upload while the log ensemble of the node is
42-degraded. When epoch GC is on and the cell has an older prefix, the owner
43-does not wait for `CELLD_LTX_COMPACTION_MIN_TXIDS`. It starts that
44-compaction at its next epoch GC pass after the first write, and a pass
45-can come up to 5 minutes later. With `CELLD_LTX_COMPACTION=0` the owner
46-does not compact, so the prefix waits for one of the other uploads. A
47-restore reads only
48-the newest epochs of a cell. celld deletes the older prefixes only when
49-`CELLD_LTX_RETENTION_SECS` enables epoch GC, so without it the bytes of
50-a cell increase with each activation that adds a prefix.
51-
52-A cell keeps no memory across these transitions, so the constructor
53-runs again on the next event. A hibernated cell wakes the same way a
54-cold start does, except that its WebSocket clients stay connected and
55-it stays on its node.
56-
57-One 8 GB node holds 1,000 resident cells, so one resident cell costs
58-approximately $0.05 each month.
59-
60-## Ownership and durability
61-
62-Exactly one node serves a cell at a time. The nodes do not elect a leader
63-or keep a membership list: a node claims a cell by writing a small record
64-to the bucket. The store accepts the write only if no other node changed
65-the record first. Object storage therefore decides who wins, and two nodes
66-cannot both claim the same cell. The claim expires unless the node renews
67-it, so a failed machine releases its cells without a separate failure
68-detector.
69-
70-celld does not answer a write until the data survives a failure, so no
71-write you were told succeeded is ever lost. That guarantee is called
72-RPO=0, for a recovery point of zero.
73-
74-The durability mechanism depends on how many nodes you run. One node
75-writes the data to the bucket first, which costs one storage round trip. Two or more
76-nodes are faster: the node serving the cell sends each write to another
77-node as well, and answers as soon as that node has the data on its own
78-disk. celld uploads the data to the bucket afterwards, so the bucket
79-still holds the long-term state. Run two or more nodes if write latency
80-matters to you; a single node has nobody to send to, so every write waits
81-for the bucket. `CELLD_DURABILITY` selects this behavior and defaults to
82-`fleet`.
83-
84-When a node stops, another node takes the cell over. It first collects
85-whatever the stopped node had not uploaded yet, so the takeover starts
86-from a complete history. The [guarantees](guarantees.md) page
87-gives the full mechanism and the exact properties that the bucket must
88-provide.
89-
90-## Alarms
91-
92-When an event sets an alarm before its response boundary, celld does not send a
93-successful response until a durable wake entry covers the alarm. celld does
94-not let a later `waitUntil` alarm delay another event's response.
95-Each committed installation requires its own publication PUT, including an
96-alarm that moves later within the same minute. Each entry has a separate
97-identity, so delayed processing of an older alarm state cannot remove the
98-entry that covers a newer alarm.
99-
100-A hibernated cell fires its alarm on the node that owns it. One node in the
101-fleet holds the waker role at a time. The waker reads the due wake entries of
102-the whole fleet, and it wakes only the cells whose owner node has stopped. Every
103-other node wakes only its own hibernated cells, so the alarm load of the fleet
104-does not queue on one node.
105-
106-## What do you build with cells
107-
108-A cell fits a workload that divides into named, stateful units:
109-
110-- **Real-time applications.** A multiplayer game, a chat room, or a
111- collaborative document is one cell. The cell holds the WebSocket
112- connections and the state of one room, so the room needs no lock and
113- no external message bus.
114-- **Agents.** Each AI agent is one cell. The cell holds the memory, the
115- schedule, and the inbox of one agent in its own SQLite database. An
116- inactive agent has no resident process, so a large agent fleet costs
117- almost nothing between events.
118-- **Sharded web applications.** One cell for each user, each tenant, or
119- each device shards the application from the start. The contention of
120- one shared database does not appear, because no shared database
121- exists.
122-
123-## Contents
124-
125-- [Cells and nodes](#cells-and-nodes)
126-- [Cell lifecycle](#cell-lifecycle)
127-- [Ownership and durability](#ownership-and-durability)
128-- [Alarms](#alarms)
129-- [What do you build with cells](#what-do-you-build-with-cells)
130-- [Install](#install)
131-- [Configure object storage](#configure-object-storage)
132-- [Deploy an application](#deploy-an-application)
133-- [Operate D1, KV, and R2](#operate-d1-kv-and-r2)
134-- [Start a node](#start-a-node)
135-- [Add nodes](#add-nodes)
136-- [Shut down and roll out a node](#shut-down-and-roll-out-a-node)
137-- [Diagnose a fleet](#diagnose-a-fleet)
138-- [List Durable Objects](#list-durable-objects)
139-- [Environment variables](#environment-variables)
140-- [Services](#services)
141-- [Cloudflare compatibility](cloudflare-compat.md)
142-- [What celld guarantees](guarantees.md)
143-- [Limitations](limitations.md)
144-- [Security](security.md)
145-- [Telemetry](telemetry.md)
146-- [Testing](testing.md)
147-- [WebAssembly](wasm.md)
148-- [Python Workers](services/workers.md#python-workers)
149-
150-## Services
151-
152-Each service page contains a runnable example and the known differences from
153-the Cloudflare service.
154-
155-- [Workers](services/workers.md)
156-- [Durable Objects / Cells](services/durable-objects.md)
157-- [Durable Object Facets](services/durable-object-facets.md)
158-- [KV](services/kv.md)
159-- [Queues](services/queues.md)
160-- [D1](services/d1.md)
161-- [R2](services/r2.md)
162-- [Workflows](services/workflows.md)
163-- [Cron Triggers](services/cron-triggers.md)
164-- [Static assets](services/static-assets.md)
165-- [Dynamic Workers](services/dynamic-workers.md)
166-- [Containers](services/containers.md)
167-
168-## Install
169-
170-The installer downloads the `celld` binary. Replication runs inside the
171-celld process, so a node needs no external replicator.
172-
173-```sh
174-curl -fsSL https://celld.dev/install.sh | sh
175-```
176-
177-If the installer tells you, add `~/.local/bin` to `PATH`. To install one
178-exact release, set `CELLD_VERSION` to its tag, for example `v0.0.1`; to
179-go back, run the installer again with the previous tag. The releases are
180-on [GitHub](https://github.com/denoland/celld/releases), and each release
181-has a GitHub Actions build attestation: verify a downloaded file with
182-`gh attestation verify <asset> --repo denoland/celld`.
183-
184-## Configure object storage
185-
186-The `s3://`, `gs://`, and `az://` scheme names are case-insensitive.
187-celld ignores leading and trailing whitespace in `CELLD_BUCKET`.
188-
189-For an S3-compatible bucket, celld uses the standard AWS credential
190-chain. Paged restores also use this chain, so an EC2 instance role does
191-not require static access keys for a large cell. On Amazon EKS, celld
192-reads the Pod Identity credentials from the injected environment
193-variables and the authorization-token file. For Cloudflare R2: create
194-a bucket, create an S3 API token with access to
195-that bucket, and set these variables:
196-
197-```sh
198-export AWS_ACCESS_KEY_ID=...
199-export AWS_SECRET_ACCESS_KEY=...
200-export AWS_REGION=auto
201-export S3_ENDPOINT=https://ACCOUNT_ID.r2.cloudflarestorage.com
202-export CELLD_BUCKET=s3://YOUR-BUCKET
203-```
204-
205-For Google Cloud Storage, celld uses Application Default Credentials.
206-Create a bucket. Then authenticate with `gcloud auth application-default
207-login`, or point `GOOGLE_APPLICATION_CREDENTIALS` at a service-account
208-key that has access to the bucket. Then set the bucket:
209-
210-```sh
211-export CELLD_BUCKET=gs://YOUR-BUCKET
212-```
213-
214-A `gs://` bucket takes no `S3_ENDPOINT` and no `AWS_*` credentials, and
215-celld ignores the storage region. On a Compute Engine instance, celld can
216-use the attached service account, but the access scopes of the instance
217-cap this credential, and the default scope permits only storage reads.
218-Create the instance with the `cloud-platform` scope, so the IAM role of
219-the service account controls the access.
220-
221-For Azure Blob Storage, the bucket NAME is the container, and the
222-storage account comes from the environment. Create a container. Then
223-set the account and one credential:
224-
225-```sh
226-export AZURE_STORAGE_ACCOUNT_NAME=YOUR-ACCOUNT
227-export AZURE_STORAGE_ACCOUNT_KEY=...
228-export CELLD_BUCKET=az://YOUR-CONTAINER
229-```
230-
231-You must configure exactly one Azure credential family: a storage account
232-key, a managed identity, or a workload identity. A system-assigned managed
233-identity needs only the account name. A user-assigned managed identity needs exactly one selector among
234-`AZURE_CLIENT_ID`, `AZURE_OBJECT_ID`, and `AZURE_MSI_RESOURCE_ID`,
235-because two selectors can name two different identities. An identity
236-must hold the Azure Blob data-plane permission to read, write, list, and
237-delete blobs; the built-in
238-[`Storage Blob Data Contributor`](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#storage-blob-data-contributor)
239-role supplies it.
240-
241-celld reads a managed identity from the Azure instance metadata service,
242-which an Azure VM and an AKS node supply. Azure App Service and Azure
243-Container Apps supply a different endpoint, so a managed identity does
244-not work there; use a workload identity or an account key instead. The
245-standard AKS workload identity environment (`AZURE_AUTHORITY_HOST`,
246-`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE`)
247-works with the public authority host, `https://login.microsoftonline.com`,
248-with or without a trailing slash; celld rejects a sovereign or custom
249-host. celld also rejects each recognized Azure configuration variable
250-outside these families, including another credential source, an endpoint
251-override, or the OneLake endpoint. It ignores an `AZURE_*` name that
252-`object_store` 0.12 does not recognize, because that name cannot change
253-the client.
254-
255-An `az://` bucket takes no `S3_ENDPOINT` and no `AWS_*` credentials, and
256-celld ignores the storage region. celld qualifies an `az://` bucket for
257-a production fleet. The startup test verifies the conditional writes and
258-ranged reads. A live Azure test from 2026-08-18 covers the multipart upload
259-path. See [guarantees](guarantees.md). For local development against Azurite,
260-set `AZURE_STORAGE_USE_EMULATOR=true`; Azurite is a development store, so
261-celld does not qualify it for a fleet either.
262-
263-The bucket credentials give full control of the fleet, so keep them
264-safe. The bucket contains the deployments, the SQLite replicas, the
265-ownership records, the node leases, and the peer-authentication secret.
266-
267-A bucket value can add a key prefix: `s3://YOUR-BUCKET/PREFIX`. Every
268-object of the fleet then goes below `PREFIX/`, so two fleets can share one
269-bucket. A bucket value without a prefix keeps the objects at the root of
270-the bucket, therefore an existing fleet does not move its data.
271-
272-The store must provide conditional writes. A ranged read must return the
273-exact requested bytes. The store must also provide read-after-write
274-consistency. Cell ownership and stored data depend on these properties.
275-Amazon S3, Cloudflare R2, Google Cloud Storage, Tigris, and Azure Blob Storage
276-qualify; Backblaze B2, Hetzner, and DigitalOcean Spaces do not. MinIO
277-(the community edition) passes the storage test, but celld has not
278-qualified it for production; do not use RELEASE.2025-09-06T17-38-46Z,
279-which rejects the conditional create that the first deploy sends
280-(denoland/celld#162). See [what celld guarantees](guarantees.md) for the
281-exact requirements.
282-
283-## Deploy an application
284-
285-If the project contains Worker code, install `esbuild` on `PATH`; an
286-asset-only project does not need it. Then run `celld deploy` from an
287-applicable Wrangler project:
288-
289-```sh
290-git clone https://github.com/denoland/celld
291-cd celld/examples/counter
292-celld deploy . \
293- --bucket "$CELLD_BUCKET" \
294- --endpoint "$S3_ENDPOINT" \
295- --region "$AWS_REGION"
296-```
297-
298-`celld deploy` accepts module Workers, Durable Object bindings, service
299-bindings, variables, cron triggers, D1 databases, KV namespaces, Queues,
300-R2 buckets, Workflows, WebAssembly modules, and static assets. An asset project can include a
301-Worker or be asset-only, and the asset functions include the assets
302-binding, HTML handling, not-found handling, worker-first routes,
303-`_headers`, and `_redirects`. If the Wrangler configuration contains an
304-unknown key, the deploy stops with an error. See the
305-[Cloudflare compatibility](cloudflare-compat.md) page for the complete
306-deployment boundary.
307-
308-A new deployment manifest records the full SHA-256 digest of each JavaScript
309-or WebAssembly module. A node verifies each module before it builds the
310-deployment, so changed module bytes cannot become active. A node also accepts
311-a legacy 16-character digest and verifies that prefix, so an upgrade can load
312-an existing deployment.
313-
314-A running node does not restart for a new deployment. Each node reads
315-`deploy/current.json` every 30 seconds (`CELLD_DEPLOY_POLL_S`) and adopts
316-a new deployment in place, and `POST /reload` on the internal listener
317-makes a node adopt the pointer now. A node builds the new deployment
318-beside the one it serves, and then it switches new requests to the new
319-deployment in one step. A request that started on the previous deployment
320-finishes on it. A deployment that does not build leaves the current
321-deployment serving, and the node reports the failure in its log and in
322-the `/reload` response. `POST /reload` also rebuilds an unchanged
323-deployment.
324-
325-A Durable Object that is not resident runs the new deployment at its
326-next activation. A resident Durable Object moves to the new deployment
327-at a safe point: no request runs in it, no alarm handler runs in it, no
328-output waits for durability, and no regular WebSocket is open. A request
329-that arrives while the object moves waits for the new code. The move
330-keeps the object's storage, its epoch, and its hibernatable WebSockets,
331-and it does not read or write the bucket. An object that reaches no safe
332-point in `CELLD_DEPLOY_MAX_AGE_S` seconds (default 60) is forced: celld
333-cancels its running work and closes its regular WebSockets with code
334-1012, which is what a Cloudflare deployment does to every object. A
335-value of 0 forces every resident object at the adoption. In this window,
336-a request on one deployment can call a Durable Object on the other, so
337-two adjacent versions must accept each other's calls. The `/state`
338-response reports the deployment a node serves, the deployments it still
339-drains, the objects that are moving, and the deployment each resident
340-object runs.
341-
342-## Develop an application locally
343-
344-Run `celld dev` in a Wrangler project:
345-
346-```sh
347-celld dev
348-```
349-
350-The command opens a local object store, deploys the application, and starts
351-one celld node. It does not require Docker or a cloud bucket. The supervisor
352-stops the node when the command finishes or returns an error. On Linux, the
353-kernel also stops the node if the supervisor exits abruptly.
354-
355-The Worker listener uses `http://127.0.0.1:9876` by default. Use `--port` to
356-select a different port:
357-
358-```sh
359-celld dev --port 3000
360-```
361-
362-Use `--host` to select the Worker listener interface:
363-
364-```sh
365-celld dev --host 0.0.0.0
366-```
367-
368-A non-loopback IP exposes the Worker listener to the network. The internal
369-operator listener stays on loopback, so another machine cannot use its
370-operator API.
371-
372-The default display uses color to identify each status and the application
373-URL. It hides the node warning and information logs, so the errors and the
374-listener remain easy to find. Use `--logs` to show these logs:
375-
376-```sh
377-celld dev --logs
378-```
379-
380-Set `NO_COLOR` to disable color. Set `FORCE_COLOR` to enable color when
381-the output is not a terminal. `NO_COLOR` always takes priority when both
382-variables are set.
383-
384-You can also give the command a project directory or a Wrangler
385-configuration file:
386-
387-```sh
388-celld dev ./examples/counter
389-```
390-
391-The command reads a `.dev.vars` file beside the Wrangler configuration, as
392-`wrangler dev` does. Each line of the file has the form `NAME=value`. A
393-value can be wrapped in double or single quotes, and the command removes
394-the quotes. The command does not read the other dotenv features, such as a
395-comment after a value or a value on more than one line. An entry becomes a
396-Worker variable, and it overrides an entry of the same name in the `vars`
397-of the configuration. Only `celld dev` reads the file, so a local
398-credential does not reach a fleet through `celld deploy`. Add `.dev.vars`
399-to the application's `.gitignore` file. A change to the file rebuilds the
400-application, so a new value takes effect without a restart. The command
401-writes each value into the local deployment record under `.celld/dev`, and
402-`--clean` deletes that record.
403-
404-The command stores the local objects and the celld work files in `.celld/dev`
405-below the project directory. Add `.celld/` to the application's `.gitignore`
406-file. A normal shutdown keeps this directory, so the next invocation uses the
407-same durable application state.
408-
409-This persistence holds across a configuration change, and celld does not
410-migrate the stored state to match the new configuration. An object therefore
411-keeps a value that the previous configuration wrote, and the application can
412-reject that value and fail. The error names the stored value and not the
413-configuration, so the failure can look unrelated to the change you made. Use
414-`--clean` to start the command from an empty local state:
415-
416-```sh
417-celld dev --clean
418-```
419-
420-The flag deletes `.celld/dev` before the server starts, and it deletes nothing
421-else below `.celld`. The command reports the outcome on the console. An absent
422-`.celld/dev` directory is the wanted result, so the flag succeeds on a project
423-that never ran `celld dev`.
424-
425-The command does not expose the local object store through a fleet flag. A
426-regular node or an operator subcommand must use a supported cloud bucket.
427-
428-The command watches the project directory. A source or configuration
429-change builds a new deployment and restarts the local node. The current
430-application continues to run during the build, and a failed build does
431-not replace it. The restart retains the durable application state.
432-
433-A read of a project file is not a change, so a tool that only reads the project
434-does not start a build.
435-
436-The watcher ignores `.celld`, `.git`, `.wrangler`, `node_modules`, and `target`
437-directories at each depth. Use `--watch-ignore PATTERN` to ignore an additional
438-project-relative glob, and repeat the option to add more globs. The
439-`--watch-ignore` option cannot be used with `--no-watch`. Use `--no-watch` to
440-disable all automatic builds and restarts.
441-
442-The watcher does not watch a source file outside the project directory. Worker
443-projects need `esbuild` on `PATH`, and asset-only projects do not need it.
444-
445-## Operate D1, KV, and R2
446-
447-`celld d1` runs SQL and migrations against a deployed D1 database. The
448-command uses the fleet bucket to find a node, and the node routes the
449-operation to the database cell.
450-
451-```sh
452-celld d1 migrations apply ledger --bucket "$CELLD_BUCKET"
453-```
454-
455-The `migrations_dir` value must be a relative path inside the project. An
456-absolute path or a path with a `..` component is invalid.
457-
458-`celld kv` reads and writes a deployed KV namespace. The bulk commands use
459-the Wrangler file format, so `wrangler kv bulk get` can export data for
460-`celld kv bulk put`.
461-
462-```sh
463-celld kv bulk put sessions wrangler-export.json --bucket "$CELLD_BUCKET"
464-```
465-
466-`celld kv bulk get` writes each row before it reads the next value, so the
467-command does not retain the complete namespace. A named output file changes
468-only after the export completes. If a stdout export fails, the output remains
469-an incomplete JSON array and a consumer cannot import it as a complete export.
470-
471-`celld kv list` prints at most 1000 keys, because a namespace can hold
472-many more keys than an operator wants to read. The command reports on
473-stderr that more keys exist, and it gives the `--after KEY` that continues
474-the listing. Pass `--all` to read every key, or `--json` for one JSON
475-object per key.
476-
477-`celld r2` reads and writes the objects behind an `r2_buckets` binding. The
478-binding serves the fleet bucket under the reserved `r2/<bucket_name>/`
479-prefix, and this command reads the same prefix directly. It therefore needs
480-no running node, so a release pipeline can publish an artifact before it
481-deploys the Worker.
482-
483-```sh
484-celld r2 put assets app.zip --path dist/app.zip \
485- --content-type application/zip \
486- --metadata '{"release":"1.2.3"}' \
487- --bucket "$CELLD_BUCKET"
488-```
489-
490-The first argument is the `bucket_name` from the project's `r2_buckets`
491-entry, not the binding name. An object this command writes carries the same
492-record as an object `env.BUCKET.put()` writes, so `--metadata` becomes
493-`customMetadata` and the content flags become `httpMetadata`. Another tool
494-can write an object into the prefix, and the binding still reads it: the
495-object's user metadata becomes its `customMetadata`, and its headers become
496-its `httpMetadata`. Such an object carries no `cacheExpiry` and no
497-checksums, because a store has no place for either.
498-
499-`celld r2 get` writes the object to stdout as bytes, and it reads the body
500-as a stream, so an artifact larger than the available memory still
501-transfers. `celld r2 list` prints at most 1000 keys and reports on stderr
502-how to continue, the same as `celld kv list`. The `celld r2 head` command
503-prints the object's stored record. With `--json`, the `http` and `custom`
504-fields contain the binding's `httpMetadata` and `customMetadata` values.
505-
506-Every celld command writes its data to stdout and its messages to stderr,
507-so a redirect or a pipe carries only data:
508-
509-```sh
510-celld kv list sessions --all --json --bucket "$CELLD_BUCKET" > keys.ndjson
511-```
512-
513-`celld --help`, `celld --version`, and the listener announcements use the same
514-stdout sink. The sink treats a closed pipe as a successful stop, and it reports
515-all other write and flush errors.
516-
517-## Start a node
518-
519-For local development, the default listener is sufficient:
520-
521-```sh
522-celld \
523- --bucket "$CELLD_BUCKET" \
524- --endpoint "$S3_ENDPOINT" \
525- --region "$AWS_REGION"
526-```
527-
528-For a fleet node, bind the public and internal listeners separately. The
529-ingress can reach the public listener, and the other nodes can reach the
530-internal listener:
531-
532-```sh
533-celld \
534- --bucket "$CELLD_BUCKET" \
535- --endpoint "$S3_ENDPOINT" \
536- --region "$AWS_REGION" \
537- --listen 0.0.0.0:8080 \
538- --internal-listen 10.0.0.12:8081 \
539- --advertise node-a.internal:8081
540-```
541-
542-An explicit advertised address requires an explicit internal-listener
543-address: set both command-line options, or their equivalent environment
544-variables. celld also rejects an explicit non-loopback public listener
545-without an explicit internal listener, because that shape identifies an
546-obsolete one-listener configuration.
547-
548-celld cannot verify that an advertised hostname or a translated port
549-reaches the internal listener. You must route the advertised address to
550-the internal listener, and you must not route it to the public Worker
551-listener.
552-
553-## Add nodes
554-
555-Start each node with the same bucket settings. Give each internal listener
556-a different address that the other nodes can reach, and set `--advertise`
557-to that address. The nodes find each other through the leases in the
558-bucket; there is no join command and no fixed membership list.
559-
560-The bucket supplies discovery and authority, not network reachability.
561-Cell fetch and RPC traffic has a protocol version but has no content
562-signature, so the private network and its code are the security boundary.
563-Peer-control and reserved-cell operator requests use the fleet HMAC, but celld does not
564-terminate TLS. Put the advertised addresses on a private network that you
565-trust, or use an encrypted overlay such as WireGuard or Tailscale. The
566-internal listener also has an unauthenticated operator API, so it must not
567-reach the public internet. See the [security](security.md) page for the
568-complete boundary.
569-
570-The listener that receives a request decides where a new cell activates,
571-so a load balancer must include a new node in its rotation. A node below
572-its residency cap keeps every cell that activates on it. A node at its
573-cap, and a node that sheds under memory pressure, hands the activation to
574-the peer with the lowest load, and an empty node wins that comparison. A
575-shed eviction releases the ownership record
576-(`CELLD_PRESSURE_OWNERSHIP=release`, the default), so the next request
577-can move the cell. An idle eviction keeps the ownership record, so an
578-idle cell wakes on its own node. The node proves the cell durable before
579-it stops the runtime, and the cell answers requests through that proof. A
580-request that arrives before the stop therefore cancels the eviction, and
581-the cell keeps its runtime and its epoch. A bucket proof confirms the
582-cell's objects before the stop, so it makes this first window longer than
583-a fleet proof does. A request that arrives during the stop can also keep
584-the epoch. The node stops the runtime, and then it writes a handoff
585-snapshot to the bucket. Before that write the node has published nothing,
586-so it gives the cell back and starts it again on the same database at the
587-same epoch. After that write the snapshot is the restore source for the
588-next owner, so a request waits for the cell to start again at a new
589-epoch. The two durability postures behave the same way during the stop,
590-because both write the same snapshot at the same point. An idle eviction
591-must stop the runtime within `CELLD_OPERATION_DEADLINE_MS`. If the
592-runtime does not stop in time, the node keeps the cell resident at its
593-current epoch. The node waits one more idle period before the next
594-attempt, and it waits the same period after it gives a cell back.
595-
596-A new node also receives existing idle cells. Every node reads a shared
597-fleet sample every five seconds (`CELLD_REBALANCE_INTERVAL_MS`; `0`
598-disables balancing). One node claims each refresh through a conditional
599-write and reads the node leases for the fleet. The other nodes read
600-the result from `fleet/capacity-v1.json`. A node judges the leases in a
601-sample at the moment the sample was taken, because the copied leases age
602-while the nodes renew the originals. A sample expires after one
603-configured interval. A node that reads during a refresh keeps the
604-previous sample while that sample is less than three intervals old. A
605-refresher that fails puts the previous sample back, so the next reader
606-refreshes at once. A refresher that stops holds its claim for three
607-intervals, or for 30 seconds if that period is shorter. This claim
608-lifetime does not exceed the maximum accepted age of a previous sample.
609-A stopped refresher can leave the other nodes without a sample until the
610-claim expires. An unavailable sample stops balancing and closes the
611-bucket-format gate.
612-With balancing disabled, the format check still reads the shared sample
613-every five seconds. A node that hands an activation to a peer reads the
614-same shared sample, so a burst of activations at a full node costs one
615-read each. Readiness, a drain, follower recruitment, and lease authority
616-read the node leases directly.
617-
618-Each node has an ownership target: the fleet's owned cells, divided in
619-proportion to the node weights
620-(`CELLD_PLACEMENT_WEIGHT`, default: the CPU count). The node with the
621-most owned cells per unit of weight hands at most 32 idle cells
622-to the peer that is furthest below its
623-target, and it hands over no more cells than the receivers have room
624-for. A receiver fills to 2% below its target, so a stale sample cannot
625-make two nodes trade the same cells. Only a hibernated cell moves. Its
626-move is one ownership record write and one signed acquire, it stays
627-hibernated on the new owner, and its parked hibernatable WebSockets close
628-with code 1012 so the clients reconnect to the new owner. A resident cell
629-does not move: it hibernates through idle eviction first
630-(`CELLD_IDLE_EVICT_S`) and moves after. Therefore a fleet without idle
631-eviction balances only the cells that hibernate on their own. A request
632-that arrives for a moving cell waits for the new owner and then follows
633-the normal route to it. A node that drains receives no cell, and a node
634-with cold activations queued behind its activation ceiling (`restoring` in
635-its lease) receives no cell until that backlog clears. The fleet moves nothing while a
636-node reports a lease without a weight, so a rolling upgrade to this
637-version completes before the first move. An operator can pause the fleet with
638-`POST /rebalance/pause` on the internal listener of any node.
639-
640-## Feed an autoscaler
641-
642-celld does not scale itself. An external system starts and stops the
643-nodes, and celld hands the cells off. Two surfaces report the numbers
644-that a scaling decision needs.
645-
646-Each node writes its lease to `nodes/<node>.json` in the bucket, and
647-each renewal refreshes it (`CELLD_TTL_MS`, default 10000, renewed at
648-one third of the lifetime). The lease carries a load block:
649-`owned_cells`, `placement_weight`, `resident_cells`, `host_websockets`,
650-`rss_bytes`, `in_use_bytes`, `cpu_percent_x100`, `open_fds`, `pressured`,
651-`memory_headroom`, `shed_cells`, and `restoring`. A script can read these
652-objects with the
653-bucket credentials alone, and `sampled_ms` dates each sample. The
654-`owned_cells` value includes the dormant cells and the cells that are waking
655-from dormancy. A started node omits the value until it has read the
656-ownership record of every cell on its own disk, so a restarted node does
657-not report an empty node while it still owns its hibernated cells. The
658-`resident_cells` value includes only the cells that consume the local
659-runtime capacity.
660-
661-The shared runtime samples the process memory, open files, and CPU every
662-second, and once before the first lease acquisition. The lease and `/state`
663-report these values from the latest sample, so they are normally one sample
664-period old. The `allocator` and `libc_malloc` objects in `/state` are read
665-when the request arrives.
666-
667-The internal listener answers `GET /state` with the live counters:
668-`owned_cells`, `occupied`, `capacity_waiting`, `activation_waiting`, `restoring`,
669-`shedding`, and the memory values. The `allocator` object reports the
670-Rust allocator's own counters in bytes: `allocated_bytes` is the memory
671-that Rust code holds, `resident_bytes` adds the freed pages that the
672-allocator keeps for reuse, and `mapped_bytes` and `retained_bytes` are its
673-address space. V8 maps its heaps itself, so `rss_bytes` includes them and
674-`allocated_bytes` does not. On Linux the `libc_malloc` object reports the
675-C allocator that SQLite and V8 use: `in_use_bytes` is what they hold, and
676-`free_bytes` is what glibc keeps for them after a free. The `handed_off` counter is the number of
677-cells this node gave to a peer, `rebalanced` is the part of that number
678-that balancing moved, and `rebalance_failed` is the number of balancing
679-moves that no peer acquired. A positive `capacity_waiting` means
680-that the node queues activations behind its residency cap, and that is
681-the direct signal to add a node. A `pressured` lease is the memory form
682-of the same signal. Scale down only when every remaining node reports
683-`memory_headroom` and a small `restoring` backlog. A drain into a fleet
684-without spare capacity parks the cells dormant on the survivors, and
685-each later activation must then shed a resident cell to run.
686-
687-The `remote_route_refreshes` counter counts cached owner or capacity routes
688-that expire and start a new lookup. It increases once for each retired
689-route, so it also increases during normal lease renewal. An adoption
690-without a lease and an explicit invalidation do not increase it.
691-
692-The `deployment.isolates` object reports the V8 isolates of the current
693-deployment, and each entry of `deployment.draining` reports the isolates
694-of one superseded deployment. The `cells` map has one entry for each
695-Worker script, and the `stateless` and `services` entries cover the
696-request handlers. Each entry counts the isolates that accept work
697-(`live`), the live isolates that house no cell (`live_empty`), the
698-retiring isolates that still hold a heap (`retiring`), and the freed
699-slots (`freed`), with the cells, requests, and turns that they hold.
700-`heap_bytes` is the physical memory that V8 has committed to those heaps,
701-and `external_bytes` is the memory that the isolates track outside them. A
702-dormant cell holds no isolate, and celld retires an empty cell isolate on
703-its next maintenance pass, so a `live_empty` count that persists for more
704-than 30 seconds means that the pass does not run. A `retiring` count that
705-persists means that a turn or a request still holds the heap.
706-
707-The public `/.well-known/celld/health` path stays a boolean. It reports
708-503 during a drain and before a joining node settles, so an
709-orchestrator can gate a rolling update on it, but it carries no
710-utilization number.
711-
712-## Shut down and roll out a node
713-
714-celld shuts a node down gracefully on SIGTERM or SIGINT, the signals that
715-`systemctl stop`, `docker stop`, and a Kubernetes pod delete send. The
716-`/.well-known/celld/health` path reports the node as unhealthy, so a load balancer
717-stops public routing to it. New public requests receive a 503 response,
718-and celld closes each connection so the client can retry on a healthy
719-node. The node finishes the public HTTP requests that it accepted before
720-shutdown, and it continues to accept versioned peer traffic for cells that
721-it has not handed off.
722-
723-You must set a longer orchestrator stop grace, such as systemd
724-`TimeoutStopSec` or Kubernetes `terminationGracePeriodSeconds`. The grace
725-must cover the drain-token wait, the expected complete handoff, and one
726-no-progress interval (the settings below). Otherwise, the orchestrator
727-can send SIGKILL before celld completes the handoff.
728-
729-The handoff works in batches. The node reserves a batch of cells and
730-stops new local routes to them: an accepted request stays local until it
731-finishes, and a new request waits for the successor route. The node
732-also cancels each firing alarm in the batch. The alarm runtime records a retry
733-and arms its wake entry, so the successor can run the alarm at least once.
734-The node cancels an active internal fetch or RPC handler before the durability
735-proof, so a Queue broker cannot retain the batch until the process stops.
736-The node proves the batch durable in the live durability ensemble, and it
737-then closes each database. The node publishes one full L9 snapshot of the
738-closed database and verifies that the bucket contains a restore object. The
739-successor therefore does not replay the complete transaction history. If the
740-snapshot fails, the node materializes the additive L0 chain within the same
741-durability deadline. A database larger than the deadline can upload, 80 MiB
742-at the default deadline of 10 seconds, skips the snapshot and hands off
743-through its L0 chain at once, and a snapshot that fails once is not retried
744-for that cell. The node does not release the cell unless one complete
745-restore path is visible. The node then releases each ownership
746-record and asks a
747-compatible peer to acquire it. The peer acknowledges after the ownership
748-update and keeps the cell dormant, so the handoff does not restore an
749-unused runtime; a later request starts the cell under the peer activation
750-limit. The donor starts the next batch after each acknowledgement.
751-
752-celld orders the resident cells by their local request count. The newest local
753-request ID resolves an equal count, and the cell ID resolves an unused cell.
754-Therefore, a total stop bound moves shared resources before one-time resources.
755-
756-`CELLD_RELEASES` limits the complete handoffs in progress (default 128).
757-Each handoff includes activity cancellation, a durability proof, a final
758-snapshot, an ownership release, and a successor update. `CELLD_ACTIVATIONS`
759-limits the demand-driven restores and the startup work.
760-
761-`CELLD_SHUTDOWN_TOTAL_MS` sets the complete process stop bound (default
762-40000 ms). The orchestrator stop grace must exceed this bound, so celld can
763-finish its local durability shutdown. celld derives its internal waits from
764-this one value. The token wait is three quarters of the bound (default
765-30000 ms). The handoff no-progress interval is five eighths of the bound
766-(default 25000 ms), with a minimum of one millisecond. Fractional milliseconds
767-are rounded down before the minimum applies.
768-
769-Each successor acknowledgement restarts the no-progress interval. The total
770-stop bound still limits the complete shutdown, so progress cannot extend the
771-process lifetime beyond the configured grace. A handoff reserves the smaller
772-of one second and ten percent of the total bound for the drain-token release.
773-A same-node preserve operation uses the no-progress interval as its semantic
774-limit because it has no successor acknowledgements. The token-release reserve
775-does not apply to a same-node preserve.
776-
777-celld rejects the removed `CELLD_SHUTDOWN_DRAIN_MS` and
778-`CELLD_DRAIN_TOKEN_WAIT_MS` variables at startup. Remove these variables and
779-set only `CELLD_SHUTDOWN_TOTAL_MS` when the default total bound is unsuitable.
780-The `CELLD_PACED_HANDOFF` switch is also removed. A bucket-backed node
781-attempts ownership handoff within this budget. If no successor can accept
782-the cells, the existing no-progress and total stop bounds still apply.
783-
784-Simultaneous stop signals do not flood the surviving nodes. A draining node
785-claims a fleet drain token before it releases cells, so concurrent donors
786-hand off one node at a time. A donor that cannot claim the token within its
787-derived wait proceeds without it because the orchestrator grace is finite.
788-The token is advisory: a dead holder's claim expires, and a handoff without
789-the token is still safe.
790-
791-A fresh process also holds its first healthy response until the fleet is
792-settled. The process requires its live node lease, no active donor, and memory
793-below every pressure low watermark on each live node. A donor records each
794-node's restore backlog before it releases ownership. The replacement permits
795-one `CELLD_ACTIVATIONS` budget above each recorded value. The incumbent
796-ownership counts must remain within one equal successor share above the fleet
797-mean. A joining process can satisfy this condition when it advertises paced
798-handoff support and owns fewer cells than the busiest incumbent. The process
799-publishes this successor capacity before readiness, so an idle rollout can
800-repair the ownership distribution during the next donor handoff.
801-
802-An initial spare has no drain token, so it has no rollout restore baseline to
803-check. It still requires memory headroom and acceptable ownership distribution.
804-
805-An older peer does not publish the low-watermark result, so the gate uses that
806-peer's pressure latch during a mixed-version update. An unreadable fleet or an
807-unsettled condition keeps the process unhealthy until the condition clears.
808-`CELLD_READY_FLEET_GATE_MS` sets the observation deadline in milliseconds
809-(default 120000; `0` disables the gate). celld emits `ready_gate_expired` once
810-at that deadline, but readiness stays closed. Set an orchestrator rollout
811-deadline so a persistent capacity problem fails the rollout. After the first
812-healthy response, fleet state does not remove readiness again.
813-
814-A deadline-cut handoff can leave a node-log recovery for the replacement.
815-One process reads and uploads that dead session, and the other processes wait
816-for its result. A waiting process can replace an unresponsive recovery after
817-30 seconds, so a failed recovery cannot block the fleet permanently. A
818-recovery store error keeps the session unsealed, so a later recovery must read
819-every retained bundle before the replacement can restore the acknowledged
820-state.
821-
822-Recovery records a checkpoint after each group of 32 completed cell epochs.
823-A later attempt uses these checkpoints to skip repeated coverage checks and
824-uploads for the recorded transactions. Each checkpoint follows the data uploads,
825-so an interrupted upload cannot create a checkpoint for incomplete data.
826-An unavailable or invalid checkpoint causes recovery to check the cell coverage
827-again. A checkpoint write failure does not stop recovery. The checkpoints do
828-not replace the follower evidence or the session seal, and different sessions
829-continue to recover independently.
830-
831-The internal listener continues to accept `/state` requests during the
832-drain, and the response reports the handoff and restore counters. The
833-public health response identifies the active drain with a 503 status.
834-
835-A remote cell call can resolve an owner generation that a replacement process
836-rejects. celld then waits for a different `(node, epoch)` and refreshes the
837-route. The wait uses `CELLD_OPERATION_DEADLINE_MS` as its total bound (default
838-15000). celld retries only a peer attempt that proves that the handler did not
839-start. It does not retry an ambiguous attempt because the handler can have
840-completed without returning its response.
841-
842-A marked stale-owner response to the outer peer tunnel proves that the
843-application request did not start. celld can therefore refresh that route for
844-an HTTP, an RPC, or a WebSocket request.
845-
846-An application must keep one stable operation ID when it retries an ambiguous
847-fetch, RPC, D1, or service operation. A WebSocket transport cannot move between
848-owners, so a client must reconnect and keep the same application operation ID.
849-
850-To roll out a new version, use the rolling update of your orchestrator:
851-stop each node with SIGTERM, wait for its replacement to report healthy,
852-then move to the next node. celld paces the cell handoffs inside each node
853-shutdown, and the first-readiness gate paces the update against fleet
854-recovery, so a deployer does not need a separate fleet-level handoff gate.
855-
856-Some upgrades are exceptions:
857-
858-- The upgrade from v0.1.0 to v0.2.0 must not be a rolling update. Stop
859- every v0.1.0 node, then start the v0.2.0 nodes. Two changes require
860- this: v0.2.0 nodes advertise the internal listener, so ownership
861- records that v0.1.0 nodes wrote name an address that v0.1.0 peers can
862- not follow to a v0.2.0 node; and v0.2.0 compacts replicated data into
863- block objects that a v0.1.0 reader can not restore. A fleet must not
864- mix the two versions.
865-- The upgrade from v0.2.1 to v0.3.0 can use a rolling update. v0.3.0
866- changes the default durability from `bucket` to `fleet`: a single node
867- keeps the v0.2.1 behavior, and a fleet of two or more nodes activates
868- fleet replication automatically. Stage the v0.3.0 binary on every node,
869- and restart one node at a time. A mixed fleet stays safe, but a v0.3.0
870- node cannot replicate to a v0.2.x peer, so it acknowledges writes
871- through the bucket and retries until the peer runs v0.3.0. Do not start
872- a v0.2.x binary after that node runs v0.3.0 unless the shutdown log
873- contains `node-log close: sealed epoch`. A graceful stop attempts this
874- seal, but a stop under load can leave the record open, and a v0.2.x
875- binary cannot read writes that wait in the replicated log or bundle
876- objects. Therefore, this downgrade can lose acknowledged writes.
877-- The upgrade from v0.3.0 to v0.4.0 must not use a rolling update. Stop
878- every v0.3.0 node, and then start the v0.4.0 nodes. v0.4.0 moves every
879- proxied fetch, RPC, and WebSocket call onto one tunneled connection that
880- carries plain HTTP. The peer protocol refuses a different version, so the
881- two versions cannot proxy calls to each other. v0.4.0 also stores each new large KV value under its ownership
882- epoch and writes an epoch-qualified row reference. A v0.3.0 node cannot
883- read that reference, so a mixed fleet can make a committed KV value
884- unavailable. The tunnel establishment carries the version, so a later
885- protocol change can negotiate instead of refuse.
886-- The upgrade from v0.4.0 to v0.4.1 can use a rolling update. v0.4.1
887- restores a large cell by paging, and a paged epoch continues the chain
888- of the epoch before it instead of opening with a whole-database snapshot.
889- A v0.4.0 node cannot restore such an epoch. Each v0.4.1 node therefore
890- publishes the bucket format it reads in its lease, and it pages a
891- takeover only while every live lease reads that format. A v0.4.1 node in
892- a mixed fleet clones a large cell the way v0.4.0 does, and paging starts
893- on its own one lease lifetime after the last v0.4.0 node stops. Do not
894- start a v0.4.0 binary after that point: a cell that paged in has no
895- epoch a v0.4.0 node can restore, and it stays unavailable on that node
896- until a v0.4.1 node takes it over.
897-- The upgrade from v0.5.1 to v0.6.0 must not use a rolling update when
898- the fleet uses `fleet` durability. Stop every v0.5.1 node, and then start
899- the v0.6.0 nodes. A v0.6.0 node recovers its previous log session only
900- when a follower returns the ranged tail format. A v0.5.1 follower returns
901- the entries-only format, so the v0.6.0 node refuses to start. A fleet
902- that uses `bucket` durability has no followers, so it can use a rolling
903- update.
904-- The upgrade from v0.6.0 to v0.6.1 can use a rolling update. Do not set
905- `CELLD_LTX_RETENTION_SECS` on a node until every node runs v0.6.1. A
906- v0.6.0 node does not read `cells/<cell>/ltx/retired.json`, so it treats
907- the rows of a deleted epoch as unstored. That node keeps those bundle
908- rows, it cannot seal its log at shutdown, and its next start uploads the
909- rows again. No data is lost, but storage use and recovery time increase.
910- A v0.6.0 node refuses a Python Workers deployment, so deploy a Python
911- application only after every node runs v0.6.1. A v0.6.0 node also refuses
912- an asset index with a file larger than 25 MiB. Therefore, raise
913- `CELLD_MAX_ASSET_FILE_BYTES` above that size only after every node runs
914- v0.6.1. A rollback to v0.6.0 can
915- also use a rolling update. Unset `CELLD_LTX_RETENTION_SECS` on every node
916- first, so that no v0.6.1 node deletes an epoch while a v0.6.0 node runs.
917-
918-The internal listener also provides an alpha operator API. `/state`
919-reports the node state, and its `node_load` object is the same load sample
920-that the node lease publishes. `POST /reload` adopts the deployment pointer now,
921-and `POST /shutdown` starts the same graceful
922-handoff. `POST /rebalance/pause` stops balancing. The node publishes the
923-pause in its lease, and one paused lease stops every move in the fleet, so
924-a pause on one node pauses the fleet. `POST /rebalance/resume` on the same
925-node resumes it. The `POST /shutdown?handoff=preserve` request prepares a clean
926-same-node reload and keeps the ownership records. The preserve operation cancels
927-a cold activation, including a wait for a recovery retry, because the activation
928-has no runtime to retain. celld writes the reload marker
929-only after it uploads each stopped database position to the bucket. If an upload
930-fails, the next process uses the normal recovery path. A release can change this
931-API, so keep the operator tooling and the celld release together.
932-
933-## Diagnose a fleet
934-
935-`celld diagnose` reads the node leases in the bucket and sends a probe to
936-each live peer. It does not take a lease, and it does not change
937-ownership.
938-
939-```sh
940-celld diagnose \
941- --bucket "$CELLD_BUCKET" \
942- --endpoint "$S3_ENDPOINT" \
943- --region "$AWS_REGION"
944-```
945-
946-To probe only some nodes, use `--peer NODE_ID` one or more times. The
947-report identifies expired records, unsafe or incorrect advertised
948-addresses, peers that it cannot reach, authentication failures, and
949-protocol versions that do not agree.
950-
951-Each node line also shows `restoring`: the count of cold routes that hold
952-an activation permit or wait for one (a capacity waiter already holds a
953-permit, so each cold route counts once). During a rolling update, wait
954-for every node to report `restoring=0` before you restart the next node,
955-so one restart's cold work finishes before the next restart removes more
956-warm capacity. A node that restarts recovers its previous session's log
957-before it takes a lease. If a peer is already recovering that log, the
958-node waits behind the peer while the peer's heartbeat is fresh, and it
959-takes the recovery over only when the heartbeat stops.
960-
961-## List Durable Objects
962-
963-List the Durable Object instances in the bucket:
964-
965-```sh
966-celld cell list \
967- --bucket "$CELLD_BUCKET" \
968- --endpoint "$S3_ENDPOINT" \
969- --region "$AWS_REGION"
970-```
971-
972-Each line is a `Class:ID` cell scope. The ID is the Durable Object ID: a
973-64-character hash unless the application supplies its own name. Give a
974-class name to list only that class, and pass `--json` for one JSON object
975-per line. The command puts the class in the storage prefix, so `--limit`
976-applies only to that class. An instance appears after the first event reaches
977-it, because its owner then writes an ownership record to the bucket. An ID
978-that an application only derives does not appear.
979-
980-The listing also shows celld's own cells. A D1 database, a KV namespace,
981-and a Workflow are each a cell in a reserved class, and their names start
982-with `__`. They hold real data in the bucket, therefore the command shows
983-them. The `--json` output marks each row with `"reserved": true` or
984-`false`, so a script can select one kind:
985-
986-```sh
987-celld cell list --all --json --bucket "$CELLD_BUCKET" |
988- jq -r 'select(.reserved | not) | .scope'
989-```
990-
991-A storage request returns at most 1000 instances, so the command stops at
992-1000 instances and writes this line to stderr:
993-
994-```
995-1000 cells shown; more exist. Continue with --after Room:d99d9174b25e46310694dd931b47fbde70a7460bb7b210b546060651ea2ff6e0
996-```
997-
998-Pass that `--after SCOPE` to read the next 1000 instances, or use
999-`--limit N` for a different bound:
1000-
1001-```sh
1002-celld cell list --bucket "$CELLD_BUCKET" \
1003- --after Room:d99d9174b25e46310694dd931b47fbde70a7460bb7b210b546060651ea2ff6e0
1004-```
1005-
1006-Pass `--all` to read the whole listing in one command. This makes one
1007-request for each 1000 instances, so it can take minutes on a large fleet;
1008-the command reports its progress and its request count on stderr.
1009-
1010-The order is the storage order, and `--after` continues from the last
1011-instance printed, so a sequence of `--after` commands lists each instance
1012-one time. An instance that an application creates during the sequence can
1013-appear or not appear, because the listing is not a snapshot.
1014-
1015-The command writes the instances to stdout and every message to stderr,
1016-so a script reads only instance data:
1017-
1018-```sh
1019-celld cell list --all --json --bucket "$CELLD_BUCKET" > cells.ndjson
1020-```
1021-
1022-To see the superseded epoch prefixes that epoch GC can delete, run
1023-`celld cell gc --dry-run`. The command takes the same listing options and
1024-writes nothing. It prints one row for each cell that has candidates: the
1025-candidate epochs, their bytes, and the base of the cell's restore chain.
1026-The owners can delete later than the report shows, or not at all:
1027-
1028-- Only a fleet node with a positive `CELLD_LTX_RETENTION_SECS` deletes,
1029- and it uses that grace instead of `--grace-secs`.
1030-- A paged cell waits until its local file is complete.
1031-- An inactive cell waits until it is active again.
1032-- A cell that is not paged waits until its activation has a write, so a
1033- cell that is only read deletes nothing. After the write, the owner
1034- compacts at its next pass and deletes at the pass after it. With
1035- `CELLD_LTX_COMPACTION=0`, the cell waits for a handoff snapshot.
1036-- One pass deletes at most 64 epochs of a cell.
1037-
1038-If the command cannot read a cell, it reports the cell, continues, and
1039-exits with an error at the end.
1040-
1041-```sh
1042-celld cell gc --dry-run --bucket "$CELLD_BUCKET" --grace-secs 3600
1043-```
1044-
1045-## Hot-cell overload
1046-
1047-celld admits a maximum of 64 concurrent fetch events for one Durable Object.
1048-Set `CELLD_MAX_CELL_REQUESTS` to use a different positive limit.
1049-
1050-A Queue broker admits a maximum of 256 concurrent producer calls. It commits
1051-at most 64 calls in one transaction, and four transactions can overlap their
1052-durability proofs. These fixed bounds limit the copied message bodies while a
1053-storage proof is slow.
1054-
1055-celld returns HTTP status `503` when the target reaches this limit, and it
1056-does not start the excess event. The response contains `Retry-After: 1` and
1057-`X-Celld-Overload: cell`, so the application can retry or reject the work.
1058-A local or remote Queue owner uses the same status and headers when its
1059-producer reservations are full. The Queue response body is
1060-`{"error":"cell admission refused"}`. A fixed-rate client must count the
1061-response as rejected work, so an immediate retry does not increase the
1062-configured offered rate.
1063-
1064-A caught Queue producer error contains `cell overload: admission refused`, so
1065-the Worker can return the same admission response to the client.
1066-
1067-The runtime writes a `cell_overload_refused` log event when a target becomes
1068-saturated. The event contains the cell scope, the node, the region, the
1069-in-flight count, and the limit. Count these overload responses separately
1070-from the transport errors and the application failures.
1071-
1072-## Environment variables
1073-
1074-For the full list, run `celld -h`. This table shows the primary settings:
1075-
1076-| variable | purpose |
1077-| --- | --- |
1078-| `CELLD_BUCKET` | The fleet bucket, and an optional key prefix. The same as `--bucket` |
1079-| `S3_ENDPOINT` | The S3-compatible endpoint. The same as `--endpoint` |
1080-| `AWS_REGION`, `AWS_DEFAULT_REGION` | The storage region |
1081-| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` | Explicit AWS credentials. The standard AWS credential chain is also available |
1082-| `GOOGLE_APPLICATION_CREDENTIALS`, `GOOGLE_SERVICE_ACCOUNT_KEY` | Google credentials for a `gs://` bucket. Application Default Credentials are also available |
1083-| `AZURE_STORAGE_ACCOUNT_NAME` | The storage account for an `az://` bucket. The bucket NAME is the container |
1084-| `AZURE_STORAGE_ACCOUNT_KEY` | The storage account key. Do not combine it with an identity selector |
1085-| `AZURE_AUTHORITY_HOST`, `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE` | The standard AKS workload identity environment for an `az://` bucket. The authority must be the public Azure host |
1086-| `AZURE_STORAGE_USE_EMULATOR` | Set to `true` to develop against Azurite. celld does not qualify Azurite for a production fleet |
1087-| `CELLD_ADDR` | The public Worker listener. The same as `--listen` |
1088-| `CELLD_INTERNAL_ADDR` | The peer and operator listener. The same as `--internal-listen` |
1089-| `CELLD_ADVERTISE` | The internal address that peers can reach. The same as `--advertise` |
1090-| `CELLD_UNSAFE_PUBLIC_ADVERTISE` | Set to `1` to permit a literal public IP in `CELLD_ADVERTISE`. This setting does not resolve a DNS name or restrict the internal listener |
1091-| `CELLD_NODE` | An explicit node-session ID. Use 1 to 128 ASCII letters, numbers, dots, dashes, or underscores. The value cannot be `.` or `..` |
1092-| `CELLD_WATCH` | The local work directory for SQLite and replication |
1093-| `CELLD_ESBUILD` | The path of the esbuild executable |
1094-| `CELLD_ACTIVATIONS` | The limit for concurrent cold-cell activations (default: 8 for each available CPU, at least 16 and at most 128). A cold activation waits on the object store for most of its time, so the default is above the CPU count |
1095-| `CELLD_DEPLOY_POLL_S` | The interval in seconds at which a node reads the deployment pointer and adopts a new deployment in place (default: 30) |
1096-| `CELLD_DEPLOY_MAX_AGE_S` | How long a resident Durable Object can keep the previous deployment's code after an adoption before celld forces the move (default: 60; 0 forces at once) |
1097-| `CELLD_OPERATION_DEADLINE_MS` | The deadline for a non-restore operation (default: 15000) |
1098-| `CELLD_MAX_CELL_REQUESTS` | The concurrent fetch limit for one Durable Object or Queue broker (default: 64) |
1099-| `CELLD_MAX_REQUEST_BODY_BYTES` | The body limit for a public Worker request or a direct Durable Object request (default: 1 GiB) |
1100-| `CELLD_MAX_RESIDENT_CELLS` | The hard limit for resident cells, enforced at admission |
1101-| `CELLD_IDLE_EVICT_S` | The age in seconds after which an idle resident cell leaves memory and hibernates (unset: only pressure or the residency cap removes an idle cell) |
1102-| `CELLD_PLACEMENT_WEIGHT` | The ownership share of this node, relative to the other nodes' weights (default: the CPU count) |
1103-| `CELLD_REBALANCE_INTERVAL_MS` | The interval between shared fleet sample reads and the maximum sample age, in milliseconds (default: 5000; 0 disables balancing) |
1104-| `CELLD_MAX_RSS_MB` | The memory threshold for pressure shedding, applied to the greater of the allocator-adjusted RSS and the allocator-adjusted active cgroup working set (default: 80% of the available memory; 0 disables the threshold and the absolute cap) |
1105-| `CELLD_DURABILITY` | How celld proves a write durable before it answers. The default is `fleet`: the node serving the cell sends the write to one or two other nodes and answers once they hold it on disk, or once the bucket upload finishes, whichever comes first. This needs two or more nodes; a single node has nobody to send to, so every write waits for the bucket. Set `bucket` to always wait for the bucket |
1106-| `CELLD_LOG_PIPELINE` | The limit for fleet log rounds that can be in flight (default: 4) |
1107-| `CELLD_LOG_HEDGE_MS` | The wait before a leader sends a second copy of a slow log append to a follower. The default is adaptive: celld derives the wait from the slowest recent append in the ensemble (4 times that append, at least 250 ms, and always below the eviction backstop), so a loaded fleet does not send copies for honest slow appends. Set a value to use a fixed wait in milliseconds, and set `0` to disable the second copy. An append is idempotent per sequence, so the copy is safe, and the leader uses the answer that arrives first and confirms |
1108-| `CELLD_LTX_TRUNCATE_PAGES` | The WAL size, in pages, at which celld truncates an ordinary cell's WAL file at the next checkpoint (default: 128, a 512 KiB cap). A passive checkpoint does not shrink the WAL file, so each capture reads the stale region after a restart. The truncate keeps the read small. A truncate ends in a full image of the database, so a database larger than 4 MiB also waits until its WAL is larger than the database. Queue cells use passive checkpoints only. Set `0` to disable the truncate for all cells |
1109-| `CELLD_LTX_RETENTION_SECS` | Unset or `0` by default, and then celld deletes no epoch prefix. A positive value enables epoch GC on a fleet node (`CELLD_DURABILITY=fleet`, the default); a node with `CELLD_DURABILITY=bucket` deletes nothing. After the owner of a cell activates it, the owner deletes each epoch prefix below the base of the cell's restore chain. The base is the epoch where a restore stops, because that epoch opens with a whole-database snapshot. A paged cell waits until its local file is complete, because until then it reads pages from the older epochs. A cell that is not paged waits until its activation has a write, so a cell that is only read deletes nothing. After the write, the owner compacts the new rows into the first L1 object of its epoch, even below `CELLD_LTX_COMPACTION_MIN_TXIDS`. That object lets the owner prove that a successor restores from its epoch. The owner compacts at its next pass after the write and deletes at the pass after the compaction, and each pass can come up to 5 minutes after the previous one. With `CELLD_LTX_COMPACTION=0` the owner does not compact, so the cell waits for a handoff snapshot. With `CELLD_LTX_HYDRATE_MBPS=0` a paged cell never completes its file, so epoch GC never runs for it. The owner keeps its own epoch and the epoch before it. It also keeps each epoch whose newest object is younger than the value, in seconds. The owner first writes `cells/<cell>/ltx/retired.json`, so that bundle GC and recovery treat the rows of those epochs as stored. Epoch GC skips facet streams. It needs a store with list-after-write consistency; see [the storage requirements](guarantees.md#what-the-bucket-must-provide). Run `celld cell gc --dry-run` to see the candidates |
1110-| `CELLD_LTX_COMPACTION` | The default is `1`: celld creates additive L1 objects, and a takeover reads tens of objects instead of thousands. Set `0` on every node of a mixed fleet until all nodes can read v0.5.2 block objects, because an old reader cannot take over a cell after its first L1 publication |
1111-| `CELLD_LTX_COMPACTION_MIN_TXIDS` | The durable TXID distance that queues a background L1 attempt (default: 256) |
1112-| `CELLD_LTX_COMPACTION_MIN_MB` | The L0 bytes since the last fold that queue a background L1 attempt, in MiB (default: 32, at most 64). The byte threshold lets a cell with large rows compact before it reaches the transaction threshold |
1113-| `CELLD_LTX_PAGED` | The default is `1`: celld restores a taken-over cell by paging when its chain is at least `CELLD_LTX_PAGED_MIN_MB`. It opens the database through a fault-in VFS that reads each page from the bucket on first use, instead of downloading the whole restore chain first, and a smaller chain is cloned. Set `0` to clone every chain. A paged cell's local file is a cache, so celld does not preserve it as an eviction snapshot and does not publish a handoff snapshot from it. A paged epoch continues the chain it paged in. celld uploads a small marker object at the next transaction before the cell serves, and its later objects follow it, so a restore composes the epochs. Set `0` on every node of a mixed fleet until all nodes run v0.4.1 or later, because a paged epoch holds no whole-database snapshot and a node before v0.4.1 restores one epoch only. Such a node refuses the activation of that cell, and the refusal is permanent for the cell. A full activation opens its epoch with a whole-database snapshot. A node pages only while every live lease in the fleet publishes a bucket format that reads a paged epoch, so a rolling update from a release without paged restore clones until that release has left the fleet; the `paged_gate` log event reports each change. A clean reload does not keep a paged cell resident; the next process pages it in again. An inspect of a paged cell must read the bucket, because celld does not copy the cell's sparse file in place. After the activation, celld fills the rest of the file in the background at `CELLD_LTX_HYDRATE_MBPS`, so a cell that stays resident soon reads only its local file. Until that fill completes, a read of a page that is not in the local file is a page fault. The fault reads the bucket synchronously inside the JavaScript turn, so it blocks the cell and the other cells on its isolate until its bucket reads complete. A query that reads many such pages can therefore take minutes. Set `CELLD_LTX_PAGED=0` to remove the fault path for every cell. A higher `CELLD_LTX_PAGED_MIN_MB` removes the fault path only for a chain that is smaller than the new value. In both cases, the cost is a slower activation, because celld downloads the whole chain before the cell serves |
1114-| `CELLD_LTX_PAGED_MIN_MB` | The chain size, in MiB, from which a restore pages instead of cloning (default: 256). A clone of a smaller chain takes seconds and fits the node's memory, so it needs no fault path and no hydration. Set `0` to page every chain |
1115-| `CELLD_LTX_HYDRATE_MBPS` | The rate, in MiB per second, at which a paged cell's file fills in the background (default: 16). One cell fills at a time per node. Set `0` to keep a paged cell sparse, so every cold page is read from the bucket on first use |
1116-| `CELLD_LTX_COMPACTIONS` | The node-wide limit for concurrent background L1 attempts (default: 2). `CELLD_RELEASES` bounds final handoff snapshots |
1117-| `CELLD_LTX_DURABILITY_TIMEOUT_SECS` | The budget for one durability proof, in seconds (default: 10). The budget runs from the moment the node starts to upload the write. A write that waits behind the uploads of other cells waits while the node proves other writes, for at most six budgets. The same budget bounds the final snapshot or L0 fallback of a handoff. A slow object store can need a longer budget for a large write |
1118-| `CELLD_TOKIO_THREADS` | The worker thread count of the host Tokio runtime (default: the CPU count) |
1119-| `RUST_LOG` | The runtime log filter |
1120-
1121-When a node starts, celld emits one `host_runtime` log event at the `info`
1122-level. The `worker_count` field reports the worker count of the host Tokio
1123-runtime, so an operator can verify the applied `CELLD_TOKIO_THREADS` setting.
1124-
1125-Each L1 compaction attempt merges at most 256 source objects. The buffer
1126-budget for the source data is 64 MiB. If one source object exceeds this
1127-budget, celld compacts that object through temporary files in the cell's
1128-local LTX directory. The node must have free disk space for the source copy
1129-and the output file. The codec keeps the page index in memory, so its memory
1130-use increases with the page count. Compaction keeps the source objects and
1131-publishes a continuous L1 range, including when a source overlaps an existing
1132-L1 object.
1133-
1134-`CELLD_OUTPUT_GATE` is removed. Remove the variable from the environment,
1135-including a value of `1` or an empty value. celld always waits for the
1136-configured durability proof before it acknowledges a write.
1137-
1138-These settings are also removed. Remove them from the environment, including
1139-an empty value or a value that matches the former default.
1140-
1141-| Removed setting | Current behavior |
1142-| --- | --- |
1143-| `CELLD_OTEL_SINK` | Set `CELLD_OTEL=1` for the fleet bucket or set `CELLD_OTEL` to the collector base URL for OTLP. |
1144-| `CELLD_AI_BINDING`, `CELLD_AI_URL` | The experimental AI adapter is removed. Call the provider from application code and remove the AI binding declaration. |
1145-| `CELLD_CLOUD_RESTART_ON_DEPLOY` | A managed deployment adopts the new code in place. Credential rotation can still restart the process. |
1146-| `CELLD_STORAGE_PROBE` | A node checks the storage contract before it serves a bucket-backed deployment. |
1147-| `CELLD_EVICTIONS` | A node runs at most four concurrent evictions. |
1148-| `CELLD_LOG_CAPTURE_WORKERS` | A node uses at most eight workers for log capture. |
1149-| `CELLD_REBALANCE_BATCH_CELLS` | A balancing batch moves at most 32 idle cells. The release limit and the receiver capacity can reduce this count. |
1150-| `CELLD_PRESENCE_SHADOW` | A managed node sends its serving status and its owned-cell count. It does not send a separate bucket comparison. |
1151-| `CELLD_LOG_BUNDLE` | Fleet durability uses bundled tiering. A node still uses per-cell uploads when the bucket must prove a write. |
1152-| `CELLD_QUEUE_PRODUCER_GROUP_MS` | A Queue owner uses a 4 ms timer to group concurrent producer calls into a SQLite transaction. |
1153-| `CELLD_LOG_GROUP_COMMIT_MS` | A node waits 1 ms before a fleet log capture when Queue writes are pending. |
1154-| `CELLD_PACED_HANDOFF` | A bucket-backed node attempts ownership handoff within the shutdown budget. Set `CELLD_SHUTDOWN_TOTAL_MS` to match the supervisor grace. |
1155-
1156-The Queue batching timers do not set a response deadline. A Queue still waits
1157-for the wake-entry proof and the configured write durability proof.
1158-
1159-Fleet uploads combine changes from multiple cells into shared bucket objects.
1160-`CELLD_DURABILITY=bucket` still requires a bucket proof for every acknowledged
1161-write, even when peers are available. Recovery can read the existing bundles
1162-and the per-cell objects.
1163-
1164-The storage check still distinguishes a contract violation from an ambiguous
1165-transport error. A violation prevents startup. After the existing retries,
1166-an ambiguous error produces a warning and permits startup.
1167-
1168-Use `celld diagnose --read-only` to check the bucket leases and the peers.
1169-A managed presence report does not prove that a node holds a bucket lease.
1170-
1171-The help output also shows the advanced tuning switches and their
1172-defaults.
1173-
1174-An unset variable selects its documented default. A Boolean variable
1175-accepts only `0` or `1`. celld exits during startup when a supplied value
1176-is invalid.
13+document, chat room, or AI agent. A cell serves HTTP, holds WebSocket
14+connections, sets alarms, and makes outbound connections. Cells share no
15+database. Each cell runs on one thread: a second request interleaves only
16+while the first awaits, and storage operations are synchronous.
17+
18+You run celld as one process on each machine. That process is a **node**,
19+and the nodes that share one bucket are a **fleet**. Any node can serve
20+any cell, so you add capacity by starting another node against the same
21+bucket.
22+
23+## Cell lifecycle
24+
25+A cell has the same states as a Durable Object. A **resident** cell is in
26+memory: it is **active** while it does work, and **idle** when it waits.
27+celld removes an idle cell from memory after `CELLD_IDLE_EVICT_S` seconds
28+without work, and earlier under memory pressure or at the residency cap.
29+Without `CELLD_IDLE_EVICT_S`, only pressure or the cap removes an idle
30+cell. A cell that keeps its hibernatable WebSocket clients on its node is
31+**hibernated**. A cell that no node holds is **inactive**: it is only an
32+object in the bucket and costs almost zero. Every cell starts inactive.
33+
34+The constructor runs again on each activation, because a cell keeps no
35+memory across these transitions. A hibernated cell wakes like a cold start,
36+but its WebSocket clients stay connected and it stays on its node.
37+
38+Each activation can add a new epoch prefix to the bucket. celld deletes
39+the older prefixes only when `CELLD_LTX_RETENTION_SECS` enables epoch GC,
40+so without it the bytes of a cell increase with each activation. See
41+[epoch GC](guarantees.md#epoch-gc).
42+
43+One 8 GB node holds 1,000 resident cells, so one resident cell costs
44+approximately $0.05 each month.
45+
46+## Ownership and durability
47+
48+Exactly one node serves a cell at a time. A node claims a cell with a
49+conditional write of a small record to the bucket, so the bucket decides
50+who wins. There is no leader election and no membership list. The claim
51+expires unless the node renews it, so a failed machine releases its cells.
52+
53+celld does not answer a write until the data survives a failure (RPO=0).
54+`CELLD_DURABILITY` selects how celld proves that a write is durable:
55+
56+- `bucket`: the node answers after the write reaches the bucket. Each write
57+ costs one object store round trip.
58+- `fleet` (the default): the node sends each write to one or two other
59+ nodes, and it answers when they hold it on disk or when the bucket upload
60+ finishes, whichever comes first.
61+
62+A single node has no peer, so a one-node fleet in `fleet` mode waits for the
63+bucket on every write, as `bucket` mode does. Two or more
64+nodes are faster, because a follower fsync is much faster than an object
65+store write. Run two or more nodes if write latency
66+matters. A fleet that loses all but one node falls back to the bucket in the
67+same way, and it stays correct. Set `bucket` to wait for the bucket on every
68+write, even when peers are available.
69+
70+When a node stops, another node takes its cells over, and first collects
71+the data that the stopped node had not uploaded. See
72+[what celld guarantees](guarantees.md) for the mechanism and the bucket
73+requirements.
74+
75+## Alarms
76+
77+When an event sets an alarm before its response boundary, celld does not
78+send a successful response until a durable wake entry covers the alarm. A
79+later `waitUntil` alarm does not delay the response of another event.
80+
81+A hibernated cell fires its alarm on the node that owns it. One node holds
82+the waker role, and it wakes only the cells whose owner node has stopped.
83+
84+## What do you build with cells
85+
86+- **Real-time applications.** A multiplayer game, a chat room, or a
87+ collaborative document is one cell. The room needs no lock and no
88+ external message bus.
89+- **Agents.** Each AI agent is one cell with its memory, schedule, and
90+ inbox in its own SQLite database. An inactive agent costs almost nothing.
91+- **Sharded web applications.** One cell for each user, tenant, or device
92+ shards the application from the start, so no shared database exists.
93+
94+## Contents
95+
96+- [Cells and nodes](#cells-and-nodes)
97+- [Cell lifecycle](#cell-lifecycle)
98+- [Ownership and durability](#ownership-and-durability)
99+- [Alarms](#alarms)
100+- [What do you build with cells](#what-do-you-build-with-cells)
101+- [Install](#install)
102+- [Configure object storage](#configure-object-storage)
103+- [Deploy an application](#deploy-an-application)
104+- [Develop an application locally](#develop-an-application-locally)
105+- [Operate D1, KV, and R2](#operate-d1-kv-and-r2)
106+- [Start a node](#start-a-node)
107+- [Add nodes](#add-nodes)
108+- [Feed an autoscaler](#feed-an-autoscaler)
109+- [Shut down and roll out a node](#shut-down-and-roll-out-a-node)
110+- [Upgrade notes](#upgrade-notes)
111+- [Diagnose a fleet](#diagnose-a-fleet)
112+- [List Durable Objects](#list-durable-objects)
113+- [Hot-cell overload](#hot-cell-overload)
114+- [Environment variables](#environment-variables)
115+- [Services](#services)
116+- [Cloudflare compatibility](cloudflare-compat.md)
117+- [What celld guarantees](guarantees.md)
118+- [Limitations](limitations.md)
119+- [Security](security.md)
120+- [Telemetry](telemetry.md)
121+- [Testing](testing.md)
122+- [WebAssembly](wasm.md)
123+- [Python Workers](services/workers.md#python-workers)
124+
125+## Services
126+
127+Each service page contains a runnable example and the known differences from
128+the Cloudflare service.
129+
130+- [Workers](services/workers.md)
131+- [Durable Objects / Cells](services/durable-objects.md)
132+- [Durable Object Facets](services/durable-object-facets.md)
133+- [KV](services/kv.md)
134+- [Queues](services/queues.md)
135+- [D1](services/d1.md)
136+- [R2](services/r2.md)
137+- [Workflows](services/workflows.md)
138+- [Cron Triggers](services/cron-triggers.md)
139+- [Static assets](services/static-assets.md)
140+- [Dynamic Workers](services/dynamic-workers.md)
141+- [Containers](services/containers.md)
142+
143+## Install
144+
145+```sh
146+curl -fsSL https://celld.dev/install.sh | sh
147+```
148+
149+The installer downloads the `celld` binary. Replication runs inside the
150+process, so a node needs no external replicator. If the installer tells
151+you, add `~/.local/bin` to `PATH`. To install one exact release, set
152+`CELLD_VERSION` to its tag, for example `v0.0.1`; to go back, run the
153+installer again with the previous tag. Each
154+[release](https://github.com/denoland/celld/releases) has a build
155+attestation: verify a file with
156+`gh attestation verify <asset> --repo denoland/celld`.
157+
158+## Configure object storage
159+
160+The `s3://`, `gs://`, and `az://` scheme names are case-insensitive, and
161+celld ignores leading and trailing whitespace in `CELLD_BUCKET`.
162+
163+For an S3-compatible bucket, celld uses the standard AWS credential chain,
164+including an EC2 instance role and Amazon EKS Pod Identity. For Cloudflare
165+R2, create a bucket and an S3 API token with access to it, and set:
166+
167+```sh
168+export AWS_ACCESS_KEY_ID=...
169+export AWS_SECRET_ACCESS_KEY=...
170+export AWS_REGION=auto
171+export S3_ENDPOINT=https://ACCOUNT_ID.r2.cloudflarestorage.com
172+export CELLD_BUCKET=s3://YOUR-BUCKET
173+```
174+
175+For Google Cloud Storage, celld uses Application Default Credentials. Run
176+`gcloud auth application-default login`, or point
177+`GOOGLE_APPLICATION_CREDENTIALS` at a service-account key. Then set
178+`CELLD_BUCKET=gs://YOUR-BUCKET`. On Compute Engine, the default instance
179+scope permits only storage reads, so create the instance with the
180+`cloud-platform` scope.
181+
182+For Azure Blob Storage, the bucket name is the container:
183+
184+```sh
185+export AZURE_STORAGE_ACCOUNT_NAME=YOUR-ACCOUNT
186+export AZURE_STORAGE_ACCOUNT_KEY=...
187+export CELLD_BUCKET=az://YOUR-CONTAINER
188+```
189+
190+You must configure exactly one Azure credential family: an account key, a
191+managed identity, or a workload identity. A system-assigned managed
192+identity needs only the account name. A user-assigned managed identity
193+needs exactly one of `AZURE_CLIENT_ID`, `AZURE_OBJECT_ID`, and
194+`AZURE_MSI_RESOURCE_ID`. An identity needs the
195+[`Storage Blob Data Contributor`](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#storage-blob-data-contributor)
196+role or equal permissions. A managed identity works on an Azure VM and an
197+AKS node, but not on App Service or Container Apps; use a workload
198+identity or an account key there. The AKS workload identity environment
199+(`AZURE_AUTHORITY_HOST`, `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`,
200+`AZURE_FEDERATED_TOKEN_FILE`) must use the public authority host,
201+`https://login.microsoftonline.com`. celld rejects every other recognized
202+Azure configuration variable, such as another credential source or an
203+endpoint override. For local development against Azurite, set
204+`AZURE_STORAGE_USE_EMULATOR=true`. celld does not qualify Azurite for a
205+fleet.
206+
207+A `gs://` or `az://` bucket takes no `S3_ENDPOINT` and no `AWS_*`
208+credentials, and celld ignores the storage region.
209+
210+The bucket credentials give full control of the fleet, so keep them safe.
211+
212+A bucket value can add a key prefix, `s3://YOUR-BUCKET/PREFIX`, so two
213+fleets can share one bucket. Without a prefix, the objects stay at the
214+bucket root.
215+
216+The store must provide conditional writes, exact ranged reads, and
217+read-after-write consistency. Amazon S3, Cloudflare R2, Google Cloud
218+Storage, Tigris, and Azure Blob Storage qualify; Backblaze B2, Hetzner,
219+and DigitalOcean Spaces do not. MinIO (community edition) passes the
220+storage test but is not qualified for production; do not use
221+RELEASE.2025-09-06T17-38-46Z, which rejects the first deploy
222+(denoland/celld#162). See [what celld guarantees](guarantees.md).
223+
224+## Deploy an application
225+
226+Install `esbuild` on `PATH` if the project contains Worker code. Then run
227+`celld deploy` in a Wrangler project:
228+
229+```sh
230+git clone https://github.com/denoland/celld
231+cd celld/examples/counter
232+celld deploy . \
233+ --bucket "$CELLD_BUCKET" \
234+ --endpoint "$S3_ENDPOINT" \
235+ --region "$AWS_REGION"
236+```
237+
238+`celld deploy` accepts module Workers, Durable Object bindings, service
239+bindings, variables, cron triggers, D1 databases, KV namespaces, Queues,
240+R2 buckets, Workflows, WebAssembly modules, and static assets. An unknown
241+Wrangler configuration key stops the deploy. See
242+[Cloudflare compatibility](cloudflare-compat.md) for the complete boundary.
243+A node verifies the SHA-256 digest of each module before it builds a
244+deployment.
245+
246+A running node does not restart for a new deployment. Each node reads
247+`deploy/current.json` every `CELLD_DEPLOY_POLL_S` seconds (default 30) and
248+adopts a new deployment in place. `POST /reload` on the internal listener
249+adopts it now, and also rebuilds an unchanged deployment. A request that
250+started on the previous deployment finishes on it. A deployment that does
251+not build leaves the current one serving, and the node reports the error
252+in its log and in the `/reload` response.
253+
254+An inactive Durable Object runs the new deployment at its next activation.
255+A resident one moves when no request, alarm handler, or regular WebSocket
256+is active, and it keeps its storage and its hibernatable WebSockets. A
257+request that arrives during the move waits for the new code. An outbound
258+call from a request that already runs in the object does not wait, so that
259+request can finish on the old code. After
260+`CELLD_DEPLOY_MAX_AGE_S` seconds (default 60; 0 forces at once), celld
261+forces the move: it cancels the running work and closes regular WebSockets
262+with code 1012, as Cloudflare does. During the move, a request on one
263+deployment can call a Durable Object on the other, so two adjacent
264+versions must accept each other's calls. `/state` reports the deployment
265+of each resident object.
266+
267+## Develop an application locally
268+
269+```sh
270+celld dev [PROJECT_DIR_OR_CONFIG]
271+```
272+
273+The command starts a local object store, deploys the application, and runs
274+one node. It does not need Docker or a cloud bucket. The Worker listener
275+is `http://127.0.0.1:9876` by default.
276+
277+| flag | effect |
278+| --- | --- |
279+| `--port PORT` | The Worker listener port |
280+| `--host ADDR` | The Worker listener interface. The operator listener stays on loopback |
281+| `--logs` | Show the node warning and information logs |
282+| `--clean` | Delete `.celld/dev` before the start |
283+| `--watch-ignore GLOB` | Ignore one more project-relative glob. Repeatable. Not valid with `--no-watch` |
284+| `--no-watch` | Disable automatic builds and restarts |
285+
286+Set `NO_COLOR` to disable color, or `FORCE_COLOR` to enable it when the
287+output is not a terminal. `NO_COLOR` takes priority.
288+
289+The command reads `.dev.vars` beside the Wrangler configuration, as
290+`wrangler dev` does. Without `.dev.vars`, it reads `.env` and then
291+`.env.local`, which overrides `.env`. Each `NAME=value` entry becomes a
292+Worker variable and overrides `vars`. A line can start with `export`, and
293+a quoted value can span lines, for example a PEM key. Comments after a
294+value and variable references are not supported. In `.env` files, the
295+command skips, with a warning, an entry that is not a valid binding name
296+or that collides with another binding; in `.dev.vars` such an entry stops
297+the build. `celld deploy` does not read these files. Add `.dev.vars`,
298+`.env`, `.env.local`, and `.celld/` to `.gitignore`.
299+
300+The command keeps the local state in `.celld/dev`, across restarts and
301+configuration changes. celld does not migrate stored state, so a stored
302+value from an earlier configuration can make the application fail with an
303+error that looks unrelated. Use `--clean` to start from an empty state.
304+`--clean` deletes nothing else under `.celld`.
305+
306+The command watches the project directory and rebuilds on a source,
307+configuration, or dotenv change. The current application serves during the
308+build, and a failed build does not replace it. The watcher ignores
309+`.celld`, `.git`, `.wrangler`, `node_modules`, and `target` at each depth,
310+and it does not watch files outside the project.
311+
312+The local object store is not available to a fleet node or an operator
313+subcommand; they need a supported cloud bucket.
314+
315+## Operate D1, KV, and R2
316+
317+These commands use the fleet bucket. `celld d1` and `celld kv` reach the
318+database cell through a node.
319+
320+```sh
321+celld d1 migrations apply ledger --bucket "$CELLD_BUCKET"
322+celld kv bulk put sessions wrangler-export.json --bucket "$CELLD_BUCKET"
323+```
324+
325+The `migrations_dir` value must be a relative path inside the project,
326+without a `..` component. The KV bulk commands use the Wrangler file
327+format. `celld kv bulk get` streams; a named output file changes only
328+after the export completes, and a failed stdout export leaves an
329+incomplete JSON array.
330+
331+`celld r2` reads and writes the objects of an `r2_buckets` binding under
332+the reserved `r2/<bucket_name>/` prefix. It needs no running node, so a
333+release pipeline can publish an artifact before it deploys.
334+
335+```sh
336+celld r2 put assets app.zip --path dist/app.zip \
337+ --content-type application/zip \
338+ --metadata '{"release":"1.2.3"}' \
339+ --bucket "$CELLD_BUCKET"
340+```
341+
342+The first argument is the `bucket_name`, not the binding name. `--metadata`
343+becomes `customMetadata`, and the content flags become `httpMetadata`. An
344+object that another tool writes into the prefix is also readable, without
345+`cacheExpiry` or checksums. `celld r2 get` streams the body to stdout, and
346+`celld r2 head` prints the stored record; with `--json`, the
347+`http` and `custom` fields hold `httpMetadata` and `customMetadata`.
348+
349+`celld kv list` and `celld r2 list` print at most 1000 keys and print the
350+`--after KEY` that continues the listing on stderr. Pass `--all` for every
351+key and `--json` for one JSON object per key.
352+
353+Every celld command writes data to stdout and messages to stderr. A closed
354+stdout pipe is a successful stop.
355+
356+## Start a node
357+
358+For local development, the default listener is sufficient:
359+
360+```sh
361+celld \
362+ --bucket "$CELLD_BUCKET" \
363+ --endpoint "$S3_ENDPOINT" \
364+ --region "$AWS_REGION"
365+```
366+
367+For a fleet node, bind the public and internal listeners separately:
368+
369+```sh
370+celld \
371+ --bucket "$CELLD_BUCKET" \
372+ --endpoint "$S3_ENDPOINT" \
373+ --region "$AWS_REGION" \
374+ --listen 0.0.0.0:8080 \
375+ --internal-listen 10.0.0.12:8081 \
376+ --advertise node-a.internal:8081
377+```
378+
379+`--advertise` requires an explicit `--internal-listen`, and so does a
380+non-loopback `--listen`. You must route the advertised address to the
381+internal listener, not to the public listener; celld cannot verify this.
382+
383+## Add nodes
384+
385+Start each node with the same bucket settings and its own reachable
386+`--advertise` address. The nodes find each other through leases in the
387+bucket; there is no join command.
388+
389+Peer traffic has no TLS and cell fetch and RPC traffic is not signed, and
390+the internal listener has an unauthenticated operator API. Put the
391+advertised addresses on a trusted private network or an encrypted overlay
392+such as WireGuard or Tailscale, and never expose the internal listener to
393+the internet. See [security](security.md).
394+
395+The node that receives a request activates a new cell, so a load balancer
396+must include a new node in its rotation. A node at its residency cap or
397+under memory pressure hands the activation to the least-loaded peer. A
398+pressure eviction releases the ownership record
399+(`CELLD_PRESSURE_OWNERSHIP=release`, the default), so the cell can move.
400+An idle eviction keeps the record, so the cell wakes on its own node. An
401+idle eviction must stop the runtime within `CELLD_OPERATION_DEADLINE_MS`,
402+or the cell stays resident until the next idle period.
403+
404+A new node also receives idle cells. Every node reads a shared fleet
405+sample, `fleet/capacity-v1.json`, every `CELLD_REBALANCE_INTERVAL_MS`
406+(default 5000; `0` disables balancing). Each node gets a share of the
407+owned cells in proportion to `CELLD_PLACEMENT_WEIGHT` (default: the CPU
408+count). The most loaded node hands at most 32 idle cells at a time to the
409+node furthest below its target, and a receiver fills to 2% below its
410+target. Only a hibernated cell moves; its hibernatable WebSockets close
411+with code 1012 so that the clients reconnect. A fleet without
412+`CELLD_IDLE_EVICT_S` therefore balances only the cells that hibernate on
413+their own. A draining node and a node with a cold-activation backlog
414+(`restoring`) receive no cells. Nothing moves while a node reports a lease
415+without a weight, so a rolling upgrade to this version completes first.
416+`POST /rebalance/pause` on any node pauses balancing for the fleet, and
417+`POST /rebalance/resume` on the same node resumes it.
418+
419+## Feed an autoscaler
420+
421+celld does not scale itself. An external system starts and stops the
422+nodes, and celld hands the cells off.
423+
424+Each node writes its lease to `nodes/<node>.json` in the bucket. The lease
425+lives `CELLD_TTL_MS` (default 10000) and renews at one third of that. Its
426+load block, dated by `sampled_ms`, contains `owned_cells`,
427+`placement_weight`, `resident_cells`, `host_websockets`, `rss_bytes`,
428+`in_use_bytes`, `cpu_percent_x100`, `open_fds`, `pressured`,
429+`memory_headroom`, `shed_cells`, and `restoring`. `owned_cells` includes
430+dormant cells; a restarted node omits it until it has read its ownership
431+records. `resident_cells` counts only cells in memory. The memory and CPU
432+values are sampled every second.
433+
434+`GET /state` on the internal listener reports the live counters. Its
435+`node_load` object is the lease load block.
436+
437+| field | meaning |
438+| --- | --- |
439+| `capacity_waiting` | Activations queued behind the residency cap. Positive means add a node |
440+| `activation_waiting`, `restoring` | Cold activations that wait for or hold a permit |
441+| `owned_cells`, `occupied`, `shedding` | Ownership, residency, and pressure shedding |
442+| `handed_off`, `rebalanced`, `rebalance_failed` | Cells given to peers, the part balancing moved, and the balancing moves no peer took |
443+| `remote_route_refreshes` | Cached routes that expired and started a new lookup. Normal lease renewal increases it |
444+| `allocator` | Rust allocator bytes: `allocated_bytes`, `resident_bytes`, `mapped_bytes`, `retained_bytes`. V8 heaps are not included |
445+| `libc_malloc` | Linux only: `in_use_bytes` and `free_bytes` of the C allocator that SQLite and V8 use |
446+| `deployment.isolates`, `deployment.draining` | Per Worker script (`cells`, `stateless`, `services`): `live`, `live_empty`, `retiring`, `freed`, `heap_bytes`, `external_bytes` |
447+
448+A `live_empty` count that persists for more than 30 seconds means that
449+isolate maintenance does not run. A persistent `retiring` count means that
450+a turn or a request still holds the heap.
451+
452+A positive `capacity_waiting` or a `pressured` lease is the signal to add
453+a node. Scale down only when every remaining node reports
454+`memory_headroom` and a small `restoring` backlog. A drain into a full
455+fleet leaves the cells dormant on the survivors, and each later activation
456+must shed a resident cell.
457+
458+`/.well-known/celld/health` on the public listener is a boolean. It
459+reports 503 during a drain and before a joining node settles.
460+
461+## Shut down and roll out a node
462+
463+celld shuts down gracefully on SIGTERM or SIGINT. The health path reports
464+503, new public requests receive 503 with the connection closed, and
465+accepted requests finish. The node hands its cells off in batches: it
466+cancels running alarms (the successor retries them), proves the data
467+durable, publishes a final snapshot, and releases each ownership record to
468+a peer. The peer keeps the cell dormant until a request arrives. A
469+database larger than the durability deadline can upload (80 MiB at the
470+default 10 seconds) hands off without the snapshot. Busy cells move first.
471+`POST /shutdown` on the internal listener starts the same handoff.
472+
473+| variable | default | effect |
474+| --- | --- | --- |
475+| `CELLD_SHUTDOWN_TOTAL_MS` | 40000 | The complete stop bound. The drain-token wait is 3/4 of it (30000) and the handoff no-progress interval is 5/8 (25000) |
476+| `CELLD_RELEASES` | 128 | Concurrent complete handoffs |
477+| `CELLD_ACTIVATIONS` | see [table](#environment-variables) | Demand-driven restores and startup work |
478+| `CELLD_READY_FLEET_GATE_MS` | 120000 | The first-readiness gate deadline; `0` disables the gate |
479+
480+You must set the orchestrator stop grace (systemd `TimeoutStopSec`,
481+Kubernetes `terminationGracePeriodSeconds`) above
482+`CELLD_SHUTDOWN_TOTAL_MS`, or SIGKILL can interrupt the handoff. celld
483+rejects the removed `CELLD_SHUTDOWN_DRAIN_MS` and
484+`CELLD_DRAIN_TOKEN_WAIT_MS` at startup.
485+
486+Concurrent stops do not flood the survivors: a draining node claims a
487+fleet drain token, so nodes hand off one at a time. A node that cannot
488+claim the token within its wait proceeds without it.
489+
490+A new process does not report healthy until the fleet settles: no node
491+drains, every node is below its memory low watermark, the restore backlogs
492+are small, and ownership is balanced. At `CELLD_READY_FLEET_GATE_MS`,
493+celld logs `ready_gate_expired` once, but readiness stays closed, so set
494+an orchestrator rollout deadline. After the first healthy response, fleet
495+state does not remove readiness.
496+
497+A cut handoff can leave the log of the stopped process for its
498+replacement to recover. Another process can replace a recovery that does
499+not respond for 30 seconds.
500+
501+A remote call to a cell that is changing owner waits for the new owner,
502+for at most `CELLD_OPERATION_DEADLINE_MS` (default 15000). celld retries
503+only an attempt that provably did not start. An application must keep one
504+stable operation ID when it retries an ambiguous fetch, RPC, D1, or
505+service operation. A WebSocket client must reconnect.
506+
507+To roll out a new version, use the rolling update of your orchestrator:
508+stop each node with SIGTERM, wait for its replacement to report healthy,
509+and then move to the next node. celld paces the handoffs and readiness
510+itself.
511+
512+`POST /shutdown?handoff=preserve` prepares a same-node restart that keeps
513+the ownership records. It cancels cold activations and uploads each
514+stopped database first. If an upload fails, the next process uses normal
515+recovery. The internal operator API is alpha and can change in any
516+release, so keep operator tooling and celld releases together.
517+
518+## Upgrade notes
519+
520+- **v0.1.0 to v0.2.0: stop all.** Stop every v0.1.0 node, then start
521+ v0.2.0. The two versions use different peer addresses and data formats,
522+ so a fleet must not mix them.
523+- **v0.2.1 to v0.3.0: rolling.** The default durability changes from
524+ `bucket` to `fleet`. Do not start a v0.2.x binary after a node runs
525+ v0.3.0 unless its shutdown log contains
526+ `node-log close: sealed epoch`. Otherwise, the downgrade can lose
527+ acknowledged writes.
528+- **v0.3.0 to v0.4.0: stop all.** The peer protocol changes, and a v0.3.0
529+ node cannot read new large KV values, so a mixed fleet can make
530+ committed KV values unavailable.
531+- **v0.4.0 to v0.4.1: rolling.** Paged restore starts one lease lifetime
532+ after the last v0.4.0 node stops. Do not start a v0.4.0 binary after
533+ that: it cannot restore a paged cell.
534+- **v0.5.1 to v0.6.0: stop all with `fleet` durability.** A v0.6.0 node
535+ refuses to start against a v0.5.1 follower. A `bucket` durability fleet
536+ can roll.
537+- **v0.6.0 to v0.6.1: rolling.** Until every node runs v0.6.1, do not set
538+ `CELLD_LTX_RETENTION_SECS`, do not deploy a Python Worker, and do not
539+ raise `CELLD_MAX_ASSET_FILE_BYTES` above 25 MiB. A rollback to v0.6.0
540+ can roll after you unset `CELLD_LTX_RETENTION_SECS` on every node.
541+- **v0.6.1 to v0.6.2: rolling.** Until every node runs v0.6.2, a handler
542+ failure on the owner of a forwarded Durable Object fetch can reach the
543+ caller as a 500 response. A v0.6.2 pair rejects the caller's `stub.fetch()`
544+ instead, as a local owner does. A rollback to v0.6.1 can also roll.
545+
546+## Diagnose a fleet
547+
548+`celld diagnose` reads the node leases and probes each live peer. It does
549+not take a lease or change ownership. Use `--peer NODE_ID`, repeatable, to
550+probe only some nodes.
551+
552+```sh
553+celld diagnose \
554+ --bucket "$CELLD_BUCKET" \
555+ --endpoint "$S3_ENDPOINT" \
556+ --region "$AWS_REGION"
557+```
558+
559+The report shows expired leases, bad advertised addresses, unreachable
560+peers, authentication failures, and protocol mismatches. Each node line
561+shows `restoring`, the cold activations in progress. During a rolling
562+update, wait for `restoring=0` on every node before you restart the next.
563+
564+## List Durable Objects
565+
566+```sh
567+celld cell list \
568+ --bucket "$CELLD_BUCKET" \
569+ --endpoint "$S3_ENDPOINT" \
570+ --region "$AWS_REGION"
571+```
572+
573+Each line is a `Class:ID` scope. Give a class name to list only that
574+class, and pass `--json` for one JSON object per line. An instance appears
575+after its first event; an ID that is only derived does not appear. D1
576+databases, KV namespaces, and Workflows are cells in reserved classes whose
577+names start with `__`. The `--json` output marks them `"reserved": true`:
578+
579+```sh
580+celld cell list --all --json --bucket "$CELLD_BUCKET" |
581+ jq -r 'select(.reserved | not) | .scope'
582+```
583+
584+The command stops at 1000 instances and prints the continuation on stderr:
585+
586+```
587+1000 cells shown; more exist. Continue with --after Room:d99d9174b25e46310694dd931b47fbde70a7460bb7b210b546060651ea2ff6e0
588+```
589+
590+Pass that `--after SCOPE` for the next page, `--limit N` for a different
591+page size, or `--all` for everything (one request per 1000, with progress
592+on stderr). The listing is not a snapshot, but a sequence of `--after`
593+commands lists each existing instance once.
594+
595+`celld cell gc --dry-run` takes the same options and prints, for each cell,
596+the epoch prefixes that epoch GC can delete, their bytes, and the restore
597+base. It writes nothing, and it exits with an error at the end if it could
598+not read a cell.
599+
600+```sh
601+celld cell gc --dry-run --bucket "$CELLD_BUCKET" --grace-secs 3600
602+```
603+
604+The real deletion can come later or not at all. Only a node with a
605+positive `CELLD_LTX_RETENTION_SECS` deletes, with that grace instead of
606+`--grace-secs`. A cell deletes only while it is active, after its
607+activation has a write and, if paged, after its local file is complete.
608+With `CELLD_LTX_COMPACTION=0`, a cell on a fleet node waits for a handoff
609+snapshot. One pass deletes at most 64 epochs of a cell.
610+
611+## Hot-cell overload
612+
613+celld admits at most 64 concurrent fetch events for one Durable Object
614+(`CELLD_MAX_CELL_REQUESTS`). A Queue broker admits 256 concurrent producer
615+calls, commits at most 64 in one transaction, and overlaps up to four
616+transactions.
617+
618+Over the limit, celld returns `503` with `Retry-After: 1` and
619+`X-Celld-Overload: cell`, and does not start the event. The Queue response
620+body is `{"error":"cell admission refused"}`, and a caught Queue producer
621+error contains `cell overload: admission refused`. A load generator must
622+count these responses as rejected work. celld logs `cell_overload_refused`
623+with the cell scope, node, region, in-flight count, and limit.
624+
625+## Environment variables
626+
627+For the full list, including advanced tuning switches, run `celld -h`. An
628+unset variable selects its default. A Boolean variable accepts only `0` or
629+`1`. celld exits at startup on an invalid value.
630+
631+| variable | purpose |
632+| --- | --- |
633+| `CELLD_BUCKET` | The fleet bucket, and an optional key prefix. The same as `--bucket` |
634+| `S3_ENDPOINT` | The S3-compatible endpoint. The same as `--endpoint` |
635+| `AWS_REGION`, `AWS_DEFAULT_REGION` | The storage region |
636+| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` | Explicit AWS credentials. The standard AWS credential chain is also available |
637+| `GOOGLE_APPLICATION_CREDENTIALS`, `GOOGLE_SERVICE_ACCOUNT_KEY` | Google credentials for a `gs://` bucket. Application Default Credentials are also available |
638+| `AZURE_STORAGE_ACCOUNT_NAME` | The storage account for an `az://` bucket |
639+| `AZURE_STORAGE_ACCOUNT_KEY` | The storage account key. Do not combine it with an identity selector |
640+| `AZURE_AUTHORITY_HOST`, `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE` | The AKS workload identity environment. The authority must be the public Azure host |
641+| `AZURE_STORAGE_USE_EMULATOR` | Set to `true` to develop against Azurite |
642+| `CELLD_ADDR` | The public Worker listener. The same as `--listen` |
643+| `CELLD_INTERNAL_ADDR` | The peer and operator listener. The same as `--internal-listen` |
644+| `CELLD_ADVERTISE` | The internal address that peers can reach. The same as `--advertise` |
645+| `CELLD_UNSAFE_PUBLIC_ADVERTISE` | Set to `1` to permit a literal public IP in `CELLD_ADVERTISE`. It does not resolve a DNS name or restrict the internal listener |
646+| `CELLD_NODE` | An explicit node-session ID: 1 to 128 ASCII letters, numbers, dots, dashes, or underscores, but not `.` or `..` |
647+| `CELLD_WATCH` | The local work directory for SQLite and replication |
648+| `CELLD_ESBUILD` | The path of the esbuild executable |
649+| `CELLD_ACTIVATIONS` | Concurrent cold-cell activations (default: 8 per CPU, at least 16, at most 128) |
650+| `CELLD_DEPLOY_POLL_S` | The deployment pointer poll interval in seconds (default: 30) |
651+| `CELLD_DEPLOY_MAX_AGE_S` | Seconds before celld forces a resident Durable Object onto a new deployment (default: 60; 0 forces at once) |
652+| `CELLD_OPERATION_DEADLINE_MS` | The deadline for a non-restore operation (default: 15000) |
653+| `CELLD_MAX_CELL_REQUESTS` | Concurrent fetch events for one Durable Object (default: 64) |
654+| `CELLD_MAX_REQUEST_BODY_BYTES` | The body limit for a public Worker request or a direct Durable Object request (default: 1 GiB) |
655+| `CELLD_MAX_RESIDENT_CELLS` | The hard limit for resident cells, enforced at admission |
656+| `CELLD_IDLE_EVICT_S` | Seconds after which an idle cell leaves memory and hibernates (unset: only pressure or the residency cap removes an idle cell) |
657+| `CELLD_PLACEMENT_WEIGHT` | The ownership share of this node, relative to the other nodes (default: the CPU count) |
658+| `CELLD_REBALANCE_INTERVAL_MS` | The fleet sample interval and maximum age (default: 5000; 0 disables balancing) |
659+| `CELLD_MAX_RSS_MB` | The memory threshold for pressure shedding, on the greater of the allocator-adjusted RSS and the active cgroup working set (default: 80% of the available memory; 0 disables the threshold and the absolute cap) |
660+| `CELLD_DURABILITY` | `fleet` (default): the node sends each write to one or two other nodes and answers when they hold it on disk or the bucket upload finishes. A single node has no peer, so every write waits for the bucket. `bucket`: always wait for the bucket |
661+| `CELLD_LOG_PIPELINE` | Fleet log rounds in flight (default: 4) |
662+| `CELLD_LOG_HEDGE_MS` | The wait before a second copy of a slow log append. The default is adaptive: 4 times the slowest recent append, at least 250 ms. `0` disables the copy |
663+| `CELLD_LTX_TRUNCATE_PAGES` | The WAL size, in pages, at which celld truncates the WAL at the next checkpoint (default: 128, 512 KiB). A database larger than 4 MiB waits until the WAL is larger than the database. `0` disables it |
664+| `CELLD_LTX_RETENTION_SECS` | Unset or `0` (default): celld deletes no epoch prefix. A positive value enables [epoch GC](guarantees.md#epoch-gc): the owner deletes the prefixes below the restore base, but keeps its own epoch, the one before it, and each epoch younger than this many seconds. A pass runs at most every 5 minutes. With `CELLD_LTX_HYDRATE_MBPS=0`, a paged cell never qualifies. Epoch GC skips facet streams and needs [list-after-write consistency](guarantees.md#what-the-bucket-must-provide) |
665+| `CELLD_LTX_COMPACTION` | `1` (default) creates additive L1 objects, so a takeover reads tens of objects instead of thousands. Set `0` on every node of a mixed fleet until all nodes read v0.5.2 block objects |
666+| `CELLD_LTX_COMPACTION_MIN_TXIDS` | The TXID distance that queues an L1 compaction (default: 256) |
667+| `CELLD_LTX_COMPACTION_MIN_MB` | The L0 MiB that queue an L1 compaction (default: 32, at most 64) |
668+| `CELLD_LTX_COMPACTIONS` | Concurrent L1 compactions per node (default: 2) |
669+| `CELLD_LTX_PAGED` | `1` (default): a takeover of a chain of at least `CELLD_LTX_PAGED_MIN_MB` reads pages from the bucket on first use instead of a full download. Until the background fill completes, a page fault blocks the cell's isolate, so a large query can take minutes. Set `0` to download every chain. Set `0` on every node of a mixed fleet with a node before v0.4.1, which permanently refuses a paged cell. The `paged_gate` log event reports when paging turns on or off |
670+| `CELLD_LTX_PAGED_MIN_MB` | The chain size, in MiB, from which a restore pages (default: 256; `0` pages every chain) |
671+| `CELLD_LTX_HYDRATE_MBPS` | The background fill rate of a paged cell, in MiB per second, one cell at a time per node (default: 16; `0` keeps the cell sparse) |
672+| `CELLD_LTX_DURABILITY_TIMEOUT_SECS` | The budget for one durability proof, and for the final snapshot of a handoff (default: 10). A queued write waits at most six budgets. A slow store can need more |
673+| `CELLD_TOKIO_THREADS` | Host Tokio worker threads (default: the CPU count). The `host_runtime` log event at startup reports `worker_count` |
674+| `RUST_LOG` | The runtime log filter |
675+
676+An L1 compaction merges at most 256 source objects within a 64 MiB buffer.
677+A larger source object spills to temporary files in the cell's local LTX
678+directory, so the node needs free disk for the source and the output.
679+
680+These settings are removed. Remove them from the environment, including an
681+empty value or the former default:
682+
683+| removed setting | current behavior |
684+| --- | --- |
685+| `CELLD_OUTPUT_GATE` | celld always waits for the durability proof before it acknowledges a write |
686+| `CELLD_SHUTDOWN_DRAIN_MS`, `CELLD_DRAIN_TOKEN_WAIT_MS` | Rejected at startup. Use `CELLD_SHUTDOWN_TOTAL_MS` |
687+| `CELLD_OTEL_SINK` | Set `CELLD_OTEL=1` for the fleet bucket or set `CELLD_OTEL` to the collector base URL for OTLP |
688+| `CELLD_AI_BINDING`, `CELLD_AI_URL` | The AI adapter is removed. Call the provider from application code and remove the AI binding |
689+| `CELLD_CLOUD_RESTART_ON_DEPLOY` | A managed deployment adopts the new code in place. Credential rotation can still restart the process |
690+| `CELLD_STORAGE_PROBE` | A node always checks the storage contract. A violation prevents startup; an ambiguous transport error produces a warning |
691+| `CELLD_EVICTIONS` | A node runs at most four concurrent evictions |
692+| `CELLD_LOG_CAPTURE_WORKERS` | A node uses at most eight log capture workers |
693+| `CELLD_REBALANCE_BATCH_CELLS` | A balancing batch moves at most 32 idle cells |
694+| `CELLD_PRESENCE_SHADOW` | A managed node sends its serving status and owned-cell count. Use `celld diagnose --read-only` to check leases |
695+| `CELLD_LOG_BUNDLE` | Fleet durability always bundles uploads |
696+| `CELLD_QUEUE_PRODUCER_GROUP_MS` | A Queue owner groups producer calls with a 4 ms timer |
697+| `CELLD_LOG_GROUP_COMMIT_MS` | A node waits 1 ms before a fleet log capture when Queue writes are pending |
698+| `CELLD_PACED_HANDOFF` | A node always attempts the handoff within `CELLD_SHUTDOWN_TOTAL_MS` |
modifieddocs/cloudflare-compat.md+37−52View file
@@ -1,25 +1,18 @@
11 # Cloudflare compatibility
22
3-celld implements the Cloudflare Workers APIs that this page links to. Read the
4-Cloudflare documentation for the standard behavior of each API.
3+This page lists only the differences from the linked Cloudflare APIs. An entry
4+without a note matches Cloudflare.
55
6-This page lists only an unavailable feature, a celld-specific limit, or an
7-observable difference. If an entry has no note, celld intends to match the
8-linked Cloudflare API.
6+- **Yes**: implemented, except for the listed differences.
7+- **Partial**: a substantial part is unavailable.
8+- **Experimental**: can change without notice.
9+- **No**: not implemented.
910
10-- **Yes** means that celld implements the API, except for the listed differences.
11-- **Partial** means that a substantial part of the API is unavailable.
12-- **Experimental** means that celld can change the API without notice.
13-- **No** means that celld does not implement the API.
11+celld rejects an unsupported configuration or API at deployment or first use.
12+An unsupported feature that does not cause an error is a defect.
1413
15-celld must reject an unsupported configuration or API at deployment or first
16-use. An unsupported feature that does not cause an error is a defect.
17-
1814 ## Services
1915
20-Each supported service has a page with an example and the known differences
21-from Cloudflare.
22-
2316 | service | status |
2417 | --- | --- |
2518 | [Workers](services/workers.md) | **Yes** |
@@ -80,8 +73,7 @@
8073
8174 ### [Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
8275
83-The [services table](#services) lists the available binding types. Each binding
84-type that the table does not list is unavailable.
76+Only the binding types in the [services table](#services) are available.
8577
8678 ### [Context](https://developers.cloudflare.com/workers/runtime-apis/context/)
8779
@@ -119,6 +111,12 @@
119111 If the owner connection fails between frames before a Close, the ingress sends
120112 code 1012. If a frame is incomplete, the ingress closes the transport instead.
121113 - `acceptWebSocket()` throws above 90 percent of the V8 heap limit.
114+- A response with a WebSocket to a request without `Upgrade: websocket` fails,
115+ as in workerd. A Durable Object's `stub.fetch()` call then rejects, and an
116+ HTTP client receives status 500. The server end of the socket receives a close
117+ event with code 1006.
118+- A Durable Object's `stub.fetch()` call rejects when the handler fails, on the
119+ owner node and on any other node.
122120
123121 ### [Web Crypto](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
124122
@@ -157,17 +155,13 @@
157155 - `node:fs` provides `access`, `mkdir`, `realpath`, `stat`, `lstat`, and
158156 `readFile`. It exposes an empty, request-local `/tmp` and a read-only
159157 `/bundle` that contains the Worker modules.
160-- The global `process` gives each field that it defines the same value that
161- workerd gives it, so a dependency that reads `process.execPath`,
162- `process.argv`, or `process.title` at module scope can load. celld does not
163- define the full workerd surface, so a field such as `process.kill` or
164- `process.features` is undefined.
158+- The global `process` matches workerd for each field that it defines, such
159+ as `process.execPath`, `process.argv`, and `process.title`. Other fields,
160+ such as `process.kill` and `process.features`, are undefined.
165161 - The celld bundler supports a synchronous CommonJS `require()` of a Node.js
166162 built-in module. A raw ESM Worker has no global `require()`.
167-- A Node.js built-in module object is writable, so a CommonJS dependency that
168- replaces a function on the module at load can start. The `graceful-fs`
169- package replaces `fs.close` this way. A patch stays in the isolate that
170- applies it, therefore another Worker never observes the patch.
163+- A Node.js built-in module object is writable, so a dependency such as
164+ `graceful-fs` can patch it at load. The patch stays in its isolate.
171165 - An import of another Node.js module succeeds, but its first call throws an
172166 error.
173167
@@ -187,12 +181,11 @@
187181
188182 ### BroadcastChannel
189183
190-celld defines the class so that a bundle can load, but its constructor throws an
191-error.
184+The class exists so that a bundle can load, but its constructor throws.
192185
193186 ## Compatibility flags
194187
195-celld honors these compatibility switches:
188+celld honors these compatibility flags:
196189
197190 - `delete_all_deletes_alarm`
198191 - `js_rpc`
@@ -201,18 +194,18 @@
201194 - `websocket_standard_binary_type`
202195 - The static-assets navigation flags
203196
204-celld accepts each other compatibility flag without effect.
205-`Cloudflare.compatibilityFlags` reports only the flags that celld honors.
197+celld accepts every other flag without effect.
198+`Cloudflare.compatibilityFlags` reports only the honored flags.
206199
207200 ## Wrangler configuration
208201
209-`celld deploy` accepts `wrangler.jsonc` or `wrangler.json`. It does not accept
202+`celld deploy` accepts `wrangler.jsonc` or `wrangler.json`, not
210203 `wrangler.toml`.
211204
212205 The `name` value must contain 1 to 63 lowercase ASCII letters, digits, or
213206 internal hyphens. It cannot start or end with a hyphen.
214207
215-The deployment accepts these top-level keys:
208+The accepted top-level keys:
216209
217210 - `$schema`, `name`, `main`, and `no_bundle`
218211 - `compatibility_date` and `compatibility_flags`
@@ -223,26 +216,18 @@
223216 - `worker_loaders` and `containers`
224217 - `define` and `rules`
225218
226-Each other top-level key, including `routes`, stops the deployment.
219+Any other top-level key, including `routes`, stops the deployment.
227220
228-`celld deploy` bundles with esbuild, and it gives `define` and `rules` to that
229-run. Each `define` value is a JavaScript expression, as it is for Wrangler.
230-A rule must have a `type` of `Text`, `Data`, or `CompiledWasm`, and each of its
231-globs must have the form `**/*.ext` or `*.ext`: esbuild selects a loader by
232-file extension, so celld refuses a glob that selects a different set of files.
233-
234-Two rules can name one extension only if they give it the same type. Two rules
235-that give one extension different types stop the deployment, because no single
236-loader satisfies both. celld applies a `CompiledWasm` rule to `**/*.wasm`
237-already, so a `CompiledWasm` rule for that extension agrees with the built-in
238-rule and the deployment continues. Another type for `**/*.wasm` stops the
221+`define` and `rules` go to the esbuild run. Each `define` value is a
222+JavaScript expression, as in Wrangler. A rule `type` must be `Text`, `Data`,
223+or `CompiledWasm`, and each glob must have the form `**/*.ext` or `*.ext`,
224+because esbuild selects a loader by extension. Two rules that give one
225+extension different types stop the deployment. celld already applies
226+`CompiledWasm` to `**/*.wasm`, so only that type is valid for `.wasm`.
227+`no_bundle` skips esbuild, so `no_bundle` with `define` or `rules` stops the
239228 deployment.
240229
241-`no_bundle` does not run esbuild. A config that sets `no_bundle` with `define`
242-or `rules` therefore stops the deployment.
230+An asset-only project can omit `main`. `celld deploy` refuses an unsafe asset
231+path, and `.assetsignore` requires Wrangler.
243232
244-An asset-only project can omit `main`. The native deploy command refuses an
245-unsafe asset path, and `.assetsignore` requires Wrangler.
246-
247-See [Limitations](limitations.md) for the operating-system, networking,
248-security, pressure, and update boundaries.
233+See [Limitations](limitations.md) for the operational limits.
modifieddocs/guarantees.md+237−398View file
@@ -1,491 +1,330 @@
11 # What celld guarantees
22
3-celld makes two promises about your data. Exactly one node serves a cell
4-at a time, so two machines never write the same database. And celld does
5-not answer a write until that write survives a failure, so nothing you
6-were told succeeded is lost.
3+celld makes two promises. Exactly one node serves a cell at a time, so two
4+machines never write the same database. celld does not acknowledge a write
5+until the write survives a failure, so an acknowledged write is never lost. Both
6+promises require a bucket with working conditional writes and ranged reads, and
7+a supervisor that restarts the process.
78
8-This page explains how celld keeps both promises. Fencing prevents a
9-slow, paused, or disconnected node's writes from damaging the current
10-owner's data after it loses a cell.
11-Each ownership epoch has a separate storage prefix, so a stale node's
12-writes cannot overwrite the current owner's data.
13-Both guarantees require a bucket with working conditional writes and
14-ranged reads, and a supervisor that restarts the process.
15-
169 ## What the bucket must provide
1710
18-celld needs four properties from the object store:
19-
2011 - A conditional create: the write must fail when the object exists.
21-- A conditional overwrite: the write must fail when the object changed
22- after the read.
23-- Read-after-write consistency: a read after a successful write must
24- return that write.
25-- Ranged reads: a read must return the requested byte range and the bytes
26- from that range.
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.
2724
28-Epoch GC (`CELLD_LTX_RETENTION_SECS`) needs a fifth property:
25+The qualified stores are Amazon S3, Cloudflare R2, Tigris, Google Cloud Storage,
26+and Azure Blob Storage. The release tests run against R2; the S3 path uses the
27+same client and headers. Azure was qualified on 2026-08-18, single-node, under
28+an account key, a VM managed identity, and an AKS workload identity. A managed
29+identity on Azure App Service or Azure Container Apps does not work; see
30+[limitations](limitations.md).
2931
30-- List-after-write consistency: a listing after a successful write must
31- include the written object.
32+Backblaze B2, Hetzner Object Storage, and DigitalOcean Spaces do not implement
33+the required conditional writes, so two nodes can own one cell on them. A store
34+that accepts the conditional headers but ignores the condition fails late and
35+silently, so run the storage test.
3236
33-Amazon S3, Cloudflare R2, Google Cloud Storage, and Azure Blob Storage
34-provide it. A Tigris Global or Dual-region bucket provides it only in the
35-region of the write. An operator must not enable epoch GC on such a
36-bucket when the nodes of a fleet are in more than one region.
37+MinIO (the community edition) passes the storage test but is not qualified for
38+production. RELEASE.2025-09-06T17-38-46Z answers the conditional create of an
39+absent object with `NoSuchKey`, so the first deploy fails (denoland/celld#162).
40+Use RELEASE.2025-09-07T16-13-09Z or later.
3741
38-The qualified stores are Amazon S3, Cloudflare R2, Tigris, Google Cloud
39-Storage, and Azure Blob Storage. celld's release tests run against R2,
40-and the S3 path uses the same client and the same headers.
42+A `gs://` bucket uses the Cloud Storage XML API with
43+`x-goog-if-generation-match` and OAuth credentials, because Cloud Storage does
44+not apply `If-Match` to a PUT. For an `az://` bucket, the NAME is the container.
4145
42-Backblaze B2, Hetzner Object Storage, and DigitalOcean Spaces do not
43-implement the required conditional writes. celld is not correct on such
44-a store: two nodes can then own one cell. A store can also accept the
45-conditional headers and ignore the condition, and that store fails late
46-and silently, so run the storage test below.
47-
48-MinIO (the community edition) implements the conditional writes and
49-passes the storage test, but celld has not qualified it for production.
50-One release is broken: RELEASE.2025-09-06T17-38-46Z answers the
51-conditional create of an absent object with `NoSuchKey`, so the first
52-deploy fails (denoland/celld#162). Use RELEASE.2025-09-07T16-13-09Z or
53-later.
54-
55-The request dialect differs per provider. An S3-compatible bucket gets
56-the `If-None-Match: *` and `If-Match` headers, and the condition
57-compares the etag. A `gs://` bucket selects the Cloud Storage XML API
58-with the `x-goog-if-generation-match` precondition and OAuth
59-credentials, because Cloud Storage does not apply `If-Match` to a PUT.
60-An `az://` bucket (the NAME is the container) uses the same `If-`
61-headers, which Put Blob applies. The adapter treats `AlreadyExists` and
62-`Precondition` (HTTP 412 on Azure) as clean conditional-write
63-rejections and keeps every other error ambiguous, because an ambiguous
64-write can have changed the object.
65-
66-Azure was qualified on 2026-08-18 under an account key, a VM managed
67-identity, and an AKS workload identity, single-node. A managed identity
68-on Azure App Service or Azure Container Apps does not work; see
69-[limitations](limitations.md).
70-
7146 ## The storage test
7247
73-No store publishes these properties, so celld asks the store directly.
74-The command `celld diagnose` sends four conditional writes to your
75-bucket and reports the result:
48+`celld diagnose` sends four conditional writes to the bucket:
7649
7750 ```
7851 ok bucket conditional write (create, reject-create, update, reject-stale)
7952 ```
8053
81-Two of the four writes must fail. A store that accepts either one
82-cannot fence a cell, so celld names the store as the fault and the
83-command exits with an error. Each node also runs these writes before it
84-serves. The node then requests part of a second object and verifies the
85-returned range and bytes.
86-
87-The startup test uses new objects for each attempt. It makes at most
88-three attempts when an operation fails without a clear cause. The node
89-starts with a warning after all three attempts fail because a temporary
90-outage can end after startup. The node stops immediately when a required
91-conditional write or ranged read is unsupported. It also stops when the
92-store ignores a condition or returns a wrong range or wrong bytes. A node
93-cannot disable this startup test. Use `celld diagnose --read-only` with a
54+Two of the four must fail; if the store accepts either, the command exits with
55+an error that names the store. Use `celld diagnose --read-only` with a
9456 credential that cannot write.
9557
96-The diagnose test writes and deletes one small object under `probe/`.
97-The startup test uses a second object for the ranged read. A process
98-that stops mid-test can leave an object behind; it is small, and celld
58+Each node runs the same writes before it serves, then reads a range of a second
59+object and verifies the range and bytes. A node cannot disable this test. It
60+makes at most three attempts, with new objects, when an operation fails without
61+a clear cause; then the node starts with a warning, because a temporary outage
62+can end. The node stops immediately when a required conditional write or ranged
63+read is unsupported, when the store ignores a condition or the `Range` header,
64+or when it returns a wrong range or wrong bytes.
65+
66+A process that stops mid-test can leave a small object under `probe/`; celld
9967 never reads it.
10068
101-celld reserves `probe/`, `cells/`, `nodes/`, `node-cells/`, `fleet/`,
102-`deploy/`, `deploy-blobs/`, `log/`, `wake/`, and `telemetry/`. celld deletes
103-objects under some of these prefixes, so an application must not write under
104-any of them.
69+celld reserves `probe/`, `cells/`, `nodes/`, `node-cells/`, `fleet/`, `deploy/`,
70+`deploy-blobs/`, `log/`, `wake/`, and `telemetry/`, and deletes objects under
71+some of them. An application must not write under any of them.
10572
106-celld requires ranged reads for stored cell data. The startup test stops
107-a node when the store ignores the `Range` header or returns incorrect
108-bytes.
109-
11073 ## The supervisor
11174
112-You must run celld under a supervisor that restarts the process, such
113-as systemd, Docker with a restart policy, or Kubernetes. A node fences
114-itself when it loses its lease (the mechanism is below), and a fenced
115-process exits; without a restart, the fleet loses that capacity until
116-an operator intervenes.
75+Run celld under a supervisor that restarts the process, such as systemd, Docker
76+with a restart policy, or Kubernetes. A node that loses its lease fences itself
77+and exits, and without a restart the fleet loses that capacity. The supervisor
78+must restart without an attempt limit and wait at least one lease lifetime
79+between attempts.
11780
118-The supervisor must restart without an attempt limit, and it must wait
119-at least one lease lifetime between attempts. A node that cannot
120-acquire a lease at startup retries and does not exit, so a repeated
121-fence needs a node that acquires a lease and then loses it, and the
122-wait keeps that cycle slow enough to observe.
123-
12481 ## The mechanism
12582
126-The short version: the ownership records use conditional writes, so two
127-nodes cannot acquire one cell. The replicated data carries its fencing
128-epoch in the object key, so a node that lost ownership writes only into
129-a superseded prefix. And before celld acknowledges a write, it proves
130-the write durable and confirms that it still owns the cell.
131-
13283 ### The ownership record
13384
134-Each cell has one ownership record in the bucket. The record names the
135-owner node's session and carries a fencing epoch. A node acquires a
136-cell with a conditional create when no record exists, or a compare-and-swap
137-on an existing record. The bucket accepts only one competing write, so two
138-nodes cannot acquire the same cell.
85+Each cell has one ownership record in the bucket. It names the owner node's
86+session and carries a fencing epoch. A node acquires a cell with a conditional
87+create when no record exists, or a compare-and-swap on an existing record, so
88+two nodes cannot acquire the same cell. Every activation, a takeover or a local
89+wake, advances the epoch, so an epoch never has two writers.
13990
140-Every activation advances the epoch, a takeover and a local wake alike.
141-Each owner therefore replicates under a fresh epoch, and an epoch never
142-has two writers.
143-
14491 ### The epoch prefix
14592
146-The replicator copies each cell's SQLite data to the bucket under
147-`cells/<cell>/ltx/e<epoch>/`, with plain unconditional PUTs. The epoch
148-in the key is the fence: a node that lost ownership can keep writing,
149-but its writes land in a superseded prefix, and a restore selects the
150-current lineage. (The tiering path can first combine segments from many
151-cells into a node bundle, and it drains each segment into its per-cell
152-prefix later.)
93+The replicator copies each cell's SQLite data to `cells/<cell>/ltx/e<epoch>/`
94+with unconditional PUTs. The epoch in the key is the fence: a node that lost
95+ownership can keep writing, but only into a superseded prefix, and a restore
96+selects the current lineage. The tiering path can first combine segments from
97+many cells into a node bundle and drain each segment into its per-cell prefix
98+later. A bundle is deleted only when the per-cell prefixes cover every segment
99+in it. A failed compaction retries after 30 seconds, backing off to at most 300
100+seconds.
153101
154-The compactor reads retained bundles when a cell's segments leave the
155-in-memory index. A failed compaction retries after 30 seconds, and repeated
156-failures increase the delay to a maximum of 300 seconds. The bundle collector
157-advances through retained objects and deletes a bundle only when the per-cell
158-prefixes cover every segment in that bundle.
159-
160-The prefix protects the new owner's data from stale writes. The next
161-two sections protect the durability promise.
162-
163102 ### The acknowledgement rule (RPO=0)
164103
165-A gate holds each write response until a durability proof covers the
166-write. A read-only response waits in the same way when the object has
167-committed a write that no proof covers yet. An error answer waits under
168-the same rule, because the message of a handler that throws can carry a
169-value that the handler read. An R2 mutation waits for the source object's write
170-proof. Therefore, the mutation cannot change the application bucket before the
171-source write is durable. A raw TCP connection, write, TLS upgrade, or shutdown
172-waits for the same proof. A response body that streams gets the same rule for
173-each chunk, so a chunk that an object produces after the response head waits
174-for a proof of the writes it can reveal. A client therefore cannot act on a
175-value that a crash can still lose. After a
176-bucket proof, celld reads the ownership record once and acknowledges
177-only if the record still names this node at this epoch. A partitioned
178-node can commit locally and replicate into its superseded prefix, but
179-the ownership read then shows the new owner, so celld does not
180-acknowledge the write. The check reads the record instead of comparing a
181-clock, so a paused process or a skewed clock cannot pass it.
104+A gate holds each response until a durability proof covers every write it can
105+reveal: a write response; a read-only response when the object has an uncovered
106+committed write; an error response, because a thrown message can carry a value
107+the handler read; an R2 mutation, so it cannot change the application bucket
108+before the source write is durable; a raw TCP connect, write, TLS upgrade, or
109+shutdown; and each chunk of a streamed body. A client therefore cannot act on a
110+value that a crash can still lose.
182111
183-A fleet proof does not require this read. The owner sends each write to
184-one or two other nodes, which hold a copy of its recent writes; those
185-nodes are its followers, and the set of them is the ensemble. Every
186-follower must fsync the write, and a takeover seals the prior node-log
187-session before it restores, so the stale owner cannot complete another
188-fleet proof.
112+After a bucket proof, celld reads the ownership record once and acknowledges
113+only if it still names this node at this epoch. A partitioned node can commit
114+locally and replicate into its superseded prefix, but it does not acknowledge.
115+The check reads the record instead of a clock, so a paused process or a skewed
116+clock cannot pass it.
189117
190-An unfinished SQL write cursor can return rows before SQLite commits the
191-write. Outside an explicit transaction, the application must consume those
192-rows before output or `storage.sync()`, so the gate can cover the commit.
193-celld rejects that output while the write cursor remains unfinished.
118+A fleet proof needs no such read. The owner sends each write to one or two other
119+nodes, its followers (together, the ensemble), and every follower must fsync it.
120+A takeover seals the prior node-log session before it restores, so a stale owner
121+cannot complete another fleet proof.
194122
123+An unfinished SQL write cursor can return rows before SQLite commits. Outside an
124+explicit transaction, the application must consume those rows before output or
125+`storage.sync()`; celld rejects output while a write cursor is unfinished.
126+
195127 ### The ensemble needs two nodes
196128
197-A node picks its followers from the other nodes in the fleet, so it never
198-counts itself. One follower is enough, therefore a fleet needs two
199-running celld nodes before any node can complete a fleet proof.
200-`CELLD_DURABILITY=fleet` is the default, so a fleet of one node requests the
129+A node never counts itself as a follower, and one follower is enough, therefore
130+a fleet needs two running celld nodes before any node can complete a fleet
131+proof. `CELLD_DURABILITY=fleet` is the default, so a one-node fleet requests the
201132 fleet posture and does not get it.
202133
203134 A node recruits up to two followers, so a fleet of three or more nodes holds
204135 three copies of an acknowledged write. The ensemble keeps acknowledging while
205-one follower remains, therefore a fleet does not fall back to the bucket each
206-time it loses a follower.
136+one follower remains. A node with one follower recruits a second one when
137+another node becomes available. Until then, a write that is not yet in the
138+bucket is only on the owner and on that one follower.
207139
208-A node without an ensemble stays correct. It acknowledges each write on a
209-bucket proof instead, so celld still does not acknowledge a write before a
210-durability proof covers it. The cost is latency: the write waits for the object
211-store, and an object store round trip is much slower than a follower fsync.
140+A node without an ensemble stays correct. It acknowledges each write on a bucket
141+proof instead, at the cost of latency: an object store round trip is much slower
142+than a follower fsync.
212143
213144 ### The takeover recovery gate
214145
215-The default fleet mode can acknowledge a write once the node-log
216-ensemble stores it; the bucket upload can complete later. Each process
217-session therefore creates a conditional node-log record before its
146+In fleet mode, celld can acknowledge a write before its bucket upload completes.
147+Each process session therefore creates a conditional node-log record before its
218148 first fleet-durable acknowledgement.
219149
220-A cold activation checks the prior owner's log records before it reads
221-the bucket. An absent record proves that the session never acknowledged
222-past the bucket, and a sealed record proves that recovery completed. An
223-open or recovering record makes the activation run recovery: it fences
224-the record with a compare-and-swap, seals the reachable followers,
225-uploads their retained segments and bundles into the per-cell prefixes,
226-and then marks the record sealed. The activation cannot restore until
227-this sequence completes.
150+A cold activation checks the prior owner's log records before it reads the
151+bucket. An absent record proves that the session never acknowledged past the
152+bucket; a sealed record proves that recovery completed. An open or recovering
153+record forces recovery before the restore: compare-and-swap the record to fence
154+it, seal the reachable followers, upload their retained segments and bundles
155+into the per-cell prefixes, and mark the record sealed.
228156
229-A cell can stop while its node session stays open. If acknowledged writes
230-remain outside its per-cell prefix, its next activation gathers that tail.
231-The log epoch becomes active before its first fleet proof. An active epoch
232-requires at least one current follower to return its complete retained range.
233-A fleet acknowledgement requires every ensemble member to store the write,
234-so one complete follower tail can provide the recovery evidence. If no
235-follower proves completeness, the activation fails and keeps the recovery
236-requirement. An inactive epoch has issued no fleet proof, so its bucket
237-bundles can provide the recovery data. When a stopped cell has a recorded
238-recovery requirement, the node keeps the log epoch until a bucket proof
239-covers its acknowledged data. A staged upload can complete after the cell
240-stops, so its bucket proof permits an ensemble change without another
241-activation. The next activation still folds any tail outside the per-cell
242-prefix.
157+A cell can stop while its node session stays open; its next activation gathers
158+any acknowledged tail outside its per-cell prefix. Once the log epoch is
159+active (before its first fleet proof), at least one current follower must
160+return its complete retained range, or the activation fails and keeps the
161+recovery requirement.
243162
244-A follower restart retains evidence of a damaged batch or a gap before a
245-later batch. The follower cannot certify the affected range until valid data
246-covers the gap. A directory read error fails the request and permits a retry.
247-The error does not become permanent evidence of a gap. A follower's HTTP
248-error does not prove that its data is absent, even when its lease has expired.
249-When no follower can return a complete tail, persistent response errors
250-can block recovery and startup. This check cannot detect a deleted final
251-batch if no later batch or persisted end records its range.
163+Recovery has these limits:
252164
253-A torn batch can contain an unacknowledged write. Recovery cannot distinguish
254-that case from damage after an acknowledgement. Therefore, the existing loss
255-record can report an uncertified range even when no acknowledged write is
256-missing.
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.
257176
258-The `/peer/log/tail` endpoint selects its response through the request's
259-`tail_format` field. A missing field or the value `1` selects the older
260-entries-only format, `CLT1`. The value `2` selects the ranged format, `CLT2`,
261-and another value fails the request. An older caller gets an HTTP error
262-when the follower cannot certify a known fragment, so an incomplete tail
263-cannot become a successful entries-only response.
264-
265-New nodes request the ranged format and decode both response formats. An
266-entries-only response provides no range evidence, so recovery treats that
267-response as inconclusive. It proves neither completeness nor data loss.
268-A recovery that requires a follower witness waits until a current member
269-returns the necessary range evidence. Therefore, response compatibility does
270-not guarantee uninterrupted recovery or startup during a mixed-version update.
271-Old nodes retain their existing recovery checks.
272-
273177 A restarting node serves authenticated follower seal and tail requests before
274-it completes its own predecessor recovery. Therefore, nodes that restart
275-together can recover acknowledged writes from their surviving follower disks.
276-The node accepts application requests and new follower appends only after
277-startup completes.
178+its own predecessor recovery completes, so nodes that restart together can
179+recover acknowledged writes from surviving follower disks. It accepts
180+application requests and new follower appends only after startup completes.
278181
279-A large dead node can hold this recovery open for minutes. The recovery
280-reads the retained bundles in windows of at most 512 MiB. It uploads the
281-rows of one window and releases them before it reads the next window, so
282-the memory of the recovery does not grow with the size of the session. A
283-cell that has rows in several windows receives one object for each window.
284-A recovery attempt that fails or times out does not fail the waiting
285-requests.
286-The cell waits, and it retries the activation with a backoff
287-(`CELLD_RECOVERY_RETRY_MS`, default 1000). The requests fail with a
288-resolve error only after the retry budget is spent
289-(`CELLD_RECOVERY_RETRIES`, default 240).
182+Recovery of a large dead node can take minutes. It reads retained bundles in
183+windows of at most 512 MiB and uploads and releases each window before the next,
184+so memory does not grow with the session; a cell with rows in several windows
185+receives one object per window. A failed or timed-out attempt does not fail
186+waiting requests: the cell retries with a backoff (`CELLD_RECOVERY_RETRY_MS`,
187+default 1000), and the requests fail with a resolve error only after
188+`CELLD_RECOVERY_RETRIES` (default 240) attempts.
290189
291190 ### Epoch-chain restore
292191
293-A restore composes the epoch prefixes that contain LTX data into one
294-chain. It starts at the newest prefix and walks down. An epoch that
295-opened with a whole-database snapshot starts the chain at transaction
296-one. An epoch that paged in continues its predecessor: its prefix holds a
297-marker object at the successor of the cut it paged from, and then its own
298-deltas, so the chain links the predecessor up to that cut and the epoch
299-from the cut onward. A link must end exactly at its successor's cut, so an
300-epoch that does not continue the chain is not part of it. celld no longer
301-writes an epoch seal object, and a legacy `e<epoch>.seal.json` object does
302-not limit the chain.
192+A restore chains the epoch prefixes that contain LTX data, from the newest down
193+to an epoch that opened with a whole-database snapshot. An epoch that paged in
194+continues its predecessor from the cut it paged from, and a predecessor that
195+does 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.
303197
198+A paged cell reads no chain up front. It opens over a sparse local file, reads
199+each page from the objects on first use, and fills the rest in the background; a
200+filled cell reads only its local file. A chain smaller than
201+`CELLD_LTX_PAGED_MIN_MB` is downloaded whole.
202+
304203 ### Epoch GC
305204
306-When `CELLD_LTX_RETENTION_SECS` has a positive value on a fleet node, the
307-owner of a cell deletes the epoch prefixes that no restore reads. The
308-owner builds the restore chain over every epoch prefix of the cell,
309-including its own. It continues only
310-when the newest epoch of the chain is its own epoch. Then its own first
311-object is in the listing, so a node that takes the cell over later also
312-lists that object and restores from a base at the same epoch or higher.
313-A paged cell also waits until its local file is complete, because until
314-then it reads pages from the objects of the chain that it restored. Next,
315-the owner reads the ownership record and continues only when the record
316-names this node at this epoch. It writes `retired.json` with the
317-base, and then it deletes the prefixes below the base. It keeps its own
318-epoch, the epoch before it, and each epoch younger than the configured
319-time.
205+When `CELLD_LTX_RETENTION_SECS` is positive, the owner of a cell deletes the
206+epoch prefixes that no restore reads, in both `CELLD_DURABILITY` modes:
320207
321-The order of these steps protects the data. If the owner reads the
322-ownership record before its own first object is in the listing, a fenced
323-owner can delete the base of the node that took the cell over. A
324-conditional write to the ownership record does not add protection,
325-because the cell can move between any check and the delete. The late
326-delete is safe because an epoch below the base never becomes part of a
327-chain again. This argument needs list-after-write consistency.
208+1. 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.
211+2. A paged cell waits until its local file is complete.
212+3. It continues only when the ownership record names this node at this epoch.
213+4. 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.
328216
329-A fenced node can append an unacknowledged tail to an older prefix. When
330-a successor opened with a whole-database snapshot, a later restore reads
331-the full chain and can expose that tail. This does not violate the
332-contract, because a failed or absent acknowledgement does not prove that
333-the write is absent, and a node-log recovery or a bundle drain can add an
334-acknowledged tail after an earlier restore. When a successor paged in, the
335-chain clips the older prefix at the successor's cut. This is safe because
336-the takeover recovery gate seals the prior node-log session before the
337-successor restores, so no write past the cut can be acknowledged.
217+The order matters: otherwise a fenced owner could delete its successor's base.
218+A late delete is safe because an epoch below the base never rejoins a chain.
219+This relies on list-after-write consistency.
338220
339-A paged cell's restore reads no chain up front. The cell opens over a
340-sparse local file, and each page the cell touches is read from the
341-objects on first use. The node then fills the rest of the file in the
342-background, and a filled cell reads only its local file. A chain smaller
343-than `CELLD_LTX_PAGED_MIN_MB` is downloaded whole, as before.
221+A fenced node can append an unacknowledged tail to an older prefix. After a
222+snapshot successor, a later restore can expose that tail; this does not violate
223+the contract, because a missing acknowledgement does not prove a write absent.
224+After a paged successor, the chain clips the older prefix at the cut, and the
225+takeover recovery gate seals the prior node-log session before the successor
226+restores, so no write past the cut can be acknowledged.
344227
345228 ### Self-fencing
346229
347-Each node holds a lease in the bucket. The lease carries an expiry, and
348-the node renews it after one third of the lifetime (`CELLD_TTL_MS`,
349-default 10000 ms). A renewal that does not reach the bucket does not
350-fence the node, because the node retries while the published expiry has
351-not passed.
230+Each node holds a lease in the bucket with an expiry, renewed after one third of
231+the lifetime (`CELLD_TTL_MS`, default 10000 ms). A failed renewal is retried
232+while the published expiry has not passed.
352233
353-A node that cannot reach the bucket cannot renew and cannot replicate,
354-so it must not own cells. When its published expiry passes, it fences
355-itself: it stops each active cell, and it fails every request that it
356-has not completed. A node also fences at once when its lease record is
357-gone, or no longer matches the record that the node published, because
358-the node can no longer prove that it holds the authority.
234+When the expiry passes, the node fences itself: it stops each active cell and
235+fails every incomplete request. It also fences at once when its lease record is
236+gone or no longer matches what it published. The fence writes nothing; peers
237+already read the lease as dead or replaced and acquire the cells through the
238+ownership records. celld checks the published expiry on every routed request,
239+so a request is safe even before the fence runs.
359240
360-The fence writes nothing to the bucket. Each peer already reads the
361-lease as dead or replaced, so a peer can acquire the cells through the
362-ownership records. And a request is safe even before the fence runs,
363-because celld compares the current time against the published expiry
364-each time it routes a request.
241+An ingress checks a cached remote route against the observed lease deadline on
242+each new request and rereads ownership at the deadline, even if the old owner
243+holds connections open. Recovery still needs the bucket and the required durable
244+data. A draining ingress can forward to a live remote owner but refuses new
245+ownership of an unowned cell or one with an expired owner. The ingress does not
246+replay a request already sent to the old owner, because the handler can have
247+committed a write; the caller can cancel it.
365248
366-An ingress checks a cached remote route against its observed lease deadline
367-for each new request. At the deadline, the ingress reads ownership again,
368-even if the previous owner keeps its connections open without a response.
369-Recovery still needs the bucket and the required durable data.
370-A draining ingress can resolve and forward to a live remote owner. It
371-refuses new ownership of an unowned cell or a cell with an expired owner.
249+A fenced node logs a line starting with `SELF-FENCE:` and exits with code 3.
250+Other 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
253+cannot prove who wrote the record). The fenced state is terminal: only a restart
254+returns the node, through the normal cold-activation path. The
255+[testing page](testing.md) shows the kill tests for this path.
372256
373-A request already sent to the previous owner can remain incomplete. The
374-ingress does not replay that request, because the handler can have committed
375-a write before it stopped. The caller can cancel the request.
257+`RUST_LOG=celld=info,store=debug` logs a `node_lease_read` or `node_lease_write`
258+event for each store request against the node's own lease record, with an
259+`outcome` of `found`, `missing`, `applied`, `rejected`, or `error`. An `error`
260+carries the store failure in an `error` field; a `found` carries the record's
261+`generation`. The target costs nothing at other filters.
376262
377-A fenced node logs a line that starts with `SELF-FENCE:` and stops with
378-the exit code 3. celld reports other internal failures with the same
379-prefix and code, so the line names the cause. An expired lease uses the
380-`node_lease_watchdog_fence` event. A missing record uses the
381-`node_lease_record_missing_fence` event, and a record that no longer
382-matches the node uses the `node_lease_record_mismatch_fence` event. The
383-mismatch event does not name an author, because the node cannot prove
384-which writer wrote that record. The fenced state is terminal:
385-only a restart returns the node to the fleet, through the same
386-cold-activation path that a peer failure uses.
387-
388-The fence line names the lease state, and it cannot name the store
389-request that produced that state. A removed record, a replaced record
390-and a failed read are three different operator problems, so celld can
391-report each lease request on its own. Set
392-`RUST_LOG=celld=info,store=debug` to turn this on. The node then logs a
393-`node_lease_read` event and a `node_lease_write` event for each request
394-against its own lease record. Each event carries an `outcome` field:
395-`found`, `missing`, `applied`, `rejected` or `error`. An `error`
396-outcome carries the store failure in an `error` field, and a `found`
397-outcome carries the `generation` field of the record that came back.
398-The target is off at every other filter, so a node in production pays
399-nothing for it.
400-
401-The failure of a node is a normal input, not a recovery procedure; the
402-[testing page](testing.md) shows the kill tests that exercise this
403-path.
404-
405263 ## Alarm discovery and the wake format
406264
407265 SQLite stores the alarm deadline, consumption, retry state, and installation
408-identity. An alarm hint only causes celld to read SQLite. The hint does not
409-authorize an alarm handler to run.
266+identity. An alarm hint only makes celld read SQLite; it never authorizes a
267+handler to run.
410268
411-Each committed alarm installation has a separate object under `wake/entries/`.
412-The ownership epoch and a persistent SQLite sequence identify the installation.
413-An alarm response waits for its publication PUT and the existing output proof.
414-Updates within the same minute also require a new publication PUT.
269+Each committed installation has an object under `wake/entries/`, identified by
270+the ownership epoch and a persistent SQLite sequence. An alarm response waits
271+for its publication PUT and the output proof; an update within the same minute
272+also needs a new PUT.
415273
416-Cleanup uses conditional writes to publish a retirement record under
417-`wake/retired/`. The record requires a durability proof, a current owner,
418-and a confirmed replacement publication when an alarm remains armed.
419-Cleanup deletes only older identities or a proven consumed identity.
420-An old DELETE therefore cannot delete a later installation.
421-This protocol requires no conditional DELETE operation from the bucket.
422-After the proof, celld attempts to delete known obsolete publications directly.
423-These deletions do not block an alarm response.
274+Cleanup publishes a retirement record under `wake/retired/` with conditional
275+writes. The record needs a durability proof, a current owner, and, if an alarm
276+remains armed, a confirmed replacement publication. Cleanup deletes only older
277+identities or a proven consumed one, so an old DELETE cannot remove a later
278+installation and the bucket needs no conditional DELETE. Deletes of obsolete
279+publications do not block an alarm response.
424280
425281 Each cleanup pass lists at most 128 objects and processes at most eight cells
426-concurrently. The next pass continues the listing, and the final page restarts
427-the scan. A failed DELETE or a late PUT can require another complete scan.
428-The default interval is 60 seconds. `CELLD_WAKER_TICK_MS` changes this interval
429-and the due-scan interval. A large inventory can require many intervals, and
430-an additional node can repeat the same reads and deletes.
431-The collector requests a SQLite refresh for a remaining installation only when
432-its minute is due. Future installations stay dormant until that minute.
433-The timer still controls delivery, so the refresh cannot run the handler early.
282+concurrently, continuing the listing on the next pass and restarting after the
283+last page. A failed DELETE or a late PUT can need another full scan. The
284+interval defaults to 60 seconds; `CELLD_WAKER_TICK_MS` sets it and the due-scan
285+interval. A large inventory can take many intervals, and each extra node can
286+repeat the same reads and deletes.
434287
435-The `wake/format.json` object selects format 2. The `wake/waker.json` object
436-holds the advisory lease for the fleet's waker role. A new node or deployment
437-initializes an empty fleet or upgrades a stopped v0.4.1 fleet automatically.
438-An unsupported format prevents startup. Existing application objects outside
439-the reserved namespaces do not prevent initialization.
440-The previous `wake-format.json`, `wake-v2/`, and `wake-retired-v2/` names
441-also identify unsupported engine data and prevent fresh initialization.
288+`wake/format.json` selects format 2; `wake/waker.json` holds the advisory lease
289+for the waker role. A new node initializes an empty fleet or upgrades a stopped
290+v0.4.1 fleet automatically. An unsupported format, or the old
291+`wake-format.json`, `wake-v2/`, or `wake-retired-v2/` names, prevents startup.
292+Application objects outside the reserved namespaces do not.
442293
443294 ### Start a fleet with this format
444295
445296 An empty fleet initializes this format automatically. An upgrade from v0.4.1
446-uses the same bucket and preserves the existing node data directories.
447-The upgrade requires a stopped fleet. Mixed versions cannot share a serving
448-fleet because v0.4.1 cannot read the new alarm discovery entries.
297+keeps the bucket and node data directories but needs a stopped fleet, because
298+v0.4.1 cannot read the new discovery entries.
449299
450-1. Stop application traffic and deployment writers. Stop every old node and
451- its supervisor, then wait for every node lease to expire.
452-2. Back up the stopped fleet's bucket and node data. Keep the node names,
453- peer addresses, and data directories for the restart. A follower disk can
454- contain acknowledged writes that the bucket does not yet contain.
455-3. Prevent the old binaries from restarting or writing to the bucket.
456- Revoke their credentials or remove their access through the deployment
457- system. The format marker cannot stop an old binary from writing.
300+1. Stop application traffic and deployment writers. Stop every old node and its
301+ supervisor, then wait for every node lease to expire.
302+2. 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.
305+3. Prevent the old binaries from restarting or writing to the bucket: revoke
306+ their credentials or access. The format marker cannot stop them.
458307 4. Start the new binary on every node with the same configuration, data, and
459- addresses. Wait for the fleet to become healthy before resuming traffic.
308+ addresses. Wait for the fleet to become healthy, then resume traffic.
460309
461-Startup upgrades the format automatically. The nodes can start together and
462-complete the same migration. A live node lease prevents the migration, so
463-stop every old writer and wait for its lease to expire before the restart.
464-The operator must prevent old writers from returning after the upgrade.
310+The nodes can start together. A live node lease blocks the migration, and the
311+operator must keep old writers from returning.
465312
466-The migration inventories stored cells and creates a discovery seed for each
467-cell. It preserves the databases, node logs, ownership records, deployments,
468-and application objects. Existing legacy wake entries remain unused.
469-The inventory uses pages of at most 128 entries and includes cells whose
470-old alarm discovery entry is missing.
313+The migration preserves databases, node logs, ownership records, deployments,
314+and application objects. It creates a discovery seed for each stored cell, in
315+pages of at most 128 entries. A seed makes recovery derive the installation
316+identity from SQLite without changing the deadline or retry state, and it is
317+removed only after durable recovery, so an interrupted migration cannot discard
318+an alarm. Recovery can load cells with future alarms while it processes seeds.
471319
472-A discovery seed makes recovery read the cell's SQLite alarm state. Recovery
473-creates the installation identity without changing the deadline or retry
474-state. A seed does not authorize an alarm handler to run. The normal
475-retirement proof removes the seed after durable recovery and replacement
476-discovery, so an interrupted migration cannot silently discard an alarm.
477-Recovery can load cells with future alarms while it processes these seeds.
320+If a node stops mid-migration, another starting node resumes it. No node serves
321+until the full inventory succeeds, so alarms can run late. Later starts do not
322+migrate again.
478323
479-If a node stops during the migration, another starting node resumes it.
480-The nodes cannot serve until the complete inventory succeeds. Later starts
481-use the completed format without another migration. Alarms can run late
482-during the outage.
324+To roll back, restore the full stopped-fleet backup; never start an old binary
325+against the upgraded fleet. The restore loses writes made after the backup, so
326+preserve those separately.
483327
484-Do not roll back by starting an old binary against the upgraded fleet.
485-Restore the complete stopped-fleet backup for a rollback. That restoration
486-loses writes made after the backup, so preserve those writes separately.
487-
488-Normal restarts and ownership transfers within this format preserve the
489-alarm history. Each restored writer takes a new ownership epoch and keeps
490-the stored sequence and consumed state, so an old mutation cannot target
491-a later installation.
328+Restarts and ownership transfers preserve alarm history. Each restored writer
329+takes a new epoch and keeps the stored sequence and consumed state, so an old
330+mutation cannot target a later installation.
modifieddocs/limitations.md+18−22View file
@@ -1,6 +1,6 @@
11 # Limitations
22
3-celld v0.6.1 is a beta release. The release has these operational limits. See
3+celld v0.6.2 is a beta release with these operational limits. See
44 [Cloudflare compatibility](cloudflare-compat.md) for the supported services,
55 APIs, and Wrangler configuration.
66
@@ -9,42 +9,38 @@
99 - A fleet runs one application. celld has no account service, multi-tenant
1010 scheduler, or managed ingress.
1111 - A fleet stores its durable state in an S3-compatible bucket, a Google Cloud
12- Storage bucket, or an Azure Blob Storage container. The `celld dev` command
13- instead uses a local SQLite object store. A regular node or an operator
14- subcommand cannot select this local backend.
15-- Ownership balancing counts cells by node weight. It does not measure the
16- CPU or memory that one cell uses, and it moves only hibernated cells, so a
17- fleet without idle eviction balances only the cells that hibernate on
18- their own.
12+ Storage bucket, or an Azure Blob Storage container. Only `celld dev` can use
13+ the local SQLite object store.
14+- Ownership balancing counts cells by node weight, not by CPU or memory use.
15+ It moves only hibernated cells, so a fleet without idle eviction balances
16+ only the cells that hibernate on their own.
1917
2018 ## Networking and security
2119
2220 - celld does not terminate TLS. Terminate public TLS at an ingress proxy, and
2321 put the internal listener on a private network or an encrypted overlay.
24-- Peer traffic crosses the internal network as plaintext HTTP. The fleet HMAC
25- authenticates tunnel establishment and control requests, and it does not
26- encrypt application data on the wire. The network layer must provide the
27- confidentiality.
22+- Peer traffic is plaintext HTTP. The fleet HMAC authenticates tunnel
23+ establishment and control requests but does not encrypt data, so the network
24+ must provide confidentiality.
2825 - The fleet bucket controls the fleet. Give its credentials access to one fleet
2926 only. See [Security](security.md).
3027
3128 ## Object storage credentials
3229
33-- celld supports different credential methods for each object storage provider.
34- See [Configure object storage](README.md#configure-object-storage) for the
35- available methods and their precedence.
36-- Azure identity support is limited to the public Azure cloud. A managed
37- identity from Azure App Service or Azure Container Apps does not work. Use a
38- workload identity or a storage account key on these platforms.
30+- The credential methods differ by provider. See
31+ [Configure object storage](README.md#configure-object-storage).
32+- Azure identity works only in the public Azure cloud. A managed identity from
33+ Azure App Service or Azure Container Apps does not work. Use a workload
34+ identity or a storage account key there.
3935
4036 ## WebSockets
4137
42-- An outbound Durable Object WebSocket keeps its cell resident. The connection
43- closes if the cell moves to another node, so the application must store the
38+- An outbound Durable Object WebSocket keeps its cell resident. It closes when
39+ the cell moves to another node, so the application must store the
4440 connection intent and reconnect.
45-- A node limits the cells and outbound WebSockets that can remain resident.
41+- A node limits the resident cells and outbound WebSockets.
4642
47-## Platforms and updates
43+## Platforms
4844
4945 - The installer supplies binaries for Linux x86-64, Linux ARM64, and Apple
5046 Silicon. Windows is not supported.
modifieddocs/security.md+85−150View file
@@ -1,155 +1,101 @@
11 # Security
22
3-celld v0.6.1 is a beta release. It is not safe for hostile multi-tenant use.
4-Security fixes apply to the latest release only, so older beta releases do not
5-receive fixes.
3+celld v0.6.2 is a beta release. It is not safe for hostile multi-tenant use.
4+Only the latest release receives security fixes.
65
76 ## Security boundary
87
9-One fleet runs one application, and celld trusts the application code, the fleet
8+One fleet runs one application. celld trusts the application code, the fleet
109 nodes, and the operators. Application code can use its configured bindings and
1110 can consume shared node resources. Do not run code from mutually distrusting
1211 tenants in one fleet.
1312
14-The engine's host functions are not reachable from application code. An
15-internal script receives them as function parameters, so a bundle cannot name
16-a host function, and `globalThis` carries no `__`-prefixed property. A worker
17-that the Worker Loader loads with `globalOutbound: null` therefore reaches the
18-host only through the capabilities in its `env`.
13+Application code cannot reach the engine's host functions. An internal script
14+receives them as function parameters, and `globalThis` carries no
15+`__`-prefixed property. A Worker Loader worker with `globalOutbound: null`
16+therefore reaches the host only through the capabilities in its `env`.
1917
20-celld depends on two external security boundaries:
18+celld depends on two external boundaries: a trusted private network protects
19+the internal listener, and object storage credentials control the fleet.
2120
22-- A trusted private network protects the internal listener. Use an encrypted
23- overlay when the private network does not provide confidentiality.
24-- Object storage credentials control the fleet. Give each credential access to
25- one fleet bucket only.
26-
2721 ## Separate the listeners
2822
29-celld opens two HTTP listeners. The public listener serves the deployed Worker,
30-and the internal listener serves the peer protocol and the operator API.
23+celld opens two HTTP listeners and terminates TLS on neither.
3124
32-Use `--listen` for the public listener. Expose this listener through a load
33-balancer, a reverse proxy, or a public firewall rule.
25+| Listener | Serves | Required protection |
26+| --- | --- | --- |
27+| `--listen` (public) | The deployed Worker | Terminate TLS and authenticate users in a proxy or the application. |
28+| `--internal-listen` (default `127.0.0.1:0`, a free loopback port) | The peer protocol and the operator API | Restrict access to trusted operators and fleet nodes. Never expose it to the public internet. Use an encrypted overlay such as WireGuard or Tailscale when the network does not provide confidentiality. |
3429
35-Use `--internal-listen` for the internal listener. Its default address is
36-`127.0.0.1:0`, so celld selects an available loopback port at each start. Use
37-`--advertise` to give peers an address that reaches this listener.
30+`--advertise` gives peers the internal address. celld rejects an explicit
31+`--advertise` or a non-loopback `--listen` without an explicit
32+`--internal-listen`. celld cannot verify a hostname or a translated port, so
33+you must route the advertised address to the internal listener.
3834
39-An explicit advertised address requires an explicit internal-listener address.
40-celld also rejects an explicit non-loopback public listener without an explicit
41-internal listener. These checks prevent an obsolete one-listener configuration.
35+The public listener reserves only `/.well-known/celld/health`: 200 with
36+`{"ok":true}` when healthy, 503 otherwise. The Worker owns every other public
37+path, including `/health`. The internal listener returns 404 for an unknown
38+path, so an operator request cannot become an application request.
4239
43-celld cannot verify a hostname or a translated port. You must route the
44-advertised address to the internal listener, and you must not route it to the
45-public listener.
40+The internal listener has three request groups, and all three require the
41+trusted private network:
4642
47-The public listener reserves only `/.well-known/celld/health`. A healthy node
48-returns a 200 response with `{"ok":true}`, and an unhealthy node returns a 503
49-response. The deployed Worker owns `/health` and every other public path.
43+- Most operator routes have no request authentication.
44+- `/peer/tunnel` opens a tunnel for cell fetch, RPC, and WebSocket calls. The
45+ establishment request carries the fleet HMAC, a clock limit, and replay
46+ protection. The calls inside the tunnel are plain, unsigned HTTP.
47+- The peer-control and reserved-cell routes sign each request with the fleet
48+ HMAC, a clock limit, and replay protection.
5049
51-The internal listener does not pass an unknown path to the Worker. It returns a
52-404 response, so an operator request cannot become an application request.
50+Every path to a runtime class therefore demands the fleet secret. The HMAC
51+does not authenticate tunnel bytes after establishment and does not encrypt
52+traffic, so it does not replace the private network.
5353
54-## Protect each surface
55-
56-| Surface | Required protection |
57-| --- | --- |
58-| The public listener | Terminate TLS and authenticate users in a proxy or the application. |
59-| The internal listener | Restrict access to trusted operators and fleet nodes. Use an encrypted overlay when the private network does not provide confidentiality. |
60-| The fleet bucket | Restrict the credentials to one fleet bucket. |
61-
62-The internal listener has three request groups:
63-
64-- Most operator routes let an operator inspect or control a node without
65- request authentication.
66-- The `/peer/tunnel` route establishes a tunnel for cell fetch, RPC, and
67- WebSocket calls. The establishment request carries the fleet HMAC, a clock
68- limit, and replay protection, so only a holder of the fleet secret can open
69- a tunnel. Each call then crosses inside the tunnel as plain HTTP with the
70- cell scope in a reserved header, and these inner calls are not signed.
71-- The peer-control routes coordinate fleet nodes, and the reserved-cell routes
72- access runtime state. These routes use the fleet HMAC for request
73- authentication, a clock limit, and replay protection.
74-
75-All three groups require the trusted private network.
76-
77-The tunnel permits a request body to stream to the owner, so the fleet HMAC
78-cannot sign an individual call. The establishment signature decides who can
79-open a tunnel, and a tunneled call can address an application class or a
80-runtime class, so every path to a runtime class demands the fleet secret.
81-The signature does not authenticate the bytes after the establishment, and
82-it does not encrypt any traffic. The private network must therefore stay
83-trusted, and the fleet HMAC does not replace this network boundary.
84-
85-celld does not terminate TLS on either listener. Do not expose the internal
86-listener to the public internet. Use an encrypted overlay such as WireGuard or
87-Tailscale when the network does not provide the required confidentiality.
88-
8954 ## Use the internal operator API
9055
91-The internal operator API is available in the released binary. It is an alpha
92-interface, so a release can change its paths or response formats.
56+The operator API is an alpha interface. A release can change its paths or
57+response formats. These routes do not authenticate the caller:
9358
94-These routes do not authenticate the caller:
95-
9659 - `/state` reports node state.
9760 - `/cell/<SCOPE>` resolves or activates a cell.
9861 - `/evict/<SCOPE>` tries to evict a resident cell and reports the result.
9962 - `/do/<ID>` sends a direct request to an ordinary Durable Object.
100-- `POST /shutdown` starts a graceful ownership handoff. The
101- `handoff=preserve` query prepares a same-node reload.
63+- `POST /shutdown` starts a graceful ownership handoff. `handoff=preserve`
64+ prepares a same-node reload.
10265
103-The `/do/<ID>` route refuses every reserved runtime class. These classes include
104-D1, Workflows, KV, and Queues. Their operator protocols can access application
105-data or change runtime state, so they use the HMAC-authenticated
106-`/runtime/<SCOPE>` route.
66+`/do/<ID>` refuses every reserved runtime class, such as D1, Workflows, KV,
67+and Queues, because their protocols can access application data. Use the
68+HMAC-authenticated `/runtime/<SCOPE>` route for these classes.
10769
108-`/peer/probe` returns a signed diagnostic response. The peer protocol also
109-uses other reserved internal paths. An operator must not call these paths
110-directly.
70+`/peer/probe` returns a signed diagnostic response. Do not call the other
71+reserved peer paths directly.
11172
11273 ### Read an eviction result
11374
114-The eviction request waits for the accepted operation to finish. A refused
115-request does not wait for an idle period or another lifecycle transition.
116-An accepted request can join an eviction that is already running, and each
117-waiting caller receives that operation's result.
75+An accepted eviction waits for the operation to finish, and a refused one
76+returns at once. Concurrent callers can join one eviction, so the success
77+count does not equal the stop count.
11878
11979 The Rust method `AppHandle::evict` returns `Result<EvictSuccess, EvictError>`.
120-The success value `Evicted` confirms that the awaited eviction completes its
121-runtime stop. The success value `AlreadyAbsent` confirms settled local absence
122-when the Actor handles the request. A caller that requires a completed eviction
123-must check for `Evicted`.
80+`Evicted` confirms a completed runtime stop, and `AlreadyAbsent` confirms
81+settled local absence. A caller that needs a completed eviction must check for
82+`Evicted`. Over HTTP, both return 200 with `{"ok":true}`. `kind()` and
83+`reason()` on the error match the HTTP error body. A later request can
84+reactivate the cell before the response arrives.
12485
125-Multiple callers can join one eviction and receive `Evicted`, so the successful
126-call count does not measure the runtime stop count.
127-The error distinguishes a refusal, a cancellation, and an execution failure.
128-The Rust error methods `kind()` and `reason()` return the `kind` and `reason`
129-strings of the HTTP error body.
86+A missing cell or a settled `Inactive`, `Dormant`, or `Remote` cell is locally
87+absent. A pending activation, stop, or ownership transfer prevents that
88+result. The request does not evict a remote runtime. A dormant cell keeps its
89+ownership and its hibernated host sockets. The node refuses during
90+preservation, reload, or local inventory confirmation, or when it lacks
91+authority.
13092
131-The response uses `application/json`. Both success values use status 200 with
132-`{"ok":true}`, so the HTTP response does not distinguish them.
133-It confirms a completed eviction or a settled local absence at the decision
134-point. A later request can reactivate the cell before the response arrives.
93+An error body has this form:
13594
136-A missing cell or a settled `Inactive`, `Dormant`, or `Remote` cell counts
137-as locally absent. A pending activation, stop, or ownership transfer prevents
138-that result. The request does not evict a remote runtime. A dormant cell
139-keeps its ownership and its hibernated host sockets.
140-
141-The node checks its availability before it reports local absence. The node
142-refuses an eviction during preservation, reload, or local inventory
143-confirmation, or when it lacks authority.
144-
145-Every eviction error has this structure:
146-
14795 ```json
14896 {"ok":false,"error":{"kind":"refused","reason":"cell_active"}}
14997 ```
15098
151-The `kind` and `reason` values have these meanings:
152-
15399 | Status | Kind | Reason | Cause |
154100 | --- | --- | --- | --- |
155101 | 409 | `refused` | `cell_active` | The cell has active work or a socket that requires a runtime. |
@@ -167,60 +113,49 @@
167113 | 500 | `failed` | `durability_timeout` | The durability verification exceeds its operation deadline. |
168114 | 500 | `failed` | `runtime_stop_failed` | The runtime stop reports a failure. |
169115
170-The runtime stop has no overall timeout. A stop that does not return keeps
171-the eviction request pending.
116+A malformed scope returns 400. An error does not prove that the runtime is
117+still resident. The runtime stop has no overall timeout, so a stop that never
118+returns keeps the request pending.
172119
173-An error does not prove that the runtime remains resident. A malformed scope
174-still returns status 400 through the existing scope validation.
175-
176120 ## Set the forwarded-header policy
177121
178122 celld ignores `X-Forwarded-Host` and `X-Forwarded-Proto` by default. Set
179123 `--trust-forwarded-headers` or `CELLD_TRUST_FORWARDED_HEADERS=1` only when a
180124 trusted proxy replaces both headers. celld uses the last value in each header,
181-so an earlier client value does not override the proxy value.
125+so an earlier client value cannot override the proxy value.
182126
183-celld always takes the path and query from the request target. It ignores the
184-scheme and authority in an absolute-form target, so a client cannot bypass the
185-host policy through the request line.
127+celld takes the path and query from the request target and ignores the scheme
128+and authority of an absolute-form target. Without a trusted proxy, the `Host`
129+header sets the hostname in `request.url`. celld accepts a hostname, an IPv4
130+address, or a bracketed IPv6 address, with an optional port. It rejects
131+malformed and noncanonical values and falls back to `celld.local`.
186132
187-Without a trusted proxy, the `Host` header controls the hostname in
188-`request.url`. celld accepts a hostname, an IPv4 address, or a bracketed IPv6
189-address, with an optional port. It rejects malformed and noncanonical values,
190-and it uses `celld.local` when no source gives a valid host.
191-
192-These checks keep the path and query valid, but they do not make the hostname
193-trustworthy. An application must not use an unchecked hostname for an
194-authorization decision. Use a trusted proxy or check the hostname against a
133+The hostname is still client-controlled. Do not use an unchecked hostname for
134+an authorization decision. Use a trusted proxy, or check the hostname against a
195135 list in the Worker.
196136
197137 ## Limit request bodies
198138
199-The public Worker listener and `/do/<ID>` have a 1 GiB request body limit by
200-default. Set `CELLD_MAX_REQUEST_BODY_BYTES` to a smaller positive value to
201-change the limit. celld returns status 413 for a declared oversized body and
202-when a Worker reads past the limit.
139+The public listener and `/do/<ID>` limit a request body to 1 GiB by default.
140+Set `CELLD_MAX_REQUEST_BODY_BYTES` to a smaller positive value to lower it.
141+celld returns 413 for a declared oversized body and when a Worker reads past
142+the limit.
203143
204-For a method other than `GET` or `HEAD`, `/do/<ID>` streams a body when its
205-declared length is at least 1 MiB or its length is unknown. celld collects each
206-smaller body before dispatch.
144+For a method other than `GET` or `HEAD`, `/do/<ID>` streams a body of unknown
145+length or of at least 1 MiB. It collects a smaller body before dispatch.
207146
208147 ## Protect the fleet bucket
209148
210-The fleet bucket is the root of authority for the fleet. It stores the
211-deployments, the cell state, the ownership leases, the node leases, and the
212-shared peer-authentication secret.
149+The fleet bucket is the root of authority. It stores the deployments, the cell
150+state, the ownership and node leases, and the shared peer-authentication
151+secret. A holder of the bucket credentials controls the fleet. Give each
152+credential access to one fleet bucket only, and rotate it after a suspected
153+disclosure.
213154
214-A person who holds the bucket credentials controls the fleet. Give each
215-credential access to one fleet bucket only, and replace a credential after a
216-suspected disclosure.
155+## Cell ownership
217156
218-## Understand cell ownership
219-
220-Each cell is a SQLite database with one writer. One node owns a cell at a time,
221-and an ownership epoch fences each cell. A node that loses its lease cannot
222-modify the current cell state.
223-
224-This fencing protects storage consistency, but it does not isolate hostile
225-applications. See [what celld guarantees](guarantees.md) for the storage protocol,
226-and see [limitations](limitations.md) for the complete beta boundary.
157+Each cell is a SQLite database with one writer. An ownership epoch fences each
158+cell, so a node that loses its lease cannot modify the current state. This
159+fencing protects storage consistency. It does not isolate hostile
160+applications. See [what celld guarantees](guarantees.md) and
161+[limitations](limitations.md).
deleteddocs/services/containers-flow.svg+0−97
@@ -1,97 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 478" role="img" aria-labelledby="containerFlowTitle containerFlowDesc">
2- <title id="containerFlowTitle">One node runs the cell and its container, behind a fence on the bridge</title>
3- <desc id="containerFlowDesc">A Worker on any node calls MY_CONTAINER.get(id), and celld routes the call to the node that owns the cell. The fleet bucket holds the image as deploy slash images slash key dot tar, and the node loads it into its container engine once. On that one owner node, two runtimes run side by side: a V8 isolate that holds the cell, the Durable Object, with ctx.container and getTcpPort(8080), and a container process with the image from the bucket, port 8080, and an ephemeral disk. The call crosses the node's container engine socket, which is a local socket and not the network. Below both runtimes, an nftables fence on the node's bridge allows a connection out to the Internet and blocks a connection to any node and to every private range. A move, a restart, or a reset destroys the container, and the new owner starts a fresh one, so the disk never survives.</desc>
4- <style>
5- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
6- text { font-size: 13px; fill: currentColor; }
7- tspan { fill: currentColor; }
8- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
9- .lead { font-weight: 600; }
10- .d-ink { color: #121212; }
11- .d-soft { color: #3d3b37; }
12- .d-faint { color: #6e6a62; }
13- .d-acc { color: #10803f; }
14- .d-panel { color: #ffffff; }
15- .d-sunk { color: #f0eee8; }
16- .d-tint { color: #d6efdf; }
17- @media (prefers-color-scheme: dark) {
18- .d-ink { color: #efede7; }
19- .d-soft { color: #c9c6be; }
20- .d-faint { color: #928e85; }
21- .d-acc { color: #3fc472; }
22- .d-panel { color: #1a1a19; }
23- .d-sunk { color: #232321; }
24- .d-tint { color: #10301d; }
25- }
26- </style>
27- <defs>
28- <marker id="ct-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
29- markerHeight="6" orient="auto-start-reverse">
30- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
31- </marker>
32- </defs>
33-
34- <!-- The caller, and the image the node needs before it can answer the caller. -->
35- <rect class="d-panel" fill="currentColor" x="8" y="8" width="196" height="54" rx="8" />
36- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="196" height="54" rx="8" />
37- <text class="d-faint" fill="currentColor" x="20" y="30">Worker, on any node</text>
38- <text class="d-ink mono" fill="currentColor" x="20" y="50">MY_CONTAINER.get(id)</text>
39-
40- <rect class="d-panel" fill="currentColor" x="236" y="8" width="196" height="54" rx="8" />
41- <rect class="d-faint" fill="none" stroke="currentColor" x="236" y="8" width="196" height="54" rx="8" />
42- <text class="d-faint" fill="currentColor" x="248" y="30">Fleet bucket, no registry</text>
43- <text class="d-ink mono" fill="currentColor" x="248" y="50">deploy/images/&lt;key&gt;.tar</text>
44-
45- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
46- <path d="M106 62 V108" marker-end="url(#ct-arrow)" />
47- <path d="M334 62 V108" marker-end="url(#ct-arrow)" />
48- </g>
49- <text class="d-faint" fill="currentColor" x="116" y="80">routed to the owner</text>
50- <text class="d-faint" fill="currentColor" x="324" y="100" text-anchor="end">loaded once per node</text>
51-
52- <!-- One node holds the cell and the container together. -->
53- <rect class="d-sunk" fill="currentColor" x="8" y="112" width="424" height="284" rx="12" />
54- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="112" width="424" height="284" rx="12" />
55- <text class="d-ink lead" fill="currentColor" x="24" y="138">Owner node</text>
56- <text class="d-faint" fill="currentColor" x="24" y="158">the cell and its container never separate</text>
57-
58- <text class="d-acc" fill="currentColor" x="220" y="176" text-anchor="middle">container engine socket</text>
59-
60- <rect class="d-panel" fill="currentColor" x="22" y="184" width="176" height="112" rx="8" />
61- <rect class="d-faint" fill="none" stroke="currentColor" x="22" y="184" width="176" height="112" rx="8" />
62- <text class="d-faint" fill="currentColor" x="34" y="206">V8 isolate</text>
63- <text class="d-ink" fill="currentColor" x="34" y="228">cell, a Durable Object</text>
64- <text class="d-acc mono" fill="currentColor" x="34" y="252">ctx.container</text>
65- <text class="d-soft mono" fill="currentColor" x="34" y="276">getTcpPort(8080)</text>
66-
67- <rect class="d-tint" fill="currentColor" x="242" y="184" width="176" height="112" rx="8" />
68- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="242" y="184" width="176" height="112" rx="8" />
69- <text class="d-faint" fill="currentColor" x="254" y="206">container process</text>
70- <text class="d-ink" fill="currentColor" x="254" y="228">the bucket's image</text>
71- <text class="d-soft mono" fill="currentColor" x="254" y="252">EXPOSE 8080</text>
72- <text class="d-soft" fill="currentColor" x="254" y="276">ephemeral disk</text>
73-
74- <path class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
75- d="M220 184 V296" />
76- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
77- <path d="M198 222 H238" marker-end="url(#ct-arrow)" />
78- <path d="M242 270 H202" marker-end="url(#ct-arrow)" />
79- </g>
80-
81- <!-- The fence is on the node, outside every container and every runtime. -->
82- <rect class="d-acc" fill="none" stroke="currentColor" stroke-dasharray="5 4"
83- x="22" y="310" width="396" height="70" rx="8" />
84- <text class="d-acc" fill="currentColor" x="34" y="332">nftables fence on the node's bridge</text>
85- <text class="d-soft" fill="currentColor" x="34" y="352">out to the Internet: allowed</text>
86- <text class="d-soft" fill="currentColor" x="34" y="372">to any node, to a private range: blocked</text>
87-
88- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
89- <path d="M220 396 V412" marker-end="url(#ct-arrow)" />
90- </g>
91-
92- <!-- The container belongs to one ownership epoch on one node. -->
93- <rect class="d-panel" fill="currentColor" x="8" y="418" width="424" height="56" rx="8" />
94- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="418" width="424" height="56" rx="8" />
95- <text class="d-ink" fill="currentColor" x="24" y="442">A move, a restart, or a reset destroys the container.</text>
96- <text class="d-faint" fill="currentColor" x="24" y="463">The new owner starts a fresh one; the disk never survives.</text>
97-</svg>
modifieddocs/services/containers.md+87−142View file
@@ -1,16 +1,13 @@
11 # Containers
22
33 A container runs a program that is not JavaScript beside the Worker that needs
4-it. A Durable Object supervises that program, so the object starts the
5-container, reaches it over a TCP port, and stops it. An application uses a
6-container for a language or a dependency that the Workers runtime does not
7-have, for a heavy computation, or for code that a customer supplies. The
8-container disk is ephemeral, therefore durable state belongs in the object's
9-storage or in another binding. Containers are experimental in celld, so the
10-configuration keys, the `ctx.container` surface, the node-side defaults, and the
4+it. A Durable Object starts the container, reaches it over a TCP port, and stops
5+it. The container disk is ephemeral, so durable state belongs in the storage of
6+the object or in another binding. Containers are experimental in celld, so the
7+configuration keys, the `ctx.container` surface, the node defaults, and the
118 security boundary can change without notice. Read the
129 [Cloudflare Containers documentation](https://developers.cloudflare.com/containers/)
13-for the standard API behavior.
10+for the standard API.
1411
1512 ## Example
1613
@@ -21,166 +18,114 @@
2118
2219 ## The object and its container
2320
24-A `containers` entry names a Durable Object class, and each object of that class
25-controls at most one container. The class must be SQLite-backed, and it must
26-belong to the same script. celld gives such an object a `ctx.container` handle,
27-and an object of any other class has none. A Worker therefore addresses a
28-container the way it addresses an object, with a name or an id.
21+A `containers` entry names a SQLite-backed Durable Object class of the same
22+script. Each object of that class gets a `ctx.container` handle and controls at
23+most one container.
2924
30-celld implements `running`, `start()`, `monitor()`, `destroy()`, `signal()`,
31-`getTcpPort()`, `exec()`, and `setInactivityTimeout()`. `start()` accepts
32-`entrypoint`, `env`, `enableInternet`, and `labels`. It checks `hardTimeout`
33-and then ignores it, so a value of 0 or less throws and a valid value changes
34-nothing. `inspect()`, the snapshot methods, and the outbound interception
35-methods reject with an error. Read the
36-[`ctx.container` reference](https://developers.cloudflare.com/durable-objects/api/container/)
37-for the standard method list.
25+celld implements this part of `ctx.container`:
3826
39-A request reaches the container through a port, and not through a public
40-address. `getTcpPort(port).fetch()` opens a connection from the node to the
41-container and speaks HTTP on it. On Linux, the node uses the container's bridge
42-address, so every port works. On macOS, the node uses a published loopback port,
43-so the image must declare the port with `EXPOSE`, as `wrangler dev` requires. A
44-fetch with an `Upgrade: websocket` header gives a 101 response with a
45-`webSocket`, as on Cloudflare. `getTcpPort(port).connect()` gives a raw socket
46-with the lifetime of the event that opened it. See
47-[TCP sockets](../cloudflare-compat.md#tcp-sockets).
27+- `start()` starts the container. It accepts `entrypoint`, `env`,
28+ `enableInternet`, and `labels`.
29+- `running` reports the state of the engine, so an object that lost its
30+ `monitor()` sees the exit at its next event.
31+- `monitor()` returns a promise that settles when the container exits.
32+- `destroy()` stops the container, and `signal()` sends it a signal.
33+- `getTcpPort(port).fetch()` sends an HTTP request to a port, and
34+ `getTcpPort(port).connect()` opens a raw socket.
35+- `exec()` runs a process in the container.
36+- `setInactivityTimeout()` sets the idle window.
4837
49-A `monitor()` promise and an `exec()` process have that same event lifetime.
50-They settle only inside the event that created them, and after the handler
51-answers they do not keep the object active, so a drain can move the object.
52-`running` always reports the engine's state, therefore an object that lost its
53-`monitor()` sees the exit at its next event. A `start()` that fails is logged by
54-the node as `container_start_failed`.
38+On Linux, `getTcpPort(port)` reaches every port through the bridge address of
39+the container. A fetch with an `Upgrade: websocket` header gives a 101 response
40+with a `webSocket`, as on Cloudflare. The node logs a failed `start()` as
41+`container_start_failed`.
5542
56-`@cloudflare/containers` runs as published, and the example above uses it. Its
57-`sleepAfter` alarm stops the container, and `getContainer()`, `getRandom()`, and
58-`switchPort()` work. Read the
59-[Container class reference](https://developers.cloudflare.com/containers/reference/container-class/)
60-for the hooks and the defaults. `@cloudflare/sandbox` also runs as published, on
61-the `cloudflare/sandbox` image. Its `exec()` API, files, processes, sessions,
62-and code interpreter run inside the container, over the HTTP transport and over
63-the RPC transport. Preview URLs need a wildcard hostname at the operator's load
64-balancer, tunnels run cloudflared inside the container, and bucket mounts use
65-the credentials that the application passes. See the
43+`@cloudflare/containers` runs as published, including the `sleepAfter` alarm,
44+`getContainer()`, `getRandom()`, and `switchPort()`. `@cloudflare/sandbox` also
45+runs as published on the `cloudflare/sandbox` image, over the HTTP and the RPC
46+transports. Its preview URLs need a wildcard hostname at the load balancer,
47+tunnels run cloudflared inside the container, and bucket mounts use the
48+credentials that the application passes. See the
6649 [sandbox example](../../examples/sandbox).
6750
6851 ## The image and the node
6952
70-Cloudflare pushes an image to its own registry, distributes it across its
71-network, and starts the container in a virtual machine at
72-[the nearest location that already holds the image](https://developers.cloudflare.com/containers/concepts/architecture/).
73-An object and its container can therefore run in different places. celld has no
74-registry and no global network, so it builds the same two steps out of the fleet
75-bucket and the node's own container engine.
53+`celld deploy` builds a Dockerfile in the project, or pulls an image reference,
54+with the `docker` CLI on `PATH` or the CLI that `CELLD_DOCKER` names. A Podman
55+CLI works. It saves the image to `deploy/images/<key>.tar` in the fleet bucket,
56+where the key hashes the image layers and config, so a redeploy of an unchanged
57+image uploads nothing. A node loads the image into its own engine the first time
58+a cell of the class starts, and never contacts a registry. The `celld-fence`
59+image rides with every deployment that has a container.
7660
77-`celld deploy` builds a Dockerfile in the project, or it pulls an image
78-reference, with the `docker` CLI on `PATH` or with the CLI that `CELLD_DOCKER`
79-names. A Podman CLI works. `celld deploy` then saves the image to the fleet
80-bucket at `deploy/images/<key>.tar`, where the key hashes the image layers and
81-the image config. A node loads the image into its own engine the first time a
82-cell of the class starts, so a node never contacts a registry, and a redeploy of
83-an unchanged image uploads nothing. The `celld-fence` image that a node needs
84-rides with every deployment that has a container.
61+`celld deploy` builds and pulls for `linux/amd64`, as Wrangler does.
62+`CELLD_CONTAINER_PLATFORM` selects another platform. `celld dev` builds for the
63+local machine and keeps the image in the local engine.
8564
86-`celld deploy` builds and pulls for `linux/amd64`, as Wrangler does, so a deploy
87-from an ARM machine runs on x86-64 nodes. `CELLD_CONTAINER_PLATFORM` selects
88-another platform. `celld dev` builds for the local machine and keeps the image
89-in the local engine.
65+The container runs on the node that owns the cell. Each node that serves a
66+container class needs a Docker or Podman daemon. celld uses the Unix socket
67+that `DOCKER_HOST` names, or the default socket of Docker, Docker Desktop,
68+OrbStack, or Podman. A `DOCKER_HOST` value that is not a `unix://` URL gives
69+celld no socket. A node without an engine cannot activate a cell of a container
70+class, and it serves every other class.
9071
91-The container runs on the node that owns the cell, and the two never separate.
92-Each node that serves a container class therefore needs a Docker daemon or a
93-Podman daemon. celld uses the Unix socket that `DOCKER_HOST` names, or the
94-default socket of Docker, Docker Desktop, OrbStack, or Podman. A `DOCKER_HOST`
95-value that is not a `unix://` URL gives celld no socket at all. A node without
96-an engine cannot activate a cell of a container class, and it serves every other
97-class.
98-
99-![A Worker on any node is routed to the node that owns the cell, where a V8 isolate and a container process run on two sides of the container engine socket, behind an nftables fence on the node's bridge, and a move destroys the container](containers-flow.svg)
100-
10172 ## The isolation boundary
10273
103-Cloudflare runs each container in its own virtual machine, so Cloudflare
104-publishes no capability policy. Under the default runtime a celld container
105-shares the node's kernel, so celld sets a policy of its own. celld drops all
106-Linux capabilities, sets `no-new-privileges`, keeps the daemon's default seccomp
107-profile, limits the container to 1024 processes, and runs an init as PID 1 that
108-reaps an orphaned process. Two containers on one node cannot open connections to
109-each other.
74+Under the default runtime, a container shares the kernel of the node and is not
75+a virtual machine. celld drops all Linux capabilities, sets
76+`no-new-privileges`, keeps the default seccomp profile of the daemon, limits the
77+container to 1024 processes, and runs an init as PID 1 that reaps orphans. Two
78+containers on one node cannot connect to each other.
11079
111-The node fences its container bridges before the first container starts. The
112-rules are nftables rules on the node, outside every container and every runtime,
113-and celld installs them through the daemon with a one-shot privileged container
114-of the `celld-fence` image. A container with `enableInternet: true` reaches the
115-Internet and nothing of the node's own. It cannot open a connection to the node,
116-to another node, to the private ranges `10/8`, `172.16/12`, `192.168/16`, and
117-`100.64/10`, or to the link-local range, so the node's internal listener and a
118-cloud metadata service are both out of reach. A node that cannot install the
119-rules starts no container, and a deployment from a celld without the fence image
80+Before the first container starts, the node installs nftables rules on its
81+container bridges through a one-shot privileged container of the `celld-fence`
82+image. A container with `enableInternet: true` reaches the Internet, but not
83+the node, another node, the private ranges `10/8`, `172.16/12`, `192.168/16`,
84+and `100.64/10`, or the link-local range. A node that cannot install the rules
85+starts no container, and a deployment from a celld without the fence image
12086 starts no container on a node that has the fence.
12187
12288 `enableInternet: false` attaches the container to an internal bridge with no
123-route out. On macOS, the node reaches a container only through a published port,
124-and an internal network publishes none, so `celld dev` on macOS keeps egress on
125-and logs a warning. The fence still applies.
89+route out. On macOS, an internal network publishes no port, so `celld dev` on
90+macOS keeps egress on and logs a warning. The fence still applies.
12691
12792 `CELLD_CONTAINER_RUNTIME` names the OCI runtime for every container on the node,
128-for example `runsc` for gVisor or `kata` for a virtual machine. A `containers`
129-entry can also name a `runtime` of its own, which overrides the node setting for
130-that class. celld adds this key, and the Cloudflare configuration has no
131-equivalent. The daemon must have the named runtime, or every `start()` of such a
132-container fails with the daemon's error, so a class runs only where its
133-isolation exists. Under the default runtime, a container is a kernel namespace
134-boundary and not a virtual machine. For code that you did not write, name a
135-runtime that gives each container its own kernel, and keep the secrets in the
136-Worker.
93+for example `runsc` for gVisor or `kata` for a virtual machine. A `runtime` key
94+in a `containers` entry overrides it for that class; Cloudflare has no such key.
95+If the daemon lacks the runtime, every `start()` fails with the daemon error.
96+For code that you did not write, name a runtime that gives each container its
97+own kernel, and keep the secrets in the Worker.
13798
138-A container that runs under a named runtime gets a written `/etc/resolv.conf`
139-with public resolvers, `1.1.1.1` and `1.0.0.1` by default, or the
140-`CELLD_CONTAINER_DNS` resolvers when the operator sets them. gVisor cannot reach
141-the container engine's built-in resolver, so a container under gVisor resolves
142-no hostname otherwise, and the fence permits the public resolver. A container on
143-the node's default runtime keeps the engine's resolver, unless the operator sets
144-`CELLD_CONTAINER_DNS`.
99+A container under a named runtime gets a written `/etc/resolv.conf` with
100+`1.1.1.1` and `1.0.0.1`, or the `CELLD_CONTAINER_DNS` resolvers, because gVisor
101+cannot reach the built-in resolver of the engine. The fence permits the public
102+resolver. A container on the default runtime keeps the engine resolver unless
103+the operator sets `CELLD_CONTAINER_DNS`.
145104
146105 ## Sleep, wake, and the node's resources
147106
148-Cloudflare stops an idle container after 10 minutes, and `sleepAfter` changes
149-that window. celld keeps the same default and the same mechanism.
150-`setInactivityTimeout()` sets the window for the engine, and celld uses 10
151-minutes without one. An idle eviction of the cell keeps the container running
152-for that window, and the next activation of the cell on the same node reconnects
153-to it. A move to another node, a node restart, and a reset destroy the container
154-instead, so the container disk is ephemeral, as on Cloudflare. A node stop
155-destroys every container of the node, and Ctrl-C on `celld dev` does the same
156-while it keeps the local state.
107+`setInactivityTimeout()` sets the idle window, and the default is 10 minutes, as
108+on Cloudflare. An idle eviction of the cell keeps the container running for that
109+window, and the next activation on the same node reconnects to it. A move to
110+another node, a node restart, a reset, and a node stop destroy the container.
111+Ctrl-C on `celld dev` destroys the containers and keeps the local state.
157112
158-`instance_type` sets the CPU limit and the memory limit of the Cloudflare
159-instance type with that name. celld accepts `lite` and its older name `dev`,
160-`basic`, `standard-1` and its alias `standard`, `standard-2`, `standard-3`, and
161-`standard-4`, with the values that
162-[the Cloudflare limits page](https://developers.cloudflare.com/containers/platform/limits/)
163-gives. An entry without an `instance_type` gets `dev`, a sixteenth of a CPU and
164-256 MiB, as on Cloudflare. A sixteenth of a CPU is a slow start for an
165-interpreter, so name a larger type when the image boots a runtime. celld does
166-not enforce the disk size of the type.
113+`instance_type` accepts `lite` and its older name `dev`, `basic`, `standard-1`
114+and its alias `standard`, `standard-2`, `standard-3`, and `standard-4`, with the
115+CPU and memory limits of
116+[the Cloudflare limits page](https://developers.cloudflare.com/containers/platform/limits/).
117+The default is `dev`: a sixteenth of a CPU and 256 MiB, as on Cloudflare. Name a
118+larger type when the image boots an interpreter.
167119
168-A container runs in its own cgroup, so the node process does not carry the
169-container's memory in its own charge. The node therefore counts the instance
170-type's memory cap of every running container as committed memory. A
171-container-heavy node reports no headroom and sheds cells, which keeps the node
172-away from the kernel out-of-memory killer. An operator must set the node memory
173-ceiling at or above the largest instance type in use, plus headroom.
120+The node counts the memory cap of every running container as committed memory,
121+because the container cgroup is outside the node process. A container-heavy
122+node therefore reports no headroom and sheds cells. Set the node memory ceiling
123+at or above the largest instance type in use, plus headroom.
174124
175-`max_instances` caps the containers that one class runs across the fleet.
176-Cloudflare holds that cap centrally. celld has no coordinator, so each node
177-publishes its running container count per class in the shared capacity sample. A
178-node that is about to start a container sums that count across the fleet and
179-adds its own live count. A start over the cap fails, and the node logs
180-`container_start_failed` with the limit. The sample can lag one refresh,
181-therefore two nodes that start the same class at once can exceed the cap for a
182-moment and converge at the next refresh. `celld dev` reads no sample, so it
183-enforces no fleet cap.
125+Each node publishes its running container count per class in the shared
126+capacity sample. Before a start, a node sums the fleet count and its own live
127+count against `max_instances`. A start over the cap fails, and the node logs
128+`container_start_failed` with the limit.
184129
185130 ## Differences from Cloudflare
186131
deleteddocs/services/cron-triggers-flow.svg+0−148
@@ -1,148 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 676" role="img" aria-labelledby="cronFlowTitle cronFlowDesc">
2- <title id="cronFlowTitle">Every node arms one reserved cron cell, its single alarm row carries the earliest occurrence, a shared deadline runs one invocation for each matching expression, and the re-arm takes the earlier of the next occurrence and the failure backoff</title>
3- <desc id="cronFlowDesc">The first panel shows three nodes of one fleet. Each node calls the same
4-reserved cell, named .cron:cron from the class and the script name, once after
5-its deployment loads. The ownership record in the fleet bucket accepts one
6-caller, and the other nodes route to that owner, so celld needs no election and
7-no reserved cron node. The second panel shows three cron expressions of one
8-script at 12:35 UTC. Two of them come due at 13:00 and one comes due on the
9-next Monday at 09:00, and the one alarm row of the cell arms for 13:00, the
10-earliest occurrence across the whole list. The third panel shows the 13:00
11-deadline firing. Both expressions that match that minute get their own call of
12-scheduled(controller, env, ctx), each with its own controller.cron, and the two
13-calls run one after another inside the cell because a cell runs one event at a
14-time. controller.scheduledTime is 13:00 for both calls and never the instant
15-the attempt started. The fourth panel shows the re-arm after a failed 13:00
16-run. For the expression */30 * * * * the retry backoff of 4 seconds is earlier
17-than the next occurrence at 13:30, so the retry is armed. For the expression
18-* * * * * the next occurrence at 13:01 is earlier than a grown backoff of 128
19-seconds, so the occurrence is armed and the retry is dropped. A backoff
20-therefore never delays or skips a scheduled occurrence.</desc>
21- <style>
22- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
23- text { font-size: 13px; fill: currentColor; }
24- tspan { fill: currentColor; }
25- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
26- .lead { font-weight: 600; }
27- .sm { font-size: 12px; }
28- .d-ink { color: #121212; }
29- .d-soft { color: #3d3b37; }
30- .d-faint { color: #6e6a62; }
31- .d-acc { color: #10803f; }
32- .d-panel { color: #ffffff; }
33- .d-sunk { color: #f0eee8; }
34- .d-tint { color: #d6efdf; }
35- @media (prefers-color-scheme: dark) {
36- .d-ink { color: #efede7; }
37- .d-soft { color: #c9c6be; }
38- .d-faint { color: #928e85; }
39- .d-acc { color: #3fc472; }
40- .d-panel { color: #1a1a19; }
41- .d-sunk { color: #232321; }
42- .d-tint { color: #10301d; }
43- }
44- </style>
45- <defs>
46- <marker id="cron-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
47- markerHeight="6" orient="auto-start-reverse">
48- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
49- </marker>
50- </defs>
51-
52- <!-- Panel one: the fan-in. Every node arms, and one ownership CAS decides. -->
53- <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="186" rx="10" />
54- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="186" rx="10" />
55- <text class="d-ink lead" fill="currentColor" x="22" y="32">Every node arms the same reserved cell</text>
56- <text class="d-faint sm" fill="currentColor" x="22" y="50">no election, and no reserved cron node</text>
57-
58- <g>
59- <rect class="d-panel" fill="currentColor" x="22" y="64" width="122" height="38" rx="8" />
60- <rect class="d-soft" fill="none" stroke="currentColor" x="22" y="64" width="122" height="38" rx="8" />
61- <text class="d-ink" fill="currentColor" x="83" y="88" text-anchor="middle">node A</text>
62- <rect class="d-panel" fill="currentColor" x="159" y="64" width="122" height="38" rx="8" />
63- <rect class="d-soft" fill="none" stroke="currentColor" x="159" y="64" width="122" height="38" rx="8" />
64- <text class="d-ink" fill="currentColor" x="220" y="88" text-anchor="middle">node B</text>
65- <rect class="d-panel" fill="currentColor" x="296" y="64" width="122" height="38" rx="8" />
66- <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="64" width="122" height="38" rx="8" />
67- <text class="d-ink" fill="currentColor" x="357" y="88" text-anchor="middle">node C</text>
68- </g>
69-
70- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
71- <path d="M83 102 V122 H220" />
72- <path d="M357 102 V122 H220" />
73- <path d="M220 102 V136" marker-end="url(#cron-arrow)" />
74- </g>
75- <text class="d-faint sm" fill="currentColor" x="228" y="118">arm</text>
76-
77- <rect class="d-tint" fill="currentColor" x="110" y="140" width="220" height="46" rx="8" />
78- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="110" y="140" width="220" height="46" rx="8" />
79- <text class="d-ink mono" fill="currentColor" x="220" y="162" text-anchor="middle">.cron:cron</text>
80- <text class="d-soft sm" fill="currentColor" x="220" y="179" text-anchor="middle">one owner, by ownership CAS</text>
81-
82- <!-- Panel two: many expressions, one alarm row, the earliest deadline. -->
83- <text class="d-ink lead" fill="currentColor" x="22" y="226">One alarm row holds one deadline</text>
84- <text class="d-faint sm mono" fill="currentColor" x="22" y="244">now 12:35 UTC</text>
85-
86- <text class="d-soft mono" fill="currentColor" x="26" y="272">*/30 * * * *</text>
87- <text class="d-ink mono" fill="currentColor" x="150" y="272">13:00</text>
88- <text class="d-soft mono" fill="currentColor" x="26" y="292">0 * * * *</text>
89- <text class="d-ink mono" fill="currentColor" x="150" y="292">13:00</text>
90- <text class="d-soft mono" fill="currentColor" x="26" y="312">0 9 * * MON</text>
91- <text class="d-faint mono" fill="currentColor" x="150" y="312">Mon 09:00</text>
92-
93- <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2"
94- d="M214 260 H222 V298 H214" />
95- <path class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"
96- d="M224 279 H244" marker-end="url(#cron-arrow)" />
97-
98- <rect class="d-panel" fill="currentColor" x="252" y="253" width="178" height="52" rx="8" />
99- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="252" y="253" width="178" height="52" rx="8" />
100- <text class="d-ink" fill="currentColor" x="341" y="276" text-anchor="middle">armed for 13:00</text>
101- <text class="d-soft sm" fill="currentColor" x="341" y="294" text-anchor="middle">the earliest of the three</text>
102-
103- <!-- Panel three: the fan-out. One deadline, one call per matching expression. -->
104- <text class="d-ink lead" fill="currentColor" x="22" y="350">A deadline that two expressions share runs twice</text>
105-
106- <rect class="d-tint" fill="currentColor" x="22" y="364" width="142" height="52" rx="8" />
107- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="364" width="142" height="52" rx="8" />
108- <text class="d-ink" fill="currentColor" x="93" y="388" text-anchor="middle">the alarm fires</text>
109- <text class="d-soft sm mono" fill="currentColor" x="93" y="406" text-anchor="middle">13:00 UTC</text>
110-
111- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
112- <path d="M164 390 H182 V380 H194" marker-end="url(#cron-arrow)" />
113- <path d="M164 390 H182 V436 H194" marker-end="url(#cron-arrow)" />
114- </g>
115-
116- <rect class="d-panel" fill="currentColor" x="200" y="356" width="232" height="48" rx="8" />
117- <rect class="d-soft" fill="none" stroke="currentColor" x="200" y="356" width="232" height="48" rx="8" />
118- <text class="d-ink mono" fill="currentColor" x="316" y="378" text-anchor="middle">scheduled(controller, env, ctx)</text>
119- <text class="d-acc sm mono" fill="currentColor" x="316" y="396" text-anchor="middle">cron: "*/30 * * * *"</text>
120-
121- <rect class="d-panel" fill="currentColor" x="200" y="412" width="232" height="48" rx="8" />
122- <rect class="d-soft" fill="none" stroke="currentColor" x="200" y="412" width="232" height="48" rx="8" />
123- <text class="d-ink mono" fill="currentColor" x="316" y="434" text-anchor="middle">scheduled(controller, env, ctx)</text>
124- <text class="d-acc sm mono" fill="currentColor" x="316" y="452" text-anchor="middle">cron: "0 * * * *"</text>
125-
126- <text class="d-soft sm" fill="currentColor" x="22" y="436">one after the other,</text>
127- <text class="d-soft sm" fill="currentColor" x="22" y="452">inside the one cell</text>
128- <text class="d-faint sm" fill="currentColor" x="22" y="486">scheduledTime is the occurrence 13:00 for both calls, never the</text>
129- <text class="d-faint sm" fill="currentColor" x="22" y="502">instant an attempt started</text>
130-
131- <!-- Panel four: the re-arm race, where the answer flips with the interval. -->
132- <text class="d-ink lead" fill="currentColor" x="22" y="536">The re-arm takes whichever deadline is earlier</text>
133- <text class="d-faint sm" fill="currentColor" x="22" y="554">both lines start at a failed 13:00 run</text>
134-
135- <text class="d-soft mono" fill="currentColor" x="22" y="586">*/30 * * * *</text>
136- <path class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5" d="M120 582 H424" />
137- <path class="d-faint" fill="none" stroke="currentColor" d="M170 574 V590 M390 574 V590" />
138- <circle class="d-acc" fill="currentColor" cx="170" cy="582" r="5" />
139- <text class="d-acc sm" fill="currentColor" x="170" y="606" text-anchor="middle">retry +4 s</text>
140- <text class="d-faint sm" fill="currentColor" x="424" y="606" text-anchor="end">next 13:30</text>
141-
142- <text class="d-soft mono" fill="currentColor" x="22" y="638">* * * * *</text>
143- <path class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5" d="M120 634 H424" />
144- <path class="d-faint" fill="none" stroke="currentColor" d="M210 626 V642 M330 626 V642" />
145- <circle class="d-acc" fill="currentColor" cx="210" cy="634" r="5" />
146- <text class="d-acc sm" fill="currentColor" x="210" y="658" text-anchor="middle">next 13:01</text>
147- <text class="d-faint sm" fill="currentColor" x="424" y="658" text-anchor="end">retry +128 s</text>
148-</svg>
modifieddocs/services/cron-triggers.md+46−104View file
@@ -1,11 +1,9 @@
11 # Cron Triggers
22
3-A Cron Trigger runs a Worker on a schedule instead of on a request. An
4-application uses one for periodic work, such as a cleanup, a report, or a poll
5-of an upstream service. celld keeps the schedule of a script in one reserved
6-cell, so a fleet of many nodes runs each occurrence once. Read the
3+A Cron Trigger runs a Worker on a schedule. celld keeps the schedule of a script
4+in one reserved cell, so a fleet runs each occurrence once. Read the
75 [Cloudflare Cron Triggers documentation](https://developers.cloudflare.com/workers/configuration/cron-triggers/)
8-for the standard API behavior.
6+for the API.
97
108 ## Example
119
@@ -14,118 +12,62 @@
1412
1513 <!-- celld-example: cron -->
1614
17-## Configuring a schedule
15+## API
1816
19-A project declares its schedules in a `triggers.crons` array, and each entry is
20-one cron expression. `celld deploy` parses every entry, therefore a malformed
21-expression stops the deployment instead of failing at the first occurrence. A
22-configuration that sets `triggers.crons` without `main` also fails, because a
23-Cron Trigger needs a `scheduled` handler to call.
17+A Worker exports a `scheduled(controller, env, ctx)` handler.
2418
25-celld reads the Cloudflare cron dialect and not the POSIX one. An expression has
26-five fields: minute, hour, day of month, month, and day of week. The resolution
27-is one minute and the zone is UTC. Cloudflare
28-[numbers the weekdays 1 to 7 from Sunday](https://developers.cloudflare.com/workers/configuration/cron-triggers/),
29-so `1-5` means Sunday to Thursday here and not Monday to Friday.
19+- `controller.cron` holds the expression text.
20+- `controller.scheduledTime` holds the occurrence in milliseconds.
21+- `controller.noRetry()` stops the retries of a failed occurrence.
22+- `ctx.waitUntil()` extends the invocation. celld drains this work before the
23+ next invocation.
3024
31-Each field takes `*`, a single value, an `a-b` range, an `a,b` list, and a `/n`
32-step on any of those. The month field and the day-of-week field also take the
33-three-letter names in any case, such as `JAN` and `MON`. celld supports the
34-non-standard day forms as well: the day-of-month field takes `L`, `L-<n>`, `LW`,
35-`L-<n>W`, and `<d>W`, and the day-of-week field takes `<dow>L` and `<dow>#<n>`.
25+## Schedules
3626
37-The two day fields form a union and not an intersection when both of them carry
38-a restriction, which is the ordinary cron rule. `0 0 1 * MON` therefore fires on
39-the first day of each month and on every Monday. Only a literal `*` leaves a day
40-field unrestricted, so `*/2` in the day-of-month field joins that union.
27+A project declares its schedules in a `triggers.crons` array. `celld deploy`
28+fails on a malformed expression, and on `triggers.crons` without `main`. celld
29+sets no limit on the number of expressions.
4130
42-celld refuses a small set of expressions that Cloudflare accepts, because the
43-upstream parser answers them in a way that nobody writes on purpose. A
44-descending range such as `SAT-SUN` wraps around the end of the field there and
45-takes one value too many at the low end, so celld stops the deployment instead
46-of shipping a schedule that fires on an unasked day. A `*` inside a list such as
47-`1,*` means the minimum of the field there and not every value, so celld refuses
48-that form and asks for the values. celld also bounds a step by the width of its
49-field, therefore `*/60` fails for the minute field.
31+celld reads the Cloudflare cron dialect. An expression has five fields: minute,
32+hour, day of month, month, and day of week. The resolution is one minute, and
33+the zone is UTC. Weekdays are
34+[numbered 1 to 7 from Sunday](https://developers.cloudflare.com/workers/configuration/cron-triggers/),
35+so `1-5` means Sunday to Thursday.
5036
51-A script can declare as many expressions as it needs, because celld sets no
52-count limit. A node fires only the schedule of the deployment that it serves, so
53-a `triggers.crons` entry in a service-binding target never runs, and celld logs
54-a warning when it loads such a target.
37+Each field takes `*`, a value, an `a-b` range, an `a,b` list, and a `/n` step.
38+The month and day-of-week fields also take three-letter names in any case, such
39+as `JAN` and `MON`. The day-of-month field takes `L`, `L-<n>`, `LW`, `L-<n>W`,
40+and `<d>W`, and the day-of-week field takes `<dow>L` and `<dow>#<n>`. When both
41+day fields are restricted, they form a union, so `0 0 1 * MON` fires on the
42+first day of each month and on every Monday. Only a literal `*` leaves a day
43+field unrestricted.
5544
56-## The node that runs a scheduled event
45+celld refuses a descending range such as `SAT-SUN` and a list that contains
46+`*`, such as `1,*`. Cloudflare accepts both with surprising results. A step
47+cannot exceed the width of its field, so `*/60` fails in the minute field.
5748
58-celld gives each deployment that declares `triggers.crons` one reserved cell,
59-named from the class `.cron` and the script name. That cell carries the whole
60-schedule of the script. Exactly one node owns a cell at a time, which is the
61-rule that every [Durable Object](durable-objects.md) already follows, so the
62-reserved cell is what makes an occurrence run once for the fleet and not once
63-for each node.
49+## Execution
6450
65-A cron cell has no client that can wake it, so every node calls the cell once
66-after its deployment loads. The ownership record in the fleet bucket accepts one
67-of those callers, and the other nodes route their call to that owner. celld adds
68-no election and reserves no cron node. The call is idempotent, because the same
69-schedule and the same clock give the same deadline, so which node wins does not
70-matter.
51+`controller.scheduledTime` holds the scheduled occurrence and not the start of
52+the attempt, so a late run and a retry name the same minute. celld runs the
53+handlers of one script one at a time and drains the `waitUntil()` work of each
54+before the next. A handler that takes longer than the interval delays the next
55+occurrence. Move long work into a [queue](queues.md) or a
56+[Workflow](workflows.md).
7157
72-The cell does nothing between two occurrences, so it hibernates like any other
73-cell and costs no isolate while it waits. A deployment that declares no
74-expression leaves nothing to arm, and the cell then deletes its alarm and
75-retires instead of waking forever.
58+A handler that throws retries after 4 seconds, and the delay doubles after each
59+further failure. celld gives up after six failures, or at the next occurrence,
60+which never waits for a retry, so a schedule faster than the
61+backoff never retries. `controller.noRetry()` stops the retries. An
62+ownership move loses a pending retry.
7663
77-The cell holds one alarm row, therefore one deadline covers every expression of
78-the script. celld arms that row at the earliest next occurrence across the whole
79-list. When the alarm fires, celld finds every expression that matches that
80-minute and calls `scheduled(controller, env, ctx)` once for each one. The
81-invocations run one after another inside the cell, because a cell runs one event
82-at a time.
64+After downtime, celld runs one missed occurrence and skips the rest. Read the
65+interval from `controller.scheduledTime` to catch up in application code.
8366
84-`controller.cron` holds the expression text as the developer wrote it, and
85-`controller.scheduledTime` holds the occurrence in milliseconds. celld reports
86-the occurrence and never the instant the attempt started, so a late run and a
87-retry both name the minute that they were scheduled for. `controller.noRetry()`
88-and `ctx.waitUntil()` behave as the
89-[scheduled handler documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/)
90-describes, and celld drains the `waitUntil()` work of one invocation before it
91-starts the next one.
67+The node that owns the reserved cell runs the occurrence, and that node can
68+change. A `triggers.crons` entry in a service-binding target never runs, and
69+celld logs a warning when it loads such a target.
9270
93-![Every node arms the same reserved cron cell and ownership CAS keeps one owner, the cell holds one alarm row armed at the earliest occurrence across all expressions, a shared deadline runs one scheduled invocation for each matching expression in turn, and the re-arm takes whichever is earlier of the next occurrence and the failure backoff](cron-triggers-flow.svg)
94-
95-Cloudflare runs a scheduled event on its own global network and selects the
96-location for you. celld makes no such placement promise. The occurrence runs on
97-the node that owns the reserved cell at the deadline, and that owner can change
98-when a node stops, when a node drains, or when idle rebalancing moves the cell.
99-
100-## Failure, retry, and a missed occurrence
101-
102-A `scheduled` handler that throws leaves its expression owed. celld logs the
103-error and arms a backoff of 4 seconds, and each further failure of the same
104-occurrence doubles that delay. celld gives up on the occurrence after six
105-failures. A retry repeats only the expressions that failed, because the
106-expressions that succeeded already ran for that occurrence.
107-`controller.noRetry()` removes an expression from that set, so a handler that
108-knows the work is pointless ends the loop itself.
109-
110-The next occurrence and the backoff compete for the one alarm row, and the
111-earlier deadline wins. A retry therefore never delays a scheduled run and never
112-replaces one. A schedule that fires faster than the backoff never retries at
113-all, which costs little, because the next attempt is already seconds away. celld
114-holds the retry state in memory, so an eviction or an ownership move loses a
115-pending retry and never the next occurrence.
116-
117-celld runs one missed occurrence after downtime. A deadline that is already due
118-when the fleet returns is a late tick and not a wrong one, so celld leaves the
119-armed alarm in place and runs it. The re-arm then walks forward from the current
120-time, therefore the occurrences between the late one and now do not run. An
121-application that must process every interval reads the interval from
122-`controller.scheduledTime` and catches up in its own code.
123-
124-Two occurrences of one script never overlap. The reserved cell runs one event at
125-a time, so a handler that takes longer than the interval holds the cell and
126-delays the next occurrence. Move long work into a [queue](queues.md) or a
127-[Workflow](workflows.md) when the schedule must stay on time.
128-
12971 ## Differences from Cloudflare
13072
13173 - celld rejects a descending range such as `SAT-SUN` and a list that contains
deleteddocs/services/d1-flow.svg+0−111
@@ -1,111 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 464" role="img" aria-labelledby="d1FlowTitle d1FlowDesc">
2- <title id="d1FlowTitle">A D1 database is one cell, so every statement crosses a node boundary</title>
3- <desc id="d1FlowDesc">Worker A runs three prepared statements against the binding DB and pays three
4-round trips. Worker B sends the same three statements as one batch and pays one
5-round trip. Both cross a node boundary, because celld routes every statement to
6-the node that owns the cell. The guestbook database is one cell owned by node C.
7-It holds one SQLite file and has one writer, so the three separate statements
8-take three cell turns while the batch runs inside one BEGIN IMMEDIATE and COMMIT
9-in a single turn, all or nothing. Below the cell, a read answers from the cell's
10-own SQLite file and touches no bucket, while a write commits and then replicates
11-to the fleet bucket as LTX, and the acknowledgement waits for that write. A
12-second database is a second cell with its own owner node and its own writer, so
13-more write capacity comes from more databases and not from a bigger one.</desc>
14- <style>
15- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
16- text { font-size: 13px; fill: currentColor; }
17- tspan { fill: currentColor; }
18- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
19- .lead { font-weight: 600; }
20- .d-ink { color: #121212; }
21- .d-soft { color: #3d3b37; }
22- .d-faint { color: #6e6a62; }
23- .d-acc { color: #10803f; }
24- .d-panel { color: #ffffff; }
25- .d-sunk { color: #f0eee8; }
26- .d-tint { color: #d6efdf; }
27- @media (prefers-color-scheme: dark) {
28- .d-ink { color: #efede7; }
29- .d-soft { color: #c9c6be; }
30- .d-faint { color: #928e85; }
31- .d-acc { color: #3fc472; }
32- .d-panel { color: #1a1a19; }
33- .d-sunk { color: #232321; }
34- .d-tint { color: #10301d; }
35- }
36- </style>
37- <defs>
38- <marker id="d1-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
39- markerHeight="6" orient="auto-start-reverse">
40- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
41- </marker>
42- </defs>
43-
44- <!-- The same three statements, sent two ways. -->
45- <rect class="d-panel" fill="currentColor" x="6" y="8" width="196" height="68" rx="8" />
46- <rect class="d-faint" fill="none" stroke="currentColor" x="6" y="8" width="196" height="68" rx="8" />
47- <text class="d-faint" fill="currentColor" x="18" y="30">Worker · node A</text>
48- <text class="d-ink mono" fill="currentColor" x="18" y="52">prepare(…).run() ×3</text>
49- <text class="d-acc" fill="currentColor" x="18" y="70">three round trips</text>
50-
51- <rect class="d-panel" fill="currentColor" x="238" y="8" width="196" height="68" rx="8" />
52- <rect class="d-faint" fill="none" stroke="currentColor" x="238" y="8" width="196" height="68" rx="8" />
53- <text class="d-faint" fill="currentColor" x="250" y="30">Worker · node B</text>
54- <text class="d-ink mono" fill="currentColor" x="250" y="52">batch([a, b, c])</text>
55- <text class="d-acc" fill="currentColor" x="250" y="70">one round trip</text>
56-
57- <!-- The boundary every statement crosses. -->
58- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
59- x="6" y="90" width="428" height="40" rx="8" />
60- <text class="d-soft" fill="currentColor" x="220" y="110" text-anchor="middle">node boundary</text>
61- <text class="d-faint" fill="currentColor" x="220" y="126" text-anchor="middle">celld routes each call to the owner</text>
62-
63- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
64- <path d="M30 76 V144" marker-end="url(#d1-arrow)" />
65- <path d="M60 76 V144" marker-end="url(#d1-arrow)" />
66- <path d="M90 76 V144" marker-end="url(#d1-arrow)" />
67- <path d="M396 76 V144" marker-end="url(#d1-arrow)" />
68- </g>
69-
70- <!-- One database, one cell, one SQLite file, one writer. -->
71- <rect class="d-tint" fill="currentColor" x="16" y="144" width="408" height="134" rx="10" />
72- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="144" width="408" height="134" rx="10" />
73- <text class="d-ink lead" fill="currentColor" x="32" y="170">guestbook database = one cell · owner: node C</text>
74- <text class="d-soft" fill="currentColor" x="32" y="190">one SQLite file, one writer — statements never overlap</text>
75-
76- <rect class="d-sunk" fill="currentColor" x="30" y="204" width="184" height="60" rx="8" />
77- <rect class="d-faint" fill="none" stroke="currentColor" x="30" y="204" width="184" height="60" rx="8" />
78- <text class="d-ink mono" fill="currentColor" x="122" y="228" text-anchor="middle">run · run · run</text>
79- <text class="d-soft" fill="currentColor" x="122" y="248" text-anchor="middle">three cell turns</text>
80-
81- <rect class="d-sunk" fill="currentColor" x="226" y="204" width="184" height="60" rx="8" />
82- <rect class="d-faint" fill="none" stroke="currentColor" x="226" y="204" width="184" height="60" rx="8" />
83- <text class="d-ink mono" fill="currentColor" x="318" y="228" text-anchor="middle">BEGIN … COMMIT</text>
84- <text class="d-soft" fill="currentColor" x="318" y="248" text-anchor="middle">one turn, all or nothing</text>
85-
86- <!-- A read stops at the cell; a write goes on to the bucket. -->
87- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
88- <path d="M100 278 V308" marker-end="url(#d1-arrow)" />
89- <path d="M330 278 V308" marker-end="url(#d1-arrow)" />
90- </g>
91- <text class="d-faint" fill="currentColor" x="108" y="300">read</text>
92- <text class="d-faint" fill="currentColor" x="338" y="300">write</text>
93-
94- <rect class="d-sunk" fill="currentColor" x="16" y="312" width="196" height="76" rx="8" />
95- <rect class="d-faint" fill="none" stroke="currentColor" x="16" y="312" width="196" height="76" rx="8" />
96- <text class="d-ink" fill="currentColor" x="30" y="336">answered here</text>
97- <text class="d-soft" fill="currentColor" x="30" y="356">from the cell's SQLite</text>
98- <text class="d-faint" fill="currentColor" x="30" y="376">no bucket round trip</text>
99-
100- <rect class="d-sunk" fill="currentColor" x="228" y="312" width="196" height="76" rx="8" />
101- <rect class="d-faint" fill="none" stroke="currentColor" x="228" y="312" width="196" height="76" rx="8" />
102- <text class="d-ink" fill="currentColor" x="242" y="336">commits, then LTX</text>
103- <text class="d-soft" fill="currentColor" x="242" y="356">to the fleet bucket</text>
104- <text class="d-faint" fill="currentColor" x="242" y="376">the ack waits for it</text>
105-
106- <!-- Scale comes from more cells, not a bigger one. -->
107- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
108- x="16" y="404" width="408" height="50" rx="8" />
109- <text class="d-soft" fill="currentColor" x="32" y="426">orders database = a second cell, a second owner node</text>
110- <text class="d-faint" fill="currentColor" x="32" y="446">a second writer, so capacity comes from more databases</text>
111-</svg>
modifieddocs/services/d1.md+47−106View file
@@ -1,12 +1,9 @@
11 # D1
22
3-D1 is a SQL database that a Worker reaches through a binding. An application
4-uses D1 for relational data that needs queries, joins, and constraints, such as
5-a user table, an order history, or a guestbook. celld gives each database its
6-own SQLite file inside one cell, so the rows live on the node that owns that
7-cell and never in the Worker isolate. Read the
3+D1 is a SQL database that a Worker reaches through a binding. celld gives each
4+database its own SQLite file inside one cell. Read the
85 [Cloudflare D1 documentation](https://developers.cloudflare.com/d1/worker-api/d1-database/)
9-for the standard API behavior.
6+for the API.
107
118 ## Example
129
@@ -14,118 +11,62 @@
1411
1512 <!-- celld-example: d1 -->
1613
17-## Statements and results
14+## API
1815
19-A project declares a database with a `d1_databases` entry that gives a
20-`binding`, a `database_name`, and a `database_id`. celld uses the
21-`database_id` as the stable identity when the entry carries one, and it falls
22-back to the `database_name`. That identity belongs to the fleet and not to one
23-script, so two Workers that name one identity reach one database. celld also
24-creates a database on first use, therefore a typo in the name opens an empty
25-database instead of an error.
16+- `prepare(sql)` returns a statement, and `bind(...values)` returns a new
17+ statement that carries the values.
18+- `all()` returns `success`, a `results` array of row objects, and `meta`.
19+ `run()` is the same method under a second name.
20+- `first()` returns the first row or `null`, and `first(column)` returns one
21+ column of that row.
22+- `raw()` returns the rows as arrays, and `raw({ columnNames: true })` puts the
23+ column names in the first array.
24+- `batch(statements)` runs prepared statements in one transaction and returns
25+ one result for each statement.
26+- `exec(sql)` runs one or more statements without parameters, such as a schema.
2627
27-`env.DB.prepare(sql)` returns a statement, and `bind()` returns a new statement
28-that carries the values. celld checks each value at that call: a number and a
29-string pass, a boolean becomes `1` or `0`, and an `ArrayBuffer`, a typed array,
30-or an array of byte numbers becomes a `BLOB`. Any other value throws
31-`D1_TYPE_ERROR` before SQL runs. celld binds the positional parameters `?` and
32-`?NNN` that
33-[Cloudflare binds](https://developers.cloudflare.com/d1/worker-api/prepared-statements/).
28+## Configuration and limits
3429
35-Four methods run a statement, and each one shapes the answer differently.
36-`all()` returns `success`, a `results` array of row objects, and a `meta`
37-block, and `run()` is the same method under a second name. `first()` returns
38-the first row as an object, or `null` for an empty result, and `first(column)`
39-returns one column of that row. `raw()` returns the rows as arrays and drops
40-`meta`, and `raw({ columnNames: true })` puts the column names in the first
41-array. `meta` carries `duration`, `rows_read`, `rows_written`, `last_row_id`,
42-`changes`, `changed_db`, and `size_after`. A read-only statement reports
43-`last_row_id` and `changes` as `0`, because both values belong to the
44-connection and a read changes neither.
30+A `d1_databases` entry gives a `binding`, a `database_name`, and a
31+`database_id`. celld uses the `database_id` as the identity, or the
32+`database_name` when the entry has no id. Two Workers that name one identity
33+reach one database. celld creates a database on first use, so a typo in the
34+name opens an empty database and does not cause an error.
4535
46-`exec(sql)` runs one or more statements without a parameter and returns a count
47-and a duration. Use it for a schema or an import, as the example does. A
48-prepared statement must hold exactly one statement, so celld refuses a second
49-one with `A prepared SQL statement must contain only one statement.` Cloudflare
50-runs the extra statement and answers with the last result, therefore an
51-application that relies on that behavior must call `exec()` or `batch()`
52-instead. The count that `exec()` returns also differs: celld counts each
53-statement, and Cloudflare counts each input line.
36+`bind()` checks each value. A number and a string pass, a boolean becomes `1`
37+or `0`, and an `ArrayBuffer`, a typed array, or an array of byte numbers becomes
38+a `BLOB`. Any other value throws `D1_TYPE_ERROR`. celld binds the positional
39+parameters `?` and `?NNN`.
5440
55-celld applies the SQLite budgets that workerd applies, so these published
56-[D1 limits](https://developers.cloudflare.com/d1/platform/limits/) hold: a
57-statement of at most 100,000 bytes, at most 100 bound parameters, at most 100
58-columns in a table, and a string, a `BLOB`, or a row of at most 2,200,000
59-bytes.
41+celld enforces these
42+[D1 limits](https://developers.cloudflare.com/d1/platform/limits/): a statement
43+of at most 100,000 bytes, at most 100 bound parameters, at most 100 columns in a
44+table, and a string, a `BLOB`, or a row of at most 2,200,000 bytes.
6045
61-## One database is one cell
46+A prepared statement that holds a second statement fails with
47+`A prepared SQL statement must contain only one statement.` Use `exec()` or
48+`batch()` for more than one statement. Both run inside one transaction, so a
49+failure rolls back the whole call.
6250
63-A celld D1 database is a cell, which is the same single-threaded actor that
64-runs a Durable Object. One node of the fleet owns a cell at a time, so a query
65-leaves the Worker's isolate and celld routes it to the owner node. A statement
66-therefore costs one cell dispatch, and a larger fleet does not make that
67-dispatch cheaper. celld materializes the result inside the cell and then copies
68-it into the calling isolate, so a result carries at most 100,000 rows or
69-32 MiB.
70-`first()` keeps one row on the cell side, so a `first()` cannot reach the row
71-cap.
51+Every statement goes to the node that owns the database cell, so each call costs
52+one cell dispatch. Group related statements in one `batch()`, which costs one
53+dispatch for all of them. The 100,000-row result cap does not apply to
54+`first()`. An acknowledged write survives the loss of the owner
55+node.
7256
73-A cell holds one SQLite file and has one writer. Two statements against one
74-database therefore run one after the other, even when they touch different
75-tables. More nodes do not divide that work, because the database has one owner.
76-An application that needs more write capacity uses more databases, and
77-[Cloudflare recommends the same many-database shape](https://developers.cloudflare.com/d1/)
78-for the same reason.
57+`withSession()` always selects the primary. `getBookmark()` returns
58+`celld:primary`, `meta.served_by_primary` is always `true`, and
59+`meta.served_by_region` is always `local`.
7960
80-Cloudflare gives a database one primary instance and asynchronous
81-[read replicas](https://developers.cloudflare.com/d1/best-practices/read-replication/)
82-across its network, and its Sessions API uses a bookmark to keep a session
83-sequentially consistent. celld has one cell and no replica. `withSession()`
84-therefore works and always selects the primary, `getBookmark()` returns the
85-stable token `celld:primary` after a query, and every read already observes
86-every committed write. `meta.served_by_primary` is therefore always `true` and
87-`meta.served_by_region` is always `local`. A celld read cannot become faster
88-near a user, because celld has no replica that can serve it.
89-
90-![Three run calls from one Worker cross the node boundary three times and take three cell turns, while one batch call from another Worker crosses once and runs inside one BEGIN and COMMIT, after which a read answers from the cell's own SQLite and a write waits for LTX to reach the fleet bucket](d1-flow.svg)
91-
92-## Batches, transactions, and durability
93-
94-`batch()` takes an array of prepared statements, sends them to the cell in one
95-dispatch, and runs them inside one `BEGIN IMMEDIATE ... COMMIT`. A failure
96-rolls the whole batch back, so a batch is all or nothing, and the call returns
97-one result for each statement in the order of the array. `exec()` uses the same
98-bracket, therefore a failing line in a multi-statement import rolls the import
99-back whole. Both behaviors match
100-[Cloudflare's batch semantics](https://developers.cloudflare.com/d1/worker-api/d1-database/).
101-
102-A batch is also one round trip and one cell turn. Three separate `run()` calls
103-cost three dispatches to the owner node, and one `batch()` of those three
104-statements costs one. Group the statements that belong together, because the
105-grouping removes two boundary crossings and makes the three writes atomic.
106-
107-An application cannot open its own transaction. celld denies `BEGIN`, `COMMIT`,
108-`ROLLBACK`, and `SAVEPOINT` in application SQL, because a D1 call owns the
109-transaction bracket and must never hand an open transaction back to the Worker.
110-`batch()` and `exec()` are therefore the transaction primitives. celld also
111-denies `ATTACH`, `DETACH`, `VACUUM`, `load_extension()`, and a temporary table,
112-index, trigger, or view. celld allows the `fts5` and `fts5vocab` virtual tables
113-that D1 allows, and it accepts a `PRAGMA` allowlist that covers the list in the
61+Application SQL cannot use `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `ATTACH`,
62+`DETACH`, `VACUUM`, `load_extension()`, or a temporary table, index, trigger, or
63+view. celld allows the `fts5` and `fts5vocab` virtual tables, and it accepts the
64+`PRAGMA` list in the
11465 [D1 SQL statement reference](https://developers.cloudflare.com/d1/sql-api/sql-statements/).
11566
116-celld acknowledges a write only after the cell's output gate releases it. The
117-cell writes its SQLite changes to the fleet bucket as LTX transaction files, so
118-an acknowledged D1 write survives the loss of the owner node and restores on
119-another node. That durability is the durability of the object store that the
120-operator runs, and it is not the durability of Cloudflare D1. A read needs no
121-such step, because the cell answers it from the SQLite file that it already
122-holds.
67+`celld d1 execute` and `celld d1 migrations apply` run SQL from the command line
68+through a live node.
12369
124-`celld d1 execute` and `celld d1 migrations apply` reach a database from the
125-command line. They find a live node through the fleet bucket and send the SQL
126-over the same dispatch path that `env.DB` uses, so the CLI never writes the
127-SQLite file behind the owner's back.
128-
12970 ## Differences from Cloudflare
13071
13172 - A binding result can contain at most 100,000 rows or 32 MiB.
deleteddocs/services/durable-object-facets-flow.svg+0−126
@@ -1,126 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 372" role="img">
2- <title>Several facets share one cell, one owner node, and one owner record, while separate Durable Objects each take their own owner record and node</title>
3- <desc>Two arrangements of the same three application databases. On the left, a
4-Worker calls one supervisor cell on node B at epoch e4. That single cell holds
5-the supervisor's SQLite database and, in separate databases beside it, the
6-facets app-a and app-b. One owner record covers all of them, and each database
7-replicates as a stream under cells/acct-9/ltx/e4/, so the call takes one hop. On the right, the same three databases are three separate Durable Object
8-cells on nodes B, C, and A. Each cell holds its own owner record and its own
9-epoch, and the three replicate under three prefixes, so a call takes a hop and
10-an output gate for each object.</desc>
11- <style>
12- .d-ink { color: #121212 }
13- .d-soft { color: #3d3b37 }
14- .d-faint { color: #6e6a62 }
15- .d-acc { color: #10803f }
16- .d-panel { color: #ffffff }
17- .d-sunk { color: #f0eee8 }
18- .d-tint { color: #d6efdf }
19- text {
20- font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
21- font-size: 13px;
22- fill: currentColor;
23- }
24- tspan { fill: currentColor; }
25- @media (prefers-color-scheme: dark) {
26- .d-ink { color: #efede7 }
27- .d-soft { color: #c9c6be }
28- .d-faint { color: #928e85 }
29- .d-acc { color: #3fc472 }
30- .d-panel { color: #1a1a19 }
31- .d-sunk { color: #232321 }
32- .d-tint { color: #10301d }
33- }
34- </style>
35- <defs>
36- <marker id="facet-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
37- markerHeight="6" orient="auto-start-reverse">
38- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
39- </marker>
40- </defs>
41-
42- <!-- Column captions: one object with facets, against separate objects. -->
43- <text class="d-ink" fill="currentColor" x="110" y="14" text-anchor="middle">one object, two facets</text>
44- <text class="d-ink" fill="currentColor" x="330" y="14" text-anchor="middle">three separate objects</text>
45-
46- <!-- The same caller in both arrangements. -->
47- <rect class="d-panel" fill="currentColor" x="6" y="24" width="208" height="32" rx="6" />
48- <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="24" width="208" height="32" rx="6" />
49- <text class="d-soft" fill="currentColor" x="110" y="45" text-anchor="middle">Worker</text>
50-
51- <rect class="d-panel" fill="currentColor" x="226" y="24" width="208" height="32" rx="6" />
52- <rect class="d-soft" fill="none" stroke="currentColor" x="226" y="24" width="208" height="32" rx="6" />
53- <text class="d-soft" fill="currentColor" x="330" y="45" text-anchor="middle">Worker</text>
54-
55- <!-- One dispatch on the left; one dispatch for each object on the right. -->
56- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
57- <path d="M110 56 V74" marker-end="url(#facet-arrow)" />
58- <path d="M330 56 V66 H234 V219" />
59- <path d="M234 99 H246" marker-end="url(#facet-arrow)" />
60- <path d="M234 159 H246" marker-end="url(#facet-arrow)" />
61- <path d="M234 219 H246" marker-end="url(#facet-arrow)" />
62- </g>
63-
64- <!-- One cell, one owner, one epoch, and two private databases inside it. -->
65- <rect class="d-tint" fill="currentColor" x="6" y="74" width="208" height="172" rx="6" />
66- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="6" y="74" width="208" height="172" rx="6" />
67- <text class="d-ink" fill="currentColor" x="110" y="95" text-anchor="middle">supervisor cell</text>
68- <text class="d-soft" fill="currentColor" x="110" y="112" text-anchor="middle">node B · epoch e4</text>
69-
70- <rect class="d-sunk" fill="currentColor" x="16" y="122" width="188" height="34" rx="6" />
71- <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="122" width="188" height="34" rx="6" />
72- <text class="d-ink" fill="currentColor" x="110" y="144" text-anchor="middle">supervisor SQLite</text>
73-
74- <g class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4">
75- <path d="M16 168 H46" />
76- <path d="M174 168 H204" />
77- </g>
78- <text class="d-faint" fill="currentColor" x="110" y="172" text-anchor="middle">separate databases</text>
79-
80- <rect class="d-sunk" fill="currentColor" x="16" y="180" width="90" height="56" rx="6" />
81- <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="180" width="90" height="56" rx="6" />
82- <text class="d-ink" fill="currentColor" x="61" y="202" text-anchor="middle">facet app-a</text>
83- <text class="d-soft" fill="currentColor" x="61" y="221" text-anchor="middle">own SQLite</text>
84-
85- <rect class="d-sunk" fill="currentColor" x="114" y="180" width="90" height="56" rx="6" />
86- <rect class="d-soft" fill="none" stroke="currentColor" x="114" y="180" width="90" height="56" rx="6" />
87- <text class="d-ink" fill="currentColor" x="159" y="202" text-anchor="middle">facet app-b</text>
88- <text class="d-soft" fill="currentColor" x="159" y="221" text-anchor="middle">own SQLite</text>
89-
90- <!-- The same three databases as three cells, each with its own owner. -->
91- <rect class="d-panel" fill="currentColor" x="246" y="74" width="176" height="50" rx="6" />
92- <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="74" width="176" height="50" rx="6" />
93- <text class="d-ink" fill="currentColor" x="334" y="95" text-anchor="middle">APP-A cell · node B</text>
94- <text class="d-soft" fill="currentColor" x="334" y="112" text-anchor="middle">own owner record · e4</text>
95-
96- <rect class="d-panel" fill="currentColor" x="246" y="134" width="176" height="50" rx="6" />
97- <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="134" width="176" height="50" rx="6" />
98- <text class="d-ink" fill="currentColor" x="334" y="155" text-anchor="middle">APP-B cell · node C</text>
99- <text class="d-soft" fill="currentColor" x="334" y="172" text-anchor="middle">own owner record · e9</text>
100-
101- <rect class="d-panel" fill="currentColor" x="246" y="194" width="176" height="50" rx="6" />
102- <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="194" width="176" height="50" rx="6" />
103- <text class="d-ink" fill="currentColor" x="334" y="215" text-anchor="middle">APP-C cell · node A</text>
104- <text class="d-soft" fill="currentColor" x="334" y="232" text-anchor="middle">own owner record · e2</text>
105-
106- <!-- One stream against three streams. -->
107- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
108- <path d="M110 246 V272" marker-end="url(#facet-arrow)" />
109- <path d="M422 99 H428 V264 H330 V272" marker-end="url(#facet-arrow)" />
110- <path d="M422 159 H428" />
111- <path d="M422 219 H428" />
112- </g>
113-
114- <rect class="d-sunk" fill="currentColor" x="6" y="272" width="208" height="52" rx="6" />
115- <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="272" width="208" height="52" rx="6" />
116- <text class="d-ink" fill="currentColor" x="110" y="293" text-anchor="middle">cells/acct-9/ltx/e4/</text>
117- <text class="d-soft" fill="currentColor" x="110" y="311" text-anchor="middle">a stream per database</text>
118-
119- <rect class="d-sunk" fill="currentColor" x="226" y="272" width="208" height="52" rx="6" />
120- <rect class="d-soft" fill="none" stroke="currentColor" x="226" y="272" width="208" height="52" rx="6" />
121- <text class="d-ink" fill="currentColor" x="330" y="293" text-anchor="middle">three bucket prefixes</text>
122- <text class="d-soft" fill="currentColor" x="330" y="311" text-anchor="middle">three epochs</text>
123-
124- <text class="d-faint" fill="currentColor" x="110" y="348" text-anchor="middle">one hop, one owner record</text>
125- <text class="d-faint" fill="currentColor" x="330" y="348" text-anchor="middle">a hop and a gate for each</text>
126-</svg>
modifieddocs/services/durable-object-facets.md+80−70View file
@@ -1,14 +1,11 @@
11 # Durable Object Facets
22
3-A facet is a child object inside a Durable Object. A supervisor class starts a
4-facet from a class that a [Worker Loader](dynamic-workers.md) provides, and the
5-supervisor and the facet then keep separate SQLite databases. An application
6-uses a facet to give generated or untrusted code durable storage without giving
7-that code a Durable Object namespace. The database of a facet replicates beside
8-the database of its root object, and the facet shares the ownership of the root
9-object. Read the
3+A facet is a child object inside a Durable Object, with a SQLite database of
4+its own. A supervisor class starts a facet from a class that a
5+[Worker Loader](dynamic-workers.md) provides, so generated or untrusted code
6+gets durable storage without a Durable Object namespace. Read the
107 [Cloudflare Durable Object Facets documentation](https://developers.cloudflare.com/dynamic-workers/usage/durable-object-facets/)
11-for the standard API behavior.
8+for the standard API.
129
1310 ## Example
1411
@@ -17,83 +14,93 @@
1714
1815 <!-- celld-example: facets -->
1916
17+## API
18+
19+- `ctx.facets.get(name, callback)` returns a stub for the named facet. The
20+ callback returns `{ class, id }`, and celld runs it only to start the facet.
21+- `worker.getDurableObjectClass("App")` on a Worker Loader binding, or
22+ `ctx.exports.App`, supplies the `class`.
23+- `ctx.exports.App({ props })` creates a class handle with startup properties.
24+- `ctx.facets.abort(name, reason)` stops a facet and keeps its database.
25+- `ctx.facets.delete(name)` stops a facet and removes its database.
26+- The stub answers `fetch()` and the RPC methods of the class.
27+
2028 ## A facet is a part of its root object
2129
22-A facet is not a cell. celld keeps the SQLite database of a facet in a file of
23-its own, and it replicates that file as a stream of its own under the bucket
24-prefix of the root cell. A facet owns no ownership record and no fencing epoch.
25-It inherits both from the root cell, and its stream uses the epoch of the root
26-cell. The
30+A facet is not a cell. It has no ownership record and no fencing epoch of its
31+own, and it uses those of the root cell, which the
2732 [Durable Objects page](durable-objects.md#ownership-and-the-single-threaded-model)
28-describes that record and that epoch.
33+describes.
2934
30-Containment also sets the lifecycle. A facet starts inside an event of the root
31-object, therefore the code of the facet runs on the node that owns the root
32-cell. celld releases every running facet when it releases the root cell, and the
33-startup callback runs again at the next call. An eviction, a reset, and a move
34-of ownership take the root object and its facets as one group, so a move proves
35-the stream of each facet before the new owner opens the root cell.
35+A facet runs on the owner node of the root cell. An eviction, a reset, and a
36+move take the root object and its facets as one group, and the startup
37+callback runs again at the next call.
3638
37-The storage of a facet is independent of the storage of its root object, as in
38-workerd. A write of a facet commits in the database of the facet, so a rollback
39-of a root storage transaction does not undo a facet call inside it. celld holds
40-an outbound effect of a facet, and the reply of a facet call, until the stream
41-of the facet proves the writes of that call. The effect also passes the output
42-gate of the root cell, because it can reveal what the root object showed the
43-facet.
39+As in workerd, a facet write commits in the database of the facet, so a
40+rollback of a root transaction does not undo a facet call inside it. A facet
41+and its root object therefore never commit atomically. celld holds an outbound
42+effect of a facet, and the reply of a facet call, until the facet stream proves
43+the writes of that call. The effect also passes the output gate of the root
44+cell.
4445
45-![Several facets share one cell, one owner node, and one replication stream, while separate Durable Objects each take their own owner record and node](durable-object-facets-flow.svg)
46-
4746 ## Starting and addressing a facet
4847
49-`ctx.facets.get(name, callback)` returns a stub for the facet with that name,
50-and celld runs the callback only when the facet is not already running. The
51-callback takes no argument and returns a `class` and an optional `id`. `class`
52-is a `DurableObjectClass`, and two sources supply one. The first source is
53-`worker.getDurableObjectClass("App")` on a Worker Loader binding. The second is
54-`ctx.exports.App` for a `DurableObject` class that the Worker exports without a
55-storage migration, and that facet runs in the isolate of its root.
48+`ctx.facets.get(name, callback)` returns a stub, and celld runs the callback
49+only when the facet is not already running. The callback returns a `class` and
50+an optional `id`. The `class` comes from
51+`worker.getDurableObjectClass("App")` on a Worker Loader binding, or from
52+`ctx.exports.App` for an exported `DurableObject` class without a storage
53+migration; that facet runs in the isolate of its root.
5654
57-`id` sets the value of `ctx.id` in the facet. A `DurableObjectId` keeps its
58-name, so an ID from `idFromName("child")` exposes `ctx.id.name === "child"`.
59-A string ID stays a string, and an omitted ID inherits the parent ID and its
60-name. An unmigrated class handle has no `idFromName()` method, so use a
61-Durable Object namespace to create a named ID.
55+A loaded class can extend `DurableObject`, or it can be a plain class with a
56+`(state, env)` constructor. A plain class answers `fetch()`, and its RPC
57+methods require the `js_rpc` compatibility flag, as on workerd.
6258
59+`id` sets `ctx.id` in the facet. A `DurableObjectId` keeps its name, a string
60+ID stays a string, and an omitted ID inherits the parent ID and its name. An
61+unmigrated class handle has no `idFromName()`, so use a Durable Object
62+namespace to create a named ID.
63+
6364 `ctx.exports.App({ props })` creates a class handle with startup properties.
64-The call copies the properties, so later changes to the original object do
65-not change `ctx.props` in the facet. The properties must be an object that
66-supports structured cloning. A loopback class without properties supplies an
67-empty object, and the facet constructor can read the properties.
65+The call copies the properties, so a later change to the object does not
66+reach `ctx.props`. The properties must support structured cloning. A
67+loopback class without properties supplies an empty object.
6868
69-The name alone selects the database, so a later call that keeps the name and
70-changes the `id` still reaches the stored data. A name has a limit of 256 bytes.
71-A facet can start a facet of its own, to a total depth of 4 that counts the root
72-object. `ctx.facets.abort(name, reason)` stops a running facet and keeps its
73-database, and a call on the stopped stub then throws the given reason.
74-`ctx.facets.delete(name)` stops the facet and removes its database and the
75-database of every facet below it. The stub answers `fetch()` and the RPC methods
76-of the class. The stub itself is not a promise, and a pipelined property path is
77-unavailable, so a call must name one method.
69+- The name alone selects the database, so a changed `id` still reaches the
70+ stored data. A name has a limit of 256 bytes.
71+- A facet can start facets of its own, to a total depth of 4 that counts the
72+ root object.
73+- `ctx.facets.abort(name, reason)` stops a facet and keeps its database. A
74+ call on the stopped stub throws the reason.
75+- `ctx.facets.delete(name)` stops the facet and removes its database and the
76+ database of every facet below it.
7877
79-## Choose a facet or a second Durable Object
78+No name reaches a facet from outside its root object, so external traffic
79+must go through the supervisor. Use a separate Durable Object, addressed with
80+[`idFromName()`](durable-objects.md#identity-and-addressing), when children
81+must run on different nodes.
8082
81-Use a facet when the child state belongs to the parent. The supervisor sits on
82-the path of every call, so it can count a call, apply a quota, and refuse a
83-request before the child code runs. The facet stays on the owner node of the
84-root cell, therefore a call from the supervisor crosses no node boundary and
85-needs no second ownership record. A facet and its root object do not commit
86-atomically, because each database proves its own writes. An application that
87-needs one atomic commit must keep that state in one database.
83+## WebSockets in a facet
8884
89-Use a separate Durable Object when the children must scale apart. Each object
90-then takes its own id, its own ownership record, and its own owner node, so the
91-fleet can place two of them on two machines and the stop of one node affects one
92-of them. A caller can also address such an object directly with
93-[`idFromName()`](durable-objects.md#identity-and-addressing). No name reaches a
94-facet from outside its root object, and a facet that must serve external traffic
95-therefore needs a supervisor that forwards the request.
85+A facet can accept a WebSocket: its `fetch()` returns a `101` response with the
86+client end of a `WebSocketPair`, and the root object returns that response. The
87+facet can call `accept()` on the server end or pass it to
88+`ctx.acceptWebSocket()`. A facet can also open a WebSocket with
89+`new WebSocket(url)` or with an `Upgrade: websocket` fetch. celld delivers the
90+events of each such socket to the facet, not to the root object. Socket output
91+waits for the facet stream and passes the output gate of the root cell.
9692
93+A facet socket does not hibernate, because celld cannot start a facet again
94+without its root object. A socket that the facet accepts or opens keeps the root
95+cell resident until it closes. The client end of a `101` response from another
96+Durable Object does not. `getWebSockets()` returns the sockets of that facet.
97+
98+`ctx.facets.abort()` and `ctx.facets.delete()` close the sockets of each stopped
99+facet with code `1001`, and the facet receives no close event. workerd drops the
100+connection instead, so its client sees `1006`. A drain, an ownership move, or a
101+generation swap closes a facet socket with `1012`, and an output gate failure
102+closes it with `1011`.
103+
97104 ## Differences from Cloudflare
98105
99106 - A Durable Object binding cannot supply a facet class. A class with a storage
@@ -103,7 +110,10 @@
103110 separate stream under the bucket prefix of the root Durable Object.
104111 - A facet cannot set an alarm. `storage.setAlarm()` throws inside a facet, so
105112 the root object must hold the schedule.
106-- A facet stub is not awaitable, and a pipelined property path is unavailable.
113+- A facet socket does not hibernate. It keeps the root cell resident until the
114+ socket closes.
115+- A facet stub is not awaitable, and a pipelined property path is unavailable,
116+ so a call must name one method.
107117 - The `clone()` method is unavailable.
108118
109119 The [Cloudflare compatibility](../cloudflare-compat.md#services)
deleteddocs/services/durable-objects-flow.svg+0−127
@@ -1,127 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 520" role="img" aria-labelledby="doFlowTitle doFlowDesc">
2- <title id="doFlowTitle">One name reaches one cell, and one node owns that cell</title>
3- <desc id="doFlowDesc">Workers on node A and node B both address the name room-7,
4-and a Worker on node C addresses the name room-8. getByName turns each name into
5-one 64-digit hexadecimal id, the owner record in the fleet bucket names one
6-owner node for each cell, and celld forwards the call to that node. The room-7
7-cell has owner node B and epoch e7, and the room-8 cell has owner node C and
8-epoch e3, so ownership belongs to a cell and not to a class. Each cell runs one
9-event at a time. The room-7 cell keeps its own SQLite database on node B. Node B
10-sends each write to a follower node, whose fsync releases the answer, and the
11-write then uploads to the fleet bucket under cells/room-7/ltx/e7/. The previous
12-prefix, cells/room-7/ltx/e6/, is superseded, so a node that lost the cell cannot
13-damage the current data. Node C keeps the room-8 cell the same way, under its
14-own epoch.</desc>
15- <style>
16- .d-ink { color: #121212 }
17- .d-soft { color: #3d3b37 }
18- .d-faint { color: #6e6a62 }
19- .d-acc { color: #10803f }
20- .d-panel { color: #ffffff }
21- .d-sunk { color: #f0eee8 }
22- .d-tint { color: #d6efdf }
23- text {
24- font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
25- font-size: 13px;
26- fill: currentColor;
27- }
28- @media (prefers-color-scheme: dark) {
29- .d-ink { color: #efede7 }
30- .d-soft { color: #c9c6be }
31- .d-faint { color: #928e85 }
32- .d-acc { color: #3fc472 }
33- .d-panel { color: #1a1a19 }
34- .d-sunk { color: #232321 }
35- .d-tint { color: #10301d }
36- }
37- </style>
38- <defs>
39- <marker id="do-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
40- markerHeight="6" orient="auto-start-reverse">
41- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
42- </marker>
43- </defs>
44-
45- <!-- Callers: three nodes, two of them addressing one name. -->
46- <rect class="d-panel" fill="currentColor" x="6" y="8" width="136" height="48" rx="6" />
47- <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="8" width="136" height="48" rx="6" />
48- <text class="d-ink" fill="currentColor" x="74" y="29" text-anchor="middle">Worker · node A</text>
49- <text class="d-soft" fill="currentColor" x="74" y="46" text-anchor="middle">name: "room-7"</text>
50-
51- <rect class="d-panel" fill="currentColor" x="152" y="8" width="136" height="48" rx="6" />
52- <rect class="d-soft" fill="none" stroke="currentColor" x="152" y="8" width="136" height="48" rx="6" />
53- <text class="d-ink" fill="currentColor" x="220" y="29" text-anchor="middle">Worker · node B</text>
54- <text class="d-soft" fill="currentColor" x="220" y="46" text-anchor="middle">name: "room-7"</text>
55-
56- <rect class="d-panel" fill="currentColor" x="298" y="8" width="136" height="48" rx="6" />
57- <rect class="d-soft" fill="none" stroke="currentColor" x="298" y="8" width="136" height="48" rx="6" />
58- <text class="d-ink" fill="currentColor" x="366" y="29" text-anchor="middle">Worker · node C</text>
59- <text class="d-soft" fill="currentColor" x="366" y="46" text-anchor="middle">name: "room-8"</text>
60-
61- <!-- The boundary each call crosses: name to id, owner record, forward. -->
62- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
63- x="6" y="72" width="428" height="62" rx="6" />
64- <text class="d-faint" fill="currentColor" x="220" y="92" text-anchor="middle">getByName() gives one 64-hex id</text>
65- <text class="d-faint" fill="currentColor" x="220" y="111" text-anchor="middle">the owner record in the bucket names one node</text>
66- <text class="d-faint" fill="currentColor" x="220" y="130" text-anchor="middle">celld forwards the call to that node</text>
67-
68- <!-- Two callers of one name join. A second name is a second cell. -->
69- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
70- <path d="M74 56 V66" />
71- <path d="M220 56 V66" />
72- <path d="M60 66 H220" />
73- <path d="M60 66 V152" marker-end="url(#do-arrow)" />
74- <path d="M366 56 V66 H380 V152" marker-end="url(#do-arrow)" />
75- </g>
76-
77- <!-- One cell, one owner, one event. Ownership belongs to a cell, not a class. -->
78- <rect class="d-tint" fill="currentColor" x="16" y="156" width="200" height="90" rx="6" />
79- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="156" width="200" height="90" rx="6" />
80- <text class="d-ink" fill="currentColor" x="116" y="177" text-anchor="middle">room-7 cell</text>
81- <text class="d-soft" fill="currentColor" x="116" y="196" text-anchor="middle">owner: node B</text>
82- <text class="d-soft" fill="currentColor" x="116" y="215" text-anchor="middle">one event at a time</text>
83- <text class="d-faint" fill="currentColor" x="116" y="234" text-anchor="middle">epoch e7</text>
84-
85- <rect class="d-tint" fill="currentColor" x="224" y="156" width="200" height="90" rx="6" />
86- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="224" y="156" width="200" height="90" rx="6" />
87- <text class="d-ink" fill="currentColor" x="324" y="177" text-anchor="middle">room-8 cell</text>
88- <text class="d-soft" fill="currentColor" x="324" y="196" text-anchor="middle">owner: node C</text>
89- <text class="d-soft" fill="currentColor" x="324" y="215" text-anchor="middle">one event at a time</text>
90- <text class="d-faint" fill="currentColor" x="324" y="234" text-anchor="middle">epoch e3</text>
91-
92- <!-- The owner holds the database, and the write then buys its durability. -->
93- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
94- <path d="M116 246 V272" marker-end="url(#do-arrow)" />
95- <path d="M116 322 V346" marker-end="url(#do-arrow)" />
96- <path d="M116 396 V420" marker-end="url(#do-arrow)" />
97- </g>
98-
99- <rect class="d-sunk" fill="currentColor" x="16" y="276" width="200" height="46" rx="6" />
100- <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="276" width="200" height="46" rx="6" />
101- <text class="d-ink" fill="currentColor" x="116" y="297" text-anchor="middle">SQLite on node B</text>
102- <text class="d-soft" fill="currentColor" x="116" y="314" text-anchor="middle">one database per cell</text>
103-
104- <rect class="d-sunk" fill="currentColor" x="16" y="350" width="200" height="46" rx="6" />
105- <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="350" width="200" height="46" rx="6" />
106- <text class="d-ink" fill="currentColor" x="116" y="371" text-anchor="middle">a follower node</text>
107- <text class="d-soft" fill="currentColor" x="116" y="388" text-anchor="middle">fsync frees the answer</text>
108-
109- <text class="d-faint" fill="currentColor" x="326" y="297" text-anchor="middle">node C keeps room-8</text>
110- <text class="d-faint" fill="currentColor" x="326" y="316" text-anchor="middle">the same way, under</text>
111- <text class="d-faint" fill="currentColor" x="326" y="335" text-anchor="middle">its own epoch</text>
112-
113- <!-- The epoch in the prefix is the fence. -->
114- <rect class="d-sunk" fill="currentColor" x="6" y="424" width="428" height="90" rx="6" />
115- <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="424" width="428" height="90" rx="6" />
116- <text class="d-ink" fill="currentColor" x="220" y="444" text-anchor="middle">fleet bucket · the long-term copy</text>
117-
118- <rect class="d-tint" fill="currentColor" x="18" y="454" width="200" height="48" rx="6" />
119- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="18" y="454" width="200" height="48" rx="6" />
120- <text class="d-ink" fill="currentColor" x="118" y="474" text-anchor="middle">cells/room-7/ltx/e7/</text>
121- <text class="d-soft" fill="currentColor" x="118" y="492" text-anchor="middle">this owner writes here</text>
122-
123- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
124- x="222" y="454" width="200" height="48" rx="6" />
125- <text class="d-faint" fill="currentColor" x="322" y="474" text-anchor="middle">cells/room-7/ltx/e6/</text>
126- <text class="d-faint" fill="currentColor" x="322" y="492" text-anchor="middle">an old owner is fenced</text>
127-</svg>
modifieddocs/services/durable-objects.md+71−112View file
@@ -1,13 +1,10 @@
11 # Durable Objects / Cells
22
3-A Durable Object is a single-threaded actor with durable storage, and celld
4-calls each running Durable Object a cell. An application uses one when a piece
5-of state needs a single consistent owner, such as a chat room, a game match, a
6-shopping cart, an agent session, or a rate limiter. The state lives in a SQLite
7-database that belongs to that object alone, on the node that serves it, and
8-celld replicates the database to the fleet. Read the
3+A Durable Object is a single-threaded actor with its own SQLite database, and
4+celld calls each running Durable Object a cell. celld replicates the database
5+to the fleet. Read the
96 [Cloudflare Durable Objects documentation](https://developers.cloudflare.com/durable-objects/)
10-for the standard API behavior.
7+for the standard API.
118
129 ## Example
1310
@@ -17,129 +14,91 @@
1714
1815 <!-- celld-example: counter -->
1916
20-## Identity and addressing
17+## API
2118
22-A `durable_objects` binding exposes one class as a namespace, and an
23-application reaches an object in two steps. `env.COUNTER.idFromName("room-7")`
24-returns a `DurableObjectId`, and `env.COUNTER.get(id)` returns a
25-`DurableObjectStub`. `getByName("room-7")` performs both steps together. The
26-stub is only a handle, so celld creates the object at the first call and not at
27-`get()`. Read the
28-[Durable Object ID documentation](https://developers.cloudflare.com/durable-objects/api/id/)
29-for the complete method list.
19+- `env.COUNTER.idFromName(name)` returns an id, and `env.COUNTER.get(id)`
20+ returns a stub. `getByName(name)` performs both steps.
21+- `newUniqueId()` and `idFromString()` create and parse a random id.
22+- `ctx.storage.get()`, `put()`, `delete()`, `list()`, and `deleteAll()` are
23+ the key-value methods.
24+- `ctx.storage.sql.exec()` runs SQL on the database of the object.
25+- `transaction()` and `transactionSync()` group several writes.
26+- `storage.setAlarm()`, `getAlarm()`, and `deleteAlarm()` manage one alarm per
27+ object, and celld calls the `alarm(alarmInfo)` handler.
28+- `ctx.acceptWebSocket()` accepts a hibernatable WebSocket, and celld calls
29+ `webSocketMessage()` for each frame.
30+- `blockConcurrencyWhile()` closes the input gate.
31+- `storage.sync()` waits for the durability of the earlier committed writes.
3032
31-`idFromName()` is deterministic. celld derives the id with HMAC-SHA-256 over
32-the name, under a key that belongs to the namespace, so one name always gives
33-the same 64-digit hexadecimal id. That id always reaches the same object, and
34-two Workers on two different nodes that use one name therefore reach one
35-object. The name also survives in `ctx.id.name` when it is 1024 UTF-8 bytes or
36-less, which is the Cloudflare rule, and a longer name still routes to the
37-correct object.
33+## Identity and addressing
3834
39-`newUniqueId()` instead draws random bytes, so its object carries no name and
40-no later caller can address it again. Keep the `toString()` form of such an id
41-if the application must reach the object a second time. `idFromString()` parses
42-that hexadecimal form and verifies the HMAC, therefore celld refuses an id that
43-belongs to a different namespace instead of creating an unrelated object.
35+celld creates the object at the first call on a stub, not at `get()`.
4436
45-celld builds the key of a namespace from the script name and the class name, so
46-a rename of the Worker script changes every id that the namespace derives. The
47-objects of the old name keep their storage under the old ids, and the renamed
48-script reaches new and empty objects. Keep the script name stable, or migrate
49-the data before the rename.
37+`idFromName()` derives a 64-digit hexadecimal id with HMAC-SHA-256 over the
38+name, under a key that celld builds from the script name and the class name.
39+One name therefore reaches one object from every node. `ctx.id.name` holds the
40+name when it is 1024 UTF-8 bytes or less, as on Cloudflare; a longer name still
41+routes correctly.
5042
51-celld implements no jurisdiction, because a celld fleet has only the machines
52-that you run. `newUniqueId({ jurisdiction })` and `namespace.jurisdiction()`
53-throw an error, so an application learns about the gap at the call site.
43+`newUniqueId()` draws random bytes, so keep its `toString()` form to reach the
44+object again. `idFromString()` verifies the HMAC, so celld refuses an id from a
45+different namespace.
5446
47+A rename of the Worker script therefore reaches new, empty objects, and the old
48+objects keep their storage under the old ids.
49+
5550 ## Ownership and the single-threaded model
5651
57-Cloudflare creates an object near the first request that uses it, and
58-Cloudflare can migrate the object afterwards. celld makes no placement,
59-migration, or jurisdiction promise, and it makes one narrower promise instead:
60-exactly one node serves a cell at a time.
52+Exactly one node serves a cell at a time. A node claims a cell with a
53+conditional write of an ownership record to the fleet bucket. Each activation
54+advances a fencing epoch that appears in the storage prefix, so a node that
55+lost the cell writes only into a superseded prefix. The
56+[guarantees](../guarantees.md) page gives the full mechanism. celld forwards
57+each stub call to the owner node.
6158
62-A node claims a cell by writing an ownership record into the fleet bucket with
63-a conditional write. The object store accepts only one of two competing
64-writers, so two nodes cannot own one cell. Every activation advances a fencing
65-epoch, and the epoch appears in the storage prefix, therefore a node that lost
66-the cell writes only into a superseded prefix. The
67-[guarantees](../guarantees.md) page gives the full mechanism.
59+Inside the cell, one synchronous turn runs at a time. An event that awaits can
60+overlap another event unless `blockConcurrencyWhile()` closes the input gate.
61+celld holds a response until a durability proof covers every write that the
62+response can reveal, as the Cloudflare
63+[output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/)
64+does, so an application does not have to `await` a `put()`.
6865
69-A Worker holds its stub on whichever node served the request. celld resolves
70-the owner of the cell and forwards the call to that node, so the object code
71-runs on the owner and nowhere else. Inside the cell, one synchronous turn runs
72-at a time. An event that awaits can overlap another event unless
73-`blockConcurrencyWhile()` closes the input gate. celld also
74-holds a response until a durability proof covers every write that the response
75-can reveal, which is the behavior Cloudflare calls the
76-[output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/).
77-An application therefore does not have to `await` a `put()`, because a client
78-cannot receive the response before the write survives a failure. The same gate
79-holds a WebSocket frame, and it holds each frame only for its own proof.
80-Therefore a `webSocketMessage()` handler that sends a frame and then awaits
81-delivers that frame while it still runs, and an application can stream an
82-answer through one handler.
83-On one socket, celld starts the message handlers in arrival order, but it does
84-not wait for a handler to finish before starting the next handler. Therefore
85-an incoming message can cancel work that an earlier handler awaits.
86-A hibernatable socket delivers the frames in send order across WebSocket
87-handlers and RPC methods, even when the output gate delays an earlier frame.
66+The output gate holds each WebSocket frame only for its own proof, so a
67+`webSocketMessage()` handler that sends and then awaits delivers that frame
68+while it runs. On one socket, celld starts message handlers in arrival order
69+but does not wait for one to finish before the next starts, so an incoming
70+message can cancel work that an earlier handler awaits. A hibernatable socket
71+delivers frames in send order across WebSocket handlers and RPC methods.
8872
89-![Two Workers on different nodes address the name room-7, the owner record in the fleet bucket names one owner node, celld forwards both calls to that node, and the cell replicates through a follower node into an epoch-fenced bucket prefix](durable-objects-flow.svg)
73+A cell keeps no in-memory state across an eviction, so the constructor runs
74+again at the next event. Ownership can also move when a node stops or drains,
75+or when idle rebalancing moves a hibernated cell. A hibernatable WebSocket
76+survives hibernation on the same node, and it closes when the cell moves, so
77+the client must reconnect.
9078
91-A cell keeps no in-memory state across an eviction. celld removes an idle cell
92-from memory, and the cell then hibernates on its node or becomes inactive in
93-the bucket, so the constructor runs again at the next event. Ownership can move
94-as well, because a node can stop, a node can drain, and idle rebalancing can
95-move a hibernated cell to another node. A reader must therefore treat only
96-durable storage as persistent. A hibernatable WebSocket survives a hibernation
97-on the same node, and it closes when the cell moves to a new owner, so a client
98-must reconnect. Cloudflare gives the same rule for
99-[in-memory state](https://developers.cloudflare.com/durable-objects/reference/in-memory-state/).
100-
10179 ## Durable storage and alarms
10280
103-`ctx.storage` gives each object its own SQLite database. A class that a
104-`new_sqlite_classes` migration declares can use the key-value methods `get()`,
105-`put()`, `delete()`, `list()`, and `deleteAll()`, and it can also run SQL
106-through `ctx.storage.sql.exec()`. `transaction()` and `transactionSync()` group
107-several writes, and `storage.sync()` waits for the durability of the earlier
108-committed writes. The `transactionSync()` callback receives no argument, as in
109-workerd. Therefore, it writes through `ctx.storage`, and a throw rolls the
110-transaction back. A callback can start another transaction, through the
111-transaction object or through `ctx.storage` itself, and celld nests the new
112-transaction inside the open one. A nested transaction that fails discards only
113-its own writes, therefore the enclosing transaction can continue and commit.
114-Read the
115-[storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/)
116-for the method signatures.
81+A class that a `new_sqlite_classes` migration declares can use the key-value
82+methods and `ctx.storage.sql.exec()`. The `transactionSync()` callback receives
83+no argument, as in workerd, and a throw rolls it back. A transaction can start
84+a nested transaction; a failed nested transaction discards only its own
85+writes, and the enclosing transaction can still commit.
11786
11887 The synchronous `ctx.storage.kv.list()` iterator reads one entry per step and
119-releases its read statement before the step returns. An unfinished iterator
120-therefore does not block later writes after a replication checkpoint. Each
121-step resumes after the last returned key in the selected direction. A later
122-step can observe a change to an entry that the iterator has not returned.
123-A new call to `kv.list()` invalidates the previous iterator for that object.
88+does not block later writes. Each step resumes after the last returned key, so
89+it can observe a change to an entry that it has not returned yet. A new call to
90+`kv.list()` invalidates the previous iterator for that object.
12491
125-The durability of that database comes from the fleet, not from a managed
126-service. celld captures each write as an LTX segment and replicates the segment
127-to `cells/<cell>/ltx/e<epoch>/` in the fleet bucket. A fleet of two or more
128-nodes is faster, because the owner also sends each write to one or two follower
129-nodes and answers as soon as a follower holds the write on its own disk. The
130-bucket upload follows afterwards. A single node has no follower, so every write
131-on it waits for the object store instead.
92+celld captures each write as an LTX segment and replicates it to
93+`cells/<cell>/ltx/e<epoch>/` in the fleet bucket. In a fleet of two or more
94+nodes, the owner answers when each of its one or two followers holds the write
95+on disk, and the bucket upload follows. On a single node, every write waits for the object
96+store.
13297
133-`storage.setAlarm()` schedules one alarm per object, `getAlarm()` reads it, and
134-`deleteAlarm()` removes it. celld calls the `alarm(alarmInfo)` handler at the
135-scheduled time and passes `retryCount` and `isRetry`, as the
136-[Alarms API](https://developers.cloudflare.com/durable-objects/api/alarms/)
137-describes. celld does not answer a successful response until a durable wake
138-entry in the bucket covers the alarm, so a crash cannot lose a schedule that a
139-client already saw. A hibernated cell fires its alarm on the node that owns it.
140-One node in the fleet holds the waker role, and it wakes only a cell whose
141-owner node stopped, so the alarm work of the fleet does not queue on one
142-machine.
98+celld does not answer a successful `setAlarm()` until a durable wake entry in
99+the bucket covers the alarm. A hibernated cell fires its alarm on its owner
100+node. One node holds the waker role, and it wakes only a cell whose owner
101+stopped.
143102
144103 ## Differences from Cloudflare
145104
deleteddocs/services/dynamic-workers-flow.svg+0−106
@@ -1,106 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 600" role="img" aria-labelledby="dwFlowTitle dwFlowDesc">
2- <title id="dwFlowTitle">What a loader grants a Dynamic Worker, and what it withholds</title>
3- <desc id="dwFlowDesc">One celld node runs one process that holds two V8 isolates, and not two machines and not a virtual machine. The host Worker isolate holds the deployment's bindings, vars, and secrets, and it calls env.LOADER.get(id, getCode), whose getCode runs once per id in that isolate. Only two things cross the boundary into the loaded isolate: the modules map with its mainModule, at most 64 MiB by default and compiled once, and the env and props values, which carry structured-clone values and capabilities up to 1 MiB. Everything else stops at the boundary: the deployment's KV, D1, R2, Queues, and Durable Object bindings, its vars and secrets, a Worker Loader binding of its own, and the host's globals and host ops. The loaded Worker isolate therefore has no ambient binding, and env is the whole of its reach. A capability call returns to the host isolate as an RPC, which is the only path back. Below, globalOutbound decides what the loaded code can dial: unspecified inherits the host's egress policy, null makes fetch() and connect() throw, and a Fetcher brokers fetch() while connect() and a WebSocket are refused.</desc>
4- <style>
5- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
6- text { font-size: 13px; fill: currentColor; }
7- tspan { fill: currentColor; }
8- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
9- .lead { font-weight: 600; }
10- .d-ink { color: #121212; }
11- .d-soft { color: #3d3b37; }
12- .d-faint { color: #6e6a62; }
13- .d-acc { color: #10803f; }
14- .d-panel { color: #ffffff; }
15- .d-sunk { color: #f0eee8; }
16- .d-tint { color: #d6efdf; }
17- @media (prefers-color-scheme: dark) {
18- .d-ink { color: #efede7; }
19- .d-soft { color: #c9c6be; }
20- .d-faint { color: #928e85; }
21- .d-acc { color: #3fc472; }
22- .d-panel { color: #1a1a19; }
23- .d-sunk { color: #232321; }
24- .d-tint { color: #10301d; }
25- }
26- </style>
27- <defs>
28- <marker id="dw-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
29- markerHeight="6" orient="auto-start-reverse">
30- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
31- </marker>
32- </defs>
33-
34- <!-- Both isolates live in one process on one node. The picture says how
35- strong the boundary is, because the prose cannot show its scale. -->
36- <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="444" rx="12" />
37- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="444" rx="12" />
38- <text class="d-ink lead" fill="currentColor" x="24" y="34">One celld node, one process</text>
39- <text class="d-faint" fill="currentColor" x="24" y="54">two V8 isolates, not two machines and not a virtual machine</text>
40-
41- <rect class="d-panel" fill="currentColor" x="22" y="68" width="372" height="104" rx="8" />
42- <rect class="d-faint" fill="none" stroke="currentColor" x="22" y="68" width="372" height="104" rx="8" />
43- <text class="d-faint" fill="currentColor" x="34" y="92">Host Worker isolate</text>
44- <text class="d-ink mono" fill="currentColor" x="34" y="114">MY_KV MY_DB MY_BUCKET vars secrets</text>
45- <text class="d-acc mono" fill="currentColor" x="34" y="140">env.LOADER.get(id, getCode)</text>
46- <text class="d-faint" fill="currentColor" x="34" y="160">getCode runs once per id in this isolate</text>
47-
48- <!-- One arrow crosses; the other stops at a bar. The contrast is the fact. -->
49- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
50- <path d="M114 172 V196" marker-end="url(#dw-arrow)" />
51- </g>
52- <g class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5">
53- <path d="M302 172 V188" />
54- <path d="M288 192 H316" stroke-width="2.5" />
55- </g>
56-
57- <rect class="d-tint" fill="currentColor" x="22" y="200" width="184" height="142" rx="8" />
58- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="200" width="184" height="142" rx="8" />
59- <text class="d-acc lead" fill="currentColor" x="34" y="224">crosses the boundary</text>
60- <text class="d-ink mono" fill="currentColor" x="34" y="248">modules, mainModule</text>
61- <text class="d-faint" fill="currentColor" x="34" y="266">64 MiB default limit</text>
62- <text class="d-ink mono" fill="currentColor" x="34" y="292">env, props</text>
63- <text class="d-faint" fill="currentColor" x="34" y="310">structured-clone values</text>
64- <text class="d-faint" fill="currentColor" x="34" y="328">and capabilities, 1 MiB</text>
65-
66- <rect class="d-panel" fill="currentColor" x="210" y="200" width="184" height="142" rx="8" />
67- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
68- x="210" y="200" width="184" height="142" rx="8" />
69- <text class="d-faint lead" fill="currentColor" x="222" y="224">stays in the host</text>
70- <text class="d-soft" fill="currentColor" x="222" y="248">KV, D1, R2, Queues,</text>
71- <text class="d-soft" fill="currentColor" x="222" y="266">and Durable Objects</text>
72- <text class="d-soft" fill="currentColor" x="222" y="292">vars and secrets</text>
73- <text class="d-soft" fill="currentColor" x="222" y="310">a Worker Loader binding</text>
74- <text class="d-soft" fill="currentColor" x="222" y="328">the host's globals, ops</text>
75-
76- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
77- <path d="M114 342 V356" marker-end="url(#dw-arrow)" />
78- </g>
79-
80- <rect class="d-panel" fill="currentColor" x="22" y="360" width="372" height="76" rx="8" />
81- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="360" width="372" height="76" rx="8" />
82- <text class="d-faint" fill="currentColor" x="34" y="384">Loaded Worker isolate</text>
83- <text class="d-ink" fill="currentColor" x="34" y="406">no ambient binding: env is the whole of its reach</text>
84- <text class="d-soft" fill="currentColor" x="34" y="426">a capability call is an RPC back to the host</text>
85-
86- <!-- The only path back into the host isolate. -->
87- <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5">
88- <path d="M394 400 C 424 400 424 130 398 130" marker-end="url(#dw-arrow)" />
89- </g>
90-
91- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
92- <path d="M220 452 V464" marker-end="url(#dw-arrow)" />
93- </g>
94-
95- <!-- Egress is a third state, and celld's answer differs per protocol. -->
96- <rect class="d-panel" fill="currentColor" x="8" y="468" width="424" height="124" rx="8" />
97- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="468" width="424" height="124" rx="8" />
98- <text class="d-ink lead" fill="currentColor" x="24" y="492">globalOutbound decides what the loaded code can dial</text>
99- <text class="d-soft mono" fill="currentColor" x="24" y="516">unspecified</text>
100- <text class="d-soft" fill="currentColor" x="150" y="516">inherits the host's egress policy</text>
101- <text class="d-soft mono" fill="currentColor" x="24" y="538">null</text>
102- <text class="d-soft" fill="currentColor" x="150" y="538">fetch() and connect() throw</text>
103- <text class="d-acc mono" fill="currentColor" x="24" y="560">a Fetcher</text>
104- <text class="d-soft" fill="currentColor" x="150" y="560">brokers fetch()</text>
105- <text class="d-faint" fill="currentColor" x="150" y="578">connect() and a WebSocket are refused</text>
106-</svg>
modifieddocs/services/dynamic-workers.md+69−109View file
@@ -1,17 +1,15 @@
11 # Dynamic Workers
22
33 A Dynamic Worker is Worker code that a running Worker supplies at runtime and
4-loads through a Worker Loader binding. An application uses one for code that it
5-does not write itself: code that a customer uploads, or code that a model
6-writes. celld compiles that code into a separate V8 isolate on the node that
7-runs the loader, and it gives the loaded Worker no binding of its own, so the
8-loader hands over every capability that the loaded code can use, and the
9-durable state stays behind in the loader's own bindings. Cloudflare runs this
10-feature in an
4+loads through a Worker Loader binding, such as code that a customer uploads or
5+that a model writes. celld compiles the code into a separate V8 isolate on the
6+node of the loader. Cloudflare runs this feature in an
117 [open beta](https://developers.cloudflare.com/changelog/post/2026-03-24-dynamic-workers-open-beta/),
12-therefore the API can still change. Read the
8+so the API can change. Read the
139 [Cloudflare Dynamic Workers documentation](https://developers.cloudflare.com/dynamic-workers/)
14-for the standard API behavior.
10+and the
11+[API reference](https://developers.cloudflare.com/dynamic-workers/api-reference/)
12+for the standard API.
1513
1614 ## Example
1715
@@ -20,127 +18,89 @@
2018
2119 <!-- celld-example: dynamic-worker-tails -->
2220
21+## API
22+
23+- `env.LOADER.get(id, getCode)` loads a Worker under a string id, and
24+ `env.LOADER.load(code)` loads an anonymous Worker.
25+- `getCode` returns a `WorkerCode` object: `mainModule`, `modules`,
26+ `compatibilityDate`, `compatibilityFlags`, `env`, `globalOutbound`, `limits`,
27+ and `tails`.
28+- `stub.getEntrypoint(name, options)` returns a Fetcher for the default export
29+ or for a named `WorkerEntrypoint`.
30+- `stub.getDurableObjectClass(name, options)` returns a Durable Object class,
31+ for example for a [facet](durable-object-facets.md).
32+- `stub.dispose()` releases the loaded Worker.
33+
2334 ## Loading a Worker
2435
25-A `worker_loaders` entry in the Wrangler configuration adds the binding, and
26-the example names it `LOADER`. Wrangler accepts only the `binding` name in
27-this entry, so set `tails` in a `WorkerCode` object and set `limits` there or
28-in a `getEntrypoint()` call. celld stops the deployment when the entry
29-contains either option. `env.LOADER.get(id, getCode)` gives a loaded
30-Worker a string id, and `env.LOADER.load(code)` loads an anonymous one. celld
31-calls `getCode` only when it must compile, so the callback can read the code
32-from a store, and it can be asynchronous. A throw inside `getCode` therefore
33-surfaces when the application first uses the Worker, and not at the `get()`
34-call.
36+A `worker_loaders` entry accepts only the `binding` name, as in Wrangler.
37+celld stops the deployment when the entry sets `tails` or `limits`; set them in
38+the `WorkerCode` object, or set `limits` in a `getEntrypoint()` call.
3539
36-`getCode` returns a `WorkerCode` object. `mainModule` names the entry module,
37-and `modules` maps each module name to its source. A value in that map can also
38-be a module object such as `{ wasm: bytes }`, and the
39-[WebAssembly page](../wasm.md#dynamic-workers) shows that form. Bare bytes are
40-not a module, so celld refuses them as workerd does. A static or dynamic relative import resolves from the importing
41-module's name. Thus, `dir/a.js` can import `./b.js` when the map contains
42-`dir/b.js`. `compatibilityDate` is required, as in workerd, and
43-`compatibilityFlags` is optional. Both select the runtime behavior of the loaded
44-Worker. The module sources can total 64 MiB by default, matching workerd.
45-A fleet operator can set `CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES` to a positive
46-byte count before starting each node to admit larger module sets. This is
47-node configuration; loaded code cannot raise it through `WorkerCode`. Heap,
48-execution, and admission limits continue to apply independently.
49-A `WorkerCode.limits` object can set
50-`cpuMs` and `subRequests` for each invocation. celld refuses a `WorkerCode`
51-that sets `allowExperimental`. Read the
52-[API reference](https://developers.cloudflare.com/dynamic-workers/api-reference/)
53-for the complete shape.
40+celld calls the `getCode` callback of `env.LOADER.get(id, getCode)` only when
41+it must compile, so a throw in `getCode` surfaces at the first use of the
42+Worker, not at `get()`.
5443
55-The stub that `get()` and `load()` return invokes the loaded code.
56-`getEntrypoint(name, options)` gives a Fetcher for the default export or for a
57-named `WorkerEntrypoint`, and `getDurableObjectClass(name, options)` gives a
58-Durable Object class. Both accept a `props` option. `getEntrypoint()` also
59-accepts `limits` for its fetch and RPC calls. celld uses the lower value for
60-each limit when both the `WorkerCode` object and the call set it. The
61-`getDurableObjectClass()` options accept only `props`.
44+- A `modules` value can be a module object such as `{ wasm: bytes }`; the
45+ [WebAssembly page](../wasm.md#dynamic-workers) shows that form. celld refuses
46+ bare bytes, as workerd does.
47+- A relative import resolves from the name of the importing module, so
48+ `dir/a.js` can import `./b.js` when the map contains `dir/b.js`.
49+- `compatibilityDate` is required, as in workerd.
50+- The module sources can total 64 MiB by default, as in workerd. An operator
51+ can set `CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES` on each node to a larger byte
52+ count. Loaded code cannot raise it, and the heap, execution, and admission
53+ limits still apply.
54+- When both `WorkerCode.limits` and `getEntrypoint()` set a limit, celld uses
55+ the lower value.
6256
6357 ## The isolation boundary
6458
65-celld compiles the loaded code into its own V8 isolate, with its own context
66-and its own heap. That isolate runs in the same process as the loader, on the
67-same node. It is not a second process and it is not a virtual machine, so the
68-boundary scopes what the loaded code can address, and it is not a claim about
69-V8 escape safety. Run the code in a container under a named runtime when the
70-workload needs a kernel boundary, and read
59+The loaded isolate has its own context and heap, but it runs in the process of
60+the loader. It is not a second process or a virtual machine, so the boundary
61+scopes what the code can address and makes no claim about V8 escape safety.
62+For a kernel boundary, run the code in a container under a named runtime; read
7163 [the isolation boundary](containers.md#the-isolation-boundary) on the
7264 Containers page.
7365
74-celld builds the loaded Worker with an empty binding set. It carries no KV
75-namespace, no D1 database, no R2 bucket, no queue, no Workflow, no Durable
76-Object class, and no `vars` entry of the deployment. It also carries no Worker
77-Loader binding, so a loaded Worker cannot load another one. The loaded code
78-therefore reaches only the `env` that the `WorkerCode` supplies. That `env`
79-takes structured-clone values and Service Binding capabilities, and Cloudflare
80-gives the same
81-[capability rule](https://developers.cloudflare.com/dynamic-workers/usage/bindings/).
82-A capability call leaves the loaded isolate as an RPC into the loader's
83-isolate, so the loader keeps control of what the call does.
66+The loaded Worker gets no binding and no `vars` entry of the deployment, and no
67+Worker Loader binding, so it cannot load another Worker. It reaches only the
68+`env` of its `WorkerCode`. A capability call is an RPC into the isolate of the
69+loader. celld passes host operations to its internal scripts as function
70+parameters, never as globals, so `globalThis` exposes none.
8471
85-![Two V8 isolates in one celld process: the modules map and the env cross into the loaded isolate, the deployment's bindings, vars, secrets, and host globals stay behind, an RPC is the only path back, and globalOutbound decides what the loaded code can dial](dynamic-workers-flow.svg)
72+When `WorkerCode` omits `globalOutbound`, the loaded Worker inherits the egress
73+policy of the loader. A `null` value makes `fetch()` and `connect()` throw. A
74+Fetcher brokers each `fetch()` through the loader. A `connect()` or a WebSocket
75+through a Fetcher throws, because the celld service protocol carries no
76+bidirectional tunnel.
8677
87-The runtime internals stay out of reach as well. celld passes each host
88-operation to its internal scripts as a function parameter and never as a
89-global, so loaded code cannot find one by reading `globalThis`. A loaded Worker
90-once reached the host through such a global, and the parameter form closed that
91-path.
92-
93-`globalOutbound` decides what the loaded code can dial. celld gives the loaded
94-Worker the loader's own egress policy when the `WorkerCode` omits the field, so
95-a deployed Worker with Internet access passes that access on. A `null` value
96-removes every ambient connection instead, and `fetch()` and `connect()` both
97-throw, which leaves an `env` capability as the only way out. A Fetcher
98-brokers each `fetch()` through the loader, which can read the request, change
99-it, or refuse it. celld does not broker a `connect()` or a WebSocket through a
100-Fetcher, and each of those throws, because celld's service protocol carries no
101-bidirectional tunnel and a direct socket would pass the broker in silence. Read
102-the
103-[egress control documentation](https://developers.cloudflare.com/dynamic-workers/usage/egress-control/)
104-for the Cloudflare behavior.
105-
10678 ## Lifetime and caching
10779
108-`get(id, getCode)` memoizes the load by id inside one loader binding of one
109-host isolate. The first use of an id runs `getCode` and compiles the modules,
110-and a later use of that id in the same isolate reuses the compiled isolate and
111-runs no callback while the loaded Worker is alive. Module scope therefore
112-survives between the two calls. Another isolate holds its own map. A request
113-that a different node serves, or a fresh isolate on the same node, pays the
114-compile again. Two `worker_loaders` entries are two maps as well, so the same
115-id in each one loads twice.
116-Cloudflare describes the same reuse as a possibility and not as a guarantee.
80+`get(id, getCode)` memoizes the compiled Worker by id inside one loader binding
81+of one host isolate, so module scope survives between calls there. Each
82+isolate, each node, and each `worker_loaders` entry has its own map, and pays
83+the compile again. Cloudflare describes this reuse as possible, not
84+guaranteed. `load(code)` compiles on each call.
11785
118-`load(code)` caches nothing and compiles on each call. For both methods, a
119-stub, an entrypoint, a Durable Object class, or a running facet keeps its
120-loaded Worker alive. The id map holds only a weak reference, so the garbage
121-collector can release a Worker after its last reference disappears. A later
122-`get()` call with that id then runs `getCode` again. The garbage collector does
123-not guarantee a release time.
86+A stub, an entrypoint, a Durable Object class, or a running facet keeps its
87+loaded Worker alive. The id map holds a weak reference, so after the last
88+reference disappears the garbage collector can release the Worker, at no
89+guaranteed time, and a later `get()` runs `getCode` again.
12490
125-The `dispose()` method of a stub releases its loaded Worker explicitly, and it
126-removes the id from the map. The other stubs for that load cannot start new
127-calls, and a later `get()` call creates a replacement. An in-flight call
128-finishes with the Worker that started it.
91+The `dispose()` method of a stub releases its loaded Worker and removes the id
92+from the map. The other stubs for that load cannot start new calls, and an
93+in-flight call finishes.
12994
130-Every loaded Worker belongs to the isolate that created it. celld drops all of
131-them when that isolate retires, which happens when the request load falls or
132-when a new deployment supersedes the script. An in-flight call finishes first.
133-A loaded Worker therefore never outlives its loader, and a redeploy compiles
134-the code again.
95+celld drops every loaded Worker when its host isolate retires, after in-flight
96+calls finish. A loaded Worker never outlives its loader, and a redeploy
97+compiles the code again.
13598
136-A process holds at most 256 live Dynamic Workers, and one generation of one
137-script holds at most 255 of them. The last slot stays reserved, so a single
138-runaway loader cannot take the whole process. A load over either limit throws.
139-
14099 ## Differences from Cloudflare
141100
142101 - The process limit is 256 live Dynamic Workers, and each script generation can
143- use 255 slots. Every loader and script shares the process limit.
102+ use 255 slots, so one loader cannot take the whole process. Every loader and
103+ script shares the process limit, and a load over either limit throws.
144104 - The process rejects the removed `CELLD_MAX_LOADED_WORKERS` environment
145105 variable.
146106 - `getEntrypoint()` supports `props` and `limits` options, while
deleteddocs/services/kv-flow.svg+0−102
@@ -1,102 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 322" role="img" aria-labelledby="kvFlowTitle kvFlowDesc">
2- <title id="kvFlowTitle">Each namespace resolves to one cell with one owner node and one writer</title>
3- <desc id="kvFlowDesc">Workers on nodes A, B, and C call two namespaces. The calls cross an empty
4-dashed layer, marked as the place where celld holds no cache, and reach two
5-namespace cells. The VALUES cell has owner node B and one writer, and the
6-SESSIONS cell has owner node C and one writer, so a second namespace adds a
7-second writer. Under the VALUES cell, a value of 1 MiB or less goes to an inline
8-row and a larger value goes to the fleet bucket. Every namespace splits the same
9-way.</desc>
10- <style>
11- .d-ink { color: #121212 }
12- .d-soft { color: #3d3b37 }
13- .d-faint { color: #6e6a62 }
14- .d-acc { color: #10803f }
15- .d-panel { color: #ffffff }
16- .d-sunk { color: #f0eee8 }
17- .d-tint { color: #d6efdf }
18- text {
19- font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
20- font-size: 13px;
21- fill: currentColor;
22- }
23- @media (prefers-color-scheme: dark) {
24- .d-ink { color: #efede7 }
25- .d-soft { color: #c9c6be }
26- .d-faint { color: #928e85 }
27- .d-acc { color: #3fc472 }
28- .d-panel { color: #1a1a19 }
29- .d-sunk { color: #232321 }
30- .d-tint { color: #10301d }
31- }
32- </style>
33- <defs>
34- <marker id="kv-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
35- markerHeight="6" orient="auto-start-reverse">
36- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
37- </marker>
38- </defs>
39-
40- <!-- Callers: three nodes, two namespaces, reads and writes together. -->
41- <rect class="d-panel" fill="currentColor" x="6" y="8" width="136" height="48" rx="6" />
42- <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="8" width="136" height="48" rx="6" />
43- <text class="d-ink" fill="currentColor" x="74" y="29" text-anchor="middle">Worker · node A</text>
44- <text class="d-soft" fill="currentColor" x="74" y="46" text-anchor="middle">VALUES.get()</text>
45-
46- <rect class="d-panel" fill="currentColor" x="152" y="8" width="136" height="48" rx="6" />
47- <rect class="d-soft" fill="none" stroke="currentColor" x="152" y="8" width="136" height="48" rx="6" />
48- <text class="d-ink" fill="currentColor" x="220" y="29" text-anchor="middle">Worker · node B</text>
49- <text class="d-soft" fill="currentColor" x="220" y="46" text-anchor="middle">VALUES.put()</text>
50-
51- <rect class="d-panel" fill="currentColor" x="298" y="8" width="136" height="48" rx="6" />
52- <rect class="d-soft" fill="none" stroke="currentColor" x="298" y="8" width="136" height="48" rx="6" />
53- <text class="d-ink" fill="currentColor" x="366" y="29" text-anchor="middle">Worker · node C</text>
54- <text class="d-soft" fill="currentColor" x="366" y="46" text-anchor="middle">SESSIONS.put()</text>
55-
56- <!-- The layer Cloudflare fills with a cache, and celld leaves empty. -->
57- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
58- x="6" y="76" width="428" height="48" rx="6" />
59- <text class="d-faint" fill="currentColor" x="220" y="96" text-anchor="middle">no cache layer</text>
60- <text class="d-faint" fill="currentColor" x="220" y="114" text-anchor="middle">every call reaches the owner cell</text>
61-
62- <!-- The two callers of one namespace join; the third goes elsewhere. -->
63- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
64- <path d="M74 56 V70" />
65- <path d="M220 56 V70" />
66- <path d="M60 70 H220" />
67- <path d="M60 70 V142" marker-end="url(#kv-arrow)" />
68- <path d="M366 56 V70 H380 V142" marker-end="url(#kv-arrow)" />
69- </g>
70-
71- <!-- One namespace, one cell, one writer. A second namespace, a second writer. -->
72- <rect class="d-tint" fill="currentColor" x="16" y="146" width="200" height="72" rx="6" />
73- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="146" width="200" height="72" rx="6" />
74- <text class="d-ink" fill="currentColor" x="116" y="169" text-anchor="middle">VALUES cell</text>
75- <text class="d-soft" fill="currentColor" x="116" y="188" text-anchor="middle">owner: node B</text>
76- <text class="d-soft" fill="currentColor" x="116" y="207" text-anchor="middle">one writer</text>
77-
78- <rect class="d-tint" fill="currentColor" x="224" y="146" width="200" height="72" rx="6" />
79- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="224" y="146" width="200" height="72" rx="6" />
80- <text class="d-ink" fill="currentColor" x="324" y="169" text-anchor="middle">SESSIONS cell</text>
81- <text class="d-soft" fill="currentColor" x="324" y="188" text-anchor="middle">owner: node C</text>
82- <text class="d-soft" fill="currentColor" x="324" y="207" text-anchor="middle">one writer</text>
83-
84- <!-- Inside a cell, the value size selects the store. -->
85- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
86- <path d="M70 218 V240 H65 V262" marker-end="url(#kv-arrow)" />
87- <path d="M162 218 V240 H167 V262" marker-end="url(#kv-arrow)" />
88- </g>
89-
90- <rect class="d-sunk" fill="currentColor" x="16" y="266" width="98" height="46" rx="6" />
91- <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="266" width="98" height="46" rx="6" />
92- <text class="d-ink" fill="currentColor" x="65" y="287" text-anchor="middle">inline row</text>
93- <text class="d-soft" fill="currentColor" x="65" y="304" text-anchor="middle">1 MiB or less</text>
94-
95- <rect class="d-sunk" fill="currentColor" x="118" y="266" width="98" height="46" rx="6" />
96- <rect class="d-soft" fill="none" stroke="currentColor" x="118" y="266" width="98" height="46" rx="6" />
97- <text class="d-ink" fill="currentColor" x="167" y="287" text-anchor="middle">fleet bucket</text>
98- <text class="d-soft" fill="currentColor" x="167" y="304" text-anchor="middle">above 1 MiB</text>
99-
100- <text class="d-faint" fill="currentColor" x="324" y="287" text-anchor="middle">every namespace splits</text>
101- <text class="d-faint" fill="currentColor" x="324" y="304" text-anchor="middle">the same way</text>
102-</svg>
modifieddocs/services/kv.md+33−77View file
@@ -1,13 +1,9 @@
11 # KV
22
3-KV is a key-value store that an application accesses through a binding. A
4-Worker reads a value with `env.NAMESPACE.get()`, and it writes one with
5-`env.NAMESPACE.put()`. An application uses KV for data that many requests read
6-and few requests change, such as a feature flag, a redirect table, or a
7-configuration document. Each namespace lives in one celld cell, and a value
8-above 1 MiB lives in the fleet bucket. Read the
3+KV is a key-value store that a Worker reaches through a binding. Each namespace
4+is one celld cell, and a value above 1 MiB lives in the fleet bucket. Read the
95 [Cloudflare KV documentation](https://developers.cloudflare.com/kv/api/) for the
10-standard API behavior.
6+API.
117
128 ## Example
139
@@ -16,84 +12,44 @@
1612
1713 <!-- celld-example: kv -->
1814
19-## Namespaces, keys, and values
15+## API
2016
21-A project declares a namespace with a `kv_namespaces` entry that gives a
22-`binding` name and an `id`. celld uses the `id` as the namespace identity,
23-whatever string it holds, so a hexadecimal id from Cloudflare and a plain name
24-such as `sessions` both work. A namespace belongs to the fleet and not to one
25-script, so two Workers that name one `id` reach one namespace. celld accepts
26-`preview_id` and ignores it, because celld does not run `wrangler dev`.
17+- `get(key, type)` returns the value as `"text"`, `"json"`, `"arrayBuffer"`, or
18+ `"stream"`. A missing key gives `null`.
19+- `getWithMetadata(key, type)` also returns the metadata of the write.
20+- `put(key, value, options)` takes a string, an `ArrayBuffer`, a typed array, or
21+ a `ReadableStream`. The options are `expiration` (an absolute time in
22+ seconds), `expirationTtl` (seconds from now), and `metadata`.
23+- `delete(key)` removes a key.
24+- `list({ prefix, cursor })` returns a page of key names and a cursor for the
25+ next page.
2726
28-`put()` accepts a string, an `ArrayBuffer`, a typed array, or a
29-`ReadableStream`, and celld copies the bytes at the call so a later change to
30-the buffer cannot alter the stored value. celld reads a stream to its end
31-before the write, therefore `put(key, request.body)` stores a request body.
32-`get()` returns the value as `"text"`, `"json"`, `"arrayBuffer"`, or
33-`"stream"`. `getWithMetadata()` also returns the metadata that the write
34-attached, and a missing key gives `null` in both methods. `list()` returns at
35-most 1000 key names in byte order, and its cursor resumes after the last
36-returned name, so a concurrent write cannot make the pagination skip a key.
27+## Configuration and limits
3728
29+A `kv_namespaces` entry gives a `binding` and an `id`. The `id` is the namespace
30+identity, and it can be any string, such as a Cloudflare hexadecimal id or
31+`sessions`. Two Workers that name one `id` reach one namespace. celld ignores
32+`preview_id`.
33+
34+`put()` reads a `ReadableStream` to its end before the write, so
35+`put(key, request.body)` works. `list()` returns at most 1000 keys in byte
36+order, and a concurrent write cannot make the cursor skip a key.
37+
3838 celld enforces the
3939 [Cloudflare KV limits](https://developers.cloudflare.com/kv/platform/limits/): a
40-key of at most 512 bytes, a value of at most 25 MiB, and serialized metadata of
41-at most 1024 bytes. One bulk `get()` takes at most 100 keys. celld refuses a
42-call that crosses a limit instead of truncating the data, so the application
43-learns about the problem at the call site.
40+key of at most 512 bytes, a value of at most 25 MiB, metadata of at most 1024
41+bytes, and at most 100 keys in one bulk `get()`. A call that crosses a limit
42+fails, and celld never truncates data. The minimum expiration is 60 seconds. An
43+expired key becomes invisible at the moment it expires.
4444
45-A write can set `expiration` as an absolute time in seconds, or `expirationTtl`
46-as a count of seconds from now. The minimum lifetime is 60 seconds. celld
47-filters an expired key on the read path, so the key becomes invisible at the
48-moment it expires, and a sweeper reclaims the storage afterwards.
45+Every call goes to the node that owns the namespace cell, so a read costs one
46+cell dispatch. Hold a value in a local variable when one request reads it many
47+times. Writes to one namespace run one at a time, so use a Durable Object for a
48+write-hot value such as a counter.
4949
50-## The read and write path
50+A write of a value above 1 MiB without a fleet bucket fails with
51+`KV large values need a fleet bucket`.
5152
52-A Cloudflare namespace is
53-[a database that replicates to the global network](https://developers.cloudflare.com/kv/concepts/kv-namespaces/),
54-and each location caches the values that it reads. celld has no such cache. A
55-celld namespace is one cell, which is the same single-threaded actor that runs a
56-Durable Object, so the namespace state lives in that cell's SQLite database.
57-Every call reaches the node that owns the cell, therefore a celld read returns
58-the committed value and is never stale.
59-
60-![Each namespace resolves to one cell with one owner node and one writer](kv-flow.svg)
61-
62-One cell owns a namespace, and a cell has one writer. Two writes to one
63-namespace therefore run one after the other, even when they touch different
64-keys. More nodes do not divide that work, because the namespace has one owner.
65-An application that needs more write capacity splits its keys across more
66-namespaces, because KV has no operation that spans two keys.
67-
68-Reads and writes cost different amounts. A write commits to the cell's SQLite
69-database and replicates to the fleet, so it pays for durability every time. A
70-read only answers from the committed state. This asymmetry makes KV a good
71-choice for configuration data that a Worker reads on every request, and a poor
72-choice for a counter that many requests increment. Use a Durable Object for a
73-write-hot value, which is the same advice that
74-[Cloudflare gives](https://developers.cloudflare.com/kv/concepts/how-kv-works/).
75-
76-A read also has a cost in celld that it does not have on Cloudflare. Cloudflare
77-answers a hot key from a cache in the location that serves the request. celld
78-sends every `get()` to the owner node, so a read costs one cell dispatch. An
79-application that reads one key many times inside one request must hold the value
80-in a local variable.
81-
82-## A value above the inline limit
83-
84-celld keeps a value of 1 MiB or less inside the cell, because such a value
85-replicates with the cell's other writes. A larger value goes to the fleet bucket
86-under a content address, and the cell row holds only the reference. This split
87-keeps one large `put()` from becoming the most expensive operation in the
88-runtime. Cloudflare made the same split for the same reason, and sends a large
89-value to object storage.
90-
91-A node therefore needs a fleet bucket to write a value above 1 MiB. Without one,
92-the write fails with the message `KV large values need a fleet bucket`. celld
93-writes the object before it commits the row, so a crash between the two steps
94-leaves an unreferenced object that a collector removes later. A committed row
95-never names an object that does not exist.
96-
9753 ## Differences from Cloudflare
9854
9955 - A celld read never returns a stale value, because it reaches the cell that
deleteddocs/services/queues-flow.svg+0−127
@@ -1,127 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 512" role="img" aria-labelledby="queuesFlowTitle queuesFlowDesc">
2- <title id="queuesFlowTitle">A batch closes on size or on timeout, and an unacknowledged message returns to the queue until the retry bound moves it to the dead-letter queue</title>
3- <desc id="queuesFlowDesc">The upper panel shows two batches under a consumer with max_batch_size 10 and
4-max_batch_timeout 5 seconds. A busy queue reaches ten messages before the
5-timeout, so the batch closes on size. A sparse queue reaches only three
6-messages, so the batch closes on the timeout and the consumer receives a
7-partial batch. The timeout runs from the oldest ready message, not from the
8-last one. The lower panel shows the settlement cycle. One queue cell with one
9-writer leases a batch to one call of queue(batch, env, ctx). A message that the
10-handler acknowledges, or that a clean return leaves unsettled, is deleted. A
11-message that calls retry, that a thrown handler abandons, or that no
12-settlement reaches, returns to the queue as the same message with its attempts
13-count raised by one, so a consumer can see a duplicate. When attempts pass
14-max_retries, the message leaves the loop and moves to the dead-letter queue
15-cell, which is itself a queue with its own consumer. celld deletes the message
16-instead when no dead_letter_queue is configured.</desc>
17- <style>
18- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
19- text { font-size: 13px; fill: currentColor; }
20- tspan { fill: currentColor; }
21- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
22- .lead { font-weight: 600; }
23- .sm { font-size: 12px; }
24- .d-ink { color: #121212; }
25- .d-soft { color: #3d3b37; }
26- .d-faint { color: #6e6a62; }
27- .d-acc { color: #10803f; }
28- .d-panel { color: #ffffff; }
29- .d-sunk { color: #f0eee8; }
30- .d-tint { color: #d6efdf; }
31- @media (prefers-color-scheme: dark) {
32- .d-ink { color: #efede7; }
33- .d-soft { color: #c9c6be; }
34- .d-faint { color: #928e85; }
35- .d-acc { color: #3fc472; }
36- .d-panel { color: #1a1a19; }
37- .d-sunk { color: #232321; }
38- .d-tint { color: #10301d; }
39- }
40- </style>
41- <defs>
42- <marker id="queues-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
43- markerHeight="6" orient="auto-start-reverse">
44- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
45- </marker>
46- </defs>
47-
48- <!-- Panel one: the batch window, where two limits race. -->
49- <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="170" rx="10" />
50- <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="170" rx="10" />
51- <text class="d-ink lead" fill="currentColor" x="22" y="32">A batch closes on whichever limit arrives first</text>
52- <text class="d-faint mono" fill="currentColor" x="22" y="52">max_batch_size 10 · max_batch_timeout 5 s</text>
53-
54- <path class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="4 4" d="M300 62 V152" />
55-
56- <!-- A busy queue fills the batch before the clock runs out. -->
57- <g class="d-acc" fill="currentColor">
58- <circle cx="24" cy="82" r="4" />
59- <circle cx="48" cy="82" r="4" />
60- <circle cx="72" cy="82" r="4" />
61- <circle cx="96" cy="82" r="4" />
62- <circle cx="120" cy="82" r="4" />
63- <circle cx="144" cy="82" r="4" />
64- <circle cx="168" cy="82" r="4" />
65- <circle cx="192" cy="82" r="4" />
66- <circle cx="216" cy="82" r="4" />
67- <circle cx="240" cy="82" r="4" />
68- </g>
69- <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2.5" d="M252 68 V96" />
70- <text class="d-soft sm" fill="currentColor" x="24" y="105">closes on size, before the timeout</text>
71-
72- <!-- A sparse queue reaches the clock with a partial batch. -->
73- <g class="d-acc" fill="currentColor">
74- <circle cx="24" cy="130" r="4" />
75- <circle cx="100" cy="130" r="4" />
76- <circle cx="184" cy="130" r="4" />
77- </g>
78- <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2.5" d="M300 116 V144" />
79- <text class="d-soft sm" fill="currentColor" x="24" y="153">closes on the timeout, 3 messages</text>
80- <text class="d-faint sm" fill="currentColor" x="308" y="134">partial batch</text>
81- <text class="d-faint sm" fill="currentColor" x="290" y="170" text-anchor="middle">the timeout runs from the oldest message</text>
82-
83- <!-- Panel two: the settlement cycle and the bound that ends it. -->
84- <text class="d-ink lead" fill="currentColor" x="22" y="204">An unacknowledged message returns to the queue</text>
85-
86- <rect class="d-tint" fill="currentColor" x="24" y="216" width="146" height="62" rx="8" />
87- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="24" y="216" width="146" height="62" rx="8" />
88- <text class="d-ink" fill="currentColor" x="97" y="242" text-anchor="middle">JOBS queue cell</text>
89- <text class="d-soft sm" fill="currentColor" x="97" y="262" text-anchor="middle">one writer</text>
90-
91- <rect class="d-panel" fill="currentColor" x="240" y="216" width="192" height="62" rx="8" />
92- <rect class="d-soft" fill="none" stroke="currentColor" x="240" y="216" width="192" height="62" rx="8" />
93- <text class="d-ink mono" fill="currentColor" x="336" y="242" text-anchor="middle">queue(batch, env, ctx)</text>
94- <text class="d-soft sm" fill="currentColor" x="336" y="262" text-anchor="middle">one batch, one lease</text>
95-
96- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
97- <path d="M170 247 H232" marker-end="url(#queues-arrow)" />
98- <path d="M336 278 V336" marker-end="url(#queues-arrow)" />
99- <path d="M336 294 H97 V336" marker-end="url(#queues-arrow)" />
100- <path d="M24 366 H12 V247 H18" marker-end="url(#queues-arrow)" />
101- <path d="M97 406 V440" marker-end="url(#queues-arrow)" />
102- </g>
103- <text class="d-faint sm" fill="currentColor" x="201" y="237" text-anchor="middle">lease</text>
104- <text class="d-soft sm" fill="currentColor" x="108" y="311">retry(), a throw,</text>
105- <text class="d-soft sm" fill="currentColor" x="108" y="327">or no settlement</text>
106-
107- <rect class="d-panel" fill="currentColor" x="24" y="336" width="146" height="70" rx="8" />
108- <rect class="d-soft" fill="none" stroke="currentColor" x="24" y="336" width="146" height="70" rx="8" />
109- <text class="d-ink" fill="currentColor" x="97" y="360" text-anchor="middle">back to the queue</text>
110- <text class="d-soft sm" fill="currentColor" x="97" y="379" text-anchor="middle">attempts + 1</text>
111- <text class="d-soft sm" fill="currentColor" x="97" y="396" text-anchor="middle">the same message</text>
112-
113- <rect class="d-panel" fill="currentColor" x="240" y="336" width="192" height="70" rx="8" />
114- <rect class="d-soft" fill="none" stroke="currentColor" x="240" y="336" width="192" height="70" rx="8" />
115- <text class="d-ink" fill="currentColor" x="336" y="366" text-anchor="middle">deleted</text>
116- <text class="d-soft sm" fill="currentColor" x="336" y="387" text-anchor="middle">ack(), or a clean return</text>
117-
118- <text class="d-acc mono" fill="currentColor" x="108" y="428">attempts &gt; max_retries</text>
119-
120- <rect class="d-tint" fill="currentColor" x="24" y="444" width="250" height="58" rx="8" />
121- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="24" y="444" width="250" height="58" rx="8" />
122- <text class="d-ink" fill="currentColor" x="149" y="470" text-anchor="middle">dead-letter queue cell</text>
123- <text class="d-soft sm" fill="currentColor" x="149" y="490" text-anchor="middle">a queue with its own consumer</text>
124-
125- <text class="d-faint sm mono" fill="currentColor" x="286" y="466">no dead_letter_queue</text>
126- <text class="d-faint sm" fill="currentColor" x="286" y="486">celld deletes it</text>
127-</svg>
modifieddocs/services/queues.md+40−89View file
@@ -1,13 +1,10 @@
11 # Queues
22
33 [Queues](https://developers.cloudflare.com/queues/) is a message broker. A
4-producer Worker sends a message, and a consumer Worker receives the message
5-later in a batch. An application uses a queue to move work out of a request,
6-such as an email, a webhook call, a thumbnail, or a search index update. Each
7-queue is one celld cell, so a message lives in that cell's SQLite database
8-until a consumer acknowledges it. Read the
4+producer Worker sends a message, and a consumer Worker receives it later in a
5+batch. Each queue is one celld cell. Read the
96 [Cloudflare Queues documentation](https://developers.cloudflare.com/queues/configuration/javascript-apis/)
10-for the standard API behavior.
7+for the API.
118
129 ## Example
1310
@@ -17,98 +14,52 @@
1714
1815 <!-- celld-example: queues -->
1916
20-## Sending a message
17+## API
2118
22-A project declares a producer with a `queues.producers` entry that gives a
23-`binding` name and a `queue` name. `env.JOBS.send(body)` sends one message, and
24-`env.JOBS.sendBatch(messages)` sends up to 100 messages in one call. celld
25-resolves the queue name to one cell, therefore every producer in the fleet that
26-names `example-jobs` writes to the same queue.
19+- `env.JOBS.send(body, { contentType, delaySeconds })` sends one message.
20+ `contentType` is `"v8"`, `"json"`, `"text"`, or `"bytes"`.
21+- `env.JOBS.sendBatch(messages)` sends up to 100 messages in one call.
22+- The consumer script exports `queue(batch, env, ctx)`. `batch.queue` names the
23+ queue, and each entry of `batch.messages` has an `id`, a `timestamp`, a
24+ `body`, and an `attempts` count.
25+- `message.ack()` and `message.retry({ delaySeconds })` settle one message.
26+ `batch.ackAll()` and `batch.retryAll()` settle the whole batch. The first
27+ call for a message wins.
28+- A handler that returns acknowledges every unsettled message. A handler that
29+ throws retries every message that it did not acknowledge.
2730
28-A message carries a body and a content type. The `contentType` option selects
29-`"v8"`, `"json"`, `"text"`, or `"bytes"`, and the `queues_json_messages`
30-compatibility flag chooses the default, as on Cloudflare. celld enforces the
31+## Producers
32+
33+A `queues.producers` entry gives a `binding` and a `queue` name. Every producer
34+in the fleet that names one queue writes to the same queue. celld enforces the
3135 [Cloudflare limits](https://developers.cloudflare.com/queues/platform/limits/):
32-a message of at most 128,000 bytes, a batch of at most 100 messages, and at most
33-256,000 bytes in one `sendBatch()` call. A `delaySeconds` option holds a message
34-invisible for up to 86,400 seconds, and a producer entry can set
35-`delivery_delay` as the default for every message of that binding.
36+a message of at most 128,000 bytes, at most 100 messages and 256,000 bytes in
37+one `sendBatch()` call, and a `delaySeconds` of at most 86,400. A producer entry
38+can set `delivery_delay` as the default delay.
3639
37-`send()` resolves after the queue cell commits the message, so a producer learns
38-that the message is durable. celld joins the concurrent sends of one queue into
39-one transaction, because a separate commit for each call makes durability the
40-cost of the queue. The cell accepts at most 256 producer calls at a time, and it
41-refuses a further call with a cell overload error that the producer can retry.
42-One queue has one writer, so an application that needs more write capacity
43-spreads its messages across more queues.
40+`send()` resolves after the queue cell commits the message. The cell accepts at
41+most 256 producer calls at a time, and it refuses a further call with a cell
42+overload error that the producer can retry.
4443
45-## The consumer and the batch
44+## Consumers
4645
47-A project declares a consumer with a `queues.consumers` entry that names the
48-`queue`. One script consumes a queue, and a deployment in which two scripts
49-consume one queue fails. The consumer entry sets `max_batch_size` (10 by
50-default, 100 at most), `max_batch_timeout` in seconds (5 by default, 60 at
51-most), `max_retries` (3 by default), `max_concurrency` (250 at most),
52-`retry_delay`, and `dead_letter_queue`. celld validates each bound at deploy
53-time, so a bad value fails the deployment instead of the first delivery. Read
46+A `queues.consumers` entry names the `queue`. Only one script can consume a
47+queue, so a deployment in which two scripts consume one queue fails. The entry
48+sets `max_batch_size` (10 by default, 100 at most), `max_batch_timeout` in
49+seconds (5 by default, 60 at most), `max_retries` (3 by default),
50+`max_concurrency` (250 at most), `retry_delay`, and `dead_letter_queue`. celld
51+validates each bound at deploy time. Read
5452 [Batching, retries, and delays](https://developers.cloudflare.com/queues/configuration/batching-retries/)
55-for the upstream meaning of each key.
53+for the meaning of each key.
5654
57-The queue cell forms the batch. It closes a batch when `max_batch_size` messages
58-are ready, or when `max_batch_timeout` passes after the oldest ready message,
59-whichever arrives first. A batch can therefore hold fewer messages than
60-`max_batch_size`. The cell leases the batch and calls the
61-`queue(batch, env, ctx)` handler that the consumer script exports. That handler
62-runs in a stateless isolate and not inside the queue cell, so a slow handler
63-does not block a producer. `max_concurrency` bounds how many batches of one
64-queue can run at the same time.
55+celld does not guarantee a delivery order, and it delivers a message at least
56+once. `message.id` stays the same across a redelivery, so an application can use
57+it as an idempotency key. A handler that never settles its batch holds the lease
58+until the lease expires, and celld counts that as one failed delivery. celld
59+adds no exponential backoff to a retry. Compute the delay from
60+`message.attempts`. A message that passes `max_retries` moves to the
61+`dead_letter_queue`, or celld deletes it when the consumer names none.
6562
66-`batch.queue` names the queue, and `batch.messages` holds the messages. Each
67-message has an `id`, a `timestamp`, the decoded `body`, and an `attempts` count
68-that is 1 on the first delivery. celld does not guarantee a delivery order, and
69-[Cloudflare gives the same rule](https://developers.cloudflare.com/queues/reference/how-queues-works/).
70-A retry, a per-message delay, and a concurrent batch each move a message away
71-from its send order, so an application that needs an order must carry that order
72-in the message body.
73-
74-## Acknowledgement and retry
75-
76-celld leases a batch instead of deleting it, so a message survives a consumer
77-that fails. Each message settles once. `message.ack()` marks one message as
78-done, and `message.retry()` returns one message to the queue. `batch.ackAll()`
79-and `batch.retryAll()` apply the same two outcomes to the whole batch. The first
80-call for a message wins, therefore a later call on that message does nothing.
81-
82-A handler that returns without a call acknowledges every message of its batch. A
83-handler that throws returns every message to the queue, except a message that
84-the handler acknowledged before the throw. A handler that never settles its
85-batch holds the lease until the lease expires, and celld then counts the batch
86-as one failed delivery.
87-
88-Every failed delivery raises `attempts` by one and makes the message visible
89-again. A `delaySeconds` option on `retry()` or `retryAll()` sets the delay, and
90-the consumer's `retry_delay` is the default. celld adds no exponential backoff,
91-so an application that wants one computes the delay from `message.attempts`.
92-
93-A message leaves the retry loop when `attempts` passes `max_retries`. celld
94-moves the message to the queue that `dead_letter_queue` names, which is an
95-ordinary queue and can have its own consumer. celld deletes a message that
96-reaches the bound when the consumer configures no dead-letter queue. Read
97-[Dead letter queues](https://developers.cloudflare.com/queues/configuration/dead-letter-queues/)
98-for the upstream behavior.
99-
100-![A busy queue closes a batch on max_batch_size and a sparse queue closes it on max_batch_timeout, and a message that no consumer acknowledges returns to the queue with attempts raised by one until attempts pass max_retries and the message moves to the dead-letter queue](queues-flow.svg)
101-
102-celld delivers a message at least once, as Cloudflare does. A consumer can crash
103-after its side effect and before its acknowledgement, and the message then
104-returns to the queue and runs again. A consumer must therefore tolerate a
105-duplicate. `message.id` stays the same across a redelivery, so an application
106-can use it as an idempotency key.
107-
108-celld keeps a message for four days after the send. A sweeper removes an older
109-message, even when no consumer read it, so a queue with no working consumer
110-loses its backlog instead of growing without a bound.
111-
11263 ## Differences from Cloudflare
11364
11465 - A queue has one writer. Use more queues to increase write capacity.
deleteddocs/services/r2-flow.svg+0−64
@@ -1,64 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 416" role="img" aria-labelledby="r2FlowTitle r2FlowDesc">
2- <title id="r2FlowTitle">Two R2 bindings share one fleet object store under reserved prefixes</title>
3- <desc id="r2FlowDesc">Two Workers each hold an R2 binding. The binding FILES has the bucket name example-files, and the binding CACHE has the bucket name renders. Both Workers write the same key, photo.png. Both bindings use one fleet object-store bucket, which is an s3, gs, or az bucket, so that store gives the binding its durability. celld turns each key into r2 slash bucket name slash key, so the two writes become the separate objects r2/example-files/photo.png and r2/renders/photo.png. The fleet's own keys, under deploy, cells, nodes, and wake, live in the same bucket outside every r2 prefix, and no binding can reach them.</desc>
4- <style>
5- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
6- text { font-size: 13px; fill: currentColor; }
7- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
8- .lead { font-weight: 600; }
9- .d-ink { color: #121212; }
10- .d-soft { color: #3d3b37; }
11- .d-faint { color: #6e6a62; }
12- .d-acc { color: #10803f; }
13- .d-panel { color: #ffffff; }
14- .d-sunk { color: #f0eee8; }
15- .d-tint { color: #d6efdf; }
16- @media (prefers-color-scheme: dark) {
17- .d-ink { color: #efede7; }
18- .d-soft { color: #c9c6be; }
19- .d-faint { color: #928e85; }
20- .d-acc { color: #3fc472; }
21- .d-panel { color: #1a1a19; }
22- .d-sunk { color: #232321; }
23- .d-tint { color: #10301d; }
24- }
25- </style>
26-
27- <!-- Two Workers, two bindings, the same key -->
28- <rect class="d-panel" x="8" y="10" width="200" height="86" rx="10" fill="currentColor" />
29- <rect class="d-faint" x="8" y="10" width="200" height="86" rx="10" fill="none" stroke="currentColor" />
30- <text class="d-faint" x="20" y="34">Worker A, binding FILES</text>
31- <text class="d-ink mono" x="20" y="58">put("photo.png")</text>
32- <text class="d-acc" x="20" y="80">bucket_name: example-files</text>
33-
34- <rect class="d-panel" x="232" y="10" width="200" height="86" rx="10" fill="currentColor" />
35- <rect class="d-faint" x="232" y="10" width="200" height="86" rx="10" fill="none" stroke="currentColor" />
36- <text class="d-faint" x="244" y="34">Worker B, binding CACHE</text>
37- <text class="d-ink mono" x="244" y="58">put("photo.png")</text>
38- <text class="d-acc" x="244" y="80">bucket_name: renders</text>
39-
40- <!-- Both bindings fan in to one store -->
41- <path class="d-faint" d="M108 96 C108 134 220 130 220 156" fill="none" stroke="currentColor" stroke-width="1.5" />
42- <path class="d-faint" d="M332 96 C332 134 220 130 220 156" fill="none" stroke="currentColor" stroke-width="1.5" />
43- <path class="d-faint" d="M220 168 L214 154 L226 154 Z" fill="currentColor" />
44- <text class="d-faint" x="220" y="130" text-anchor="middle">one store</text>
45-
46- <!-- The fleet object store -->
47- <rect class="d-sunk" x="8" y="172" width="424" height="234" rx="12" fill="currentColor" />
48- <rect class="d-faint" x="8" y="172" width="424" height="234" rx="12" fill="none" stroke="currentColor" />
49- <text class="d-ink lead" x="24" y="198">Fleet object-store bucket</text>
50- <text class="d-faint" x="24" y="218">s3:// gs:// az:// — durability comes from here</text>
51-
52- <rect class="d-tint" x="22" y="228" width="396" height="108" rx="8" fill="currentColor" />
53- <rect class="d-acc" x="22" y="228" width="396" height="108" rx="8" fill="none" stroke="currentColor" stroke-dasharray="5 4" />
54- <text class="d-acc" x="36" y="252">reserved r2/ prefixes, one per bucket_name</text>
55- <text class="d-ink mono" x="36" y="280"><tspan class="d-acc" fill="currentColor">r2/example-files/</tspan>photo.png</text>
56- <text class="d-faint" x="404" y="280" text-anchor="end">FILES</text>
57- <text class="d-ink mono" x="36" y="304"><tspan class="d-acc" fill="currentColor">r2/renders/</tspan>photo.png</text>
58- <text class="d-faint" x="404" y="304" text-anchor="end">CACHE</text>
59- <text class="d-ink mono" x="36" y="328"><tspan class="d-acc" fill="currentColor">r2/renders/</tspan>tile-04.png</text>
60- <text class="d-faint" x="404" y="328" text-anchor="end">CACHE</text>
61-
62- <text class="d-soft mono" x="24" y="366">deploy/ cells/ nodes/ wake/</text>
63- <text class="d-faint" x="24" y="388">fleet keys, outside every binding's reach</text>
64-</svg>
modifieddocs/services/r2.md+43−100View file
@@ -1,14 +1,11 @@
11 # R2
22
3-[R2](https://developers.cloudflare.com/r2/) is object storage. A bucket holds
4-unstructured blobs of any size, and an application reads or writes a blob by
5-name. An application uses R2 for a file that a request handler must keep: an
6-upload, an image, a backup, a build artifact, or a large data export. A Worker
7-reaches a bucket through an `r2_buckets` binding, so `env.BUCKET` gives the
8-bucket API without a credential in the Worker code. The objects live outside the
9-Worker isolate, in the fleet object store that the node already uses. Read the
3+[R2](https://developers.cloudflare.com/r2/) is object storage. A Worker reaches
4+a bucket through an `r2_buckets` binding. celld stores the objects in the fleet
5+bucket that the node opened with `--bucket`, so R2 has the durability of that
6+object store. On a node without a fleet bucket, every R2 method fails. Read the
107 [Workers API reference](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/)
11-for the full method list.
8+for the API.
129
1310 ## Example
1411
@@ -17,109 +14,55 @@
1714
1815 <!-- celld-example: r2 -->
1916
20-## The object model
17+## API
2118
22-A bucket contains objects, and each object has a key. A key is a string of 1 to
23-1024 bytes. The namespace is flat, so a slash in a key is only a character, and
24-`list()` folds a prefix into a group when a caller passes a `delimiter`. See
25-[Objects](https://developers.cloudflare.com/r2/objects/) for the upstream model.
19+- `get(key, { range, onlyIf })` returns an `R2ObjectBody` with a streamed body,
20+ or `null`. A range is an `offset`, a `length`, a `suffix`, or a `Range`
21+ header.
22+- `head(key)` returns the object record without the body.
23+- `put(key, value, { httpMetadata, customMetadata, onlyIf })` takes a string,
24+ an `ArrayBuffer`, a typed array, a `Blob`, or a `ReadableStream`. A refused
25+ condition returns `null`.
26+- `delete(keys)` removes one key or a list of keys.
27+- `list({ prefix, delimiter, cursor, startAfter })` returns a page of objects.
28+- `createMultipartUpload(key)` returns a handle. `uploadPart(number, value)`
29+ sends one part, and `complete(parts)` assembles the object.
2630
27-An object carries a body and a record. The record holds `httpMetadata` (the
28-content headers and a cache expiry), `customMetadata` (the application's own
29-string map), `checksums`, a `storageClass`, a `size`, an `uploaded` time, an
30-`etag`, and a `version`. celld stores the body as a plain object in the fleet
31-bucket and writes the five content headers as real headers, so another tool can
32-read the object. The parts that an object store has no place for travel as one
33-JSON value in a reserved metadata entry, and an object without that entry still
34-reads correctly.
31+## Keys and storage
3532
36-celld takes the `version` from the object store. Most object stores report no
37-version identifier, so the ETag becomes the version. Two writes of identical
38-bytes therefore produce the same version, and an application must not use a
39-version to count writes.
33+Each binding has its own `bucket_name`, and celld stores key `<key>` as the
34+object `r2/<bucket_name>/<key>`. A key is 1 to 1024 bytes. A streamed `put()`
35+body that grows past 8 MiB becomes a multipart upload. `delete()` removes up to
36+1000 keys in one call. celld has no public bucket URL, no presigned URL, and no
37+S3 endpoint, so put a Worker in front of the bytes to publish them.
4038
41-## Where celld stores an object
39+The object store keeps some keys in a percent-encoded form: a key with a
40+non-ASCII character, a control character, or one of
41+``% \ { } ^ ` [ ] " < > ~ # | * ?``. For example, `přehled.html` becomes
42+`r2/<bucket_name>/p%C5%99ehled.html`. Each empty segment becomes `%`, so
43+`photos/` becomes `r2/<bucket_name>/photos/%`, and `a/b`, `/a/b`, `a//b`, and
44+`a/b/` are four different objects, as in Cloudflare R2. `list()` returns the
45+decoded key, but it sorts by the encoded form and compares `startAfter` with the
46+encoded form. Cloudflare R2 sorts by UTF-8 bytes. For example, Cloudflare R2
47+returns `a~` after `startAfter: "aa"`, but celld compares `a%7E` with `aa` and
48+skips the key. A `cursor` from a celld listing does not have this problem.
4249
43-celld does not run its own blob service, because celld already runs on one. An
44-R2 binding therefore uses the fleet bucket that the node opened with `--bucket`,
45-and it does not use a second store or a second credential. The durability of an
46-R2 binding is the durability of that object store, and it is not the durability
47-of Cloudflare R2. A node that starts without a fleet bucket has nowhere to put a
48-blob, so every R2 method on such a node fails with an explicit error.
50+`list()` fails when it reaches an object that another tool wrote with a
51+percent-encoded key that is not UTF-8, such as `a%FF`.
4952
50-Each binding is a logical bucket with its own `bucket_name`, and celld gives
51-each one a reserved key space in the single fleet bucket. A call to `get()`,
52-`put()`, `head()`, or `delete()` turns the key into `r2/<bucket_name>/<key>`
53-before the call reaches the store. The `bucket_name` comes from the deployment
54-manifest, which validates it, so two bindings cannot collide and no binding can
55-read or overwrite the fleet's own keys.
56-
57-The object store keeps some keys in a percent-encoded form. This applies to a
58-key with a non-ASCII character, a control character, or one of the characters
59-``% \ { } ^ ` [ ] " < > ~ # | * ?``. For example, `přehled.html` becomes the
60-object `r2/<bucket_name>/p%C5%99ehled.html`. The store also keeps each empty
61-segment of a key as `%`, so `photos/` becomes the object
62-`r2/<bucket_name>/photos/%`. Therefore, the keys `a/b`, `/a/b`, `a//b`, and
63-`a/b/` are four different objects, as in Cloudflare R2. `list()` decodes each
64-key, so a listed key is the same key that `put()` received. However, `list()`
65-sorts the keys by the encoded form, and Cloudflare R2 sorts them by UTF-8
66-bytes. Therefore, a key with one of these characters can have a different
67-position in a celld listing. `list()` also compares the `startAfter` option
68-with the encoded form, so a celld listing can return a key that Cloudflare R2
69-skips, or skip a key that Cloudflare R2 returns. For example, Cloudflare R2
70-returns the key `a~` after `startAfter: "aa"`, because `~` sorts after `a`.
71-celld compares `a%7E` with `aa` and skips the key. A `cursor` from a celld
72-listing does not have this problem, because celld made it.
73-
74-A tool other than celld can write an object under `r2/<bucket_name>/` with a
75-percent-encoded key that is not UTF-8, such as `a%FF`. No R2 key can name this
76-object, so `list()` fails when it reaches the object.
77-
7853 celld 0.5.1 and earlier removed each empty segment from a key. An object that
79-such a version wrote under a key like `photos/` stays under `photos`, and
80-`list()` returns it as `photos`.
54+such a version wrote under `photos/` stays under `photos`, and `list()` returns
55+it as `photos`.
8156
82-![Two bindings with different bucket names share one fleet object store, where each key becomes r2 slash bucket name slash key, beside the fleet's own keys](r2-flow.svg)
57+## Multipart uploads
8358
84-`get(key)` returns an `R2ObjectBody`, or `null` when the key is absent. The body
85-arrives as a `ReadableStream` from the host, so a large object never has to fit
86-in the isolate heap. `get()` also accepts a range, and celld accepts every range
87-spelling that R2 accepts: an `offset`, a `length`, a `suffix`, or a `Range`
88-header. `put(key, value, options)` accepts a string, an `ArrayBuffer`, a typed
89-array, a `Blob`, or a `ReadableStream`. celld writes a small body in one
90-request, and a streamed body that grows past 8 MiB becomes a multipart upload to
91-the object store. `delete(keys)` removes up to 1000 keys in one call, and
92-`head(key)` returns the record without the body.
93-
94-celld serves a bucket through the binding only. There is no public bucket URL,
95-no presigned URL, and no S3 endpoint into an R2 binding, so an application must
96-put a Worker in front of the bytes it wants to publish.
97-
98-## Conditional requests and multipart uploads
99-
100-A conditional operation takes an `onlyIf`, either as an `R2Conditional` or as a
101-`Headers` object with `If-Match`, `If-None-Match`, `If-Modified-Since`, or
102-`If-Unmodified-Since`. A refused `get()` answers the record with no body, and a
103-refused `put()` answers `null`. celld passes the precondition to the object
104-store, which applies it. A streamed body larger than 8 MiB becomes a multipart
105-upload, and a multipart completion takes no precondition, so celld refuses a
106-conditional write of such a body instead of dropping the condition.
107-
108-`createMultipartUpload(key)` returns a handle, `uploadPart(number, value)` sends
109-one part, and `complete(parts)` assembles the object. Read
59+A multipart upload lives on the node that opened it. Read
11060 [Multipart upload](https://developers.cloudflare.com/r2/objects/multipart-objects/)
111-for the part-size and part-number rules. celld holds the upload in the node that
112-opened it, because the handle that the object store returns cannot be derived
113-again from an upload id. An upload therefore cannot resume on another node or
114-after a restart.
61+for the part rules. A part that arrives before its predecessor waits in memory,
62+up to 256 MiB, and celld then refuses a further part. A waiting part can be
63+replaced. A part that already went to the object store cannot, and celld
64+refuses that write.
11565
116-celld hands the parts to the object store in ascending order, because the store
117-appends them. A part that arrives before its predecessor waits in memory, and
118-that backlog can reach 256 MiB before celld refuses a further part. A part that
119-is still waiting can be replaced by a second upload of the same number. A part
120-that already went to the store cannot be replaced, so celld refuses that write
121-rather than losing the bytes without a report.
122-
12366 ## Differences from Cloudflare
12467
12568 - An R2 binding uses the fleet bucket under `r2/<bucket_name>/`.
modifieddocs/services/static-assets-flow.svg+106−104View file
@@ -1,4 +1,4 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 674" role="img" aria-labelledby="assetsFlowTitle assetsFlowDesc">
1+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 456 690" role="img" aria-labelledby="assetsFlowTitle assetsFlowDesc">
22 <title id="assetsFlowTitle">How celld decides between an asset and the Worker</title>
33 <desc id="assetsFlowDesc">A request reaches a node and passes down a column of tests. A method other
44 than GET or HEAD leaves at once and the Worker answers. A path that
@@ -45,139 +45,141 @@
4545 }
4646 </style>
4747 <defs>
48- <marker id="sa-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
49- <path class="d-soft" d="M0,1 L9,5 L0,9 z" fill="currentColor" />
48+ <marker id="sa-arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="10"
49+ markerHeight="10" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
50+ <path class="d-acc" fill="none" stroke="currentColor" stroke-width="1" d="M1 1 L5 5 L1 9" />
5051 </marker>
51- <marker id="sa-arrow-acc" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
52- <path class="d-acc" d="M0,1 L9,5 L0,9 z" fill="currentColor" />
52+ <marker id="sa-arrow-acc" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="10"
53+ markerHeight="10" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
54+ <path class="d-acc" fill="none" stroke="currentColor" stroke-width="1" d="M1 1 L5 5 L1 9" />
5355 </marker>
5456 </defs>
5557
5658 <!-- One request enters the column of tests. -->
57- <rect class="d-panel" x="8" y="8" width="228" height="32" rx="6" fill="currentColor" />
58- <rect class="d-ink" x="8" y="8" width="228" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5" />
59- <text class="d-ink" x="122" y="29" fill="currentColor" text-anchor="middle">One request reaches a node</text>
60- <text class="d-faint sm" x="342" y="29" fill="currentColor" text-anchor="middle">who answers, and with what</text>
59+ <rect class="d-panel" x="8" y="8" width="228" height="32" fill="currentColor" />
60+ <rect class="d-ink" x="8" y="8" width="228" height="32" fill="none" stroke="currentColor" stroke-width="1" />
61+ <text class="d-ink" x="122" y="28.5" fill="currentColor" text-anchor="middle">One request reaches a node</text>
62+ <text class="d-faint sm" x="358" y="29" fill="currentColor" text-anchor="middle">who answers, and with what</text>
6163
62- <path class="d-soft" d="M122,40 V62" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
64+ <path class="d-acc" d="M122 40 V61" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
6365
6466 <!-- The method test: only GET and HEAD can reach an asset. -->
65- <rect class="d-panel" x="8" y="62" width="228" height="40" rx="6" fill="currentColor" />
66- <rect class="d-faint" x="8" y="62" width="228" height="40" rx="6" fill="none" stroke="currentColor" />
67- <text class="d-ink" x="20" y="87" fill="currentColor">Method other than GET or HEAD</text>
68- <path class="d-soft" d="M236,82 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
69- <rect class="d-sunk" x="252" y="62" width="180" height="40" rx="6" fill="currentColor" />
70- <rect class="d-soft" x="252" y="62" width="180" height="40" rx="6" fill="none" stroke="currentColor" />
71- <text class="d-ink sm" x="262" y="87" fill="currentColor">the Worker answers</text>
67+ <rect class="d-panel" x="8" y="62" width="228" height="40" fill="currentColor" />
68+ <rect class="d-faint" x="8" y="62" width="228" height="40" fill="none" stroke="currentColor" />
69+ <text class="d-ink" x="20" y="86.5" fill="currentColor">Method other than GET or HEAD</text>
70+ <path class="d-acc" d="M236 82 H267" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
71+ <rect class="d-sunk" x="268" y="62" width="180" height="40" fill="currentColor" />
72+ <rect class="d-soft" x="268" y="62" width="180" height="40" fill="none" stroke="currentColor" />
73+ <text class="d-ink sm" x="278" y="86" fill="currentColor">the Worker answers</text>
7274
73- <path class="d-soft" d="M122,102 V124" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
75+ <path class="d-acc" d="M122 102 V123" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
7476
7577 <!-- run_worker_first inverts the order for the paths it names. -->
76- <rect class="d-panel" x="8" y="124" width="228" height="40" rx="6" fill="currentColor" />
77- <rect class="d-faint" x="8" y="124" width="228" height="40" rx="6" fill="none" stroke="currentColor" />
78- <text class="d-ink mono" x="20" y="143" fill="currentColor">run_worker_first</text>
79- <text class="d-faint sm" x="20" y="158" fill="currentColor">true, or up to 100 patterns</text>
80- <path class="d-soft" d="M236,144 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
81- <rect class="d-sunk" x="252" y="124" width="180" height="40" rx="6" fill="currentColor" />
82- <rect class="d-soft" x="252" y="124" width="180" height="40" rx="6" fill="none" stroke="currentColor" />
83- <text class="d-ink sm" x="262" y="143" fill="currentColor">the Worker answers</text>
84- <text class="d-faint sm" x="262" y="158" fill="currentColor">no asset lookup at all</text>
78+ <rect class="d-panel" x="8" y="124" width="228" height="40" fill="currentColor" />
79+ <rect class="d-faint" x="8" y="124" width="228" height="40" fill="none" stroke="currentColor" />
80+ <text class="d-ink mono" x="20" y="141" fill="currentColor">run_worker_first</text>
81+ <text class="d-faint sm" x="20" y="155" fill="currentColor">true, or up to 100 patterns</text>
82+ <path class="d-acc" d="M236 144 H267" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
83+ <rect class="d-sunk" x="268" y="124" width="180" height="40" fill="currentColor" />
84+ <rect class="d-soft" x="268" y="124" width="180" height="40" fill="none" stroke="currentColor" />
85+ <text class="d-ink sm" x="278" y="141" fill="currentColor">the Worker answers</text>
86+ <text class="d-faint sm" x="278" y="155" fill="currentColor">no asset lookup at all</text>
8587
86- <path class="d-soft" d="M122,164 V186" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
88+ <path class="d-acc" d="M122 164 V185" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
8789
8890 <!-- _redirects runs before any file lookup. -->
89- <rect class="d-panel" x="8" y="186" width="228" height="80" rx="6" fill="currentColor" />
90- <rect class="d-faint" x="8" y="186" width="228" height="80" rx="6" fill="none" stroke="currentColor" />
91- <text class="d-ink mono" x="20" y="218" fill="currentColor">_redirects</text>
92- <text class="d-faint sm" x="20" y="236" fill="currentColor">file order, first match wins</text>
93- <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5">
94- <path d="M236,226 H244" />
95- <path d="M244,204 V248" />
96- <path d="M244,204 H252" marker-end="url(#sa-arrow-acc)" />
97- <path d="M244,248 H252" marker-end="url(#sa-arrow-acc)" />
91+ <rect class="d-panel" x="8" y="186" width="228" height="80" fill="currentColor" />
92+ <rect class="d-faint" x="8" y="186" width="228" height="80" fill="none" stroke="currentColor" />
93+ <text class="d-ink mono" x="20" y="223" fill="currentColor">_redirects</text>
94+ <text class="d-faint sm" x="20" y="237" fill="currentColor">file order, first match wins</text>
95+ <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1">
96+ <path d="M236 226 H252" />
97+ <path d="M252 204 V248" />
98+ <path d="M252 204 H267" marker-end="url(#sa-arrow-acc)" />
99+ <path d="M252 248 H267" marker-end="url(#sa-arrow-acc)" />
98100 </g>
99- <rect class="d-tint" x="252" y="186" width="180" height="36" rx="6" fill="currentColor" />
100- <rect class="d-acc" x="252" y="186" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
101- <text class="d-ink sm" x="262" y="204" fill="currentColor">301 302 303 307 308</text>
102- <text class="d-faint sm" x="262" y="218" fill="currentColor">a Location, no body</text>
103- <rect class="d-tint" x="252" y="230" width="180" height="36" rx="6" fill="currentColor" />
104- <rect class="d-acc" x="252" y="230" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
105- <text class="d-ink sm" x="262" y="248" fill="currentColor">200</text>
106- <text class="d-faint sm" x="262" y="262" fill="currentColor">restart at the destination</text>
101+ <rect class="d-tint" x="268" y="186" width="180" height="36" fill="currentColor" />
102+ <rect class="d-acc" x="268" y="186" width="180" height="36" fill="none" stroke="currentColor" />
103+ <text class="d-ink sm" x="278" y="201" fill="currentColor">301 302 303 307 308</text>
104+ <text class="d-faint sm" x="278" y="215" fill="currentColor">a Location, no body</text>
105+ <rect class="d-tint" x="268" y="230" width="180" height="36" fill="currentColor" />
106+ <rect class="d-acc" x="268" y="230" width="180" height="36" fill="none" stroke="currentColor" />
107+ <text class="d-ink sm" x="278" y="245" fill="currentColor">200</text>
108+ <text class="d-faint sm" x="278" y="259" fill="currentColor">restart at the destination</text>
107109
108- <path class="d-soft" d="M122,266 V288" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
109- <path class="d-acc" d="M268,266 V282 H126" fill="none" stroke="currentColor" stroke-width="1.5" stroke-dasharray="4 3" marker-end="url(#sa-arrow-acc)" />
110+ <path class="d-acc" d="M122 266 V303" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
111+ <path class="d-acc" d="M284 266 V282 H127" fill="none" stroke="currentColor" stroke-width="1" stroke-dasharray="4 3" marker-end="url(#sa-arrow-acc)" />
110112
111113 <!-- html_handling chooses which file a path can reach. -->
112- <rect class="d-panel" x="8" y="288" width="228" height="80" rx="6" fill="currentColor" />
113- <rect class="d-faint" x="8" y="288" width="228" height="80" rx="6" fill="none" stroke="currentColor" />
114- <text class="d-ink mono" x="20" y="320" fill="currentColor">html_handling</text>
115- <text class="d-faint sm" x="20" y="338" fill="currentColor">auto, force, drop, or none</text>
116- <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5">
117- <path d="M236,328 H244" />
118- <path d="M244,306 V350" />
119- <path d="M244,306 H252" marker-end="url(#sa-arrow-acc)" />
120- <path d="M244,350 H252" marker-end="url(#sa-arrow-acc)" />
114+ <rect class="d-panel" x="8" y="304" width="228" height="80" fill="currentColor" />
115+ <rect class="d-faint" x="8" y="304" width="228" height="80" fill="none" stroke="currentColor" />
116+ <text class="d-ink mono" x="20" y="341" fill="currentColor">html_handling</text>
117+ <text class="d-faint sm" x="20" y="355" fill="currentColor">auto, force, drop, or none</text>
118+ <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1">
119+ <path d="M236 344 H252" />
120+ <path d="M252 322 V366" />
121+ <path d="M252 322 H267" marker-end="url(#sa-arrow-acc)" />
122+ <path d="M252 366 H267" marker-end="url(#sa-arrow-acc)" />
121123 </g>
122- <rect class="d-tint" x="252" y="288" width="180" height="36" rx="6" fill="currentColor" />
123- <rect class="d-acc" x="252" y="288" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
124- <text class="d-ink sm" x="262" y="306" fill="currentColor">the canonical path</text>
125- <text class="d-faint sm" x="262" y="320" fill="currentColor">200 with the body</text>
126- <rect class="d-tint" x="252" y="332" width="180" height="36" rx="6" fill="currentColor" />
127- <rect class="d-acc" x="252" y="332" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
128- <text class="d-ink sm" x="262" y="350" fill="currentColor">another spelling</text>
129- <text class="d-faint sm" x="262" y="364" fill="currentColor">307 to the canonical path</text>
124+ <rect class="d-tint" x="268" y="304" width="180" height="36" fill="currentColor" />
125+ <rect class="d-acc" x="268" y="304" width="180" height="36" fill="none" stroke="currentColor" />
126+ <text class="d-ink sm" x="278" y="319" fill="currentColor">the canonical path</text>
127+ <text class="d-faint sm" x="278" y="333" fill="currentColor">200 with the body</text>
128+ <rect class="d-tint" x="268" y="348" width="180" height="36" fill="currentColor" />
129+ <rect class="d-acc" x="268" y="348" width="180" height="36" fill="none" stroke="currentColor" />
130+ <text class="d-ink sm" x="278" y="363" fill="currentColor">another spelling</text>
131+ <text class="d-faint sm" x="278" y="377" fill="currentColor">307 to the canonical path</text>
130132
131- <path class="d-soft" d="M122,368 V390" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
133+ <path class="d-acc" d="M122 384 V405" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
132134
133135 <!-- The step Cloudflare does not need: a rolling restart leaves nodes on
134136 different indexes, so a miss re-reads the pointer. -->
135- <rect class="d-panel" x="8" y="390" width="228" height="44" rx="6" fill="currentColor" />
136- <rect class="d-faint" x="8" y="390" width="228" height="44" rx="6" fill="none" stroke="currentColor" />
137- <text class="d-ink" x="20" y="411" fill="currentColor">Miss: re-read the pointer</text>
138- <text class="d-faint sm" x="20" y="427" fill="currentColor">at most once in five seconds</text>
139- <path class="d-acc" d="M236,412 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow-acc)" />
140- <rect class="d-tint" x="252" y="390" width="180" height="44" rx="6" fill="currentColor" />
141- <rect class="d-acc" x="252" y="390" width="180" height="44" rx="6" fill="none" stroke="currentColor" />
142- <text class="d-ink sm" x="262" y="411" fill="currentColor">a newer deployment has it</text>
143- <text class="d-faint sm" x="262" y="427" fill="currentColor">200 with the body</text>
137+ <rect class="d-panel" x="8" y="406" width="228" height="44" fill="currentColor" />
138+ <rect class="d-faint" x="8" y="406" width="228" height="44" fill="none" stroke="currentColor" />
139+ <text class="d-ink" x="20" y="425.5" fill="currentColor">Miss: re-read the pointer</text>
140+ <text class="d-faint sm" x="20" y="439.5" fill="currentColor">at most once in five seconds</text>
141+ <path class="d-acc" d="M236 428 H267" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow-acc)" />
142+ <rect class="d-tint" x="268" y="406" width="180" height="44" fill="currentColor" />
143+ <rect class="d-acc" x="268" y="406" width="180" height="44" fill="none" stroke="currentColor" />
144+ <text class="d-ink sm" x="278" y="425" fill="currentColor">a newer deployment has it</text>
145+ <text class="d-faint sm" x="278" y="439" fill="currentColor">200 with the body</text>
144146
145- <path class="d-soft" d="M122,434 V456" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
147+ <path class="d-acc" d="M122 450 V471" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
146148
147149 <!-- not_found_handling fabricates a response, but not for every request. -->
148- <rect class="d-panel" x="8" y="456" width="228" height="80" rx="6" fill="currentColor" />
149- <rect class="d-faint" x="8" y="456" width="228" height="80" rx="6" fill="none" stroke="currentColor" />
150- <text class="d-ink mono" x="20" y="488" fill="currentColor">not_found_handling</text>
151- <text class="d-faint sm" x="20" y="506" fill="currentColor">navigation, or no Worker</text>
152- <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5">
153- <path d="M236,496 H244" />
154- <path d="M244,474 V518" />
155- <path d="M244,474 H252" marker-end="url(#sa-arrow-acc)" />
156- <path d="M244,518 H252" marker-end="url(#sa-arrow-acc)" />
150+ <rect class="d-panel" x="8" y="472" width="228" height="80" fill="currentColor" />
151+ <rect class="d-faint" x="8" y="472" width="228" height="80" fill="none" stroke="currentColor" />
152+ <text class="d-ink mono" x="20" y="509" fill="currentColor">not_found_handling</text>
153+ <text class="d-faint sm" x="20" y="523" fill="currentColor">navigation, or no Worker</text>
154+ <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1">
155+ <path d="M236 512 H252" />
156+ <path d="M252 490 V534" />
157+ <path d="M252 490 H267" marker-end="url(#sa-arrow-acc)" />
158+ <path d="M252 534 H267" marker-end="url(#sa-arrow-acc)" />
157159 </g>
158- <rect class="d-tint" x="252" y="456" width="180" height="36" rx="6" fill="currentColor" />
159- <rect class="d-acc" x="252" y="456" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
160- <text class="d-ink sm" x="262" y="474" fill="currentColor">single-page-application</text>
161- <text class="d-faint sm" x="262" y="488" fill="currentColor">/index.html, 200</text>
162- <rect class="d-tint" x="252" y="500" width="180" height="36" rx="6" fill="currentColor" />
163- <rect class="d-acc" x="252" y="500" width="180" height="36" rx="6" fill="none" stroke="currentColor" />
164- <text class="d-ink sm" x="262" y="518" fill="currentColor">404-page</text>
165- <text class="d-faint sm" x="262" y="532" fill="currentColor">the nearest 404.html, 404</text>
160+ <rect class="d-tint" x="268" y="472" width="180" height="36" fill="currentColor" />
161+ <rect class="d-acc" x="268" y="472" width="180" height="36" fill="none" stroke="currentColor" />
162+ <text class="d-ink sm" x="278" y="487" fill="currentColor">single-page-application</text>
163+ <text class="d-faint sm" x="278" y="501" fill="currentColor">/index.html, 200</text>
164+ <rect class="d-tint" x="268" y="516" width="180" height="36" fill="currentColor" />
165+ <rect class="d-acc" x="268" y="516" width="180" height="36" fill="none" stroke="currentColor" />
166+ <text class="d-ink sm" x="278" y="531" fill="currentColor">404-page</text>
167+ <text class="d-faint sm" x="278" y="545" fill="currentColor">the nearest 404.html, 404</text>
166168
167- <path class="d-soft" d="M122,536 V558" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
169+ <path class="d-acc" d="M122 552 V573" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
168170
169171 <!-- The asset layer has no answer left. -->
170- <rect class="d-panel" x="8" y="558" width="228" height="44" rx="6" fill="currentColor" />
171- <rect class="d-ink" x="8" y="558" width="228" height="44" rx="6" fill="none" stroke="currentColor" stroke-width="1.5" />
172- <text class="d-ink" x="20" y="585" fill="currentColor">Nothing matched</text>
173- <path class="d-soft" d="M236,580 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" />
174- <rect class="d-sunk" x="252" y="558" width="180" height="44" rx="6" fill="currentColor" />
175- <rect class="d-soft" x="252" y="558" width="180" height="44" rx="6" fill="none" stroke="currentColor" />
176- <text class="d-ink sm" x="262" y="579" fill="currentColor">the Worker answers</text>
177- <text class="d-faint sm" x="262" y="595" fill="currentColor">no Worker: 404</text>
172+ <rect class="d-panel" x="8" y="574" width="228" height="44" fill="currentColor" />
173+ <rect class="d-ink" x="8" y="574" width="228" height="44" fill="none" stroke="currentColor" stroke-width="1" />
174+ <text class="d-ink" x="20" y="600.5" fill="currentColor">Nothing matched</text>
175+ <path class="d-acc" d="M236 596 H267" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#sa-arrow)" />
176+ <rect class="d-sunk" x="268" y="574" width="180" height="44" fill="currentColor" />
177+ <rect class="d-soft" x="268" y="574" width="180" height="44" fill="none" stroke="currentColor" />
178+ <text class="d-ink sm" x="278" y="593" fill="currentColor">the Worker answers</text>
179+ <text class="d-faint sm" x="278" y="607" fill="currentColor">no Worker: 404</text>
178180
179181 <!-- The one outcome that never reaches the Worker. -->
180- <rect class="d-faint" x="8" y="624" width="424" height="42" rx="6" fill="none" stroke="currentColor" stroke-dasharray="5 4" />
181- <text class="d-ink sm" x="20" y="644" fill="currentColor">A missing or corrupt asset body gives 502.</text>
182- <text class="d-faint sm" x="20" y="659" fill="currentColor">The request never falls through to the Worker.</text>
182+ <rect class="d-faint" x="8" y="640" width="440" height="42" fill="none" stroke="currentColor" stroke-dasharray="5 4" />
183+ <text class="d-ink sm" x="20" y="658" fill="currentColor">A missing or corrupt asset body gives 502.</text>
184+ <text class="d-faint sm" x="20" y="672" fill="currentColor">The request never falls through to the Worker.</text>
183185 </svg>
modifieddocs/services/static-assets.md+61−102View file
@@ -1,11 +1,9 @@
11 # Static assets
22
3-Static assets serve the files of a directory, with a Worker or without one. An
4-application uses them for the front end that a browser downloads: an HTML page,
5-a stylesheet, a script bundle, a font, or an image. `celld deploy` uploads the
6-directory with the deployment, so the files become part of the deployed version
7-and not a separate store. The bytes live in the fleet bucket, and a node copies
8-a file to its own disk cache when it first serves that file. Read the
3+Static assets serve the files of a directory, with a Worker or without one.
4+`celld deploy` uploads the directory to the fleet bucket with the deployment,
5+and a node caches a file on its own disk when it first serves that file. Read
6+the
97 [Cloudflare Static Assets documentation](https://developers.cloudflare.com/workers/static-assets/)
108 for the standard behavior.
119
@@ -17,109 +15,73 @@
1715
1816 <!-- celld-example: static-assets -->
1917
20-## What a deployment uploads
18+## API
2119
22-An `assets` block in the Wrangler configuration names the directory. celld
23-accepts five keys in that block: `directory`, `binding`, `html_handling`,
24-`not_found_handling`, and `run_worker_first`. It refuses any other key by name,
25-so an unsupported Cloudflare option stops the deployment instead of changing the
26-behavior in silence. A project that declares `assets` and no `main` is an
27-asset-only project, and such a project cannot set `run_worker_first` or declare
28-a binding, because it runs no code. The
29-[binding documentation](https://developers.cloudflare.com/workers/static-assets/binding/)
30-describes the same keys for Cloudflare.
20+The `assets` block configures the directory and the routing:
3121
32-`celld deploy` reads each file, takes the SHA-256 digest of the exact bytes, and
33-stores the body once under that digest. Two identical files in one directory
34-therefore upload one body. A redeploy compares the digest with the stored object
35-and skips a body that the fleet already holds, so a build that changes one file
36-uploads one file. The command also assigns a content type from a fixed table of
37-file extensions. An unknown extension gets no `Content-Type` header at all,
38-which is the behavior that Wrangler produces.
22+- `directory` names the directory to upload.
23+- `binding` exposes `env.ASSETS.fetch()` to a Worker.
24+- `html_handling` maps a path to an HTML file.
25+- `not_found_handling` selects `single-page-application` or `404-page`.
26+- `run_worker_first` sends a matching request to the Worker first.
27+- A `_headers` file and a `_redirects` file in the directory set headers and
28+ redirects.
3929
40-The upload produces an index beside the deployment manifest. The index maps each
41-path to its digest, its size, and its content type, and it carries the `assets`
42-configuration and the complete text of the `_headers` and `_redirects` files.
43-The manifest names the index and the checksum of the index. celld writes the
44-bodies first, then the index, then the manifest, and the deployment pointer
45-last. A node therefore cannot read a pointer whose bodies are still incomplete.
46-A node loads only the index at startup and fetches a body when a request asks
47-for it, so a large asset directory does not become a large startup cost.
30+## Deployment
4831
49-## The routing decision
32+The `assets` block accepts `directory`, `binding`, `html_handling`,
33+`not_found_handling`, and `run_worker_first`. Any other key stops the
34+deployment. A project with `assets` and no `main` cannot set `run_worker_first`
35+or declare a binding.
5036
51-A request meets the asset layer before it meets the Worker. celld considers only
52-a `GET` or a `HEAD` request for an asset, and it sends every other method to the
53-Worker. `run_worker_first` reverses the order. It takes `true`, or a list of up
54-to 100 route patterns in which a `!` prefix excludes a path, and a match sends
55-the request to the Worker with no asset lookup. The exact `/` pattern sends only
56-the root path to the Worker. Cloudflare describes the same control in its
57-[Worker script routing documentation](https://developers.cloudflare.com/workers/static-assets/routing/worker-script/).
37+`celld deploy` stores each file body once under its SHA-256 digest, and a
38+redeploy uploads only the changed bodies. A file with an unknown extension gets
39+no `Content-Type` header, as with Wrangler.
5840
59-![The routing decision for one request: the method test, run_worker_first, the _redirects rules, the html_handling lookup, the pointer re-read after a miss, not_found_handling, and the fall through to the Worker](static-assets-flow.svg)
41+## Routing
6042
61-The `_redirects` rules run before any file lookup, in file order, and the first
62-match wins. A rule with status 301, 302, 303, 307, or 308 answers with a
63-`Location` header. A rule with status 200 names a local path, and routing
64-restarts at that path, so the client sees the destination content under the
65-original URL.
43+celld looks up an asset only for a `GET` or a `HEAD` request. Every other
44+method goes to the Worker. `run_worker_first` takes `true`, or a list of up to
45+100 route patterns in which a `!` prefix excludes a path. A match sends the
46+request to the Worker first. The exact `/` pattern matches only the root path.
6647
67-`html_handling` then decides which file a path can reach.
68-`auto-trailing-slash` is the default, and it maps `/about` to `/about.html` and
69-`/about/` to `/about/index.html`. `force-trailing-slash` and
70-`drop-trailing-slash` pick one spelling, and `none` matches the exact path only.
71-When the request uses a spelling that is not the canonical one, celld answers
72-`307` to the canonical path and keeps the query string. The
73-[html_handling documentation](https://developers.cloudflare.com/workers/static-assets/routing/advanced/html-handling/)
74-lists the same four modes.
48+![The routing decision for one request: the method test, run_worker_first, the _redirects rules, the html_handling lookup, the pointer re-read after a miss, not_found_handling, and the fall through to the Worker](static-assets-flow.svg)
7549
76-A miss has one more step that Cloudflare does not need. celld re-reads the
77-deployment pointer, at most once in five seconds, because a rolling restart can
78-leave one node on an older index while an upgraded node serves HTML that names a
79-newer content-hashed file. A newer index therefore answers the request instead
80-of a broken page.
50+The `_redirects` rules run before any file lookup, and the first match wins. A
51+rule with status 301, 302, 303, 307, or 308 answers with a `Location` header. A
52+rule with status 200 restarts routing at the local path and keeps the original
53+URL.
8154
82-`not_found_handling` fabricates the last answer. `single-page-application`
83-returns `/index.html` with status 200, and `404-page` returns the nearest
84-`404.html` with status 404, which
85-[Cloudflare also does](https://developers.cloudflare.com/workers/static-assets/routing/single-page-application/).
86-celld applies this step only when the deployment has no Worker, or when the
87-request is a navigation request. A deployment with a Worker therefore keeps a
88-non-navigation miss for the Worker, and the Worker answers it. When nothing
89-matches and there is no Worker, the node answers `404`.
55+`html_handling` is `auto-trailing-slash` by default, which maps `/about` to
56+`/about.html` and `/about/` to `/about/index.html`. The other modes are
57+`force-trailing-slash`, `drop-trailing-slash`, and `none`. A non-canonical
58+spelling gets a `307` to the canonical path with the query string.
9059
91-One failure never reaches the Worker. A body that the fleet bucket cannot supply
92-gives `502`, because a silent fall through would run the Worker for a request
93-that an asset owns.
60+After a miss, a node re-reads the deployment pointer at most once in five
61+seconds. During a rolling restart, a newer index can then serve a file that an
62+upgraded node references.
9463
95-## How a node serves a file
64+`not_found_handling` set to `single-page-application` returns `/index.html`
65+with status 200, and `404-page` returns the nearest `404.html` with status 404.
66+With a Worker, celld applies it only to a navigation request, and the Worker
67+answers any other miss. With no Worker and no match, the node answers `404`. A
68+body that the fleet bucket cannot supply gives `502` and never reaches the
69+Worker.
9670
97-A node fetches a body once and writes it to a local disk cache. It verifies the
98-digest after the write, and it keeps the cache under a bound of 512 MiB that
99-`CELLD_ASSET_CACHE_BYTES` changes. The cache evicts the least recently used file
100-when it crosses the bound, so the cache is a copy and never the durable record.
101-The fleet bucket holds the durable bytes.
71+## Responses
10272
103-The `ETag` is the strong SHA-256 digest of the body. A conditional `GET` with
104-`If-None-Match` therefore gives `304` with no body, and a changed file gives a
105-new tag. celld sends no `Last-Modified` header and reads no `If-Modified-Since`
106-header, so revalidation uses the tag. A `Range` header selects one byte range
107-and gives `206`, an unsatisfiable range gives `416`, and a `HEAD` request keeps
108-the real `Content-Length` with an empty body. celld also sends
109-`Cache-Control: public, max-age=0, must-revalidate` on a plain request, which
110-makes a browser revalidate each time.
73+The disk cache holds 512 MiB by default, and `CELLD_ASSET_CACHE_BYTES` changes
74+it. The cache evicts the least recently used file.
11175
112-celld runs no edge cache and no content delivery network, so this response path
113-is the whole of it. Cloudflare caches an asset in the location that serves the
114-request and pulls a miss from a nearby cache. A celld fleet has only the
115-machines that you run. Latency comes from your own placement, and a `_headers`
116-rule that sets a long `Cache-Control` on a content-hashed file is the way to
117-keep a browser from asking again.
76+The `ETag` is the strong SHA-256 digest of the body, so `If-None-Match` gives
77+`304`. A `Range` header gives `206`, an unsatisfiable range gives `416`, and a
78+`HEAD` response keeps the real `Content-Length`. A plain response carries
79+`Cache-Control: public, max-age=0, must-revalidate`. Use a `_headers` rule to
80+set a long `Cache-Control` on a content-hashed file.
11881
119-A `binding` name puts the same serving code behind `env.ASSETS.fetch()`. The
120-binding takes a `Request`, a `URL`, or a string, and `fetch()` is its only
121-method. It answers `405` for a method other than `GET` or `HEAD`, and it always
122-applies `not_found_handling`, so a Worker can render a fallback page itself.
82+A `binding` exposes `env.ASSETS.fetch()`, which takes a `Request`, a `URL`, or a
83+string. It answers `405` for a method other than `GET` or `HEAD`, and it always
84+applies `not_found_handling`.
12385
12486 ## Differences from Cloudflare
12587
@@ -133,15 +95,12 @@
13395 and reads no `If-Modified-Since` header.
13496 - A `_headers` file cannot change `connection`, `content-length`, or
13597 `transfer-encoding`.
136-- A deployment can contain 20,000 assets and 1 GiB in total. The per-file
137- default is 25 MiB; set `CELLD_MAX_ASSET_FILE_BYTES` to a positive byte count
138- consistently on the deployment builder, managed deployment agent, and serving
139- nodes to change it. The per-file limit stays fixed after its first use, so
140- restart the process to apply a new value. When a file exceeds this limit,
141- the deployment builder, the managed agent, and the serving node report its
142- path, its size, and the limit.
143- The total deployment bound still applies. Each `_headers` or `_redirects`
144- file has a 100 KiB limit.
98+- A deployment can contain 20,000 assets and 1 GiB in total. A file can be at
99+ most 25 MiB. `CELLD_MAX_ASSET_FILE_BYTES` changes the per-file limit, and it
100+ must have the same value on the deployment builder, the managed deployment
101+ agent, and the serving nodes. A process reads it once, so a new value needs
102+ a restart. An error for a file that is too large reports its path, its size,
103+ and the limit. Each `_headers` or `_redirects` file has a 100 KiB limit.
145104 - `celld deploy` accepts only `directory`, `binding`, `html_handling`,
146105 `not_found_handling`, and `run_worker_first` in the `assets` block.
147106 - `celld deploy` refuses a `.assetsignore` file, and it stops the deployment
modifieddocs/services/workers-flow.svg+57−55View file
@@ -8,7 +8,7 @@
88 default, and a class that sets only `color` never reaches the fill, so
99 every label sets fill="currentColor" as well. */
1010 svg { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; }
11- text { font-size: 13px; fill: currentColor; }
11+ text { font-size: 12px; fill: currentColor; }
1212 .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
1313 .d-ink { color: #121212; }
1414 .d-soft { color: #3d3b37; }
@@ -28,84 +28,86 @@
2828 }
2929 </style>
3030 <defs>
31- <marker id="wf-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
32- <path class="d-soft" d="M0,1 L9,5 L0,9 z" fill="currentColor"/>
31+ <marker id="wf-arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="10"
32+ markerHeight="10" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
33+ <path class="d-acc" fill="none" stroke="currentColor" stroke-width="1" d="M1 1 L5 5 L1 9" />
3334 </marker>
34- <marker id="wf-arrow-acc" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
35- <path class="d-acc" d="M0,1 L9,5 L0,9 z" fill="currentColor"/>
35+ <marker id="wf-arrow-acc" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="10"
36+ markerHeight="10" markerUnits="userSpaceOnUse" orient="auto-start-reverse">
37+ <path class="d-acc" fill="none" stroke="currentColor" stroke-width="1" d="M1 1 L5 5 L1 9" />
3638 </marker>
3739 </defs>
3840
3941 <!-- client and ingress: TLS ends outside celld -->
40- <rect class="d-panel" x="110" y="8" width="180" height="34" rx="6" fill="currentColor"/>
41- <rect class="d-ink" x="110" y="8" width="180" height="34" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
42- <text class="d-ink" x="200" y="30" fill="currentColor" text-anchor="middle">HTTP client</text>
43- <path class="d-soft" d="M200,42 V58" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
42+ <rect class="d-panel" x="110" y="8" width="180" height="34" fill="currentColor"/>
43+ <rect class="d-ink" x="110" y="8" width="180" height="34" fill="none" stroke="currentColor" stroke-width="1"/>
44+ <text class="d-ink" x="200" y="29.5" fill="currentColor" text-anchor="middle">HTTP client</text>
45+ <path class="d-acc" d="M200,42 V61" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
4446
45- <rect class="d-panel" x="70" y="62" width="260" height="46" rx="6" fill="currentColor"/>
46- <rect class="d-ink" x="70" y="62" width="260" height="46" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
47- <text class="d-ink" x="200" y="84" fill="currentColor" text-anchor="middle">Ingress or load balancer</text>
48- <text class="d-soft" x="200" y="101" fill="currentColor" text-anchor="middle">terminates TLS</text>
47+ <rect class="d-panel" x="70" y="62" width="260" height="46" fill="currentColor"/>
48+ <rect class="d-ink" x="70" y="62" width="260" height="46" fill="none" stroke="currentColor" stroke-width="1"/>
49+ <text class="d-ink" x="200" y="82.5" fill="currentColor" text-anchor="middle">Ingress or load balancer</text>
50+ <text class="d-soft" x="200" y="96.5" fill="currentColor" text-anchor="middle">terminates TLS</text>
4951
5052 <!-- any node of the fleet can accept the request -->
51- <path class="d-soft" d="M200,108 C200,124 66,114 66,126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
52- <path class="d-soft" d="M200,108 V126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
53- <path class="d-soft" d="M200,108 C200,124 334,114 334,126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
53+ <path class="d-acc" d="M200 108 V120 H66 V131" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
54+ <path class="d-acc" d="M200,108 V131" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
55+ <path class="d-acc" d="M200 108 V120 H334 V131" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
5456
55- <rect class="d-ink" x="8" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
56- <text class="d-ink" x="66" y="153" fill="currentColor" text-anchor="middle">celld node</text>
57- <rect class="d-acc" x="142" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
58- <text class="d-ink" x="200" y="153" fill="currentColor" text-anchor="middle">celld node</text>
59- <rect class="d-ink" x="276" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
60- <text class="d-ink" x="334" y="153" fill="currentColor" text-anchor="middle">celld node</text>
57+ <rect class="d-ink" x="8" y="132" width="116" height="32" fill="none" stroke="currentColor" stroke-width="1"/>
58+ <text class="d-ink" x="66" y="152.5" fill="currentColor" text-anchor="middle">celld node</text>
59+ <rect class="d-acc" x="142" y="132" width="116" height="32" fill="none" stroke="currentColor" stroke-width="1"/>
60+ <text class="d-ink" x="200" y="152.5" fill="currentColor" text-anchor="middle">celld node</text>
61+ <rect class="d-ink" x="276" y="132" width="116" height="32" fill="none" stroke="currentColor" stroke-width="1"/>
62+ <text class="d-ink" x="334" y="152.5" fill="currentColor" text-anchor="middle">celld node</text>
6163
62- <path class="d-soft" d="M200,164 V184" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
64+ <path class="d-acc" d="M200,164 V187" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
6365 <text class="d-faint" x="208" y="180" fill="currentColor">any node</text>
6466
6567 <!-- the isolate of the accepting node -->
66- <rect class="d-sunk" x="20" y="188" width="360" height="124" rx="8" fill="currentColor"/>
67- <rect class="d-ink" x="20" y="188" width="360" height="124" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/>
68+ <rect class="d-sunk" x="20" y="188" width="360" height="124" fill="currentColor"/>
69+ <rect class="d-ink" x="20" y="188" width="360" height="124" fill="none" stroke="currentColor" stroke-width="1"/>
6870 <text class="d-soft" x="200" y="211" fill="currentColor" text-anchor="middle">Worker deployment in a V8 isolate</text>
6971
70- <rect class="d-tint" x="60" y="220" width="280" height="32" rx="6" fill="currentColor"/>
71- <rect class="d-acc" x="60" y="220" width="280" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
72- <text class="d-ink mono" x="200" y="241" fill="currentColor" text-anchor="middle">fetch(request, env, ctx)</text>
72+ <rect class="d-tint" x="60" y="220" width="280" height="32" fill="currentColor"/>
73+ <rect class="d-acc" x="60" y="220" width="280" height="32" fill="none" stroke="currentColor" stroke-width="1"/>
74+ <text class="d-ink mono" x="200" y="240" fill="currentColor" text-anchor="middle">fetch(request, env, ctx)</text>
7375
74- <path class="d-soft" d="M150,252 C150,268 110,258 110,268" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/>
75- <path class="d-acc" d="M250,252 C250,268 290,258 290,268" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/>
76+ <path class="d-acc" d="M150 252 V262 H110 V271" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow)"/>
77+ <path class="d-acc" d="M250 252 V262 H290 V271" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow-acc)"/>
7678
77- <rect class="d-panel" x="40" y="272" width="140" height="30" rx="6" fill="currentColor"/>
78- <rect class="d-ink" x="40" y="272" width="140" height="30" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
79- <text class="d-ink" x="110" y="292" fill="currentColor" text-anchor="middle">Response</text>
79+ <rect class="d-panel" x="40" y="272" width="140" height="30" fill="currentColor"/>
80+ <rect class="d-ink" x="40" y="272" width="140" height="30" fill="none" stroke="currentColor" stroke-width="1"/>
81+ <text class="d-ink" x="110" y="291.5" fill="currentColor" text-anchor="middle">Response</text>
8082
81- <rect class="d-panel" x="228" y="272" width="124" height="30" rx="6" fill="currentColor"/>
82- <rect class="d-acc" x="228" y="272" width="124" height="30" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
83- <text class="d-ink mono" x="290" y="292" fill="currentColor" text-anchor="middle">env</text>
83+ <rect class="d-panel" x="228" y="272" width="124" height="30" fill="currentColor"/>
84+ <rect class="d-acc" x="228" y="272" width="124" height="30" fill="none" stroke="currentColor" stroke-width="1"/>
85+ <text class="d-ink mono" x="290" y="291" fill="currentColor" text-anchor="middle">env</text>
8486
8587 <!-- a binding call leaves the isolate, and its target decides where it goes -->
86- <path class="d-acc" d="M290,302 V330" fill="none" stroke="currentColor" stroke-width="1.5"/>
87- <path class="d-acc" d="M142,330 H338" fill="none" stroke="currentColor" stroke-width="1.5"/>
88- <path class="d-acc" d="M142,330 V348" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/>
89- <path class="d-acc" d="M338,330 V348" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/>
88+ <path class="d-acc" d="M290,302 V330" fill="none" stroke="currentColor" stroke-width="1"/>
89+ <path class="d-acc" d="M142,330 H338" fill="none" stroke="currentColor" stroke-width="1"/>
90+ <path class="d-acc" d="M142,330 V351" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow-acc)"/>
91+ <path class="d-acc" d="M338,330 V351" fill="none" stroke="currentColor" stroke-width="1" marker-end="url(#wf-arrow-acc)"/>
9092 <text class="d-faint" x="96" y="326" fill="currentColor" text-anchor="middle">to the owner</text>
9193 <text class="d-faint" x="366" y="326" fill="currentColor" text-anchor="middle">direct</text>
9294
93- <rect class="d-soft" x="8" y="352" width="268" height="92" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/>
95+ <rect class="d-soft" x="8" y="352" width="268" height="92" fill="none" stroke="currentColor" stroke-width="1"/>
9496 <text class="d-ink" x="142" y="370" fill="currentColor" text-anchor="middle">cells</text>
95- <text class="d-faint" x="142" y="386" fill="currentColor" text-anchor="middle">one owner node each</text>
96- <rect class="d-soft" x="14" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
97- <text class="d-ink" x="43" y="419" fill="currentColor" text-anchor="middle">KV</text>
98- <rect class="d-soft" x="78" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
99- <text class="d-ink" x="107" y="419" fill="currentColor" text-anchor="middle">D1</text>
100- <rect class="d-soft" x="142" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
101- <text class="d-ink" x="171" y="419" fill="currentColor" text-anchor="middle">Queues</text>
102- <rect class="d-soft" x="206" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
103- <text class="d-ink" x="235" y="412" fill="currentColor" text-anchor="middle">Durable</text>
104- <text class="d-ink" x="235" y="427" fill="currentColor" text-anchor="middle">Objects</text>
97+ <text class="d-faint" x="142" y="384" fill="currentColor" text-anchor="middle">one owner node each</text>
98+ <rect class="d-soft" x="14" y="394" width="58" height="40" fill="none" stroke="currentColor" stroke-width="1"/>
99+ <text class="d-ink" x="43" y="418.5" fill="currentColor" text-anchor="middle">KV</text>
100+ <rect class="d-soft" x="78" y="394" width="58" height="40" fill="none" stroke="currentColor" stroke-width="1"/>
101+ <text class="d-ink" x="107" y="418.5" fill="currentColor" text-anchor="middle">D1</text>
102+ <rect class="d-soft" x="142" y="394" width="58" height="40" fill="none" stroke="currentColor" stroke-width="1"/>
103+ <text class="d-ink" x="171" y="418.5" fill="currentColor" text-anchor="middle">Queues</text>
104+ <rect class="d-soft" x="206" y="394" width="58" height="40" fill="none" stroke="currentColor" stroke-width="1"/>
105+ <text class="d-ink" x="235" y="411.5" fill="currentColor" text-anchor="middle">Durable</text>
106+ <text class="d-ink" x="235" y="425.5" fill="currentColor" text-anchor="middle">Objects</text>
105107
106- <rect class="d-soft" x="284" y="352" width="108" height="92" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/>
108+ <rect class="d-soft" x="284" y="352" width="108" height="92" fill="none" stroke="currentColor" stroke-width="1"/>
107109 <text class="d-ink" x="338" y="370" fill="currentColor" text-anchor="middle">fleet bucket</text>
108- <text class="d-faint" x="338" y="386" fill="currentColor" text-anchor="middle">no owner</text>
109- <rect class="d-soft" x="292" y="394" width="92" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
110- <text class="d-ink" x="338" y="419" fill="currentColor" text-anchor="middle">R2</text>
110+ <text class="d-faint" x="338" y="384" fill="currentColor" text-anchor="middle">no owner</text>
111+ <rect class="d-soft" x="292" y="394" width="92" height="40" fill="none" stroke="currentColor" stroke-width="1"/>
112+ <text class="d-ink" x="338" y="418.5" fill="currentColor" text-anchor="middle">R2</text>
111113 </svg>
modifieddocs/services/workers.md+64−115View file
@@ -1,12 +1,8 @@
11 # Workers
22
3-A Worker is a stateless request handler that uses the Cloudflare Workers API.
4-An application uses a Worker for the code that answers an HTTP request, such as
5-an API endpoint, a router, a webhook receiver, or a front end for a binding.
6-celld runs the deployment in a V8 isolate on a node of the fleet, so a Worker
7-keeps the persistent state of an application in a binding instead. Read the
8-[Cloudflare Workers documentation](https://developers.cloudflare.com/workers/runtime-apis/)
9-for the standard API behavior.
3+A Worker is a stateless request handler that uses the
4+[Cloudflare Workers API](https://developers.cloudflare.com/workers/runtime-apis/).
5+celld runs the deployment in a V8 isolate on every node of the fleet.
106
117 ## Example
128
@@ -15,139 +11,94 @@
1511
1612 <!-- celld-example: hello -->
1713
18-## The request path
14+## API
1915
20-An operator puts an ingress proxy or a load balancer in front of the fleet.
21-The ingress terminates TLS, because celld serves plain HTTP on the public
22-listener of a node. The load balancer can send a request to any node in its
23-rotation, and every node embeds V8 and holds the current deployment. The node
24-that accepts the request therefore runs the handler itself, and it forwards
25-only a binding call that a different node owns.
16+- `fetch(request, env, ctx)` is the default export. It receives the inbound
17+ `Request` and returns a `Response`.
18+- `scheduled` handles a Cron Trigger, and `queue` handles a Queues consumer.
19+- `env` holds the bindings that the Wrangler configuration declares.
20+- `ctx.waitUntil(promise)` keeps the isolate alive for the promise after the
21+ response goes to the client.
2622
27-Cloudflare instead routes a request through its own global network and starts
28-the Worker in a nearby data center. A celld fleet has only the machines that
29-you run, so you control the placement and the routing. Read
30-[How Workers works](https://developers.cloudflare.com/workers/reference/how-workers-works/)
31-for the Cloudflare model.
32-
33-![An ingress terminates TLS and sends a request to any celld node, which runs the Worker in a V8 isolate, while a binding call goes to the node that owns the cell or to the fleet bucket](workers-flow.svg)
34-
35-## The handler
36-
37-An HTTP request invokes the `fetch(request, env, ctx)` handler that the module
38-exports as its default export. The handler receives the inbound `Request`, and
39-it must return a `Response`. A module can export more handlers, such as
40-`scheduled` for a Cron Trigger or `queue` for a Queues consumer. Each export of
41-the main module must be a handler object or a class, as in workerd. A Worker
42-whose main module exports a string or a number therefore fails to start. Read
43-the
23+Read the
4424 [handlers documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/)
45-for the complete list, and the
46-[fetch handler documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/)
47-for the parameters.
25+for the complete list.
4826
49-The `ctx` argument controls the lifetime of the invocation. `ctx.waitUntil()`
50-keeps the isolate alive for a promise after the response goes to the client.
51-`ctx.passThroughOnException()` has no effect on celld, because celld has no CDN
52-that can answer in place of a failed Worker.
27+## The request path
5328
54-## State and bindings
29+celld serves plain HTTP, so an ingress proxy must terminate TLS. A load
30+balancer can send a request to any node, because every node holds the current
31+deployment. That node runs the handler, and it forwards a binding call to the
32+node that owns the cell. An R2 binding reads and writes the fleet bucket
33+directly.
5534
56-The `env` argument contains the bindings that the Wrangler configuration
57-declares. A binding gives the Worker a permission and an API together, so the
58-code needs no credential for the target service. Read the
59-[bindings documentation](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
60-for the configuration syntax.
35+![An ingress terminates TLS and sends a request to any celld node, which runs the Worker in a V8 isolate, while a binding call goes to the node that owns the cell or to the fleet bucket](workers-flow.svg)
6136
62-A binding call leaves the isolate, and the target decides where the call goes.
63-A KV namespace, a D1 database, a queue, and a Durable Object are each a cell,
64-and one node owns a cell at a time, so celld routes the call to that owner. An
65-R2 binding has no cell, and it reads and writes the fleet bucket directly.
37+Each export of the main module must be a handler object or a class, as in
38+workerd, so a main module that exports a string or a number fails to start.
6639
67-celld runs many requests in one isolate, so a value in the module scope can
68-still be present for a later request. That value is not a safe place for
69-application state. The load balancer can send the next request to a different
70-node, and celld retires an isolate when the request load falls or when a new
71-deployment supersedes it, so the value can also disappear. A Worker must
72-therefore not depend on mutable in-memory state, and it must write the state
73-that it must keep into a binding. The Cloudflare
74-[best practices](https://developers.cloudflare.com/workers/best-practices/workers-best-practices/)
75-give the same rule.
40+celld runs many requests in one isolate and retires isolates at any time, so
41+a Worker must keep its state in a binding, not in module scope.
7642
7743 ## Differences from Cloudflare
7844
79-- celld does not manage a custom domain or terminate TLS. Terminate TLS in the
80- ingress proxy.
81-- celld does not supply a Workers AI binding. Call an AI provider from the
82- application. The process rejects `CELLD_AI_BINDING` and `CELLD_AI_URL`, and a
83- deployment rejects an `ai` declaration.
45+- celld does not manage a custom domain or terminate TLS.
46+- `ctx.passThroughOnException()` has no effect, because celld has no CDN.
47+- celld does not supply a Workers AI binding. The process rejects
48+ `CELLD_AI_BINDING` and `CELLD_AI_URL`, and a deployment rejects an `ai`
49+ declaration.
8450
8551 The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the
8652 runtime APIs and the unsupported services.
8753
8854 ## Python Workers
8955
90-A Worker whose `main` is a `.py` file runs on celld with the
56+A Worker whose `main` is a `.py` file uses the
9157 [Cloudflare Python Workers](https://developers.cloudflare.com/workers/languages/python/)
92-API: a `Default` class that extends `WorkerEntrypoint`, the `Response`
93-and `fetch` of the `workers` package, and bindings on `self.env`. The same
94-project runs on Cloudflare without a change.
58+API. The same project runs on Cloudflare without a change. celld supports a
59+part of that platform, which this section lists.
9560
9661 The [Python example](../../examples/python) uses the SDK and a vendored
9762 package to handle a request.
9863
9964 <!-- celld-example: python -->
10065
101-celld supports a bounded part of the Python Workers platform. This page
102-lists what that part is.
103-
10466 ### Build a project
10567
106-Run `uv run pywrangler sync` to vendor the project's packages with
107-Cloudflare's `pywrangler`. Then run `celld dev .` to start the project.
68+Run `uv run pywrangler sync` to vendor the packages into `python_modules/`,
69+then run `celld dev .`. The build rejects an incomplete Workers SDK
70+(`workers-runtime-sdk`).
10871
109-`pywrangler sync` writes the packages to `python_modules/`, including the
110-Workers SDK (`workers-runtime-sdk`). The build rejects an incomplete Workers
111-SDK. `celld deploy` embeds the files below the directory of `main` that
112-Wrangler uploads with its default module rules: `.py`, `.txt`, `.html`,
113-`.sql`, `.bin`, and `.wasm` files. It also embeds the files of
114-`python_modules/`, and puts all of them in one bundle with the Pyodide
115-runtime. The Worker can open each embedded file under `/session/metadata`,
116-as on Cloudflare. Nothing is downloaded when the Worker runs.
72+`celld deploy` bundles the Pyodide runtime, `python_modules/`, and the files
73+below the directory of `main` that match the default Wrangler module rules:
74+`.py`, `.txt`, `.html`, `.sql`, `.bin`, and `.wasm`. The Worker can open each
75+file under `/session/metadata`, as on Cloudflare. Nothing downloads at run
76+time.
11777
118-The first build downloads the Pyodide runtime files from the Pyodide CDN
119-and checks the size and the SHA-256 of each one. Later builds reuse them
120-from `$XDG_CACHE_HOME/celld/pyodide-0.28.3`, or from
121-`~/.cache/celld/pyodide-0.28.3` when `XDG_CACHE_HOME` is not set. Set
122-`CELLD_PYTHON_RUNTIME_DIR` to use another directory; a directory that
123-already holds the files lets a build run offline. A download fails when the
124-CDN sends no data for 60 seconds, so a stalled network does not stop the
125-build without an error. The build needs `esbuild` on `PATH`, as a JavaScript build
126-does, or `CELLD_ESBUILD` set to its path.
78+The first build downloads the Pyodide runtime from the Pyodide CDN and checks
79+the size and SHA-256 of each file. Later builds reuse
80+`$XDG_CACHE_HOME/celld/pyodide-0.28.3`, or `~/.cache/celld/pyodide-0.28.3`.
81+Set `CELLD_PYTHON_RUNTIME_DIR` to use another directory; a populated directory
82+lets a build run offline. A download fails after 60 seconds without data. The
83+build needs `esbuild` on `PATH`, or `CELLD_ESBUILD` set to its path.
12784
128-A Python deployment requires the `python-workers-v1` feature.
129-`celld deploy` does not examine the nodes of the fleet, so the
130-deployment succeeds even when a node does not have the feature. A running node that
131-predates the feature logs an error and continues to serve its current
132-deployment, so the fleet then serves two versions. A node that predates
133-the feature and starts while a Python deployment is current exits with
134-an error. Therefore, upgrade every node before the first Python
135-deployment, and do not replace this celld version with an earlier one
136-while a Python deployment is current.
85+A Python deployment requires the `python-workers-v1` feature, and
86+`celld deploy` does not check the nodes for it. A running node without the
87+feature logs an error and keeps its current deployment, so the fleet serves
88+two versions. A node without the feature that starts while a Python
89+deployment is current exits with an error. Upgrade every node before the first
90+Python deployment, and do not downgrade while one is current.
13791
13892 ### Runtime version
13993
140-celld runs Pyodide 0.28.3 with CPython 3.13.2 and the `pyodide_2025_0`
141-wheel ABI. This is the runtime line that Cloudflare selects with
142-`python_workers_20250116` (Cloudflare runs Pyodide 0.28.2 with its own
143-patches). The configuration must select that line and the vendored SDK:
94+celld runs Pyodide 0.28.3 with CPython 3.13.2 and the `pyodide_2025_0` wheel
95+ABI. Cloudflare selects this line with `python_workers_20250116` (it runs
96+Pyodide 0.28.2 with its own patches). The configuration must satisfy:
14497
14598 - `compatibility_flags` includes `python_workers`.
14699 - `compatibility_date` has the form `YYYY-MM-DD`.
147-- `compatibility_date` is 2026-04-21 or later, which turns on
148- `enable_python_external_sdk`, `python_no_global_handlers`, and the
149- `python_modules` search path. With an earlier date, a flag must turn on
150- each behavior that the date does not turn on:
100+- `compatibility_date` is 2026-04-21 or later. With an earlier date, a flag
101+ must turn on each behavior that the date does not:
151102 `python_workers_force_new_vendor_path` before 2025-08-11,
152103 `python_no_global_handlers` before 2025-08-14, `python_workers_20250116`
153104 before 2025-09-29, and `enable_python_external_sdk` before 2026-04-21.
@@ -180,8 +131,8 @@
180131 `sqlite3`, `lzma`, and the OpenSSL-backed `hashlib` algorithms.
181132 - `pyodide.ffi.run_sync`, and `workers.import_from_javascript` for
182133 modules other than `cloudflare:workers` and `cloudflare:sockets`. celld
183- hides WebAssembly stack switching (JSPI) from the runtime, because under
184- JSPI each async entry leaks C stack until the interpreter stops.
134+ hides WebAssembly stack switching (JSPI), because under JSPI each async
135+ entry leaks C stack until the interpreter stops.
185136 - `process.exit()` throws an error in a Python Worker.
186137 - Memory snapshots and the import patches of the `_cloudflare` package.
187138 Package patches that need them, such as synchronous FastAPI handlers,
@@ -189,12 +140,10 @@
189140
190141 ### Failure behavior
191142
192-The interpreter starts on the first request that an isolate handles, and
193-concurrent first requests share that start. If the main module raises an
194-error, every request to that isolate fails with the same traceback.
143+The interpreter starts on the first request to an isolate, and concurrent
144+first requests share that start. If the main module raises an error, every
145+request to that isolate fails with the same traceback.
195146
196-A fatal interpreter error, such as a C stack overflow from deep
197-recursion, fails the request in flight and the other requests that the
198-isolate is running. celld then replaces the isolate, as Cloudflare does.
199-The next request goes to another isolate, so it can wait for a new
200-interpreter to start.
147+A fatal interpreter error, such as a C stack overflow, fails every request
148+that the isolate is running. celld then replaces the isolate, as Cloudflare
149+does, so the next request can wait for a new interpreter.
deleteddocs/services/workflows-flow.svg+0−125
@@ -1,125 +1,0 @@
1-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 420" role="img" aria-labelledby="wfFlowTitle wfFlowDesc">
2- <title id="wfFlowTitle">A replay re-enters run() from the top, and the ledger answers for every finished step</title>
3- <desc id="wfFlowDesc">A workflow instance starts when create() makes the first run, and it starts again every time the cell alarm fires on the node that owns the cell at that moment. Each run re-executes run(event, step) from the first line. The instance cell holds a ledger under the __wf prefix, with one record per step occurrence. The first two steps, step.do("fetch") and step.do("charge"), read their stored results out of the ledger records step.1.fetch and step.1.charge, so their callbacks do not run again. A key counts the occurrences of one step name, so each of these names is at its first occurrence. The third step, step.sleep("wait"), reads the record step.1.wait, finds the stored wake time, and blocks because the deadline is not due. The run then arms the cell alarm at the earliest blocked deadline and returns, so the cell hibernates and a fleet wake entry holds the time instead of an isolate. No isolate waits for the deadline, and the node that owns the cell when the alarm fires runs the next replay. The loop closes from the hibernated cell back to the alarm on every resume.</desc>
4- <style>
5- svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
6- text { font-size: 12.5px; fill: currentColor; }
7- tspan { fill: currentColor; }
8- .sm { font-size: 11.5px; }
9- .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; }
10- .d-ink { color: #121212; }
11- .d-soft { color: #3d3b37; }
12- .d-faint { color: #6e6a62; }
13- .d-acc { color: #10803f; }
14- .d-panel { color: #ffffff; }
15- .d-sunk { color: #f0eee8; }
16- .d-tint { color: #d6efdf; }
17- @media (prefers-color-scheme: dark) {
18- .d-ink { color: #efede7; }
19- .d-soft { color: #c9c6be; }
20- .d-faint { color: #928e85; }
21- .d-acc { color: #3fc472; }
22- .d-panel { color: #1a1a19; }
23- .d-sunk { color: #232321; }
24- .d-tint { color: #10301d; }
25- }
26- </style>
27- <defs>
28- <marker id="wf-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6"
29- markerHeight="6" orient="auto-start-reverse">
30- <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" />
31- </marker>
32- </defs>
33-
34- <!-- The two entries into a run: the first create, and every later alarm. -->
35- <rect class="d-tint" fill="currentColor" x="36" y="6" width="216" height="44" rx="6" />
36- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="36" y="6" width="216" height="44" rx="6" />
37- <text class="d-ink" fill="currentColor" x="144" y="26" text-anchor="middle">the alarm fires</text>
38- <text class="d-soft sm" fill="currentColor" x="144" y="42" text-anchor="middle">on the node that owns the cell</text>
39-
40- <rect class="d-panel" fill="currentColor" x="288" y="6" width="152" height="44" rx="6" />
41- <rect class="d-soft" fill="none" stroke="currentColor" x="288" y="6" width="152" height="44" rx="6" />
42- <text class="d-ink mono" fill="currentColor" x="364" y="26" text-anchor="middle">create()</text>
43- <text class="d-soft sm" fill="currentColor" x="364" y="42" text-anchor="middle">starts the first run</text>
44-
45- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
46- <path d="M364 50 V56 H144" />
47- <path d="M144 50 V62" marker-end="url(#wf-arrow)" />
48- </g>
49-
50- <!-- The replay: one invocation that always begins at the first line. -->
51- <rect class="d-sunk" fill="currentColor" x="36" y="62" width="216" height="206" rx="8" />
52- <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="62" width="216" height="206" rx="8" />
53- <text class="d-ink mono" fill="currentColor" x="144" y="84" text-anchor="middle">run(event, step)</text>
54- <text class="d-faint sm" fill="currentColor" x="144" y="101" text-anchor="middle">re-executed from the top</text>
55-
56- <rect class="d-panel" fill="currentColor" x="46" y="112" width="196" height="44" rx="6" />
57- <rect class="d-soft" fill="none" stroke="currentColor" x="46" y="112" width="196" height="44" rx="6" />
58- <text class="d-ink mono" fill="currentColor" x="58" y="131">step.do("fetch")</text>
59- <text class="d-acc sm" fill="currentColor" x="58" y="148">ledger hit, callback skipped</text>
60-
61- <rect class="d-panel" fill="currentColor" x="46" y="164" width="196" height="44" rx="6" />
62- <rect class="d-soft" fill="none" stroke="currentColor" x="46" y="164" width="196" height="44" rx="6" />
63- <text class="d-ink mono" fill="currentColor" x="58" y="183">step.do("charge")</text>
64- <text class="d-acc sm" fill="currentColor" x="58" y="200">ledger hit, callback skipped</text>
65-
66- <rect class="d-tint" fill="currentColor" x="46" y="216" width="196" height="44" rx="6" />
67- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="46" y="216" width="196" height="44" rx="6" />
68- <text class="d-ink mono" fill="currentColor" x="58" y="235">step.sleep("wait")</text>
69- <text class="d-soft sm" fill="currentColor" x="58" y="252">not due, so it blocks</text>
70-
71- <!-- The ledger in the instance cell: one record per step occurrence. -->
72- <rect class="d-sunk" fill="currentColor" x="288" y="62" width="152" height="206" rx="8" />
73- <rect class="d-soft" fill="none" stroke="currentColor" x="288" y="62" width="152" height="206" rx="8" />
74- <text class="d-ink" fill="currentColor" x="364" y="84" text-anchor="middle">instance cell</text>
75- <text class="d-faint mono" fill="currentColor" x="364" y="101" text-anchor="middle">__wf ledger</text>
76-
77- <rect class="d-panel" fill="currentColor" x="296" y="112" width="136" height="44" rx="6" />
78- <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="112" width="136" height="44" rx="6" />
79- <text class="d-soft mono" fill="currentColor" x="306" y="131">step.1.fetch</text>
80- <text class="d-ink mono" fill="currentColor" x="306" y="148">{bytes: 812}</text>
81-
82- <rect class="d-panel" fill="currentColor" x="296" y="164" width="136" height="44" rx="6" />
83- <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="164" width="136" height="44" rx="6" />
84- <text class="d-soft mono" fill="currentColor" x="306" y="183">step.1.charge</text>
85- <text class="d-ink mono" fill="currentColor" x="306" y="200">{ok: true}</text>
86-
87- <rect class="d-tint" fill="currentColor" x="296" y="216" width="136" height="44" rx="6" />
88- <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="296" y="216" width="136" height="44" rx="6" />
89- <text class="d-soft mono" fill="currentColor" x="306" y="235">step.1.wait</text>
90- <text class="d-ink mono" fill="currentColor" x="306" y="252">wake at 09:00</text>
91-
92- <!-- The ledger answers; the callback never starts. -->
93- <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5">
94- <path d="M288 134 H254" marker-end="url(#wf-arrow)" />
95- <path d="M288 186 H254" marker-end="url(#wf-arrow)" />
96- <path d="M288 238 H254" marker-end="url(#wf-arrow)" />
97- <path d="M144 268 V292" marker-end="url(#wf-arrow)" />
98- <path d="M144 344 V356" marker-end="url(#wf-arrow)" />
99- </g>
100-
101- <!-- The blocked step ends the invocation instead of waiting inside it. -->
102- <rect class="d-panel" fill="currentColor" x="36" y="292" width="216" height="52" rx="6" />
103- <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="292" width="216" height="52" rx="6" />
104- <text class="d-ink" fill="currentColor" x="144" y="313" text-anchor="middle">arm the cell alarm at the</text>
105- <text class="d-ink" fill="currentColor" x="144" y="331" text-anchor="middle">earliest blocked deadline</text>
106-
107- <rect class="d-sunk" fill="currentColor" x="36" y="356" width="216" height="52" rx="6" />
108- <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="356" width="216" height="52" rx="6" />
109- <text class="d-ink" fill="currentColor" x="144" y="377" text-anchor="middle">the cell hibernates</text>
110- <text class="d-soft sm" fill="currentColor" x="144" y="395" text-anchor="middle">a fleet wake entry holds the time</text>
111-
112- <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"
113- x="288" y="292" width="152" height="116" rx="8" />
114- <text class="d-faint sm" fill="currentColor" x="364" y="318" text-anchor="middle">no isolate waits</text>
115- <text class="d-faint sm" fill="currentColor" x="364" y="336" text-anchor="middle">for the deadline.</text>
116- <text class="d-faint sm" fill="currentColor" x="364" y="360" text-anchor="middle">the owner at that</text>
117- <text class="d-faint sm" fill="currentColor" x="364" y="378" text-anchor="middle">moment runs the</text>
118- <text class="d-faint sm" fill="currentColor" x="364" y="396" text-anchor="middle">next replay.</text>
119-
120- <!-- The back edge: the loop that makes this a replay and not a sequence. -->
121- <path class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"
122- stroke-dasharray="6 4" d="M36 382 H10 V28 H36" marker-end="url(#wf-arrow)" />
123- <text class="d-faint sm" fill="currentColor" x="26" y="200" text-anchor="middle"
124- transform="rotate(-90 26 200)">every resume</text>
125-</svg>
modifieddocs/services/workflows.md+40−83View file
@@ -1,12 +1,9 @@
11 # Workflows
22
33 A Workflow is a durable function that runs as a named sequence of steps,
4-sleeps, and events. An application uses a Workflow for work that must survive a
5-failure or a long delay, such as an order pipeline, a staged import, or an
6-export that retries. celld runs each instance as a cell, so the state of an
7-instance lives in that cell's storage and moves with the cell. Read the
4+sleeps, and events. celld runs each instance as a cell. Read the
85 [Cloudflare Workflows documentation](https://developers.cloudflare.com/workflows/build/workers-api/)
9-for the standard API behavior.
6+for the API.
107
118 ## Example
129
@@ -15,94 +12,54 @@
1512
1613 <!-- celld-example: workflow -->
1714
18-## Steps and replay
15+## API
1916
20-A Workflow class extends `WorkflowEntrypoint` and implements
21-`run(event, step)`. `event.payload` holds the parameters that `create()`
22-supplied, and the `step` object supplies the durable operations. A value that
23-`run()` returns becomes the `output` field of `status()`. Read the
24-[Workers API documentation](https://developers.cloudflare.com/workflows/build/workers-api/)
25-for the complete signature.
17+- A class extends `WorkflowEntrypoint` and implements `run(event, step)`.
18+ `event.payload` holds the parameters, and the return value becomes the
19+ `output` field of `status()`.
20+- `step.do(name, callback)` runs a durable step, and it retries the callback on
21+ failure.
22+- `step.sleep(name, duration)` and `step.sleepUntil(name, timestamp)` stop the
23+ instance until a deadline.
24+- `step.waitForEvent(name, options)` stops the instance until a matching event.
25+- `env.MY_WORKFLOW.create()`, `createBatch()`, and `get(id)` return an
26+ instance. `deleteBatch()` deletes several instances.
27+- An instance has `status()`, `sendEvent()`, `pause()`, `resume()`,
28+ `restart()`, `terminate()`, and `delete()`.
2629
27-celld does not stop `run()` in place and continue it later. Each time an
28-instance makes progress, celld calls `run()` again from the first line. A step
29-that already finished returns its stored result, and its callback does not run
30-a second time. celld writes each result into the storage of the instance cell,
31-under a key that joins the step name and the occurrence count of that name, so
32-a step inside a loop keeps one record for each iteration.
30+## Replay
3331
34-![A resume re-enters run from the top, the ledger in the instance cell answers for each finished step, and the first blocked step arms the cell alarm so the cell hibernates until the next replay](workflows-flow.svg)
32+Each time an instance makes progress, celld calls `run()` again from the first
33+line. A finished step returns its stored result and does not run its callback
34+again. All code outside a step callback therefore runs again on every replay.
35+Put each subrequest, each side effect, and each value that must stay stable
36+inside a `step.do()` callback, as the
37+[rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/)
38+require. A step whose result did not commit before a node failure runs again,
39+so a step callback must tolerate a second attempt.
3540
36-This design puts one rule on the application code: everything outside a step
37-callback runs again on every replay. Put each subrequest, each side effect, and
38-each value that must stay stable inside a `step.do()` callback. Cloudflare
39-gives the same rule in the
40-[rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/).
41+`run()` can await work that is not a step, but a replay cannot resume that
42+await. celld fails the instance when such work keeps `run()` pending for 60
43+seconds while no step runs or waits.
4144
42-celld ends an invocation when no step callback runs and no step can make
43-progress. `run()` can also await work that is not a step. Upstream permits that
44-await and does not make it durable, and celld accepts it for a short time. A
45-replay cannot resume such an await, therefore celld fails the instance when it
46-keeps `run()` pending for 60 seconds while no step runs and none waits.
45+## Sleeps, events, and retries
4746
48-## Sleeping and waiting for an event
47+`step.waitForEvent()` times out after 24 hours by default. An event that
48+arrives before the instance reaches its wait step is buffered. A sleep, a wait,
49+and a pending retry each store their deadline, so a crash or a slow replay
50+cannot move the deadline. `status()` reports `waiting` for all three.
4951
50-`step.sleep(name, duration)` and `step.sleepUntil(name, timestamp)` stop the
51-instance until a deadline. `step.waitForEvent(name, options)` stops it until
52-`sendEvent()` delivers an event of the matching type, or until a timeout that
53-is 24 hours by default. Read
54-[sleeping and retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/)
55-and
56-[events and parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/)
57-for the durations and the event rules.
52+A waiting instance holds no isolate. Its cell hibernates when the next deadline
53+is further away than the near-alarm residency window. That window is one hour,
54+and `CELLD_ALARM_RESIDENT_MS` changes it.
5855
59-celld computes the deadline once and commits it with the step record. A later
60-replay reads the stored deadline instead of adding the duration to the current
61-time, therefore a crash or a slow resume cannot move the wake further away.
56+`step.do()` uses the Cloudflare retry defaults when the call supplies no
57+`retries` object: 5 retries, a delay of 10 seconds, exponential backoff, and a
58+timeout of 10 minutes for one attempt.
6259
63-A waiting instance holds no isolate. celld arms the alarm of the instance cell
64-at the earliest blocked deadline and returns, so the cell hibernates like any
65-other [cell](durable-objects.md) when the alarm is further away than the
66-near-alarm residency window. That window is one hour, and
67-`CELLD_ALARM_RESIDENT_MS` changes it. The armed alarm has a durable wake entry
68-in the fleet, and the node that owns the cell at the deadline runs the next
69-replay.
60+celld sets no limit on the number of concurrent instances. Fleet memory and the
61+resident-cell cap bound it.
7062
71-An event that arrives before the instance reaches its wait step is buffered,
72-and a matching step then consumes the buffered events in arrival order. celld
73-deletes the event and writes the step record in one SQLite commit, so an
74-acknowledged event cannot disappear. celld compares the stored deadline before
75-the buffer, therefore a late replay cannot accept an event that arrived after
76-the step timed out.
77-
78-## Retries, failure, and a node that stops
79-
80-`step.do()` retries a failed callback. celld uses the upstream defaults when
81-the call supplies no `retries` object: a limit of 5 retries, a delay of 10
82-seconds, exponential backoff, and a timeout of 10 minutes for one attempt. A
83-`NonRetryableError` stops the retries at once. When the retries run out, the
84-step promise rejects and `run()` can catch it. An error that escapes `run()`
85-moves the instance to the `errored` status.
86-
87-celld commits the time of the next attempt when an attempt fails, so a replay
88-waits out the rest of the backoff instead of starting it again. A pending retry
89-suspends the instance in the same way a sleep does, and `status()` reports
90-`waiting` for both.
91-
92-A node that stops does not lose an instance. The instance is a cell, so it has
93-the ownership, the fencing, and the replication that every cell has. celld
94-leaves the alarm that started an invocation armed for the whole invocation, and
95-it consumes that alarm only after the invocation returns cleanly. A node that
96-dies in the middle therefore leaves an armed alarm, and the next owner replays
97-`run()` over the step results that reached a replicated commit. A step whose
98-result did not commit runs again, which is why a step callback must tolerate a
99-second attempt.
100-
101-celld enforces no limit on the number of instances that run at once. The memory
102-of the fleet and the resident-cell cap bound that number instead. A waiting
103-instance costs no memory, so a fleet holds far more waiting instances than
104-running ones.
105-
10663 ## Differences from Cloudflare
10764
10865 - celld retains a successful or failed instance for 30 days by default. Each
modifieddocs/telemetry.md+60−111View file
@@ -1,21 +1,15 @@
11 # Telemetry
22
3-celld can record traces and logs for the requests it serves. The
4-feature is off by default, and the off state costs nothing. Set
5-`CELLD_OTEL=1` to write telemetry to the fleet bucket.
6-Set `CELLD_OTEL=http://collector:4318` to send telemetry to an OTLP collector.
3+celld can record traces and logs for the requests it serves. Telemetry is off
4+by default and costs nothing when off. `CELLD_OTEL=1` writes Parquet files
5+under the `telemetry/` prefix of the fleet bucket, which DuckDB can query
6+directly. `CELLD_OTEL=http://collector:4318` sends the same data to an
7+OpenTelemetry collector.
78
8-The default sink is the fleet bucket. celld writes Parquet files under
9-the `telemetry/` prefix, so a fleet with a bucket has observability
10-with no other service. DuckDB can query these files directly. An
11-alternative sink sends the same data to an OpenTelemetry collector.
9+The schema is version `v0-unstable`, so column names can change before a
10+stable release. Each file carries the version in the object metadata name
11+`celld-schema`, or `celld_schema` on an `az://` bucket.
1212
13-The schema is version `v0-unstable`. The column names can change
14-before a stable release, and each file carries the schema version in
15-its object metadata under the name `celld-schema`. Azure Blob Storage
16-does not accept a hyphen in a metadata name, so on an `az://` bucket
17-the name is `celld_schema`.
18-
1913 ## Configuration
2014
2115 | variable | default | effect |
@@ -30,35 +24,26 @@
3024 | `OTEL_EXPORTER_OTLP_TIMEOUT` | `10000` | The collector request timeout in milliseconds. |
3125 | `OTEL_SERVICE_NAME` | `celld` | The service name in the exported resource. |
3226
33-The `bucket` sink requires the node to have a fleet bucket
34-(`CELLD_BUCKET`). The `otlp` sink works on a node without one.
27+The bucket sink requires `CELLD_BUCKET`. The OTLP sink does not.
3528
36-Use a full HTTP(S) collector base URL without a query or a fragment.
37-celld adds `/v1/traces` and `/v1/logs` to its path for the two signals.
38-`CELLD_OTEL` supplies the collector address, so celld does not read
39-`OTEL_EXPORTER_OTLP_ENDPOINT`.
29+A collector URL must have no query or fragment. celld appends `/v1/traces` and
30+`/v1/logs` to its path and ignores `OTEL_EXPORTER_OTLP_ENDPOINT`.
4031
41-`CELLD_OTEL_SINK` is removed. Remove this setting before starting the node.
42-For a collector, copy its full base URL into `CELLD_OTEL`. For the fleet bucket, keep `CELLD_OTEL=1`.
32+`CELLD_OTEL_SINK` is removed, and a node with it set does not start. Put the
33+collector base URL in `CELLD_OTEL`, or keep `CELLD_OTEL=1` for the bucket.
4334
44-
4535 ## What celld records
4636
47-celld records a span for each request a stateless Worker serves, for
48-each event a cell serves (a fetch, an alarm, an RPC, a WebSocket
49-message), for each outbound `fetch()`, and for each cell start. A
50-span carries the request id, the cell, the isolate, the
51-queue wait, the outbound URL and status, and the durability facts the
52-runtime already knows.
37+celld records a span for each stateless Worker request, each cell event (a
38+fetch, an alarm, an RPC, a WebSocket message), each outbound `fetch()`, and
39+each cell start. A span carries the request id, the cell, the isolate, the
40+queue wait, the outbound URL and status, and the known durability facts.
5341
54-celld also records each `console.log` line as a log record. The log
55-record carries the trace id and the span id of the handler that wrote
56-it, so a query can join the logs to the traces. The correlation
57-survives `await`.
42+Each `console.log` line becomes a log record with the trace id and span id of
43+its handler, across `await`. The record carries the console method's severity
44+in `severity_number` and `severity_text` (OTLP fields and Parquet columns). The
45+body holds only the message.
5846
59-The log record also carries the OpenTelemetry severity of the console
60-method:
61-
6247 | method | severity number | severity text |
6348 | --- | --- | --- |
6449 | `console.debug` | `5` | `DEBUG` |
@@ -66,38 +51,23 @@
6651 | `console.warn` | `13` | `WARN` |
6752 | `console.error` | `17` | `ERROR` |
6853
69-The OTLP export sets these values in the `severity_number` and
70-`severity_text` fields. The Parquet export writes them to columns with
71-the same names. The body contains only the message, so a query must use
72-the severity to find the level.
54+Log files from earlier celld versions have no severity columns. Read a mix of
55+versions with `union_by_name = true`.
7356
74-A log file from an earlier celld version has no severity columns. A
75-DuckDB query over files from both versions must therefore read them
76-with `union_by_name = true`.
57+celld reads the W3C `traceparent` header on incoming requests and sends it on
58+outbound `fetch()`. A malformed header starts a new trace. A Worker call to a
59+Durable Object stays in one trace.
7760
78-celld reads the W3C `traceparent` header on incoming requests, so its
79-spans join the trace of the system in front of it. celld sends a
80-`traceparent` header on outbound `fetch()`, so downstream systems can
81-join too. celld ignores a malformed header and starts a new trace. A
82-Worker call to a Durable Object stays in one trace.
61+The sampler decides at the start of a request, and an unsampled request
62+records nothing. A ratio of `0` records no traces and `1` records all. An
63+intermediate ratio makes the same trace-id decision on each node. celld keeps
64+a valid incoming context that the sampler rejects: an outbound `fetch()` or
65+Durable Object call keeps the trace id, uses a new span id, and keeps the
66+sampled flag clear.
8367
84-The sampler decides at the start of a request. An unsampled request
85-records nothing and costs almost nothing. Under load, telemetry sheds
86-before requests do, and celld counts what it sheds.
68+Under load, telemetry sheds before requests do, and celld counts what it
69+sheds. celld records no metrics yet.
8770
88-A sampling ratio of `0` records no traces, and a ratio of `1` records
89-every trace. An intermediate ratio makes the same trace-id decision on
90-each node.
91-
92-celld keeps a valid incoming context when the sampler rejects it. An
93-outbound `fetch()` or Durable Object call keeps the trace id, uses a new
94-span id, and keeps the sampled flag clear.
95-
96-celld records no metrics yet. The spans carry the durations and the
97-queue waits, so many questions a metric answers have an answer in the
98-traces, and a metrics signal can come later without a change to the
99-trace schema.
100-
10171 ## Query the bucket with DuckDB
10272
10373 ```sql
@@ -123,59 +93,42 @@
12393 JOIN traces t ON l.trace_id = t.trace_id AND l.span_id = t.span_id;
12494 ```
12595
126-An S3-compatible endpoint such as minio needs `URL_STYLE 'path'` in
127-the secret, and a plain-HTTP endpoint also needs `USE_SSL false`. AWS
128-itself does not need either.
96+A non-AWS S3-compatible endpoint needs `URL_STYLE 'path'`. A plain-HTTP
97+endpoint also needs `USE_SSL false`.
12998
130-The files are partitioned by node and by hour:
131-`telemetry/traces/<node>/<yyyy>/<mm>/<dd>/<hh>/<id>.parquet`. A query
132-that reads one day therefore touches only that day's files.
99+Files are partitioned by node and hour:
100+`telemetry/traces/<node>/<yyyy>/<mm>/<dd>/<hh>/<id>.parquet`.
133101
134-## File size and compaction
102+## Flushing and delivery
135103
136-celld writes one Parquet file for each flush, on a time limit or a
137-size target, whichever it reaches first. The default interval is 5 minutes
138-(`CELLD_OTEL_FLUSH_MS=300000`). The default size target is 5 MiB of estimated
139-buffered events (`CELLD_OTEL_FLUSH_BYTES=5242880`). The event that reaches
140-the target can take the batch past it.
104+celld writes one Parquet file per flush, at 5 minutes
105+(`CELLD_OTEL_FLUSH_MS=300000`) or 5 MiB of estimated buffered events
106+(`CELLD_OTEL_FLUSH_BYTES=5242880`), whichever comes first. The event that
107+reaches the target can take the batch past it.
141108
142-Keep the defaults if you run no compaction job. They make files large
143-enough for a fast query with no other moving part. The default batching
144-delay can reach 5 minutes, so the default suits an investigation after the fact.
109+Keep the defaults if you run no compaction job. They produce large files, but
110+data can arrive up to 5 minutes late. `CELLD_OTEL_FLUSH_MS=5000` gives a
111+five-second interval, plus upload or collector delay. A short interval makes
112+many small files and slows queries within hours, so start the compaction job
113+first. For a near-live view, use the OTLP sink with the same short interval.
145114
146-Set `CELLD_OTEL_FLUSH_MS=5000` for a five-second batching interval.
147-An upload, a retry, or collector processing can add a delivery delay.
148-A short flush makes many small files, and DuckDB
149-opens every file a query reads, so you must also run the compaction
150-job below. Turn on the compaction job first, then shorten the flush,
151-or queries grow slow within hours.
115+The OTLP sink makes at most five attempts per batch on a transient failure
116+(HTTP 408, 429, 502, 503, or 504). It uses exponential backoff with jitter and
117+honors `Retry-After`, with each delay capped at 30 seconds. A permanent
118+refusal drops the batch.
152119
153-The `otlp` sink is the other route to a near-live view. It sends each
154-batch to a collector, so set the same short `CELLD_OTEL_FLUSH_MS`.
120+The exporter holds one retrying batch, and the input channel holds 8192 new
121+events. When the channel is full, celld drops and counts new telemetry, so
122+request handling continues.
155123
156-The `otlp` sink makes no more than five attempts for a batch when a
157-transient failure occurs. It uses exponential backoff with jitter, and it
158-uses an applicable `Retry-After` value from the collector. The exporter caps
159-each delay at 30 seconds, so a collector cannot suspend a batch indefinitely.
160-HTTP 408, 429, 502, 503, and 504 responses are transient failures. A
161-permanent refusal drops the batch immediately.
124+The retention sweep runs at startup and six hours after each completed sweep.
162125
163-The exporter owns one retrying batch, and the input channel holds 8192
164-new events. An outage cannot make either bound grow. celld drops and counts
165-new telemetry when the channel is full, so request handling continues.
166-
167-The retention sweep runs at startup and six hours after each completed sweep. It deletes expired
168-objects and preserves objects within the configured retention window.
169-
170126 ## Compaction
171127
172-Run a compaction job on a maintenance node, not on a celld node. celld
173-does not compact its own files, because the serving path must not do
174-storage maintenance and each node writes only the files it produced.
128+celld does not compact its own files. Run a compaction job on a maintenance
129+node once an hour, for the hour that just ended. Do not compact the current
130+hour, because a node still writes to it.
175131
176-The job rewrites one past hour of small files into one large file.
177-DuckDB does the work:
178-
179132 ```sql
180133 COPY (
181134 SELECT * FROM
@@ -185,8 +138,4 @@
185138 (FORMAT parquet, COMPRESSION zstd);
186139 ```
187140
188-Run the job once an hour, for the hour that just ended. Do not compact
189-the current hour, because a node still writes to it. Delete the source
190-files after DuckDB writes the compacted file. The compacted file is
191-also smaller, because zstd compresses one sorted batch better than
192-many separate files.
141+Delete the source files after DuckDB writes the compacted file.
modifieddocs/testing.md+105−147View file
@@ -4,184 +4,142 @@
44
55 - An acknowledged write is durable.
66 - A cell has one writer at a time.
7-- Code written for Cloudflare Workers and Durable Objects operates the
8- same on celld.
7+- Code written for Cloudflare Workers and Durable Objects operates the same on
8+ celld.
99
10-We try to break each promise at the layer where a failure shows most
11-clearly. We test the API contract with differential execution against the
12-Cloudflare runtime. We check the coordination protocol against an
13-exhaustively model-checked specification, and we test it with
14-deterministic simulation. We test the full system with fault injection
15-on live fleets.
10+We test the API contract by differential execution against workerd, the
11+coordination protocol by model checking and deterministic simulation, and the
12+full system by fault injection on live fleets.
1613
1714 ## Conformance: two runtimes, one output
1815
19-We run the same Workers and Durable Objects program on both workerd,
20-Cloudflare's production runtime, and celld. The two outputs must match,
21-so each test checks celld against the Cloudflare runtime.
22-The reference output comes from workerd, so the expected behavior does
23-not depend on the celld implementation.
16+We run the same Workers and Durable Objects programs on workerd, Cloudflare's
17+production runtime, and on celld, and the outputs must match. workerd supplies
18+the reference output, so the expected behavior does not depend on celld.
2419
25-We expand the corpus with fixtures for each new API, and each fixture must
26-give the same output on both engines. We also port test suites from workerd:
27-the Durable Objects contract, the web-platform globals, and the upstream
28-Web Platform Tests. Before a release, we replay storage, SQL, alarm,
29-stream, WebSocket, and lifecycle scenarios through the full `celld` binary
30-in each deployment mode.
20+Each new API adds fixtures to the corpus. We also port the workerd Durable
21+Objects contract tests, its web-platform globals tests, and the upstream Web
22+Platform Tests. Before a release, we replay storage, SQL, alarm, stream,
23+WebSocket, and lifecycle scenarios through the full `celld` binary in each
24+deployment mode.
3125
3226 ## Specification: exhaustive at small size
3327
34-The coordination protocol is also specified in TLA+. Heyang Zhou wrote
35-the specifications against celld v0.1.0, and his model checking found
36-four bugs and a split-brain that lost an acknowledged write. All are
37-fixed. None had surfaced in our own review or testing.
28+The coordination protocol is specified in TLA+. Heyang Zhou wrote the
29+specifications against celld v0.1.0. His model checking found four bugs and a
30+split-brain that lost an acknowledged write. All are fixed. None had surfaced
31+in our own review or testing.
3832
39-Where simulation samples schedules, the checker enumerates them: at a
40-small configuration it visits every reachable state. The model grants
41-the implementation a linearizable object store and perfect shared
42-clocks, so a violation it finds needs no clock skew and no storage
43-anomaly to occur. The invariants are the first two promises at the top
44-of this page: one writer for each epoch, and no acknowledged write
45-lost. The checker also verifies that the epoch in the key prevents a stale
46-owner's late writes from causing the loss of an acknowledged write.
33+At a small configuration, the checker visits every reachable state. The model
34+grants a linearizable object store and perfect shared clocks, so a violation
35+needs no clock skew or storage anomaly. The invariants are one writer for each
36+epoch and no lost acknowledged write. The checker also verifies that the epoch
37+in the key stops a stale owner's late writes from losing an acknowledged write.
4738
48-Every configuration carries a pinned expected verdict, and most of the
49-verdicts are failures: each failing configuration models a bug the
50-protocol once had, or a deliberately broken checker, and the model
51-must produce the counterexample. If a configuration stops producing its
52-expected failure, we investigate and repair the check.
39+Each configuration pins an expected verdict, and most verdicts are failures:
40+each models a past protocol bug or a deliberately broken checker, and must
41+produce its counterexample.
5342
54-Some specifications model a proposed protocol before it is built. When
55-the fence on write acknowledgments was redesigned, the design-stage
56-check produced an eight-state counterexample against the version it
57-replaced: a dormant cell resumes at its old epoch while its release is
58-in flight, acknowledges a write, and the takeover that follows
59-restores without it. The fix shipped; the counterexample stays as a
60-pinned failure.
43+A redesign of the write-acknowledgment fence was checked before it was built.
44+The check found an eight-state counterexample against the old version: a
45+dormant cell resumes at its old epoch while its release is in flight,
46+acknowledges a write, and the following takeover restores without it. The fix
47+shipped, and the counterexample stays as a pinned failure.
6148
62-The checker has also removed code: celld once sealed a cell's durable
63-history at restore, and the verdicts showed the seal defended only the
64-return of an unacknowledged write, which celld does not promise to prevent.
65-The seal could also turn a recoverable ordering error into permanent data
66-loss, so celld no longer uses it.
49+The checker also removed code. celld once sealed a cell's durable history at
50+restore. The verdicts showed that the seal only prevented the return of an
51+unacknowledged write, which celld does not promise, and that it could turn a
52+recoverable ordering error into permanent data loss.
6753
68-We update the specifications manually alongside the protocol changes.
69-They do not run in continuous integration, because an outdated model can
70-give false confidence. A separate record tracks what the model does not
71-yet describe, including guarantees weaker than those in the code.
72-Simulation checks each commit, and model checking adds exhaustive coverage
73-of small configurations.
54+We update the specifications by hand with protocol changes. They do not run in
55+continuous integration. A separate record tracks what the model does not yet
56+describe, including guarantees weaker than the code's.
7457
7558 ## Simulation: the protocol under adversarial schedules
7659
77-The dangerous bugs live in the coordination: a crash during an ownership
78-handoff, a lease renewal that races a takeover, an alarm that fires
79-against a partially restored cell. These windows are nanoseconds wide and
80-open rarely, so a test cannot wait for them.
60+The dangerous bugs are in coordination: a crash during an ownership handoff, a
61+lease renewal that races a takeover, an alarm against a partially restored
62+cell. These windows are too narrow and too rare to wait for.
8163
82-Thus the coordination protocol is a
64+The coordination protocol is therefore a
8365 [pure decision core](https://github.com/denoland/celld/tree/main/crates/logic)
84-with no I/O of its own: the clock, the randomness, and the object store
85-are interfaces, and a simulator drives the core. The simulated store
86-injects latency, compare-and-swap races, and lost responses; the clocks
87-drift apart; a node can crash at each await point. Scripted adversaries
88-play the cells: a handler that never returns, a write stream that stops
89-halfway. V8 stays out of the simulation, because V8 is not deterministic.
66+with no I/O. The clock, the randomness, and the object store are interfaces
67+that a simulator drives. The simulated store injects latency, compare-and-swap
68+races, and lost responses. The clocks drift, and a node can crash at each
69+await point. Scripted adversaries play the cells, such as a handler that never
70+returns or a write stream that stops halfway. V8 is not deterministic, so it
71+stays out of the simulation.
9072
91-A seeded scheduler drives each run, so we can reproduce a failure exactly
92-and keep its seed until we fix the bug. We check safety properties for
93-two writers in one epoch, a lost acknowledged write, and an expired lease
94-that returns. We also check liveness: each armed alarm fires, and ownership
95-settles on one node after a crash. A property must survive tens of thousands
96-of seeds, and the core protocols have run through millions of different
97-schedules.
73+A seeded scheduler drives each run, so a failure reproduces exactly. We check
74+safety (two writers in one epoch, a lost acknowledged write, an expired lease
75+that returns) and liveness (each armed alarm fires, ownership settles on one
76+node after a crash). A property must survive tens of thousands of seeds, and
77+the core protocols have run through millions of schedules. Deliberately broken
78+protocol variants verify that the checkers detect the faults.
9879
99-We also run deliberately broken variants of the protocol to verify that
100-the checkers detect the faults. A checker that accepts a broken protocol
101-cannot protect the corresponding property.
102-
10380 ## Live fleets: what simulation cannot see
10481
105-Simulation cannot see the real S3 tail latency, the real kernel and
106-filesystem behavior, or V8 under memory pressure. The third layer is
107-therefore a permanent fleet lab: standard VMs from standard providers,
108-and a real bucket. The workloads rotate: chat rooms under many WebSocket
109-connections, working sets that shift across tens of thousands of cells
110-(each cell has a unique checksum), deployment cutovers under load, and
111-runs that fill the nodes to the memory limit. The lab qualifies each
112-release and tests greater density and more faults between releases. We
113-archive each run's configuration, verification sweeps, node journals,
114-kernel logs, and phase timings. We preserve failed runs as well as
115-successful ones, because both provide evidence of the system's behavior.
82+Simulation cannot see real S3 tail latency, real kernel and filesystem
83+behavior, or V8 under memory pressure. A permanent fleet lab runs standard VMs
84+from standard providers against a real bucket. Workloads rotate: chat rooms
85+with many WebSocket connections, working sets that shift across tens of
86+thousands of checksummed cells, deployment cutovers under load, and nodes
87+filled to the memory limit. The lab qualifies each release. We archive each
88+run's configuration, verification sweeps, node journals, kernel logs, and
89+phase timings, including failed runs.
11690
117-We inject the faults between verification passes. A pass fetches each
118-cell through different nodes and compares the durable state exactly: the
119-status, the body, and the full message ledger. Each run therefore records
120-the state before and after the fault. A cell can be unavailable for a short
121-time while its ownership moves, but its committed state must
122-stay complete, and a live node must serve that state again.
91+Faults land between verification passes. A pass fetches each cell through
92+different nodes and compares the status, the body, and the full message
93+ledger. A cell can be briefly unavailable while ownership moves, but its
94+committed state must stay complete and a live node must serve it again.
12395
124-The scenarios attack every seam that we know:
96+The scenarios:
12597
126-- Stop a node with `SIGKILL` in the middle of a write stream and delete
127- its local database, so recovery can only come from the bucket. Every
128- acknowledged write comes back, because the output gate held each
129- response until the write was durable.
130-- Freeze an owner node, write to its cells through other nodes, and
131- unfreeze it. The node sees that its lease moved and refuses to serve
132- the old state, and each write from the other nodes lands exactly one
133- time: one epoch has at most one writer.
134-- Cut a node off from the bucket. It fences itself, because a node that
135- cannot replicate must not own cells.
136-- Throttle the bucket, so it answers each request with a 429. The engine
137- slows to the write rate of the store and does not amplify the
138- throttle, because a node that knows its replicated position does not
139- ask a slow store for extra listings.
140-- Stop a full host at the provider level in the middle of a workload.
141- Its cells move to the other nodes, and the returning host joins again
142- with no duplicate residency.
98+- `SIGKILL` a node mid-write-stream and delete its local database, so recovery
99+ comes only from the bucket. Every acknowledged write returns, because the
100+ output gate held each response until the write was durable.
101+- Freeze an owner, write to its cells through other nodes, and unfreeze it.
102+ The node sees that its lease moved and refuses to serve the old state. Each
103+ write lands exactly once.
104+- Cut a node off from the bucket. It fences itself.
105+- Throttle the bucket to 429 on every request. The engine slows to the store's
106+ rate and does not amplify the throttle.
107+- Stop a full host at the provider level mid-workload. Its cells move to other
108+ nodes, and the returning host rejoins with no duplicate residency.
143109
144-Across every run of every scenario, no acknowledged write was lost and
145-no committed state was damaged; the verification sweeps show zero body
110+Across every run of every scenario, the verification sweeps show zero body
146111 faults, zero status faults, and zero lost messages.
147112
148113 ## A few numbers we trust
149114
150-Each number includes its measurement conditions, so you can assess whether
151-it applies to your workload.
115+- **The epoch fence holds under contention.** Five hundred concurrent
116+ claimants made 5,500 attempts on the same cells: one writer for each epoch,
117+ zero violations.
118+- **A warm resident request is local.** A request to a resident cell does zero
119+ bucket operations and returns in p50 ~1.1 ms and p99 ~7 ms (a fixed-host
120+ measurement). Only a cold activation touches object storage.
121+- **A durable write waits for a durability proof.** A single node proves each
122+ write through the bucket, so one storage round trip is the minimum. A fleet
123+ of two or more nodes can instead prove a write when each follower holds it
124+ on disk. A lab fleet measured about 600 ms for a bucket proof and about 25 ms
125+ for a fleet proof. The bucket upload races every fleet proof, so a slow
126+ follower cannot make a write slower than a bucket proof. Concurrent writes
127+ to one cell share one upload.
128+- **A restore is normal work.** Placement treats the restore of an inactive
129+ cell as ordinary work. The measured restore times come from the retired
130+ external replicator, so this page gives no number until a fleet run measures
131+ `celld-ltx`.
132+- **Ten small nodes held real scale.** Ten nodes, each with 4 vCPU and 8 GB,
133+ held 10,000 resident cells and 20,000 concurrent WebSocket connections. With
134+ two of the ten nodes stopped, every cell was available again on another node
135+ in ~11 s at the tail (with reserve headroom).
152136
153-- **The epoch fence holds under contention.** Five hundred claimants
154- tried at the same time to own the same cells: 5,500 attempts, one
155- writer for each epoch, zero violations.
156-- **A warm resident request is local.** A request to a resident cell does
157- zero bucket operations and returns in p50 ~1.1 ms and p99 ~7 ms (a
158- fixed-host measurement). Only a cold activation touches object storage.
159-- **A durable write waits for a durability proof.** A single node proves
160- each write through the bucket, so one storage round trip is the minimum
161- latency for that write. A fleet of two or more nodes can prove a write
162- when each follower holds it on disk, and a follower fsync is much
163- faster than a storage round trip: a lab fleet measured about 600 ms for
164- a bucket proof and about 25 ms for a fleet proof. The bucket upload
165- races every fleet proof and either one proves the write, so a slow
166- follower cannot make a write slower than a bucket proof. Concurrent
167- writes to one cell join one shared upload, so the throughput of one
168- cell is not one round trip for each write.
169-- **A restore is normal work.** Placement handles the restore of an
170- inactive cell as ordinary work, and not as an emergency procedure. The
171- measured restore times come from the retired external replicator, so this
172- page gives no number until a fleet run measures `celld-ltx`.
173-- **Ten small nodes held real scale.** A fleet of ten nodes, each with 4
174- vCPU and 8 GB, held 10,000 resident cells and 20,000 concurrent
175- WebSocket connections. We stopped two of the ten nodes, and the data of
176- every cell was available again on another node in ~11 s at the tail
177- (with reserve headroom).
137+## Known failure edges
178138
179-## The failure edges we intend to find
139+A fleet at its resident limit has no space for a lost node's cells, so losing
140+multiple nodes degrades service. We test recovery with and without reserve
141+capacity to measure this limit.
180142
181-A fleet at its resident limit has no space for the cells of a lost node,
182-so the loss of multiple nodes degrades the service. We test recovery with
183-and without reserve capacity to measure this limit.
184-
185-Report a schedule that breaks a guarantee, a fault that we do not test,
186-or a measurement that you cannot reproduce in the
143+Report a schedule that breaks a guarantee, an untested fault, or a measurement
144+that you cannot reproduce in the
187145 [issue tracker](https://github.com/denoland/celld/issues).
modifieddocs/wasm.md+29−42View file
@@ -1,9 +1,7 @@
11 # WebAssembly
22
3-A Worker bundle can import a `.wasm` file. The import gives the
4-compiled module, not the bytes. This is the same rule that Wrangler
5-applies, so a bundle that runs on Cloudflare runs on celld without a
6-change.
3+A Worker bundle can import a `.wasm` file. As in Wrangler, the import gives
4+the compiled module, not the bytes.
75
86 ```js
97 import addModule from "./add.wasm";
@@ -17,15 +15,13 @@
1715 };
1816 ```
1917
20-`celld deploy` finds each wasm import, uploads the file beside the
21-bundle, and marks the deployment with the `wasm-v1` feature. A node
22-that predates this feature refuses the deployment with a clear
23-message, so a mixed fleet fails at deploy time and not at request
18+`celld deploy` uploads each imported wasm file beside the bundle and marks the
19+deployment with the `wasm-v1` feature. A node that predates this feature
20+refuses the deployment, so a mixed fleet fails at deploy time, not at request
2421 time.
2522
26-celld compiles each wasm module once for the whole process. Every
27-isolate after the first one reuses the compiled module, so a cell
28-activation does not pay the compilation again.
23+celld compiles each wasm module once per process, so later isolates and cell
24+activations reuse it.
2925
3026 ## Example
3127
@@ -36,33 +32,27 @@
3632
3733 ## Prebuilt Workers
3834
39-With `no_bundle: true`, celld preserves the entry JavaScript byte for byte.
40-It applies Wrangler's default `**/*.wasm` and `**/*.wasm?module` patterns below
35+With `no_bundle: true`, celld preserves the entry JavaScript byte for byte. It
36+applies Wrangler's default `**/*.wasm` and `**/*.wasm?module` patterns below
4137 the directory that contains `main`. For example, `main: "./dist/shim.mjs"` can
4238 import `"./add.wasm"` or `"./lib/add.wasm"` from `dist`. The module names keep
43-these relative paths. The files use the same WASM metadata and feature gate as
44-a bundled deploy.
39+these relative paths. This mode does not require esbuild.
4540
46-The default scan includes WASM files that the JavaScript does not import. Use
47-a dedicated build output directory, so celld does not upload unrelated WASM.
48-The scan excludes `.git`, `.celld`, `.wrangler`, and symbolic links to
49-directories. It refuses a symbolic link whose name matches a WASM pattern.
50-Copy the WASM file into the build output instead of linking to it or importing
51-it from a parent directory.
41+The scan uploads WASM files that the JavaScript does not import, so use a
42+dedicated build output directory. It skips `.git`, `.celld`, `.wrangler`, and
43+symbolic links to directories. It refuses a symbolic link whose name matches a
44+WASM pattern, so copy the file into the build output instead.
5245
53-This mode matches Wrangler's default WASM discovery, but it does not implement
54-all [Wrangler module discovery settings](https://developers.cloudflare.com/workers/wrangler/configuration/#find-additional-modules).
55-celld does not discover additional JavaScript modules and does not accept
46+celld does not implement the other
47+[Wrangler module discovery settings](https://developers.cloudflare.com/workers/wrangler/configuration/#find-additional-modules).
48+It does not discover additional JavaScript modules and does not accept
5649 `rules`, `base_dir`, or `find_additional_modules`. The JavaScript must already
57-be bundled, and its WASM imports must be relative to the entry directory. This
58-mode does not require an esbuild executable.
50+be bundled, and its WASM imports must be relative to the entry directory.
5951
6052 ## Rust with workers-rs
6153
62-[workers-rs](https://github.com/cloudflare/workers-rs) compiles a Rust
63-crate to a Worker. The tool `worker-build` produces a JavaScript shim
64-and a wasm file, and the shim is a normal entry point for
65-`celld deploy`.
54+[workers-rs](https://github.com/cloudflare/workers-rs) builds a JavaScript shim
55+and a wasm file, and the shim is a normal entry point for `celld deploy`.
6656
6757 1. Install the build tool: `cargo install worker-build`.
6858 2. Build the crate: `worker-build --release`.
@@ -78,17 +68,15 @@
7868
7969 4. Deploy: `celld deploy`.
8070
81-The shim wraps its exports in a JavaScript Proxy, and celld resolves
82-entrypoint classes and Durable Object classes through that wrapper.
83-The runtime surface that the application can use is the surface in
84-[Cloudflare compatibility](cloudflare-compat.md); a workers-rs API
85-that maps to a missing runtime feature does not work.
71+celld resolves entrypoint and Durable Object classes through the shim's Proxy
72+wrapper. A workers-rs API that needs a runtime feature missing from
73+[Cloudflare compatibility](cloudflare-compat.md) does not work.
8674
8775 ## Dynamic Workers
8876
89-A dynamically loaded worker can also carry wasm. Pass the bytes in the
90-`modules` map as `{ wasm: bytes }`, and the loaded worker imports a compiled
91-module. celld refuses bare bytes, as workerd does.
77+Pass wasm to a dynamically loaded worker as `{ wasm: bytes }` in the `modules`
78+map, and the worker imports a compiled module. celld refuses bare bytes, as
79+workerd does.
9280
9381 ```js
9482 const worker = env.loader.load({
@@ -103,7 +91,6 @@
10391
10492 ## Limits
10593
106-The wasm bytes count against the deployment size limits, exactly as
107-JavaScript modules do. A wasm module that does not compile fails the
108-importing module with a `WebAssembly.CompileError` that names the
109-file.
94+Wasm bytes count against the deployment size limits like JavaScript modules. A
95+module that does not compile fails the importing module with a
96+`WebAssembly.CompileError` that names the file.