Diffinery

homeflare/celldpublic

v0.6.1

Upgrading from v0.6.0 can use a rolling update.

Setting `CELLD_LTX_RETENTION_SECS`, deploying a Python Worker, or raising
`CELLD_MAX_ASSET_FILE_BYTES` above 25 MiB can be done only after every node
runs v0.6.1.

- Add support for Python Workers.
- Bucket usage can now track a cell's data instead of growing with every
  activation: set `CELLD_LTX_RETENTION_SECS` to delete epochs that no restore
  reads. It is off by default.
- New `celld cell gc --dry-run` lists the superseded epoch prefixes that
  epoch GC can delete, with their sizes, and writes nothing.
- New `CELLD_MAX_ASSET_FILE_BYTES` (default 25 MiB) and
  `CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES` (default 64 MiB) make the per-file
  asset limit and the Dynamic Worker module size limit configurable.
- Console log records now carry the OpenTelemetry severity (`DEBUG`, `INFO`,
  `WARN`, `ERROR`) in the OTLP export and as Parquet columns.
- WebSocket message handlers on one socket now start in arrival order and do
  not wait for the previous handler to finish. Hibernatable sockets keep send
  order across WebSocket handlers and RPC methods.
- A loaded Worker is now released once no stub, entrypoint,
  class or running facet refers to it, and a later `get()` runs `getCode`
  again. `dispose()` releases it explicitly.
- Durable Object facets: `ctx.id` keeps the name of a named
  `DurableObjectId`, and `ctx.exports.App({ props })` passes startup
  properties.
- The synchronous `ctx.storage.kv.list()` iterator releases its read between
  steps, so an unfinished iterator no longer blocks later writes after a
  replication checkpoint.

Issues fixed:

- #233: An unfinished `kv.list()` iterator no longer blocks later writes.
- #236: Hibernatable sockets keep send order across handlers and `send()`.
- #237: Facets started through `ctx.exports` keep `ctx.id.name`.
- #240: Epoch GC deletes superseded epochs (`CELLD_LTX_RETENTION_SECS`).
- #241: OTLP log records carry the console method's severity.
- #242: `webSocketMessage()` no longer blocks later messages on a connection.

Co-authored-by: Ryan Dahl <[email protected]>
Co-authored-by: Yusuke Tanaka <[email protected]>
Co-authored-by: Nathan Whitaker <[email protected]>
Co-authored-by: Kyle Kelley <[email protected]>
Bartek Iwańczuk authored signed1 parent bad4649commit f2bf648663a610eefde71f3547ad61e9b896b1f0Browse files
65 files changed+4677−1042
Files (65)
modified.github/workflows/release.yml+1−1View file
@@ -28,7 +28,7 @@
2828 cancel-in-progress: true
2929
3030 env:
31- RUST_VERSION: 1.97.1
31+ RUST_VERSION: 1.98.1
3232 IMAGE: ghcr.io/denoland/celld
3333
3434 jobs:
modifiedCargo.lock+1−1View file
@@ -285,7 +285,7 @@
285285
286286 [[package]]
287287 name = "celld"
288-version = "0.6.0"
288+version = "0.6.1"
289289 dependencies = [
290290 "aes",
291291 "aes-gcm",
modifiedDockerfile+1−1View file
@@ -1,6 +1,6 @@
11 # syntax=docker/dockerfile:1.7
22
3-ARG RUST_VERSION=1.97.1
3+ARG RUST_VERSION=1.98.1
44 ARG CELLD_COMMIT=unknown
55
66 FROM rust:${RUST_VERSION}-bookworm AS build
modifiedcrates/celld/Cargo.toml+1−1View file
@@ -1,6 +1,6 @@
11 [package]
22 name = "celld"
3-version = "0.6.0"
3+version = "0.6.1"
44 edition = "2021"
55 rust-version = "1.94.1"
66 license = "Apache-2.0"
modifiedcrates/celld/actor.rs+306−333View file
@@ -3,7 +3,7 @@
33 //! The serial lifecycle executor and its shell-side request drivers.
44
55 use crate::cell_host::CellHost;
6-use crate::js::{HttpResponse, WsOut};
6+use crate::js::{HttpResponse, WsBatch};
77 use crate::machine::{
88 ownership_on_evict_from_environment, pressure_config_from_environment,
99 random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
@@ -28,9 +28,12 @@
2828 use tokio::sync::{mpsc, oneshot, watch, Mutex};
2929 use tokio_util::time::{delay_queue, DelayQueue};
3030
31+mod effects;
3132 mod local_request;
3233 mod production;
3334 pub use celld_logic::{EvictCancellation, EvictError, EvictFailure, EvictRefusal, EvictSuccess};
35+pub use effects::StepOutput;
36+pub(crate) use effects::{drain_step_output, LeaseRequest};
3437 pub use local_request::{LocalRequest, LocalRequestCompletion, LocalRequestFailure};
3538
3639 type EvictionReply = oneshot::Sender<Result<EvictSuccess, EvictError>>;
@@ -390,7 +393,7 @@
390393 pub enum Message {
391394 /// A periodic resource sample. The measuring is the shell's job; every
392395 /// decision that follows belongs to the core.
393- SampleLoad,
396+ SampleLoad(crate::host_services::HostMetricsSample),
394397 /// The log tier changed the folded log object the next lease write
395398 /// must carry (lease-fold): renew now so the change becomes durable.
396399 NudgeNodeLease,
@@ -475,7 +478,7 @@
475478 WsOutput {
476479 request: u64,
477480 scope: String,
478- frames: Vec<(u64, WsOut)>,
481+ frames: WsBatch,
479482 write_position: Option<u64>,
480483 observed: Option<u64>,
481484 reply: oneshot::Sender<()>,
@@ -1214,33 +1217,6 @@
12141217 TimerFired(Timer),
12151218 }
12161219
1217-/// Futures and timer arms emitted by one Actor transition.
1218-#[derive(Default)]
1219-pub struct StepOutput {
1220- pub effects: Vec<EffectFuture>,
1221- pub timers: Vec<TimerArm>,
1222-}
1223-
1224-fn drain_step_output(
1225- out: &mut StepOutput,
1226- effects: &mut FuturesUnordered<EffectFuture>,
1227- delays: &mut DelayQueue<TimerArm>,
1228- timers: &mut TimerSlots<delay_queue::Key>,
1229-) {
1230- for effect in out.effects.drain(..) {
1231- effects.push(effect);
1232- }
1233- for arm in out.timers.drain(..) {
1234- let delay = std::time::Duration::from_millis(
1235- arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()),
1236- );
1237- let key = delays.insert(arm.clone(), delay);
1238- if let Some(displaced) = timers.install(&arm, key) {
1239- delays.remove(&displaced);
1240- }
1241- }
1242-}
1243-
12441220 /// The largest request body that a node accepts unless the operator lowers
12451221 /// the limit. The value keeps the large git-pack ingress use case supported.
12461222 pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1 << 30;
@@ -1512,6 +1488,13 @@
15121488 result
15131489 }
15141490
1491+ pub(crate) fn execution_host(&self) -> Option<CellHost> {
1492+ let host = self.runtime.clone().map(CellHost::Engine);
1493+ #[cfg(all(test, celld_internal_tests))]
1494+ let host = host.or_else(|| self.scripted_activity_host.clone().map(CellHost::Scripted));
1495+ host
1496+ }
1497+
15151498 pub fn activity(&self, request: u64, cell: String) -> ActivityGuard {
15161499 self.activity_for(request, cell, None, "local")
15171500 }
@@ -1524,9 +1507,7 @@
15241507 origin: &'static str,
15251508 ) -> ActivityGuard {
15261509 let cancellation = self.drain_pins.begin(request, request_id, origin);
1527- let host = self.runtime.clone().map(CellHost::Engine);
1528- #[cfg(all(test, celld_internal_tests))]
1529- let host = host.or_else(|| self.scripted_activity_host.clone().map(CellHost::Scripted));
1510+ let host = self.execution_host();
15301511 ActivityGuard {
15311512 tx: self.tx.clone(),
15321513 request,
@@ -1619,7 +1600,7 @@
16191600 &self,
16201601 request: u64,
16211602 scope: String,
1622- frames: Vec<(u64, WsOut)>,
1603+ frames: impl Into<WsBatch>,
16231604 write_position: Option<u64>,
16241605 observed: Option<u64>,
16251606 ) -> Result<(), ActorStopped> {
@@ -1628,7 +1609,7 @@
16281609 .send(Message::WsOutput {
16291610 request,
16301611 scope,
1631- frames,
1612+ frames: frames.into(),
16321613 write_position,
16331614 observed,
16341615 reply,
@@ -1835,7 +1816,7 @@
18351816 struct WsBarrier {
18361817 request: u64,
18371818 settled: Option<bool>,
1838- frames: Vec<(u64, WsOut)>,
1819+ frames: WsBatch,
18391820 }
18401821
18411822 /// The actor stopped before it answered: its channel is closed, and nothing
@@ -1968,9 +1949,8 @@
19681949 /// Debug builds keep it. Release builds rely on the deterministic model,
19691950 /// because this full-table scan is too expensive for production traffic.
19701951 validate_invariants: bool,
1971- /// The counters peers rank this node by, when there is a bucket to
1972- /// publish them to.
1973- live_load: Option<Arc<crate::ownership_store::LiveLoad>>,
1952+ /// Keep a sample for `/state` even without a bucket to publish it to.
1953+ live_load: Arc<crate::ownership_store::LiveLoad>,
19741954 /// The shed reason last reported to the log, so a latch that holds for
19751955 /// minutes is reported once rather than on every sample.
19761956 logged_shed_reason: Option<&'static str>,
@@ -2040,7 +2020,31 @@
20402020 directory.sampled_at_mono_ms = Some(now_mono_ms);
20412021 }
20422022 let peers = directory.peers.clone();
2043- let mut ranked = rank_handoff_candidates(peers, source, cell, now_ms());
2023+ let current_ms = now_ms();
2024+ let mut ranked = rank_handoff_candidates(peers, source, cell, current_ms);
2025+ // Several cells share this directory between refreshes. Emit one peer
2026+ // list per scan, so a blocked drain does not repeat it for every cell.
2027+ if stale && ranked.is_empty() && tracing::enabled!(tracing::Level::DEBUG) {
2028+ tracing::debug!(
2029+ event = "handoff_no_candidate",
2030+ %source,
2031+ %cell,
2032+ excluded_peers = %serde_json::Value::Array(directory.peers.iter().map(|peer| {
2033+ serde_json::json!({
2034+ "node": peer.node,
2035+ "excluded_by": handoff_exclusions(peer, source, current_ms).collect::<Vec<_>>(),
2036+ "pressured": peer.pressured,
2037+ "memory_headroom": peer.memory_headroom,
2038+ "sampled_ms": peer.sampled_ms,
2039+ "addr": peer.addr,
2040+ "protocol": peer.peer_protocol,
2041+ "paced_handoff": peer.paced_handoff,
2042+ "expires_ms": peer.expires_ms,
2043+ })
2044+ }).collect()),
2045+ "no peer can adopt a released cell"
2046+ );
2047+ }
20442048 if rebalance {
20452049 // A drain takes any peer with room. A balancing move takes only a
20462050 // peer below its ownership target, least dense first; a fuller peer
@@ -2068,6 +2072,33 @@
20682072 Ok(ranked)
20692073 }
20702074
2075+/// Names every reason a peer cannot adopt a handoff. Candidate selection and
2076+/// the no-candidate diagnostic both use it, so a logged reason cannot drift
2077+/// from the rule that actually excluded the peer.
2078+fn handoff_exclusions(
2079+ peer: &CapacityPeer,
2080+ source: &str,
2081+ current_ms: u64,
2082+) -> impl Iterator<Item = &'static str> {
2083+ [
2084+ (peer.node == source, "source"),
2085+ (peer.expires_ms <= current_ms, "expiry"),
2086+ (peer.addr.is_empty(), "addr"),
2087+ (
2088+ peer.peer_protocol != peer_auth::PROTOCOL_VERSION,
2089+ "protocol",
2090+ ),
2091+ (peer.sampled_ms == 0, "sampled_ms"),
2092+ (
2093+ !peer.reports_adoption_capacity(),
2094+ "reports_adoption_capacity",
2095+ ),
2096+ (!peer.paced_handoff, "paced_handoff"),
2097+ ]
2098+ .into_iter()
2099+ .filter_map(|(excluded, reason)| excluded.then_some(reason))
2100+}
2101+
20712102 fn rank_handoff_candidates(
20722103 peers: Vec<CapacityPeer>,
20732104 source: &str,
@@ -2077,13 +2108,9 @@
20772108 let mut peers: Vec<_> = peers
20782109 .into_iter()
20792110 .filter(|peer| {
2080- peer.node != source
2081- && peer.expires_ms > current_ms
2082- && !peer.addr.is_empty()
2083- && peer.peer_protocol == peer_auth::PROTOCOL_VERSION
2084- && peer.sampled_ms != 0
2085- && peer.reports_adoption_capacity()
2086- && peer.paced_handoff
2111+ handoff_exclusions(peer, source, current_ms)
2112+ .next()
2113+ .is_none()
20872114 })
20882115 .collect();
20892116 peers.sort_by_key(|peer| {
@@ -2391,13 +2418,14 @@
23912418 })))
23922419 };
23932420 let live_load = match &ownership {
2394- Ownership::Bucket(bucket) => Some(bucket.live()),
2395- Ownership::Memory(_) => None,
2421+ Ownership::Bucket(bucket) => bucket.live(),
2422+ Ownership::Memory(_) => Arc::new(crate::ownership_store::LiveLoad::default()),
23962423 };
2397- if let Some(live) = &live_load {
2398- live.placement_weight
2399- .store(limits.placement_weight.max(1), Ordering::Relaxed);
2400- crate::ownership_store::set_node_load(live.clone());
2424+ live_load
2425+ .placement_weight
2426+ .store(limits.placement_weight.max(1), Ordering::Relaxed);
2427+ if matches!(&ownership, Ownership::Bucket(_)) {
2428+ crate::ownership_store::set_node_load(live_load.clone());
24012429 }
24022430 let process_generation = match &ownership {
24032431 Ownership::Bucket(bucket) => bucket
@@ -2497,10 +2525,26 @@
24972525 })
24982526 }
24992527
2528+ /// Stores a host sample for `/state` and the node lease.
2529+ pub fn store_load_sample(&self, sample: crate::host_services::HostMetricsSample) {
2530+ // Bucket mode shares this Arc with bucket.live(), so this also seeds the lease.
2531+ self.live_load.store_sample(sample);
2532+ }
2533+
25002534 /// Emits the exactly-once pre-loop node-lease transition.
25012535 pub fn start(&mut self, out: &mut StepOutput) {
25022536 assert!(!self.started, "Actor::start was called more than once");
25032537 self.started = true;
2538+ // A later sample does not rewrite the lease. Fold a sample before the
2539+ // first CAS can publish defaults, which otherwise reject healthy
2540+ // handoff targets or hide pressure until a renewal. Production seeds
2541+ // one off the core before the core thread starts; the fallback serves
2542+ // deterministic worlds, whose scripted services read no host files.
2543+ let metrics = self
2544+ .live_load
2545+ .stored_sample()
2546+ .unwrap_or_else(|| crate::asyncrt::services().sample_metrics());
2547+ self.sample_load(metrics, out);
25042548 self.drive(
25052549 Event::StartNodeLease {
25062550 now_ms: now_ms(),
@@ -2511,6 +2555,89 @@
25112555 );
25122556 }
25132557
2558+ /// Folds one load sample into the core and publishes it to the lease
2559+ /// adapter. `start` calls it before the first lease; the periodic sampler
2560+ /// message calls it afterwards. The caller supplies the sample, so the
2561+ /// core itself reads no host files.
2562+ fn sample_load(
2563+ &mut self,
2564+ metrics: crate::host_services::HostMetricsSample,
2565+ out: &mut StepOutput,
2566+ ) {
2567+ // Counted once: it is a walk of every cell, and the latch and
2568+ // the number peers rank this node by must agree anyway.
2569+ let occupied = self.state.occupied();
2570+ let load = celld_logic::pressure::Load {
2571+ resident_cells: occupied,
2572+ rss_bytes: metrics.rss_bytes,
2573+ in_use_bytes: metrics.in_use_bytes,
2574+ cgroup_working_set_bytes: metrics.cgroup_working_set_bytes,
2575+ cgroup_current_bytes: metrics.cgroup_current_bytes,
2576+ // Containers run in sibling cgroups, so the sample above
2577+ // omits their memory; add what they reserve on this node.
2578+ container_reserved_bytes: crate::container::reserved_memory_bytes(),
2579+ };
2580+ let now_mono_ms = crate::asyncrt::mono_ms();
2581+ self.drive(Event::LoadSampled { load, now_mono_ms }, out);
2582+ // Report a change of shed reason once. `rss-hard` retains its
2583+ // established name, but in a Linux cgroup it says
2584+ // `memory.current` crossed the absolute cap.
2585+ let reason = self.state.shed_reason();
2586+ if reason != self.logged_shed_reason {
2587+ self.logged_shed_reason = reason;
2588+ // How many V8 heaps the resident cells hold open. Most of
2589+ // what a cell costs is its heap, and a heap comes back
2590+ // only when its last cell goes, so cells alone do not say
2591+ // how much a walk down can still return.
2592+ let heaps = self
2593+ .state
2594+ .resident_isolates()
2595+ .into_iter()
2596+ .collect::<BTreeSet<_>>()
2597+ .len();
2598+ match reason {
2599+ Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!(
2600+ rss_bytes = load.rss_bytes,
2601+ in_use_bytes = load.in_use_bytes,
2602+ cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2603+ cgroup_current_bytes = load.cgroup_current_bytes,
2604+ heaps,
2605+ "shedding on the absolute memory cap"
2606+ ),
2607+ Some(reason) => tracing::info!(
2608+ reason,
2609+ rss_bytes = load.rss_bytes,
2610+ in_use_bytes = load.in_use_bytes,
2611+ cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2612+ cgroup_current_bytes = load.cgroup_current_bytes,
2613+ heaps,
2614+ "shedding"
2615+ ),
2616+ None => tracing::info!("no longer shedding"),
2617+ }
2618+ }
2619+ // Republish what peers rank this node by. The same numbers the
2620+ // latch just saw: a node that reports last tick's residency
2621+ // attracts work it has already refused.
2622+ let live = &self.live_load;
2623+ live.owned_cells
2624+ .store(self.state.owned_cells(), Ordering::Relaxed);
2625+ live.ownership_confirmed
2626+ .store(self.state.ownership_confirmed(), Ordering::Relaxed);
2627+ live.resident_cells.store(occupied, Ordering::Relaxed);
2628+ live.host_websockets
2629+ .store(self.state.host_websockets(), Ordering::Relaxed);
2630+ live.pressured
2631+ .store(self.state.shedding(), Ordering::Relaxed);
2632+ live.memory_headroom
2633+ .store(self.state.memory_headroom(), Ordering::Relaxed);
2634+ live.restoring
2635+ .store(self.state.activation_backlog() as u64, Ordering::Relaxed);
2636+ live.draining
2637+ .store(self.state.draining(), Ordering::Relaxed);
2638+ live.store_sample(metrics);
2639+ }
2640+
25142641 /// Handles exactly one ready mailbox item, completion, or timer.
25152642 pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) {
25162643 assert!(self.started, "Actor::step was called before Actor::start");
@@ -2654,84 +2781,8 @@
26542781 };
26552782 let _ = reply.send(epoch);
26562783 }
2657- Message::SampleLoad if self.preserving => {}
2658- Message::SampleLoad => {
2659- // Counted once: it is a walk of every cell, and the latch and
2660- // the number peers rank this node by must agree anyway.
2661- let occupied = self.state.occupied();
2662- let metrics = crate::asyncrt::services().sample_metrics();
2663- let cpu = metrics.cpu_percent_x100;
2664- let load = celld_logic::pressure::Load {
2665- resident_cells: occupied,
2666- rss_bytes: metrics.rss_bytes,
2667- in_use_bytes: metrics.in_use_bytes,
2668- cgroup_working_set_bytes: metrics.cgroup_working_set_bytes,
2669- cgroup_current_bytes: metrics.cgroup_current_bytes,
2670- // Containers run in sibling cgroups, so the sample above
2671- // omits their memory; add what they reserve on this node.
2672- container_reserved_bytes: crate::container::reserved_memory_bytes(),
2673- };
2674- let now_mono_ms = crate::asyncrt::mono_ms();
2675- self.drive(Event::LoadSampled { load, now_mono_ms }, out);
2676- // Report a change of shed reason once. `rss-hard` retains its
2677- // established name, but in a Linux cgroup it says
2678- // `memory.current` crossed the absolute cap.
2679- let reason = self.state.shed_reason();
2680- if reason != self.logged_shed_reason {
2681- self.logged_shed_reason = reason;
2682- // How many V8 heaps the resident cells hold open. Most of
2683- // what a cell costs is its heap, and a heap comes back
2684- // only when its last cell goes, so cells alone do not say
2685- // how much a walk down can still return.
2686- let heaps = self
2687- .state
2688- .resident_isolates()
2689- .into_iter()
2690- .collect::<BTreeSet<_>>()
2691- .len();
2692- match reason {
2693- Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!(
2694- rss_bytes = load.rss_bytes,
2695- in_use_bytes = load.in_use_bytes,
2696- cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2697- cgroup_current_bytes = load.cgroup_current_bytes,
2698- heaps,
2699- "shedding on the absolute memory cap"
2700- ),
2701- Some(reason) => tracing::info!(
2702- reason,
2703- rss_bytes = load.rss_bytes,
2704- in_use_bytes = load.in_use_bytes,
2705- cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2706- cgroup_current_bytes = load.cgroup_current_bytes,
2707- heaps,
2708- "shedding"
2709- ),
2710- None => tracing::info!("no longer shedding"),
2711- }
2712- }
2713- // Republish what peers rank this node by. The same numbers the
2714- // latch just saw: a node that reports last tick's residency
2715- // attracts work it has already refused.
2716- if let Some(live) = &self.live_load {
2717- live.owned_cells
2718- .store(self.state.owned_cells(), Ordering::Relaxed);
2719- live.ownership_confirmed
2720- .store(self.state.ownership_confirmed(), Ordering::Relaxed);
2721- live.resident_cells.store(occupied, Ordering::Relaxed);
2722- live.host_websockets
2723- .store(self.state.host_websockets(), Ordering::Relaxed);
2724- live.pressured
2725- .store(self.state.shedding(), Ordering::Relaxed);
2726- live.memory_headroom
2727- .store(self.state.memory_headroom(), Ordering::Relaxed);
2728- live.cpu_percent_x100.store(cpu, Ordering::Relaxed);
2729- live.restoring
2730- .store(self.state.activation_backlog() as u64, Ordering::Relaxed);
2731- live.draining
2732- .store(self.state.draining(), Ordering::Relaxed);
2733- }
2734- }
2784+ Message::SampleLoad(metrics) if self.preserving => self.live_load.store_sample(metrics),
2785+ Message::SampleLoad(metrics) => self.sample_load(metrics, out),
27352786 Message::Output {
27362787 request,
27372788 ticket,
@@ -2981,9 +3032,14 @@
29813032 }
29823033 };
29833034 if broke {
2984- self.ws_gates.remove(&scope);
3035+ // Close before the barriers drop. A captured batch that drops
3036+ // unreleased closes its sockets with its own reason, and a socket
3037+ // writer stops after the first close, so dropping the gate first
3038+ // would replace this reason on every socket that had a frame held.
3039+ let gate = self.ws_gates.remove(&scope);
29853040 self.ws_gated.retain(|_, s| *s != scope);
29863041 crate::js::ws_close_scope(&scope, 1011, "durability unproven");
3042+ drop(gate);
29873043 return;
29883044 }
29893045 for frames in flush {
@@ -3104,17 +3160,13 @@
31043160 out.timers.push(arm);
31053161 }
31063162 Effect::ReadSelfNodeLease { op } => {
3107- let ownership = self.ownership.clone();
3108- let node = self.state.node().to_string();
3109- out.effects.push(Box::pin(async move {
3110- let result = ownership.read_self_node_lease(&node).await;
3111- CompletedEffect::plain(Event::SelfNodeLeaseRead {
3163+ out.lease(
3164+ LeaseRequest::ReadSelf {
31123165 op,
3113- now_ms: now_ms(),
3114- now_mono_ms: crate::asyncrt::mono_ms(),
3115- result,
3116- })
3117- }));
3166+ node: self.state.node().to_string(),
3167+ },
3168+ &self.ownership,
3169+ );
31183170 }
31193171 Effect::CasNodeLease {
31203172 op,
@@ -3122,115 +3174,19 @@
31223174 record,
31233175 authority_expires_ms,
31243176 } => {
3125- let ownership = self.ownership.clone();
3126- out.effects.push(Box::pin(async move {
3127- let attempt_started_mono_ms = crate::asyncrt::mono_ms();
3128- let node = record.node.clone();
3129- let candidate_expires_ms = record.expires_ms;
3130- // Logged before the CAS: with only the completion line, a
3131- // renewal hung on a storage tail is indistinguishable from
3132- // a timer that never fired (the n6 fence, 2026-08-11).
3133- tracing::info!(
3134- event = "node_lease_attempt_started",
3135- %node,
3136- attempt = if authority_expires_ms.is_some() {
3137- "renew"
3138- } else {
3139- "acquire"
3140- },
3141- prior_authority_headroom_ms = authority_expires_ms
3142- .map(|expires_ms| expires_ms.saturating_sub(now_ms()))
3143- .unwrap_or(0),
3144- "node lease attempt started"
3145- );
3146- // A renewal must return while proven authority remains,
3147- // because only a returned attempt lets the ambiguity
3148- // read-back run before the watchdog. The 10:15Z R2
3149- // brownout fenced 9 nodes whose sole hung attempt was
3150- // still inside the transport's 15 s timeout when the
3151- // 10 s TTL expired. Bound the attempt to half the
3152- // remaining authority (capped, floored) and map timeout
3153- // to Ambiguous — the same conservative outcome a lost
3154- // response already produces, so safety is unchanged.
3155- // The stamp survives a timed-out attempt: the backend
3156- // writes it through the out-parameter synchronously at
3157- // serialization, before the transport await, so even a
3158- // dropped future has reported what the possibly-landed
3159- // body carried.
3160- let mut stamped_log_state = None;
3161- let result = match authority_expires_ms {
3162- Some(expires_ms) => {
3163- let remaining = expires_ms.saturating_sub(now_ms());
3164- let bound =
3165- std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500));
3166- match crate::asyncrt::timeout(
3167- bound,
3168- ownership.cas_node_lease(guard, record, &mut stamped_log_state),
3169- )
3170- .await
3171- {
3172- Ok(result) => result,
3173- Err(_) => Err(Failure::Ambiguous),
3174- }
3175- }
3176- None => {
3177- ownership
3178- .cas_node_lease(guard, record, &mut stamped_log_state)
3179- .await
3180- }
3181- };
3182- let completed_ms = now_ms();
3183- let elapsed_ms =
3184- crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms);
3185- let prior_authority_headroom_ms = authority_expires_ms
3186- .map(|expires_ms| expires_ms.saturating_sub(completed_ms))
3187- .unwrap_or(0);
3188- let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms);
3189- let attempt = if authority_expires_ms.is_some() {
3190- "renew"
3191- } else {
3192- "acquire"
3193- };
3194- let outcome = match &result {
3195- Ok(LeaseCasOutcome::Applied { .. }) => "applied",
3196- Ok(LeaseCasOutcome::Rejected) => "rejected",
3197- Err(Failure::Ambiguous) => "ambiguous",
3198- Err(Failure::Definite) => "definite_failure",
3199- };
3200- if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) {
3201- tracing::info!(
3202- event = "node_lease_attempt",
3203- %node,
3204- attempt,
3205- outcome,
3206- elapsed_ms,
3207- prior_authority_headroom_ms,
3208- candidate_headroom_ms,
3209- "node lease attempt completed"
3210- );
3211- } else {
3212- tracing::warn!(
3213- event = "node_lease_attempt",
3214- %node,
3215- attempt,
3216- outcome,
3217- elapsed_ms,
3218- prior_authority_headroom_ms,
3219- candidate_headroom_ms,
3220- "node lease attempt did not apply"
3221- );
3222- }
3223- CompletedEffect::plain(Event::NodeLeaseCasCompleted {
3177+ out.lease(
3178+ LeaseRequest::Cas {
32243179 op,
3225- now_mono_ms: crate::asyncrt::mono_ms(),
3226- result,
3227- stamped_log_state,
3228- })
3229- }));
3180+ guard,
3181+ record,
3182+ authority_expires_ms,
3183+ },
3184+ &self.ownership,
3185+ );
32303186 }
32313187 Effect::ReadLocalCells => {
32323188 let runtime = self.host.clone();
3233- out.effects.push(Box::pin(async move {
3189+ out.spawn_scoped(async move {
32343190 let result = match runtime {
32353191 // The host runtime's blocking pool, not a second
32363192 // pool on the core's current-thread runtime.
@@ -3245,13 +3201,13 @@
32453201 None => Err(Failure::Definite),
32463202 };
32473203 CompletedEffect::plain(Event::LocalCellsRead { result })
3248- }));
3204+ });
32493205 }
32503206 Effect::ReadOwner { op, cell } => {
32513207 self.route_effect_started(&cell);
32523208 let ownership = self.ownership.clone();
32533209 let timing_cell = cell.clone();
3254- out.effects.push(Box::pin(async move {
3210+ out.spawn_scoped(async move {
32553211 let started = crate::asyncrt::mono_ms();
32563212 let result = ownership.read_owner(&cell).await;
32573213 CompletedEffect::timed(
@@ -3264,13 +3220,13 @@
32643220 RouteStage::OwnershipRead,
32653221 started,
32663222 )
3267- }));
3223+ });
32683224 }
32693225 Effect::ReadNodeLease { op, cell, owner } => {
32703226 self.route_effect_started(&cell);
32713227 let ownership = self.ownership.clone();
32723228 let timing_cell = cell;
3273- out.effects.push(Box::pin(async move {
3229+ out.spawn_scoped(async move {
32743230 let started = crate::asyncrt::mono_ms();
32753231 let result = ownership.read_node_lease(&owner).await;
32763232 CompletedEffect::timed(
@@ -3283,13 +3239,13 @@
32833239 RouteStage::NodeLeaseLookup,
32843240 started,
32853241 )
3286- }));
3242+ });
32873243 }
32883244 Effect::RecoverNodeLog { op, cell, owner } => {
32893245 self.route_effect_started(&cell);
32903246 let interlock = self.node_log.lock().unwrap().clone();
32913247 let timing_cell = cell.clone();
3292- out.effects.push(Box::pin(async move {
3248+ out.spawn_scoped(async move {
32933249 let started = crate::asyncrt::mono_ms();
32943250 let result = match interlock {
32953251 // No log tier on this node (no bucket): nothing to
@@ -3311,13 +3267,13 @@
33113267 RouteStage::NodeLeaseLookup,
33123268 started,
33133269 )
3314- }));
3270+ });
33153271 }
33163272 Effect::ReadCapacityPeers { op, cell } => {
33173273 self.route_effect_started(&cell);
33183274 let ownership = self.ownership.clone();
33193275 let timing_cell = cell;
3320- out.effects.push(Box::pin(async move {
3276+ out.spawn_scoped(async move {
33213277 let started = crate::asyncrt::mono_ms();
33223278 // The shared sample, judged at the instant it was taken:
33233279 // its leases are copies that age while the nodes renew.
@@ -3331,7 +3287,7 @@
33313287 RouteStage::CapacityLookup,
33323288 started,
33333289 )
3334- }));
3290+ });
33353291 }
33363292 Effect::CasOwner {
33373293 op,
@@ -3348,7 +3304,7 @@
33483304 }
33493305 let ownership = self.ownership.clone();
33503306 let timing_cell = cell.clone();
3351- out.effects.push(Box::pin(async move {
3307+ out.spawn_scoped(async move {
33523308 let started = crate::asyncrt::mono_ms();
33533309 let result = ownership.cas_owner(&cell, guard, epoch).await;
33543310 CompletedEffect::timed(
@@ -3357,7 +3313,7 @@
33573313 RouteStage::OwnershipAcquire,
33583314 started,
33593315 )
3360- }));
3316+ });
33613317 }
33623318 Effect::ReconcileWakeEntry { cell, alarm } => {
33633319 self.schedule_wake_maintenance(cell, alarm);
@@ -3374,10 +3330,10 @@
33743330 );
33753331 }
33763332 let ownership = self.ownership.clone();
3377- out.effects.push(Box::pin(async move {
3333+ out.spawn_scoped(async move {
33783334 let result = ownership.release_owner(&cell, epoch).await;
33793335 CompletedEffect::plain(Event::OwnerReleased { op, result })
3380- }));
3336+ });
33813337 }
33823338 Effect::AdoptReleased {
33833339 op,
@@ -3411,7 +3367,7 @@
34113367 // next request to claim.
34123368 let deadline =
34133369 rebalance.then(|| std::time::Duration::from_millis(self.operation_deadline_ms));
3414- out.effects.push(Box::pin(async move {
3370+ out.spawn_scoped(async move {
34153371 let started_mono_ms = crate::asyncrt::mono_ms();
34163372 let request = HandoffRequest {
34173373 cell: cell.clone(),
@@ -3463,9 +3419,43 @@
34633419 Ok(HandoffAttempt::CurrentOwner(owner)) => {
34643420 target = owner;
34653421 }
3466- Ok(HandoffAttempt::Accepted(_))
3467- | Ok(HandoffAttempt::Refused)
3468- | Err(_) => break,
3422+ Ok(HandoffAttempt::Accepted(adopted)) => {
3423+ tracing::debug!(
3424+ event = "cell_handoff_stale_epoch",
3425+ %cell,
3426+ released_epoch,
3427+ successor = %adopted.node,
3428+ successor_epoch = adopted.epoch,
3429+ attempts,
3430+ "successor acknowledged an obsolete ownership epoch"
3431+ );
3432+ break;
3433+ }
3434+ Ok(HandoffAttempt::Refused) => {
3435+ tracing::debug!(
3436+ event = "cell_handoff_refused",
3437+ %cell,
3438+ released_epoch,
3439+ successor = %target.node,
3440+ successor_addr = %target.addr,
3441+ attempts,
3442+ "successor refused a released cell"
3443+ );
3444+ break;
3445+ }
3446+ Err(error) => {
3447+ tracing::debug!(
3448+ event = "cell_handoff_failed",
3449+ %cell,
3450+ released_epoch,
3451+ successor = %target.node,
3452+ successor_addr = %target.addr,
3453+ attempts,
3454+ %error,
3455+ "successor handoff request failed"
3456+ );
3457+ break;
3458+ }
34693459 }
34703460 }
34713461 }
@@ -3494,7 +3484,7 @@
34943484 }),
34953485 None => adoption.await,
34963486 }
3497- }));
3487+ });
34983488 }
34993489 Effect::CancelCellActivity {
35003490 cell,
@@ -3554,7 +3544,7 @@
35543544 match runtime.alarm_observation(&cell) {
35553545 Some((mut alarm, false)) if alarm.at_ms().is_some() => {
35563546 let at_ms = alarm.at_ms().unwrap();
3557- out.effects.push(Box::pin(async move {
3547+ out.spawn_scoped(async move {
35583548 let started = crate::asyncrt::mono_ms();
35593549 // One refresh is not enough for an object
35603550 // that re-arms its alarm continuously (the
@@ -3601,7 +3591,7 @@
36013591 now_ms: now_ms(),
36023592 now_mono_ms: crate::asyncrt::mono_ms(),
36033593 })
3604- }));
3594+ });
36053595 }
36063596 Some((alarm, covered)) => immediate.push_back(Event::AlarmObserved {
36073597 cell,
@@ -3618,11 +3608,11 @@
36183608 self.route_effect_started(&cell);
36193609 if let Some(runtime) = self.host.clone() {
36203610 let timing_cell = cell.clone();
3621- // A restore downloads, merges, and fsyncs a whole
3622- // database. Poll it on the host runtime: this future
3623- // lives in `out`, which the core thread drives,
3624- // and the core owns the node lease timer.
3625- let task = crate::asyncrt::spawn(async move {
3611+ // A restore downloads, merges, and fsyncs a whole database.
3612+ // The drain runs it off the core, which owns the node lease timer.
3613+ // Choosing `spawn_detached` over `spawn_scoped` only keeps this
3614+ // arm's seeded DST schedule stable (see `StepOutput::spawn_detached`).
3615+ out.spawn_detached(async move {
36263616 let started = crate::asyncrt::mono_ms();
36273617 let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| {
36283618 eprintln!("celld restore failed for {cell}: {error:#}");
@@ -3635,9 +3625,6 @@
36353625 started,
36363626 )
36373627 });
3638- out.effects.push(Box::pin(async move {
3639- task.await.expect("restore task panicked")
3640- }));
36413628 } else {
36423629 self.record_effect_timing(EffectTiming {
36433630 cell,
@@ -3662,7 +3649,7 @@
36623649 .and_then(|timing| timing.fresh)
36633650 .unwrap_or(false);
36643651 let timing_cell = cell.clone();
3665- out.effects.push(Box::pin(async move {
3652+ out.spawn_scoped(async move {
36663653 let started = crate::asyncrt::mono_ms();
36673654 let placed = runtime
36683655 .start_cell(cell.clone(), epoch, fresh)
@@ -3687,7 +3674,7 @@
36873674 RouteStage::IsolateStartup,
36883675 started,
36893676 )
3690- }));
3677+ });
36913678 } else {
36923679 self.record_effect_timing(EffectTiming {
36933680 cell,
@@ -3767,13 +3754,11 @@
37673754 );
37683755 }
37693756 if let Some(runtime) = self.host.clone() {
3770- // A hot cell can merge thousands of staged LTX rows while
3771- // this future is between awaits. Keep that synchronous
3772- // merge on the host runtime: `out` is polled by the
3773- // dedicated core thread, which also owns the node-lease
3774- // renew and fence timers. Polling the proof inline can
3775- // therefore turn a graceful handoff into a self-fence.
3776- let task = crate::asyncrt::spawn(async move {
3757+ // This durability wait runs during a graceful handoff.
3758+ // The drain keeps it off the core, which owns the lease timers.
3759+ // `spawn_detached` only keeps the seeded DST schedule stable
3760+ // (see `StepOutput::spawn_detached`).
3761+ out.spawn_detached(async move {
37773762 let proved = runtime.ensure_durable(&cell, epoch, revocable).await;
37783763 let result = proved.map_err(|error| {
37793764 eprintln!(
@@ -3783,9 +3768,6 @@
37833768 });
37843769 CompletedEffect::plain(Event::DurabilityChecked { op, result })
37853770 });
3786- out.effects.push(Box::pin(async move {
3787- task.await.expect("durability proof task panicked")
3788- }));
37893771 } else {
37903772 immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) });
37913773 }
@@ -3800,7 +3782,7 @@
38003782 position,
38013783 } => {
38023784 if let Some(runtime) = self.host.clone() {
3803- out.effects.push(Box::pin(async move {
3785+ out.spawn_scoped(async move {
38043786 // The replicator reports the position it actually
38053787 // proved durable and which mechanism proved it; the
38063788 // core acks only if the position covers this write,
@@ -3818,7 +3800,7 @@
38183800 }
38193801 };
38203802 CompletedEffect::plain(Event::DurableReached { op, result, source })
3821- }));
3803+ });
38223804 } else {
38233805 immediate.push_back(Event::DurableReached {
38243806 op,
@@ -3838,7 +3820,7 @@
38383820 // restores from a lineage that already contains the write.
38393821 let ownership = self.ownership.clone();
38403822 let node = self.state.node().to_string();
3841- out.effects.push(Box::pin(async move {
3823+ out.spawn_scoped(async move {
38423824 let result = match ownership.read_owner(&cell).await {
38433825 Ok(Some(record))
38443826 if record.node.as_deref() == Some(node.as_str())
@@ -3857,7 +3839,7 @@
38573839 Err(failure) => Err(failure),
38583840 };
38593841 CompletedEffect::plain(Event::OwnershipVerified { op, result })
3860- }));
3842+ });
38613843 }
38623844 // The shell's only per-channel code: how the effect was held, and
38633845 // how it is released. Every channel but one takes a durability
@@ -3924,7 +3906,7 @@
39243906 self.published.remove(&cell);
39253907 if let Some(runtime) = self.host.clone() {
39263908 let released = cell.clone();
3927- let task = crate::asyncrt::spawn(report_stopped_when_released(
3909+ out.spawn_detached(report_stopped_when_released(
39283910 op,
39293911 cell,
39303912 epoch,
@@ -3936,9 +3918,6 @@
39363918 async move { runtime.swap_out_cell(&cell, epoch).await }
39373919 },
39383920 ));
3939- out.effects.push(Box::pin(async move {
3940- task.await.expect("swap out task panicked")
3941- }));
39423921 } else {
39433922 immediate.push_back(Event::RuntimeStopped { op });
39443923 }
@@ -3974,25 +3953,21 @@
39743953 StopCause::Swap => unreachable!("generation swaps return above"),
39753954 };
39763955 if evicting {
3977- if let Some(live) = &self.live_load {
3978- live.shed_cells.fetch_add(1, Ordering::Relaxed);
3979- }
3956+ self.live_load.shed_cells.fetch_add(1, Ordering::Relaxed);
39803957 }
39813958 self.published.remove(&cell);
39823959 if let Some(runtime) = self.host.clone() {
3983- // A stop closes a whole database. It fsyncs the directory
3984- // and the file, then unlinks the local copy, and it does
3985- // all of that inside one synchronous call. Poll it on the
3986- // host runtime: this future lives in `out`, which the core
3987- // thread drives in the same select as the timer queue, and
3988- // the core owns the node lease timer. A slow fsync on the
3989- // core thread starves the lease renew and the lease fence,
3990- // and the node then fences itself.
3960+ // The drain keeps the stop off the core and its lease timers.
3961+ // `spawn_detached` only keeps the seeded DST schedule stable.
3962+ // `remove_local` still runs a SQLite close and a rename or unlink
3963+ // synchronously on a host runtime worker. Unlike `close_in_place`,
3964+ // which uses `asyncrt::blocking`, this work is off the core but
3965+ // not isolated from other runtime work.
39913966 let released = cell.clone();
39923967 let deadline_mono_ms = bounded.then(|| {
39933968 crate::asyncrt::mono_ms().saturating_add(self.operation_deadline_ms)
39943969 });
3995- let task = crate::asyncrt::spawn(report_stopped_when_released(
3970+ out.spawn_detached(report_stopped_when_released(
39963971 op,
39973972 cell,
39983973 epoch,
@@ -4005,9 +3980,6 @@
40053980 async move { runtime.stop_cell(&cell, epoch, stop_mode).await }
40063981 },
40073982 ));
4008- out.effects.push(Box::pin(async move {
4009- task.await.expect("stop runtime task panicked")
4010- }));
40113983 } else {
40123984 immediate.push_back(Event::RuntimeStopped { op });
40133985 }
@@ -4034,7 +4006,7 @@
40344006 scheduled_ms,
40354007 } => {
40364008 if let Some(runtime) = self.host.clone() {
4037- out.effects.push(Box::pin(async move {
4009+ out.spawn_scoped(async move {
40384010 // The shell reports the firing raw: the deadline that
40394011 // stands after the handler, whether a wake entry
40404012 // covers it, and the position of the consuming
@@ -4061,7 +4033,7 @@
40614033 now_mono_ms: crate::asyncrt::mono_ms(),
40624034 result,
40634035 })
4064- }));
4036+ });
40654037 } else {
40664038 immediate.push_back(Event::AlarmFinished {
40674039 op,
@@ -4161,18 +4133,22 @@
41614133 fn state_json(&self) -> String {
41624134 // The lease sample reads counts the load tick last stored. Store them
41634135 // now, so the sample below agrees with the state beside it.
4164- let node_load = self.live_load.as_ref().map(|live| {
4165- live.owned_cells
4166- .store(self.state.owned_cells(), Ordering::Relaxed);
4167- live.ownership_confirmed
4168- .store(self.state.ownership_confirmed(), Ordering::Relaxed);
4169- live.resident_cells
4170- .store(self.state.occupied(), Ordering::Relaxed);
4171- live.host_websockets
4172- .store(self.state.host_websockets(), Ordering::Relaxed);
4173- serde_json::to_string(&crate::ownership_store::process_load(live))
4174- .expect("node load serializes")
4175- });
4136+ let live = &self.live_load;
4137+ live.owned_cells
4138+ .store(self.state.owned_cells(), Ordering::Relaxed);
4139+ live.ownership_confirmed
4140+ .store(self.state.ownership_confirmed(), Ordering::Relaxed);
4141+ live.resident_cells
4142+ .store(self.state.occupied(), Ordering::Relaxed);
4143+ live.host_websockets
4144+ .store(self.state.host_websockets(), Ordering::Relaxed);
4145+ // Keep the raw RSS/in-use pair from one stored sample; a gap can reflect
4146+ // allocator retention. The allocator and libc statistics below are read
4147+ // live, so they can describe a later instant.
4148+ let sample = live.sample();
4149+ let load = crate::ownership_store::process_load(live);
4150+ let node_load = matches!(&self.ownership, Ownership::Bucket(_))
4151+ .then(|| serde_json::to_string(&load).expect("node load serializes"));
41764152 let activity = self.state.presence_snapshot().activity;
41774153 let residents = self
41784154 .state
@@ -4187,9 +4163,6 @@
41874163 .map(|cell| format!("{cell:?}"))
41884164 .collect::<Vec<_>>()
41894165 .join(",");
4190- // Both numbers: a gap between them is memory the allocator kept, which
4191- // no eviction returns. One sample, so they cannot disagree.
4192- let memory = crate::memory::sample();
41934166 // `restoring` is a sum, and a node that refuses cells for a quarter of
41944167 // an hour needs its parts. `activating` holds a permit and is doing
41954168 // work; `activation_waiting` is queued behind the activation ceiling;
@@ -4225,18 +4198,18 @@
42254198 self.state
42264199 .shed_reason()
42274200 .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")),
4228- memory.rss_bytes,
4229- memory.in_use_bytes,
4230- // The allocator's split of the two numbers above. `None`
4231- // serializes as null, so a failed read leaves the rest intact.
4201+ sample.rss_bytes,
4202+ sample.in_use_bytes,
4203+ // Read allocator details live. `None` serializes as null, so a
4204+ // failed read leaves the rest intact.
42324205 serde_json::to_string(&crate::memory::allocator_stats())
42334206 .unwrap_or_else(|_| "null".to_string()),
42344207 serde_json::to_string(&crate::memory::libc_malloc_stats())
42354208 .unwrap_or_else(|_| "null".to_string()),
4236- memory
4209+ sample
42374210 .cgroup_working_set_bytes
42384211 .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()),
4239- memory
4212+ sample
42404213 .cgroup_current_bytes
42414214 .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()),
42424215 node_load.unwrap_or_else(|| "null".to_string()),
addedcrates/celld/actor/effects.rs+257−0View file
@@ -1,0 +1,257 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Effect dispatch keeps ordinary work off the core's lease timer thread.
4+
5+use super::{CompletedEffect, EffectFuture, Ownership, TimerArm, TimerSlots};
6+use crate::ownership_store::now_ms;
7+use celld_logic::{CasGuard, Event, Failure, LeaseCasOutcome, NodeLeaseRecord, OpId};
8+use futures_util::stream::FuturesUnordered;
9+use std::future::Future;
10+use tokio_util::time::{delay_queue, DelayQueue};
11+
12+enum EffectJob {
13+ Spawn(EffectFuture),
14+ // Lease authority must progress even when the host workers are occupied.
15+ Lease(EffectFuture),
16+}
17+
18+#[cfg(celld_internal_tests)]
19+impl EffectJob {
20+ fn into_future(self) -> EffectFuture {
21+ match self {
22+ Self::Spawn(future) | Self::Lease(future) => future,
23+ }
24+ }
25+}
26+
27+pub(crate) enum LeaseRequest {
28+ ReadSelf {
29+ op: OpId,
30+ node: String,
31+ },
32+ Cas {
33+ op: OpId,
34+ guard: CasGuard,
35+ record: NodeLeaseRecord,
36+ authority_expires_ms: Option<u64>,
37+ },
38+}
39+
40+/// Futures and timer arms emitted by one Actor transition.
41+#[derive(Default)]
42+pub struct StepOutput {
43+ effects: Vec<EffectJob>,
44+ pub timers: Vec<TimerArm>,
45+}
46+
47+impl StepOutput {
48+ /// Queue ordinary effect work. In production the drain spawns it on the host
49+ /// runtime immediately after the Actor step, so it runs to completion and
50+ /// the core polls only its join handle.
51+ ///
52+ /// The difference from `spawn_detached` is only visible when a deterministic
53+ /// driver takes the queue: dropping an unpolled future discards this work
54+ /// before it starts.
55+ pub(crate) fn spawn_scoped(
56+ &mut self,
57+ future: impl Future<Output = CompletedEffect> + Send + 'static,
58+ ) {
59+ self.effects.push(EffectJob::Spawn(Box::pin(future)));
60+ }
61+
62+ /// Production behavior is identical to `spawn_scoped`: the work runs to
63+ /// completion on the host runtime and the core polls only a join handle.
64+ ///
65+ /// This method exists because deterministic worlds drop queued futures and
66+ /// name these tasks by their `actor.rs` spawn site. Starting the work at the
67+ /// call keeps seeded stop, restore, and durability regressions on their
68+ /// existing schedules.
69+ ///
70+ /// `#[track_caller]` is load-bearing: the simulated spawn records the caller
71+ /// location as the task's spawn site.
72+ #[track_caller]
73+ pub(crate) fn spawn_detached(
74+ &mut self,
75+ future: impl Future<Output = CompletedEffect> + Send + 'static,
76+ ) {
77+ let task = crate::asyncrt::spawn(future);
78+ self.spawn_scoped(async move { task.await.expect("actor effect task panicked") });
79+ }
80+
81+ pub(crate) fn lease(&mut self, request: LeaseRequest, ownership: &Ownership) {
82+ let ownership = ownership.clone();
83+ let future: EffectFuture = match request {
84+ LeaseRequest::ReadSelf { op, node } => Box::pin(async move {
85+ let result = ownership.read_self_node_lease(&node).await;
86+ CompletedEffect::plain(Event::SelfNodeLeaseRead {
87+ op,
88+ now_ms: now_ms(),
89+ now_mono_ms: crate::asyncrt::mono_ms(),
90+ result,
91+ })
92+ }),
93+ LeaseRequest::Cas {
94+ op,
95+ guard,
96+ record,
97+ authority_expires_ms,
98+ } => Box::pin(async move {
99+ let attempt_started_mono_ms = crate::asyncrt::mono_ms();
100+ let node = record.node.clone();
101+ let candidate_expires_ms = record.expires_ms;
102+ // Logged before the CAS: with only the completion line, a
103+ // renewal hung on a storage tail is indistinguishable from
104+ // a timer that never fired (the n6 fence, 2026-08-11).
105+ tracing::info!(
106+ event = "node_lease_attempt_started",
107+ %node,
108+ attempt = if authority_expires_ms.is_some() {
109+ "renew"
110+ } else {
111+ "acquire"
112+ },
113+ prior_authority_headroom_ms = authority_expires_ms
114+ .map(|expires_ms| expires_ms.saturating_sub(now_ms()))
115+ .unwrap_or(0),
116+ "node lease attempt started"
117+ );
118+ // A renewal must return while proven authority remains,
119+ // because only a returned attempt lets the ambiguity
120+ // read-back run before the watchdog. The 10:15Z R2
121+ // brownout fenced 9 nodes whose sole hung attempt was
122+ // still inside the transport's 15 s timeout when the
123+ // 10 s TTL expired. Bound the attempt to half the
124+ // remaining authority (capped, floored) and map timeout
125+ // to Ambiguous — the same conservative outcome a lost
126+ // response already produces, so safety is unchanged.
127+ // The stamp survives a timed-out attempt: the backend
128+ // writes it through the out-parameter synchronously at
129+ // serialization, before the transport await, so even a
130+ // dropped future has reported what the possibly-landed
131+ // body carried.
132+ let mut stamped_log_state = None;
133+ let result = match authority_expires_ms {
134+ Some(expires_ms) => {
135+ let remaining = expires_ms.saturating_sub(now_ms());
136+ let bound =
137+ std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500));
138+ match crate::asyncrt::timeout(
139+ bound,
140+ ownership.cas_node_lease(guard, record, &mut stamped_log_state),
141+ )
142+ .await
143+ {
144+ Ok(result) => result,
145+ Err(_) => Err(Failure::Ambiguous),
146+ }
147+ }
148+ None => {
149+ ownership
150+ .cas_node_lease(guard, record, &mut stamped_log_state)
151+ .await
152+ }
153+ };
154+ let completed_ms = now_ms();
155+ let elapsed_ms = crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms);
156+ let prior_authority_headroom_ms = authority_expires_ms
157+ .map(|expires_ms| expires_ms.saturating_sub(completed_ms))
158+ .unwrap_or(0);
159+ let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms);
160+ let attempt = if authority_expires_ms.is_some() {
161+ "renew"
162+ } else {
163+ "acquire"
164+ };
165+ let outcome = match &result {
166+ Ok(LeaseCasOutcome::Applied { .. }) => "applied",
167+ Ok(LeaseCasOutcome::Rejected) => "rejected",
168+ Err(Failure::Ambiguous) => "ambiguous",
169+ Err(Failure::Definite) => "definite_failure",
170+ };
171+ if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) {
172+ tracing::info!(
173+ event = "node_lease_attempt",
174+ %node,
175+ attempt,
176+ outcome,
177+ elapsed_ms,
178+ prior_authority_headroom_ms,
179+ candidate_headroom_ms,
180+ "node lease attempt completed"
181+ );
182+ } else {
183+ tracing::warn!(
184+ event = "node_lease_attempt",
185+ %node,
186+ attempt,
187+ outcome,
188+ elapsed_ms,
189+ prior_authority_headroom_ms,
190+ candidate_headroom_ms,
191+ "node lease attempt did not apply"
192+ );
193+ }
194+ CompletedEffect::plain(Event::NodeLeaseCasCompleted {
195+ op,
196+ now_mono_ms: crate::asyncrt::mono_ms(),
197+ result,
198+ stamped_log_state,
199+ })
200+ }),
201+ };
202+ self.effects.push(EffectJob::Lease(future));
203+ }
204+
205+ // Binary test harnesses compile the library without cfg(test).
206+ // celld_internal_tests is never set in a shipped build.
207+ #[cfg(celld_internal_tests)]
208+ pub fn take_effects(&mut self) -> Vec<EffectFuture> {
209+ self.effects.drain(..).map(EffectJob::into_future).collect()
210+ }
211+
212+ #[cfg(celld_internal_tests)]
213+ pub fn effects_is_empty(&self) -> bool {
214+ self.effects.is_empty()
215+ }
216+
217+ // A driver that runs only the newest effect must retain every older job.
218+ #[cfg(celld_internal_tests)]
219+ pub fn pop_effect(&mut self) -> Option<EffectFuture> {
220+ self.effects.pop().map(EffectJob::into_future)
221+ }
222+
223+ #[cfg(celld_internal_tests)]
224+ pub fn effects_len(&self) -> usize {
225+ self.effects.len()
226+ }
227+}
228+
229+pub(crate) fn drain_step_output(
230+ out: &mut StepOutput,
231+ effects: &mut FuturesUnordered<EffectFuture>,
232+ delays: &mut DelayQueue<TimerArm>,
233+ timers: &mut TimerSlots<delay_queue::Key>,
234+) {
235+ for job in out.effects.drain(..) {
236+ match job {
237+ EffectJob::Spawn(future) => {
238+ // Spawn only at the production drain so deterministic drivers
239+ // can take the futures and retain their existing schedule.
240+ let task = crate::asyncrt::spawn(future);
241+ effects.push(Box::pin(async move {
242+ task.await.expect("actor effect task panicked")
243+ }));
244+ }
245+ EffectJob::Lease(future) => effects.push(future),
246+ }
247+ }
248+ for arm in out.timers.drain(..) {
249+ let delay = std::time::Duration::from_millis(
250+ arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()),
251+ );
252+ let key = delays.insert(arm.clone(), delay);
253+ if let Some(displaced) = timers.install(&arm, key) {
254+ delays.remove(&displaced);
255+ }
256+ }
257+}
modifiedcrates/celld/assets.rs+13−4View file
@@ -1309,7 +1309,18 @@
13091309 Ok(())
13101310 }
13111311
1312+/// Report the same size-policy mismatch in the builder, managed agent, and serving node.
1313+pub(crate) fn validate_asset_file_size(path: &str, bytes: u64, limit: u64) -> anyhow::Result<()> {
1314+ if bytes > limit {
1315+ return Err(anyhow!(
1316+ "asset {path:?} size ({bytes} bytes) exceeds CELLD_MAX_ASSET_FILE_BYTES ({limit} bytes)"
1317+ ));
1318+ }
1319+ Ok(())
1320+}
1321+
13121322 fn validate_index(index: &AssetIndex, reference: &AssetManifestRef) -> anyhow::Result<()> {
1323+ let max_file_bytes = crate::env_vars::max_asset_file_bytes()?;
13131324 if index.schema_version != 1 {
13141325 return Err(anyhow!(
13151326 "unsupported asset index schema: {}",
@@ -1374,13 +1385,11 @@
13741385 }
13751386 let mut total = 0_u64;
13761387 for (path, entry) in &index.entries {
1377- if !is_canonical_asset_path(path)
1378- || path == "/"
1379- || asset_blob_key(&entry.sha256).is_none()
1380- || entry.bytes > 25 * 1024 * 1024
1388+ if !is_canonical_asset_path(path) || path == "/" || asset_blob_key(&entry.sha256).is_none()
13811389 {
13821390 return Err(anyhow!("invalid asset index entry: {path:?}"));
13831391 }
1392+ validate_asset_file_size(path, entry.bytes, max_file_bytes)?;
13841393 if entry
13851394 .content_type
13861395 .as_deref()
modifiedcrates/celld/asyncrt.rs+12−3View file
@@ -58,8 +58,13 @@
5858 }
5959 }
6060
61+// No lazy initialization: a first call from a thread whose current runtime is
62+// not the shared one, such as the core's, would bind every later spawn to that
63+// runtime and silently put effect work back on the lease timer thread.
6164 fn current_domain() -> &'static ProductionDomain {
62- PROCESS_DOMAIN.get_or_init(|| ProductionDomain::new(tokio::runtime::Handle::current()))
65+ PROCESS_DOMAIN
66+ .get()
67+ .expect("asyncrt::set_host_handle must run before the first spawn or domain access")
6368 }
6469
6570 struct ProductionDomainOwner {
@@ -181,9 +186,13 @@
181186 }
182187 }
183188
184-/// Install the process runtime handle.
189+/// Install the process runtime handle, exactly once. A second call would
190+/// otherwise be ignored and leave the first runtime in place.
185191 pub fn set_host_handle(handle: tokio::runtime::Handle) {
186- let _ = PROCESS_DOMAIN.set(ProductionDomain::new(handle));
192+ assert!(
193+ PROCESS_DOMAIN.set(ProductionDomain::new(handle)).is_ok(),
194+ "asyncrt::set_host_handle must run exactly once"
195+ );
187196 }
188197
189198 /// Return the Tokio handle for the V8 arm.
modifiedcrates/celld/cell_cli.rs+270−3View file
@@ -87,6 +87,12 @@
8787 pub(crate) fn list_options_from_arguments(
8888 arguments: Vec<String>,
8989 ) -> anyhow::Result<Option<ListOptions>> {
90+ parse_listing(arguments, "list")
91+}
92+
93+/// The listing flags shared by `celld cell list` and `celld cell gc`;
94+/// `command` names the subcommand in an error.
95+fn parse_listing(arguments: Vec<String>, command: &str) -> anyhow::Result<Option<ListOptions>> {
9096 let mut options = ListOptions::default();
9197 let mut arguments = arguments.into_iter();
9298 while let Some(argument) = arguments.next() {
@@ -111,11 +117,11 @@
111117 // mistyped option rather than a class named "--clas".
112118 if other.starts_with('-') {
113119 bail!(
114- "unknown cell list option: {other}; run `celld cell list --help` for usage"
120+ "unknown cell {command} option: {other}; run `celld cell {command} --help` for usage"
115121 );
116122 }
117123 if let Some(existing) = options.class.as_deref() {
118- bail!("celld cell list takes one class, and already has {existing:?}");
124+ bail!("celld cell {command} takes one class, and already has {existing:?}");
119125 }
120126 options.class = Some(other.to_string());
121127 }
@@ -142,6 +148,8 @@
142148 USAGE:
143149 celld cell list [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
144150
151+Run `celld cell gc --help` for the report of superseded epochs.
152+
145153 The listing is bounded by default, because a fleet can hold far more cells
146154 than an operator wants to read and each request returns at most {page}
147155 children. A bounded answer reports on stderr that more cells exist.
@@ -186,10 +194,11 @@
186194 let mut arguments = arguments.into_iter();
187195 match arguments.next().as_deref() {
188196 Some("list") => run_list(arguments.collect()).await,
197+ Some("gc") => run_gc(arguments.collect()).await,
189198 None | Some("-h") | Some("--help") | Some("help") => {
190199 Output::new(Format::Text).help(&help_text())
191200 }
192- Some(other) => bail!("unknown cell command: {other}; celld cell list is the only one"),
201+ Some(other) => bail!("unknown cell command: {other}; use celld cell list or celld cell gc"),
193202 }
194203 }
195204
@@ -257,3 +266,261 @@
257266 }
258267 Ok(())
259268 }
269+
270+/// One cell's epoch prefixes that the owner's epoch GC would delete. A row
271+/// is a whole cell, so `--after` resumes at a cell boundary and never skips
272+/// the rest of a cell's epochs.
273+struct CellEpochs {
274+ scope: String,
275+ epochs: Vec<u64>,
276+ base: u64,
277+ bytes: u64,
278+}
279+
280+impl Record for CellEpochs {
281+ fn json(&self) -> serde_json::Value {
282+ serde_json::json!({
283+ "scope": self.scope,
284+ "epochs": self.epochs,
285+ "base": self.base,
286+ "bytes": self.bytes,
287+ })
288+ }
289+
290+ fn text(&self) -> Cow<'_, str> {
291+ let epochs: Vec<String> = self.epochs.iter().map(|e| format!("e{e}")).collect();
292+ Cow::Owned(format!(
293+ "{} {} {} bytes (below base e{})",
294+ self.scope,
295+ epochs.join(" "),
296+ self.bytes,
297+ self.base
298+ ))
299+ }
300+}
301+
302+impl Resumable for CellEpochs {
303+ fn cursor(&self) -> &str {
304+ &self.scope
305+ }
306+}
307+
308+#[derive(Debug, PartialEq, Eq)]
309+pub(crate) struct GcOptions {
310+ pub(crate) list: ListOptions,
311+ pub(crate) grace_secs: u64,
312+}
313+
314+/// The dry run's grace when the operator passes no `--grace-secs`. The
315+/// owner has no default: epoch GC is off until `CELLD_LTX_RETENTION_SECS`
316+/// sets one.
317+const DEFAULT_GC_GRACE_SECS: u64 = 3600;
318+
319+pub(crate) fn gc_options_from_arguments(
320+ arguments: Vec<String>,
321+) -> anyhow::Result<Option<GcOptions>> {
322+ let mut dry_run = false;
323+ let mut grace_secs = DEFAULT_GC_GRACE_SECS;
324+ let mut rest = Vec::new();
325+ let mut arguments = arguments.into_iter();
326+ while let Some(argument) = arguments.next() {
327+ match argument.as_str() {
328+ "-h" | "--help" => return Ok(None),
329+ "--dry-run" => dry_run = true,
330+ "--grace-secs" => {
331+ let value = arguments
332+ .next()
333+ .ok_or_else(|| anyhow::anyhow!("--grace-secs requires a value"))?;
334+ grace_secs = value
335+ .parse()
336+ .with_context(|| format!("--grace-secs takes seconds, not {value:?}"))?;
337+ }
338+ _ => rest.push(argument),
339+ }
340+ }
341+ // Deletion without an owner has no fence: the owner deletes under the
342+ // order that makes a late delete safe, and a separate process cannot
343+ // follow it. Report only.
344+ if !dry_run {
345+ bail!(
346+ "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 \
348+ let them"
349+ );
350+ }
351+ let Some(list) = parse_listing(rest, "gc")? else {
352+ return Ok(None);
353+ };
354+ Ok(Some(GcOptions { list, grace_secs }))
355+}
356+
357+pub(crate) fn gc_help_text() -> String {
358+ format!(
359+ r#"Report the superseded LTX epochs that epoch GC can delete.
360+
361+USAGE:
362+ celld cell gc --dry-run [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
363+
364+For each cell, the report builds the restore chain the way a restore does
365+and prints the candidates: the epochs below the chain's base, except the
366+newest epoch, the epoch before it, and each epoch whose newest object is
367+younger than the grace. This command reads the bucket and writes nothing.
368+
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.
375+
376+OPTIONS:
377+ --dry-run Required; report without deleting
378+ --grace-secs N Grace in seconds (default: {DEFAULT_GC_GRACE_SECS})
379+{FLEET_HELP}
380+{LISTING_HELP}
381+ -h, --help Show this help"#
382+ )
383+}
384+
385+async fn run_gc(arguments: Vec<String>) -> anyhow::Result<()> {
386+ let Some(options) = gc_options_from_arguments(arguments)? else {
387+ return Output::new(Format::Text).help(&gc_help_text());
388+ };
389+ let storage = options.list.fleet.resolve("celld cell gc")?;
390+ let store = storage.open().await?;
391+ let mut out = Output::new(if options.list.json {
392+ Format::Json
393+ } else {
394+ Format::Text
395+ });
396+ let started = std::time::Instant::now();
397+ let now_ms = u64::try_from(
398+ std::time::SystemTime::now()
399+ .duration_since(std::time::UNIX_EPOCH)
400+ .unwrap_or_default()
401+ .as_millis(),
402+ )
403+ .unwrap_or(u64::MAX);
404+ let grace_ms = options.grace_secs.saturating_mul(1000);
405+ let class = options.list.class.clone();
406+ let prefix = class
407+ .as_deref()
408+ .map_or_else(|| "cells/".to_string(), |class| format!("cells/{class}:"));
409+
410+ let skipped = std::sync::atomic::AtomicUsize::new(0);
411+ let listed = list(&mut out, &options.list.bounds, |resume, want| {
412+ let store = &store;
413+ let skipped = &skipped;
414+ let class = class.clone();
415+ let prefix = prefix.clone();
416+ let boundary = resume.boundary().map(str::to_string);
417+ let start_after = boundary.as_deref().map(|scope| format!("cells/{scope}"));
418+ let token = match resume {
419+ Resume::Token(token) => Some(token),
420+ Resume::From(_) => None,
421+ };
422+ async move {
423+ let page = store
424+ .common_prefixes_page(&prefix, start_after.as_deref(), token, want)
425+ .await
426+ .context("enumerate Durable Object instances")?;
427+ let mut rows = Vec::new();
428+ for scope in
429+ cell_scopes_from_prefixes(page.prefixes, class.as_deref(), boundary.as_deref())
430+ {
431+ // One unreadable cell must not hide the report for the rest,
432+ // and a report with skipped cells must not read as clean.
433+ match cell_epochs(store, &scope, now_ms, grace_ms).await {
434+ Ok(row) => rows.extend(row),
435+ Err(error) => {
436+ skipped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
437+ note!("skipped {scope}: {error:#}");
438+ }
439+ }
440+ }
441+ Ok(Page {
442+ rows,
443+ next: page.page_token,
444+ })
445+ }
446+ })
447+ .await?;
448+
449+ out.finish()?;
450+ let skipped = skipped.into_inner();
451+ if listed.printed == 0 && !listed.abandoned && skipped == 0 {
452+ note!("no superseded epochs to delete");
453+ } else if options.list.bounds.all {
454+ listed.report_all("cell", started.elapsed());
455+ } else {
456+ // A bounded run with a skipped cell still prints where to resume.
457+ listed.report("cell", "--after");
458+ }
459+ if skipped > 0 {
460+ bail!("celld cell gc could not read {skipped} cell(s); the report is incomplete");
461+ }
462+ Ok(())
463+}
464+
465+/// The epochs of one cell that the owner of its newest epoch would delete.
466+async fn cell_epochs(
467+ store: &crate::bucket::Bucket,
468+ scope: &str,
469+ now_ms: u64,
470+ grace_ms: u64,
471+) -> anyhow::Result<Option<CellEpochs>> {
472+ let client_for = |epoch: u64| {
473+ celld_ltx::ObjectStoreClient::with_store(
474+ celld_ltx::client::object_store::ObjectStoreConfig {
475+ bucket: store.name.clone(),
476+ path: format!("{}cells/{scope}/ltx/e{epoch}", store.prefix),
477+ ..Default::default()
478+ },
479+ store.store.clone(),
480+ )
481+ };
482+ let Some(scan) = crate::ltx_repl::scan_epochs(
483+ store.store.as_ref(),
484+ &store.prefix,
485+ scope,
486+ usize::MAX,
487+ client_for,
488+ )
489+ .await
490+ .with_context(|| format!("scan the epochs of {scope}"))?
491+ else {
492+ return Ok(None);
493+ };
494+ let below: Vec<_> = scan.below.iter().map(|b| b.listed).collect();
495+ // The owner refuses to plan under a mark above its base, so the report
496+ // reads the same mark.
497+ let recorded = crate::ltx_repl::read_retired_mark(store.store.as_ref(), &store.prefix, scope)
498+ .await
499+ .with_context(|| format!("read the retired mark of {scope}"))?;
500+ let Some(plan) = celld_logic::epoch_gc::plan(
501+ scan.newest,
502+ &scan.chain,
503+ &below,
504+ recorded,
505+ false,
506+ now_ms,
507+ grace_ms,
508+ ) else {
509+ return Ok(None);
510+ };
511+ if plan.delete.is_empty() {
512+ return Ok(None);
513+ }
514+ let bytes = scan
515+ .below
516+ .iter()
517+ .filter(|b| plan.delete.contains(&b.listed.epoch))
518+ .map(|b| b.bytes)
519+ .sum();
520+ Ok(Some(CellEpochs {
521+ scope: scope.to_string(),
522+ epochs: plan.delete,
523+ base: plan.retired_below,
524+ bytes,
525+ }))
526+}
addedcrates/celld/cell_dispatch.rs+379−0View file
@@ -1,0 +1,379 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Routed local execution and the durability gate for outgoing effects.
4+use crate::actor::{ActivityGuard, AppHandle, LocalRequestFailure, Routed};
5+use crate::engine_api::{
6+ HttpResponse, HttpResponseWebSocket, RequestBody, RequestId, RuntimeFetch,
7+};
8+use crate::http_streams::RequestBodyGuard;
9+use crate::js::{CallOrder, DoCallReq};
10+use crate::telemetry::TraceContext;
11+use anyhow::Context as _;
12+use celld_logic::{Epoch, NodeId, RequestError, Route, WebSocketKind};
13+use futures_util::StreamExt as _;
14+use tokio::sync::oneshot;
15+
16+#[derive(Debug)]
17+pub struct RoutedRequestError(pub RequestError);
18+
19+/// The gate's verdict as the answer's error, with the handler's own failure
20+/// kept below it when the answer was one: the client needs the verdict, and
21+/// the operator reading the chain needs what the handler said too. The
22+/// verdict stays on top, so the routed-error match still finds it.
23+pub fn local_request_error(failure: LocalRequestFailure) -> anyhow::Error {
24+ match failure {
25+ LocalRequestFailure::Handler(error) => error,
26+ LocalRequestFailure::OutputGate { verdict, handler } => match handler {
27+ Some(handler) => handler.context(RoutedRequestError(verdict)),
28+ None => anyhow::Error::new(RoutedRequestError(verdict)),
29+ },
30+ }
31+}
32+
33+impl std::fmt::Display for RoutedRequestError {
34+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35+ write!(formatter, "route failed: {:?}", self.0)
36+ }
37+}
38+
39+impl std::error::Error for RoutedRequestError {}
40+
41+/// The output gate for an effect raised inside a handler, as opposed to the
42+/// handler's own response.
43+///
44+/// 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.
48+pub async fn dispatch_gate(app: AppHandle, req: crate::js::GateReq) {
49+ let routed = match app.request(req.scope.clone()).await {
50+ Ok(routed) => routed,
51+ Err(error) => {
52+ let _ = req.reply.send(Err(error));
53+ return;
54+ }
55+ };
56+ // The guard pins the cell and releases the request on drop, so the else
57+ // branch does not leak the just-acquired request.
58+ let _activity = app.activity(routed.request, req.scope.clone());
59+ let result = if routed.route == Route::Local {
60+ app.gate_output(routed.request, req.ticket).await
61+ } else {
62+ // The owning isolate should route the cell locally; if it moved off the
63+ // node mid-call, fail closed rather than acknowledge an unproven write.
64+ Err(RequestError::NodeFenced)
65+ };
66+ let _ = req.reply.send(result);
67+}
68+
69+pub fn local_dispatch_request_id(
70+ request_id: Option<crate::js::RequestId>,
71+) -> Option<crate::js::RequestId> {
72+ // Internal Queue, cron, alarm, and peer calls have no client request ID,
73+ // but a local handler still needs an identity in the abort registry. The
74+ // drain cancels by core request and resolves that identity through the
75+ // activity pin; leaving it absent makes a busy internal handler impossible
76+ // to stop before the process deadline.
77+ Some(request_id.unwrap_or_else(crate::js::next_request_id))
78+}
79+
80+/// The part of a fetch-style call that a dispatch attempt consumes.
81+///
82+/// A local attempt moves it into the handler's `RuntimeFetch`; a remote route
83+/// hands it back inside [`CallAttempt::Remote`], so the peer forwarder in the
84+/// binary receives the route and the body together and cannot lose the body
85+/// between two attempts.
86+pub struct CallPayload {
87+ pub name: Option<String>,
88+ pub url: String,
89+ pub method: String,
90+ pub body: RequestBody,
91+ pub headers: Vec<(String, String)>,
92+}
93+
94+/// The state of a fetch-style call that outlives one dispatch attempt.
95+///
96+/// A retry after a stale remote route re-enters routing with the same client
97+/// identity, the same cancellation signal, and the same streamed-body claim.
98+/// `order` is different: only a local attempt takes it, and a local attempt
99+/// always ends the call. A remote attempt leaves it in place, so the peer path
100+/// holds this call's place in its caller's order until the call ends.
101+pub struct CallContext {
102+ pub scope: String,
103+ pub request_id: Option<RequestId>,
104+ pub parent: Option<TraceContext>,
105+ pub deliver_abort_to_handler: bool,
106+ pub cancel: Option<oneshot::Receiver<()>>,
107+ pub order: Option<CallOrder>,
108+ /// Reclaims a streamed body abandoned by an early error. A local target or
109+ /// the peer HTTP body takes ownership before this guard is disarmed.
110+ pub body_guard: RequestBodyGuard,
111+}
112+
113+/// Split a proxied call into its cross-attempt context, its consumable
114+/// payload, and its reply channel.
115+///
116+/// The binary and the simulated dispatcher both start from a `DoCallReq`, and
117+/// one mapping keeps the two from assigning a field differently.
118+pub fn split_do_call(
119+ call: DoCallReq,
120+) -> (
121+ CallContext,
122+ CallPayload,
123+ oneshot::Sender<anyhow::Result<HttpResponse>>,
124+) {
125+ let DoCallReq {
126+ request_id,
127+ cancel,
128+ deliver_abort_to_handler,
129+ scope,
130+ name,
131+ url,
132+ method,
133+ body,
134+ body_guard,
135+ headers,
136+ reply,
137+ order,
138+ parent,
139+ } = call;
140+ (
141+ CallContext {
142+ scope,
143+ request_id,
144+ parent,
145+ deliver_abort_to_handler,
146+ cancel,
147+ order,
148+ body_guard,
149+ },
150+ CallPayload {
151+ name,
152+ url,
153+ method,
154+ body,
155+ headers,
156+ },
157+ reply,
158+ )
159+}
160+
161+/// The outcome of one dispatch attempt.
162+///
163+/// The binary logs WebSocket route timing, and it treats the three terminal
164+/// outcomes differently: nothing for a call that never reached routing, a
165+/// `route_error` record for a refused route, and an `ok`/`error` record with
166+/// the dispatch time for a local dispatch. A single `Completed(Result)` variant
167+/// would erase that distinction, and a `RoutedRequestError` downcast cannot
168+/// recover it, because `local_request_error` also puts a `RoutedRequestError`
169+/// on top of an output-gate failure. The outcome class therefore crosses this
170+/// boundary explicitly, while the error values themselves are built here so
171+/// the client-facing messages live in one place.
172+pub enum CallAttempt {
173+ /// The attempt ended before routing completed: the scope is malformed, or
174+ /// the cancellation tied route resolution. No handler ran and no core
175+ /// request survived, so the binary emits no timing record.
176+ Unstarted(anyhow::Error),
177+ /// `AppHandle::request` refused the route, in the Actor shell or in the
178+ /// decision core. No handler ran.
179+ RouteError(anyhow::Error),
180+ /// The route was local, and the local dispatch result is the call's
181+ /// result. A missing runtime or a refused admission can end it before
182+ /// the handler starts.
183+ Local(anyhow::Result<HttpResponse>),
184+ /// The route left this node. The payload comes back unconsumed for the
185+ /// peer forwarder.
186+ Remote {
187+ node: NodeId,
188+ addr: String,
189+ epoch: Epoch,
190+ peer_protocol: u16,
191+ payload: CallPayload,
192+ },
193+}
194+
195+/// Perform one dispatch attempt of a fetch-style call, up to and including
196+/// local execution.
197+///
198+/// The binary's `dispatch_do_call` loop and the simulated dispatcher both call
199+/// this function, so routing, the cancellation tie, and the local execution
200+/// branch exist once. The peer transport stays in the binary because it owns
201+/// the HTTP client and the stale-route retry policy.
202+///
203+/// `on_routed` runs once, when the core resolved a route and before the local
204+/// handler starts or the remote route returns. The binary times route
205+/// resolution separately from dispatch, and this point is the only place that
206+/// separates the two. The library cannot take the stamp itself: `Instant::now`
207+/// is outside the execution boundary, and `asyncrt::mono_ms` is
208+/// millisecond-grained while the record is in microseconds.
209+pub async fn dispatch_call_attempt(
210+ app: &AppHandle,
211+ call: &mut CallContext,
212+ payload: CallPayload,
213+ on_routed: impl FnOnce(),
214+) -> CallAttempt {
215+ // The check is pure and cheap, so repeating it on a retry costs nothing,
216+ // and placing it inside the attempt puts every dispatcher behind the same
217+ // guard instead of asking each one to remember a separate call.
218+ if !celld_logic::cell::valid_cell_scope(&call.scope) {
219+ return CallAttempt::Unstarted(anyhow::anyhow!(
220+ "cell scope is malformed or exceeds the fleet storage limit"
221+ ));
222+ }
223+ // A disconnect before routing completes has executed no handler, so
224+ // cancel the core request and release its activation admission. Once
225+ // routing completes, the same signal moves into the local or remote
226+ // dispatch and aborts work that did start.
227+ let route = app.request(call.scope.clone());
228+ let routed = if call.deliver_abort_to_handler {
229+ // Workerd delivers an explicit JavaScript AbortSignal to the target
230+ // request. Resolve the route first, then give the already-fired
231+ // receiver to fetch_cell so the handler sees request.signal and its
232+ // waitUntil work can continue.
233+ route.await
234+ } else {
235+ match call.cancel.as_mut() {
236+ Some(cancel) => crate::asyncrt::select_biased! {
237+ "a cancellation that ties route resolution prevents dispatch from starting";
238+ _ = cancel => return CallAttempt::Unstarted(anyhow::anyhow!("Durable Object call cancelled")),
239+ routed = route => routed,
240+ },
241+ None => route.await,
242+ }
243+ };
244+ let Routed { request, route } = match routed {
245+ Ok(routed) => routed,
246+ Err(error) => {
247+ return CallAttempt::RouteError(anyhow::Error::new(RoutedRequestError(error)));
248+ }
249+ };
250+ on_routed();
251+ match route {
252+ Route::Local => {
253+ let CallPayload {
254+ name,
255+ url,
256+ method,
257+ body,
258+ headers,
259+ } = 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,
279+ )
280+ }
281+ Route::Remote {
282+ node,
283+ addr,
284+ epoch,
285+ peer_protocol,
286+ } => CallAttempt::Remote {
287+ node,
288+ addr,
289+ epoch,
290+ peer_protocol,
291+ payload,
292+ },
293+ }
294+}
295+
296+/// Execute an admitted local call and retain its activity through the response.
297+async fn dispatch_local_fetch(
298+ app: &AppHandle,
299+ request: u64,
300+ scope: String,
301+ name: Option<String>,
302+ mut fetch: RuntimeFetch,
303+ cancel: Option<tokio::sync::oneshot::Receiver<()>>,
304+ body_guard: &mut RequestBodyGuard,
305+) -> anyhow::Result<HttpResponse> {
306+ let local_request_id = local_dispatch_request_id(fetch.request_id);
307+ fetch.request_id = local_request_id;
308+ let local = app.local_request(request, scope.clone(), local_request_id, "local");
309+ let completed = local
310+ .run(async {
311+ let host = app.execution_host().context("no cell runtime")?;
312+ let response = host.fetch_cell(scope.clone(), name, fetch, cancel).await?;
313+ // `fetch_cell` cannot return a response until the cell
314+ // has installed its request context. That context now
315+ // owns an unread tail through its waitUntil work.
316+ body_guard.disarm();
317+ if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket {
318+ let kind = if crate::js::ws_hibernatable(target.id).unwrap_or(false) {
319+ WebSocketKind::Hibernatable
320+ } else {
321+ WebSocketKind::Regular
322+ };
323+ app.websocket_opened(target.scope.clone(), target.id, kind)
324+ .await?;
325+ }
326+ Ok(response)
327+ })
328+ .await;
329+ let activity = completed.activity;
330+ let result = completed.result.map_err(local_request_error);
331+ match result {
332+ Ok(mut response) => {
333+ let body_active = response.stream.is_some();
334+ activity.set_phase("response_body", true, body_active);
335+ if let Some(stream) = response.stream.take() {
336+ response.stream = Some(local_response_stream(stream, activity, || {}));
337+ } else {
338+ drop(activity);
339+ }
340+ Ok(response)
341+ }
342+ Err(error) => Err(error),
343+ }
344+}
345+
346+// The body owns the activity until EOF, cancellation, or drop. A forwarded
347+// body also owns its peer-abort guard: disarm it at EOF, but retain it on a
348+// dropped body so the owner cancels work for the disconnected peer.
349+pub fn local_response_stream(
350+ stream: crate::js::HttpChunkStream,
351+ activity: ActivityGuard,
352+ on_finish: impl FnOnce() + Send + 'static,
353+) -> crate::js::HttpChunkStream {
354+ let cancellation = activity.cancellation();
355+ Box::pin(futures_util::stream::unfold(
356+ (stream, activity, on_finish, cancellation),
357+ |(mut stream, activity, on_finish, mut cancellation)| async move {
358+ let chunk = if *cancellation.borrow() {
359+ None
360+ } else {
361+ crate::asyncrt::select! {
362+ chunk = stream.next() => chunk,
363+ changed = cancellation.changed() => {
364+ let _ = changed;
365+ None
366+ }
367+ }
368+ };
369+ match chunk {
370+ Some(chunk) => Some((chunk, (stream, activity, on_finish, cancellation))),
371+ None => {
372+ on_finish();
373+ drop(activity);
374+ None
375+ }
376+ }
377+ },
378+ ))
379+}
modifiedcrates/celld/cell_host.rs+18−0View file
@@ -22,6 +22,24 @@
2222 }
2323
2424 impl CellHost {
25+ pub(crate) async fn fetch_cell(
26+ &self,
27+ cell: String,
28+ name: Option<String>,
29+ request: crate::engine_api::RuntimeFetch,
30+ cancel: Option<tokio::sync::oneshot::Receiver<()>>,
31+ ) -> anyhow::Result<crate::engine_api::HttpResponse> {
32+ match self {
33+ Self::Engine(runtime) => runtime.fetch_cell(cell, name, request, cancel).await,
34+ #[cfg(all(test, celld_internal_tests))]
35+ Self::Scripted(runtime) => {
36+ runtime
37+ .fetch_cell_for_world(cell, name, request, cancel)
38+ .await
39+ }
40+ }
41+ }
42+
2543 pub(crate) fn local_reload_cells(&self) -> anyhow::Result<Vec<celld_logic::LocalCell>> {
2644 match self {
2745 Self::Engine(runtime) => runtime.local_reload_cells(),
modifiedcrates/celld/control_plane.rs+1−4View file
@@ -2198,10 +2198,7 @@
21982198 if asset_blob_key(sha256).is_none() {
21992199 return Err(anyhow!("invalid asset digest in index: {sha256:?}"));
22002200 }
2201- if bytes > 25 * 1024 * 1024 {
2202- return Err(anyhow!("asset exceeds runtime size limit: {path:?}"));
2203- }
2204- Ok(())
2201+ crate::assets::validate_asset_file_size(path, bytes, crate::env_vars::max_asset_file_bytes()?)
22052202 }
22062203
22072204 async fn connect(options: ConnectOptions, wait: bool) -> anyhow::Result<()> {
modifiedcrates/celld/deploy.rs+30−8View file
@@ -18,8 +18,9 @@
1818 asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest,
1919 ModuleKind, ModuleRef, QueueConsumerAttachment, QueueConsumerConfig, QueueConsumerDeployment,
2020 Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CONTAINERS_V1, FEATURE_CRON_V1,
21- FEATURE_D1_V1, FEATURE_KV_V1, FEATURE_QUEUES_V1, FEATURE_R2_V1, FEATURE_SQLITE_VEC_V1,
22- FEATURE_WASM_V1, FEATURE_WORKFLOWS_V1, QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION,
21+ FEATURE_D1_V1, FEATURE_KV_V1, FEATURE_PYTHON_WORKERS_V1, FEATURE_QUEUES_V1, FEATURE_R2_V1,
22+ FEATURE_SQLITE_VEC_V1, FEATURE_WASM_V1, FEATURE_WORKFLOWS_V1,
23+ QUEUE_CONSUMER_ATTACHMENT_SCHEMA_VERSION,
2324 };
2425 use anyhow::{anyhow, bail, Context};
2526 use flate2::write::GzEncoder;
@@ -34,6 +35,8 @@
3435 use std::process::Command;
3536 use std::time::{Duration, Instant};
3637
38+mod python;
39+
3740 /// Config keys we understand. Anything else is an error: refusing is
3841 /// compat-safe, guessing produces confusing activation failures later.
3942 const SUPPORTED_KEYS: &[&str] = &[
@@ -181,7 +184,6 @@
181184
182185 const MAX_ASSET_FILES: usize = 20_000;
183186 const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024;
184-const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024;
185187 const MAX_ASSET_DIRECTIVE_BYTES: u64 = 100 * 1024;
186188 const ASSET_UPLOAD_CONCURRENCY: usize = 16;
187189
@@ -299,6 +301,9 @@
299301 has_queues: bool,
300302 has_r2: bool,
301303 containers: Vec<ContainerDecl>,
304+ /// Set when `main` is a `.py` file: the Python behavior its
305+ /// compatibility date and flags select.
306+ python: Option<python::PythonCompat>,
302307 }
303308
304309 /// The two Wrangler bundling knobs that celld forwards to esbuild.
@@ -600,7 +605,11 @@
600605 .entry
601606 .as_deref()
602607 .map(|entry| {
603- if project.no_bundle {
608+ if let Some(compat) = &project.python {
609+ let (output, descriptor) = python::build(&root, entry, compat)?;
610+ project.metadata["python_runtime"] = descriptor;
611+ Ok(output)
612+ } else if project.no_bundle {
604613 // Already bundled by the caller's toolchain. Read it as it is;
605614 // running esbuild over a Vite build is what corrupts it.
606615 let path = root.join(entry);
@@ -652,6 +661,7 @@
652661 .and_then(Value::as_array)
653662 .is_some_and(|flags| flags.iter().any(|flag| flag.as_str() == Some("sqlite_vec")));
654663 let uses_d1 = project.do_classes.iter().any(|class| class == D1_CLASS);
664+ let python_runtime = project.python.is_some();
655665 let manifest = Manifest {
656666 schema_version: if asset_reference.is_some() { 2 } else { 1 },
657667 version: version.clone(),
@@ -708,6 +718,9 @@
708718 if !wasm_names.is_empty() {
709719 features.push(FEATURE_WASM_V1.to_string());
710720 }
721+ if python_runtime {
722+ features.push(FEATURE_PYTHON_WORKERS_V1.to_string());
723+ }
711724 features
712725 },
713726 raw_metadata: project.metadata,
@@ -1315,6 +1328,14 @@
13151328 if no_bundle && main.is_none() {
13161329 bail!("config sets `no_bundle` without `main`");
13171330 }
1331+ let python = main
1332+ .as_deref()
1333+ .filter(|main| main.ends_with(".py"))
1334+ .map(|_| {
1335+ python::check_supported_events(object)?;
1336+ python::python_compat(object)
1337+ })
1338+ .transpose()?;
13181339 let bundle = read_bundle_config(object)?;
13191340 // `define` and `rules` describe the esbuild run, and `no_bundle` is the
13201341 // absence of one. Accepting both would produce a deployment that silently
@@ -1951,6 +1972,7 @@
19511972 queue_consumers,
19521973 has_r2: !r2_buckets.is_empty(),
19531974 containers,
1975+ python,
19541976 })
19551977 }
19561978
@@ -2583,6 +2605,7 @@
25832605 }
25842606
25852607 fn build_assets(project: &ProjectAssets) -> anyhow::Result<BuiltAssets> {
2608+ let max_file_bytes = crate::env_vars::max_asset_file_bytes()?;
25862609 let mut files = Vec::new();
25872610 collect_asset_files(&project.directory, "", &mut files)?;
25882611 files.sort_by(|left, right| left.0.cmp(&right.0));
@@ -2596,9 +2619,8 @@
25962619 for (relative, path) in files {
25972620 let metadata =
25982621 std::fs::metadata(&path).with_context(|| format!("inspect {}", path.display()))?;
2599- if metadata.len() > MAX_ASSET_FILE_BYTES {
2600- bail!("asset /{relative} exceeds the 25 MiB file limit");
2601- }
2622+ let asset_path = format!("/{relative}");
2623+ crate::assets::validate_asset_file_size(&asset_path, metadata.len(), max_file_bytes)?;
26022624 total_bytes = total_bytes
26032625 .checked_add(metadata.len())
26042626 .context("asset byte count overflow")?;
@@ -2612,7 +2634,7 @@
26122634 let sha256 = format!("{:x}", Sha256::digest(&body));
26132635 blobs.entry(sha256.clone()).or_insert(body);
26142636 entries.insert(
2615- format!("/{relative}"),
2637+ asset_path,
26162638 AssetEntry {
26172639 sha256,
26182640 bytes: metadata.len(),
addedcrates/celld/deploy/python.rs+677−0View file
@@ -1,0 +1,677 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! The build path for a Worker whose `main` is a `.py` file.
4+//!
5+//! celld implements one line of Cloudflare's Python Workers runtime: Pyodide
6+//! 0.28 with CPython 3.13, running the application's vendored Workers SDK
7+//! (the `enable_python_external_sdk` behavior). Configurations that
8+//! Cloudflare would run on a different Pyodide are refused, because the
9+//! wheels in `python_modules/` are built for one interpreter ABI.
10+//!
11+//! The build embeds the application's `.py` files and its `python_modules/`
12+//! directory (the output of `pywrangler sync`) in one JavaScript bundle with
13+//! the pinned upstream Pyodide release. The interpreter and its GC sentinel
14+//! become compiled Wasm modules. Nothing is fetched when the Worker runs.
15+
16+use super::BundleOutput;
17+use anyhow::{anyhow, bail, Context};
18+use serde_json::{json, Map, Value};
19+use sha2::{Digest, Sha256};
20+use std::collections::BTreeMap;
21+use std::path::{Path, PathBuf};
22+use std::process::Command;
23+use std::time::Duration;
24+
25+/// Pyodide release embedded in every Python Worker. Cloudflare runs 0.28.2
26+/// with its own patches for this line; 0.28.3 has the same CPython 3.13.2
27+/// and wheel ABI (`pyodide_2025_0`), and `pywrangler` resolves packages
28+/// for Python 3.13 against the 0.28.3 package index.
29+pub const PYODIDE_VERSION: &str = "0.28.3";
30+const PYODIDE_BASE_URL: &str = "https://cdn.jsdelivr.net/pyodide/v0.28.3/full/";
31+
32+/// Each runtime file with its size and SHA-256. A cached or downloaded file
33+/// that does not match is refused.
34+const RUNTIME_FILES: &[(&str, u64, &str)] = &[
35+ (
36+ "pyodide.asm.js",
37+ 1_073_033,
38+ "b22e5831eade9ff10e6fe2c811c68688cd91f10154377b4f80debcf5bafa1e56",
39+ ),
40+ (
41+ "pyodide.asm.wasm",
42+ 8_645_967,
43+ "5effb6a1a6cc4a1a85bec4622701aa797c031e1de923cbbaf2ad47abdc4ab325",
44+ ),
45+ (
46+ "pyodide.mjs",
47+ 16_347,
48+ "635a6da3218fe4e5668da595acfe8b5ce77453d597d602f19a423dd250653441",
49+ ),
50+ (
51+ "python_stdlib.zip",
52+ 2_416_866,
53+ "71fee17f88a6260ec8c9c7c063533ee59c021fdc88a1ce76247378d3c4a35f4c",
54+ ),
55+ (
56+ "pyodide-lock.json",
57+ 109_732,
58+ "f6e6f42f451f42affbbcddb00e8c9a3278dcbf399f57aab9f3f568839a7ff4a6",
59+ ),
60+];
61+
62+/// The GC sentinel program that `pyodide.mjs` carries as base64.
63+const SENTINEL_SHA256: &str = "d22ea2a6a2cb1afea8157d6e4570887a06e5af9e388c5f0fa5a984a8e9bb1021";
64+
65+const SHIMS_JS: &str = include_str!("../python/shims.js");
66+const FATAL_JS: &str = include_str!("../python/fatal.js");
67+const WORKER_JS: &str = include_str!("../python/worker.js");
68+const WORKER_PY: &str = include_str!("../python/worker.py");
69+
70+/// The file extensions of Wrangler's `PythonModule` rule and its default
71+/// module rules (Text, Data and CompiledWasm). Wrangler uploads a matching
72+/// file beside the Python sources, and workerd exposes it as a file under
73+/// /session/metadata, so an application can open a bundled template or SQL
74+/// file. Leaving one out would pass on Cloudflare and fail on celld with
75+/// `FileNotFoundError`.
76+const SOURCE_EXTENSIONS: &[&str] = &[".py", ".txt", ".html", ".sql", ".bin", ".wasm"];
77+
78+/// Directories under the entry directory that never hold application
79+/// modules. `python_modules` is collected separately, from the project root.
80+const SKIPPED_SOURCE_DIRECTORIES: &[&str] =
81+ &["__pycache__", "node_modules", "python_modules", "target"];
82+
83+/// The Python behavior a configuration selects. Every Cloudflare switch
84+/// that decides which interpreter, SDK, search path or handler style runs is
85+/// resolved here, so the bundle carries answers rather than dates.
86+#[derive(Debug, PartialEq, Eq)]
87+pub struct PythonCompat {
88+ pub process_pth_files: bool,
89+ pub request_headers_preserve_commas: bool,
90+ pub workflows_implicit_dependencies: bool,
91+}
92+
93+/// Refuse a configuration that Cloudflare would not run on the Pyodide 0.28
94+/// line with the vendored SDK and `Default` entrypoint classes.
95+///
96+/// The dates are workerd's `compatibility-date.capnp` at commit
97+/// da46ad950c54b19158c5ea5cb997a9727491ca17 (v1.20260926.1).
98+pub fn python_compat(object: &Map<String, Value>) -> anyhow::Result<PythonCompat> {
99+ // A dropped flag would silently select another runtime behavior.
100+ let flags: Vec<&str> = match object.get("compatibility_flags") {
101+ None => Vec::new(),
102+ Some(Value::Array(flags)) => flags
103+ .iter()
104+ .map(|flag| {
105+ flag.as_str()
106+ .ok_or_else(|| anyhow!("compatibility flags must be strings"))
107+ })
108+ .collect::<anyhow::Result<_>>()?,
109+ Some(_) => bail!("config `compatibility_flags` must be an array"),
110+ };
111+ let has = |flag: &str| flags.contains(&flag);
112+ let date = object
113+ .get("compatibility_date")
114+ .and_then(Value::as_str)
115+ .ok_or_else(|| anyhow!("Python Workers need a `compatibility_date`"))?;
116+ // The dates below are compared as text, which orders only this form:
117+ // "2026-4-3" would sort after "2026-04-21" and select later behavior.
118+ let well_formed = date.len() == 10
119+ && date.bytes().enumerate().all(|(index, byte)| match index {
120+ 4 | 7 => byte == b'-',
121+ _ => byte.is_ascii_digit(),
122+ });
123+ if !well_formed {
124+ bail!("compatibility_date {date:?} must have the form YYYY-MM-DD");
125+ }
126+ let since = |day: &str| date >= day;
127+ let switch =
128+ |enable: &str, disable: &str, day: &str| has(enable) || (!has(disable) && since(day));
129+ if !has("python_workers") {
130+ bail!("Python entries require the python_workers compatibility flag");
131+ }
132+ for flag in [
133+ "python_workers_314",
134+ "python_workers_20260610",
135+ "python_workers_development",
136+ ] {
137+ if has(flag) {
138+ bail!(
139+ "celld runs Python Workers on Pyodide {PYODIDE_VERSION} (Python 3.13); \
140+ remove the `{flag}` compatibility flag"
141+ );
142+ }
143+ }
144+ if switch("python_workers_314", "no_python_workers_314", "2026-09-08") {
145+ bail!(
146+ "compatibility_date {date} selects Pyodide 314 (Python 3.14) on Cloudflare, and \
147+ celld runs Pyodide {PYODIDE_VERSION} (Python 3.13); use a date before 2026-09-08 \
148+ or add the `no_python_workers_314` compatibility flag"
149+ );
150+ }
151+ // Everything below is on by date from 2026-04-21, so each check only
152+ // rejects an explicit opt-out or an older date.
153+ let required = [
154+ (
155+ "python_workers_20250116",
156+ "no_python_workers_20250116",
157+ "2025-09-29",
158+ "Pyodide 0.28",
159+ ),
160+ (
161+ "enable_python_external_sdk",
162+ "disable_python_external_sdk",
163+ "2026-04-21",
164+ "the vendored Workers SDK",
165+ ),
166+ (
167+ "python_no_global_handlers",
168+ "disable_python_no_global_handlers",
169+ "2025-08-14",
170+ "`Default` entrypoint classes",
171+ ),
172+ (
173+ "python_workers_force_new_vendor_path",
174+ "",
175+ "2025-08-11",
176+ "the `python_modules` search path",
177+ ),
178+ ];
179+ for (enable, disable, day, behavior) in required {
180+ if !switch(enable, disable, day) {
181+ bail!(
182+ "celld runs Python Workers only with {behavior} ({enable}); use a \
183+ compatibility_date from 2026-04-21 without opting out of it"
184+ );
185+ }
186+ }
187+ Ok(PythonCompat {
188+ process_pth_files: switch(
189+ "python_process_pth_files",
190+ "disable_python_process_pth_files",
191+ "2026-05-26",
192+ ),
193+ request_headers_preserve_commas: switch(
194+ "python_request_headers_preserve_commas",
195+ "disable_python_request_headers_preserve_commas",
196+ "2026-02-17",
197+ ),
198+ workflows_implicit_dependencies: switch(
199+ "python_workflows_implicit_dependencies",
200+ "no_python_workflows_implicit_dependencies",
201+ "2026-02-25",
202+ ),
203+ })
204+}
205+
206+/// Refuse the parts of a configuration that would route an event other than
207+/// `fetch` to Python. Only `Default.fetch` is dispatched.
208+pub fn check_supported_events(object: &Map<String, Value>) -> anyhow::Result<()> {
209+ let non_empty = |value: Option<&Value>| match value {
210+ None | Some(Value::Null) => false,
211+ Some(Value::Array(items)) => !items.is_empty(),
212+ Some(Value::Object(fields)) => !fields.is_empty(),
213+ Some(_) => true,
214+ };
215+ for (present, what) in [
216+ (
217+ non_empty(
218+ object
219+ .get("durable_objects")
220+ .and_then(|d| d.get("bindings")),
221+ ),
222+ "Durable Objects",
223+ ),
224+ (non_empty(object.get("workflows")), "Workflows"),
225+ (
226+ non_empty(object.get("triggers").and_then(|t| t.get("crons"))),
227+ "Cron Triggers",
228+ ),
229+ (
230+ non_empty(object.get("queues").and_then(|q| q.get("consumers"))),
231+ "Queue consumers",
232+ ),
233+ (non_empty(object.get("containers")), "Containers"),
234+ ] {
235+ if present {
236+ bail!("celld does not run {what} in Python Workers yet; a Python Worker handles `fetch` only");
237+ }
238+ }
239+ // Refused only when they would change the build: an empty table or a
240+ // `false` is what a generated config writes and means the default.
241+ for (present, key) in [
242+ (
243+ object.get("no_bundle") == Some(&Value::Bool(true)),
244+ "no_bundle",
245+ ),
246+ (non_empty(object.get("define")), "define"),
247+ (non_empty(object.get("rules")), "rules"),
248+ ] {
249+ if present {
250+ bail!("Python entries do not support `{key}`");
251+ }
252+ }
253+ Ok(())
254+}
255+
256+pub fn build(
257+ root: &Path,
258+ entry: &str,
259+ compat: &PythonCompat,
260+) -> anyhow::Result<(BundleOutput, Value)> {
261+ let entry_path = Path::new(entry);
262+ let main_module = entry_path
263+ .file_stem()
264+ .and_then(|stem| stem.to_str())
265+ .filter(|stem| is_identifier(stem))
266+ .ok_or_else(|| anyhow!("Python entry {entry} must be named as an importable module"))?;
267+ let source_root = root.join(entry_path.parent().unwrap_or(Path::new("")));
268+ let mut files = BTreeMap::new();
269+ collect_sources(&source_root, "", &mut files)?;
270+ let sdk = collect_python_modules(&root.join("python_modules"), &mut files)?;
271+
272+ let runtime = runtime_files()?;
273+ let directory = tempfile::tempdir().context("create Python build directory")?;
274+ let out = directory.path();
275+ for (name, bytes) in &runtime {
276+ if name != "pyodide.asm.wasm" && name != "pyodide-lock.json" {
277+ std::fs::write(out.join(name), bytes)?;
278+ }
279+ }
280+ let sentinel = sentinel_bytes(&runtime["pyodide.mjs"])?;
281+ let lock: Value = serde_json::from_slice(&runtime["pyodide-lock.json"])?;
282+ let flags = json!({
283+ "python_workers": true,
284+ "python_workers_20250116": true,
285+ "enable_python_external_sdk": true,
286+ "python_no_global_handlers": true,
287+ "python_workers_force_new_vendor_path": true,
288+ "python_process_pth_files": compat.process_pth_files,
289+ "python_request_headers_preserve_commas": compat.request_headers_preserve_commas,
290+ "python_workflows_implicit_dependencies": compat.workflows_implicit_dependencies,
291+ });
292+ let config = format!(
293+ "export const SENTINEL_BYTES = new Uint8Array({});\n\
294+ export const LOCK = {};\n\
295+ export const MAIN_MODULE = {};\n\
296+ export const COMPATIBILITY_FLAGS = {flags};\n\
297+ export const PROCESS_PTH_FILES = {};\n",
298+ serde_json::to_string(&sentinel)?,
299+ // The loader checks the lock's interpreter identity. No package is
300+ // ever loaded from it, so the package table stays out of the bundle.
301+ json!({ "info": lock["info"], "packages": {} }),
302+ serde_json::to_string(main_module)?,
303+ compat.process_pth_files,
304+ );
305+ std::fs::write(out.join("config.js"), config)?;
306+ // The `browser` map of the pyodide npm package: esbuild replaces the
307+ // loader's Node.js builtins with empty modules, as a browser build does.
308+ std::fs::write(
309+ out.join("package.json"),
310+ r#"{"private":true,"browser":{"fs":false,"vm":false,"ws":false,"url":false,"path":false,"crypto":false,"fs/promises":false,"child_process":false}}"#,
311+ )?;
312+ std::fs::write(out.join("shims.js"), SHIMS_JS)?;
313+ std::fs::write(out.join("fatal.js"), FATAL_JS)?;
314+ std::fs::write(out.join("worker.js"), WORKER_JS)?;
315+ std::fs::write(out.join("worker.py"), WORKER_PY)?;
316+ std::fs::write(out.join("files.bin"), pack(&files)?)?;
317+ run_esbuild(out)?;
318+ let bundle = std::fs::read(out.join("index.js")).context("read Python Worker bundle")?;
319+
320+ let descriptor = json!({
321+ "pyodide": PYODIDE_VERSION,
322+ "python": lock["info"]["python"],
323+ "abi": lock["info"]["abi_version"],
324+ "sdk": sdk,
325+ "main_module": main_module,
326+ });
327+ let wasm = vec![
328+ (
329+ "pyodide.asm.wasm".to_string(),
330+ runtime["pyodide.asm.wasm"].clone(),
331+ ),
332+ ("sentinel.wasm".to_string(), sentinel),
333+ ];
334+ Ok((BundleOutput { bundle, wasm }, descriptor))
335+}
336+
337+fn is_identifier(name: &str) -> bool {
338+ let mut chars = name.chars();
339+ chars
340+ .next()
341+ .is_some_and(|first| first == '_' || first.is_ascii_alphabetic())
342+ && chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
343+}
344+
345+/// Every file below the entry directory that Wrangler's module rules
346+/// upload (see `SOURCE_EXTENSIONS`), keyed by its path in that directory.
347+fn collect_sources(
348+ directory: &Path,
349+ relative: &str,
350+ files: &mut BTreeMap<String, Vec<u8>>,
351+) -> anyhow::Result<()> {
352+ for entry in std::fs::read_dir(directory)
353+ .with_context(|| format!("read Python source directory {}", directory.display()))?
354+ {
355+ let entry = entry?;
356+ let name = entry
357+ .file_name()
358+ .into_string()
359+ .map_err(|_| anyhow!("non-UTF-8 name under {}", directory.display()))?;
360+ let file_type = entry.file_type()?;
361+ if name.starts_with('.') {
362+ continue;
363+ }
364+ let path = if relative.is_empty() {
365+ name.clone()
366+ } else {
367+ format!("{relative}/{name}")
368+ };
369+ if file_type.is_dir() {
370+ if !SKIPPED_SOURCE_DIRECTORIES.contains(&name.as_str()) {
371+ collect_sources(&entry.path(), &path, files)?;
372+ }
373+ } else if SOURCE_EXTENSIONS
374+ .iter()
375+ .any(|extension| name.ends_with(extension))
376+ {
377+ if !file_type.is_file() {
378+ bail!("Python Worker module {path} is not a regular file");
379+ }
380+ files.insert(path, std::fs::read(entry.path())?);
381+ }
382+ }
383+ Ok(())
384+}
385+
386+/// Add `python_modules/` to `files` and return the vendored SDK's identity.
387+///
388+/// The tree is what `pywrangler sync` writes: wheels unpacked for the
389+/// Pyodide target. Compiled extensions need a loader that this build does
390+/// not have yet, so they are refused rather than left to fail on import.
391+fn collect_python_modules(
392+ directory: &Path,
393+ files: &mut BTreeMap<String, Vec<u8>>,
394+) -> anyhow::Result<Value> {
395+ if !directory.join("workers").join("__init__.py").is_file() {
396+ bail!(
397+ "{} does not contain the Workers SDK (`workers-runtime-sdk`); run \
398+ `uv run pywrangler sync` to vendor the project's packages",
399+ directory.display()
400+ );
401+ }
402+ let mut vendored = BTreeMap::new();
403+ collect_vendored(directory, "", &mut vendored)?;
404+ let sdk_version = vendored
405+ .keys()
406+ .find_map(|path| {
407+ let name = path.strip_suffix(".dist-info/METADATA")?;
408+ name.strip_prefix("workers_runtime_sdk-")
409+ .filter(|version| !version.contains('/'))
410+ })
411+ .map(str::to_string)
412+ .ok_or_else(|| anyhow!("python_modules has no workers_runtime_sdk metadata"))?;
413+ let entrypoints = vendored.get("workers/entrypoints.py").ok_or_else(|| {
414+ anyhow!(
415+ "python_modules is missing workers/entrypoints.py; run \
416+ `uv run pywrangler sync` to restore the Workers SDK"
417+ )
418+ })?;
419+ let digest = format!("{:x}", Sha256::digest(entrypoints));
420+ for (path, bytes) in vendored {
421+ files.insert(format!("python_modules/{path}"), bytes);
422+ }
423+ Ok(json!({
424+ "package": "workers-runtime-sdk",
425+ "version": sdk_version,
426+ "entrypoints_sha256": digest,
427+ }))
428+}
429+
430+fn collect_vendored(
431+ directory: &Path,
432+ relative: &str,
433+ files: &mut BTreeMap<String, Vec<u8>>,
434+) -> anyhow::Result<()> {
435+ for entry in
436+ std::fs::read_dir(directory).with_context(|| format!("read {}", directory.display()))?
437+ {
438+ let entry = entry?;
439+ let name = entry
440+ .file_name()
441+ .into_string()
442+ .map_err(|_| anyhow!("non-UTF-8 name under {}", directory.display()))?;
443+ let file_type = entry.file_type()?;
444+ let path = if relative.is_empty() {
445+ name.clone()
446+ } else {
447+ format!("{relative}/{name}")
448+ };
449+ if file_type.is_symlink() {
450+ bail!("python_modules/{path} is a symbolic link; vendor packages as files");
451+ }
452+ if file_type.is_dir() {
453+ if name != "__pycache__" {
454+ collect_vendored(&entry.path(), &path, files)?;
455+ }
456+ continue;
457+ }
458+ if !file_type.is_file() {
459+ bail!("python_modules/{path} is not a regular file");
460+ }
461+ if name.ends_with(".so") || name.contains(".so.") {
462+ bail!(
463+ "python_modules/{path} is a compiled extension; celld runs pure-Python \
464+ packages only"
465+ );
466+ }
467+ if name.ends_with(".pyc") {
468+ continue;
469+ }
470+ files.insert(path, std::fs::read(entry.path())?);
471+ }
472+ Ok(())
473+}
474+
475+/// The `files.bin` format read by `python/worker.js`: a count, then each
476+/// path and its bytes, all lengths as little-endian u32.
477+fn pack(files: &BTreeMap<String, Vec<u8>>) -> anyhow::Result<Vec<u8>> {
478+ let length = |value: usize| -> anyhow::Result<[u8; 4]> {
479+ Ok(u32::try_from(value)
480+ .map_err(|_| anyhow!("Python bundle file is too large"))?
481+ .to_le_bytes())
482+ };
483+ let mut out = Vec::new();
484+ out.extend(length(files.len())?);
485+ for (path, bytes) in files {
486+ out.extend(length(path.len())?);
487+ out.extend(path.as_bytes());
488+ out.extend(length(bytes.len())?);
489+ out.extend(bytes);
490+ }
491+ Ok(out)
492+}
493+
494+fn sentinel_bytes(loader: &[u8]) -> anyhow::Result<Vec<u8>> {
495+ use base64::Engine;
496+ let loader = std::str::from_utf8(loader)?;
497+ let start = loader
498+ .find("\"AGFzbQ")
499+ .ok_or_else(|| anyhow!("pyodide.mjs has no embedded sentinel"))?
500+ + 1;
501+ let end = start
502+ + loader[start..]
503+ .find('"')
504+ .ok_or_else(|| anyhow!("unterminated sentinel in pyodide.mjs"))?;
505+ let bytes = base64::engine::general_purpose::STANDARD.decode(&loader[start..end])?;
506+ if format!("{:x}", Sha256::digest(&bytes)) != SENTINEL_SHA256 {
507+ bail!("pyodide.mjs carries an unexpected sentinel program");
508+ }
509+ Ok(bytes)
510+}
511+
512+/// Where verified runtime files are kept between builds.
513+/// `CELLD_PYTHON_RUNTIME_DIR` selects a directory; a directory that already
514+/// holds the verified files lets a build run offline.
515+fn runtime_directory() -> anyhow::Result<PathBuf> {
516+ if let Some(directory) = std::env::var_os("CELLD_PYTHON_RUNTIME_DIR") {
517+ return Ok(PathBuf::from(directory));
518+ }
519+ let cache = std::env::var_os("XDG_CACHE_HOME")
520+ .map(PathBuf::from)
521+ .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache")))
522+ .ok_or_else(|| anyhow!("set CELLD_PYTHON_RUNTIME_DIR to cache the Python runtime"))?;
523+ Ok(cache
524+ .join("celld")
525+ .join(format!("pyodide-{PYODIDE_VERSION}")))
526+}
527+
528+fn runtime_files() -> anyhow::Result<BTreeMap<String, Vec<u8>>> {
529+ let directory = runtime_directory()?;
530+ let verified = |bytes: &[u8], size: u64, sha256: &str| {
531+ bytes.len() as u64 == size && format!("{:x}", Sha256::digest(bytes)) == sha256
532+ };
533+ let mut files = BTreeMap::new();
534+ let mut missing = Vec::new();
535+ for &(name, size, sha256) in RUNTIME_FILES {
536+ match std::fs::read(directory.join(name)) {
537+ Ok(bytes) if verified(&bytes, size, sha256) => {
538+ files.insert(name.to_string(), bytes);
539+ }
540+ _ => missing.push((name, size, sha256)),
541+ }
542+ }
543+ if missing.is_empty() {
544+ return Ok(files);
545+ }
546+ std::fs::create_dir_all(&directory)
547+ .with_context(|| format!("create {}", directory.display()))?;
548+ for (name, bytes) in download(&missing)? {
549+ let (_, size, sha256) = missing.iter().find(|file| file.0 == name).unwrap();
550+ if !verified(&bytes, *size, sha256) {
551+ bail!("downloaded {name} does not match Pyodide {PYODIDE_VERSION}");
552+ }
553+ let staged = tempfile::NamedTempFile::new_in(&directory)?;
554+ std::fs::write(staged.path(), &bytes)?;
555+ staged
556+ .persist(directory.join(&name))
557+ .map_err(|error| anyhow!("store {name}: {error}"))?;
558+ files.insert(name, bytes);
559+ }
560+ Ok(files)
561+}
562+
563+/// How long a runtime download may wait for a connection. The stall bound
564+/// below covers a connection that opens and then goes quiet.
565+const DOWNLOAD_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
566+/// How long a runtime download may wait for its next bytes. There is no
567+/// total deadline: the interpreter alone is 8.6 MB, and a slow link that
568+/// keeps delivering must still finish. Without this bound a stalled CDN
569+/// hangs `celld deploy` and never shows the offline hint.
570+const DOWNLOAD_STALL_TIMEOUT: Duration = Duration::from_secs(60);
571+
572+fn download(files: &[(&str, u64, &str)]) -> anyhow::Result<Vec<(String, Vec<u8>)>> {
573+ download_from(PYODIDE_BASE_URL, files, DOWNLOAD_STALL_TIMEOUT)
574+}
575+
576+/// Fetch runtime files on a private thread, so a build works whether or not
577+/// the caller is inside an async runtime. Each body is read up to its pinned
578+/// size: a larger one cannot pass verification, and an unbounded read would
579+/// buffer an endless body until the process runs out of memory.
580+fn download_from(
581+ base_url: &str,
582+ files: &[(&str, u64, &str)],
583+ stall: Duration,
584+) -> anyhow::Result<Vec<(String, Vec<u8>)>> {
585+ let files: Vec<(String, u64)> = files
586+ .iter()
587+ .map(|&(name, size, _)| (name.to_string(), size))
588+ .collect();
589+ let base_url = base_url.to_string();
590+ std::thread::spawn(move || {
591+ let runtime = tokio::runtime::Builder::new_current_thread()
592+ .enable_all()
593+ .build()?;
594+ runtime.block_on(async {
595+ let client = reqwest::Client::builder()
596+ .connect_timeout(DOWNLOAD_CONNECT_TIMEOUT)
597+ .read_timeout(stall)
598+ .build()?;
599+ let mut out = Vec::new();
600+ for (name, size) in files {
601+ let url = format!("{base_url}{name}");
602+ let hint = || {
603+ format!(
604+ "download {url}; to build offline, place the Pyodide \
605+ {PYODIDE_VERSION} files in CELLD_PYTHON_RUNTIME_DIR"
606+ )
607+ };
608+ let mut response = client
609+ .get(&url)
610+ .send()
611+ .await
612+ .and_then(reqwest::Response::error_for_status)
613+ .with_context(hint)?;
614+ let limit = usize::try_from(size)?;
615+ let mut bytes = Vec::with_capacity(limit);
616+ while let Some(chunk) = response.chunk().await.with_context(hint)? {
617+ if bytes.len() + chunk.len() > limit {
618+ bail!("{url} is larger than the {size} bytes of Pyodide {PYODIDE_VERSION}");
619+ }
620+ bytes.extend_from_slice(&chunk);
621+ }
622+ out.push((name, bytes));
623+ }
624+ Ok(out)
625+ })
626+ })
627+ .join()
628+ .map_err(|_| anyhow!("Python runtime download panicked"))?
629+}
630+
631+fn run_esbuild(directory: &Path) -> anyhow::Result<()> {
632+ let binary = std::env::var("CELLD_ESBUILD").unwrap_or_else(|_| "esbuild".to_string());
633+ let output = Command::new(&binary)
634+ .current_dir(directory)
635+ .arg("worker.js")
636+ .arg("--bundle")
637+ .arg("--format=esm")
638+ .arg("--platform=browser")
639+ .arg("--target=es2022")
640+ .arg("--outfile=index.js")
641+ .arg("--inject:./shims.js")
642+ .arg("--loader:.zip=binary")
643+ .arg("--loader:.bin=binary")
644+ .arg("--loader:.py=text")
645+ // The loader treats a defined `process` as Node. These names are
646+ // replaced only inside the bundle.
647+ .arg("--define:process=undefined")
648+ .arg("--define:location=\"https://python-runtime.invalid/\"")
649+ .arg("--external:cloudflare:*")
650+ // The host module that retires an isolate after a fatal error.
651+ .arg("--external:celld:python")
652+ // Dynamic imports on the loader's Node.js path, which never runs.
653+ .arg("--external:node:*")
654+ .arg("--external:./pyodide.asm.wasm")
655+ .arg("--external:./sentinel.wasm")
656+ .arg("--log-level=warning")
657+ .output()
658+ .map_err(|error| {
659+ if error.kind() == std::io::ErrorKind::NotFound {
660+ anyhow!("esbuild not found ({binary}); install it or set CELLD_ESBUILD")
661+ } else {
662+ anyhow!("run esbuild: {error}")
663+ }
664+ })?;
665+ if !output.status.success() {
666+ bail!(
667+ "esbuild failed on the Python Worker bundle:\n{}",
668+ String::from_utf8_lossy(&output.stderr).trim()
669+ );
670+ }
671+ Ok(())
672+}
673+
674+#[cfg(all(test, celld_internal_tests))]
675+mod internal_tests {
676+ include!(env!("CELLD_INTERNAL_PYTHON_DEPLOY_TESTS"));
677+}
modifiedcrates/celld/engine_api.rs+7−1View file
@@ -613,7 +613,7 @@
613613 return None;
614614 }
615615 let mut output = [0_u8; 32];
616- for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
616+ for (index, pair) in value.as_bytes().as_chunks::<2>().0.iter().enumerate() {
617617 let nibble = |byte| match byte {
618618 b'0'..=b'9' => Some(byte - b'0'),
619619 b'a'..=b'f' => Some(byte - b'a' + 10),
@@ -831,6 +831,12 @@
831831 .then(|| anyhow::anyhow!("injected generation swap release failure"))
832832 }
833833
834+/// Is `cell` a facet's stream? Only [`facet_cell`] builds a name with this
835+/// segment; a root cell's scope cannot contain `/`.
836+pub(crate) fn is_facet_cell(cell: &str) -> bool {
837+ cell.contains("/facets/")
838+}
839+
834840 /// The replication stream of a facet: nested under its root's own
835841 /// coordinates, `<root>/facets/<h>` locally and `cells/<root>/facets/<h>/`
836842 /// in the bucket, one level per name of the facet's path, so no scan of
modifiedcrates/celld/env_vars.rs+22−0View file
@@ -9,6 +9,24 @@
99 use anyhow::{anyhow, bail};
1010
1111 pub const DEFAULT_SHUTDOWN_TOTAL_MS: u64 = 40_000;
12+
13+/// Shared by deployment assembly, managed deployment validation and serving
14+/// nodes. Operators must configure the same policy on all three paths.
15+pub fn max_asset_file_bytes() -> anyhow::Result<u64> {
16+ // A manifest can contain thousands of entries. Cache the policy so each
17+ // entry neither allocates an environment string nor observes a new limit.
18+ // Keep parse failures fallible for library callers that skip startup validation.
19+ static LIMIT: std::sync::OnceLock<Result<u64, String>> = std::sync::OnceLock::new();
20+ LIMIT
21+ .get_or_init(|| {
22+ positive_or("CELLD_MAX_ASSET_FILE_BYTES", 25 * 1024 * 1024)
23+ .map_err(|error| error.to_string())
24+ })
25+ .as_ref()
26+ .copied()
27+ .map_err(|message| anyhow!("{message}"))
28+}
29+
1230 /// One process stop budget and the internal waits derived from it.
1331 /// The absolute deadline also bounds progress extensions, so neither wait
1432 /// grants time beyond the supervisor-facing process budget.
@@ -233,6 +251,7 @@
233251 "CELLD_LTX_COMPACTION_MIN_TXIDS",
234252 "CELLD_LTX_DURABILITY_TIMEOUT_SECS",
235253 "CELLD_MAX_CELL_REQUESTS",
254+ "CELLD_MAX_ASSET_FILE_BYTES",
236255 "CELLD_MAX_OUTBOUND_WEBSOCKETS",
237256 "CELLD_MAX_REQUEST_BODY_BYTES",
238257 "CELLD_MAX_REQUESTS",
@@ -256,6 +275,7 @@
256275 "CELLD_DEPLOY_MAX_AGE_S",
257276 "CELLD_LOCAL_CACHE_MAX_BYTES",
258277 "CELLD_LTX_TRUNCATE_PAGES",
278+ "CELLD_LTX_RETENTION_SECS",
259279 "CELLD_LOG_HEDGE_MS",
260280 "CELLD_LOG_WINDOW",
261281 "CELLD_LOG_WINDOW_BYTES",
@@ -269,6 +289,8 @@
269289
270290 shutdown_timing()?;
271291
292+ positive::<usize>("CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES")?;
293+
272294 if let Some(value) = optional::<u64>("CELLD_PRESENCE_HEARTBEAT_MS")? {
273295 if !(50..=30_000).contains(&value) {
274296 bail!("CELLD_PRESENCE_HEARTBEAT_MS must be between 50 and 30000, not {value}");
modifiedcrates/celld/host_channels.rs+77−0View file
@@ -280,3 +280,80 @@
280280 pub fn set_r2_store(bucket: Bucket) {
281281 let _ = R2_STORE.set(bucket);
282282 }
283+
284+/// Why the output gate did not release a ticket.
285+pub(crate) enum GateRefusal {
286+ /// The process installed no gate channel. A write must still fail closed
287+ /// here: an acknowledgement nobody can prove is the loss this gate exists
288+ /// to prevent.
289+ NoChannel,
290+ /// The core answered, and the answer is that the write is not durable.
291+ Unproven(celld_logic::RequestError),
292+ /// The shell dropped the ticket before the core answered.
293+ Dropped,
294+ /// A facet's write never reached a database a proof can cover.
295+ Unpersisted(String),
296+}
297+
298+impl std::fmt::Display for GateRefusal {
299+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300+ match self {
301+ GateRefusal::NoChannel => f.write_str("no output-gate channel"),
302+ GateRefusal::Unproven(error @ celld_logic::RequestError::DurabilityUnproven) => {
303+ write!(
304+ f,
305+ "the write this request follows is not durable ({error:?})"
306+ )
307+ }
308+ GateRefusal::Unproven(error) => {
309+ write!(f, "the output gate refused the ticket ({error:?})")
310+ }
311+ GateRefusal::Dropped => f.write_str("output gate dropped"),
312+ GateRefusal::Unpersisted(error) => {
313+ write!(f, "the facet's write did not reach its database ({error})")
314+ }
315+ }
316+ }
317+}
318+
319+/// Ask the host to prove the caller's sampled position before an effect leaves.
320+pub(crate) async fn request_gate(
321+ channel: Option<&tokio::sync::mpsc::UnboundedSender<GateReq>>,
322+ scope: String,
323+ ticket: crate::actor::GateTicket,
324+) -> std::result::Result<(), GateRefusal> {
325+ let (tx, receive) = tokio::sync::oneshot::channel();
326+ let sent = channel
327+ .map(|gate| {
328+ gate.send(GateReq {
329+ scope,
330+ ticket,
331+ reply: tx,
332+ })
333+ .is_ok()
334+ })
335+ .unwrap_or(false);
336+ if !sent {
337+ return Err(GateRefusal::NoChannel);
338+ }
339+ match receive.await {
340+ Ok(Ok(())) => Ok(()),
341+ Ok(Err(error)) => Err(GateRefusal::Unproven(error)),
342+ Err(_) => Err(GateRefusal::Dropped),
343+ }
344+}
345+
346+/// Submit only after the caller's durability future releases the effect.
347+/// Taking the sender after the await preserves host-channel installation order.
348+pub(crate) async fn send_after_gate<'a, T: 'a>(
349+ gate: impl std::future::Future<Output = std::result::Result<(), String>>,
350+ channel: impl FnOnce() -> Option<&'a tokio::sync::mpsc::UnboundedSender<T>>,
351+ request: T,
352+ missing: &'static str,
353+) -> std::result::Result<(), String> {
354+ gate.await?;
355+ match channel() {
356+ Some(tx) if tx.send(request).is_ok() => Ok(()),
357+ _ => Err(missing.to_string()),
358+ }
359+}
modifiedcrates/celld/host_services.rs+29−1View file
@@ -9,7 +9,7 @@
99 use crate::ownership_store::LiveLoad;
1010 use std::sync::{Arc, Mutex, OnceLock};
1111
12-/// One resource observation used by the pressure path.
12+/// One resource observation shared by pressure decisions and node leases.
1313 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1414 pub struct HostMetricsSample {
1515 pub cpu_percent_x100: u64,
@@ -17,6 +17,8 @@
1717 pub in_use_bytes: u64,
1818 pub cgroup_working_set_bytes: Option<u64>,
1919 pub cgroup_current_bytes: Option<u64>,
20+ pub open_fds: u64,
21+ pub fd_limit: u64,
2022 }
2123
2224 enum MetricsBackend {
@@ -136,17 +138,43 @@
136138 self.http_streams.close();
137139 }
138140
141+ /// Collect off the core so filesystem reads cannot delay a lease.
142+ #[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage.
139143 pub fn sample_metrics(&self) -> HostMetricsSample {
140144 match &self.metrics {
141145 MetricsBackend::Production(sampler) => {
142146 let mut sampler = sampler.lock().unwrap();
143147 let memory = crate::memory::sample();
148+ #[cfg(target_os = "linux")]
149+ let open_fds = std::fs::read_dir("/proc/self/fd")
150+ .map(|entries| entries.count() as u64)
151+ .unwrap_or_default();
152+ #[cfg(not(target_os = "linux"))]
153+ let open_fds = 0;
154+
155+ #[cfg(unix)]
156+ let fd_limit = {
157+ let mut limit = libc::rlimit {
158+ rlim_cur: 0,
159+ rlim_max: 0,
160+ };
161+ if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 {
162+ limit.rlim_cur
163+ } else {
164+ 0
165+ }
166+ };
167+ #[cfg(not(unix))]
168+ let fd_limit = 0;
169+
144170 HostMetricsSample {
145171 cpu_percent_x100: sampler.sample_cpu_percent_x100(),
146172 rss_bytes: memory.rss_bytes,
147173 in_use_bytes: memory.in_use_bytes,
148174 cgroup_working_set_bytes: memory.cgroup_working_set_bytes,
149175 cgroup_current_bytes: memory.cgroup_current_bytes,
176+ open_fds,
177+ fd_limit,
150178 }
151179 }
152180 #[cfg(celld_internal_tests)]
modifiedcrates/celld/js.rs+291−100View file
@@ -614,6 +614,9 @@
614614 scope: String,
615615 ws_id: u64,
616616 data: WsIn,
617+ /// Released after the first turn, so the socket can deliver the next
618+ /// message in order without waiting for this handler's async work.
619+ started: Option<tokio::sync::oneshot::Sender<()>>,
617620 reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
618621 },
619622 WsClosed {
@@ -746,6 +749,7 @@
746749
747750 #[doc(hidden)]
748751 pub mod websocket;
752+use crate::host_channels::GateRefusal;
749753 pub(crate) use websocket::WebSocketService;
750754 pub use websocket::*;
751755 use websocket::{
@@ -947,41 +951,6 @@
947951 }
948952 }
949953
950-/// Why the output gate did not release a ticket.
951-enum GateRefusal {
952- /// The process installed no gate channel. A write must still fail closed
953- /// here: an acknowledgement nobody can prove is the loss this gate exists
954- /// to prevent.
955- NoChannel,
956- /// The core answered, and the answer is that the write is not durable.
957- Unproven(celld_logic::RequestError),
958- /// The shell dropped the ticket before the core answered.
959- Dropped,
960- /// A facet's write never reached a database a proof can cover.
961- Unpersisted(String),
962-}
963-
964-impl std::fmt::Display for GateRefusal {
965- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966- match self {
967- GateRefusal::NoChannel => f.write_str("no output-gate channel"),
968- GateRefusal::Unproven(error @ celld_logic::RequestError::DurabilityUnproven) => {
969- write!(
970- f,
971- "the write this request follows is not durable ({error:?})"
972- )
973- }
974- GateRefusal::Unproven(error) => {
975- write!(f, "the output gate refused the ticket ({error:?})")
976- }
977- GateRefusal::Dropped => f.write_str("output gate dropped"),
978- GateRefusal::Unpersisted(error) => {
979- write!(f, "the facet's write did not reach its database ({error})")
980- }
981- }
982- }
983-}
984-
985954 /// Take one ticket on the output gate and wait for the core's verdict.
986955 ///
987956 /// This is the output gate applied to an in-handler effect rather than to the
@@ -1010,31 +979,17 @@
1010979 (cell, channel, None, observed, epoch)
1011980 }
1012981 };
1013- let (tx, receive) = tokio::sync::oneshot::channel();
1014- let sent = GATE_TX
1015- .get()
1016- .map(|gate| {
1017- gate.send(GateReq {
1018- scope: cell,
1019- ticket: crate::actor::GateTicket {
1020- channel,
1021- position,
1022- observed,
1023- epoch,
1024- },
1025- reply: tx,
1026- })
1027- .is_ok()
1028- })
1029- .unwrap_or(false);
1030- if !sent {
1031- return Err(GateRefusal::NoChannel);
1032- }
1033- match receive.await {
1034- Ok(Ok(())) => Ok(()),
1035- Ok(Err(error)) => Err(GateRefusal::Unproven(error)),
1036- Err(_) => Err(GateRefusal::Dropped),
1037- }
982+ crate::host_channels::request_gate(
983+ GATE_TX.get(),
984+ cell,
985+ crate::actor::GateTicket {
986+ channel,
987+ position,
988+ observed,
989+ epoch,
990+ },
991+ )
992+ .await
1038993 }
1039994
1040995 /// Wait for the writes an outbound effect can reveal to be proven durable
@@ -1063,11 +1018,13 @@
10631018 request: T,
10641019 missing: &'static str,
10651020 ) -> std::result::Result<(), String> {
1066- await_egress_gate(gate).await?;
1067- match channel.get() {
1068- Some(tx) if tx.send(request).is_ok() => Ok(()),
1069- _ => Err(missing.to_string()),
1070- }
1021+ crate::host_channels::send_after_gate(
1022+ await_egress_gate(gate),
1023+ || channel.get(),
1024+ request,
1025+ missing,
1026+ )
1027+ .await
10711028 }
10721029
10731030 /// One `celld_logic::gate::InputGate` per cell.
@@ -3452,13 +3409,24 @@
34523409 send_and_end(tc, &self.context, reply, outcome)
34533410 }
34543411 Answer::WsMessage(reply) => {
3455- let dispatch = self
3456- .gate_positions()
3457- .map(|(write_position, observed_position)| WsDispatch {
3458- frames: ws_capture_take(),
3412+ // Taken before the sample, because the capture reserved each
3413+ // frame's place in its socket's queue when the script sent it.
3414+ // A failed sample authorizes no output, so its frames are
3415+ // discarded as a rejected handler's are. Left on the context,
3416+ // the reservation holds every later frame on the socket until
3417+ // the context drops, and then closes the socket with 1011.
3418+ let frames = ws_capture_take();
3419+ let dispatch = match self.gate_positions() {
3420+ Ok((write_position, observed_position)) => Ok(WsDispatch {
3421+ frames,
34593422 write_position,
34603423 observed_position,
3461- });
3424+ }),
3425+ Err(error) => {
3426+ frames.discard();
3427+ Err(error)
3428+ }
3429+ };
34623430 send_and_end(tc, &self.context, reply, dispatch)
34633431 }
34643432 Answer::Ack(reply) => send_and_end(tc, &self.context, reply, self.write_delta()),
@@ -4431,6 +4399,13 @@
44314399 let _cpu_watchdog = cpu_watchdog_for_context(tc, &entry.context);
44324400 settle(tc, entry);
44334401 tc.perform_microtask_checkpoint();
4402+ // V8 schedules FinalizationRegistry cleanup as a foreground task,
4403+ // not a microtask. Without driving that queue, collected loader
4404+ // lifetimes never release their host registry entries. Run one task
4405+ // per turn under the same CPU watchdog, so cleanup cannot monopolize
4406+ // the isolate by continually scheduling more foreground work.
4407+ v8::Platform::pump_message_loop(&v8::V8::get_current_platform(), tc, false);
4408+ tc.perform_microtask_checkpoint();
44344409 }
44354410 if let Err(error) = finish_cpu_turn(tc, entry) {
44364411 let error = take_execution_termination_in_context(tc, Some(&entry.context))
@@ -5346,6 +5321,7 @@
53465321 ws_id,
53475322 data,
53485323 reply,
5324+ ..
53495325 } => start_cell_event(
53505326 tc,
53515327 &scope,
@@ -6132,7 +6108,7 @@
61326108 cell: &str,
61336109 parent: &storage::StorageIdentity,
61346110 name: &str,
6135- id: &str,
6111+ id_sc: Vec<u8>,
61366112 props_sc: Vec<u8>,
61376113 file: (std::path::PathBuf, bool),
61386114 ) -> Result<Option<i64>> {
@@ -6158,7 +6134,7 @@
61586134 parent,
61596135 name,
61606136 EmbeddedStartup {
6161- id,
6137+ id_sc,
61626138 props_sc,
61636139 path,
61646140 restored,
@@ -6779,6 +6755,7 @@
67796755 "__response_stream_closed" => op_response_stream_closed,
67806756 "__response_stream_close" => op_response_stream_close,
67816757 "__op_timer" => op_timer,
6758+ "__isolate_condemn" => op_isolate_condemn,
67826759 "__timer_alloc" => op_timer_alloc,
67836760 "__io_context_id" => op_io_context_id,
67846761 "__with_input_gate_context" => op_with_input_gate_context,
@@ -7166,10 +7143,22 @@
71667143 // and invokes it. The loaded isolate uses the same turn driver as every
71677144 // stateless Worker, so an awaited operation holds no thread or isolate.
71687145
7169-// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
7170-// module bytes, 1 MiB env. Messages match so the conformance cases pass.
7171-const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
7146+// Default to workerd's module-byte ceiling. A fleet operator may admit larger
7147+// compiled runtimes; loaded guest code cannot change this host policy.
7148+const DEFAULT_MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
71727149 const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
7150+
7151+fn dynamic_worker_code_limit() -> usize {
7152+ static LIMIT: OnceLock<usize> = OnceLock::new();
7153+ *LIMIT.get_or_init(|| {
7154+ crate::env_vars::positive_or(
7155+ "CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES",
7156+ DEFAULT_MAX_DYNAMIC_WORKER_CODE_SIZE,
7157+ )
7158+ .expect("validated CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES")
7159+ })
7160+}
7161+
71737162 /// The largest `props` value one loaded entrypoint or Durable Object class can
71747163 /// carry, as structured-clone bytes. Workerd does not impose this bound, but
71757164 /// celld holds the value on a host job for the whole call. The harness shares
@@ -7437,12 +7426,13 @@
74377426 ModuleSource::Wasm(bytes) => bytes.len(),
74387427 })
74397428 .sum::<usize>();
7440- if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
7429+ let max_code_bytes = dynamic_worker_code_limit();
7430+ if code_size > max_code_bytes {
74417431 return loader_throw(
74427432 scope,
74437433 &format!(
74447434 "Dynamic Worker code size ({code_size} bytes) exceeds the \
7445- maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
7435+ maximum allowed size of {max_code_bytes} bytes."
74467436 ),
74477437 );
74487438 }
@@ -7866,7 +7856,7 @@
78667856 parent_scope: String,
78677857 owner: String,
78687858 name: String,
7869- id: String,
7859+ id_sc: Vec<u8>,
78707860 props_sc: Vec<u8>,
78717861 parent: storage::StorageIdentity,
78727862 }
@@ -7926,7 +7916,162 @@
79267916 }
79277917 }
79287918
7919+/// The facets that each root runs in loaded Workers' isolates, by the root's
7920+/// cell and epoch.
7921+///
7922+/// A loaded Worker can outlive a root through another stub or until garbage
7923+/// collection. Neither lifetime tells the loaded isolate when a root stops,
7924+/// so connection closure cannot depend on collection. The root's own
7925+/// `facets._release()` invalidates its stubs synchronously: the give-back
7926+/// turn cannot drive an asynchronous abort. Previously, each reactivation
7927+/// left a connection open on an unlinked file, with the facet's JavaScript
7928+/// state. The adoption turn records each facet here, and the root's
7929+/// give-back closes them.
7930+///
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.
7934+static ROOT_FACETS: OnceLock<Mutex<HashMap<(String, u64), RootFacets>>> = OnceLock::new();
7935+
7936+fn root_facets() -> std::sync::MutexGuard<'static, HashMap<(String, u64), RootFacets>> {
7937+ ROOT_FACETS
7938+ .get_or_init(Mutex::default)
7939+ .lock()
7940+ .expect("root facets poisoned")
7941+}
7942+
7943+#[derive(Default)]
7944+struct RootFacets {
7945+ /// Facet calls between their start and their adoption turn. The entry
7946+ /// lives while one runs, so a call that adopts after the root stopped
7947+ /// finds `stopped` rather than a fresh entry.
7948+ pending: usize,
7949+ /// The root gave its residency back and does not run again at this
7950+ /// epoch, so no facet of it can be adopted.
7951+ stopped: bool,
7952+ /// Each slot keeps its loaded isolate alive until the release closes
7953+ /// the facet in it.
7954+ open: Vec<(Arc<crate::pool::Slot>, String)>,
7955+}
7956+
7957+/// One facet call of a root, from its start until its adoption turn.
7958+struct PendingFacet {
7959+ key: (String, u64),
7960+}
7961+
7962+impl PendingFacet {
7963+ fn begin(root: &str, epoch: u64) -> Result<Self, String> {
7964+ let key = (root.to_string(), epoch);
7965+ let mut roots = root_facets();
7966+ let entry = roots.entry(key.clone()).or_default();
7967+ if entry.stopped {
7968+ return Err(format!("{root} epoch {epoch} stopped"));
7969+ }
7970+ entry.pending += 1;
7971+ Ok(Self { key })
7972+ }
7973+
7974+ /// Record the facet before its adoption. Call inside the adoption turn:
7975+ /// a release that takes the record queues its close behind this turn on
7976+ /// 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> {
7978+ let mut roots = root_facets();
7979+ let entry = roots
7980+ .get_mut(&self.key)
7981+ .expect("a pending facet keeps its entry");
7982+ if entry.stopped {
7983+ return Err(format!("{} epoch {} stopped", self.key.0, self.key.1));
7984+ }
7985+ if !entry
7986+ .open
7987+ .iter()
7988+ .any(|(open, name)| Arc::ptr_eq(open, slot) && name == scope)
7989+ {
7990+ entry.open.push((slot.clone(), scope.to_string()));
7991+ }
7992+ Ok(())
7993+ }
7994+}
7995+
7996+impl Drop for PendingFacet {
7997+ fn drop(&mut self) {
7998+ let mut roots = root_facets();
7999+ if let Some(entry) = roots.get_mut(&self.key) {
8000+ entry.pending -= 1;
8001+ if entry.pending == 0 && entry.open.is_empty() {
8002+ roots.remove(&self.key);
8003+ }
8004+ }
8005+ }
8006+}
8007+
8008+/// How a root leaves the isolate that runs it.
8009+#[derive(Clone, Copy)]
8010+pub(crate) enum RootRelease {
8011+ /// The root stops at this epoch: its facets close, and none opens again.
8012+ Stop,
8013+ /// The root restarts at the same epoch on another generation. It builds
8014+ /// a new facet manager there, so the facets of this one close, but the
8015+ /// new instance can open its own.
8016+ ///
8017+ /// A call of the old instance can still adopt after this release, and
8018+ /// that is bounded. The facet ops read the root's storage identity
8019+ /// synchronously, and the give-back closed that storage, so only a call
8020+ /// that started before the swap turn gets here. It records under the
8021+ /// same root and epoch, so the root's next release closes it. Marking
8022+ /// the epoch stopped instead would refuse the new instance's facets.
8023+ Swap,
8024+}
8025+
8026+/// Close each facet that `root` runs in a loaded Worker's isolate. The
8027+/// caller gives the root back first, so the root cannot start a facet call
8028+/// after the facets are taken.
8029+pub(crate) async fn release_root_facets(root: &str, epoch: u64, release: RootRelease) {
8030+ let key = (root.to_string(), epoch);
8031+ let open = {
8032+ let mut roots = root_facets();
8033+ let Some(entry) = roots.get_mut(&key) else {
8034+ return;
8035+ };
8036+ if matches!(release, RootRelease::Stop) {
8037+ entry.stopped = true;
8038+ }
8039+ let open = std::mem::take(&mut entry.open);
8040+ if entry.pending == 0 {
8041+ roots.remove(&key);
8042+ }
8043+ open
8044+ };
8045+ // A nested facet records after its parent, so it closes first.
8046+ for (slot, scope) in open.into_iter().rev() {
8047+ if let Err(error) = slot.turn(|worker| worker.own_cell(&scope, None)).await {
8048+ tracing::warn!(root, epoch, facet = %scope, %error, "a facet did not close with its root");
8049+ }
8050+ }
8051+}
8052+
8053+/// Drop an aborted facet's record, which its abort closed already.
8054+fn forget_root_facet(root: &str, epoch: u64, slot: &Arc<crate::pool::Slot>, scope: &str) {
8055+ let key = (root.to_string(), epoch);
8056+ let mut roots = root_facets();
8057+ if let Some(entry) = roots.get_mut(&key) {
8058+ entry
8059+ .open
8060+ .retain(|(open, name)| !(Arc::ptr_eq(open, slot) && name == scope));
8061+ if entry.pending == 0 && entry.open.is_empty() {
8062+ roots.remove(&key);
8063+ }
8064+ }
8065+}
8066+
79298067 async fn prepare_facet(host: FacetHost, start: FacetStart) -> Result<LoadedFacet, String> {
8068+ let pending = match host {
8069+ FacetHost::Loaded(_) => Some(PendingFacet::begin(
8070+ &start.parent.root_scope,
8071+ start.parent.epoch,
8072+ )?),
8073+ FacetHost::Own(_) => None,
8074+ };
79308075 let slot = host.slot().await?;
79318076 let file = open_facet_file(&start.parent, &start.name).await?;
79328077 let mut names = start.parent.facet_path.clone();
@@ -7940,14 +8085,19 @@
79408085 &start.name,
79418086 );
79428087 slot.turn(|worker| {
7943- worker.own_embedded_cell(
7944- &scope,
7945- &start.parent,
7946- &start.name,
7947- &start.id,
7948- start.props_sc,
7949- file,
7950- )
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}"))
79518101 })
79528102 .await
79538103 .map_err(|error| format!("worker loader facet: {error}"))?;
@@ -7969,7 +8119,9 @@
79698119 let parent_scope = args.get(2).to_rust_string_lossy(scope);
79708120 let owner = args.get(3).to_rust_string_lossy(scope);
79718121 let name = args.get(4).to_rust_string_lossy(scope);
7972- let facet_id = args.get(5).to_rust_string_lossy(scope);
8122+ let Some(id_sc) = view_bytes(args.get(5)) else {
8123+ return loader_throw(scope, "facet identity is not a typed array");
8124+ };
79738125 let props_sc = match loader_props_bytes(args.get(6)) {
79748126 Ok(props) => props,
79758127 Err(error) => return loader_throw(scope, &error),
@@ -7996,7 +8148,7 @@
79968148 parent_scope,
79978149 owner,
79988150 name,
7999- id: facet_id,
8151+ id_sc,
80008152 props_sc,
80018153 parent,
80028154 },
@@ -8049,7 +8201,9 @@
80498201 let parent_scope = args.get(2).to_rust_string_lossy(scope);
80508202 let owner = args.get(3).to_rust_string_lossy(scope);
80518203 let name = args.get(4).to_rust_string_lossy(scope);
8052- let facet_id = args.get(5).to_rust_string_lossy(scope);
8204+ let Some(id_sc) = view_bytes(args.get(5)) else {
8205+ return loader_throw(scope, "facet identity is not a typed array");
8206+ };
80538207 let props_sc = match loader_props_bytes(args.get(6)) {
80548208 Ok(props) => props,
80558209 Err(error) => return loader_throw(scope, &error),
@@ -8098,7 +8252,7 @@
80988252 parent_scope,
80998253 owner,
81008254 name,
8101- id: facet_id,
8255+ id_sc,
81028256 props_sc,
81038257 parent,
81048258 },
@@ -8154,11 +8308,22 @@
81548308 let name = args.get(4).to_rust_string_lossy(scope);
81558309 let host = FacetHost::of(loader);
81568310 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.
8313+ let root = storage::storage_identity(&parent_scope)
8314+ .ok()
8315+ .flatten()
8316+ .map(|parent| (parent.root_scope, parent.epoch));
81578317 let async_id = asyncrt::enqueue(async move {
8158- let slot = host?.slot().await?;
8318+ let host = host?;
8319+ let loaded = matches!(host, FacetHost::Loaded(_));
8320+ let slot = host.slot().await?;
81598321 slot.turn(|worker| worker.own_cell(&facet_scope, None))
81608322 .await
81618323 .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);
8326+ }
81628327 Ok(Vec::new())
81638328 });
81648329 rv.set(promise_for(scope, async_id));
@@ -8215,9 +8380,9 @@
82158380 rv.set(promise_for(scope, async_id));
82168381 }
82178382
8218-/// `__loader_drop(id)` — evict a loaded worker. Called from a
8219-/// FinalizationRegistry when its stub is GC'd. Removing the registry entry
8220-/// drops the isolate after any calls that already cloned its load state end.
8383+/// `__loader_drop(id)` — release the loader's ownership on explicit disposal
8384+/// or collection of the shared JavaScript load lifetime. In-flight calls and
8385+/// root facet records retain their own references until they finish.
82218386 fn op_loader_drop(
82228387 scope: &mut v8::PinScope,
82238388 args: v8::FunctionCallbackArguments,
@@ -9591,14 +9756,11 @@
95919756 if let Some(context) = current_reaction_or_untracked_io_context(scope) {
95929757 context.record_tail_log(&level, &body);
95939758 }
9594- let displayed = match level.as_str() {
9595- "error" => format!("ERROR {body}"),
9596- "warn" => format!("WARN {body}"),
9597- _ => body,
9598- };
95999759 // Correlated by CPED, so a continuation logging after an await — or
96009760 // another entry's continuation running in this turn's checkpoint —
96019761 // lands on the trace that owns it, not on whoever holds the isolate.
9762+ // The record carries the level as its severity, so its body omits the
9763+ // prefix that the console line needs.
96029764 if crate::telemetry::active() {
96039765 if let Some(ids) =
96049766 current_trace_context(scope).and_then(crate::telemetry::TraceContext::recording_ids)
@@ -9607,12 +9769,41 @@
96079769 trace_id: Some(ids.trace_id),
96089770 span_id: Some(ids.span_id),
96099771 time_unix_us: crate::telemetry::now_unix_us(),
9610- body: displayed.clone(),
9772+ severity: crate::telemetry::Severity::from_console_level(&level),
9773+ body: body.clone(),
96119774 });
96129775 }
96139776 }
9777+ let displayed = match level.as_str() {
9778+ "error" => format!("ERROR {body}"),
9779+ "warn" => format!("WARN {body}"),
9780+ _ => body,
9781+ };
96149782 tracing::info!(target: "cell_console", "{}", displayed);
96159783 }
9784+/// `__isolate_condemn(reason)` -> whether this isolate will be replaced.
9785+///
9786+/// The guest's own verdict that it cannot run here again: the Python bundle
9787+/// calls it from Pyodide's fatal hook, where Cloudflare aborts the isolate.
9788+/// It condemns only the isolate running the call, so a guest can cost itself
9789+/// a cold start and nothing else. `false` for a Dynamic Worker, whose slot
9790+/// has no pool to replace it.
9791+fn op_isolate_condemn(
9792+ scope: &mut v8::PinScope,
9793+ args: v8::FunctionCallbackArguments,
9794+ mut rv: v8::ReturnValue<v8::Value>,
9795+) {
9796+ let mut reason = args.get(0).to_rust_string_lossy(scope);
9797+ // The reason is guest text bound for the node log.
9798+ if let Some((cut, _)) = reason.char_indices().nth(MAX_CONDEMN_REASON_CHARS) {
9799+ reason.truncate(cut);
9800+ }
9801+ let condemned = crate::pool::current_slot().is_some_and(|slot| slot.condemn(&reason));
9802+ rv.set(v8::Boolean::new(scope, condemned).into());
9803+}
9804+
9805+const MAX_CONDEMN_REASON_CHARS: usize = 256;
9806+
96169807 fn op_heap_limit_excessively_exceeded(
96179808 scope: &mut v8::PinScope,
96189809 _args: v8::FunctionCallbackArguments,
modifiedcrates/celld/js/bootstrap.rs+7−5View file
@@ -911,8 +911,8 @@
911911 finish_cell_adoption(tc, cell, owned)
912912 }
913913
914-pub(super) struct EmbeddedStartup<'a> {
915- pub id: &'a str,
914+pub(super) struct EmbeddedStartup {
915+ pub id_sc: Vec<u8>,
916916 pub props_sc: Vec<u8>,
917917 pub path: std::path::PathBuf,
918918 pub restored: bool,
@@ -923,7 +923,7 @@
923923 cell: &str,
924924 parent: &storage::StorageIdentity,
925925 name: &str,
926- startup: EmbeddedStartup<'_>,
926+ startup: EmbeddedStartup,
927927 compat: Compat,
928928 ) -> Result<Option<i64>> {
929929 storage::open_embedded(
@@ -948,8 +948,10 @@
948948 .ok_or_else(|| anyhow!("missing facet config registry"))?;
949949 let config = v8::Object::new(tc);
950950 let id_key = v8::String::new(tc, "id").unwrap();
951- let id_value = v8::String::new(tc, startup.id).unwrap();
952- config.set(tc, id_key.into(), id_value.into());
951+ let id_value =
952+ storage_ops::deserialize_storage_value(tc, storage::StoredValue::V8(startup.id_sc))
953+ .ok_or_else(|| anyhow!("decode facet identity"))?;
954+ config.set(tc, id_key.into(), id_value);
953955 let props = if startup.props_sc.is_empty() {
954956 v8::undefined(tc).into()
955957 } else {
modifiedcrates/celld/js/harness.js+90−36View file
@@ -238,6 +238,14 @@
238238 ];
239239 }
240240 }
241+// Body streams expose the standard constructor to consumers. In particular,
242+// the Python Workers SDK validates JS body types by constructor.name.
243+// Keep the internal prototypes and their specialized read/tee behavior.
244+for (const bodyStream of [CelldBodyStream, CelldHttpBodyStream]) {
245+ Object.defineProperty(bodyStream.prototype, "constructor", {
246+ value: ReadableStream, writable: true, configurable: true,
247+ });
248+}
241249 globalThis.Response = class Response {
242250 constructor(body, init = {}) {
243251 // Streaming/iterable detection runs only for object bodies, so
@@ -2092,15 +2100,37 @@
20922100 // here is a bag nothing validated, and reading one key out of it is how every
20932101 // other key came to be dropped in silence. The loader stub validates the bag
20942102 // and encodes its value before it creates the class.
2095-const __makeDurableObjectClass = (idPromise, name, propsSc) => {
2103+const __makeDurableObjectClass = (loadPromise, name, propsSc) => {
20962104 const value = {};
20972105 __durableClassMeta.set(value, {
2098- idPromise,
2106+ loadPromise,
20992107 name: name === null || name === undefined ? "default" : String(name),
21002108 propsSc,
21012109 });
21022110 return value;
21032111 };
2112+// Loopback classes are callable; a specialized class is only a handle. Capture
2113+// props now, so later mutation of the caller's options cannot change startup.
2114+const __makeLoopbackDurableObjectClass = (name) => {
2115+ const loadPromise = Promise.resolve({ id: 0 });
2116+ const specialize = function(options) {
2117+ if (arguments.length === 0)
2118+ throw new TypeError("DurableObjectClass requires an options argument.");
2119+ if (options !== undefined && options !== null &&
2120+ typeof options !== "object" && typeof options !== "function")
2121+ throw new TypeError("DurableObjectClass options must be an object.");
2122+ const props = options?.props;
2123+ if (props !== undefined &&
2124+ (props === null || (typeof props !== "object" && typeof props !== "function")))
2125+ throw new TypeError("DurableObjectClass props must be an object.");
2126+ return __makeDurableObjectClass(
2127+ loadPromise, name, __rpcOut(props === undefined ? {} : props, false));
2128+ };
2129+ __durableClassMeta.set(specialize, {
2130+ loadPromise, name, propsSc: __rpcOut({}, false),
2131+ });
2132+ return specialize;
2133+};
21042134 class DurableObjectFacets {
21052135 constructor(state) {
21062136 this._state = state;
@@ -2142,11 +2172,14 @@
21422172 if (meta === undefined)
21432173 throw new TypeError(
21442174 "FacetStartupOptions.class must be a DurableObjectClass.");
2145- const loader = await meta.idPromise;
2146- const id = options.id instanceof DurableObjectId
2147- ? options.id.toString()
2148- : options.id === undefined ? this._state.id.toString() : String(options.id);
2149- return [loader, meta.name, id, meta.propsSc];
2175+ const { id: loader } = await meta.loadPromise;
2176+ const id = options.id === undefined ? this._state.id : options.id;
2177+ // Keep the ID kind and name in one clone. A string round-trip erases
2178+ // named IDs and turns a literal string ID into a DurableObjectId.
2179+ const idSc = __sc_encode(id instanceof DurableObjectId
2180+ ? [id._className, id.toString(), id.name] : String(id));
2181+ // Keep the load alive after the startup callback and class are gone.
2182+ return [loader, meta.name, idSc, meta.propsSc, meta];
21502183 });
21512184 const invoke = async (operation) => {
21522185 if (record.aborted) throw record.error;
@@ -2233,8 +2266,16 @@
22332266 barrier.then(clear, () => {});
22342267 }
22352268 _release() {
2236- for (const name of Array.from(this._running.keys()))
2237- this._abort(name, new Error("The parent Durable Object was released."));
2269+ // The host closes these facets during give-back. Queuing _abort here
2270+ // leaves an undriven op whose promise retains the manager, its root,
2271+ // and the loaded classes after the root has stopped.
2272+ const reason = new Error("The parent Durable Object was released.");
2273+ for (const record of this._running.values()) {
2274+ record.aborted = true;
2275+ record.error = reason;
2276+ }
2277+ this._running.clear();
2278+ this._barriers.clear();
22382279 }
22392280 }
22402281 // The reason a failed critical section gives its waiters. It must not throw:
@@ -2546,10 +2587,11 @@
25462587 this._facetDepth = facet?.depth ?? 0;
25472588 const separator = scope.indexOf(":");
25482589 const className = separator < 0 ? scope : scope.slice(0, separator);
2549- const value = facet?.id ?? (separator < 0 ? scope : scope.slice(separator + 1));
2550- this.id = new DurableObjectId(
2551- className, value, __cell.idNames[scope],
2552- );
2590+ this.id = facet === undefined
2591+ ? new DurableObjectId(
2592+ className, separator < 0 ? scope : scope.slice(separator + 1),
2593+ __cell.idNames[scope])
2594+ : typeof facet.id === "string" ? facet.id : new DurableObjectId(...facet.id);
25532595 this.props = facet?.props;
25542596 // A class outside `containers` has no `ctx.container`, which is what
25552597 // the `@cloudflare/containers` constructor checks.
@@ -3150,8 +3192,9 @@
31503192 const __outboundMeta = new WeakMap();
31513193 const __loaderServiceMarker = "__celld$loaderSvc";
31523194 __celld.__makeLoader = () => {
3153- // `get(name, ...)` is memoized by name to one isolate; `load()` is anonymous.
3154- // A stub holds a Promise<id> so `getCode` may be async and load lazily.
3195+ // A name weakly caches a shared load; `load()` is anonymous. Keep the load
3196+ // promise itself on every derived capability, including a running facet,
3197+ // so collection cannot evict a Worker while that capability still uses it.
31553198 const byName = new Map();
31563199 const loaderOptions = (method, options, supportsLimits) => {
31573200 if (options === null || options === undefined) return undefined;
@@ -3258,17 +3301,24 @@
32583301 },
32593302 });
32603303 };
3261- // Anonymous load() workers are evicted when their only stub is GC'd: the
3262- // finalizer drops the worker's isolate so it does not leak. Named get()
3263- // workers are retained by `byName` (memoized) and so are not registered.
3264- const finalizer = typeof FinalizationRegistry === "function"
3265- ? new FinalizationRegistry((id) => __loader_drop(id))
3266- : null;
3267- const makeStub = (loadPromise, evictable) => {
3268- // Explicit disposal evicts the worker deterministically; the finalizer is
3269- // a GC backstop for anonymous stubs that are dropped without disposing.
3270- // __loader_drop is idempotent, so the two paths cannot double-free.
3304+ // The load promise is the shared lifetime, retained by stubs, entrypoints,
3305+ // classes, and running facets. Finalizing only the original stub can evict
3306+ // a Worker that one of its derived capabilities still uses.
3307+ const finalizer = new FinalizationRegistry(({ id, name, ref }) => {
3308+ if (ref !== undefined && byName.get(name) === ref) byName.delete(name);
3309+ if (id !== undefined) __loader_drop(id);
3310+ });
3311+ const track = (loadPromise, name, ref) => {
3312+ // Register before settlement, so failed loads also release their names.
3313+ const held = { id: undefined, name, ref };
3314+ finalizer.register(loadPromise, held, loadPromise);
3315+ loadPromise.then(({ id }) => { held.id = id; }, () => {});
3316+ return loadPromise;
3317+ };
3318+ const makeStub = (loadPromise, name, ref) => {
32713319 const drop = () => {
3320+ if (ref !== undefined && byName.get(name) === ref) byName.delete(name);
3321+ finalizer.unregister(loadPromise);
32723322 loadPromise.then(({ id }) => __loader_drop(id), () => {});
32733323 };
32743324 const stub = {
@@ -3280,14 +3330,11 @@
32803330 },
32813331 getDurableObjectClass(name = null, options = {}) {
32823332 return __makeDurableObjectClass(
3283- loadPromise.then(({ id }) => id), name,
3284- loaderPropsSc("getDurableObjectClass", options));
3333+ loadPromise, name, loaderPropsSc("getDurableObjectClass", options));
32853334 },
32863335 dispose: drop,
32873336 };
32883337 if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop;
3289- if (evictable && finalizer)
3290- loadPromise.then(({ id }) => finalizer.register(stub, id), () => {});
32913338 return stub;
32923339 };
32933340 // JSON.stringify silently drops binary values, so each non-string module --
@@ -3450,14 +3497,17 @@
34503497 return { id, tails };
34513498 });
34523499 return {
3453- load(code) { return makeStub(loadFrom(() => code), true); },
3500+ load(code) { return makeStub(track(loadFrom(() => code))); },
34543501 get(name, getCode) {
3455- let idPromise = byName.get(name);
3456- if (idPromise === undefined) {
3457- idPromise = loadFrom(getCode);
3458- byName.set(name, idPromise);
3502+ let ref = byName.get(name);
3503+ let loadPromise = ref?.deref();
3504+ if (loadPromise === undefined) {
3505+ loadPromise = loadFrom(getCode);
3506+ ref = new WeakRef(loadPromise);
3507+ byName.set(name, ref);
3508+ track(loadPromise, name, ref);
34593509 }
3460- return makeStub(idPromise, false);
3510+ return makeStub(loadPromise, name, ref);
34613511 },
34623512 };
34633513 };
@@ -4928,7 +4978,7 @@
49284978 if (__runtimeClasses.has(name)) continue;
49294979 out[name] = Object.hasOwn(__cell.namespaceKeys, name)
49304980 ? __cell.makeNamespace(name)
4931- : __makeDurableObjectClass(Promise.resolve(0), name, undefined);
4981+ : __makeLoopbackDurableObjectClass(name);
49324982 }
49334983 return out;
49344984 })();
@@ -9260,6 +9310,10 @@
92609310 }
92619311 // Backing object for the `cloudflare:workflows` builtin module.
92629312 __celld.__cfWorkflows = { NonRetryableError };
9313+// `celld:python`, imported only by the Python Worker bundle.
9314+__celld.__pythonHost = {
9315+ condemnIsolate: (reason) => __isolate_condemn(String(reason)),
9316+};
92639317
92649318 const __wfValidInstanceId = (id) =>
92659319 typeof id === "string" && id.length >= 1 && id.length <= 100 &&
modifiedcrates/celld/js/modules.rs+16−5View file
@@ -181,6 +181,10 @@
181181 /// rejects, and a static import from a user module fails to link.
182182 const INTERNALS_SPECIFIER: &str = "celld:internals";
183183
184+/// The host module of the Python Worker bundle that `celld deploy` builds.
185+/// Its one export condemns the calling isolate; see `op_isolate_condemn`.
186+const PYTHON_HOST_SPECIFIER: &str = "celld:python";
187+
184188 /// One synthetic module per isolate whose default export is the internals
185189 /// object, built the first time a stub links.
186190 fn internals_module<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Module> {
@@ -230,11 +234,12 @@
230234 .expect("isolate has no module registry")
231235 }
232236
233-/// Is `spec` an external builtin (`node:*`, `cloudflare:*`, or a bare node
234-/// builtin)? esbuild bundles every npm dep inline and leaves only builtins
235-/// external, so a remaining bare specifier is a node builtin.
237+/// Is `spec` an external builtin (`node:*`, `cloudflare:*`, `celld:python`,
238+/// or a bare node builtin)? esbuild bundles every npm dep inline and leaves
239+/// only builtins external, so a remaining bare specifier is a node builtin.
236240 fn is_external(spec: &str) -> bool {
237- if spec.starts_with("node:") || spec.starts_with("cloudflare:") {
241+ if spec.starts_with("node:") || spec.starts_with("cloudflare:") || spec == PYTHON_HOST_SPECIFIER
242+ {
238243 return true;
239244 }
240245 // bare builtin, or a builtin submodule like `stream/promises`
@@ -567,6 +572,7 @@
567572 // subclass would make `throw new NonRetryableError(...)` throw a value
568573 // the retry policy cannot recognize — the step would retry, silently.
569574 let cf_workflows = spec == "cloudflare:workflows";
575+ let python_host = spec == PYTHON_HOST_SPECIFIER;
570576 let lazy = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec));
571577 let eager = eager_module_global(spec);
572578 let base = if cf {
@@ -575,6 +581,8 @@
575581 "__celld.__cfSockets".to_string()
576582 } else if cf_workflows {
577583 "__celld.__cfWorkflows".to_string()
584+ } else if python_host {
585+ "__celld.__pythonHost".to_string()
578586 } else if let Some(m) = lazy {
579587 format!("__celld.{}", m.global)
580588 } else if let Some(global) = eager {
@@ -913,6 +921,9 @@
913921 if spec == "cloudflare:workflows" {
914922 return Some("__celld.__cfWorkflows".into());
915923 }
924+ if spec == PYTHON_HOST_SPECIFIER {
925+ return Some("__celld.__pythonHost".into());
926+ }
916927 if let Some(module) = install_lazy_module(scope, spec) {
917928 return Some(format!("__celld.{}", module.global));
918929 }
@@ -968,7 +979,7 @@
968979 mut rv: v8::ReturnValue<v8::Value>,
969980 ) {
970981 let spec = args.get(0).to_rust_string_lossy(scope);
971- if spec.starts_with("cloudflare:") {
982+ if spec.starts_with("cloudflare:") || spec == PYTHON_HOST_SPECIFIER {
972983 return; // not a node builtin
973984 }
974985 let Some(expr) = builtin_source(scope, &spec) else {
modifiedcrates/celld/js/websocket.rs+8−11View file
@@ -12,7 +12,7 @@
1212
1313 #[derive(Default)]
1414 pub(super) struct WsCapture {
15- frames: Vec<(u64, WsOut)>,
15+ frames: WsBatch,
1616 /// The handler whose outcome authorizes an incremental flush. This is
1717 /// installed after the synchronous dispatch returns its promise; until
1818 /// then no turn-end flush can run.
@@ -93,7 +93,7 @@
9393 .promise = Some(promise);
9494 }
9595
96-pub(super) fn ws_capture_take() -> Vec<(u64, WsOut)> {
96+pub(super) fn ws_capture_take() -> WsBatch {
9797 current_context()
9898 .ws_capture
9999 .lock()
@@ -104,7 +104,9 @@
104104 }
105105
106106 pub(super) fn ws_capture_discard(context: &IoContext) {
107- context.ws_capture.lock().unwrap().pop();
107+ if let Some(capture) = context.ws_capture.lock().unwrap().pop() {
108+ capture.frames.discard();
109+ }
108110 }
109111
110112 /// Release what a running `webSocketMessage` handler has sent so far.
@@ -144,7 +146,7 @@
144146 // `settle`. Drop its frames now instead of publishing output
145147 // from a failed dispatch.
146148 v8::PromiseState::Rejected => {
147- capture.last_mut().unwrap().frames.clear();
149+ std::mem::take(&mut capture.last_mut().unwrap().frames).discard();
148150 return;
149151 }
150152 }
@@ -157,17 +159,12 @@
157159 // Every captured frame belongs to a hibernatable socket, because that is
158160 // what `ws_emit` captures, so one channel names the whole batch.
159161 let gate = egress_gate_request(context, celld_logic::Channel::WsHibernatable);
160- let flush = ws_flush_state();
161- let registry = ws_registry();
162- let Some(flushing) = flush.emit_or_defer(&registry, frames, gate.is_gated()) else {
163- return;
164- };
165162 // On the HOST runtime, for the reason `ws_emit` spawns there: this flush
166163 // must outlive the turn that produced the frames, and the ticket it waits
167164 // for resolves with no isolate involvement.
168165 asyncrt::op_handle().spawn(async move {
169166 let held = await_egress_gate(gate).await;
170- flushing.release(&registry, held);
167+ frames.release(held);
171168 });
172169 }
173170
@@ -190,7 +187,7 @@
190187 fn ws_emit(context: &Arc<IoContext>, id: u64, out: WsOut) {
191188 let mut capture = context.ws_capture.lock().unwrap();
192189 if !capture.is_empty() && ws_channel(id) == celld_logic::Channel::WsHibernatable {
193- capture.last_mut().unwrap().frames.push((id, out));
190+ capture.last_mut().unwrap().frames.capture(id, out);
194191 let runtime_state = context
195192 .continuation
196193 .as_ref()
modifiedcrates/celld/lib.rs+1−0View file
@@ -324,6 +324,7 @@
324324 }
325325 pub mod bucket;
326326 pub mod cell_cli;
327+pub mod cell_dispatch;
327328 mod cell_host;
328329 pub mod cell_runtime;
329330 pub mod clean_reload;
modifiedcrates/celld/ltx_repl.rs+538−52View file
@@ -919,6 +919,151 @@
919919 complete: AtomicBool,
920920 }
921921
922+/// How long a read of a stream's retired mark answers coverage questions
923+/// before the next question reads it again.
924+const RETIRED_MARK_TTL_MS: u64 = 5 * 60 * 1000;
925+
926+/// How long a read that found no retired mark answers before the next
927+/// question reads it again. A mark is read only for a stream this node does
928+/// not hold and only for a row its per-cell prefix does not cover, which is
929+/// rare outside recovery, so a short wait costs little; it bounds how long a
930+/// node keeps the rows of an epoch another owner retired.
931+const RETIRED_MARK_ABSENT_TTL_MS: u64 = 30 * 1000;
932+
933+/// Restores of an unowned snapshot before a missing object is an error. Each
934+/// retry lists the epochs again, so it fails only when the bucket keeps losing
935+/// an object that every fresh chain still needs.
936+const RESTORE_SNAPSHOT_ATTEMPTS: usize = 3;
937+
938+/// The body of `cells/<stream>/ltx/retired.json`.
939+#[derive(serde::Serialize, serde::Deserialize)]
940+struct RetiredMark {
941+ retired_below: u64,
942+}
943+
944+/// What one epoch-GC pass did for one stream.
945+#[derive(Debug, Clone, PartialEq, Eq)]
946+pub struct EpochGcOutcome {
947+ /// The chain's base; the stream's rows below it are covered.
948+ pub retired_below: u64,
949+ /// The epoch prefixes this pass deleted.
950+ pub deleted: Vec<u64>,
951+ /// No further pass for this activation can delete more.
952+ pub settled: bool,
953+}
954+
955+/// One superseded epoch below a stream's chain base.
956+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957+pub struct EpochBelowBase {
958+ pub listed: celld_logic::epoch_gc::ListedEpoch,
959+ /// Bytes under the epoch's prefix.
960+ pub bytes: u64,
961+}
962+
963+fn retired_mark_key(prefix: &str, cell: &str) -> celld_ltx::object_store::path::Path {
964+ celld_ltx::object_store::path::Path::from(format!("{prefix}cells/{cell}/ltx/retired.json"))
965+}
966+
967+/// Read one stream's retired mark from the bucket; `None` when it has none.
968+pub(crate) async fn read_retired_mark(
969+ store: &dyn ObjectStore,
970+ prefix: &str,
971+ cell: &str,
972+) -> anyhow::Result<Option<u64>> {
973+ match store.get(&retired_mark_key(prefix, cell)).await {
974+ Ok(result) => {
975+ let bytes = result.bytes().await?;
976+ Ok(Some(
977+ serde_json::from_slice::<RetiredMark>(&bytes)?.retired_below,
978+ ))
979+ }
980+ Err(celld_ltx::object_store::Error::NotFound { .. }) => Ok(None),
981+ Err(error) => Err(error.into()),
982+ }
983+}
984+
985+/// The most superseded epochs one owner pass summarizes and deletes. A cell
986+/// with thousands of them spends one listing per epoch, so a pass takes the
987+/// oldest few and the next pass continues.
988+const EPOCH_GC_EPOCHS_PER_PASS: usize = 64;
989+
990+/// A read-only view of one stream's epochs for epoch GC.
991+#[derive(Debug, Clone, PartialEq, Eq)]
992+pub struct EpochScan {
993+ /// The newest listed epoch.
994+ pub newest: u64,
995+ /// The restore chain over every listed epoch, oldest first.
996+ pub chain: Vec<u64>,
997+ /// The oldest listed epochs below the chain's base, ascending, at most
998+ /// the scan's bound.
999+ pub below: Vec<EpochBelowBase>,
1000+ /// More epochs below the base exist than the scan summarized.
1001+ pub more_below: bool,
1002+}
1003+
1004+/// Scan one stream's epochs the way a restore sees them: build the restore
1005+/// chain over every listed epoch with the restore code, require its restore
1006+/// plan to resolve, and summarize each epoch below its base. `None` when the
1007+/// stream has no epoch or no complete chain. The owner's pass and
1008+/// `celld cell gc --dry-run` share this, so the dry run reports what the
1009+/// owner would decide.
1010+pub async fn scan_epochs(
1011+ store: &dyn ObjectStore,
1012+ prefix: &str,
1013+ cell: &str,
1014+ max_below: usize,
1015+ client_for: impl Fn(u64) -> ObjectStoreClient,
1016+) -> anyhow::Result<Option<EpochScan>> {
1017+ use celld_ltx::object_store::path::Path as ObjPath;
1018+ use futures_util::StreamExt as _;
1019+ let base_path = ObjPath::from(format!("{prefix}cells/{cell}/ltx"));
1020+ let mut listed: Vec<u64> = store
1021+ .list_with_delimiter(Some(&base_path))
1022+ .await?
1023+ .common_prefixes
1024+ .iter()
1025+ .filter_map(|p| p.filename()?.strip_prefix('e')?.parse().ok())
1026+ .collect();
1027+ listed.sort_unstable();
1028+ let Some(&newest) = listed.last() else {
1029+ return Ok(None);
1030+ };
1031+ let clients = listed.iter().map(|e| (*e, client_for(*e))).collect();
1032+ let chain = match EpochChain::build(clients).await {
1033+ Ok(chain) => chain,
1034+ Err(celld_ltx::Error::TxNotAvailable) => return Ok(None),
1035+ Err(error) => return Err(error.into()),
1036+ };
1037+ if replica::calc_restore_plan(&chain, TXID(0)).await.is_err() {
1038+ return Ok(None);
1039+ }
1040+ let chain: Vec<u64> = chain.spans().into_iter().map(|(e, _)| e).collect();
1041+ let base = chain.first().copied().unwrap_or(newest);
1042+ let mut below = Vec::new();
1043+ let superseded: Vec<u64> = listed.into_iter().filter(|e| *e < base).collect();
1044+ let more_below = superseded.len() > max_below;
1045+ for epoch in superseded.into_iter().take(max_below) {
1046+ let path = ObjPath::from(format!("{prefix}cells/{cell}/ltx/e{epoch}"));
1047+ let mut objects = store.list(Some(&path));
1048+ let (mut newest_ms, mut bytes) = (0_u64, 0_u64);
1049+ while let Some(object) = objects.next().await {
1050+ let object = object?;
1051+ newest_ms = newest_ms.max(object.last_modified.timestamp_millis().max(0) as u64);
1052+ bytes = bytes.saturating_add(object.size);
1053+ }
1054+ below.push(EpochBelowBase {
1055+ listed: celld_logic::epoch_gc::ListedEpoch { epoch, newest_ms },
1056+ bytes,
1057+ });
1058+ }
1059+ Ok(Some(EpochScan {
1060+ newest,
1061+ chain,
1062+ below,
1063+ more_below,
1064+ }))
1065+}
1066+
9221067 pub struct LtxRepl {
9231068 /// Local root: cell dbs live at `watch/<cell>/ltx/e<epoch>/db.sqlite`.
9241069 watch: PathBuf,
@@ -1022,6 +1167,20 @@
10221167 /// second, and the retained backlog grew for the life of the process.
10231168 /// On 2026-09-03 a dead session's recovery read 209 of them.
10241169 covered_by_cell: Mutex<BTreeMap<(String, u64), u64>>,
1170+ /// Each stream's retired mark (`cells/<stream>/ltx/retired.json`) as
1171+ /// last read or written, with the monotonic time of that read. A
1172+ /// coverage question for a stream this node does not hold reads the mark
1173+ /// when the per-cell answer does not reach the row, so a read is reused
1174+ /// for [`RETIRED_MARK_TTL_MS`], or [`RETIRED_MARK_ABSENT_TTL_MS`] when it
1175+ /// found none; a mark only rises, so a stale one only under-reports and
1176+ /// keeps a row.
1177+ retired_marks: Mutex<BTreeMap<String, (Option<u64>, u64)>>,
1178+ /// How old the newest object of a superseded epoch must be before epoch
1179+ /// GC deletes the epoch, or `None` when epoch GC is off
1180+ /// (`CELLD_LTX_RETENTION_SECS`, unset or `0`). Deletion is off by default:
1181+ /// turning it on is the operator's decision, not a side effect of an
1182+ /// upgrade.
1183+ epoch_gc_grace_ms: Option<u64>,
10251184 /// The cell's TRUNCATE checkpoint threshold. Passive checkpoints never
10261185 /// shrink the WAL FILE, so after every periodic restart the capture's
10271186 /// tail read spans the stale high-water region — ~350 KB per sync on
@@ -1304,6 +1463,11 @@
13041463 durability_timeout_ms.saturating_mul(SNAPSHOT_BYTES_PER_MS),
13051464 ),
13061465 covered_by_cell: Mutex::new(BTreeMap::new()),
1466+ 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)),
13071471 truncate_pages: Some(
13081472 crate::env_vars::optional::<u32>("CELLD_LTX_TRUNCATE_PAGES")
13091473 .ok()
@@ -1450,40 +1614,100 @@
14501614 Self::all_cells_shipped_tiered(&cells) && self.dirty_tails.lock().unwrap().is_empty()
14511615 }
14521616
1453- /// Recovery's primitive: PUT one gathered L0 segment to the exact key
1454- /// the dead leader's own upload would have used. Idempotent by key.
14551617 /// The highest TXID the cell's per-cell prefix already covers, over
1456- /// every level. Recovery uses it to skip re-uploading rows the drain
1457- /// points (compaction, eviction sync) have already folded in — one
1458- /// LIST per level and cell instead of one PUT per historical row.
1459- pub async fn covered_txid(&self, cell: &str, epoch: u64) -> u64 {
1618+ /// every level, or `u64::MAX` for a retired epoch. The caller passes the
1619+ /// highest row it needs covered. Recovery uses the answer to skip
1620+ /// re-uploading rows the drain points (compaction, eviction sync) have
1621+ /// already folded in, bundle GC and the graceful seal's scan to decide
1622+ /// which bundle rows are safe to drop, and the compaction overlay to
1623+ /// skip rows the prefix holds.
1624+ ///
1625+ /// An epoch below the stream's retired mark is covered through every
1626+ /// txid: the chain's base holds all of its acknowledged rows, and epoch
1627+ /// GC may have deleted its prefix, so a listing would answer zero and
1628+ /// keep its bundles and re-upload its rows forever. The mark is read only
1629+ /// when the per-cell answer does not reach `needed`, so a covered row
1630+ /// costs no mark read on any fleet, and a mark read never stands between
1631+ /// a question and a per-cell answer that already settles it. Every node
1632+ /// reads the mark, whether or not it runs epoch GC itself: while a fleet
1633+ /// rolls the setting out, a node without it must still seal over, drop,
1634+ /// and not re-upload the rows of an epoch another node deleted. An
1635+ /// absent mark is cached for [`RETIRED_MARK_ABSENT_TTL_MS`], which bounds
1636+ /// how long such a node lags a new mark.
1637+ ///
1638+ /// A stream this node holds a handle for answers from its per-cell
1639+ /// watermark alone and reads no mark. A busy cell's bundle rows sit above
1640+ /// that watermark until the next drain point, so reading the mark there
1641+ /// would cost a GET on every bundle-GC tick for every active cell, on
1642+ /// every fleet. Holding the handle means the epoch is this node's current
1643+ /// one, or a fenced node's whose successor may have retired it, because
1644+ /// teardown is asynchronous; that answer is lower than the truth, which
1645+ /// keeps rows and is safe. Once the handle goes, its coverage moves to
1646+ /// the remembered watermark and the mark decides rows above it. The
1647+ /// compaction overlay therefore reads no mark while its cell is
1648+ /// resident, and a fenced compactor can write merged rows back under a
1649+ /// retired prefix; no restore reads a prefix below the base, and a later
1650+ /// owner pass deletes it again once the grace passes, measured from the
1651+ /// rewritten objects. The current owner keeps it when it is the epoch
1652+ /// just before its own, because a plan never deletes that epoch.
1653+ ///
1654+ /// This is safe only because the base holds every acknowledged row of
1655+ /// every epoch below it. A successor claims a cell only after the prior
1656+ /// owner's node-log session is recovered and sealed, and recovery puts
1657+ /// every acknowledged row in the per-cell prefix first, so the
1658+ /// successor's restore, and with it the base, contains those rows; a
1659+ /// local wake restores from the file its own rows were shipped from. A
1660+ /// recovery upload that lands after the seal can only repeat rows the
1661+ /// base already holds.
1662+ pub async fn covered_txid(&self, cell: &str, epoch: u64, needed: u64) -> u64 {
14601663 let key = (cell.to_string(), epoch);
1461- let resident = self
1462- .cells
1463- .lock()
1464- .unwrap()
1465- .get(&key)
1466- .map(|handle| percell_coverage(handle));
1664+ // Held is decided by the handle, not its value: a fresh cell that has
1665+ // not reached a drain point holds a zero watermark and must not fall
1666+ // through to the mark on every tick either.
1667+ let (held, resident) = {
1668+ let cells = self.cells.lock().unwrap();
1669+ let handle = cells.get(&key);
1670+ (
1671+ handle.is_some(),
1672+ handle
1673+ .map(|handle| percell_coverage(handle))
1674+ .filter(|covered| *covered > 0),
1675+ )
1676+ };
1677+ // A handoff snapshot raises the remembered watermark while the
1678+ // evicting handle is still resident, so the higher of the two holds.
14671679 let known = self.covered_by_cell.lock().unwrap().get(&key).copied();
1468- if let Some(covered) = resident.filter(|covered| *covered > 0).max(known) {
1680+ if held {
1681+ return resident.max(known).unwrap_or(0);
1682+ }
1683+ let covered = match resident.max(known) {
1684+ Some(covered) => covered,
1685+ // Nothing this process put there: a cell it never served, or one
1686+ // it has not shipped yet. Ask the bucket once, with one listing
1687+ // of the epoch's whole prefix rather than one per level, and
1688+ // remember the answer; the watermark only rises, so a remembered
1689+ // value never over-reports. A restarting node recovers thousands
1690+ // of cells it never served, so this listing, and a mark read for
1691+ // a row it does not cover, is its recovery cost.
1692+ None => match self.client_for(cell, epoch).max_txid_all_levels().await {
1693+ Ok(txid) => {
1694+ // Zero is a useful answer too: undrained cells otherwise
1695+ // force the same empty-prefix LIST on every GC tick. A
1696+ // read error is not zero coverage and must remain
1697+ // retryable.
1698+ self.note_covered(cell, epoch, txid.0);
1699+ txid.0
1700+ }
1701+ Err(_) => 0,
1702+ },
1703+ };
1704+ if covered >= needed {
14691705 return covered;
14701706 }
1471- // Nothing this process put there: a cell it never served, or one it
1472- // has not shipped yet. Ask the bucket once, with one listing of the
1473- // epoch's whole prefix rather than one per level, and remember the
1474- // answer; the watermark only rises, so a remembered value never
1475- // over-reports. A restarting node recovers thousands of cells it
1476- // never served, so this listing is its whole recovery cost.
1477- match self.client_for(cell, epoch).max_txid_all_levels().await {
1478- Ok(txid) => {
1479- // Zero is a useful answer too: undrained cells otherwise
1480- // force the same empty-prefix LIST on every GC tick. A read
1481- // error is not zero coverage and must remain retryable.
1482- self.note_covered(cell, epoch, txid.0);
1483- txid.0
1484- }
1485- Err(_) => 0,
1707+ if celld_logic::epoch_gc::retired(epoch, self.retired_mark(cell).await) {
1708+ return u64::MAX;
14861709 }
1710+ covered
14871711 }
14881712
14891713 /// Remember that the bucket holds this cell epoch through `txid`.
@@ -1493,6 +1717,222 @@
14931717 *entry = (*entry).max(txid);
14941718 }
14951719
1720+ fn retired_mark_key(&self, cell: &str) -> celld_ltx::object_store::path::Path {
1721+ retired_mark_key(&self.prefix, cell)
1722+ }
1723+
1724+ /// The stream's retired mark, by its exact stream name. A read error
1725+ /// answers the cached mark, or none: a missing mark keeps rows, which
1726+ /// costs space, never data.
1727+ pub async fn retired_mark(&self, cell: &str) -> Option<u64> {
1728+ let now = asyncrt::mono_ms();
1729+ if let Some((mark, read_at)) = self.retired_marks.lock().unwrap().get(cell) {
1730+ let ttl = if mark.is_some() {
1731+ RETIRED_MARK_TTL_MS
1732+ } else {
1733+ RETIRED_MARK_ABSENT_TTL_MS
1734+ };
1735+ if now.saturating_sub(*read_at) < ttl {
1736+ return *mark;
1737+ }
1738+ }
1739+ let Ok(mark) = read_retired_mark(self.store.as_ref(), &self.prefix, cell).await else {
1740+ // A failed read answers the cached mark and restarts its wait:
1741+ // 30 s with nothing cached, and 5 min for an expired cached mark,
1742+ // which a failed reread keeps. A store outage therefore does not
1743+ // cost a GET on every question, and a stale answer is only low.
1744+ return self.remember_retired(cell, None, now);
1745+ };
1746+ self.remember_retired(cell, mark, now)
1747+ }
1748+
1749+ /// Record that the stream's epochs below `below` are retired. The owner
1750+ /// writes this before it deletes any of them, so a prefix is never gone
1751+ /// while its bundle rows still look uncovered. The write is not
1752+ /// conditional: an owner that stalled after its checks can write an
1753+ /// older, lower base over a successor's mark. Every written base was a
1754+ /// real base once, so a lower mark only makes some rows look uncovered
1755+ /// again, which costs a re-upload and a later pass, not data.
1756+ async fn record_retired(&self, cell: &str, below: u64) -> anyhow::Result<()> {
1757+ let body = serde_json::to_vec(&RetiredMark {
1758+ retired_below: below,
1759+ })?;
1760+ self.store
1761+ .put(&self.retired_mark_key(cell), body.into())
1762+ .await
1763+ .map_err(|error| anyhow!("record retired epochs of {cell} below e{below}: {error}"))?;
1764+ self.remember_retired(cell, Some(below), asyncrt::mono_ms());
1765+ Ok(())
1766+ }
1767+
1768+ /// Cache a mark read or written at `at`. The cached value never falls,
1769+ /// because an older read racing a newer write must not lower it.
1770+ /// Returns the mark the cache now holds.
1771+ fn remember_retired(&self, cell: &str, mark: Option<u64>, at: u64) -> Option<u64> {
1772+ let mut marks = self.retired_marks.lock().unwrap();
1773+ let entry = marks.entry(cell.to_string()).or_insert((None, at));
1774+ entry.0 = entry.0.max(mark);
1775+ entry.1 = at;
1776+ entry.0
1777+ }
1778+
1779+ /// The epoch-GC grace in milliseconds, or `None` when epoch GC is off.
1780+ pub(crate) fn epoch_gc_grace_ms(&self) -> Option<u64> {
1781+ self.epoch_gc_grace_ms
1782+ }
1783+
1784+ /// The streams this node holds, with the epoch it holds each at.
1785+ pub(crate) fn resident_epochs(&self) -> Vec<(String, u64)> {
1786+ self.cells.lock().unwrap().keys().cloned().collect()
1787+ }
1788+
1789+ /// Delete one stream's superseded epoch prefixes, as the owner of
1790+ /// `epoch` (denoland/celld#240).
1791+ ///
1792+ /// The steps run in a fixed order, and the order is the fence:
1793+ ///
1794+ /// 1. Build the restore chain over every listed epoch, the owner's
1795+ /// included, with the restore code. Stop unless its newest span is
1796+ /// `epoch` and the chain's full restore plan resolves. The first
1797+ /// proves the owner's own opener is listed, so a successor that claims
1798+ /// the cell after step 2 lists it too and restores from a base at or
1799+ /// above this one. A successor that claimed before step 2 fails it.
1800+ /// 2. `confirm_owner`: read the ownership record and require this node
1801+ /// at `epoch`. Reading before step 1 would let a fenced owner delete
1802+ /// the base of a successor that restored while its epoch was still
1803+ /// empty.
1804+ /// 3. Record the stream's retired mark, so coverage treats the rows of
1805+ /// every epoch below the base as covered before any prefix is gone.
1806+ /// 4. Delete the planned prefixes. A crash here leaves the mark, and the
1807+ /// next owner deletes the rest.
1808+ ///
1809+ /// A conditional write on the ownership record would add nothing: the
1810+ /// cell can move between any check and the delete. What makes the late
1811+ /// delete safe is that an epoch below the base never re-enters a chain.
1812+ /// The argument assumes a list-after-write consistent store.
1813+ pub async fn gc_superseded_epochs<F, Fut>(
1814+ &self,
1815+ cell: &str,
1816+ epoch: u64,
1817+ grace_ms: u64,
1818+ confirm_owner: F,
1819+ ) -> anyhow::Result<Option<EpochGcOutcome>>
1820+ where
1821+ F: FnOnce() -> Fut,
1822+ Fut: std::future::Future<Output = anyhow::Result<bool>>,
1823+ {
1824+ // The cheap facts first, so a cell that cannot decide anything costs
1825+ // no listing. A cell that is not resident here has no owner here to
1826+ // run this pass. A paged cell reads pages from its activation chain's
1827+ // objects until its fill completes, and a paged cell whose fill is
1828+ // off never completes one, so only a positive completion unpins it.
1829+ let pinned_reads = match self.cells.lock().unwrap().get(&(cell.to_string(), epoch)) {
1830+ None => return Ok(None),
1831+ Some(handle) => {
1832+ handle.paged_vfs.is_some()
1833+ && handle
1834+ .hydration
1835+ .as_ref()
1836+ .is_none_or(|fill| !fill.complete.load(Ordering::SeqCst))
1837+ }
1838+ };
1839+ // The plan below refuses pinned reads too; returning here skips the
1840+ // listings it would not use.
1841+ if pinned_reads {
1842+ return Ok(None);
1843+ }
1844+ let Some(scan) = scan_epochs(
1845+ self.store.as_ref(),
1846+ &self.prefix,
1847+ cell,
1848+ EPOCH_GC_EPOCHS_PER_PASS,
1849+ |e| self.client_for(cell, e),
1850+ )
1851+ .await?
1852+ else {
1853+ return Ok(None);
1854+ };
1855+ if scan.newest != epoch {
1856+ if scan.newest < epoch {
1857+ self.queue_epoch_opener(cell, epoch);
1858+ }
1859+ return Ok(None);
1860+ }
1861+ let below: Vec<_> = scan.below.iter().map(|b| b.listed).collect();
1862+ // The grace compares the store's upload times with this node's
1863+ // clock, so skew shortens or lengthens it. It is a margin for a slow
1864+ // unowned reader, not part of the safety argument.
1865+ let now_ms = asyncrt::wall_ms().max(0) as u64;
1866+ let Some(plan) = celld_logic::epoch_gc::plan(
1867+ epoch,
1868+ &scan.chain,
1869+ &below,
1870+ self.retired_mark(cell).await,
1871+ pinned_reads,
1872+ now_ms,
1873+ grace_ms,
1874+ ) else {
1875+ return Ok(None);
1876+ };
1877+ if !confirm_owner().await? {
1878+ return Ok(None);
1879+ }
1880+ if plan.record {
1881+ self.record_retired(cell, plan.retired_below).await?;
1882+ }
1883+ for victim in &plan.delete {
1884+ self.client_for(cell, *victim)
1885+ .delete_all()
1886+ .await
1887+ .map_err(|error| anyhow!("delete {cell} e{victim}: {error}"))?;
1888+ self.note_covered(cell, *victim, u64::MAX);
1889+ }
1890+ // Only the previous epoch may stay below the base once the grace has
1891+ // passed; the next activation's pass deletes it.
1892+ let settled = !scan.more_below
1893+ && below
1894+ .iter()
1895+ .all(|l| plan.delete.contains(&l.epoch) || l.epoch + 1 == epoch);
1896+ Ok(Some(EpochGcOutcome {
1897+ retired_below: plan.retired_below,
1898+ deleted: plan.delete,
1899+ settled,
1900+ }))
1901+ }
1902+
1903+ /// Folds a cloned activation's durable rows into its first L1 object, the
1904+ /// opener that epoch GC waits for. Under bundled tiering a write reaches
1905+ /// only the node's bundles, and the first per-cell object is otherwise
1906+ /// the threshold fold (`CELLD_LTX_COMPACTION_MIN_TXIDS`) or a handoff
1907+ /// snapshot. A cell with fewer writes per activation then never lists
1908+ /// its opener and never deletes a superseded epoch; the 2026-09-30 GCE
1909+ /// run measured that. The fold opens at TXID 1, so it makes the owner's
1910+ /// epoch the chain's base, and the next pass decides. A paged epoch
1911+ /// 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.
1915+ fn queue_epoch_opener(&self, cell: &str, epoch: u64) {
1916+ let Some(handle) = self
1917+ .cells
1918+ .lock()
1919+ .unwrap()
1920+ .get(&(cell.to_string(), epoch))
1921+ .cloned()
1922+ else {
1923+ return;
1924+ };
1925+ let Some(compaction) = &handle.compaction else {
1926+ return;
1927+ };
1928+ if compaction.base_txid == 1
1929+ && compaction.compacted_txid.load(Ordering::SeqCst) == 0
1930+ && handle.durable_txid.load(Ordering::SeqCst) > 0
1931+ {
1932+ enqueue_compaction(&handle);
1933+ }
1934+ }
1935+
14961936 /// Highest contiguous TXID prefix proved by the live per-cell L0/L1 objects.
14971937 ///
14981938 /// Unlike `covered_txid`, this is an activation safety proof. A maximum
@@ -1523,6 +1963,8 @@
15231963 Ok(covered)
15241964 }
15251965
1966+ /// Recovery's primitive: PUT one gathered L0 segment to the exact key
1967+ /// the dead leader's own upload would have used. Idempotent by key.
15261968 pub async fn upload_raw_l0(
15271969 &self,
15281970 cell: &str,
@@ -3163,30 +3605,64 @@
31633605
31643606 /// Restore the newest durable replica into a private snapshot without
31653607 /// claiming or activating the cell.
3608+ ///
3609+ /// This reader holds no ownership, so the owner's epoch GC can delete an
3610+ /// epoch this restore planned against. A missing planned object therefore
3611+ /// rebuilds the chain from a fresh epoch listing and restores again; the
3612+ /// new chain starts at a base at or above the deleted epochs. Replanning
3613+ /// over the old chain would pick the same deleted objects, because the
3614+ /// chain caches its listings.
31663615 pub async fn restore_snapshot(&self, cell: &str) -> anyhow::Result<Option<RestoredSnapshot>> {
3167- let Some(chain) = self.epoch_chain(cell, u64::MAX).await? else {
3168- return Ok(None);
3169- };
3170- let epoch = chain.spans().last().map_or(0, |(e, _)| *e);
3171- let directory = self.watch.join(format!(".restore-{cell}"));
3172- let _ = self.ltx_host.remove_dir_all(&directory);
3173- self.ltx_host.create_dir_all(&directory)?;
3174- let path = directory.join("db.sqlite");
3175- replica::restore_with_host_and_download_slots(
3176- &chain,
3177- &path,
3178- TXID(0),
3179- self.ltx_host.clone(),
3180- self.restore_slots.clone(),
3181- )
3182- .await
3183- .map_err(|error| anyhow!("restore snapshot {cell} e{epoch}: {error}"))?;
3184- Ok(Some(RestoredSnapshot::new(
3185- epoch,
3186- path,
3187- directory,
3188- self.ltx_host.filesystem(),
3189- )))
3616+ let mut attempts_left = RESTORE_SNAPSHOT_ATTEMPTS;
3617+ loop {
3618+ // GC can delete a listed epoch while the chain lists its levels,
3619+ // which leaves a continuation without its base; list again.
3620+ let chain = match self.epoch_chain(cell, u64::MAX).await {
3621+ Ok(Some(chain)) => chain,
3622+ Ok(None) => return Ok(None),
3623+ Err(_) if attempts_left > 1 => {
3624+ attempts_left -= 1;
3625+ continue;
3626+ }
3627+ Err(error) => return Err(error),
3628+ };
3629+ // A base deleted between the epoch listing and its level listing
3630+ // does not fail the build: the walk skips the empty epoch and
3631+ // returns a continuation whose oldest span starts past TXID 1.
3632+ if chain.spans().first().is_none_or(|(_, lo)| *lo != TXID(1)) && attempts_left > 1 {
3633+ attempts_left -= 1;
3634+ continue;
3635+ }
3636+ let epoch = chain.spans().last().map_or(0, |(e, _)| *e);
3637+ let directory = self.watch.join(format!(".restore-{cell}"));
3638+ let _ = self.ltx_host.remove_dir_all(&directory);
3639+ self.ltx_host.create_dir_all(&directory)?;
3640+ let path = directory.join("db.sqlite");
3641+ match replica::restore_with_host_and_download_slots(
3642+ &chain,
3643+ &path,
3644+ TXID(0),
3645+ self.ltx_host.clone(),
3646+ self.restore_slots.clone(),
3647+ )
3648+ .await
3649+ {
3650+ Ok(_) => {
3651+ return Ok(Some(RestoredSnapshot::new(
3652+ epoch,
3653+ path,
3654+ directory,
3655+ self.ltx_host.filesystem(),
3656+ )))
3657+ }
3658+ Err(celld_ltx::Error::LTXMissing | celld_ltx::Error::TxNotAvailable)
3659+ if attempts_left > 1 =>
3660+ {
3661+ attempts_left -= 1
3662+ }
3663+ Err(error) => return Err(anyhow!("restore snapshot {cell} e{epoch}: {error}")),
3664+ }
3665+ }
31903666 }
31913667
31923668 pub fn prune_local_cache(&self, max_bytes: u64) -> std::io::Result<(usize, usize, u64)> {
@@ -3463,9 +3939,19 @@
34633939 .saturating_sub(compaction.compacted_txid.load(Ordering::SeqCst))
34643940 >= compaction.min_txids;
34653941 let due_by_bytes = compaction.pending_bytes.load(Ordering::SeqCst) >= compaction.min_bytes;
3942+ if due_by_txids || due_by_bytes {
3943+ enqueue_compaction(handle);
3944+ }
3945+}
3946+
3947+/// Queues one round regardless of the thresholds, behind the same
3948+/// cancellation, backoff and single-flight guards as a threshold round.
3949+fn enqueue_compaction(handle: &CellHandle) {
3950+ let Some(compaction) = &handle.compaction else {
3951+ return;
3952+ };
34663953 if compaction.cancelled.load(Ordering::SeqCst)
34673954 || asyncrt::mono_ms() < compaction.retry_after_ms.load(Ordering::SeqCst)
3468- || !(due_by_txids || due_by_bytes)
34693955 || compaction
34703956 .queued
34713957 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
modifiedcrates/celld/main.rs+100−244View file
@@ -7,13 +7,17 @@
77 //! Runnable celld vertical slice.
88 //!
99 //! One actor serializes every event through `celld-logic`; the actor polls its
10-//! mailbox, timers, and in-flight effect futures together. This is the
11-//! execution shape required for monotonic lease ticks to fence the node even
12-//! when a storage operation remains hung, without spawning a task per effect.
10+//! mailbox, timers, lease futures, and task completions together. Other effect
11+//! work runs on the host runtime so synchronous work cannot starve the core's
12+//! monotonic lease timers.
1313
1414 use anyhow::Context as _;
1515 use celld::actor::*;
1616 use celld::bucket::Bucket;
17+use celld::cell_dispatch::{
18+ dispatch_call_attempt, dispatch_gate, local_dispatch_request_id, local_request_error,
19+ local_response_stream, split_do_call, CallAttempt, CallPayload, RoutedRequestError,
20+};
1721 use celld::fleet;
1822 use celld::generation::{
1923 DeploymentGraph, Generation, GenerationOptions, ReloadOutcome, ReloadRequest, FIRST_GENERATION,
@@ -364,23 +368,6 @@
364368
365369 impl std::error::Error for StalePeerRoute {}
366370
367-#[derive(Debug)]
368-struct RoutedRequestError(RequestError);
369-
370-/// The gate's verdict as the answer's error, with the handler's own failure
371-/// kept below it when the answer was one: the client needs the verdict, and
372-/// the operator reading the chain needs what the handler said too. The
373-/// verdict stays on top, so the routed-error match still finds it.
374-fn local_request_error(failure: LocalRequestFailure) -> anyhow::Error {
375- match failure {
376- LocalRequestFailure::Handler(error) => error,
377- LocalRequestFailure::OutputGate { verdict, handler } => match handler {
378- Some(handler) => handler.context(RoutedRequestError(verdict)),
379- None => anyhow::Error::new(RoutedRequestError(verdict)),
380- },
381- }
382-}
383-
384371 /// Preserve the owner's durability verdict and handler failure in a peer reply.
385372 fn peer_gate_failure(verdict: RequestError, handler: Option<&anyhow::Error>) -> HttpReply {
386373 let detail = match handler {
@@ -393,14 +380,6 @@
393380 ))
394381 }
395382
396-impl std::fmt::Display for RoutedRequestError {
397- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398- write!(formatter, "route failed: {:?}", self.0)
399- }
400-}
401-
402-impl std::error::Error for RoutedRequestError {}
403-
404383 fn classify_remote_attempt(error: &anyhow::Error) -> celld_logic::routing::Attempt {
405384 if error.downcast_ref::<StalePeerRoute>().is_some()
406385 || error
@@ -602,34 +581,6 @@
602581 }
603582 }
604583
605-/// The output gate for an effect raised inside a handler, as opposed to the
606-/// handler's own response.
607-///
608-/// Every in-handler channel arrives here holding a `GateReq`. Reuses the routed
609-/// machinery: `request` pins the cell (no eviction mid-wait) and the core gate
610-/// decides. `Ok` releases the held effect; `Err` breaks the call, as a routed
611-/// gate failure would.
612-async fn dispatch_gate(app: AppHandle, req: celld::js::GateReq) {
613- let routed = match app.request(req.scope.clone()).await {
614- Ok(routed) => routed,
615- Err(error) => {
616- let _ = req.reply.send(Err(error));
617- return;
618- }
619- };
620- // The guard pins the cell and releases the request on drop, so the else
621- // branch does not leak the just-acquired request.
622- let _activity = app.activity(routed.request, req.scope.clone());
623- let result = if routed.route == Route::Local {
624- app.gate_output(routed.request, req.ticket).await
625- } else {
626- // The owning isolate should route the cell locally; if it moved off the
627- // node mid-call, fail closed rather than acknowledge an unproven write.
628- Err(RequestError::NodeFenced)
629- };
630- let _ = req.reply.send(result);
631-}
632-
633584 /// A facet stream request from the isolate that runs the facet.
634585 async fn dispatch_facet(app: AppHandle, req: celld::js::FacetReq) {
635586 use celld::js::FacetReq;
@@ -1084,36 +1035,10 @@
10841035 response(status, body.to_string())
10851036 }
10861037
1087-fn local_dispatch_request_id(
1088- request_id: Option<celld::js::RequestId>,
1089-) -> Option<celld::js::RequestId> {
1090- // Internal Queue, cron, alarm, and peer calls have no client request ID,
1091- // but a local handler still needs an identity in the abort registry. The
1092- // drain cancels by core request and resolves that identity through the
1093- // activity pin; leaving it absent makes a busy internal handler impossible
1094- // to stop before the process deadline.
1095- Some(request_id.unwrap_or_else(celld::js::next_request_id))
1096-}
1097-
10981038 async fn dispatch_do_call(app: AppHandle, call: DoCallReq) {
1099- let DoCallReq {
1100- request_id,
1101- cancel,
1102- deliver_abort_to_handler,
1103- scope,
1104- name,
1105- url,
1106- method,
1107- body,
1108- mut body_guard,
1109- headers,
1110- reply,
1111- order,
1112- parent,
1113- } = call;
1114- let mut cancel = cancel;
1115- let mut order = order;
1116- let mut websocket_timing = headers
1039+ let (mut call, mut payload, reply) = split_do_call(call);
1040+ let mut websocket_timing = payload
1041+ .headers
11171042 .iter()
11181043 .any(|(name, value)| {
11191044 name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket")
@@ -1125,128 +1050,46 @@
11251050 attempts: 0,
11261051 });
11271052 let operation = async {
1128- // Reclaims a streamed body abandoned by an early error below. A local
1129- // target or the peer HTTP body takes ownership before this guard is
1130- // disarmed.
1131- anyhow::ensure!(
1132- celld_logic::cell::valid_cell_scope(&scope),
1133- "cell scope is malformed or exceeds the fleet storage limit"
1134- );
11351053 let mut dispatcher = RemoteRouteRetry::new(app.operation_deadline_ms);
11361054 loop {
11371055 if let Some(timing) = websocket_timing.as_mut() {
11381056 timing.attempts = timing.attempts.saturating_add(1);
11391057 }
11401058 let route_started = Instant::now();
1141- // A disconnect before routing completes has executed no handler,
1142- // so cancel the core request and release its activation admission.
1143- // Once routing completes, the same signal moves into the local or
1144- // remote dispatch below and aborts work that did start.
1145- let route = app.request(scope.clone());
1146- let routed = if deliver_abort_to_handler {
1147- // Workerd delivers an explicit JavaScript AbortSignal to the
1148- // target request. Resolve the route first, then give the
1149- // already-fired receiver to fetch_cell so the handler sees
1150- // request.signal and its waitUntil work can continue.
1151- route.await
1152- } else {
1153- match cancel.as_mut() {
1154- Some(cancel) => celld::asyncrt::select_biased! {
1155- "a cancellation that ties route resolution prevents dispatch from starting";
1156- _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")),
1157- routed = route => routed,
1158- },
1159- None => route.await,
1059+ // The routed hook stamps the boundary between route resolution and
1060+ // local dispatch; the library owns that moment and cannot read the
1061+ // clock. A remote route leaves the stamp unused, because remote
1062+ // dispatch time starts after the stale-route pacing below.
1063+ let mut dispatch_started = route_started;
1064+ let attempt = dispatch_call_attempt(&app, &mut call, payload, || {
1065+ if let Some(timing) = websocket_timing.as_mut() {
1066+ timing.route_resolution_us = timing
1067+ .route_resolution_us
1068+ .saturating_add(route_started.elapsed().as_micros() as u64);
11601069 }
1161- };
1162- let routed = match routed {
1163- Ok(routed) => routed,
1164- Err(error) => {
1070+ dispatch_started = Instant::now();
1071+ })
1072+ .await;
1073+ let (node, addr, epoch, peer_protocol) = match attempt {
1074+ CallAttempt::Unstarted(error) => break Err(error),
1075+ CallAttempt::RouteError(error) => {
11651076 if let Some(timing) = websocket_timing.as_mut() {
11661077 timing.route_resolution_us = timing
11671078 .route_resolution_us
11681079 .saturating_add(route_started.elapsed().as_micros() as u64);
1169- timing.emit(&app, &scope, request_id, "route_error", "", "");
1080+ timing.emit(&app, &call.scope, call.request_id, "route_error", "", "");
11701081 }
1171- break Err(anyhow::Error::new(RoutedRequestError(error)));
1082+ break Err(error);
11721083 }
1173- };
1174- if let Some(timing) = websocket_timing.as_mut() {
1175- timing.route_resolution_us = timing
1176- .route_resolution_us
1177- .saturating_add(route_started.elapsed().as_micros() as u64);
1178- }
1179- let Routed { request, route } = routed;
1180- let (node, addr, epoch, peer_protocol) = match route {
1181- Route::Local => {
1182- let dispatch_started = Instant::now();
1183- let local_request_id = local_dispatch_request_id(request_id);
1184- let local =
1185- app.local_request(request, scope.clone(), local_request_id, "local");
1186- let completed = local
1187- .run(async {
1188- let runtime = app.runtime.as_ref().context("no cell runtime")?;
1189- let response = runtime
1190- .fetch_cell(
1191- scope.clone(),
1192- name,
1193- RuntimeFetch {
1194- url,
1195- method,
1196- body,
1197- headers,
1198- request_id: local_request_id,
1199- // Moved on the first attempt and gone on
1200- // a retry, which is right: a retry is a
1201- // second delivery of a call whose place
1202- // in the order was already taken.
1203- order: order.take(),
1204- parent,
1205- },
1206- cancel.take(),
1207- )
1208- .await?;
1209- // `fetch_cell` cannot return a response until the cell
1210- // has installed its request context. That context now
1211- // owns an unread tail through its waitUntil work.
1212- body_guard.disarm();
1213- if let Some(HttpResponseWebSocket::Cell(target)) = &response.websocket {
1214- let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false)
1215- {
1216- WebSocketKind::Hibernatable
1217- } else {
1218- WebSocketKind::Regular
1219- };
1220- app.websocket_opened(target.scope.clone(), target.id, kind)
1221- .await?;
1222- }
1223- Ok(response)
1224- })
1225- .await;
1226- let activity = completed.activity;
1227- let result = completed.result.map_err(local_request_error);
1228- let result = match result {
1229- Ok(mut response) => {
1230- let body_active = response.stream.is_some();
1231- activity.set_phase("response_body", true, body_active);
1232- if let Some(stream) = response.stream.take() {
1233- response.stream =
1234- Some(local_response_stream(stream, activity, || {}));
1235- } else {
1236- drop(activity);
1237- }
1238- Ok(response)
1239- }
1240- Err(error) => Err(error),
1241- };
1084+ CallAttempt::Local(result) => {
12421085 if let Some(timing) = websocket_timing.as_mut() {
12431086 timing.dispatch_us = timing
12441087 .dispatch_us
12451088 .saturating_add(dispatch_started.elapsed().as_micros() as u64);
12461089 timing.emit(
12471090 &app,
1248- &scope,
1249- request_id,
1091+ &call.scope,
1092+ call.request_id,
12501093 if result.is_ok() { "ok" } else { "error" },
12511094 "local",
12521095 app.runtime.as_ref().map_or("", |runtime| runtime.node()),
@@ -1254,13 +1097,31 @@
12541097 }
12551098 break result;
12561099 }
1257- Route::Remote {
1100+ CallAttempt::Remote {
12581101 node,
12591102 addr,
12601103 epoch,
12611104 peer_protocol,
1262- } => (node, addr, epoch, peer_protocol),
1105+ payload: returned,
1106+ } => {
1107+ // The attempt hands the payload back with the route, so a
1108+ // retry re-enters routing with the body it never lost.
1109+ payload = returned;
1110+ (node, addr, epoch, peer_protocol)
1111+ }
12631112 };
1113+ let scope = &call.scope;
1114+ let request_id = call.request_id;
1115+ let deliver_abort_to_handler = call.deliver_abort_to_handler;
1116+ let cancel = &mut call.cancel;
1117+ let body_guard = &mut call.body_guard;
1118+ let CallPayload {
1119+ name,
1120+ url,
1121+ method,
1122+ body,
1123+ headers,
1124+ } = &payload;
12641125 if dispatcher.observe(&node, epoch) {
12651126 let cancel = if deliver_abort_to_handler {
12661127 None
@@ -1269,7 +1130,7 @@
12691130 };
12701131 match dispatcher.wait(cancel).await {
12711132 RemoteRetryOutcome::Ready => {
1272- dispatcher.invalidate(&app, &scope).await;
1133+ dispatcher.invalidate(&app, scope).await;
12731134 continue;
12741135 }
12751136 RemoteRetryOutcome::Cancelled => {
@@ -1296,7 +1157,7 @@
12961157 request_id,
12971158 capacity_handoff: epoch == 0,
12981159 };
1299- let attempt_body = match &body {
1160+ let attempt_body = match body {
13001161 celld::js::RequestBody::Bytes(bytes) => {
13011162 celld::js::RequestBody::Bytes(bytes.clone())
13021163 }
@@ -1325,7 +1186,7 @@
13251186 attempt_body,
13261187 )
13271188 .await
1328- .map_err(|error| owner_unreachable(&scope, &addr, error))?;
1189+ .map_err(|error| owner_unreachable(scope, &addr, error))?;
13291190 // Only after the tunnel has taken the stream: `disarm`
13301191 // releases the guard's registry claim, and a claim that
13311192 // drops to zero deletes the entry, so disarming before
@@ -1340,7 +1201,7 @@
13401201 {
13411202 abort.disarm();
13421203 return Err(owner_unreachable(
1343- &scope,
1204+ scope,
13441205 &addr,
13451206 anyhow::Error::new(StalePeerRoute {
13461207 scope: scope.clone(),
@@ -1431,7 +1292,7 @@
14311292 match remote {
14321293 Ok(response) => {
14331294 if let Some(timing) = websocket_timing.as_ref() {
1434- timing.emit(&app, &scope, request_id, "ok", "remote", &node);
1295+ timing.emit(&app, scope, request_id, "ok", "remote", &node);
14351296 }
14361297 break Ok(response);
14371298 }
@@ -1468,7 +1329,7 @@
14681329 cancel.as_mut()
14691330 };
14701331 match dispatcher
1471- .retry(&app, &scope, classify_remote_attempt(&error), cancel, None)
1332+ .retry(&app, scope, classify_remote_attempt(&error), cancel, None)
14721333 .await
14731334 {
14741335 RemoteRetryOutcome::Ready => continue,
@@ -1478,7 +1339,7 @@
14781339 RemoteRetryOutcome::Stop => {}
14791340 }
14801341 if let Some(timing) = websocket_timing.as_ref() {
1481- timing.emit(&app, &scope, request_id, "error", "remote", &node);
1342+ timing.emit(&app, scope, request_id, "error", "remote", &node);
14821343 }
14831344 break Err(error);
14841345 }
@@ -1627,11 +1488,11 @@
16271488 request: Request<Incoming>,
16281489 trust_forwarded_headers: bool,
16291490 max_body_bytes: usize,
1630-) -> Result<(String, String, Vec<u8>, Vec<(String, String)>), HttpReply> {
1491+) -> Result<(String, String, Vec<u8>, Vec<(String, String)>), Box<HttpReply>> {
16311492 let (parts, body) = request.into_parts();
16321493 let body = collect_limited_body(body, max_body_bytes)
16331494 .await
1634- .map_err(|error| body_read_error("request", error))?;
1495+ .map_err(|error| Box::new(body_read_error("request", error)))?;
16351496 let headers = parts
16361497 .headers
16371498 .iter()
@@ -1776,7 +1637,7 @@
17761637 celld::js::RequestBody,
17771638 Vec<(String, String)>,
17781639 ),
1779- HttpReply,
1640+ Box<HttpReply>,
17801641 > {
17811642 let declared = request
17821643 .headers()
@@ -1784,18 +1645,18 @@
17841645 .and_then(|value| value.to_str().ok())
17851646 .and_then(|value| value.parse::<u64>().ok());
17861647 if declared.is_some_and(|length| length > max_body_bytes as u64) {
1787- return Err(response(
1648+ return Err(Box::new(response(
17881649 StatusCode::PAYLOAD_TOO_LARGE,
17891650 "request body too large",
1790- ));
1651+ )));
17911652 }
17921653 let (url, method, body, headers, held) =
17931654 ingress_payload_parts(request, trust_forwarded_headers, max_body_bytes).map_err(
17941655 |error| {
1795- response(
1656+ Box::new(response(
17961657 StatusCode::SERVICE_UNAVAILABLE,
17971658 format!("request body stream: {error}"),
1798- )
1659+ ))
17991660 },
18001661 )?;
18011662 // The host collects a small body here. A read failure at this point
@@ -1806,7 +1667,7 @@
18061667 None => body,
18071668 Some(held) => match collect_limited_body(held, max_body_bytes).await {
18081669 Ok(collected) => celld::js::RequestBody::Bytes(collected),
1809- Err(error) => return Err(body_read_error("request", error)),
1670+ Err(error) => return Err(Box::new(body_read_error("request", error))),
18101671 },
18111672 };
18121673 Ok((url, method, body, headers))
@@ -2426,7 +2287,7 @@
24262287 .await
24272288 {
24282289 Ok(payload) => payload,
2429- Err(response) => return response,
2290+ Err(response) => return *response,
24302291 };
24312292 let preserve_representation_length = method.eq_ignore_ascii_case("HEAD");
24322293 match app
@@ -3095,7 +2956,7 @@
30952956 .await
30962957 {
30972958 Ok(payload) => payload,
3098- Err(response) => return Ok(response),
2959+ Err(response) => return Ok(*response),
30992960 };
31002961 dispatch_cell_fetch(cell, None, url, method, body, headers).await
31012962 }
@@ -3525,7 +3386,8 @@
35253386 };
35263387 #[cfg(not(all(test, celld_internal_tests)))]
35273388 let action = action_from_process()?;
3528- celld::asyncrt::set_host_handle(tokio::runtime::Handle::current());
3389+ let host_runtime = tokio::runtime::Handle::current();
3390+ celld::asyncrt::set_host_handle(host_runtime.clone());
35293391 // Docker and journald can stop consuming the process pipe during a log
35303392 // burst. Logging must lose diagnostics under that backpressure rather
35313393 // than block the Tokio workers that route requests and renew authority.
@@ -3682,6 +3544,14 @@
36823544 }
36833545 Action::Run(settings) => settings,
36843546 };
3547+ // Operators need the applied worker count to verify CELLD_TOKIO_THREADS;
3548+ // a count of process threads also includes unrelated, lazily started
3549+ // thread pools, so it cannot stand in for this value.
3550+ tracing::info!(
3551+ event = "host_runtime",
3552+ worker_count = host_runtime.metrics().num_workers(),
3553+ "host runtime initialized"
3554+ );
36853555 celld::startup::raise_file_limit();
36863556 let max_resident = celld::env_vars::optional("CELLD_MAX_RESIDENT_CELLS")?
36873557 // celld has no resident ceiling unless the operator configures one.
@@ -4406,6 +4276,10 @@
44064276 if let Ownership::Bucket(bucket_ownership) = &actor.ownership {
44074277 celld::js::set_kv_blob_store(bucket_ownership.bucket_client());
44084278 }
4279+ // Seed `/state` and the first lease before the core starts or the ticker posts a sample.
4280+ let services = celld::asyncrt::services();
4281+ let initial_sample = tokio::task::spawn_blocking(move || services.sample_metrics()).await?;
4282+ actor.store_load_sample(initial_sample);
44094283 // The core is a serial ownership actor, not a Worker executor. It owns the
44104284 // node lease timer, so ingress, proxy retries, and restore completions must
44114285 // not consume every scheduler turn it needs. Its isolated single-thread
@@ -4431,6 +4305,10 @@
44314305 celld::asyncrt::spawn(async move {
44324306 let mut tick = celld::asyncrt::interval(LOAD_SAMPLE_PERIOD);
44334307 tick.set_missed_tick_behavior(celld::asyncrt::MissedTickBehavior::Delay);
4308+ // The seed sample above takes the CPU baseline. Sampling again on
4309+ // the immediate tick divides CPU clock ticks by too little time and
4310+ // spikes the load.
4311+ tick.tick().await;
44344312 loop {
44354313 tick.tick().await;
44364314 // What SQLite freed when a cell stopped stays on the C
@@ -4440,7 +4318,20 @@
44404318 // ahead of the sample, on a blocking thread because a trim
44414319 // walks every free chunk.
44424320 let _ = tokio::task::spawn_blocking(celld::memory::trim_c_heap_if_retained).await;
4443- if sample_tx.send(Message::SampleLoad).is_err() {
4321+ let services = celld::asyncrt::services();
4322+ let sample =
4323+ match tokio::task::spawn_blocking(move || services.sample_metrics()).await {
4324+ Ok(sample) => sample,
4325+ Err(error) => {
4326+ tracing::warn!(
4327+ event = "load_sample_failed",
4328+ %error,
4329+ "process load sample failed"
4330+ );
4331+ continue;
4332+ }
4333+ };
4334+ if sample_tx.send(Message::SampleLoad(sample)).is_err() {
44444335 return;
44454336 }
44464337 }
@@ -5696,41 +5587,6 @@
56965587 ))
56975588 }
56985589
5699-// The body owns the activity until EOF, cancellation, or drop. A forwarded
5700-// body also owns its peer-abort guard: disarm it at EOF, but retain it on a
5701-// dropped body so the owner cancels work for the disconnected peer.
5702-fn local_response_stream(
5703- stream: celld::js::HttpChunkStream,
5704- activity: ActivityGuard,
5705- on_finish: impl FnOnce() + Send + 'static,
5706-) -> celld::js::HttpChunkStream {
5707- let cancellation = activity.cancellation();
5708- Box::pin(futures_util::stream::unfold(
5709- (stream, activity, on_finish, cancellation),
5710- |(mut stream, activity, on_finish, mut cancellation)| async move {
5711- let chunk = if *cancellation.borrow() {
5712- None
5713- } else {
5714- celld::asyncrt::select! {
5715- chunk = stream.next() => chunk,
5716- changed = cancellation.changed() => {
5717- let _ = changed;
5718- None
5719- }
5720- }
5721- };
5722- match chunk {
5723- Some(chunk) => Some((chunk, (stream, activity, on_finish, cancellation))),
5724- None => {
5725- on_finish();
5726- drop(activity);
5727- None
5728- }
5729- }
5730- },
5731- ))
5732-}
5733-
57345590 #[cfg(all(test, celld_internal_tests))]
57355591 mod durability_lifecycle_private {
57365592 include!(env!("CELLD_CONFORMANCE_MAIN_DURABILITY_TESTS"));
modifiedcrates/celld/main/cli.rs+4−0View file
@@ -270,6 +270,7 @@
270270 celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
271271 celld dev [PROJECT] [--host IP] [--port PORT] [--logs]
272272 celld cell list [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
273+ celld cell gc --dry-run [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
273274 celld d1 migrations apply DATABASE [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
274275 celld d1 execute DATABASE --command SQL [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
275276 celld kv get|put|delete|list|info NAMESPACE --bucket [s3://|gs://|az://]NAME[/PREFIX]
@@ -357,6 +358,8 @@
357358 CELLD_MAX_RESIDENT_CELLS Resident-cell hard cap, enforced at admission
358359 CELLD_MAX_CELL_REQUESTS Concurrent fetches per cell (default: 64)
359360 CELLD_MAX_REQUEST_BODY_BYTES Ingress request body limit (default: 1 GiB)
361+ CELLD_MAX_ASSET_FILE_BYTES Per-file asset limit (default: 25 MiB)
362+ CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES Loaded module total (default: 64 MiB)
360363 CELLD_PRESSURE_OWNERSHIP release to rebalance, sticky to cache locally
361364 CELLD_MAX_RSS_MB Active-memory shed threshold (default: 80%; 0 disables)
362365 CELLD_ALARM_RESIDENT_MS Near-alarm residency window
@@ -374,6 +377,7 @@
374377 CELLD_LOG_PIPELINE Fleet log rounds in flight (default: 4)
375378 CELLD_LOG_HEDGE_MS Duplicate a slow log append (default: adaptive; 0 disables)
376379 CELLD_LTX_TRUNCATE_PAGES WAL pages before a truncate checkpoint (default: 128; Queues never truncate; 0 disables)
380+ CELLD_LTX_RETENTION_SECS Grace in seconds before an owner deletes superseded epochs (default: unset, no deletion)
377381 RUST_LOG Runtime log filter (default: info)
378382
379383 Documentation: https://celld.dev/docs"#,
modifiedcrates/celld/main/websocket.rs+43−2View file
@@ -30,12 +30,53 @@
3030 .await
3131 .map_err(|error| anyhow::anyhow!("route WebSocket {scope}: {error:?}"))?;
3232 anyhow::ensure!(route == Route::Local, "WebSocket owner moved off node");
33+ // The handler's output must reach the gate even when the caller stops
34+ // waiting. A socket task stops reading, and drops this future, once its own
35+ // socket closes, but the handler it started runs on regardless. A dropped
36+ // reply loses a captured batch that already reserved places on other
37+ // sockets, and a lost batch must close those sockets with 1011 because the
38+ // gate never answered for it. A task, which a dropped handle only
39+ // detaches, therefore owns everything from the handoff on. Routing stays
40+ // above it: a message the cell never received has no output to lose.
41+ let app = app.clone();
42+ let scope = scope.to_string();
43+ let (started, receive) = tokio::sync::oneshot::channel();
44+ let delivery_scope = scope.clone();
45+ let delivery = celld::asyncrt::spawn(async move {
46+ deliver_ws_message(&app, &delivery_scope, request, ws_id, data, started).await
47+ });
48+ // The reader waits only until the first turn. Keep observing completion:
49+ // ignoring the detached task would hide failures and leave a broken
50+ // connection open. The delivery still owns its activity and output gate
51+ // handoff even if this socket closes while the handler is suspended.
52+ celld::asyncrt::spawn(async move {
53+ let failure = match delivery.await {
54+ Ok(Ok(())) => return,
55+ Ok(Err(error)) => format!("{error:#}"),
56+ Err(panic) => format!("WebSocket message delivery panicked: {panic}"),
57+ };
58+ tracing::warn!(scope, ws_id, %failure, "WebSocket message delivery failed");
59+ celld::js::ws_close(ws_id, 1011, "WebSocket message delivery failed");
60+ })
61+ .detach();
62+ receive.await.context("WebSocket message did not start")
63+}
64+
65+/// Run `webSocketMessage` and hand its output to the cell's barrier queue.
66+async fn deliver_ws_message(
67+ app: &AppHandle,
68+ scope: &str,
69+ request: u64,
70+ ws_id: u64,
71+ data: celld::js::WsIn,
72+ started: tokio::sync::oneshot::Sender<()>,
73+) -> anyhow::Result<()> {
3374 let activity = app.activity(request, scope.to_string());
3475 let dispatch = match app
3576 .runtime
3677 .as_ref()
3778 .context("no cell runtime")?
38- .ws_message(scope.to_string(), ws_id, data)
79+ .ws_message(scope.to_string(), ws_id, data, started)
3980 .await
4081 {
4182 Ok(dispatch) => dispatch,
@@ -901,7 +942,7 @@
901942 .await
902943 {
903944 Ok(payload) => payload,
904- Err(response) => return response,
945+ Err(response) => return *response,
905946 };
906947 let body_read_us = body_started.elapsed().as_micros() as u64;
907948 let worker_started = Instant::now();
modifiedcrates/celld/node_log.rs+145−18View file
@@ -3890,6 +3890,20 @@
38903890
38913891 // ── Recovery and the takeover interlock ─────────────────────────────────────
38923892
3893+/// The wait before epoch GC retries a cell whose last pass decided nothing
3894+/// or left an epoch inside the grace.
3895+const EPOCH_GC_RETRY_MS: u64 = 5 * 60 * 1000;
3896+
3897+/// The wait before epoch GC looks again at a cell whose last pass deleted
3898+/// everything it could.
3899+const EPOCH_GC_SETTLED_RETRY_MS: u64 = 60 * 60 * 1000;
3900+
3901+/// 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;
3906+
38933907 /// Everything node-log recovery needs from the node: the bucket, the signed
38943908 /// peer client, address resolution, and the raw per-cell upload.
38953909 pub struct NodeLogManager {
@@ -3922,6 +3936,12 @@
39223936 /// record) must not cost a bundle LIST on every sweep tick forever
39233937 /// Process-local; a restart re-confirms once.
39243938 gc_confirmed_empty: Mutex<std::collections::HashSet<String>>,
3939+ /// When each resident (cell, epoch) pair is next due for an epoch-GC
3940+ /// attempt, in monotonic milliseconds. A
3941+ /// pass that decides nothing (an idle cell whose opener is not listed
3942+ /// yet, a paged cell still filling, an epoch inside the grace) waits
3943+ /// [`EPOCH_GC_RETRY_MS`] instead of listing the bucket every tick.
3944+ epoch_gc_due: Mutex<BTreeMap<(String, u64), u64>>,
39253945 /// Retained bundles this process has already declared unreadable. The
39263946 /// record is the durable one; this only keeps one process from
39273947 /// rewriting the same declaration on every scan.
@@ -4450,6 +4470,7 @@
44504470 predecessors_clean: std::sync::atomic::AtomicBool::new(false),
44514471 recovery_locks: Mutex::new(BTreeMap::new()),
44524472 gc_confirmed_empty: Mutex::new(std::collections::HashSet::new()),
4473+ epoch_gc_due: Mutex::new(BTreeMap::new()),
44534474 declared_bundle_losses: Mutex::new(BTreeSet::new()),
44544475 task_stop,
44554476 child_tasks,
@@ -4720,7 +4741,7 @@
47204741 /// (cell, epoch), each group's contiguous tail merged into ONE L0
47214742 /// segment (per-row fallback for non-contiguous chains), skipping
47224743 /// rows the per-cell watermark already covers. Shared by recovery's
4723- /// gather and the reopen healing pass. Any failure propagates —
4744+ /// gather and `fold_cell`. Any failure propagates —
47244745 /// callers must not seal past an incomplete fold. A recovery passes
47254746 /// its claim and its progress record, which carries the watermarks
47264747 /// from one gather window to the next.
@@ -4752,7 +4773,7 @@
47524773 let ltx = self.ltx.clone();
47534774 async move {
47544775 let through = rows.last().expect("a gathered cell has at least one row").0;
4755- let watermark = ltx.covered_txid(&cell, cell_epoch).await;
4776+ let watermark = ltx.covered_txid(&cell, cell_epoch, through).await;
47564777 let rows: Vec<(u64, Vec<u8>)> = rows
47574778 .into_iter()
47584779 .filter(|(txid, _)| *txid > watermark)
@@ -5982,21 +6003,26 @@
59826003 bundles.push((key, rows, bytes));
59836004 }
59846005
5985- // A coverage watermark costs one object-store listing for each LTX
5986- // level. Awaiting every distinct cell here serialized hundreds of
5987- // pairs on the process-exit path, after the handoff itself had
5988- // completed. Collect the exact unique set first and overlap it under
5989- // the same bound recovery uses. An unbounded fan-out would trade the
6006+ // A coverage watermark for a cell this node does not hold costs at
6007+ // most one object-store listing of the epoch's prefix, and a
6008+ // retired-mark read for a row it does not cover. Awaiting every
6009+ // distinct cell here serialized hundreds of pairs on the process-exit
6010+ // path, after the handoff itself had completed. Collect the exact
6011+ // unique set first and overlap it under the same bound recovery uses. An unbounded fan-out would trade the
59906012 // shutdown delay for a store burst and recreate the recovery storm
59916013 // this barrier exists to avoid.
5992- let cells = bundles
5993- .iter()
5994- .flat_map(|(_, rows, _)| rows.iter().map(|row| (row.cell.clone(), row.cell_epoch)))
5995- .filter(|(cell, _)| only_cell.is_none_or(|only| only == cell))
5996- .collect::<BTreeSet<_>>();
6014+ // Each key's highest row is what its coverage must reach.
6015+ let mut cells: BTreeMap<(String, u64), u64> = BTreeMap::new();
6016+ for row in bundles.iter().flat_map(|(_, rows, _)| rows.iter()) {
6017+ if only_cell.is_some_and(|only| only != row.cell) {
6018+ continue;
6019+ }
6020+ let needed = cells.entry((row.cell.clone(), row.cell_epoch)).or_insert(0);
6021+ *needed = (*needed).max(row.txid);
6022+ }
59976023 let ltx = &self.ltx;
5998- let lookups = cells.into_iter().map(|(cell, epoch)| async move {
5999- let watermark = ltx.covered_txid(&cell, epoch).await;
6024+ let lookups = cells.into_iter().map(|((cell, epoch), needed)| async move {
6025+ let watermark = ltx.covered_txid(&cell, epoch, needed).await;
60006026 ((cell, epoch), watermark)
60016027 });
60026028 let mut lookups =
@@ -6135,6 +6161,93 @@
61356161 Ok(())
61366162 }
61376163
6164+ /// Does the ownership record still name this node at `epoch`? Epoch GC
6165+ /// reads it only after the owner's own opener is listed; see
6166+ /// [`crate::ltx_repl::LtxRepl::gc_superseded_epochs`] for why that order
6167+ /// is the fence.
6168+ async fn owns_epoch(&self, cell: &str, epoch: u64) -> anyhow::Result<bool> {
6169+ Ok(matches!(
6170+ self.ownership.read_owner(cell).await?,
6171+ Some(record)
6172+ if record.node.as_deref() == Some(self.node.as_str()) && record.epoch == epoch
6173+ ))
6174+ }
6175+
6176+ /// The maintenance pass of epoch GC (denoland/celld#240): for each root
6177+ /// cell this node holds, delete the epochs below its restore chain's
6178+ /// base. Off unless `CELLD_LTX_RETENTION_SECS` is positive. A facet stream is
6179+ /// skipped: it has no ownership record, its epochs are a sparse subset of
6180+ /// its root's, and its own chain base is usually far below the root's.
6181+ /// A per-cell failure does not stop the pass.
6182+ pub async fn gc_superseded_epochs(&self) -> anyhow::Result<()> {
6183+ let Some(grace_ms) = self.ltx.epoch_gc_grace_ms() else {
6184+ return Ok(());
6185+ };
6186+ let resident: BTreeSet<(String, u64)> = self.ltx.resident_epochs().into_iter().collect();
6187+ 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.
6190+ let due: Vec<(String, u64)> = {
6191+ let mut schedule = self.epoch_gc_due.lock().unwrap();
6192+ schedule.retain(|key, _| resident.contains(key));
6193+ let mut due: Vec<(u64, (String, u64))> = resident
6194+ .into_iter()
6195+ .filter(|(cell, _)| !crate::engine_api::is_facet_cell(cell))
6196+ .map(|key| (schedule.get(&key).copied().unwrap_or(0), key))
6197+ .filter(|(at, _)| *at <= now)
6198+ .collect();
6199+ due.sort();
6200+ due.into_iter()
6201+ .take(EPOCH_GC_CELLS_PER_PASS)
6202+ .map(|(_, key)| key)
6203+ .collect()
6204+ };
6205+ for (cell, epoch) in due {
6206+ let next = match self
6207+ .ltx
6208+ .gc_superseded_epochs(&cell, epoch, grace_ms, || self.owns_epoch(&cell, epoch))
6209+ .await
6210+ {
6211+ Ok(Some(outcome)) => {
6212+ if !outcome.deleted.is_empty() {
6213+ info!(
6214+ event = "ltx_epoch_gc",
6215+ cell = %cell,
6216+ epoch,
6217+ retired_below = outcome.retired_below,
6218+ deleted = ?outcome.deleted,
6219+ "deleted superseded epoch prefixes"
6220+ );
6221+ }
6222+ // A settled cell is looked at again later, because a
6223+ // recovery upload issued before the retirement can still
6224+ // recreate a deleted prefix.
6225+ mono_ms().saturating_add(if outcome.settled {
6226+ EPOCH_GC_SETTLED_RETRY_MS
6227+ } else {
6228+ EPOCH_GC_RETRY_MS
6229+ })
6230+ }
6231+ Ok(None) => mono_ms().saturating_add(EPOCH_GC_RETRY_MS),
6232+ Err(error) => {
6233+ warn!(
6234+ event = "ltx_epoch_gc",
6235+ cell = %cell,
6236+ epoch,
6237+ %error,
6238+ "epoch GC pass failed"
6239+ );
6240+ mono_ms().saturating_add(EPOCH_GC_RETRY_MS)
6241+ }
6242+ };
6243+ self.epoch_gc_due
6244+ .lock()
6245+ .unwrap()
6246+ .insert((cell, epoch), next);
6247+ }
6248+ Ok(())
6249+ }
6250+
61386251 pub async fn gc_bundles(&self) -> anyhow::Result<()> {
61396252 // Bound both the listing and the work. Restarting at the prefix
61406253 // every tick starved newer, covered bundles behind an undrained
@@ -6184,10 +6297,18 @@
61846297 let mut paired = Vec::with_capacity(rows.len());
61856298 for row in &rows {
61866299 let cache_key = (row.cell.clone(), row.cell_epoch);
6300+ // A cached watermark answers only the rows it reaches; a
6301+ // higher row asks again, because only that question may read
6302+ // the retired mark.
61876303 let watermark = match covered.get(&cache_key) {
6188- Some(watermark) => *watermark,
6189- None => {
6190- let watermark = self.ltx.covered_txid(&row.cell, row.cell_epoch).await;
6304+ Some(watermark) if *watermark >= row.txid => *watermark,
6305+ cached => {
6306+ let cached = cached.copied().unwrap_or(0);
6307+ let watermark = self
6308+ .ltx
6309+ .covered_txid(&row.cell, row.cell_epoch, row.txid)
6310+ .await
6311+ .max(cached);
61916312 covered.insert(cache_key, watermark);
61926313 watermark
61936314 }
@@ -6381,6 +6502,7 @@
63816502 ("maintain", manager.maintain().boxed()),
63826503 ("dead-leader sweep", manager.sweep_dead_leaders().boxed()),
63836504 ("bundle GC", manager.gc_bundles().boxed()),
6505+ ("epoch GC", manager.gc_superseded_epochs().boxed()),
63846506 ] {
63856507 let started = mono_ms();
63866508 let mut work = work;
@@ -6603,7 +6725,12 @@
66036725 evicted,
66046726 evicted_through,
66056727 } = self.bundle_index.lock().unwrap().cell_rows(cell, epoch);
6606- let covered = self.ltx.covered_txid(cell, epoch).await;
6728+ // The cell is normally resident for the whole compaction, so the
6729+ // answer is its per-cell watermark; see `LtxRepl::covered_txid`.
6730+ let covered = self
6731+ .ltx
6732+ .covered_txid(cell, epoch, evicted_through.unwrap_or(0))
6733+ .await;
66076734 if evicted_through.is_some_and(|through| covered < through) {
66086735 // A cache is not the source of truth. A slow cell can lose its
66096736 // first row long before it reaches the compaction threshold.
modifiedcrates/celld/otlp.rs+4−3View file
@@ -177,13 +177,14 @@
177177 out
178178 }
179179
180-/// logs.v1.LogRecord: time=1, severity_number=2, body=5, trace_id=9,
181-/// span_id=10, observed_time=11.
180+/// logs.v1.LogRecord: time=1, severity_number=2, severity_text=3, body=5,
181+/// trace_id=9, span_id=10, observed_time=11.
182182 fn log_message(log: &Log) -> Vec<u8> {
183183 let mut out = Vec::new();
184184 let time_ns = log.time_unix_us.max(0) as u64 * 1_000;
185185 field_fixed64(&mut out, 1, time_ns);
186- field_varint(&mut out, 2, 9); // SEVERITY_NUMBER_INFO
186+ field_varint(&mut out, 2, log.severity.number() as u64);
187+ field_str(&mut out, 3, log.severity.text());
187188 field_bytes(&mut out, 5, &any_string(&log.body));
188189 if let Some(trace_id) = log.trace_id {
189190 field_bytes(&mut out, 9, &trace_id);
modifiedcrates/celld/ownership_store.rs+35−60View file
@@ -7,6 +7,7 @@
77 //! `celld-logic`.
88
99 use crate::bucket::Bucket;
10+use crate::host_services::HostMetricsSample;
1011 use anyhow::Context;
1112 use celld_logic::{
1213 CapacityPeer, CasGuard, CasOutcome, LeaseCasOutcome, NodeLeaseRecord, OwnerRecord,
@@ -15,7 +16,7 @@
1516 use serde::{Deserialize, Serialize};
1617 use serde_json::value::RawValue;
1718 use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
18-use std::sync::Arc;
19+use std::sync::{Arc, Mutex};
1920
2021 #[derive(Serialize)]
2122 struct OwnerWire<'a> {
@@ -402,11 +403,6 @@
402403 /// the live Actor counters load-bearing.
403404 #[cfg(all(test, celld_internal_tests))]
404405 ambient_load_override: Option<AmbientLoadSample>,
405- /// A gated tooth observes whether a deterministic override reached the
406- /// production sampler. Such a call advances jemalloc's epoch and reads
407- /// process resources even if the caller later replaces the values.
408- #[cfg(all(test, celld_internal_tests))]
409- production_load_samples: AtomicUsize,
410406 /// The full folded log object this node's OWN lease record carries,
411407 /// tagged with a publish sequence.
412408 /// Renewals snapshot (seq, object) ONCE when they serialize the wire
@@ -452,6 +448,8 @@
452448
453449 #[derive(Debug, Default)]
454450 pub struct LiveLoad {
451+ /// Keep telemetry together: a torn RSS/in-use pair reads as allocator retention.
452+ sample: Mutex<Option<HostMetricsSample>>,
455453 pub owned_cells: AtomicUsize,
456454 /// False until the actor has confirmed every record on its own disk
457455 /// after a start. The lease publishes no owned count until then, so a
@@ -462,7 +460,6 @@
462460 pub placement_weight: AtomicU64,
463461 pub resident_cells: AtomicUsize,
464462 pub host_websockets: AtomicUsize,
465- pub cpu_percent_x100: AtomicU64,
466463 pub pressured: AtomicBool,
467464 /// Stricter than not pressured: the last sample cleared every resume line.
468465 pub memory_headroom: AtomicBool,
@@ -480,6 +477,21 @@
480477 pub draining: AtomicBool,
481478 }
482479
480+impl LiveLoad {
481+ pub fn store_sample(&self, sample: HostMetricsSample) {
482+ *self.sample.lock().unwrap() = Some(sample);
483+ }
484+
485+ /// The stored sample, or `None` before the first one arrives.
486+ pub(crate) fn stored_sample(&self) -> Option<HostMetricsSample> {
487+ *self.sample.lock().unwrap()
488+ }
489+
490+ pub(crate) fn sample(&self) -> HostMetricsSample {
491+ self.sample.lock().unwrap().unwrap_or_default()
492+ }
493+}
494+
483495 impl BucketOwnership {
484496 /// Creates an adapter with an isolated lease pool and the process key
485497 /// advertised for challenge-bound direct probes.
@@ -499,8 +511,6 @@
499511 fleet_sample_ms: 5_000,
500512 #[cfg(all(test, celld_internal_tests))]
501513 ambient_load_override: None,
502- #[cfg(all(test, celld_internal_tests))]
503- production_load_samples: AtomicUsize::new(0),
504514 own_log: std::sync::Mutex::new((0, None)),
505515 applied: tokio::sync::watch::channel((String::new(), 0)).0,
506516 }
@@ -529,11 +539,6 @@
529539 self.process_load()
530540 }
531541
532- #[cfg(all(test, celld_internal_tests))]
533- pub(crate) fn production_load_samples_for_test(&self) -> usize {
534- self.production_load_samples.load(Ordering::Relaxed)
535- }
536-
537542 pub fn lease_ttl_ms(&self) -> u64 {
538543 self.lease_ttl_ms
539544 }
@@ -1007,7 +1012,7 @@
10071012 in_use_bytes: Some(ambient.in_use_bytes.max(1).min(rss_bytes)),
10081013 cgroup_working_set_bytes: ambient.cgroup_working_set_bytes,
10091014 cgroup_current_bytes: ambient.cgroup_current_bytes,
1010- cpu_percent_x100: self.live.cpu_percent_x100.load(Ordering::Relaxed),
1015+ cpu_percent_x100: self.live.sample().cpu_percent_x100,
10111016 open_fds: ambient.open_fds,
10121017 fd_limit: ambient.fd_limit,
10131018 pressured: self.live.pressured.load(Ordering::Relaxed),
@@ -1019,8 +1024,6 @@
10191024 container_instances: Default::default(),
10201025 };
10211026 }
1022- #[cfg(all(test, celld_internal_tests))]
1023- self.production_load_samples.fetch_add(1, Ordering::Relaxed);
10241027 process_load(&self.live)
10251028 }
10261029 }
@@ -1195,65 +1198,37 @@
11951198 .then(|| live.owned_cells.load(Ordering::Relaxed))
11961199 }
11971200
1198-/// Sample the process with the schema a node lease publishes. `/state`
1199-/// reports the same sample, so an operator reads the numbers peers rank
1200-/// this node by rather than a second set assembled from other sources.
12011201 fn placement_weight(live: &LiveLoad) -> Option<u64> {
12021202 let weight = live.placement_weight.load(Ordering::Relaxed);
12031203 (weight > 0).then_some(weight)
12041204 }
12051205
1206-/// Sample the process with the schema a node lease publishes. `/state`
1207-/// reports the same sample, so an operator reads the numbers peers rank
1208-/// this node by rather than a second set assembled from other sources.
1209-#[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage.
1206+/// Build the node load record from live counters and stored resource values.
1207+/// `/state` uses this record for `node_load`, and reports raw memory separately.
12101208 pub(crate) fn process_load(live: &LiveLoad) -> NodeLoadWire {
1211- // One sample for both numbers. Reading the resident set size here and the
1212- // in-use figure from a value the actor wrote on its own timer would publish
1213- // a pair from two instants, and before the first sample it would publish a
1214- // real resident set size beside an in-use figure of zero -- which reads as
1215- // total allocator retention.
1216- let memory = crate::memory::sample();
1217- // A 1-byte floor is the sentinel a platform without /proc leaves behind.
1209+ // One stored sample for both numbers. Resampling RSS here would pair two
1210+ // instants and report allocator retention that never occurred.
1211+ let sample = live.sample();
1212+ // A 1-byte floor is the sentinel before a sample or on a platform without /proc.
12181213 // Both numbers take it, so the in-use figure can never read as zero beside
12191214 // a real resident set size.
1220- let rss_bytes = memory.rss_bytes.max(1);
1221- let in_use_bytes = memory.in_use_bytes.max(1).min(rss_bytes);
1215+ let rss_bytes = sample.rss_bytes.max(1);
1216+ let in_use_bytes = sample.in_use_bytes.max(1).min(rss_bytes);
12221217
1223- #[cfg(target_os = "linux")]
1224- let open_fds = std::fs::read_dir("/proc/self/fd")
1225- .map(|entries| entries.count() as u64)
1226- .unwrap_or_default();
1227- #[cfg(not(target_os = "linux"))]
1228- let open_fds = 0;
1229-
1230- #[cfg(unix)]
1231- let fd_limit = {
1232- let mut limit = libc::rlimit {
1233- rlim_cur: 0,
1234- rlim_max: 0,
1235- };
1236- if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 {
1237- limit.rlim_cur
1238- } else {
1239- 0
1240- }
1241- };
1242- #[cfg(not(unix))]
1243- let fd_limit = 0;
1244-
12451218 NodeLoadWire {
1219+ // Version the whole record, including live counters. Reusing the resource
1220+ // sample's time would retain peers' capacity reservations across renewals.
12461221 sampled_ms: now_ms(),
12471222 owned_cells: owned_cells(live),
12481223 placement_weight: placement_weight(live),
12491224 bucket_format: Some(celld_logic::format::BUCKET_FORMAT),
12501225 rss_bytes,
12511226 in_use_bytes: Some(in_use_bytes),
1252- cgroup_working_set_bytes: memory.cgroup_working_set_bytes,
1253- cgroup_current_bytes: memory.cgroup_current_bytes,
1254- open_fds,
1255- fd_limit,
1256- cpu_percent_x100: live.cpu_percent_x100.load(Ordering::Relaxed),
1227+ cgroup_working_set_bytes: sample.cgroup_working_set_bytes,
1228+ cgroup_current_bytes: sample.cgroup_current_bytes,
1229+ open_fds: sample.open_fds,
1230+ fd_limit: sample.fd_limit,
1231+ cpu_percent_x100: sample.cpu_percent_x100,
12571232 resident_cells: live.resident_cells.load(Ordering::Relaxed),
12581233 host_websockets: live.host_websockets.load(Ordering::Relaxed),
12591234 pressured: live.pressured.load(Ordering::Relaxed),
modifiedcrates/celld/peer_auth.rs+1−1View file
@@ -372,7 +372,7 @@
372372 return Err(anyhow!("incorrect hexadecimal length"));
373373 }
374374 let mut decoded = [0_u8; N];
375- for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() {
375+ for (index, pair) in encoded.as_bytes().as_chunks::<2>().0.iter().enumerate() {
376376 decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?;
377377 }
378378 Ok(decoded)
modifiedcrates/celld/peer_probe.rs+1−1View file
@@ -223,7 +223,7 @@
223223 return Err(anyhow!("incorrect hexadecimal length"));
224224 }
225225 let mut decoded = [0_u8; N];
226- for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() {
226+ for (index, pair) in encoded.as_bytes().as_chunks::<2>().0.iter().enumerate() {
227227 decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?;
228228 }
229229 Ok(decoded)
modifiedcrates/celld/pool.rs+72−0View file
@@ -186,6 +186,10 @@
186186 /// The pool's admission bell, cloned into every slot so an
187187 /// `Affiliation` drop can ring it without holding the pool.
188188 freed: Arc<tokio::sync::Notify>,
189+ /// The pool's reclaim bell, rung when a retiring isolate may have
190+ /// drained. `None` for a standalone slot: nothing frees or replaces it,
191+ /// so [`Slot::condemn`] cannot apply to it.
192+ reclaim: Option<Arc<tokio::sync::Notify>>,
189193 /// Cells whose realm lives in this isolate. Not a count of live work: a
190194 /// cell stays until it is evicted or handed to another node, which is
191195 /// why `retire` refuses an isolate holding any.
@@ -317,6 +321,7 @@
317321 turns: AtomicUsize::new(0),
318322 requests: AtomicUsize::new(0),
319323 freed: Arc::new(tokio::sync::Notify::new()),
324+ reclaim: None,
320325 cells: AtomicUsize::new(0),
321326 adopted_cells: AtomicUsize::new(0),
322327 retiring: AtomicBool::new(false),
@@ -342,6 +347,7 @@
342347 turns: AtomicUsize::new(0),
343348 requests: AtomicUsize::new(0),
344349 freed: Arc::new(tokio::sync::Notify::new()),
350+ reclaim: None,
345351 cells: AtomicUsize::new(0),
346352 adopted_cells: AtomicUsize::new(0),
347353 retiring: AtomicBool::new(false),
@@ -389,6 +395,37 @@
389395 self.retiring.load(Ordering::Relaxed)
390396 }
391397
398+ /// Retire this isolate because its guest can no longer run in it, and
399+ /// ask the pool to free it once it drains. Returns whether the slot
400+ /// belongs to a pool that can do both.
401+ ///
402+ /// Placement already skips a retiring slot, so the next request grows a
403+ /// fresh isolate instead. Leaving the dead isolate to placement is the
404+ /// failure this prevents: it fails each request in about a millisecond,
405+ /// so it carries the fewest turns and `place` hands it nearly every
406+ /// request. [`reap`](Self::reap) does not know it is dead, and on a
407+ /// four-isolate node it retired the three healthy isolates first, one
408+ /// per 30 s pass, so one fatal Python error failed that node's traffic
409+ /// for 94 s.
410+ ///
411+ /// The bell, not the 30 s reap, frees the heap: a guest that fails on
412+ /// every start would otherwise hold one dead heap per failure until the
413+ /// next tick, and a Python heap is tens of megabytes.
414+ ///
415+ /// A cell pool has no task on the bell. A condemned cell isolate still
416+ /// takes no new cell, and frees when its cells leave, as retirement
417+ /// always has; Python Workers cannot declare cells.
418+ pub(crate) fn condemn(&self, reason: &str) -> bool {
419+ let Some(reclaim) = &self.reclaim else {
420+ return false;
421+ };
422+ if !self.retiring.swap(true, Ordering::Relaxed) {
423+ tracing::warn!(isolate = %self.heap_id, slot = self.id, reason, "isolate condemned");
424+ }
425+ reclaim.notify_one();
426+ true
427+ }
428+
392429 /// The node-wide identity of this slot's currently installed V8 heap.
393430 pub fn heap_id(&self) -> HeapId {
394431 self.heap_id
@@ -419,6 +456,14 @@
419456 // the capacity to a single parked request, where waking them all
420457 // would stampede `admit` on every release.
421458 self.0.freed.notify_one();
459+ // The last request out of a retiring isolate is what lets it free.
460+ // Freeing here would drop a V8 isolate inside whatever turn dropped
461+ // this affiliation, so the pool's maintenance task does it.
462+ if self.0.is_retiring() {
463+ if let Some(reclaim) = &self.0.reclaim {
464+ reclaim.notify_one();
465+ }
466+ }
422467 }
423468 }
424469
@@ -483,6 +528,9 @@
483528 limits: PoolLimits,
484529 build: Build,
485530 freed: Arc<tokio::sync::Notify>,
531+ /// Rung by a condemnation and by the last request out of a retiring
532+ /// isolate. See [`Pool::reclaim_bell`].
533+ reclaim: Arc<tokio::sync::Notify>,
486534 admission_wait: std::time::Duration,
487535 /// The whole pool belongs to a superseded generation. An isolate grown
488536 /// after this is set starts out retiring: a placement that snapshotted
@@ -502,6 +550,7 @@
502550 limits,
503551 build,
504552 freed: Arc::new(tokio::sync::Notify::new()),
553+ reclaim: Arc::new(tokio::sync::Notify::new()),
505554 admission_wait,
506555 retired: AtomicBool::new(false),
507556 maintenance: RwLock::new(()),
@@ -567,6 +616,7 @@
567616 turns: AtomicUsize::new(0),
568617 requests: AtomicUsize::new(0),
569618 freed: self.freed.clone(),
619+ reclaim: Some(self.reclaim.clone()),
570620 cells: AtomicUsize::new(0),
571621 adopted_cells: AtomicUsize::new(0),
572622 retiring: AtomicBool::new(self.retired.load(Ordering::Relaxed)),
@@ -700,6 +750,28 @@
700750 self.free_retired();
701751 }
702752
753+ /// The bell a maintenance task awaits to call
754+ /// [`free_drained`](Self::free_drained) between reap ticks.
755+ pub(crate) fn reclaim_bell(&self) -> Arc<tokio::sync::Notify> {
756+ self.reclaim.clone()
757+ }
758+
759+ /// Free every retiring isolate that has drained, and retire nothing.
760+ /// Returns `false` when admission or cell placement holds the pool, so
761+ /// the caller retries rather than let the heap wait for the next reap.
762+ ///
763+ /// The guard is the one `reap` takes, for the same race: an admission
764+ /// that snapshotted this slot before it began retiring can still
765+ /// affiliate to it, and `may_free` only sees that request once the
766+ /// admission has released the guard.
767+ pub(crate) fn free_drained(&self) -> bool {
768+ let Ok(_maintenance) = self.maintenance.try_write() else {
769+ return false;
770+ };
771+ self.free_retired();
772+ true
773+ }
774+
703775 /// Retire every empty isolate. Cell pools use this after eviction because
704776 /// an empty cell heap carries no warm request capacity worth preserving.
705777 pub fn reap_empty(&self) {
modifiedcrates/celld/protocol.rs+6−0View file
@@ -73,6 +73,7 @@
7373 FEATURE_R2_V1,
7474 FEATURE_WASM_V1,
7575 FEATURE_WORKFLOWS_V1,
76+ FEATURE_PYTHON_WORKERS_V1,
7677 ];
7778
7879 pub const FEATURE_ASSETS_V1: &str = "assets-v1";
@@ -96,6 +97,11 @@
9697 pub const FEATURE_R2_V1: &str = "r2-v1";
9798 pub const FEATURE_SQLITE_VEC_V1: &str = "sqlite-vec-v1";
9899 pub const FEATURE_WASM_V1: &str = "wasm-v1";
100+/// A deployment whose `main` is a `.py` file. Required because the bundle
101+/// passes the Workers SDK's own body streams back to `Response`, and a node
102+/// whose body streams do not report `ReadableStream` as their constructor
103+/// fails those requests with a Python `TypeError`.
104+pub const FEATURE_PYTHON_WORKERS_V1: &str = "python-workers-v1";
99105 /// A deployment with `workflows` bindings. Required because a build without
100106 /// the reserved workflow cell would load the manifest, build an `env` missing
101107 /// the binding, and fail only when the application first calls `create()` —
addedcrates/celld/python/fatal.js+34−0View file
@@ -1,0 +1,34 @@
1+// The fatal-error gate of a Python Worker bundle.
2+//
3+// After a fatal interpreter error, Python futures can no longer settle, so
4+// every call that waits on one must fail instead of hanging. The gate keeps
5+// one reject callback for each waiting call and removes it when that call
6+// settles. A single never-settling promise raced by every call is the
7+// obvious alternative, and it is wrong: each race adds a reaction to that
8+// promise, and the reaction holds the call's result for the life of the
9+// isolate, so a healthy Worker leaks every response it returns.
10+export function fatalGate() {
11+ let error = null;
12+ const waiting = new Set();
13+ return {
14+ get error() {
15+ return error;
16+ },
17+ fail(reason) {
18+ if (error !== null) return;
19+ error = reason;
20+ for (const reject of waiting) reject(reason);
21+ waiting.clear();
22+ },
23+ // Settle as `awaitable` does, or reject when the interpreter fails first.
24+ guard(awaitable) {
25+ if (error !== null) return Promise.reject(error);
26+ return new Promise((resolve, reject) => {
27+ waiting.add(reject);
28+ Promise.resolve(awaitable)
29+ .then(resolve, reject)
30+ .finally(() => waiting.delete(reject));
31+ });
32+ },
33+ };
34+}
addedcrates/celld/python/shims.js+85−0View file
@@ -1,0 +1,85 @@
1+// Lexical globals for the upstream Pyodide loader in a Python Worker bundle.
2+//
3+// `celld deploy` injects this module into the generated bundle with esbuild's
4+// `--inject`, so each name below shadows the global of the same name only
5+// inside the bundle. The isolate's own globals are untouched.
6+//
7+// The loader runs as if in a browser Web Worker: it finds `importScripts`
8+// and `WorkerGlobalScope`, reads `self.location`, and fetches its assets.
9+// Every asset is already in the bundle, so the fetch below serves them and
10+// refuses any other runtime URL. A Python Worker never downloads runtime
11+// code at request time.
12+import interpreter from "./pyodide.asm.wasm";
13+import sentinel from "./sentinel.wasm";
14+import stdlib from "./python_stdlib.zip";
15+import { SENTINEL_BYTES } from "./config.js";
16+
17+export const RUNTIME_URL = "https://python-runtime.invalid/";
18+
19+const interpreterResponses = new WeakSet();
20+
21+export function importScripts(url) {
22+ throw new Error(`Python runtime scripts are bundled; refusing ${url}`);
23+}
24+export class WorkerGlobalScope {}
25+export const self = Object.create(globalThis);
26+Object.defineProperty(self, "location", { value: { href: RUNTIME_URL } });
27+
28+export async function fetch(input, init) {
29+ const url = String(input instanceof Request ? input.url : input);
30+ if (url === `${RUNTIME_URL}python_stdlib.zip`) return new Response(stdlib);
31+ if (url === `${RUNTIME_URL}pyodide.asm.wasm`) {
32+ const response = new Response(null);
33+ interpreterResponses.add(response);
34+ return response;
35+ }
36+ if (url.startsWith(RUNTIME_URL)) {
37+ throw new Error(`Python runtime asset is not bundled: ${url}`);
38+ }
39+ return globalThis.fetch(input, init);
40+}
41+
42+// JSPI members are omitted. Pyodide 0.28 turns on stack switching when it
43+// finds `WebAssembly.Suspending`, and in celld each awaited async entry then
44+// leaks 48 bytes of the 5 MiB Emscripten stack until an entry hangs. Without
45+// them Pyodide uses its non-switching path, so `pyodide.ffi.run_sync` and
46+// JS imports that need it are unavailable. Revisit when the pinned runtime
47+// changes.
48+const JSPI_MEMBERS = new Set(["Suspending", "promising", "Suspender"]);
49+export const WebAssembly = {};
50+for (const name of Object.getOwnPropertyNames(globalThis.WebAssembly)) {
51+ if (!JSPI_MEMBERS.has(name)) WebAssembly[name] = globalThis.WebAssembly[name];
52+}
53+
54+function sameBytes(input, expected) {
55+ const bytes = ArrayBuffer.isView(input)
56+ ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
57+ : new Uint8Array(input);
58+ return bytes.length === expected.length &&
59+ bytes.every((byte, index) => byte === expected[index]);
60+}
61+
62+// The loader compiles two programs: the interpreter and a tiny GC sentinel.
63+// Both are deployed as compiled Wasm modules, so compilation returns those
64+// modules. Any other byte string is refused rather than compiled at run time.
65+WebAssembly.compile = async (input) => {
66+ if (sameBytes(input, SENTINEL_BYTES)) return sentinel;
67+ throw new globalThis.WebAssembly.CompileError(
68+ "Python runtime requested an unbundled Wasm module",
69+ );
70+};
71+WebAssembly.instantiate = async (input, imports) => {
72+ if (input instanceof globalThis.WebAssembly.Module) {
73+ return globalThis.WebAssembly.instantiate(input, imports);
74+ }
75+ const module = await WebAssembly.compile(input);
76+ return { module, instance: await globalThis.WebAssembly.instantiate(module, imports) };
77+};
78+WebAssembly.instantiateStreaming = async (source, imports) => {
79+ const response = await source;
80+ if (interpreterResponses.has(response)) {
81+ const instance = await globalThis.WebAssembly.instantiate(interpreter, imports);
82+ return { module: interpreter, instance };
83+ }
84+ return WebAssembly.instantiate(await response.arrayBuffer(), imports);
85+};
addedcrates/celld/python/worker.js+212−0View file
@@ -1,0 +1,212 @@
1+// Entrypoint of a Python Worker bundle built by `celld deploy`.
2+//
3+// Adapted from workerd at commit da46ad950c54b19158c5ea5cb997a9727491ca17
4+// (v1.20260926.1): src/pyodide/python-entrypoint-helper.ts. Copyright (c)
5+// 2026 Cloudflare, Inc. (Apache-2.0). As there, the default export is a
6+// WorkerEntrypoint class whose constructor creates one instance of the Python
7+// `Default` class per invocation, `fetch` calls it with the SDK's RPC
8+// conversions, and a Python awaitable given to waitUntil is kept alive
9+// until it settles. Changed for celld: the interpreter comes from the
10+// upstream Pyodide loader, and only `fetch` is dispatched.
11+//
12+// celld cannot evaluate an asynchronous module top level, so the interpreter
13+// starts on the first invocation of the isolate instead of at load. Every
14+// concurrent first invocation shares that one start. A failed start is kept:
15+// the interpreter is never started twice in one isolate, so a callback of an
16+// earlier interpreter can never reach a later one.
17+import { WorkerEntrypoint } from "cloudflare:workers";
18+import * as cloudflareWorkers from "cloudflare:workers";
19+import * as cloudflareSockets from "cloudflare:sockets";
20+import "./pyodide.asm.js";
21+import { loadPyodide } from "./pyodide.mjs";
22+import workerSource from "./worker.py";
23+import files from "./files.bin";
24+import { COMPATIBILITY_FLAGS, LOCK, MAIN_MODULE, PROCESS_PTH_FILES } from "./config.js";
25+import { RUNTIME_URL } from "./shims.js";
26+import { fatalGate } from "./fatal.js";
27+import { condemnIsolate } from "celld:python";
28+
29+// A hard termination inside Wasm abandons the interpreter's frames, and
30+// celld keeps the isolate in use afterwards, so the next entry would run
31+// on a broken interpreter. `process.exit()` is the only termination a
32+// Worker can reach itself, so it throws here instead.
33+if (globalThis.process) {
34+ globalThis.process.exit = function exit() {
35+ throw new Error("process.exit() is not supported in Python Workers on celld");
36+ };
37+}
38+
39+// Files are `u32 count`, then for each file `u32 path length`, the UTF-8
40+// path under /session/metadata, `u32 size` and the bytes (little endian).
41+function unpack(bytes) {
42+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
43+ const decoder = new TextDecoder();
44+ let offset = 0;
45+ const u32 = () => {
46+ const value = view.getUint32(offset, true);
47+ offset += 4;
48+ return value;
49+ };
50+ const entries = [];
51+ for (let count = u32(); count > 0; count--) {
52+ const pathLength = u32();
53+ const path = decoder.decode(bytes.subarray(offset, offset + pathLength));
54+ offset += pathLength;
55+ const size = u32();
56+ entries.push([path, bytes.subarray(offset, offset + size)]);
57+ offset += size;
58+ }
59+ return entries;
60+}
61+
62+// Cloudflare stops the isolate on a fatal interpreter error. celld condemns
63+// it instead: placement stops choosing it, and the pool frees it once the
64+// calls in flight drain. The gate fails those calls and the background work,
65+// and refuses any entry that still reaches this module. Callbacks that
66+// Python already registered on JS promises are not fenced.
67+const fatal = fatalGate();
68+
69+// A Python awaitable passed to waitUntil is a borrowed proxy that Python
70+// releases when the call returns. Take an owned copy synchronously and
71+// release it when it settles (workerd getPatchedWaitUntil). The gate ends
72+// the wait on a fatal error, because the awaitable can no longer settle and
73+// the invocation would otherwise stay open.
74+function retaining(waitUntil) {
75+ return (awaitable) => {
76+ waitUntil((async () => {
77+ if (awaitable && typeof awaitable.copy === "function") awaitable = awaitable.copy();
78+ try {
79+ await fatal.guard(awaitable);
80+ } finally {
81+ if (awaitable && typeof awaitable.destroy === "function") release(awaitable);
82+ }
83+ })());
84+ };
85+}
86+
87+const patched = new WeakSet();
88+function patchWaitUntil(ctx) {
89+ if (ctx === null || typeof ctx !== "object" || patched.has(ctx)) return;
90+ if (typeof ctx.waitUntil !== "function") return;
91+ ctx.waitUntil = retaining(ctx.waitUntil.bind(ctx));
92+ patched.add(ctx);
93+}
94+
95+const workersWaitUntil = retaining(cloudflareWorkers.waitUntil);
96+const cloudflareWorkersModule = new Proxy(cloudflareWorkers, {
97+ get(target, property, receiver) {
98+ return property === "waitUntil"
99+ ? workersWaitUntil
100+ : Reflect.get(target, property, receiver);
101+ },
102+});
103+
104+const entrypointHelper = {
105+ cloudflareWorkersModule,
106+ cloudflareSocketsModule: cloudflareSockets,
107+ patchWaitUntil,
108+ doAnImport(name) {
109+ throw new Error(`JavaScript module import is not supported in Python Workers on celld: ${name}`);
110+ },
111+ patch_env_helper() {
112+ throw new Error("workers.patch_env is not supported in Python Workers on celld");
113+ },
114+};
115+
116+let started;
117+function describe(error) {
118+ try {
119+ return String(error);
120+ } catch {
121+ return "an error that cannot be printed";
122+ }
123+}
124+
125+async function start() {
126+ const pyodide = await loadPyodide({
127+ indexURL: RUNTIME_URL,
128+ lockFileContents: LOCK,
129+ jsglobals: globalThis,
130+ // workerd's interpreter environment. The fixed hash seed makes string
131+ // hashing, and so set iteration order, match Cloudflare.
132+ env: { HOME: "/session", PYTHONHASHSEED: "111" },
133+ });
134+ pyodide._api.on_fatal = (error) => {
135+ const reason = `Python Worker fatal error: ${describe(error)}`;
136+ fatal.fail(new Error(reason));
137+ condemnIsolate(reason);
138+ };
139+ pyodide.loadPackage = () => {
140+ throw new Error("pyodide.loadPackage is disabled");
141+ };
142+ for (const [path, contents] of unpack(files)) {
143+ const full = `/session/metadata/${path}`;
144+ pyodide.FS.mkdirTree(full.slice(0, full.lastIndexOf("/")));
145+ pyodide.FS.writeFile(full, contents);
146+ }
147+ pyodide.registerJsModule("_pyodide_entrypoint_helper", entrypointHelper);
148+ pyodide.registerJsModule("_cloudflare_compat_flags", COMPATIBILITY_FLAGS);
149+ const namespace = pyodide.globals.get("dict")();
150+ pyodide.runPython(workerSource, { globals: namespace, filename: "<celld-python-worker>" });
151+ namespace.get("setup_python_search_path")(PROCESS_PTH_FILES);
152+ const main = pyodide.pyimport(MAIN_MODULE);
153+ return {
154+ Default: namespace.get("default_entrypoint")(main),
155+ callMethod: namespace.get("call_method"),
156+ };
157+}
158+
159+function runtime() {
160+ if (fatal.error !== null) throw fatal.error;
161+ return started ??= start();
162+}
163+
164+// Release a proxy after a call. A release that throws in `finally` would
165+// replace the call's own result or error, and the caller must see that
166+// instead: a failed release costs a leaked proxy at worst, and a fatal
167+// interpreter error still refuses every later entry through the gate.
168+function release(proxy) {
169+ if (fatal.error !== null) return;
170+ try {
171+ proxy.destroy();
172+ } catch {
173+ // Keep the call's outcome.
174+ }
175+}
176+
177+async function call(entry, name, args) {
178+ const { callMethod } = await runtime();
179+ const instance = await entry;
180+ try {
181+ if (fatal.error !== null) throw fatal.error;
182+ const future = callMethod(name === "fetch", instance, name, ...args);
183+ try {
184+ return await fatal.guard(future);
185+ } finally {
186+ release(future);
187+ }
188+ } finally {
189+ release(instance);
190+ }
191+}
192+
193+export default class Default extends WorkerEntrypoint {
194+ #instance;
195+
196+ constructor(ctx, env) {
197+ super(ctx, env);
198+ this.#instance = (async () => {
199+ const { Default: cls } = await runtime();
200+ if (cls === undefined || cls === null) {
201+ throw new Error("Handler does not export a fetch() function.");
202+ }
203+ return cls(ctx, env);
204+ })();
205+ // A failed start is reported by the method call that awaits it.
206+ this.#instance.catch(() => {});
207+ }
208+
209+ fetch(request) {
210+ return call(this.#instance, "fetch", [request]);
211+ }
212+}
addedcrates/celld/python/worker.py+69−0View file
@@ -1,0 +1,69 @@
1+# Python side of the celld Python Worker entrypoint.
2+#
3+# Adapted from workerd at commit da46ad950c54b19158c5ea5cb997a9727491ca17
4+# (v1.20260926.1): src/pyodide/internal/setup_python_search_path.py and
5+# `wrapper_func` in src/pyodide/internal/introspection.py. Copyright (c)
6+# 2017-2026 Cloudflare, Inc. (Apache-2.0). Changed for celld: one module, the
7+# workerd session paths set up here, and no signal or snapshot handling.
8+#
9+# The same application sees the same `sys.path` and the same argument and
10+# result conversions on both runtimes. The `workers` package is the
11+# application's vendored SDK.
12+import os
13+import sys
14+from inspect import isawaitable, isclass
15+from site import addsitedir
16+
17+SESSION_PATH = "/session/metadata"
18+PYTHON_MODULES_PATH = "/session/metadata/python_modules"
19+SESSION_SITE_PACKAGES = "/session/lib/python3.13/site-packages"
20+
21+
22+def setup_python_search_path(process_pth_files):
23+ # workerd starts with the stdlib entries only and the root directory as
24+ # the working directory.
25+ if sys.path and sys.path[0] == "":
26+ del sys.path[0]
27+ os.chdir("/")
28+ sys.path.append(SESSION_PATH)
29+ sys.path.append(SESSION_SITE_PACKAGES)
30+ for index, path in enumerate(sys.path):
31+ if "site-packages" in path:
32+ sys.path.insert(index, PYTHON_MODULES_PATH)
33+ break
34+ else:
35+ raise ValueError("No site-packages found in sys.path")
36+ if process_pth_files:
37+ addsitedir(PYTHON_MODULES_PATH)
38+
39+
40+def default_entrypoint(main_module):
41+ """The `Default` WorkerEntrypoint class of the main module, or None."""
42+ from workers import WorkerEntrypoint
43+
44+ if hasattr(main_module, "__all__"):
45+ names = main_module.__all__
46+ else:
47+ names = [name for name in dir(main_module) if not name.startswith("_")]
48+ for name in names:
49+ value = getattr(main_module, name)
50+ if (
51+ isclass(value)
52+ and issubclass(value, WorkerEntrypoint)
53+ and value is not WorkerEntrypoint
54+ and value.__name__ == "Default"
55+ ):
56+ return value
57+ return None
58+
59+
60+async def call_method(relaxed, instance, name, *args):
61+ from pyodide.code import relaxed_call
62+ from workers import python_from_rpc, python_to_rpc
63+
64+ method = getattr(instance, name)
65+ py_args = [python_from_rpc(arg) for arg in args]
66+ result = relaxed_call(method, *py_args) if relaxed else method(*py_args)
67+ if isawaitable(result):
68+ result = await result
69+ return python_to_rpc(result)
modifiedcrates/celld/runtime.rs+42−3View file
@@ -41,6 +41,9 @@
4141 /// How often the isolate pool gives back what it no longer needs.
4242 const REAP_INTERVAL: Duration = Duration::from_secs(30);
4343
44+/// How long a reclaim waits before it retries when admission holds the pool.
45+const RECLAIM_RETRY: Duration = Duration::from_millis(10);
46+
4447 /// How often a suspended request re-reads its cancellation flag. Matches the
4548 /// blocking run loop's own cap, which exists for the same reason: a client
4649 /// disconnect is raised on another thread and has nothing to wake this one.
@@ -1187,6 +1190,7 @@
11871190 })
11881191 .await
11891192 .with_context(|| format!("release {cell} from its isolate for a generation swap"))?;
1193+ crate::js::release_root_facets(cell, epoch, crate::js::RootRelease::Swap).await;
11901194 tracing::info!(
11911195 event = "generation_swap_out",
11921196 scope = %cell,
@@ -1435,6 +1439,10 @@
14351439 // the isolate once no cell is left in it.
14361440 drop(handle);
14371441 }
1442+ // After the give-back, so the root cannot start another facet call,
1443+ // and before the facet streams stop, so no write reaches a file that
1444+ // the facet's eviction unlinked.
1445+ crate::js::release_root_facets(cell, epoch, crate::js::RootRelease::Stop).await;
14381446 let Some(replication) = &self.replication else {
14391447 self.facets.forget(cell, epoch);
14401448 return Ok(());
@@ -1796,12 +1804,14 @@
17961804 cell: String,
17971805 ws_id: u64,
17981806 data: js::WsIn,
1807+ started: tokio::sync::oneshot::Sender<()>,
17991808 ) -> anyhow::Result<js::WsDispatch> {
18001809 let (reply, receive) = tokio::sync::oneshot::channel();
18011810 let job = CellJob::WsMessage {
18021811 scope: cell.clone(),
18031812 ws_id,
18041813 data,
1814+ started: Some(started),
18051815 reply,
18061816 };
18071817 self.cell_event(
@@ -2581,6 +2591,7 @@
25812591 // Weak, so this loop cannot keep a superseded generation's pool
25822592 // alive: it ends when the pool is dropped.
25832593 let reaping = Arc::downgrade(&isolates);
2594+ let reclaim = isolates.reclaim_bell();
25842595 handle.spawn(async move {
25852596 // `interval` fires its first tick immediately, which
25862597 // reaped the isolate `warm` had just built and handed the
@@ -2591,11 +2602,29 @@
25912602 );
25922603 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
25932604 loop {
2594- tick.tick().await;
2595- let Some(pool) = reaping.upgrade() else {
2605+ let reap = crate::asyncrt::select_biased! {
2606+ "the paced reap also frees, so it wins a tie with the reclaim bell";
2607+ _ = tick.tick() => true,
2608+ _ = reclaim.notified() => false,
2609+ };
2610+ let Some(mut pool) = reaping.upgrade() else {
25962611 return;
25972612 };
2598- pool.reap();
2613+ if reap {
2614+ pool.reap();
2615+ continue;
2616+ }
2617+ // A condemned isolate is freed as soon as it drains, not
2618+ // at the next tick. Admission holds the guard only while
2619+ // it places one request, so a short retry gets it.
2620+ while !pool.free_drained() {
2621+ drop(pool);
2622+ crate::asyncrt::sleep(RECLAIM_RETRY).await;
2623+ let Some(again) = reaping.upgrade() else {
2624+ return;
2625+ };
2626+ pool = again;
2627+ }
25992628 }
26002629 });
26012630 }
@@ -3192,6 +3221,10 @@
31923221 // ticket cannot be missed by a release landing between the two. Only the
31933222 // waiting happens out here, because a turn may not await.
31943223 let mut pending = Some(job);
3224+ let started_event = match pending.as_mut() {
3225+ Some(CellJob::WsMessage { started, .. }) => started.take(),
3226+ _ => None,
3227+ };
31953228 let (begun, started, moves) = loop {
31963229 let mut waiting = None;
31973230 let taken = slot
@@ -3230,6 +3263,12 @@
32303263 }
32313264 };
32323265 // Delivered. Whatever the caller sent next may go.
3266+ // A socket waits for this turn, including the input gate, rather than
3267+ // handler completion. Acknowledging a queued task instead can reorder
3268+ // messages; awaiting completion prevents a later message cancelling it.
3269+ if let Some(started) = started_event {
3270+ let _ = started.send(());
3271+ }
32333272 if let Some(order) = order.as_mut() {
32343273 order.delivered();
32353274 }
modifiedcrates/celld/storage.rs+73−100View file
@@ -17,6 +17,7 @@
1717 use std::cell::RefCell;
1818 use std::collections::{HashMap, HashSet};
1919 use std::ffi::{CStr, CString};
20+use std::ops::Bound;
2021 use std::sync::atomic::{AtomicU64, Ordering};
2122 use std::sync::Arc;
2223
@@ -300,10 +301,17 @@
300301 generation: Option<i64>,
301302 }
302303
304+// Keep a keyset position, not a stepped SQLite statement. LTX checkpoints
305+// write their control tables through another connection; a retained read
306+// snapshot then makes application writes fail with SQLITE_BUSY_SNAPSHOT.
307+// Fetching one row per step also keeps abandoned iterators harmless without
308+// materializing an unbounded list or depending on JavaScript iterator cleanup.
303309 struct SyncListCursor {
304310 scope: String,
305- database: *mut rusqlite::ffi::sqlite3,
306- statement: *mut rusqlite::ffi::sqlite3_stmt,
311+ lower: Bound<String>,
312+ end: Option<String>,
313+ remaining: usize,
314+ reverse: bool,
307315 }
308316
309317 struct SqlCursor {
@@ -339,17 +347,6 @@
339347 }
340348 }
341349
342-impl Drop for SyncListCursor {
343- fn drop(&mut self) {
344- // SAFETY: the statement is prepared by sync_list_start(), stored in
345- // exactly one cursor, and finalized before its owning connection is
346- // removed from DBS.
347- unsafe {
348- rusqlite::ffi::sqlite3_finalize(self.statement);
349- }
350- }
351-}
352-
353350 impl Drop for SqlCursor {
354351 fn drop(&mut self) {
355352 if self.statement.is_null() {
@@ -3823,39 +3820,28 @@
38233820 reverse: bool,
38243821 ) -> anyhow::Result<u64> {
38253822 close_sync_list_cursors(scope);
3826- let (query, parameters) = list_query(scope, begin, end, start_after, prefix, limit, reverse);
3827- let query = CString::new(query)?;
3828- let cursor = with(scope, |connection| -> anyhow::Result<SyncListCursor> {
3829- // SAFETY: the connection remains resident in DBS for the cursor's
3830- // lifetime. close() finalizes all of its cursors before removal.
3831- unsafe {
3832- let database = connection.handle();
3833- let mut statement = std::ptr::null_mut();
3834- let result = rusqlite::ffi::sqlite3_prepare_v2(
3835- database,
3836- query.as_ptr(),
3837- -1,
3838- &mut statement,
3839- std::ptr::null_mut(),
3840- );
3841- if result != rusqlite::ffi::SQLITE_OK {
3842- return Err(sqlite_failure(database, "prepare sync KV cursor"));
3843- }
3844- for (offset, value) in parameters.iter().enumerate() {
3845- if bind_cursor_value(statement, offset as i32 + 1, value).is_err() {
3846- let error = sqlite_failure(database, "bind sync KV cursor");
3847- rusqlite::ffi::sqlite3_finalize(statement);
3848- return Err(error);
3849- }
3850- }
3851- Ok(SyncListCursor {
3852- scope: scope.to_string(),
3853- database,
3854- statement,
3855- })
3856- }
3857- })
3858- .unwrap_or_else(|| Err(anyhow::anyhow!("no db for {scope}")))?;
3823+ with(scope, |_| ()).ok_or_else(|| anyhow::anyhow!("no db for {scope}"))?;
3824+ // Give SQLite one bound per direction. With redundant range/prefix
3825+ // predicates it can seek to the original lower bound, then scan and
3826+ // filter every previously returned key on each next() (quadratic work).
3827+ let lower = match (begin.max(prefix), start_after) {
3828+ (Some(begin), Some(after)) if begin > after => Bound::Included(begin.to_string()),
3829+ (_, Some(after)) => Bound::Excluded(after.to_string()),
3830+ (Some(begin), None) => Bound::Included(begin.to_string()),
3831+ (None, None) => Bound::Unbounded,
3832+ };
3833+ let end = end
3834+ .map(str::to_string)
3835+ .into_iter()
3836+ .chain(prefix.and_then(prefix_upper_bound))
3837+ .min();
3838+ let cursor = SyncListCursor {
3839+ scope: scope.to_string(),
3840+ lower,
3841+ end,
3842+ remaining: limit.unwrap_or(usize::MAX).min(i64::MAX as usize),
3843+ reverse,
3844+ };
38593845 let id = NEXT_SYNC_LIST_CURSOR.fetch_add(1, Ordering::Relaxed);
38603846 sync_list_cursors(|cursors| cursors.borrow_mut().insert(id, cursor));
38613847 Ok(id)
@@ -3867,65 +3853,52 @@
38673853 let cursor = cursors
38683854 .get_mut(&cursor_id)
38693855 .ok_or_else(|| anyhow::anyhow!("sync KV cursor was invalidated"))?;
3870- // SAFETY: the cursor owns a prepared statement on its still-live
3871- // connection. Column bytes are copied before the next step/finalize.
3872- let result = unsafe { rusqlite::ffi::sqlite3_step(cursor.statement) };
3856+ if cursor.remaining == 0 {
3857+ cursors.remove(&cursor_id);
3858+ return Ok(None);
3859+ }
3860+ let result = with(&cursor.scope, |connection| -> anyhow::Result<_> {
3861+ let (begin, start_after) = match &cursor.lower {
3862+ Bound::Included(key) => (Some(key.as_str()), None),
3863+ Bound::Excluded(key) => (None, Some(key.as_str())),
3864+ Bound::Unbounded => (None, None),
3865+ };
3866+ let (query, parameters) = list_query(
3867+ &cursor.scope,
3868+ begin,
3869+ cursor.end.as_deref(),
3870+ start_after,
3871+ None,
3872+ Some(1),
3873+ cursor.reverse,
3874+ );
3875+ // query_row resets the statement before returning. A cached,
3876+ // reset statement holds no read snapshot between iterator steps.
3877+ let mut statement = connection.prepare_cached(&query)?;
3878+ Ok(statement
3879+ .query_row(rusqlite::params_from_iter(parameters), |row| {
3880+ Ok((row.get::<_, String>(0)?, stored_value(row.get_ref(1)?)))
3881+ })
3882+ .optional()?)
3883+ })
3884+ .unwrap_or_else(|| Err(anyhow::anyhow!("no db for {}", cursor.scope)));
38733885 match result {
3874- rusqlite::ffi::SQLITE_ROW => {
3875- let key = unsafe {
3876- let length = rusqlite::ffi::sqlite3_column_bytes(cursor.statement, 0) as usize;
3877- let pointer = rusqlite::ffi::sqlite3_column_text(cursor.statement, 0);
3878- if length == 0 {
3879- String::new()
3880- } else {
3881- String::from_utf8_lossy(std::slice::from_raw_parts(pointer, length))
3882- .into_owned()
3883- }
3884- };
3885- let value = unsafe {
3886- match rusqlite::ffi::sqlite3_column_type(cursor.statement, 1) {
3887- rusqlite::ffi::SQLITE_BLOB => {
3888- let length =
3889- rusqlite::ffi::sqlite3_column_bytes(cursor.statement, 1) as usize;
3890- let pointer =
3891- rusqlite::ffi::sqlite3_column_blob(cursor.statement, 1).cast();
3892- StoredValue::V8(if length == 0 {
3893- Vec::new()
3894- } else {
3895- std::slice::from_raw_parts(pointer, length).to_vec()
3896- })
3897- }
3898- rusqlite::ffi::SQLITE_TEXT => {
3899- let length =
3900- rusqlite::ffi::sqlite3_column_bytes(cursor.statement, 1) as usize;
3901- let pointer = rusqlite::ffi::sqlite3_column_text(cursor.statement, 1);
3902- StoredValue::LegacyJson(if length == 0 {
3903- String::new()
3904- } else {
3905- String::from_utf8_lossy(std::slice::from_raw_parts(pointer, length))
3906- .into_owned()
3907- })
3908- }
3909- rusqlite::ffi::SQLITE_INTEGER => StoredValue::LegacyJson(
3910- rusqlite::ffi::sqlite3_column_int64(cursor.statement, 1).to_string(),
3911- ),
3912- rusqlite::ffi::SQLITE_FLOAT => StoredValue::LegacyJson(
3913- rusqlite::ffi::sqlite3_column_double(cursor.statement, 1).to_string(),
3914- ),
3915- _ => StoredValue::LegacyJson("null".to_string()),
3916- }
3917- };
3886+ Ok(Some((key, value))) => {
3887+ // The returned key already satisfies every original bound.
3888+ // Tighten only the bound in the traversal direction, so a
3889+ // delete or insert before this position cannot shift an offset.
3890+ if cursor.reverse {
3891+ cursor.end = Some(key.clone());
3892+ } else {
3893+ cursor.lower = Bound::Excluded(key.clone());
3894+ }
3895+ cursor.remaining -= 1;
39183896 Ok(Some((key, value)))
39193897 }
3920- rusqlite::ffi::SQLITE_DONE => {
3898+ other => {
39213899 cursors.remove(&cursor_id);
3922- Ok(None)
3900+ other
39233901 }
3924- _ => {
3925- let error = sqlite_failure(cursor.database, "step sync KV cursor");
3926- cursors.remove(&cursor_id);
3927- Err(error)
3928- }
39293902 }
39303903 })
39313904 }
modifiedcrates/celld/telemetry.rs+50−0View file
@@ -346,9 +346,54 @@
346346 pub trace_id: Option<[u8; 16]>,
347347 pub span_id: Option<[u8; 8]>,
348348 pub time_unix_us: i64,
349+ pub severity: Severity,
349350 pub body: String,
350351 }
351352
353+/// The OpenTelemetry severity of a console line. One value yields both the
354+/// exported number and the exported text, so an exporter cannot pair a
355+/// number with the wrong text.
356+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357+pub enum Severity {
358+ Debug,
359+ Info,
360+ Warn,
361+ Error,
362+}
363+
364+impl Severity {
365+ /// `console.log` and any unknown level are INFO, the level every line
366+ /// carried before the console method reached the exporter.
367+ pub fn from_console_level(level: &str) -> Severity {
368+ match level {
369+ "debug" => Severity::Debug,
370+ "warn" => Severity::Warn,
371+ "error" => Severity::Error,
372+ _ => Severity::Info,
373+ }
374+ }
375+
376+ /// The `SeverityNumber` of the OpenTelemetry log data model: the first
377+ /// value of each range.
378+ pub fn number(self) -> i32 {
379+ match self {
380+ Severity::Debug => 5,
381+ Severity::Info => 9,
382+ Severity::Warn => 13,
383+ Severity::Error => 17,
384+ }
385+ }
386+
387+ pub fn text(self) -> &'static str {
388+ match self {
389+ Severity::Debug => "DEBUG",
390+ Severity::Info => "INFO",
391+ Severity::Warn => "WARN",
392+ Severity::Error => "ERROR",
393+ }
394+ }
395+}
396+
352397 impl Span {
353398 pub fn new(ids: TraceIds, name: &'static str, kind: u8) -> Span {
354399 Span {
@@ -1076,6 +1121,8 @@
10761121 optional binary trace_id (STRING);
10771122 optional binary span_id (STRING);
10781123 required int64 time_unix_us;
1124+ required int32 severity_number;
1125+ required binary severity_text (STRING);
10791126 required binary body (STRING);
10801127 }";
10811128
@@ -1164,6 +1211,7 @@
11641211 use parquet::basic::ZstdLevel;
11651212 use parquet::data_type::ByteArray;
11661213 use parquet::data_type::ByteArrayType;
1214+ use parquet::data_type::Int32Type;
11671215 use parquet::data_type::Int64Type;
11681216 use parquet::file::properties::WriterProperties;
11691217 use parquet::file::writer::SerializedFileWriter;
@@ -1207,6 +1255,8 @@
12071255 column!(ByteArrayType, opt each.clone().map(|l| l.trace_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>());
12081256 column!(ByteArrayType, opt each.clone().map(|l| l.span_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>());
12091257 column!(Int64Type, req each.clone().map(|l| l.time_unix_us).collect::<Vec<_>>());
1258+ column!(Int32Type, req each.clone().map(|l| l.severity.number()).collect::<Vec<_>>());
1259+ column!(ByteArrayType, req each.clone().map(|l| text(l.severity.text())).collect::<Vec<_>>());
12101260 column!(ByteArrayType, req each.clone().map(|l| text(&l.body)).collect::<Vec<_>>());
12111261
12121262 group.close()?;
modifiedcrates/celld/ws_client.rs+3−3View file
@@ -51,7 +51,7 @@
5151 /// The server answered and refused the upgrade. Callers read this: a 401
5252 /// revokes managed credentials, a stale-route header triggers a
5353 /// redispatch, and the isolate surfaces the whole thing to `onerror`.
54- Declined(Declined),
54+ Declined(Box<Declined>),
5555 /// No answer to read -- DNS, TCP, TLS, or a malformed handshake.
5656 Failed(anyhow::Error),
5757 }
@@ -183,11 +183,11 @@
183183 .await
184184 .map(|body| body.to_bytes().to_vec())
185185 .unwrap_or_default();
186- return Err(Error::Declined(Declined {
186+ return Err(Error::Declined(Box::new(Declined {
187187 status,
188188 headers,
189189 body,
190- }));
190+ })));
191191 }
192192 if response
193193 .headers()
modifiedcrates/celld/ws_registry.rs+167−11View file
@@ -58,6 +58,109 @@
5858 Close(u16, String),
5959 }
6060
61+/// Outbound frames together with any positions already reserved in their sockets.
62+/// Captured sends reserve positions inside the isolate, before a later RPC can
63+/// send. The reservation travels through the handler and Actor gate with the
64+/// batch; reconstructing a plain vector at either handoff loses send order.
65+pub struct WsBatch(WsBatchState);
66+
67+enum WsBatchState {
68+ Frames(Vec<(u64, WsOut)>),
69+ Captured(CapturedWsBatch),
70+}
71+
72+struct CapturedWsBatch {
73+ registry: Arc<std::sync::Mutex<WsRegistry>>,
74+ state: Arc<WsFlushState>,
75+ /// The one flush that owns every segment this batch reserved. `None`
76+ /// only until the first frame, since a guard must name a segment.
77+ flush: Option<WsFlushGuard>,
78+ /// The newest segment `flush` holds on each socket, by token. A map, so a
79+ /// broadcast to many sockets does not scan every earlier segment per frame.
80+ tails: HashMap<u64, u64>,
81+ frames: usize,
82+}
83+
84+impl Default for WsBatch {
85+ fn default() -> Self {
86+ Self(WsBatchState::Frames(Vec::new()))
87+ }
88+}
89+
90+impl WsBatch {
91+ pub fn len(&self) -> usize {
92+ match &self.0 {
93+ WsBatchState::Frames(frames) => frames.len(),
94+ WsBatchState::Captured(batch) => batch.frames,
95+ }
96+ }
97+
98+ pub fn is_empty(&self) -> bool {
99+ self.len() == 0
100+ }
101+
102+ pub(crate) fn capture(&mut self, id: u64, out: WsOut) {
103+ if let WsBatchState::Frames(frames) = &self.0 {
104+ assert!(frames.is_empty(), "capture starts with an empty batch");
105+ self.0 = WsBatchState::Captured(CapturedWsBatch {
106+ registry: ws_registry(),
107+ state: ws_flush_state(),
108+ flush: None,
109+ tails: HashMap::new(),
110+ frames: 0,
111+ });
112+ }
113+ let WsBatchState::Captured(batch) = &mut self.0 else {
114+ unreachable!("capture installs its ordered batch");
115+ };
116+ batch
117+ .state
118+ .capture(&mut batch.flush, &mut batch.tails, id, out);
119+ batch.frames += 1;
120+ }
121+
122+ pub(crate) fn release(self, verdict: Result<(), String>) {
123+ match self.0 {
124+ WsBatchState::Captured(mut batch) => {
125+ if let Some(flush) = batch.flush.take() {
126+ flush.release(&batch.registry, verdict);
127+ }
128+ }
129+ WsBatchState::Frames(frames) if verdict.is_ok() && !frames.is_empty() => {
130+ let flushing = ws_flush_state().emit_or_defer(&ws_registry(), frames, false);
131+ debug_assert!(flushing.is_none(), "a released batch opens no flush");
132+ }
133+ WsBatchState::Frames(_) => {}
134+ }
135+ }
136+
137+ /// A rejected handler never published these frames. Remove its reservations
138+ /// without cancelling independent events queued behind them.
139+ pub(crate) fn discard(self) {
140+ if let WsBatchState::Captured(mut batch) = self.0 {
141+ if let Some(flush) = batch.flush.take() {
142+ flush.discard(&batch.registry);
143+ }
144+ }
145+ }
146+}
147+
148+impl From<Vec<(u64, WsOut)>> for WsBatch {
149+ fn from(frames: Vec<(u64, WsOut)>) -> Self {
150+ Self(WsBatchState::Frames(frames))
151+ }
152+}
153+
154+impl Drop for CapturedWsBatch {
155+ fn drop(&mut self) {
156+ // A lost dispatch or cancelled flush has no successful gate verdict.
157+ // Refuse its reservations so successors cannot hang or cross the gap.
158+ if let Some(flush) = self.flush.take() {
159+ flush.release(&self.registry, Err("WebSocket batch abandoned".into()));
160+ }
161+ }
162+}
163+
61164 /// The result of delivering one `webSocketMessage`. `frames` are the outbound
62165 /// frames of the turn the handler answered in, captured by the output gate; a
63166 /// turn the handler suspended in released its own frames as it ended, so those
@@ -66,7 +169,7 @@
66169 /// handler wrote, and its frames must be held until that position is durable.
67170 /// `None` means no write: flush the frames.
68171 pub struct WsDispatch {
69- pub frames: Vec<(u64, WsOut)>,
172+ pub frames: WsBatch,
70173 pub write_position: Option<u64>,
71174 /// As on `HttpResponse`: what a handler that wrote nothing observed above
72175 /// the cell's published baseline, for the gate to hold its frames behind
@@ -763,6 +866,52 @@
763866 flushing
764867 }
765868
869+ /// Reserve one captured frame's place in its socket's queue, inside the
870+ /// batch's single flush.
871+ ///
872+ /// The frame joins the flush's own segment while that segment is still
873+ /// the socket's tail, so a handler that sends many frames, or broadcasts
874+ /// one frame to many sockets, holds one segment per socket, as a batch
875+ /// through `emit_or_defer` does. A segment for each frame would cost a
876+ /// queue lock, a count, and a waiter wake-up for each frame at release.
877+ /// A frame that another event queued in between ends that segment, and
878+ /// this frame opens a new one behind it, so send order still holds.
879+ fn capture(
880+ self: &Arc<Self>,
881+ flush: &mut Option<WsFlushGuard>,
882+ tails: &mut HashMap<u64, u64>,
883+ id: u64,
884+ out: WsOut,
885+ ) {
886+ // One queue lock covers the tail check and the count, as in
887+ // `emit_or_defer`: a teardown must not observe a queued frame with no
888+ // flush behind it.
889+ let mut deferred = self.deferred.lock().unwrap();
890+ let queue = deferred.entry(id).or_default();
891+ let own_tail = tails
892+ .get(&id)
893+ .and_then(|token| queue.back_mut().filter(|segment| segment.token == *token));
894+ if let Some(segment) = own_tail {
895+ segment.frames.push(out);
896+ return;
897+ }
898+ let token = self.next_token.fetch_add(1, Ordering::Relaxed);
899+ queue.push_back(WsSegment {
900+ token,
901+ frames: vec![out],
902+ settled: None,
903+ });
904+ *self.flushes.lock().unwrap().entry(id).or_default() += 1;
905+ tails.insert(id, token);
906+ flush
907+ .get_or_insert_with(|| WsFlushGuard {
908+ state: self.clone(),
909+ segments: Vec::new(),
910+ })
911+ .segments
912+ .push((id, token));
913+ }
914+
766915 /// Wait until no flush holds frames for `id` any more.
767916 async fn await_flushes(&self, id: u64) {
768917 loop {
@@ -883,6 +1032,21 @@
8831032 }
8841033
8851034 impl WsFlushGuard {
1035+ fn discard(self, registry: &std::sync::Mutex<WsRegistry>) {
1036+ {
1037+ let mut deferred = self.state.deferred.lock().unwrap();
1038+ for (id, token) in &self.segments {
1039+ if let Some(segment) = deferred
1040+ .get_mut(id)
1041+ .and_then(|queue| queue.iter_mut().find(|segment| segment.token == *token))
1042+ {
1043+ segment.frames.clear();
1044+ }
1045+ }
1046+ }
1047+ self.release(registry, Ok(()));
1048+ }
1049+
8861050 /// Give the gate's verdict to every segment this flush holds, then
8871051 /// deliver what each socket can now release.
8881052 ///
@@ -1025,16 +1189,8 @@
10251189 /// Release a batch into each socket's ordered stream. A socket whose
10261190 /// durability-ticket queue is still present joins that queue, so an Actor
10271191 /// barrier release cannot overtake an earlier frame on the same socket.
1028-pub fn ws_emit_batch(frames: Vec<(u64, WsOut)>) {
1029- let flush = ws_flush_state();
1030- let registry = ws_registry();
1031- // Ungated: the Actor's own barrier already released these frames, so they
1032- // need no verdict of their own and no flush comes back to wait for one.
1033- let flushing = flush.emit_or_defer(&registry, frames, false);
1034- debug_assert!(
1035- flushing.is_none(),
1036- "an already released batch opens no flush",
1037- );
1192+pub fn ws_emit_batch(frames: impl Into<WsBatch>) {
1193+ frames.into().release(Ok(()));
10381194 }
10391195
10401196 /// Close one socket. A forced generation swap closes the regular and
addedcrates/logic/epoch_gc.rs+98−0View file
@@ -1,0 +1,98 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! Which superseded LTX epoch prefixes an owner may delete.
4+//!
5+//! Every activation opens a new epoch prefix, and a restore reads only the
6+//! epochs of its chain: it walks down from the newest epoch and stops at the
7+//! first span that opens at TXID 1, the chain's base. Every epoch below the
8+//! base is never read again, yet nothing removed it, so a bucket grew with
9+//! database size times activations (denoland/celld#240).
10+//!
11+//! The decision is pure; the owner supplies the facts by I/O. The chain is the
12+//! one the restore code builds (`EpochChain::spans`), over every listed epoch
13+//! including the owner's own. A second walk written here could disagree with
14+//! the restore walk, and the disagreement deletes a base: a fenced owner's
15+//! late snapshot in an intermediate epoch opens at TXID 1 yet sits outside the
16+//! chain, so "the newest epoch that opens at TXID 1" is not the base.
17+//!
18+//! The owner deletes nothing until the chain's newest span is its own epoch.
19+//! That proves its own opener (a TXID-1 snapshot, or a paged activation's
20+//! marker) is listed, so a successor that claims the cell later lists it too
21+//! and restores from a base at or above this one. The caller must read
22+//! `own.json` after this point and before the delete; that order, not a
23+//! conditional write, is the fence. Every uncertain fact keeps the epoch: a
24+//! leak costs bytes, a wrong delete makes a cell unrestorable.
25+
26+pub type Epoch = u64;
27+
28+/// One epoch prefix under a stream, with the upload time of its newest object.
29+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30+pub struct ListedEpoch {
31+ pub epoch: Epoch,
32+ pub newest_ms: u64,
33+}
34+
35+/// What an owner does after activation.
36+#[derive(Debug, Clone, PartialEq, Eq)]
37+pub struct Plan {
38+ /// The chain's base. Rows for epochs below it are covered by the base's
39+ /// image, so bundle GC and recovery may treat them as retired.
40+ pub retired_below: Epoch,
41+ /// Whether the stream's recorded mark must be raised to `retired_below`
42+ /// before any delete.
43+ pub record: bool,
44+ /// Epoch prefixes to delete, ascending.
45+ pub delete: Vec<Epoch>,
46+}
47+
48+/// Plans one stream's epoch GC, or `None` when nothing may be decided yet.
49+///
50+/// `chain` holds the restore chain's epochs, oldest first. `recorded` is the
51+/// stream's current retired mark. `pinned_reads` is true while the owner's
52+/// own activation still reads objects by the chain it built at activation:
53+/// a paged cell faults pages from those objects until its background fill
54+/// completes. The chain can gain a later base in the meantime (a fenced
55+/// owner's late snapshot that ends exactly at the cut links in above the old
56+/// base), and deleting below the new base would remove objects the fill
57+/// still reads. An epoch is deleted only when it is below the
58+/// base, is neither the owner's epoch nor the one before it, and its newest
59+/// object is at least `grace_ms` old. The previous-epoch rule is a margin
60+/// against a lagging listing, not the safety argument.
61+pub fn plan(
62+ own_epoch: Epoch,
63+ chain: &[Epoch],
64+ listed: &[ListedEpoch],
65+ recorded: Option<Epoch>,
66+ pinned_reads: bool,
67+ now_ms: u64,
68+ grace_ms: u64,
69+) -> Option<Plan> {
70+ if pinned_reads || chain.last() != Some(&own_epoch) {
71+ return None;
72+ }
73+ let base = *chain.first()?;
74+ // A recorded mark above the base means an earlier owner saw a higher
75+ // base. The base never falls under a consistent listing, so this owner's
76+ // view is stale; it decides nothing.
77+ if recorded.is_some_and(|mark| mark > base) {
78+ return None;
79+ }
80+ let delete = listed
81+ .iter()
82+ .filter(|l| l.epoch < base && l.epoch + 1 < own_epoch)
83+ .filter(|l| now_ms.saturating_sub(l.newest_ms) >= grace_ms)
84+ .map(|l| l.epoch)
85+ .collect();
86+ Some(Plan {
87+ retired_below: base,
88+ record: recorded != Some(base),
89+ delete,
90+ })
91+}
92+
93+/// Is a node-log row for `epoch` covered by a stream's retired mark? The mark
94+/// is read per stream by its exact name; a facet nests under its root's
95+/// path, and a prefix match would apply the root's mark to the facet.
96+pub fn retired(epoch: Epoch, recorded: Option<Epoch>) -> bool {
97+ recorded.is_some_and(|mark| epoch < mark)
98+}
modifiedcrates/logic/lib.rs+4−1View file
@@ -15,6 +15,7 @@
1515 pub mod dead_node_reconciliation;
1616 pub mod drain;
1717 pub mod durability;
18+pub mod epoch_gc;
1819 pub mod format;
1920 pub mod gate;
2021 pub mod http;
@@ -1004,7 +1005,9 @@
10041005 }
10051006
10061007 /// Whether the last load sample reserves memory below every pressure
1007- /// resume line. False before the first sample.
1008+ /// resume line. False until the first `LoadSampled` event. The actor must
1009+ /// fold a sample before it publishes a lease, or the lease reports no
1010+ /// headroom.
10081011 pub fn memory_headroom(&self) -> bool {
10091012 self.memory_headroom
10101013 }
modifiedcrates/ltx/src/paged_vfs.rs+5−0View file
@@ -162,6 +162,11 @@
162162 // Two faults of one run both fetch; the loser writes nothing.
163163 let run = match reader.read_run(pgno) {
164164 Ok(run) => run,
165+ // The fill can complete while this fetch is in flight, and
166+ // then the owner's epoch GC may delete the objects the fetch
167+ // reads. The page is in the local file by then; read it there
168+ // instead of failing the query.
169+ Err(_) if state.hydrated.lock().unwrap().contains(&pgno) => continue,
165170 Err(_) => return ffi::SQLITE_IOERR_READ,
166171 };
167172 let mut hydrated = state.hydrated.lock().unwrap();
modifiedcrates/ltx/src/replica.rs+12−1View file
@@ -527,6 +527,17 @@
527527 Ok(())
528528 }
529529
530+/// Maps a download failure during restore. A planned object that is gone
531+/// becomes [`Error::LTXMissing`], so a caller that owns the listing can build
532+/// a fresh plan: epoch GC can delete an object between plan selection and its
533+/// download. Every other failure stays opaque and aborts the restore.
534+fn classify_restore_open_error(e: Error) -> Error {
535+ match &e {
536+ Error::Io(io) if io.kind() == std::io::ErrorKind::NotFound => Error::LTXMissing,
537+ _ => Error::Other(format!("open ltx file: {e}").into()),
538+ }
539+}
540+
530541 async fn restore_from_plan_inner<C: ReplicaClient>(
531542 client: &C,
532543 output_path: &Path,
@@ -577,7 +588,7 @@
577588 client
578589 .open_ltx_file(info.level, info.min_txid, info.max_txid)
579590 .await
580- .map_err(|e| Error::Other(format!("open ltx file: {e}").into()))
591+ .map_err(classify_restore_open_error)
581592 }
582593 })
583594 .buffered(RESTORE_DOWNLOAD_CONCURRENCY)
modifieddocs/README.md+65−2View file
@@ -33,7 +33,21 @@
3333 hibernatable WebSocket clients, and stays on its node, is **hibernated**.
3434 A cell that no node holds is **inactive**. An inactive cell is only an
3535 object in the bucket, so it costs almost zero, and every cell starts in
36-this state.
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.
3751
3852 A cell keeps no memory across these transitions, so the constructor
3953 runs again on the next event. A hibernated cell wakes the same way a
@@ -131,6 +145,7 @@
131145 - [Telemetry](telemetry.md)
132146 - [Testing](testing.md)
133147 - [WebAssembly](wasm.md)
148+- [Python Workers](services/workers.md#python-workers)
134149
135150 ## Services
136151
@@ -643,6 +658,12 @@
643658 `resident_cells` value includes only the cells that consume the local
644659 runtime capacity.
645660
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+
646667 The internal listener answers `GET /state` with the live counters:
647668 `owned_cells`, `occupied`, `capacity_waiting`, `activation_waiting`, `restoring`,
648669 `shedding`, and the memory values. The `allocator` object reports the
@@ -880,6 +901,19 @@
880901 the entries-only format, so the v0.6.0 node refuses to start. A fleet
881902 that uses `bucket` durability has no followers, so it can use a rolling
882903 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.
883917
884918 The internal listener also provides an alpha operator API. `/state`
885919 reports the node state, and its `node_load` object is the same load sample
@@ -985,6 +1019,29 @@
9851019 celld cell list --all --json --bucket "$CELLD_BUCKET" > cells.ndjson
9861020 ```
9871021
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+
9881045 ## Hot-cell overload
9891046
9901047 celld admits a maximum of 64 concurrent fetch events for one Durable Object.
@@ -1049,16 +1106,22 @@
10491106 | `CELLD_LOG_PIPELINE` | The limit for fleet log rounds that can be in flight (default: 4) |
10501107 | `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 |
10511108 | `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 |
10521110 | `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 |
10531111 | `CELLD_LTX_COMPACTION_MIN_TXIDS` | The durable TXID distance that queues a background L1 attempt (default: 256) |
10541112 | `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 |
1055-| `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 |
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 |
10561114 | `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 |
10571115 | `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 |
10581116 | `CELLD_LTX_COMPACTIONS` | The node-wide limit for concurrent background L1 attempts (default: 2). `CELLD_RELEASES` bounds final handoff snapshots |
10591117 | `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) |
10601119 | `RUST_LOG` | The runtime log filter |
10611120
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+
10621125 Each L1 compaction attempt merges at most 256 source objects. The buffer
10631126 budget for the source data is 64 MiB. If one source object exceeds this
10641127 budget, celld compacts that object through temporary files in the cell's
modifieddocs/cloudflare-compat.md+1−1View file
@@ -39,7 +39,7 @@
3939 | Hyperdrive | **No** |
4040 | Browser Rendering | **No** |
4141 | Email Workers | **No** |
42-| Python Workers | **No** |
42+| [Python Workers](services/workers.md#python-workers) | **Partial** — `fetch` handlers on the Pyodide 0.28 runtime line |
4343
4444 ## Runtime APIs
4545
modifieddocs/guarantees.md+35−0View file
@@ -25,6 +25,16 @@
2525 - Ranged reads: a read must return the requested byte range and the bytes
2626 from that range.
2727
28+Epoch GC (`CELLD_LTX_RETENTION_SECS`) needs a fifth property:
29+
30+- List-after-write consistency: a listing after a successful write must
31+ include the written object.
32+
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+
2838 The qualified stores are Amazon S3, Cloudflare R2, Tigris, Google Cloud
2939 Storage, and Azure Blob Storage. celld's release tests run against R2,
3040 and the S3 path uses the same client and the same headers.
@@ -291,6 +301,31 @@
291301 writes an epoch seal object, and a legacy `e<epoch>.seal.json` object does
292302 not limit the chain.
293303
304+### Epoch GC
305+
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.
320+
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.
328+
294329 A fenced node can append an unacknowledged tail to an older prefix. When
295330 a successor opened with a whole-database snapshot, a later restore reads
296331 the full chain and can expose that tail. This does not violate the
modifieddocs/limitations.md+1−1View file
@@ -1,6 +1,6 @@
11 # Limitations
22
3-celld v0.6.0 is a beta release. The release has these operational limits. See
3+celld v0.6.1 is a beta release. The release has these operational limits. See
44 [Cloudflare compatibility](cloudflare-compat.md) for the supported services,
55 APIs, and Wrangler configuration.
66
modifieddocs/security.md+1−1View file
@@ -1,6 +1,6 @@
11 # Security
22
3-celld v0.6.0 is a beta release. It is not safe for hostile multi-tenant use.
3+celld v0.6.1 is a beta release. It is not safe for hostile multi-tenant use.
44 Security fixes apply to the latest release only, so older beta releases do not
55 receive fixes.
66
modifieddocs/services/durable-object-facets.md+13−3View file
@@ -52,10 +52,20 @@
5252 is a `DurableObjectClass`, and two sources supply one. The first source is
5353 `worker.getDurableObjectClass("App")` on a Worker Loader binding. The second is
5454 `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. `id` sets what
56-the facet reads at `ctx.id`, and the facet inherits the id of its root object
57-when the callback gives no `id`.
55+storage migration, and that facet runs in the isolate of its root.
5856
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.
62+
63+`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.
68+
5969 The name alone selects the database, so a later call that keeps the name and
6070 changes the `id` still reaches the stored data. A name has a limit of 256 bytes.
6171 A facet can start a facet of its own, to a total depth of 4 that counts the root
modifieddocs/services/durable-objects.md+15−2View file
@@ -68,8 +68,9 @@
6868
6969 A Worker holds its stub on whichever node served the request. celld resolves
7070 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 event runs at a time:
72-a `fetch`, an RPC method, an `alarm()`, or a WebSocket message. celld also
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
7374 holds a response until a durability proof covers every write that the response
7475 can reveal, which is the behavior Cloudflare calls the
7576 [output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/).
@@ -79,6 +80,11 @@
7980 Therefore a `webSocketMessage()` handler that sends a frame and then awaits
8081 delivers that frame while it still runs, and an application can stream an
8182 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.
8288
8389 ![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)
8490
@@ -109,6 +115,13 @@
109115 [storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/)
110116 for the method signatures.
111117
118+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.
124+
112125 The durability of that database comes from the fleet, not from a managed
113126 service. celld captures each write as an LTX segment and replicates the segment
114127 to `cells/<cell>/ltx/e<epoch>/` in the fleet bucket. A fleet of two or more
modifieddocs/services/dynamic-workers-flow.svg+2−2View file
@@ -1,6 +1,6 @@
11 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 600" role="img" aria-labelledby="dwFlowTitle dwFlowDesc">
22 <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 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>
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>
44 <style>
55 svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
66 text { font-size: 13px; fill: currentColor; }
@@ -58,7 +58,7 @@
5858 <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="200" width="184" height="142" rx="8" />
5959 <text class="d-acc lead" fill="currentColor" x="34" y="224">crosses the boundary</text>
6060 <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, compiled once</text>
61+ <text class="d-faint" fill="currentColor" x="34" y="266">64 MiB default limit</text>
6262 <text class="d-ink mono" fill="currentColor" x="34" y="292">env, props</text>
6363 <text class="d-faint" fill="currentColor" x="34" y="310">structured-clone values</text>
6464 <text class="d-faint" fill="currentColor" x="34" y="328">and capabilities, 1 MiB</text>
modifieddocs/services/dynamic-workers.md+22−10View file
@@ -41,8 +41,12 @@
4141 module's name. Thus, `dir/a.js` can import `./b.js` when the map contains
4242 `dir/b.js`. `compatibilityDate` is required, as in workerd, and
4343 `compatibilityFlags` is optional. Both select the runtime behavior of the loaded
44-Worker. The module sources can
45-total 64 MiB, which is the workerd limit. A `WorkerCode.limits` object can set
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
4650 `cpuMs` and `subRequests` for each invocation. celld refuses a `WorkerCode`
4751 that sets `allowExperimental`. Read the
4852 [API reference](https://developers.cloudflare.com/dynamic-workers/api-reference/)
@@ -104,17 +108,25 @@
104108 `get(id, getCode)` memoizes the load by id inside one loader binding of one
105109 host isolate. The first use of an id runs `getCode` and compiles the modules,
106110 and a later use of that id in the same isolate reuses the compiled isolate and
107-runs no callback, so module scope survives between the two calls. Another
108-isolate holds its own map. A request that a different node serves, or a fresh
109-isolate on the same node, therefore pays the compile again. Two `worker_loaders`
110-entries are two maps as well, so the same id in each one loads twice.
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.
111116 Cloudflare describes the same reuse as a possibility and not as a guarantee.
112117
113-`load(code)` caches nothing and compiles on each call. Its isolate goes away
114-when the application disposes the stub, and a garbage collection of an
115-undisposed stub drops it as a backstop. A `get()` stub instead stays in the
116-memo map, so its loaded isolate lives as long as the loader's isolate does.
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.
117124
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.
129+
118130 Every loaded Worker belongs to the isolate that created it. celld drops all of
119131 them when that isolate retires, which happens when the request load falls or
120132 when a new deployment supersedes the script. An in-flight call finishes first.
modifieddocs/services/static-assets.md+9−2View file
@@ -133,8 +133,15 @@
133133 and reads no `If-Modified-Since` header.
134134 - A `_headers` file cannot change `connection`, `content-length`, or
135135 `transfer-encoding`.
136-- A deployment can contain 20,000 assets, 25 MiB for each asset, and 1 GiB in
137- total. Each `_headers` or `_redirects` file has a 100 KiB limit.
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.
138145 - `celld deploy` accepts only `directory`, `binding`, `html_handling`,
139146 `not_found_handling`, and `run_worker_first` in the `assets` block.
140147 - `celld deploy` refuses a `.assetsignore` file, and it stops the deployment
modifieddocs/services/workers.md+114−0View file
@@ -84,3 +84,117 @@
8484
8585 The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the
8686 runtime APIs and the unsupported services.
87+
88+## Python Workers
89+
90+A Worker whose `main` is a `.py` file runs on celld with the
91+[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.
95+
96+The [Python example](../../examples/python) uses the SDK and a vendored
97+package to handle a request.
98+
99+<!-- celld-example: python -->
100+
101+celld supports a bounded part of the Python Workers platform. This page
102+lists what that part is.
103+
104+### Build a project
105+
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.
108+
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.
117+
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.
127+
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.
137+
138+### Runtime version
139+
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:
144+
145+- `compatibility_flags` includes `python_workers`.
146+- `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:
151+ `python_workers_force_new_vendor_path` before 2025-08-11,
152+ `python_no_global_handlers` before 2025-08-14, `python_workers_20250116`
153+ before 2025-09-29, and `enable_python_external_sdk` before 2026-04-21.
154+- `compatibility_date` is before 2026-09-08, or the flags include
155+ `no_python_workers_314`. From 2026-09-08 Cloudflare runs Pyodide 314
156+ (Python 3.14), which needs wheels for another ABI.
157+
158+celld refuses other settings at deploy time. `python_process_pth_files`
159+follows its compatibility date (2026-05-26).
160+
161+### Supported
162+
163+| API | Notes |
164+| --- | --- |
165+| `Default(WorkerEntrypoint).fetch` | One instance for each request, as on Cloudflare |
166+| `workers.Response`, `Response.json`, request body, text and headers | Compared with workerd in the tests |
167+| `workers.fetch` | Outbound HTTP |
168+| `self.env` bindings | Tested with KV. Other bindings are the objects a JavaScript Worker gets, untested from Python |
169+| `self.ctx.waitUntil` | Python awaitables are kept alive until they settle |
170+| Pure-Python packages in `python_modules/` | Tested with `beautifulsoup4` |
171+| `from js import ...` | The JavaScript globals of the isolate |
172+
173+### Not supported
174+
175+- Durable Objects, Workflows, Cron Triggers and Queue consumers written
176+ in Python. `celld deploy` refuses a Python project that declares them.
177+- Named entrypoint classes and RPC to Python methods.
178+- Packages with compiled extensions (`.so` files), and the standard
179+ library modules that Pyodide ships as separate packages: `ssl`,
180+ `sqlite3`, `lzma`, and the OpenSSL-backed `hashlib` algorithms.
181+- `pyodide.ffi.run_sync`, and `workers.import_from_javascript` for
182+ 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.
185+- `process.exit()` throws an error in a Python Worker.
186+- Memory snapshots and the import patches of the `_cloudflare` package.
187+ Package patches that need them, such as synchronous FastAPI handlers,
188+ do not apply.
189+
190+### Failure behavior
191+
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.
195+
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.
modifieddocs/telemetry.md+22−0View file
@@ -56,6 +56,25 @@
5656 it, so a query can join the logs to the traces. The correlation
5757 survives `await`.
5858
59+The log record also carries the OpenTelemetry severity of the console
60+method:
61+
62+| method | severity number | severity text |
63+| --- | --- | --- |
64+| `console.debug` | `5` | `DEBUG` |
65+| `console.log`, `console.info` | `9` | `INFO` |
66+| `console.warn` | `13` | `WARN` |
67+| `console.error` | `17` | `ERROR` |
68+
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.
73+
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`.
77+
5978 celld reads the W3C `traceparent` header on incoming requests, so its
6079 spans join the trace of the system in front of it. celld sends a
6180 `traceparent` header on outbound `fetch()`, so downstream systems can
@@ -96,6 +115,9 @@
96115 SELECT name, duration_us, trace_id FROM traces
97116 ORDER BY duration_us DESC LIMIT 20;
98117
118+-- The error lines.
119+SELECT time_unix_us, body FROM logs WHERE severity_number >= 17;
120+
99121 -- Every log line, inside the span that wrote it.
100122 SELECT l.body, t.name, t.duration_us FROM logs l
101123 JOIN traces t ON l.trace_id = t.trace_id AND l.span_id = t.span_id;
modifiedexamples/README.md+2−0View file
@@ -29,6 +29,8 @@
2929 in a container per sandbox; needs `npm install` and a Docker or Podman CLI
3030 - `pi/` — the PiHarness agent loop in a Durable Object
3131 - `opencode/` — the OpenCode Workerd SDK in a Durable Object
32+- `python/` — a Python Worker that summarizes HTML with a vendored package;
33+ needs `uv run pywrangler sync` first (see [Python Workers](../docs/services/workers.md#python-workers))
3234 - `wasm/` — a Durable Object counter in Rust, compiled to Wasm with
3335 [workers-rs](https://github.com/cloudflare/workers-rs); needs a build step
3436 first (see its [README](wasm/README.md))
addedexamples/python/.gitignore+3−0View file
@@ -1,0 +1,3 @@
1+python_modules/
2+.venv-workers/
3+pylock.toml
addedexamples/python/pyproject.toml+8−0View file
@@ -1,0 +1,8 @@
1+[project]
2+name = "python-example"
3+version = "0.1.0"
4+requires-python = ">=3.13"
5+dependencies = ["beautifulsoup4"]
6+
7+[dependency-groups]
8+dev = ["workers-py", "workers-runtime-sdk"]
addedexamples/python/src/entry.py+34−0View file
@@ -1,0 +1,34 @@
1+# POST an HTML page to /summarize to get its title and links. The summary is
2+# kept in KV under the page's SHA-256, and GET /summary/<sha256> reads it back.
3+import hashlib
4+import json
5+from urllib.parse import urlparse
6+
7+from bs4 import BeautifulSoup
8+from workers import Response, WorkerEntrypoint
9+
10+
11+def summarize(html):
12+ soup = BeautifulSoup(html, "html.parser")
13+ return {
14+ "title": soup.title.get_text(strip=True) if soup.title else None,
15+ "headings": [h.get_text(strip=True) for h in soup.select("h1, h2")],
16+ "links": [a["href"] for a in soup.select("a[href]")],
17+ }
18+
19+
20+class Default(WorkerEntrypoint):
21+ async def fetch(self, request):
22+ path = urlparse(request.url).path
23+ if request.method == "POST" and path == "/summarize":
24+ html = await request.text()
25+ digest = hashlib.sha256(html.encode()).hexdigest()
26+ summary = summarize(html)
27+ await self.env.PAGES.put(digest, json.dumps(summary))
28+ return Response.json({"sha256": digest, **summary})
29+ if request.method == "GET" and path.startswith("/summary/"):
30+ stored = await self.env.PAGES.get(path.removeprefix("/summary/"))
31+ if stored is None:
32+ return Response("not found", status=404)
33+ return Response(stored, headers={"content-type": "application/json"})
34+ return Response("POST HTML to /summarize\n", status=404)
addedexamples/python/wrangler.jsonc+12−0View file
@@ -1,0 +1,12 @@
1+{
2+ "name": "python",
3+ "main": "src/entry.py",
4+ "compatibility_date": "2026-09-01",
5+ "compatibility_flags": ["python_workers"],
6+ "kv_namespaces": [
7+ {
8+ "binding": "PAGES",
9+ "id": "example-pages"
10+ }
11+ ]
12+}