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)
- .github/workflows/release.yml+1−1
- Cargo.lock+1−1
- Dockerfile+1−1
- crates/celld/Cargo.toml+1−1
- crates/celld/actor.rs+306−333
- crates/celld/actor/effects.rs+257−0
- crates/celld/assets.rs+13−4
- crates/celld/asyncrt.rs+12−3
- crates/celld/cell_cli.rs+270−3
- crates/celld/cell_dispatch.rs+379−0
- crates/celld/cell_host.rs+18−0
- crates/celld/control_plane.rs+1−4
- crates/celld/deploy.rs+30−8
- crates/celld/deploy/python.rs+677−0
- crates/celld/engine_api.rs+7−1
- crates/celld/env_vars.rs+22−0
- crates/celld/host_channels.rs+77−0
- crates/celld/host_services.rs+29−1
- crates/celld/js.rs+291−100
- crates/celld/js/bootstrap.rs+7−5
- crates/celld/js/harness.js+90−36
- crates/celld/js/modules.rs+16−5
- crates/celld/js/websocket.rs+8−11
- crates/celld/lib.rs+1−0
- crates/celld/ltx_repl.rs+538−52
- crates/celld/main.rs+100−244
- crates/celld/main/cli.rs+4−0
- crates/celld/main/websocket.rs+43−2
- crates/celld/node_log.rs+145−18
- crates/celld/otlp.rs+4−3
- crates/celld/ownership_store.rs+35−60
- crates/celld/peer_auth.rs+1−1
- crates/celld/peer_probe.rs+1−1
- crates/celld/pool.rs+72−0
- crates/celld/protocol.rs+6−0
- crates/celld/python/fatal.js+34−0
- crates/celld/python/shims.js+85−0
- crates/celld/python/worker.js+212−0
- crates/celld/python/worker.py+69−0
- crates/celld/runtime.rs+42−3
- crates/celld/storage.rs+73−100
- crates/celld/telemetry.rs+50−0
- crates/celld/ws_client.rs+3−3
- crates/celld/ws_registry.rs+167−11
- crates/logic/epoch_gc.rs+98−0
- crates/logic/lib.rs+4−1
- crates/ltx/src/paged_vfs.rs+5−0
- crates/ltx/src/replica.rs+12−1
- docs/README.md+65−2
- docs/cloudflare-compat.md+1−1
- docs/guarantees.md+35−0
- docs/limitations.md+1−1
- docs/security.md+1−1
- docs/services/durable-object-facets.md+13−3
- docs/services/durable-objects.md+15−2
- docs/services/dynamic-workers-flow.svg+2−2
- docs/services/dynamic-workers.md+22−10
- docs/services/static-assets.md+9−2
- docs/services/workers.md+114−0
- docs/telemetry.md+22−0
- examples/README.md+2−0
- examples/python/.gitignore+3−0
- examples/python/pyproject.toml+8−0
- examples/python/src/entry.py+34−0
- examples/python/wrangler.jsonc+12−0
modified.github/workflows/release.yml+1−1View file
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | cancel-in-progress: true |
| 29 | 29 | |
| 30 | 30 | env: |
| 31 | - RUST_VERSION: 1.97.1 | |
| 31 | + RUST_VERSION: 1.98.1 | |
| 32 | 32 | IMAGE: ghcr.io/denoland/celld |
| 33 | 33 | |
| 34 | 34 | jobs: |
modifiedCargo.lock+1−1View file
| @@ -285,7 +285,7 @@ | ||
| 285 | 285 | |
| 286 | 286 | [[package]] |
| 287 | 287 | name = "celld" |
| 288 | -version = "0.6.0" | |
| 288 | +version = "0.6.1" | |
| 289 | 289 | dependencies = [ |
| 290 | 290 | "aes", |
| 291 | 291 | "aes-gcm", |
modifiedDockerfile+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # syntax=docker/dockerfile:1.7 |
| 2 | 2 | |
| 3 | -ARG RUST_VERSION=1.97.1 | |
| 3 | +ARG RUST_VERSION=1.98.1 | |
| 4 | 4 | ARG CELLD_COMMIT=unknown |
| 5 | 5 | |
| 6 | 6 | FROM rust:${RUST_VERSION}-bookworm AS build |
modifiedcrates/celld/Cargo.toml+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.6.0" | |
| 3 | +version = "0.6.1" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
modifiedcrates/celld/actor.rs+306−333View file
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | //! The serial lifecycle executor and its shell-side request drivers. |
| 4 | 4 | |
| 5 | 5 | use crate::cell_host::CellHost; |
| 6 | -use crate::js::{HttpResponse, WsOut}; | |
| 6 | +use crate::js::{HttpResponse, WsBatch}; | |
| 7 | 7 | use crate::machine::{ |
| 8 | 8 | ownership_on_evict_from_environment, pressure_config_from_environment, |
| 9 | 9 | random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, |
| @@ -28,9 +28,12 @@ | ||
| 28 | 28 | use tokio::sync::{mpsc, oneshot, watch, Mutex}; |
| 29 | 29 | use tokio_util::time::{delay_queue, DelayQueue}; |
| 30 | 30 | |
| 31 | +mod effects; | |
| 31 | 32 | mod local_request; |
| 32 | 33 | mod production; |
| 33 | 34 | pub use celld_logic::{EvictCancellation, EvictError, EvictFailure, EvictRefusal, EvictSuccess}; |
| 35 | +pub use effects::StepOutput; | |
| 36 | +pub(crate) use effects::{drain_step_output, LeaseRequest}; | |
| 34 | 37 | pub use local_request::{LocalRequest, LocalRequestCompletion, LocalRequestFailure}; |
| 35 | 38 | |
| 36 | 39 | type EvictionReply = oneshot::Sender<Result<EvictSuccess, EvictError>>; |
| @@ -390,7 +393,7 @@ | ||
| 390 | 393 | pub enum Message { |
| 391 | 394 | /// A periodic resource sample. The measuring is the shell's job; every |
| 392 | 395 | /// decision that follows belongs to the core. |
| 393 | - SampleLoad, | |
| 396 | + SampleLoad(crate::host_services::HostMetricsSample), | |
| 394 | 397 | /// The log tier changed the folded log object the next lease write |
| 395 | 398 | /// must carry (lease-fold): renew now so the change becomes durable. |
| 396 | 399 | NudgeNodeLease, |
| @@ -475,7 +478,7 @@ | ||
| 475 | 478 | WsOutput { |
| 476 | 479 | request: u64, |
| 477 | 480 | scope: String, |
| 478 | - frames: Vec<(u64, WsOut)>, | |
| 481 | + frames: WsBatch, | |
| 479 | 482 | write_position: Option<u64>, |
| 480 | 483 | observed: Option<u64>, |
| 481 | 484 | reply: oneshot::Sender<()>, |
| @@ -1214,33 +1217,6 @@ | ||
| 1214 | 1217 | TimerFired(Timer), |
| 1215 | 1218 | } |
| 1216 | 1219 | |
| 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 | - | |
| 1244 | 1220 | /// The largest request body that a node accepts unless the operator lowers |
| 1245 | 1221 | /// the limit. The value keeps the large git-pack ingress use case supported. |
| 1246 | 1222 | pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1 << 30; |
| @@ -1512,6 +1488,13 @@ | ||
| 1512 | 1488 | result |
| 1513 | 1489 | } |
| 1514 | 1490 | |
| 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 | + | |
| 1515 | 1498 | pub fn activity(&self, request: u64, cell: String) -> ActivityGuard { |
| 1516 | 1499 | self.activity_for(request, cell, None, "local") |
| 1517 | 1500 | } |
| @@ -1524,9 +1507,7 @@ | ||
| 1524 | 1507 | origin: &'static str, |
| 1525 | 1508 | ) -> ActivityGuard { |
| 1526 | 1509 | 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(); | |
| 1530 | 1511 | ActivityGuard { |
| 1531 | 1512 | tx: self.tx.clone(), |
| 1532 | 1513 | request, |
| @@ -1619,7 +1600,7 @@ | ||
| 1619 | 1600 | &self, |
| 1620 | 1601 | request: u64, |
| 1621 | 1602 | scope: String, |
| 1622 | - frames: Vec<(u64, WsOut)>, | |
| 1603 | + frames: impl Into<WsBatch>, | |
| 1623 | 1604 | write_position: Option<u64>, |
| 1624 | 1605 | observed: Option<u64>, |
| 1625 | 1606 | ) -> Result<(), ActorStopped> { |
| @@ -1628,7 +1609,7 @@ | ||
| 1628 | 1609 | .send(Message::WsOutput { |
| 1629 | 1610 | request, |
| 1630 | 1611 | scope, |
| 1631 | - frames, | |
| 1612 | + frames: frames.into(), | |
| 1632 | 1613 | write_position, |
| 1633 | 1614 | observed, |
| 1634 | 1615 | reply, |
| @@ -1835,7 +1816,7 @@ | ||
| 1835 | 1816 | struct WsBarrier { |
| 1836 | 1817 | request: u64, |
| 1837 | 1818 | settled: Option<bool>, |
| 1838 | - frames: Vec<(u64, WsOut)>, | |
| 1819 | + frames: WsBatch, | |
| 1839 | 1820 | } |
| 1840 | 1821 | |
| 1841 | 1822 | /// The actor stopped before it answered: its channel is closed, and nothing |
| @@ -1968,9 +1949,8 @@ | ||
| 1968 | 1949 | /// Debug builds keep it. Release builds rely on the deterministic model, |
| 1969 | 1950 | /// because this full-table scan is too expensive for production traffic. |
| 1970 | 1951 | 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>, | |
| 1974 | 1954 | /// The shed reason last reported to the log, so a latch that holds for |
| 1975 | 1955 | /// minutes is reported once rather than on every sample. |
| 1976 | 1956 | logged_shed_reason: Option<&'static str>, |
| @@ -2040,7 +2020,31 @@ | ||
| 2040 | 2020 | directory.sampled_at_mono_ms = Some(now_mono_ms); |
| 2041 | 2021 | } |
| 2042 | 2022 | 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 | + } | |
| 2044 | 2048 | if rebalance { |
| 2045 | 2049 | // A drain takes any peer with room. A balancing move takes only a |
| 2046 | 2050 | // peer below its ownership target, least dense first; a fuller peer |
| @@ -2068,6 +2072,33 @@ | ||
| 2068 | 2072 | Ok(ranked) |
| 2069 | 2073 | } |
| 2070 | 2074 | |
| 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 | + | |
| 2071 | 2102 | fn rank_handoff_candidates( |
| 2072 | 2103 | peers: Vec<CapacityPeer>, |
| 2073 | 2104 | source: &str, |
| @@ -2077,13 +2108,9 @@ | ||
| 2077 | 2108 | let mut peers: Vec<_> = peers |
| 2078 | 2109 | .into_iter() |
| 2079 | 2110 | .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() | |
| 2087 | 2114 | }) |
| 2088 | 2115 | .collect(); |
| 2089 | 2116 | peers.sort_by_key(|peer| { |
| @@ -2391,13 +2418,14 @@ | ||
| 2391 | 2418 | }))) |
| 2392 | 2419 | }; |
| 2393 | 2420 | 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()), | |
| 2396 | 2423 | }; |
| 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()); | |
| 2401 | 2429 | } |
| 2402 | 2430 | let process_generation = match &ownership { |
| 2403 | 2431 | Ownership::Bucket(bucket) => bucket |
| @@ -2497,10 +2525,26 @@ | ||
| 2497 | 2525 | }) |
| 2498 | 2526 | } |
| 2499 | 2527 | |
| 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 | + | |
| 2500 | 2534 | /// Emits the exactly-once pre-loop node-lease transition. |
| 2501 | 2535 | pub fn start(&mut self, out: &mut StepOutput) { |
| 2502 | 2536 | assert!(!self.started, "Actor::start was called more than once"); |
| 2503 | 2537 | 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); | |
| 2504 | 2548 | self.drive( |
| 2505 | 2549 | Event::StartNodeLease { |
| 2506 | 2550 | now_ms: now_ms(), |
| @@ -2511,6 +2555,89 @@ | ||
| 2511 | 2555 | ); |
| 2512 | 2556 | } |
| 2513 | 2557 | |
| 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 | + | |
| 2514 | 2641 | /// Handles exactly one ready mailbox item, completion, or timer. |
| 2515 | 2642 | pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) { |
| 2516 | 2643 | assert!(self.started, "Actor::step was called before Actor::start"); |
| @@ -2654,84 +2781,8 @@ | ||
| 2654 | 2781 | }; |
| 2655 | 2782 | let _ = reply.send(epoch); |
| 2656 | 2783 | } |
| 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), | |
| 2735 | 2786 | Message::Output { |
| 2736 | 2787 | request, |
| 2737 | 2788 | ticket, |
| @@ -2981,9 +3032,14 @@ | ||
| 2981 | 3032 | } |
| 2982 | 3033 | }; |
| 2983 | 3034 | 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); | |
| 2985 | 3040 | self.ws_gated.retain(|_, s| *s != scope); |
| 2986 | 3041 | crate::js::ws_close_scope(&scope, 1011, "durability unproven"); |
| 3042 | + drop(gate); | |
| 2987 | 3043 | return; |
| 2988 | 3044 | } |
| 2989 | 3045 | for frames in flush { |
| @@ -3104,17 +3160,13 @@ | ||
| 3104 | 3160 | out.timers.push(arm); |
| 3105 | 3161 | } |
| 3106 | 3162 | 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 { | |
| 3112 | 3165 | 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 | + ); | |
| 3118 | 3170 | } |
| 3119 | 3171 | Effect::CasNodeLease { |
| 3120 | 3172 | op, |
| @@ -3122,115 +3174,19 @@ | ||
| 3122 | 3174 | record, |
| 3123 | 3175 | authority_expires_ms, |
| 3124 | 3176 | } => { |
| 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 { | |
| 3224 | 3179 | 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 | + ); | |
| 3230 | 3186 | } |
| 3231 | 3187 | Effect::ReadLocalCells => { |
| 3232 | 3188 | let runtime = self.host.clone(); |
| 3233 | - out.effects.push(Box::pin(async move { | |
| 3189 | + out.spawn_scoped(async move { | |
| 3234 | 3190 | let result = match runtime { |
| 3235 | 3191 | // The host runtime's blocking pool, not a second |
| 3236 | 3192 | // pool on the core's current-thread runtime. |
| @@ -3245,13 +3201,13 @@ | ||
| 3245 | 3201 | None => Err(Failure::Definite), |
| 3246 | 3202 | }; |
| 3247 | 3203 | CompletedEffect::plain(Event::LocalCellsRead { result }) |
| 3248 | - })); | |
| 3204 | + }); | |
| 3249 | 3205 | } |
| 3250 | 3206 | Effect::ReadOwner { op, cell } => { |
| 3251 | 3207 | self.route_effect_started(&cell); |
| 3252 | 3208 | let ownership = self.ownership.clone(); |
| 3253 | 3209 | let timing_cell = cell.clone(); |
| 3254 | - out.effects.push(Box::pin(async move { | |
| 3210 | + out.spawn_scoped(async move { | |
| 3255 | 3211 | let started = crate::asyncrt::mono_ms(); |
| 3256 | 3212 | let result = ownership.read_owner(&cell).await; |
| 3257 | 3213 | CompletedEffect::timed( |
| @@ -3264,13 +3220,13 @@ | ||
| 3264 | 3220 | RouteStage::OwnershipRead, |
| 3265 | 3221 | started, |
| 3266 | 3222 | ) |
| 3267 | - })); | |
| 3223 | + }); | |
| 3268 | 3224 | } |
| 3269 | 3225 | Effect::ReadNodeLease { op, cell, owner } => { |
| 3270 | 3226 | self.route_effect_started(&cell); |
| 3271 | 3227 | let ownership = self.ownership.clone(); |
| 3272 | 3228 | let timing_cell = cell; |
| 3273 | - out.effects.push(Box::pin(async move { | |
| 3229 | + out.spawn_scoped(async move { | |
| 3274 | 3230 | let started = crate::asyncrt::mono_ms(); |
| 3275 | 3231 | let result = ownership.read_node_lease(&owner).await; |
| 3276 | 3232 | CompletedEffect::timed( |
| @@ -3283,13 +3239,13 @@ | ||
| 3283 | 3239 | RouteStage::NodeLeaseLookup, |
| 3284 | 3240 | started, |
| 3285 | 3241 | ) |
| 3286 | - })); | |
| 3242 | + }); | |
| 3287 | 3243 | } |
| 3288 | 3244 | Effect::RecoverNodeLog { op, cell, owner } => { |
| 3289 | 3245 | self.route_effect_started(&cell); |
| 3290 | 3246 | let interlock = self.node_log.lock().unwrap().clone(); |
| 3291 | 3247 | let timing_cell = cell.clone(); |
| 3292 | - out.effects.push(Box::pin(async move { | |
| 3248 | + out.spawn_scoped(async move { | |
| 3293 | 3249 | let started = crate::asyncrt::mono_ms(); |
| 3294 | 3250 | let result = match interlock { |
| 3295 | 3251 | // No log tier on this node (no bucket): nothing to |
| @@ -3311,13 +3267,13 @@ | ||
| 3311 | 3267 | RouteStage::NodeLeaseLookup, |
| 3312 | 3268 | started, |
| 3313 | 3269 | ) |
| 3314 | - })); | |
| 3270 | + }); | |
| 3315 | 3271 | } |
| 3316 | 3272 | Effect::ReadCapacityPeers { op, cell } => { |
| 3317 | 3273 | self.route_effect_started(&cell); |
| 3318 | 3274 | let ownership = self.ownership.clone(); |
| 3319 | 3275 | let timing_cell = cell; |
| 3320 | - out.effects.push(Box::pin(async move { | |
| 3276 | + out.spawn_scoped(async move { | |
| 3321 | 3277 | let started = crate::asyncrt::mono_ms(); |
| 3322 | 3278 | // The shared sample, judged at the instant it was taken: |
| 3323 | 3279 | // its leases are copies that age while the nodes renew. |
| @@ -3331,7 +3287,7 @@ | ||
| 3331 | 3287 | RouteStage::CapacityLookup, |
| 3332 | 3288 | started, |
| 3333 | 3289 | ) |
| 3334 | - })); | |
| 3290 | + }); | |
| 3335 | 3291 | } |
| 3336 | 3292 | Effect::CasOwner { |
| 3337 | 3293 | op, |
| @@ -3348,7 +3304,7 @@ | ||
| 3348 | 3304 | } |
| 3349 | 3305 | let ownership = self.ownership.clone(); |
| 3350 | 3306 | let timing_cell = cell.clone(); |
| 3351 | - out.effects.push(Box::pin(async move { | |
| 3307 | + out.spawn_scoped(async move { | |
| 3352 | 3308 | let started = crate::asyncrt::mono_ms(); |
| 3353 | 3309 | let result = ownership.cas_owner(&cell, guard, epoch).await; |
| 3354 | 3310 | CompletedEffect::timed( |
| @@ -3357,7 +3313,7 @@ | ||
| 3357 | 3313 | RouteStage::OwnershipAcquire, |
| 3358 | 3314 | started, |
| 3359 | 3315 | ) |
| 3360 | - })); | |
| 3316 | + }); | |
| 3361 | 3317 | } |
| 3362 | 3318 | Effect::ReconcileWakeEntry { cell, alarm } => { |
| 3363 | 3319 | self.schedule_wake_maintenance(cell, alarm); |
| @@ -3374,10 +3330,10 @@ | ||
| 3374 | 3330 | ); |
| 3375 | 3331 | } |
| 3376 | 3332 | let ownership = self.ownership.clone(); |
| 3377 | - out.effects.push(Box::pin(async move { | |
| 3333 | + out.spawn_scoped(async move { | |
| 3378 | 3334 | let result = ownership.release_owner(&cell, epoch).await; |
| 3379 | 3335 | CompletedEffect::plain(Event::OwnerReleased { op, result }) |
| 3380 | - })); | |
| 3336 | + }); | |
| 3381 | 3337 | } |
| 3382 | 3338 | Effect::AdoptReleased { |
| 3383 | 3339 | op, |
| @@ -3411,7 +3367,7 @@ | ||
| 3411 | 3367 | // next request to claim. |
| 3412 | 3368 | let deadline = |
| 3413 | 3369 | 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 { | |
| 3415 | 3371 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 3416 | 3372 | let request = HandoffRequest { |
| 3417 | 3373 | cell: cell.clone(), |
| @@ -3463,9 +3419,43 @@ | ||
| 3463 | 3419 | Ok(HandoffAttempt::CurrentOwner(owner)) => { |
| 3464 | 3420 | target = owner; |
| 3465 | 3421 | } |
| 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 | + } | |
| 3469 | 3459 | } |
| 3470 | 3460 | } |
| 3471 | 3461 | } |
| @@ -3494,7 +3484,7 @@ | ||
| 3494 | 3484 | }), |
| 3495 | 3485 | None => adoption.await, |
| 3496 | 3486 | } |
| 3497 | - })); | |
| 3487 | + }); | |
| 3498 | 3488 | } |
| 3499 | 3489 | Effect::CancelCellActivity { |
| 3500 | 3490 | cell, |
| @@ -3554,7 +3544,7 @@ | ||
| 3554 | 3544 | match runtime.alarm_observation(&cell) { |
| 3555 | 3545 | Some((mut alarm, false)) if alarm.at_ms().is_some() => { |
| 3556 | 3546 | let at_ms = alarm.at_ms().unwrap(); |
| 3557 | - out.effects.push(Box::pin(async move { | |
| 3547 | + out.spawn_scoped(async move { | |
| 3558 | 3548 | let started = crate::asyncrt::mono_ms(); |
| 3559 | 3549 | // One refresh is not enough for an object |
| 3560 | 3550 | // that re-arms its alarm continuously (the |
| @@ -3601,7 +3591,7 @@ | ||
| 3601 | 3591 | now_ms: now_ms(), |
| 3602 | 3592 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 3603 | 3593 | }) |
| 3604 | - })); | |
| 3594 | + }); | |
| 3605 | 3595 | } |
| 3606 | 3596 | Some((alarm, covered)) => immediate.push_back(Event::AlarmObserved { |
| 3607 | 3597 | cell, |
| @@ -3618,11 +3608,11 @@ | ||
| 3618 | 3608 | self.route_effect_started(&cell); |
| 3619 | 3609 | if let Some(runtime) = self.host.clone() { |
| 3620 | 3610 | 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 { | |
| 3626 | 3616 | let started = crate::asyncrt::mono_ms(); |
| 3627 | 3617 | let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| { |
| 3628 | 3618 | eprintln!("celld restore failed for {cell}: {error:#}"); |
| @@ -3635,9 +3625,6 @@ | ||
| 3635 | 3625 | started, |
| 3636 | 3626 | ) |
| 3637 | 3627 | }); |
| 3638 | - out.effects.push(Box::pin(async move { | |
| 3639 | - task.await.expect("restore task panicked") | |
| 3640 | - })); | |
| 3641 | 3628 | } else { |
| 3642 | 3629 | self.record_effect_timing(EffectTiming { |
| 3643 | 3630 | cell, |
| @@ -3662,7 +3649,7 @@ | ||
| 3662 | 3649 | .and_then(|timing| timing.fresh) |
| 3663 | 3650 | .unwrap_or(false); |
| 3664 | 3651 | let timing_cell = cell.clone(); |
| 3665 | - out.effects.push(Box::pin(async move { | |
| 3652 | + out.spawn_scoped(async move { | |
| 3666 | 3653 | let started = crate::asyncrt::mono_ms(); |
| 3667 | 3654 | let placed = runtime |
| 3668 | 3655 | .start_cell(cell.clone(), epoch, fresh) |
| @@ -3687,7 +3674,7 @@ | ||
| 3687 | 3674 | RouteStage::IsolateStartup, |
| 3688 | 3675 | started, |
| 3689 | 3676 | ) |
| 3690 | - })); | |
| 3677 | + }); | |
| 3691 | 3678 | } else { |
| 3692 | 3679 | self.record_effect_timing(EffectTiming { |
| 3693 | 3680 | cell, |
| @@ -3767,13 +3754,11 @@ | ||
| 3767 | 3754 | ); |
| 3768 | 3755 | } |
| 3769 | 3756 | 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 { | |
| 3777 | 3762 | let proved = runtime.ensure_durable(&cell, epoch, revocable).await; |
| 3778 | 3763 | let result = proved.map_err(|error| { |
| 3779 | 3764 | eprintln!( |
| @@ -3783,9 +3768,6 @@ | ||
| 3783 | 3768 | }); |
| 3784 | 3769 | CompletedEffect::plain(Event::DurabilityChecked { op, result }) |
| 3785 | 3770 | }); |
| 3786 | - out.effects.push(Box::pin(async move { | |
| 3787 | - task.await.expect("durability proof task panicked") | |
| 3788 | - })); | |
| 3789 | 3771 | } else { |
| 3790 | 3772 | immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) }); |
| 3791 | 3773 | } |
| @@ -3800,7 +3782,7 @@ | ||
| 3800 | 3782 | position, |
| 3801 | 3783 | } => { |
| 3802 | 3784 | if let Some(runtime) = self.host.clone() { |
| 3803 | - out.effects.push(Box::pin(async move { | |
| 3785 | + out.spawn_scoped(async move { | |
| 3804 | 3786 | // The replicator reports the position it actually |
| 3805 | 3787 | // proved durable and which mechanism proved it; the |
| 3806 | 3788 | // core acks only if the position covers this write, |
| @@ -3818,7 +3800,7 @@ | ||
| 3818 | 3800 | } |
| 3819 | 3801 | }; |
| 3820 | 3802 | CompletedEffect::plain(Event::DurableReached { op, result, source }) |
| 3821 | - })); | |
| 3803 | + }); | |
| 3822 | 3804 | } else { |
| 3823 | 3805 | immediate.push_back(Event::DurableReached { |
| 3824 | 3806 | op, |
| @@ -3838,7 +3820,7 @@ | ||
| 3838 | 3820 | // restores from a lineage that already contains the write. |
| 3839 | 3821 | let ownership = self.ownership.clone(); |
| 3840 | 3822 | let node = self.state.node().to_string(); |
| 3841 | - out.effects.push(Box::pin(async move { | |
| 3823 | + out.spawn_scoped(async move { | |
| 3842 | 3824 | let result = match ownership.read_owner(&cell).await { |
| 3843 | 3825 | Ok(Some(record)) |
| 3844 | 3826 | if record.node.as_deref() == Some(node.as_str()) |
| @@ -3857,7 +3839,7 @@ | ||
| 3857 | 3839 | Err(failure) => Err(failure), |
| 3858 | 3840 | }; |
| 3859 | 3841 | CompletedEffect::plain(Event::OwnershipVerified { op, result }) |
| 3860 | - })); | |
| 3842 | + }); | |
| 3861 | 3843 | } |
| 3862 | 3844 | // The shell's only per-channel code: how the effect was held, and |
| 3863 | 3845 | // how it is released. Every channel but one takes a durability |
| @@ -3924,7 +3906,7 @@ | ||
| 3924 | 3906 | self.published.remove(&cell); |
| 3925 | 3907 | if let Some(runtime) = self.host.clone() { |
| 3926 | 3908 | let released = cell.clone(); |
| 3927 | - let task = crate::asyncrt::spawn(report_stopped_when_released( | |
| 3909 | + out.spawn_detached(report_stopped_when_released( | |
| 3928 | 3910 | op, |
| 3929 | 3911 | cell, |
| 3930 | 3912 | epoch, |
| @@ -3936,9 +3918,6 @@ | ||
| 3936 | 3918 | async move { runtime.swap_out_cell(&cell, epoch).await } |
| 3937 | 3919 | }, |
| 3938 | 3920 | )); |
| 3939 | - out.effects.push(Box::pin(async move { | |
| 3940 | - task.await.expect("swap out task panicked") | |
| 3941 | - })); | |
| 3942 | 3921 | } else { |
| 3943 | 3922 | immediate.push_back(Event::RuntimeStopped { op }); |
| 3944 | 3923 | } |
| @@ -3974,25 +3953,21 @@ | ||
| 3974 | 3953 | StopCause::Swap => unreachable!("generation swaps return above"), |
| 3975 | 3954 | }; |
| 3976 | 3955 | 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); | |
| 3980 | 3957 | } |
| 3981 | 3958 | self.published.remove(&cell); |
| 3982 | 3959 | 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. | |
| 3991 | 3966 | let released = cell.clone(); |
| 3992 | 3967 | let deadline_mono_ms = bounded.then(|| { |
| 3993 | 3968 | crate::asyncrt::mono_ms().saturating_add(self.operation_deadline_ms) |
| 3994 | 3969 | }); |
| 3995 | - let task = crate::asyncrt::spawn(report_stopped_when_released( | |
| 3970 | + out.spawn_detached(report_stopped_when_released( | |
| 3996 | 3971 | op, |
| 3997 | 3972 | cell, |
| 3998 | 3973 | epoch, |
| @@ -4005,9 +3980,6 @@ | ||
| 4005 | 3980 | async move { runtime.stop_cell(&cell, epoch, stop_mode).await } |
| 4006 | 3981 | }, |
| 4007 | 3982 | )); |
| 4008 | - out.effects.push(Box::pin(async move { | |
| 4009 | - task.await.expect("stop runtime task panicked") | |
| 4010 | - })); | |
| 4011 | 3983 | } else { |
| 4012 | 3984 | immediate.push_back(Event::RuntimeStopped { op }); |
| 4013 | 3985 | } |
| @@ -4034,7 +4006,7 @@ | ||
| 4034 | 4006 | scheduled_ms, |
| 4035 | 4007 | } => { |
| 4036 | 4008 | if let Some(runtime) = self.host.clone() { |
| 4037 | - out.effects.push(Box::pin(async move { | |
| 4009 | + out.spawn_scoped(async move { | |
| 4038 | 4010 | // The shell reports the firing raw: the deadline that |
| 4039 | 4011 | // stands after the handler, whether a wake entry |
| 4040 | 4012 | // covers it, and the position of the consuming |
| @@ -4061,7 +4033,7 @@ | ||
| 4061 | 4033 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 4062 | 4034 | result, |
| 4063 | 4035 | }) |
| 4064 | - })); | |
| 4036 | + }); | |
| 4065 | 4037 | } else { |
| 4066 | 4038 | immediate.push_back(Event::AlarmFinished { |
| 4067 | 4039 | op, |
| @@ -4161,18 +4133,22 @@ | ||
| 4161 | 4133 | fn state_json(&self) -> String { |
| 4162 | 4134 | // The lease sample reads counts the load tick last stored. Store them |
| 4163 | 4135 | // 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")); | |
| 4176 | 4152 | let activity = self.state.presence_snapshot().activity; |
| 4177 | 4153 | let residents = self |
| 4178 | 4154 | .state |
| @@ -4187,9 +4163,6 @@ | ||
| 4187 | 4163 | .map(|cell| format!("{cell:?}")) |
| 4188 | 4164 | .collect::<Vec<_>>() |
| 4189 | 4165 | .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(); | |
| 4193 | 4166 | // `restoring` is a sum, and a node that refuses cells for a quarter of |
| 4194 | 4167 | // an hour needs its parts. `activating` holds a permit and is doing |
| 4195 | 4168 | // work; `activation_waiting` is queued behind the activation ceiling; |
| @@ -4225,18 +4198,18 @@ | ||
| 4225 | 4198 | self.state |
| 4226 | 4199 | .shed_reason() |
| 4227 | 4200 | .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. | |
| 4232 | 4205 | serde_json::to_string(&crate::memory::allocator_stats()) |
| 4233 | 4206 | .unwrap_or_else(|_| "null".to_string()), |
| 4234 | 4207 | serde_json::to_string(&crate::memory::libc_malloc_stats()) |
| 4235 | 4208 | .unwrap_or_else(|_| "null".to_string()), |
| 4236 | - memory | |
| 4209 | + sample | |
| 4237 | 4210 | .cgroup_working_set_bytes |
| 4238 | 4211 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
| 4239 | - memory | |
| 4212 | + sample | |
| 4240 | 4213 | .cgroup_current_bytes |
| 4241 | 4214 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
| 4242 | 4215 | 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 @@ | ||
| 1309 | 1309 | Ok(()) |
| 1310 | 1310 | } |
| 1311 | 1311 | |
| 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 | + | |
| 1312 | 1322 | fn validate_index(index: &AssetIndex, reference: &AssetManifestRef) -> anyhow::Result<()> { |
| 1323 | + let max_file_bytes = crate::env_vars::max_asset_file_bytes()?; | |
| 1313 | 1324 | if index.schema_version != 1 { |
| 1314 | 1325 | return Err(anyhow!( |
| 1315 | 1326 | "unsupported asset index schema: {}", |
| @@ -1374,13 +1385,11 @@ | ||
| 1374 | 1385 | } |
| 1375 | 1386 | let mut total = 0_u64; |
| 1376 | 1387 | 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() | |
| 1381 | 1389 | { |
| 1382 | 1390 | return Err(anyhow!("invalid asset index entry: {path:?}")); |
| 1383 | 1391 | } |
| 1392 | + validate_asset_file_size(path, entry.bytes, max_file_bytes)?; | |
| 1384 | 1393 | if entry |
| 1385 | 1394 | .content_type |
| 1386 | 1395 | .as_deref() |
modifiedcrates/celld/asyncrt.rs+12−3View file
| @@ -58,8 +58,13 @@ | ||
| 58 | 58 | } |
| 59 | 59 | } |
| 60 | 60 | |
| 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. | |
| 61 | 64 | 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") | |
| 63 | 68 | } |
| 64 | 69 | |
| 65 | 70 | struct ProductionDomainOwner { |
| @@ -181,9 +186,13 @@ | ||
| 181 | 186 | } |
| 182 | 187 | } |
| 183 | 188 | |
| 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. | |
| 185 | 191 | 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 | + ); | |
| 187 | 196 | } |
| 188 | 197 | |
| 189 | 198 | /// Return the Tokio handle for the V8 arm. |
modifiedcrates/celld/cell_cli.rs+270−3View file
| @@ -87,6 +87,12 @@ | ||
| 87 | 87 | pub(crate) fn list_options_from_arguments( |
| 88 | 88 | arguments: Vec<String>, |
| 89 | 89 | ) -> 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>> { | |
| 90 | 96 | let mut options = ListOptions::default(); |
| 91 | 97 | let mut arguments = arguments.into_iter(); |
| 92 | 98 | while let Some(argument) = arguments.next() { |
| @@ -111,11 +117,11 @@ | ||
| 111 | 117 | // mistyped option rather than a class named "--clas". |
| 112 | 118 | if other.starts_with('-') { |
| 113 | 119 | 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" | |
| 115 | 121 | ); |
| 116 | 122 | } |
| 117 | 123 | 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:?}"); | |
| 119 | 125 | } |
| 120 | 126 | options.class = Some(other.to_string()); |
| 121 | 127 | } |
| @@ -142,6 +148,8 @@ | ||
| 142 | 148 | USAGE: |
| 143 | 149 | celld cell list [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] |
| 144 | 150 | |
| 151 | +Run `celld cell gc --help` for the report of superseded epochs. | |
| 152 | + | |
| 145 | 153 | The listing is bounded by default, because a fleet can hold far more cells |
| 146 | 154 | than an operator wants to read and each request returns at most {page} |
| 147 | 155 | children. A bounded answer reports on stderr that more cells exist. |
| @@ -186,10 +194,11 @@ | ||
| 186 | 194 | let mut arguments = arguments.into_iter(); |
| 187 | 195 | match arguments.next().as_deref() { |
| 188 | 196 | Some("list") => run_list(arguments.collect()).await, |
| 197 | + Some("gc") => run_gc(arguments.collect()).await, | |
| 189 | 198 | None | Some("-h") | Some("--help") | Some("help") => { |
| 190 | 199 | Output::new(Format::Text).help(&help_text()) |
| 191 | 200 | } |
| 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"), | |
| 193 | 202 | } |
| 194 | 203 | } |
| 195 | 204 | |
| @@ -257,3 +266,261 @@ | ||
| 257 | 266 | } |
| 258 | 267 | Ok(()) |
| 259 | 268 | } |
| 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 @@ | ||
| 22 | 22 | } |
| 23 | 23 | |
| 24 | 24 | 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 | + | |
| 25 | 43 | pub(crate) fn local_reload_cells(&self) -> anyhow::Result<Vec<celld_logic::LocalCell>> { |
| 26 | 44 | match self { |
| 27 | 45 | Self::Engine(runtime) => runtime.local_reload_cells(), |
modifiedcrates/celld/control_plane.rs+1−4View file
| @@ -2198,10 +2198,7 @@ | ||
| 2198 | 2198 | if asset_blob_key(sha256).is_none() { |
| 2199 | 2199 | return Err(anyhow!("invalid asset digest in index: {sha256:?}")); |
| 2200 | 2200 | } |
| 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()?) | |
| 2205 | 2202 | } |
| 2206 | 2203 | |
| 2207 | 2204 | async fn connect(options: ConnectOptions, wait: bool) -> anyhow::Result<()> { |
modifiedcrates/celld/deploy.rs+30−8View file
| @@ -18,8 +18,9 @@ | ||
| 18 | 18 | asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest, |
| 19 | 19 | ModuleKind, ModuleRef, QueueConsumerAttachment, QueueConsumerConfig, QueueConsumerDeployment, |
| 20 | 20 | 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, | |
| 23 | 24 | }; |
| 24 | 25 | use anyhow::{anyhow, bail, Context}; |
| 25 | 26 | use flate2::write::GzEncoder; |
| @@ -34,6 +35,8 @@ | ||
| 34 | 35 | use std::process::Command; |
| 35 | 36 | use std::time::{Duration, Instant}; |
| 36 | 37 | |
| 38 | +mod python; | |
| 39 | + | |
| 37 | 40 | /// Config keys we understand. Anything else is an error: refusing is |
| 38 | 41 | /// compat-safe, guessing produces confusing activation failures later. |
| 39 | 42 | const SUPPORTED_KEYS: &[&str] = &[ |
| @@ -181,7 +184,6 @@ | ||
| 181 | 184 | |
| 182 | 185 | const MAX_ASSET_FILES: usize = 20_000; |
| 183 | 186 | const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024; |
| 184 | -const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024; | |
| 185 | 187 | const MAX_ASSET_DIRECTIVE_BYTES: u64 = 100 * 1024; |
| 186 | 188 | const ASSET_UPLOAD_CONCURRENCY: usize = 16; |
| 187 | 189 | |
| @@ -299,6 +301,9 @@ | ||
| 299 | 301 | has_queues: bool, |
| 300 | 302 | has_r2: bool, |
| 301 | 303 | 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>, | |
| 302 | 307 | } |
| 303 | 308 | |
| 304 | 309 | /// The two Wrangler bundling knobs that celld forwards to esbuild. |
| @@ -600,7 +605,11 @@ | ||
| 600 | 605 | .entry |
| 601 | 606 | .as_deref() |
| 602 | 607 | .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 { | |
| 604 | 613 | // Already bundled by the caller's toolchain. Read it as it is; |
| 605 | 614 | // running esbuild over a Vite build is what corrupts it. |
| 606 | 615 | let path = root.join(entry); |
| @@ -652,6 +661,7 @@ | ||
| 652 | 661 | .and_then(Value::as_array) |
| 653 | 662 | .is_some_and(|flags| flags.iter().any(|flag| flag.as_str() == Some("sqlite_vec"))); |
| 654 | 663 | let uses_d1 = project.do_classes.iter().any(|class| class == D1_CLASS); |
| 664 | + let python_runtime = project.python.is_some(); | |
| 655 | 665 | let manifest = Manifest { |
| 656 | 666 | schema_version: if asset_reference.is_some() { 2 } else { 1 }, |
| 657 | 667 | version: version.clone(), |
| @@ -708,6 +718,9 @@ | ||
| 708 | 718 | if !wasm_names.is_empty() { |
| 709 | 719 | features.push(FEATURE_WASM_V1.to_string()); |
| 710 | 720 | } |
| 721 | + if python_runtime { | |
| 722 | + features.push(FEATURE_PYTHON_WORKERS_V1.to_string()); | |
| 723 | + } | |
| 711 | 724 | features |
| 712 | 725 | }, |
| 713 | 726 | raw_metadata: project.metadata, |
| @@ -1315,6 +1328,14 @@ | ||
| 1315 | 1328 | if no_bundle && main.is_none() { |
| 1316 | 1329 | bail!("config sets `no_bundle` without `main`"); |
| 1317 | 1330 | } |
| 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()?; | |
| 1318 | 1339 | let bundle = read_bundle_config(object)?; |
| 1319 | 1340 | // `define` and `rules` describe the esbuild run, and `no_bundle` is the |
| 1320 | 1341 | // absence of one. Accepting both would produce a deployment that silently |
| @@ -1951,6 +1972,7 @@ | ||
| 1951 | 1972 | queue_consumers, |
| 1952 | 1973 | has_r2: !r2_buckets.is_empty(), |
| 1953 | 1974 | containers, |
| 1975 | + python, | |
| 1954 | 1976 | }) |
| 1955 | 1977 | } |
| 1956 | 1978 | |
| @@ -2583,6 +2605,7 @@ | ||
| 2583 | 2605 | } |
| 2584 | 2606 | |
| 2585 | 2607 | fn build_assets(project: &ProjectAssets) -> anyhow::Result<BuiltAssets> { |
| 2608 | + let max_file_bytes = crate::env_vars::max_asset_file_bytes()?; | |
| 2586 | 2609 | let mut files = Vec::new(); |
| 2587 | 2610 | collect_asset_files(&project.directory, "", &mut files)?; |
| 2588 | 2611 | files.sort_by(|left, right| left.0.cmp(&right.0)); |
| @@ -2596,9 +2619,8 @@ | ||
| 2596 | 2619 | for (relative, path) in files { |
| 2597 | 2620 | let metadata = |
| 2598 | 2621 | 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)?; | |
| 2602 | 2624 | total_bytes = total_bytes |
| 2603 | 2625 | .checked_add(metadata.len()) |
| 2604 | 2626 | .context("asset byte count overflow")?; |
| @@ -2612,7 +2634,7 @@ | ||
| 2612 | 2634 | let sha256 = format!("{:x}", Sha256::digest(&body)); |
| 2613 | 2635 | blobs.entry(sha256.clone()).or_insert(body); |
| 2614 | 2636 | entries.insert( |
| 2615 | - format!("/{relative}"), | |
| 2637 | + asset_path, | |
| 2616 | 2638 | AssetEntry { |
| 2617 | 2639 | sha256, |
| 2618 | 2640 | 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 @@ | ||
| 613 | 613 | return None; |
| 614 | 614 | } |
| 615 | 615 | 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() { | |
| 617 | 617 | let nibble = |byte| match byte { |
| 618 | 618 | b'0'..=b'9' => Some(byte - b'0'), |
| 619 | 619 | b'a'..=b'f' => Some(byte - b'a' + 10), |
| @@ -831,6 +831,12 @@ | ||
| 831 | 831 | .then(|| anyhow::anyhow!("injected generation swap release failure")) |
| 832 | 832 | } |
| 833 | 833 | |
| 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 | + | |
| 834 | 840 | /// The replication stream of a facet: nested under its root's own |
| 835 | 841 | /// coordinates, `<root>/facets/<h>` locally and `cells/<root>/facets/<h>/` |
| 836 | 842 | /// 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 @@ | ||
| 9 | 9 | use anyhow::{anyhow, bail}; |
| 10 | 10 | |
| 11 | 11 | 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 | + | |
| 12 | 30 | /// One process stop budget and the internal waits derived from it. |
| 13 | 31 | /// The absolute deadline also bounds progress extensions, so neither wait |
| 14 | 32 | /// grants time beyond the supervisor-facing process budget. |
| @@ -233,6 +251,7 @@ | ||
| 233 | 251 | "CELLD_LTX_COMPACTION_MIN_TXIDS", |
| 234 | 252 | "CELLD_LTX_DURABILITY_TIMEOUT_SECS", |
| 235 | 253 | "CELLD_MAX_CELL_REQUESTS", |
| 254 | + "CELLD_MAX_ASSET_FILE_BYTES", | |
| 236 | 255 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 237 | 256 | "CELLD_MAX_REQUEST_BODY_BYTES", |
| 238 | 257 | "CELLD_MAX_REQUESTS", |
| @@ -256,6 +275,7 @@ | ||
| 256 | 275 | "CELLD_DEPLOY_MAX_AGE_S", |
| 257 | 276 | "CELLD_LOCAL_CACHE_MAX_BYTES", |
| 258 | 277 | "CELLD_LTX_TRUNCATE_PAGES", |
| 278 | + "CELLD_LTX_RETENTION_SECS", | |
| 259 | 279 | "CELLD_LOG_HEDGE_MS", |
| 260 | 280 | "CELLD_LOG_WINDOW", |
| 261 | 281 | "CELLD_LOG_WINDOW_BYTES", |
| @@ -269,6 +289,8 @@ | ||
| 269 | 289 | |
| 270 | 290 | shutdown_timing()?; |
| 271 | 291 | |
| 292 | + positive::<usize>("CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES")?; | |
| 293 | + | |
| 272 | 294 | if let Some(value) = optional::<u64>("CELLD_PRESENCE_HEARTBEAT_MS")? { |
| 273 | 295 | if !(50..=30_000).contains(&value) { |
| 274 | 296 | 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 @@ | ||
| 280 | 280 | pub fn set_r2_store(bucket: Bucket) { |
| 281 | 281 | let _ = R2_STORE.set(bucket); |
| 282 | 282 | } |
| 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 @@ | ||
| 9 | 9 | use crate::ownership_store::LiveLoad; |
| 10 | 10 | use std::sync::{Arc, Mutex, OnceLock}; |
| 11 | 11 | |
| 12 | -/// One resource observation used by the pressure path. | |
| 12 | +/// One resource observation shared by pressure decisions and node leases. | |
| 13 | 13 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 14 | 14 | pub struct HostMetricsSample { |
| 15 | 15 | pub cpu_percent_x100: u64, |
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | pub in_use_bytes: u64, |
| 18 | 18 | pub cgroup_working_set_bytes: Option<u64>, |
| 19 | 19 | pub cgroup_current_bytes: Option<u64>, |
| 20 | + pub open_fds: u64, | |
| 21 | + pub fd_limit: u64, | |
| 20 | 22 | } |
| 21 | 23 | |
| 22 | 24 | enum MetricsBackend { |
| @@ -136,17 +138,43 @@ | ||
| 136 | 138 | self.http_streams.close(); |
| 137 | 139 | } |
| 138 | 140 | |
| 141 | + /// Collect off the core so filesystem reads cannot delay a lease. | |
| 142 | + #[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage. | |
| 139 | 143 | pub fn sample_metrics(&self) -> HostMetricsSample { |
| 140 | 144 | match &self.metrics { |
| 141 | 145 | MetricsBackend::Production(sampler) => { |
| 142 | 146 | let mut sampler = sampler.lock().unwrap(); |
| 143 | 147 | 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 | + | |
| 144 | 170 | HostMetricsSample { |
| 145 | 171 | cpu_percent_x100: sampler.sample_cpu_percent_x100(), |
| 146 | 172 | rss_bytes: memory.rss_bytes, |
| 147 | 173 | in_use_bytes: memory.in_use_bytes, |
| 148 | 174 | cgroup_working_set_bytes: memory.cgroup_working_set_bytes, |
| 149 | 175 | cgroup_current_bytes: memory.cgroup_current_bytes, |
| 176 | + open_fds, | |
| 177 | + fd_limit, | |
| 150 | 178 | } |
| 151 | 179 | } |
| 152 | 180 | #[cfg(celld_internal_tests)] |
modifiedcrates/celld/js.rs+291−100View file
| @@ -614,6 +614,9 @@ | ||
| 614 | 614 | scope: String, |
| 615 | 615 | ws_id: u64, |
| 616 | 616 | 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<()>>, | |
| 617 | 620 | reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>, |
| 618 | 621 | }, |
| 619 | 622 | WsClosed { |
| @@ -746,6 +749,7 @@ | ||
| 746 | 749 | |
| 747 | 750 | #[doc(hidden)] |
| 748 | 751 | pub mod websocket; |
| 752 | +use crate::host_channels::GateRefusal; | |
| 749 | 753 | pub(crate) use websocket::WebSocketService; |
| 750 | 754 | pub use websocket::*; |
| 751 | 755 | use websocket::{ |
| @@ -947,41 +951,6 @@ | ||
| 947 | 951 | } |
| 948 | 952 | } |
| 949 | 953 | |
| 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 | - | |
| 985 | 954 | /// Take one ticket on the output gate and wait for the core's verdict. |
| 986 | 955 | /// |
| 987 | 956 | /// This is the output gate applied to an in-handler effect rather than to the |
| @@ -1010,31 +979,17 @@ | ||
| 1010 | 979 | (cell, channel, None, observed, epoch) |
| 1011 | 980 | } |
| 1012 | 981 | }; |
| 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 | |
| 1038 | 993 | } |
| 1039 | 994 | |
| 1040 | 995 | /// Wait for the writes an outbound effect can reveal to be proven durable |
| @@ -1063,11 +1018,13 @@ | ||
| 1063 | 1018 | request: T, |
| 1064 | 1019 | missing: &'static str, |
| 1065 | 1020 | ) -> 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 | |
| 1071 | 1028 | } |
| 1072 | 1029 | |
| 1073 | 1030 | /// One `celld_logic::gate::InputGate` per cell. |
| @@ -3452,13 +3409,24 @@ | ||
| 3452 | 3409 | send_and_end(tc, &self.context, reply, outcome) |
| 3453 | 3410 | } |
| 3454 | 3411 | 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, | |
| 3459 | 3422 | write_position, |
| 3460 | 3423 | observed_position, |
| 3461 | - }); | |
| 3424 | + }), | |
| 3425 | + Err(error) => { | |
| 3426 | + frames.discard(); | |
| 3427 | + Err(error) | |
| 3428 | + } | |
| 3429 | + }; | |
| 3462 | 3430 | send_and_end(tc, &self.context, reply, dispatch) |
| 3463 | 3431 | } |
| 3464 | 3432 | Answer::Ack(reply) => send_and_end(tc, &self.context, reply, self.write_delta()), |
| @@ -4431,6 +4399,13 @@ | ||
| 4431 | 4399 | let _cpu_watchdog = cpu_watchdog_for_context(tc, &entry.context); |
| 4432 | 4400 | settle(tc, entry); |
| 4433 | 4401 | 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(); | |
| 4434 | 4409 | } |
| 4435 | 4410 | if let Err(error) = finish_cpu_turn(tc, entry) { |
| 4436 | 4411 | let error = take_execution_termination_in_context(tc, Some(&entry.context)) |
| @@ -5346,6 +5321,7 @@ | ||
| 5346 | 5321 | ws_id, |
| 5347 | 5322 | data, |
| 5348 | 5323 | reply, |
| 5324 | + .. | |
| 5349 | 5325 | } => start_cell_event( |
| 5350 | 5326 | tc, |
| 5351 | 5327 | &scope, |
| @@ -6132,7 +6108,7 @@ | ||
| 6132 | 6108 | cell: &str, |
| 6133 | 6109 | parent: &storage::StorageIdentity, |
| 6134 | 6110 | name: &str, |
| 6135 | - id: &str, | |
| 6111 | + id_sc: Vec<u8>, | |
| 6136 | 6112 | props_sc: Vec<u8>, |
| 6137 | 6113 | file: (std::path::PathBuf, bool), |
| 6138 | 6114 | ) -> Result<Option<i64>> { |
| @@ -6158,7 +6134,7 @@ | ||
| 6158 | 6134 | parent, |
| 6159 | 6135 | name, |
| 6160 | 6136 | EmbeddedStartup { |
| 6161 | - id, | |
| 6137 | + id_sc, | |
| 6162 | 6138 | props_sc, |
| 6163 | 6139 | path, |
| 6164 | 6140 | restored, |
| @@ -6779,6 +6755,7 @@ | ||
| 6779 | 6755 | "__response_stream_closed" => op_response_stream_closed, |
| 6780 | 6756 | "__response_stream_close" => op_response_stream_close, |
| 6781 | 6757 | "__op_timer" => op_timer, |
| 6758 | + "__isolate_condemn" => op_isolate_condemn, | |
| 6782 | 6759 | "__timer_alloc" => op_timer_alloc, |
| 6783 | 6760 | "__io_context_id" => op_io_context_id, |
| 6784 | 6761 | "__with_input_gate_context" => op_with_input_gate_context, |
| @@ -7166,10 +7143,22 @@ | ||
| 7166 | 7143 | // and invokes it. The loaded isolate uses the same turn driver as every |
| 7167 | 7144 | // stateless Worker, so an awaited operation holds no thread or isolate. |
| 7168 | 7145 | |
| 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; | |
| 7172 | 7149 | 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 | + | |
| 7173 | 7162 | /// The largest `props` value one loaded entrypoint or Durable Object class can |
| 7174 | 7163 | /// carry, as structured-clone bytes. Workerd does not impose this bound, but |
| 7175 | 7164 | /// celld holds the value on a host job for the whole call. The harness shares |
| @@ -7437,12 +7426,13 @@ | ||
| 7437 | 7426 | ModuleSource::Wasm(bytes) => bytes.len(), |
| 7438 | 7427 | }) |
| 7439 | 7428 | .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 { | |
| 7441 | 7431 | return loader_throw( |
| 7442 | 7432 | scope, |
| 7443 | 7433 | &format!( |
| 7444 | 7434 | "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." | |
| 7446 | 7436 | ), |
| 7447 | 7437 | ); |
| 7448 | 7438 | } |
| @@ -7866,7 +7856,7 @@ | ||
| 7866 | 7856 | parent_scope: String, |
| 7867 | 7857 | owner: String, |
| 7868 | 7858 | name: String, |
| 7869 | - id: String, | |
| 7859 | + id_sc: Vec<u8>, | |
| 7870 | 7860 | props_sc: Vec<u8>, |
| 7871 | 7861 | parent: storage::StorageIdentity, |
| 7872 | 7862 | } |
| @@ -7926,7 +7916,162 @@ | ||
| 7926 | 7916 | } |
| 7927 | 7917 | } |
| 7928 | 7918 | |
| 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 | + | |
| 7929 | 8067 | 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 | + }; | |
| 7930 | 8075 | let slot = host.slot().await?; |
| 7931 | 8076 | let file = open_facet_file(&start.parent, &start.name).await?; |
| 7932 | 8077 | let mut names = start.parent.facet_path.clone(); |
| @@ -7940,14 +8085,19 @@ | ||
| 7940 | 8085 | &start.name, |
| 7941 | 8086 | ); |
| 7942 | 8087 | 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}")) | |
| 7951 | 8101 | }) |
| 7952 | 8102 | .await |
| 7953 | 8103 | .map_err(|error| format!("worker loader facet: {error}"))?; |
| @@ -7969,7 +8119,9 @@ | ||
| 7969 | 8119 | let parent_scope = args.get(2).to_rust_string_lossy(scope); |
| 7970 | 8120 | let owner = args.get(3).to_rust_string_lossy(scope); |
| 7971 | 8121 | 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 | + }; | |
| 7973 | 8125 | let props_sc = match loader_props_bytes(args.get(6)) { |
| 7974 | 8126 | Ok(props) => props, |
| 7975 | 8127 | Err(error) => return loader_throw(scope, &error), |
| @@ -7996,7 +8148,7 @@ | ||
| 7996 | 8148 | parent_scope, |
| 7997 | 8149 | owner, |
| 7998 | 8150 | name, |
| 7999 | - id: facet_id, | |
| 8151 | + id_sc, | |
| 8000 | 8152 | props_sc, |
| 8001 | 8153 | parent, |
| 8002 | 8154 | }, |
| @@ -8049,7 +8201,9 @@ | ||
| 8049 | 8201 | let parent_scope = args.get(2).to_rust_string_lossy(scope); |
| 8050 | 8202 | let owner = args.get(3).to_rust_string_lossy(scope); |
| 8051 | 8203 | 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 | + }; | |
| 8053 | 8207 | let props_sc = match loader_props_bytes(args.get(6)) { |
| 8054 | 8208 | Ok(props) => props, |
| 8055 | 8209 | Err(error) => return loader_throw(scope, &error), |
| @@ -8098,7 +8252,7 @@ | ||
| 8098 | 8252 | parent_scope, |
| 8099 | 8253 | owner, |
| 8100 | 8254 | name, |
| 8101 | - id: facet_id, | |
| 8255 | + id_sc, | |
| 8102 | 8256 | props_sc, |
| 8103 | 8257 | parent, |
| 8104 | 8258 | }, |
| @@ -8154,11 +8308,22 @@ | ||
| 8154 | 8308 | let name = args.get(4).to_rust_string_lossy(scope); |
| 8155 | 8309 | let host = FacetHost::of(loader); |
| 8156 | 8310 | 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)); | |
| 8157 | 8317 | 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?; | |
| 8159 | 8321 | slot.turn(|worker| worker.own_cell(&facet_scope, None)) |
| 8160 | 8322 | .await |
| 8161 | 8323 | .map_err(|error| format!("abort facet: {error}"))?; |
| 8324 | + if let (true, Some((root, epoch))) = (loaded, root) { | |
| 8325 | + forget_root_facet(&root, epoch, &slot, &facet_scope); | |
| 8326 | + } | |
| 8162 | 8327 | Ok(Vec::new()) |
| 8163 | 8328 | }); |
| 8164 | 8329 | rv.set(promise_for(scope, async_id)); |
| @@ -8215,9 +8380,9 @@ | ||
| 8215 | 8380 | rv.set(promise_for(scope, async_id)); |
| 8216 | 8381 | } |
| 8217 | 8382 | |
| 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. | |
| 8221 | 8386 | fn op_loader_drop( |
| 8222 | 8387 | scope: &mut v8::PinScope, |
| 8223 | 8388 | args: v8::FunctionCallbackArguments, |
| @@ -9591,14 +9756,11 @@ | ||
| 9591 | 9756 | if let Some(context) = current_reaction_or_untracked_io_context(scope) { |
| 9592 | 9757 | context.record_tail_log(&level, &body); |
| 9593 | 9758 | } |
| 9594 | - let displayed = match level.as_str() { | |
| 9595 | - "error" => format!("ERROR {body}"), | |
| 9596 | - "warn" => format!("WARN {body}"), | |
| 9597 | - _ => body, | |
| 9598 | - }; | |
| 9599 | 9759 | // Correlated by CPED, so a continuation logging after an await — or |
| 9600 | 9760 | // another entry's continuation running in this turn's checkpoint — |
| 9601 | 9761 | // 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. | |
| 9602 | 9764 | if crate::telemetry::active() { |
| 9603 | 9765 | if let Some(ids) = |
| 9604 | 9766 | current_trace_context(scope).and_then(crate::telemetry::TraceContext::recording_ids) |
| @@ -9607,12 +9769,41 @@ | ||
| 9607 | 9769 | trace_id: Some(ids.trace_id), |
| 9608 | 9770 | span_id: Some(ids.span_id), |
| 9609 | 9771 | 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(), | |
| 9611 | 9774 | }); |
| 9612 | 9775 | } |
| 9613 | 9776 | } |
| 9777 | + let displayed = match level.as_str() { | |
| 9778 | + "error" => format!("ERROR {body}"), | |
| 9779 | + "warn" => format!("WARN {body}"), | |
| 9780 | + _ => body, | |
| 9781 | + }; | |
| 9614 | 9782 | tracing::info!(target: "cell_console", "{}", displayed); |
| 9615 | 9783 | } |
| 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 | + | |
| 9616 | 9807 | fn op_heap_limit_excessively_exceeded( |
| 9617 | 9808 | scope: &mut v8::PinScope, |
| 9618 | 9809 | _args: v8::FunctionCallbackArguments, |
modifiedcrates/celld/js/bootstrap.rs+7−5View file
| @@ -911,8 +911,8 @@ | ||
| 911 | 911 | finish_cell_adoption(tc, cell, owned) |
| 912 | 912 | } |
| 913 | 913 | |
| 914 | -pub(super) struct EmbeddedStartup<'a> { | |
| 915 | - pub id: &'a str, | |
| 914 | +pub(super) struct EmbeddedStartup { | |
| 915 | + pub id_sc: Vec<u8>, | |
| 916 | 916 | pub props_sc: Vec<u8>, |
| 917 | 917 | pub path: std::path::PathBuf, |
| 918 | 918 | pub restored: bool, |
| @@ -923,7 +923,7 @@ | ||
| 923 | 923 | cell: &str, |
| 924 | 924 | parent: &storage::StorageIdentity, |
| 925 | 925 | name: &str, |
| 926 | - startup: EmbeddedStartup<'_>, | |
| 926 | + startup: EmbeddedStartup, | |
| 927 | 927 | compat: Compat, |
| 928 | 928 | ) -> Result<Option<i64>> { |
| 929 | 929 | storage::open_embedded( |
| @@ -948,8 +948,10 @@ | ||
| 948 | 948 | .ok_or_else(|| anyhow!("missing facet config registry"))?; |
| 949 | 949 | let config = v8::Object::new(tc); |
| 950 | 950 | 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); | |
| 953 | 955 | let props = if startup.props_sc.is_empty() { |
| 954 | 956 | v8::undefined(tc).into() |
| 955 | 957 | } else { |
modifiedcrates/celld/js/harness.js+90−36View file
| @@ -238,6 +238,14 @@ | ||
| 238 | 238 | ]; |
| 239 | 239 | } |
| 240 | 240 | } |
| 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 | +} | |
| 241 | 249 | globalThis.Response = class Response { |
| 242 | 250 | constructor(body, init = {}) { |
| 243 | 251 | // Streaming/iterable detection runs only for object bodies, so |
| @@ -2092,15 +2100,37 @@ | ||
| 2092 | 2100 | // here is a bag nothing validated, and reading one key out of it is how every |
| 2093 | 2101 | // other key came to be dropped in silence. The loader stub validates the bag |
| 2094 | 2102 | // and encodes its value before it creates the class. |
| 2095 | -const __makeDurableObjectClass = (idPromise, name, propsSc) => { | |
| 2103 | +const __makeDurableObjectClass = (loadPromise, name, propsSc) => { | |
| 2096 | 2104 | const value = {}; |
| 2097 | 2105 | __durableClassMeta.set(value, { |
| 2098 | - idPromise, | |
| 2106 | + loadPromise, | |
| 2099 | 2107 | name: name === null || name === undefined ? "default" : String(name), |
| 2100 | 2108 | propsSc, |
| 2101 | 2109 | }); |
| 2102 | 2110 | return value; |
| 2103 | 2111 | }; |
| 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 | +}; | |
| 2104 | 2134 | class DurableObjectFacets { |
| 2105 | 2135 | constructor(state) { |
| 2106 | 2136 | this._state = state; |
| @@ -2142,11 +2172,14 @@ | ||
| 2142 | 2172 | if (meta === undefined) |
| 2143 | 2173 | throw new TypeError( |
| 2144 | 2174 | "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]; | |
| 2150 | 2183 | }); |
| 2151 | 2184 | const invoke = async (operation) => { |
| 2152 | 2185 | if (record.aborted) throw record.error; |
| @@ -2233,8 +2266,16 @@ | ||
| 2233 | 2266 | barrier.then(clear, () => {}); |
| 2234 | 2267 | } |
| 2235 | 2268 | _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(); | |
| 2238 | 2279 | } |
| 2239 | 2280 | } |
| 2240 | 2281 | // The reason a failed critical section gives its waiters. It must not throw: |
| @@ -2546,10 +2587,11 @@ | ||
| 2546 | 2587 | this._facetDepth = facet?.depth ?? 0; |
| 2547 | 2588 | const separator = scope.indexOf(":"); |
| 2548 | 2589 | 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); | |
| 2553 | 2595 | this.props = facet?.props; |
| 2554 | 2596 | // A class outside `containers` has no `ctx.container`, which is what |
| 2555 | 2597 | // the `@cloudflare/containers` constructor checks. |
| @@ -3150,8 +3192,9 @@ | ||
| 3150 | 3192 | const __outboundMeta = new WeakMap(); |
| 3151 | 3193 | const __loaderServiceMarker = "__celld$loaderSvc"; |
| 3152 | 3194 | __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. | |
| 3155 | 3198 | const byName = new Map(); |
| 3156 | 3199 | const loaderOptions = (method, options, supportsLimits) => { |
| 3157 | 3200 | if (options === null || options === undefined) return undefined; |
| @@ -3258,17 +3301,24 @@ | ||
| 3258 | 3301 | }, |
| 3259 | 3302 | }); |
| 3260 | 3303 | }; |
| 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) => { | |
| 3271 | 3319 | const drop = () => { |
| 3320 | + if (ref !== undefined && byName.get(name) === ref) byName.delete(name); | |
| 3321 | + finalizer.unregister(loadPromise); | |
| 3272 | 3322 | loadPromise.then(({ id }) => __loader_drop(id), () => {}); |
| 3273 | 3323 | }; |
| 3274 | 3324 | const stub = { |
| @@ -3280,14 +3330,11 @@ | ||
| 3280 | 3330 | }, |
| 3281 | 3331 | getDurableObjectClass(name = null, options = {}) { |
| 3282 | 3332 | return __makeDurableObjectClass( |
| 3283 | - loadPromise.then(({ id }) => id), name, | |
| 3284 | - loaderPropsSc("getDurableObjectClass", options)); | |
| 3333 | + loadPromise, name, loaderPropsSc("getDurableObjectClass", options)); | |
| 3285 | 3334 | }, |
| 3286 | 3335 | dispose: drop, |
| 3287 | 3336 | }; |
| 3288 | 3337 | if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; |
| 3289 | - if (evictable && finalizer) | |
| 3290 | - loadPromise.then(({ id }) => finalizer.register(stub, id), () => {}); | |
| 3291 | 3338 | return stub; |
| 3292 | 3339 | }; |
| 3293 | 3340 | // JSON.stringify silently drops binary values, so each non-string module -- |
| @@ -3450,14 +3497,17 @@ | ||
| 3450 | 3497 | return { id, tails }; |
| 3451 | 3498 | }); |
| 3452 | 3499 | return { |
| 3453 | - load(code) { return makeStub(loadFrom(() => code), true); }, | |
| 3500 | + load(code) { return makeStub(track(loadFrom(() => code))); }, | |
| 3454 | 3501 | 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); | |
| 3459 | 3509 | } |
| 3460 | - return makeStub(idPromise, false); | |
| 3510 | + return makeStub(loadPromise, name, ref); | |
| 3461 | 3511 | }, |
| 3462 | 3512 | }; |
| 3463 | 3513 | }; |
| @@ -4928,7 +4978,7 @@ | ||
| 4928 | 4978 | if (__runtimeClasses.has(name)) continue; |
| 4929 | 4979 | out[name] = Object.hasOwn(__cell.namespaceKeys, name) |
| 4930 | 4980 | ? __cell.makeNamespace(name) |
| 4931 | - : __makeDurableObjectClass(Promise.resolve(0), name, undefined); | |
| 4981 | + : __makeLoopbackDurableObjectClass(name); | |
| 4932 | 4982 | } |
| 4933 | 4983 | return out; |
| 4934 | 4984 | })(); |
| @@ -9260,6 +9310,10 @@ | ||
| 9260 | 9310 | } |
| 9261 | 9311 | // Backing object for the `cloudflare:workflows` builtin module. |
| 9262 | 9312 | __celld.__cfWorkflows = { NonRetryableError }; |
| 9313 | +// `celld:python`, imported only by the Python Worker bundle. | |
| 9314 | +__celld.__pythonHost = { | |
| 9315 | + condemnIsolate: (reason) => __isolate_condemn(String(reason)), | |
| 9316 | +}; | |
| 9263 | 9317 | |
| 9264 | 9318 | const __wfValidInstanceId = (id) => |
| 9265 | 9319 | typeof id === "string" && id.length >= 1 && id.length <= 100 && |
modifiedcrates/celld/js/modules.rs+16−5View file
| @@ -181,6 +181,10 @@ | ||
| 181 | 181 | /// rejects, and a static import from a user module fails to link. |
| 182 | 182 | const INTERNALS_SPECIFIER: &str = "celld:internals"; |
| 183 | 183 | |
| 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 | + | |
| 184 | 188 | /// One synthetic module per isolate whose default export is the internals |
| 185 | 189 | /// object, built the first time a stub links. |
| 186 | 190 | fn internals_module<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Module> { |
| @@ -230,11 +234,12 @@ | ||
| 230 | 234 | .expect("isolate has no module registry") |
| 231 | 235 | } |
| 232 | 236 | |
| 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. | |
| 236 | 240 | 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 | + { | |
| 238 | 243 | return true; |
| 239 | 244 | } |
| 240 | 245 | // bare builtin, or a builtin submodule like `stream/promises` |
| @@ -567,6 +572,7 @@ | ||
| 567 | 572 | // subclass would make `throw new NonRetryableError(...)` throw a value |
| 568 | 573 | // the retry policy cannot recognize — the step would retry, silently. |
| 569 | 574 | let cf_workflows = spec == "cloudflare:workflows"; |
| 575 | + let python_host = spec == PYTHON_HOST_SPECIFIER; | |
| 570 | 576 | let lazy = LAZY_MODULES.iter().find(|m| m.specs.contains(&spec)); |
| 571 | 577 | let eager = eager_module_global(spec); |
| 572 | 578 | let base = if cf { |
| @@ -575,6 +581,8 @@ | ||
| 575 | 581 | "__celld.__cfSockets".to_string() |
| 576 | 582 | } else if cf_workflows { |
| 577 | 583 | "__celld.__cfWorkflows".to_string() |
| 584 | + } else if python_host { | |
| 585 | + "__celld.__pythonHost".to_string() | |
| 578 | 586 | } else if let Some(m) = lazy { |
| 579 | 587 | format!("__celld.{}", m.global) |
| 580 | 588 | } else if let Some(global) = eager { |
| @@ -913,6 +921,9 @@ | ||
| 913 | 921 | if spec == "cloudflare:workflows" { |
| 914 | 922 | return Some("__celld.__cfWorkflows".into()); |
| 915 | 923 | } |
| 924 | + if spec == PYTHON_HOST_SPECIFIER { | |
| 925 | + return Some("__celld.__pythonHost".into()); | |
| 926 | + } | |
| 916 | 927 | if let Some(module) = install_lazy_module(scope, spec) { |
| 917 | 928 | return Some(format!("__celld.{}", module.global)); |
| 918 | 929 | } |
| @@ -968,7 +979,7 @@ | ||
| 968 | 979 | mut rv: v8::ReturnValue<v8::Value>, |
| 969 | 980 | ) { |
| 970 | 981 | 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 { | |
| 972 | 983 | return; // not a node builtin |
| 973 | 984 | } |
| 974 | 985 | let Some(expr) = builtin_source(scope, &spec) else { |
modifiedcrates/celld/js/websocket.rs+8−11View file
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | |
| 13 | 13 | #[derive(Default)] |
| 14 | 14 | pub(super) struct WsCapture { |
| 15 | - frames: Vec<(u64, WsOut)>, | |
| 15 | + frames: WsBatch, | |
| 16 | 16 | /// The handler whose outcome authorizes an incremental flush. This is |
| 17 | 17 | /// installed after the synchronous dispatch returns its promise; until |
| 18 | 18 | /// then no turn-end flush can run. |
| @@ -93,7 +93,7 @@ | ||
| 93 | 93 | .promise = Some(promise); |
| 94 | 94 | } |
| 95 | 95 | |
| 96 | -pub(super) fn ws_capture_take() -> Vec<(u64, WsOut)> { | |
| 96 | +pub(super) fn ws_capture_take() -> WsBatch { | |
| 97 | 97 | current_context() |
| 98 | 98 | .ws_capture |
| 99 | 99 | .lock() |
| @@ -104,7 +104,9 @@ | ||
| 104 | 104 | } |
| 105 | 105 | |
| 106 | 106 | 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 | + } | |
| 108 | 110 | } |
| 109 | 111 | |
| 110 | 112 | /// Release what a running `webSocketMessage` handler has sent so far. |
| @@ -144,7 +146,7 @@ | ||
| 144 | 146 | // `settle`. Drop its frames now instead of publishing output |
| 145 | 147 | // from a failed dispatch. |
| 146 | 148 | v8::PromiseState::Rejected => { |
| 147 | - capture.last_mut().unwrap().frames.clear(); | |
| 149 | + std::mem::take(&mut capture.last_mut().unwrap().frames).discard(); | |
| 148 | 150 | return; |
| 149 | 151 | } |
| 150 | 152 | } |
| @@ -157,17 +159,12 @@ | ||
| 157 | 159 | // Every captured frame belongs to a hibernatable socket, because that is |
| 158 | 160 | // what `ws_emit` captures, so one channel names the whole batch. |
| 159 | 161 | 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(®istry, frames, gate.is_gated()) else { | |
| 163 | - return; | |
| 164 | - }; | |
| 165 | 162 | // On the HOST runtime, for the reason `ws_emit` spawns there: this flush |
| 166 | 163 | // must outlive the turn that produced the frames, and the ticket it waits |
| 167 | 164 | // for resolves with no isolate involvement. |
| 168 | 165 | asyncrt::op_handle().spawn(async move { |
| 169 | 166 | let held = await_egress_gate(gate).await; |
| 170 | - flushing.release(®istry, held); | |
| 167 | + frames.release(held); | |
| 171 | 168 | }); |
| 172 | 169 | } |
| 173 | 170 | |
| @@ -190,7 +187,7 @@ | ||
| 190 | 187 | fn ws_emit(context: &Arc<IoContext>, id: u64, out: WsOut) { |
| 191 | 188 | let mut capture = context.ws_capture.lock().unwrap(); |
| 192 | 189 | 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); | |
| 194 | 191 | let runtime_state = context |
| 195 | 192 | .continuation |
| 196 | 193 | .as_ref() |
modifiedcrates/celld/lib.rs+1−0View file
| @@ -324,6 +324,7 @@ | ||
| 324 | 324 | } |
| 325 | 325 | pub mod bucket; |
| 326 | 326 | pub mod cell_cli; |
| 327 | +pub mod cell_dispatch; | |
| 327 | 328 | mod cell_host; |
| 328 | 329 | pub mod cell_runtime; |
| 329 | 330 | pub mod clean_reload; |
modifiedcrates/celld/ltx_repl.rs+538−52View file
| @@ -919,6 +919,151 @@ | ||
| 919 | 919 | complete: AtomicBool, |
| 920 | 920 | } |
| 921 | 921 | |
| 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 | + | |
| 922 | 1067 | pub struct LtxRepl { |
| 923 | 1068 | /// Local root: cell dbs live at `watch/<cell>/ltx/e<epoch>/db.sqlite`. |
| 924 | 1069 | watch: PathBuf, |
| @@ -1022,6 +1167,20 @@ | ||
| 1022 | 1167 | /// second, and the retained backlog grew for the life of the process. |
| 1023 | 1168 | /// On 2026-09-03 a dead session's recovery read 209 of them. |
| 1024 | 1169 | 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>, | |
| 1025 | 1184 | /// The cell's TRUNCATE checkpoint threshold. Passive checkpoints never |
| 1026 | 1185 | /// shrink the WAL FILE, so after every periodic restart the capture's |
| 1027 | 1186 | /// tail read spans the stale high-water region — ~350 KB per sync on |
| @@ -1304,6 +1463,11 @@ | ||
| 1304 | 1463 | durability_timeout_ms.saturating_mul(SNAPSHOT_BYTES_PER_MS), |
| 1305 | 1464 | ), |
| 1306 | 1465 | 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)), | |
| 1307 | 1471 | truncate_pages: Some( |
| 1308 | 1472 | crate::env_vars::optional::<u32>("CELLD_LTX_TRUNCATE_PAGES") |
| 1309 | 1473 | .ok() |
| @@ -1450,40 +1614,100 @@ | ||
| 1450 | 1614 | Self::all_cells_shipped_tiered(&cells) && self.dirty_tails.lock().unwrap().is_empty() |
| 1451 | 1615 | } |
| 1452 | 1616 | |
| 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. | |
| 1455 | 1617 | /// 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 { | |
| 1460 | 1663 | 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. | |
| 1467 | 1679 | 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 { | |
| 1469 | 1705 | return covered; |
| 1470 | 1706 | } |
| 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; | |
| 1486 | 1709 | } |
| 1710 | + covered | |
| 1487 | 1711 | } |
| 1488 | 1712 | |
| 1489 | 1713 | /// Remember that the bucket holds this cell epoch through `txid`. |
| @@ -1493,6 +1717,222 @@ | ||
| 1493 | 1717 | *entry = (*entry).max(txid); |
| 1494 | 1718 | } |
| 1495 | 1719 | |
| 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 | + | |
| 1496 | 1936 | /// Highest contiguous TXID prefix proved by the live per-cell L0/L1 objects. |
| 1497 | 1937 | /// |
| 1498 | 1938 | /// Unlike `covered_txid`, this is an activation safety proof. A maximum |
| @@ -1523,6 +1963,8 @@ | ||
| 1523 | 1963 | Ok(covered) |
| 1524 | 1964 | } |
| 1525 | 1965 | |
| 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. | |
| 1526 | 1968 | pub async fn upload_raw_l0( |
| 1527 | 1969 | &self, |
| 1528 | 1970 | cell: &str, |
| @@ -3163,30 +3605,64 @@ | ||
| 3163 | 3605 | |
| 3164 | 3606 | /// Restore the newest durable replica into a private snapshot without |
| 3165 | 3607 | /// 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. | |
| 3166 | 3615 | 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 | + } | |
| 3190 | 3666 | } |
| 3191 | 3667 | |
| 3192 | 3668 | pub fn prune_local_cache(&self, max_bytes: u64) -> std::io::Result<(usize, usize, u64)> { |
| @@ -3463,9 +3939,19 @@ | ||
| 3463 | 3939 | .saturating_sub(compaction.compacted_txid.load(Ordering::SeqCst)) |
| 3464 | 3940 | >= compaction.min_txids; |
| 3465 | 3941 | 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 | + }; | |
| 3466 | 3953 | if compaction.cancelled.load(Ordering::SeqCst) |
| 3467 | 3954 | || asyncrt::mono_ms() < compaction.retry_after_ms.load(Ordering::SeqCst) |
| 3468 | - || !(due_by_txids || due_by_bytes) | |
| 3469 | 3955 | || compaction |
| 3470 | 3956 | .queued |
| 3471 | 3957 | .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) |
modifiedcrates/celld/main.rs+100−244View file
| @@ -7,13 +7,17 @@ | ||
| 7 | 7 | //! Runnable celld vertical slice. |
| 8 | 8 | //! |
| 9 | 9 | //! 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. | |
| 13 | 13 | |
| 14 | 14 | use anyhow::Context as _; |
| 15 | 15 | use celld::actor::*; |
| 16 | 16 | 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 | +}; | |
| 17 | 21 | use celld::fleet; |
| 18 | 22 | use celld::generation::{ |
| 19 | 23 | DeploymentGraph, Generation, GenerationOptions, ReloadOutcome, ReloadRequest, FIRST_GENERATION, |
| @@ -364,23 +368,6 @@ | ||
| 364 | 368 | |
| 365 | 369 | impl std::error::Error for StalePeerRoute {} |
| 366 | 370 | |
| 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 | - | |
| 384 | 371 | /// Preserve the owner's durability verdict and handler failure in a peer reply. |
| 385 | 372 | fn peer_gate_failure(verdict: RequestError, handler: Option<&anyhow::Error>) -> HttpReply { |
| 386 | 373 | let detail = match handler { |
| @@ -393,14 +380,6 @@ | ||
| 393 | 380 | )) |
| 394 | 381 | } |
| 395 | 382 | |
| 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 | - | |
| 404 | 383 | fn classify_remote_attempt(error: &anyhow::Error) -> celld_logic::routing::Attempt { |
| 405 | 384 | if error.downcast_ref::<StalePeerRoute>().is_some() |
| 406 | 385 | || error |
| @@ -602,34 +581,6 @@ | ||
| 602 | 581 | } |
| 603 | 582 | } |
| 604 | 583 | |
| 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 | - | |
| 633 | 584 | /// A facet stream request from the isolate that runs the facet. |
| 634 | 585 | async fn dispatch_facet(app: AppHandle, req: celld::js::FacetReq) { |
| 635 | 586 | use celld::js::FacetReq; |
| @@ -1084,36 +1035,10 @@ | ||
| 1084 | 1035 | response(status, body.to_string()) |
| 1085 | 1036 | } |
| 1086 | 1037 | |
| 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 | - | |
| 1098 | 1038 | 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 | |
| 1117 | 1042 | .iter() |
| 1118 | 1043 | .any(|(name, value)| { |
| 1119 | 1044 | name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket") |
| @@ -1125,128 +1050,46 @@ | ||
| 1125 | 1050 | attempts: 0, |
| 1126 | 1051 | }); |
| 1127 | 1052 | 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 | - ); | |
| 1135 | 1053 | let mut dispatcher = RemoteRouteRetry::new(app.operation_deadline_ms); |
| 1136 | 1054 | loop { |
| 1137 | 1055 | if let Some(timing) = websocket_timing.as_mut() { |
| 1138 | 1056 | timing.attempts = timing.attempts.saturating_add(1); |
| 1139 | 1057 | } |
| 1140 | 1058 | 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); | |
| 1160 | 1069 | } |
| 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) => { | |
| 1165 | 1076 | if let Some(timing) = websocket_timing.as_mut() { |
| 1166 | 1077 | timing.route_resolution_us = timing |
| 1167 | 1078 | .route_resolution_us |
| 1168 | 1079 | .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", "", ""); | |
| 1170 | 1081 | } |
| 1171 | - break Err(anyhow::Error::new(RoutedRequestError(error))); | |
| 1082 | + break Err(error); | |
| 1172 | 1083 | } |
| 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) => { | |
| 1242 | 1085 | if let Some(timing) = websocket_timing.as_mut() { |
| 1243 | 1086 | timing.dispatch_us = timing |
| 1244 | 1087 | .dispatch_us |
| 1245 | 1088 | .saturating_add(dispatch_started.elapsed().as_micros() as u64); |
| 1246 | 1089 | timing.emit( |
| 1247 | 1090 | &app, |
| 1248 | - &scope, | |
| 1249 | - request_id, | |
| 1091 | + &call.scope, | |
| 1092 | + call.request_id, | |
| 1250 | 1093 | if result.is_ok() { "ok" } else { "error" }, |
| 1251 | 1094 | "local", |
| 1252 | 1095 | app.runtime.as_ref().map_or("", |runtime| runtime.node()), |
| @@ -1254,13 +1097,31 @@ | ||
| 1254 | 1097 | } |
| 1255 | 1098 | break result; |
| 1256 | 1099 | } |
| 1257 | - Route::Remote { | |
| 1100 | + CallAttempt::Remote { | |
| 1258 | 1101 | node, |
| 1259 | 1102 | addr, |
| 1260 | 1103 | epoch, |
| 1261 | 1104 | 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 | + } | |
| 1263 | 1112 | }; |
| 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; | |
| 1264 | 1125 | if dispatcher.observe(&node, epoch) { |
| 1265 | 1126 | let cancel = if deliver_abort_to_handler { |
| 1266 | 1127 | None |
| @@ -1269,7 +1130,7 @@ | ||
| 1269 | 1130 | }; |
| 1270 | 1131 | match dispatcher.wait(cancel).await { |
| 1271 | 1132 | RemoteRetryOutcome::Ready => { |
| 1272 | - dispatcher.invalidate(&app, &scope).await; | |
| 1133 | + dispatcher.invalidate(&app, scope).await; | |
| 1273 | 1134 | continue; |
| 1274 | 1135 | } |
| 1275 | 1136 | RemoteRetryOutcome::Cancelled => { |
| @@ -1296,7 +1157,7 @@ | ||
| 1296 | 1157 | request_id, |
| 1297 | 1158 | capacity_handoff: epoch == 0, |
| 1298 | 1159 | }; |
| 1299 | - let attempt_body = match &body { | |
| 1160 | + let attempt_body = match body { | |
| 1300 | 1161 | celld::js::RequestBody::Bytes(bytes) => { |
| 1301 | 1162 | celld::js::RequestBody::Bytes(bytes.clone()) |
| 1302 | 1163 | } |
| @@ -1325,7 +1186,7 @@ | ||
| 1325 | 1186 | attempt_body, |
| 1326 | 1187 | ) |
| 1327 | 1188 | .await |
| 1328 | - .map_err(|error| owner_unreachable(&scope, &addr, error))?; | |
| 1189 | + .map_err(|error| owner_unreachable(scope, &addr, error))?; | |
| 1329 | 1190 | // Only after the tunnel has taken the stream: `disarm` |
| 1330 | 1191 | // releases the guard's registry claim, and a claim that |
| 1331 | 1192 | // drops to zero deletes the entry, so disarming before |
| @@ -1340,7 +1201,7 @@ | ||
| 1340 | 1201 | { |
| 1341 | 1202 | abort.disarm(); |
| 1342 | 1203 | return Err(owner_unreachable( |
| 1343 | - &scope, | |
| 1204 | + scope, | |
| 1344 | 1205 | &addr, |
| 1345 | 1206 | anyhow::Error::new(StalePeerRoute { |
| 1346 | 1207 | scope: scope.clone(), |
| @@ -1431,7 +1292,7 @@ | ||
| 1431 | 1292 | match remote { |
| 1432 | 1293 | Ok(response) => { |
| 1433 | 1294 | 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); | |
| 1435 | 1296 | } |
| 1436 | 1297 | break Ok(response); |
| 1437 | 1298 | } |
| @@ -1468,7 +1329,7 @@ | ||
| 1468 | 1329 | cancel.as_mut() |
| 1469 | 1330 | }; |
| 1470 | 1331 | match dispatcher |
| 1471 | - .retry(&app, &scope, classify_remote_attempt(&error), cancel, None) | |
| 1332 | + .retry(&app, scope, classify_remote_attempt(&error), cancel, None) | |
| 1472 | 1333 | .await |
| 1473 | 1334 | { |
| 1474 | 1335 | RemoteRetryOutcome::Ready => continue, |
| @@ -1478,7 +1339,7 @@ | ||
| 1478 | 1339 | RemoteRetryOutcome::Stop => {} |
| 1479 | 1340 | } |
| 1480 | 1341 | 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); | |
| 1482 | 1343 | } |
| 1483 | 1344 | break Err(error); |
| 1484 | 1345 | } |
| @@ -1627,11 +1488,11 @@ | ||
| 1627 | 1488 | request: Request<Incoming>, |
| 1628 | 1489 | trust_forwarded_headers: bool, |
| 1629 | 1490 | 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>> { | |
| 1631 | 1492 | let (parts, body) = request.into_parts(); |
| 1632 | 1493 | let body = collect_limited_body(body, max_body_bytes) |
| 1633 | 1494 | .await |
| 1634 | - .map_err(|error| body_read_error("request", error))?; | |
| 1495 | + .map_err(|error| Box::new(body_read_error("request", error)))?; | |
| 1635 | 1496 | let headers = parts |
| 1636 | 1497 | .headers |
| 1637 | 1498 | .iter() |
| @@ -1776,7 +1637,7 @@ | ||
| 1776 | 1637 | celld::js::RequestBody, |
| 1777 | 1638 | Vec<(String, String)>, |
| 1778 | 1639 | ), |
| 1779 | - HttpReply, | |
| 1640 | + Box<HttpReply>, | |
| 1780 | 1641 | > { |
| 1781 | 1642 | let declared = request |
| 1782 | 1643 | .headers() |
| @@ -1784,18 +1645,18 @@ | ||
| 1784 | 1645 | .and_then(|value| value.to_str().ok()) |
| 1785 | 1646 | .and_then(|value| value.parse::<u64>().ok()); |
| 1786 | 1647 | if declared.is_some_and(|length| length > max_body_bytes as u64) { |
| 1787 | - return Err(response( | |
| 1648 | + return Err(Box::new(response( | |
| 1788 | 1649 | StatusCode::PAYLOAD_TOO_LARGE, |
| 1789 | 1650 | "request body too large", |
| 1790 | - )); | |
| 1651 | + ))); | |
| 1791 | 1652 | } |
| 1792 | 1653 | let (url, method, body, headers, held) = |
| 1793 | 1654 | ingress_payload_parts(request, trust_forwarded_headers, max_body_bytes).map_err( |
| 1794 | 1655 | |error| { |
| 1795 | - response( | |
| 1656 | + Box::new(response( | |
| 1796 | 1657 | StatusCode::SERVICE_UNAVAILABLE, |
| 1797 | 1658 | format!("request body stream: {error}"), |
| 1798 | - ) | |
| 1659 | + )) | |
| 1799 | 1660 | }, |
| 1800 | 1661 | )?; |
| 1801 | 1662 | // The host collects a small body here. A read failure at this point |
| @@ -1806,7 +1667,7 @@ | ||
| 1806 | 1667 | None => body, |
| 1807 | 1668 | Some(held) => match collect_limited_body(held, max_body_bytes).await { |
| 1808 | 1669 | 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))), | |
| 1810 | 1671 | }, |
| 1811 | 1672 | }; |
| 1812 | 1673 | Ok((url, method, body, headers)) |
| @@ -2426,7 +2287,7 @@ | ||
| 2426 | 2287 | .await |
| 2427 | 2288 | { |
| 2428 | 2289 | Ok(payload) => payload, |
| 2429 | - Err(response) => return response, | |
| 2290 | + Err(response) => return *response, | |
| 2430 | 2291 | }; |
| 2431 | 2292 | let preserve_representation_length = method.eq_ignore_ascii_case("HEAD"); |
| 2432 | 2293 | match app |
| @@ -3095,7 +2956,7 @@ | ||
| 3095 | 2956 | .await |
| 3096 | 2957 | { |
| 3097 | 2958 | Ok(payload) => payload, |
| 3098 | - Err(response) => return Ok(response), | |
| 2959 | + Err(response) => return Ok(*response), | |
| 3099 | 2960 | }; |
| 3100 | 2961 | dispatch_cell_fetch(cell, None, url, method, body, headers).await |
| 3101 | 2962 | } |
| @@ -3525,7 +3386,8 @@ | ||
| 3525 | 3386 | }; |
| 3526 | 3387 | #[cfg(not(all(test, celld_internal_tests)))] |
| 3527 | 3388 | 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()); | |
| 3529 | 3391 | // Docker and journald can stop consuming the process pipe during a log |
| 3530 | 3392 | // burst. Logging must lose diagnostics under that backpressure rather |
| 3531 | 3393 | // than block the Tokio workers that route requests and renew authority. |
| @@ -3682,6 +3544,14 @@ | ||
| 3682 | 3544 | } |
| 3683 | 3545 | Action::Run(settings) => settings, |
| 3684 | 3546 | }; |
| 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 | + ); | |
| 3685 | 3555 | celld::startup::raise_file_limit(); |
| 3686 | 3556 | let max_resident = celld::env_vars::optional("CELLD_MAX_RESIDENT_CELLS")? |
| 3687 | 3557 | // celld has no resident ceiling unless the operator configures one. |
| @@ -4406,6 +4276,10 @@ | ||
| 4406 | 4276 | if let Ownership::Bucket(bucket_ownership) = &actor.ownership { |
| 4407 | 4277 | celld::js::set_kv_blob_store(bucket_ownership.bucket_client()); |
| 4408 | 4278 | } |
| 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); | |
| 4409 | 4283 | // The core is a serial ownership actor, not a Worker executor. It owns the |
| 4410 | 4284 | // node lease timer, so ingress, proxy retries, and restore completions must |
| 4411 | 4285 | // not consume every scheduler turn it needs. Its isolated single-thread |
| @@ -4431,6 +4305,10 @@ | ||
| 4431 | 4305 | celld::asyncrt::spawn(async move { |
| 4432 | 4306 | let mut tick = celld::asyncrt::interval(LOAD_SAMPLE_PERIOD); |
| 4433 | 4307 | 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; | |
| 4434 | 4312 | loop { |
| 4435 | 4313 | tick.tick().await; |
| 4436 | 4314 | // What SQLite freed when a cell stopped stays on the C |
| @@ -4440,7 +4318,20 @@ | ||
| 4440 | 4318 | // ahead of the sample, on a blocking thread because a trim |
| 4441 | 4319 | // walks every free chunk. |
| 4442 | 4320 | 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() { | |
| 4444 | 4335 | return; |
| 4445 | 4336 | } |
| 4446 | 4337 | } |
| @@ -5696,41 +5587,6 @@ | ||
| 5696 | 5587 | )) |
| 5697 | 5588 | } |
| 5698 | 5589 | |
| 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 | - | |
| 5734 | 5590 | #[cfg(all(test, celld_internal_tests))] |
| 5735 | 5591 | mod durability_lifecycle_private { |
| 5736 | 5592 | include!(env!("CELLD_CONFORMANCE_MAIN_DURABILITY_TESTS")); |
modifiedcrates/celld/main/cli.rs+4−0View file
| @@ -270,6 +270,7 @@ | ||
| 270 | 270 | celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] |
| 271 | 271 | celld dev [PROJECT] [--host IP] [--port PORT] [--logs] |
| 272 | 272 | 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] | |
| 273 | 274 | celld d1 migrations apply DATABASE [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| 274 | 275 | celld d1 execute DATABASE --command SQL [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| 275 | 276 | celld kv get|put|delete|list|info NAMESPACE --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| @@ -357,6 +358,8 @@ | ||
| 357 | 358 | CELLD_MAX_RESIDENT_CELLS Resident-cell hard cap, enforced at admission |
| 358 | 359 | CELLD_MAX_CELL_REQUESTS Concurrent fetches per cell (default: 64) |
| 359 | 360 | 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) | |
| 360 | 363 | CELLD_PRESSURE_OWNERSHIP release to rebalance, sticky to cache locally |
| 361 | 364 | CELLD_MAX_RSS_MB Active-memory shed threshold (default: 80%; 0 disables) |
| 362 | 365 | CELLD_ALARM_RESIDENT_MS Near-alarm residency window |
| @@ -374,6 +377,7 @@ | ||
| 374 | 377 | CELLD_LOG_PIPELINE Fleet log rounds in flight (default: 4) |
| 375 | 378 | CELLD_LOG_HEDGE_MS Duplicate a slow log append (default: adaptive; 0 disables) |
| 376 | 379 | 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) | |
| 377 | 381 | RUST_LOG Runtime log filter (default: info) |
| 378 | 382 | |
| 379 | 383 | Documentation: https://celld.dev/docs"#, |
modifiedcrates/celld/main/websocket.rs+43−2View file
| @@ -30,12 +30,53 @@ | ||
| 30 | 30 | .await |
| 31 | 31 | .map_err(|error| anyhow::anyhow!("route WebSocket {scope}: {error:?}"))?; |
| 32 | 32 | 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<()> { | |
| 33 | 74 | let activity = app.activity(request, scope.to_string()); |
| 34 | 75 | let dispatch = match app |
| 35 | 76 | .runtime |
| 36 | 77 | .as_ref() |
| 37 | 78 | .context("no cell runtime")? |
| 38 | - .ws_message(scope.to_string(), ws_id, data) | |
| 79 | + .ws_message(scope.to_string(), ws_id, data, started) | |
| 39 | 80 | .await |
| 40 | 81 | { |
| 41 | 82 | Ok(dispatch) => dispatch, |
| @@ -901,7 +942,7 @@ | ||
| 901 | 942 | .await |
| 902 | 943 | { |
| 903 | 944 | Ok(payload) => payload, |
| 904 | - Err(response) => return response, | |
| 945 | + Err(response) => return *response, | |
| 905 | 946 | }; |
| 906 | 947 | let body_read_us = body_started.elapsed().as_micros() as u64; |
| 907 | 948 | let worker_started = Instant::now(); |
modifiedcrates/celld/node_log.rs+145−18View file
| @@ -3890,6 +3890,20 @@ | ||
| 3890 | 3890 | |
| 3891 | 3891 | // ── Recovery and the takeover interlock ───────────────────────────────────── |
| 3892 | 3892 | |
| 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 | + | |
| 3893 | 3907 | /// Everything node-log recovery needs from the node: the bucket, the signed |
| 3894 | 3908 | /// peer client, address resolution, and the raw per-cell upload. |
| 3895 | 3909 | pub struct NodeLogManager { |
| @@ -3922,6 +3936,12 @@ | ||
| 3922 | 3936 | /// record) must not cost a bundle LIST on every sweep tick forever |
| 3923 | 3937 | /// Process-local; a restart re-confirms once. |
| 3924 | 3938 | 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>>, | |
| 3925 | 3945 | /// Retained bundles this process has already declared unreadable. The |
| 3926 | 3946 | /// record is the durable one; this only keeps one process from |
| 3927 | 3947 | /// rewriting the same declaration on every scan. |
| @@ -4450,6 +4470,7 @@ | ||
| 4450 | 4470 | predecessors_clean: std::sync::atomic::AtomicBool::new(false), |
| 4451 | 4471 | recovery_locks: Mutex::new(BTreeMap::new()), |
| 4452 | 4472 | gc_confirmed_empty: Mutex::new(std::collections::HashSet::new()), |
| 4473 | + epoch_gc_due: Mutex::new(BTreeMap::new()), | |
| 4453 | 4474 | declared_bundle_losses: Mutex::new(BTreeSet::new()), |
| 4454 | 4475 | task_stop, |
| 4455 | 4476 | child_tasks, |
| @@ -4720,7 +4741,7 @@ | ||
| 4720 | 4741 | /// (cell, epoch), each group's contiguous tail merged into ONE L0 |
| 4721 | 4742 | /// segment (per-row fallback for non-contiguous chains), skipping |
| 4722 | 4743 | /// 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 — | |
| 4724 | 4745 | /// callers must not seal past an incomplete fold. A recovery passes |
| 4725 | 4746 | /// its claim and its progress record, which carries the watermarks |
| 4726 | 4747 | /// from one gather window to the next. |
| @@ -4752,7 +4773,7 @@ | ||
| 4752 | 4773 | let ltx = self.ltx.clone(); |
| 4753 | 4774 | async move { |
| 4754 | 4775 | 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; | |
| 4756 | 4777 | let rows: Vec<(u64, Vec<u8>)> = rows |
| 4757 | 4778 | .into_iter() |
| 4758 | 4779 | .filter(|(txid, _)| *txid > watermark) |
| @@ -5982,21 +6003,26 @@ | ||
| 5982 | 6003 | bundles.push((key, rows, bytes)); |
| 5983 | 6004 | } |
| 5984 | 6005 | |
| 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 | |
| 5990 | 6012 | // shutdown delay for a store burst and recreate the recovery storm |
| 5991 | 6013 | // 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 | + } | |
| 5997 | 6023 | 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; | |
| 6000 | 6026 | ((cell, epoch), watermark) |
| 6001 | 6027 | }); |
| 6002 | 6028 | let mut lookups = |
| @@ -6135,6 +6161,93 @@ | ||
| 6135 | 6161 | Ok(()) |
| 6136 | 6162 | } |
| 6137 | 6163 | |
| 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 | + | |
| 6138 | 6251 | pub async fn gc_bundles(&self) -> anyhow::Result<()> { |
| 6139 | 6252 | // Bound both the listing and the work. Restarting at the prefix |
| 6140 | 6253 | // every tick starved newer, covered bundles behind an undrained |
| @@ -6184,10 +6297,18 @@ | ||
| 6184 | 6297 | let mut paired = Vec::with_capacity(rows.len()); |
| 6185 | 6298 | for row in &rows { |
| 6186 | 6299 | 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. | |
| 6187 | 6303 | 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); | |
| 6191 | 6312 | covered.insert(cache_key, watermark); |
| 6192 | 6313 | watermark |
| 6193 | 6314 | } |
| @@ -6381,6 +6502,7 @@ | ||
| 6381 | 6502 | ("maintain", manager.maintain().boxed()), |
| 6382 | 6503 | ("dead-leader sweep", manager.sweep_dead_leaders().boxed()), |
| 6383 | 6504 | ("bundle GC", manager.gc_bundles().boxed()), |
| 6505 | + ("epoch GC", manager.gc_superseded_epochs().boxed()), | |
| 6384 | 6506 | ] { |
| 6385 | 6507 | let started = mono_ms(); |
| 6386 | 6508 | let mut work = work; |
| @@ -6603,7 +6725,12 @@ | ||
| 6603 | 6725 | evicted, |
| 6604 | 6726 | evicted_through, |
| 6605 | 6727 | } = 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; | |
| 6607 | 6734 | if evicted_through.is_some_and(|through| covered < through) { |
| 6608 | 6735 | // A cache is not the source of truth. A slow cell can lose its |
| 6609 | 6736 | // first row long before it reaches the compaction threshold. |
modifiedcrates/celld/otlp.rs+4−3View file
| @@ -177,13 +177,14 @@ | ||
| 177 | 177 | out |
| 178 | 178 | } |
| 179 | 179 | |
| 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. | |
| 182 | 182 | fn log_message(log: &Log) -> Vec<u8> { |
| 183 | 183 | let mut out = Vec::new(); |
| 184 | 184 | let time_ns = log.time_unix_us.max(0) as u64 * 1_000; |
| 185 | 185 | 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()); | |
| 187 | 188 | field_bytes(&mut out, 5, &any_string(&log.body)); |
| 188 | 189 | if let Some(trace_id) = log.trace_id { |
| 189 | 190 | field_bytes(&mut out, 9, &trace_id); |
modifiedcrates/celld/ownership_store.rs+35−60View file
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | //! `celld-logic`. |
| 8 | 8 | |
| 9 | 9 | use crate::bucket::Bucket; |
| 10 | +use crate::host_services::HostMetricsSample; | |
| 10 | 11 | use anyhow::Context; |
| 11 | 12 | use celld_logic::{ |
| 12 | 13 | CapacityPeer, CasGuard, CasOutcome, LeaseCasOutcome, NodeLeaseRecord, OwnerRecord, |
| @@ -15,7 +16,7 @@ | ||
| 15 | 16 | use serde::{Deserialize, Serialize}; |
| 16 | 17 | use serde_json::value::RawValue; |
| 17 | 18 | use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; |
| 18 | -use std::sync::Arc; | |
| 19 | +use std::sync::{Arc, Mutex}; | |
| 19 | 20 | |
| 20 | 21 | #[derive(Serialize)] |
| 21 | 22 | struct OwnerWire<'a> { |
| @@ -402,11 +403,6 @@ | ||
| 402 | 403 | /// the live Actor counters load-bearing. |
| 403 | 404 | #[cfg(all(test, celld_internal_tests))] |
| 404 | 405 | 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, | |
| 410 | 406 | /// The full folded log object this node's OWN lease record carries, |
| 411 | 407 | /// tagged with a publish sequence. |
| 412 | 408 | /// Renewals snapshot (seq, object) ONCE when they serialize the wire |
| @@ -452,6 +448,8 @@ | ||
| 452 | 448 | |
| 453 | 449 | #[derive(Debug, Default)] |
| 454 | 450 | pub struct LiveLoad { |
| 451 | + /// Keep telemetry together: a torn RSS/in-use pair reads as allocator retention. | |
| 452 | + sample: Mutex<Option<HostMetricsSample>>, | |
| 455 | 453 | pub owned_cells: AtomicUsize, |
| 456 | 454 | /// False until the actor has confirmed every record on its own disk |
| 457 | 455 | /// after a start. The lease publishes no owned count until then, so a |
| @@ -462,7 +460,6 @@ | ||
| 462 | 460 | pub placement_weight: AtomicU64, |
| 463 | 461 | pub resident_cells: AtomicUsize, |
| 464 | 462 | pub host_websockets: AtomicUsize, |
| 465 | - pub cpu_percent_x100: AtomicU64, | |
| 466 | 463 | pub pressured: AtomicBool, |
| 467 | 464 | /// Stricter than not pressured: the last sample cleared every resume line. |
| 468 | 465 | pub memory_headroom: AtomicBool, |
| @@ -480,6 +477,21 @@ | ||
| 480 | 477 | pub draining: AtomicBool, |
| 481 | 478 | } |
| 482 | 479 | |
| 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 | + | |
| 483 | 495 | impl BucketOwnership { |
| 484 | 496 | /// Creates an adapter with an isolated lease pool and the process key |
| 485 | 497 | /// advertised for challenge-bound direct probes. |
| @@ -499,8 +511,6 @@ | ||
| 499 | 511 | fleet_sample_ms: 5_000, |
| 500 | 512 | #[cfg(all(test, celld_internal_tests))] |
| 501 | 513 | ambient_load_override: None, |
| 502 | - #[cfg(all(test, celld_internal_tests))] | |
| 503 | - production_load_samples: AtomicUsize::new(0), | |
| 504 | 514 | own_log: std::sync::Mutex::new((0, None)), |
| 505 | 515 | applied: tokio::sync::watch::channel((String::new(), 0)).0, |
| 506 | 516 | } |
| @@ -529,11 +539,6 @@ | ||
| 529 | 539 | self.process_load() |
| 530 | 540 | } |
| 531 | 541 | |
| 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 | - | |
| 537 | 542 | pub fn lease_ttl_ms(&self) -> u64 { |
| 538 | 543 | self.lease_ttl_ms |
| 539 | 544 | } |
| @@ -1007,7 +1012,7 @@ | ||
| 1007 | 1012 | in_use_bytes: Some(ambient.in_use_bytes.max(1).min(rss_bytes)), |
| 1008 | 1013 | cgroup_working_set_bytes: ambient.cgroup_working_set_bytes, |
| 1009 | 1014 | 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, | |
| 1011 | 1016 | open_fds: ambient.open_fds, |
| 1012 | 1017 | fd_limit: ambient.fd_limit, |
| 1013 | 1018 | pressured: self.live.pressured.load(Ordering::Relaxed), |
| @@ -1019,8 +1024,6 @@ | ||
| 1019 | 1024 | container_instances: Default::default(), |
| 1020 | 1025 | }; |
| 1021 | 1026 | } |
| 1022 | - #[cfg(all(test, celld_internal_tests))] | |
| 1023 | - self.production_load_samples.fetch_add(1, Ordering::Relaxed); | |
| 1024 | 1027 | process_load(&self.live) |
| 1025 | 1028 | } |
| 1026 | 1029 | } |
| @@ -1195,65 +1198,37 @@ | ||
| 1195 | 1198 | .then(|| live.owned_cells.load(Ordering::Relaxed)) |
| 1196 | 1199 | } |
| 1197 | 1200 | |
| 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. | |
| 1201 | 1201 | fn placement_weight(live: &LiveLoad) -> Option<u64> { |
| 1202 | 1202 | let weight = live.placement_weight.load(Ordering::Relaxed); |
| 1203 | 1203 | (weight > 0).then_some(weight) |
| 1204 | 1204 | } |
| 1205 | 1205 | |
| 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. | |
| 1210 | 1208 | 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. | |
| 1218 | 1213 | // Both numbers take it, so the in-use figure can never read as zero beside |
| 1219 | 1214 | // 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); | |
| 1222 | 1217 | |
| 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 | - | |
| 1245 | 1218 | NodeLoadWire { |
| 1219 | + // Version the whole record, including live counters. Reusing the resource | |
| 1220 | + // sample's time would retain peers' capacity reservations across renewals. | |
| 1246 | 1221 | sampled_ms: now_ms(), |
| 1247 | 1222 | owned_cells: owned_cells(live), |
| 1248 | 1223 | placement_weight: placement_weight(live), |
| 1249 | 1224 | bucket_format: Some(celld_logic::format::BUCKET_FORMAT), |
| 1250 | 1225 | rss_bytes, |
| 1251 | 1226 | 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, | |
| 1257 | 1232 | resident_cells: live.resident_cells.load(Ordering::Relaxed), |
| 1258 | 1233 | host_websockets: live.host_websockets.load(Ordering::Relaxed), |
| 1259 | 1234 | pressured: live.pressured.load(Ordering::Relaxed), |
modifiedcrates/celld/peer_auth.rs+1−1View file
| @@ -372,7 +372,7 @@ | ||
| 372 | 372 | return Err(anyhow!("incorrect hexadecimal length")); |
| 373 | 373 | } |
| 374 | 374 | 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() { | |
| 376 | 376 | decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?; |
| 377 | 377 | } |
| 378 | 378 | Ok(decoded) |
modifiedcrates/celld/peer_probe.rs+1−1View file
| @@ -223,7 +223,7 @@ | ||
| 223 | 223 | return Err(anyhow!("incorrect hexadecimal length")); |
| 224 | 224 | } |
| 225 | 225 | 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() { | |
| 227 | 227 | decoded[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?; |
| 228 | 228 | } |
| 229 | 229 | Ok(decoded) |
modifiedcrates/celld/pool.rs+72−0View file
| @@ -186,6 +186,10 @@ | ||
| 186 | 186 | /// The pool's admission bell, cloned into every slot so an |
| 187 | 187 | /// `Affiliation` drop can ring it without holding the pool. |
| 188 | 188 | 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>>, | |
| 189 | 193 | /// Cells whose realm lives in this isolate. Not a count of live work: a |
| 190 | 194 | /// cell stays until it is evicted or handed to another node, which is |
| 191 | 195 | /// why `retire` refuses an isolate holding any. |
| @@ -317,6 +321,7 @@ | ||
| 317 | 321 | turns: AtomicUsize::new(0), |
| 318 | 322 | requests: AtomicUsize::new(0), |
| 319 | 323 | freed: Arc::new(tokio::sync::Notify::new()), |
| 324 | + reclaim: None, | |
| 320 | 325 | cells: AtomicUsize::new(0), |
| 321 | 326 | adopted_cells: AtomicUsize::new(0), |
| 322 | 327 | retiring: AtomicBool::new(false), |
| @@ -342,6 +347,7 @@ | ||
| 342 | 347 | turns: AtomicUsize::new(0), |
| 343 | 348 | requests: AtomicUsize::new(0), |
| 344 | 349 | freed: Arc::new(tokio::sync::Notify::new()), |
| 350 | + reclaim: None, | |
| 345 | 351 | cells: AtomicUsize::new(0), |
| 346 | 352 | adopted_cells: AtomicUsize::new(0), |
| 347 | 353 | retiring: AtomicBool::new(false), |
| @@ -389,6 +395,37 @@ | ||
| 389 | 395 | self.retiring.load(Ordering::Relaxed) |
| 390 | 396 | } |
| 391 | 397 | |
| 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 | + | |
| 392 | 429 | /// The node-wide identity of this slot's currently installed V8 heap. |
| 393 | 430 | pub fn heap_id(&self) -> HeapId { |
| 394 | 431 | self.heap_id |
| @@ -419,6 +456,14 @@ | ||
| 419 | 456 | // the capacity to a single parked request, where waking them all |
| 420 | 457 | // would stampede `admit` on every release. |
| 421 | 458 | 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 | + } | |
| 422 | 467 | } |
| 423 | 468 | } |
| 424 | 469 | |
| @@ -483,6 +528,9 @@ | ||
| 483 | 528 | limits: PoolLimits, |
| 484 | 529 | build: Build, |
| 485 | 530 | 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>, | |
| 486 | 534 | admission_wait: std::time::Duration, |
| 487 | 535 | /// The whole pool belongs to a superseded generation. An isolate grown |
| 488 | 536 | /// after this is set starts out retiring: a placement that snapshotted |
| @@ -502,6 +550,7 @@ | ||
| 502 | 550 | limits, |
| 503 | 551 | build, |
| 504 | 552 | freed: Arc::new(tokio::sync::Notify::new()), |
| 553 | + reclaim: Arc::new(tokio::sync::Notify::new()), | |
| 505 | 554 | admission_wait, |
| 506 | 555 | retired: AtomicBool::new(false), |
| 507 | 556 | maintenance: RwLock::new(()), |
| @@ -567,6 +616,7 @@ | ||
| 567 | 616 | turns: AtomicUsize::new(0), |
| 568 | 617 | requests: AtomicUsize::new(0), |
| 569 | 618 | freed: self.freed.clone(), |
| 619 | + reclaim: Some(self.reclaim.clone()), | |
| 570 | 620 | cells: AtomicUsize::new(0), |
| 571 | 621 | adopted_cells: AtomicUsize::new(0), |
| 572 | 622 | retiring: AtomicBool::new(self.retired.load(Ordering::Relaxed)), |
| @@ -700,6 +750,28 @@ | ||
| 700 | 750 | self.free_retired(); |
| 701 | 751 | } |
| 702 | 752 | |
| 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 | + | |
| 703 | 775 | /// Retire every empty isolate. Cell pools use this after eviction because |
| 704 | 776 | /// an empty cell heap carries no warm request capacity worth preserving. |
| 705 | 777 | pub fn reap_empty(&self) { |
modifiedcrates/celld/protocol.rs+6−0View file
| @@ -73,6 +73,7 @@ | ||
| 73 | 73 | FEATURE_R2_V1, |
| 74 | 74 | FEATURE_WASM_V1, |
| 75 | 75 | FEATURE_WORKFLOWS_V1, |
| 76 | + FEATURE_PYTHON_WORKERS_V1, | |
| 76 | 77 | ]; |
| 77 | 78 | |
| 78 | 79 | pub const FEATURE_ASSETS_V1: &str = "assets-v1"; |
| @@ -96,6 +97,11 @@ | ||
| 96 | 97 | pub const FEATURE_R2_V1: &str = "r2-v1"; |
| 97 | 98 | pub const FEATURE_SQLITE_VEC_V1: &str = "sqlite-vec-v1"; |
| 98 | 99 | 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"; | |
| 99 | 105 | /// A deployment with `workflows` bindings. Required because a build without |
| 100 | 106 | /// the reserved workflow cell would load the manifest, build an `env` missing |
| 101 | 107 | /// 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 @@ | ||
| 41 | 41 | /// How often the isolate pool gives back what it no longer needs. |
| 42 | 42 | const REAP_INTERVAL: Duration = Duration::from_secs(30); |
| 43 | 43 | |
| 44 | +/// How long a reclaim waits before it retries when admission holds the pool. | |
| 45 | +const RECLAIM_RETRY: Duration = Duration::from_millis(10); | |
| 46 | + | |
| 44 | 47 | /// How often a suspended request re-reads its cancellation flag. Matches the |
| 45 | 48 | /// blocking run loop's own cap, which exists for the same reason: a client |
| 46 | 49 | /// disconnect is raised on another thread and has nothing to wake this one. |
| @@ -1187,6 +1190,7 @@ | ||
| 1187 | 1190 | }) |
| 1188 | 1191 | .await |
| 1189 | 1192 | .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; | |
| 1190 | 1194 | tracing::info!( |
| 1191 | 1195 | event = "generation_swap_out", |
| 1192 | 1196 | scope = %cell, |
| @@ -1435,6 +1439,10 @@ | ||
| 1435 | 1439 | // the isolate once no cell is left in it. |
| 1436 | 1440 | drop(handle); |
| 1437 | 1441 | } |
| 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; | |
| 1438 | 1446 | let Some(replication) = &self.replication else { |
| 1439 | 1447 | self.facets.forget(cell, epoch); |
| 1440 | 1448 | return Ok(()); |
| @@ -1796,12 +1804,14 @@ | ||
| 1796 | 1804 | cell: String, |
| 1797 | 1805 | ws_id: u64, |
| 1798 | 1806 | data: js::WsIn, |
| 1807 | + started: tokio::sync::oneshot::Sender<()>, | |
| 1799 | 1808 | ) -> anyhow::Result<js::WsDispatch> { |
| 1800 | 1809 | let (reply, receive) = tokio::sync::oneshot::channel(); |
| 1801 | 1810 | let job = CellJob::WsMessage { |
| 1802 | 1811 | scope: cell.clone(), |
| 1803 | 1812 | ws_id, |
| 1804 | 1813 | data, |
| 1814 | + started: Some(started), | |
| 1805 | 1815 | reply, |
| 1806 | 1816 | }; |
| 1807 | 1817 | self.cell_event( |
| @@ -2581,6 +2591,7 @@ | ||
| 2581 | 2591 | // Weak, so this loop cannot keep a superseded generation's pool |
| 2582 | 2592 | // alive: it ends when the pool is dropped. |
| 2583 | 2593 | let reaping = Arc::downgrade(&isolates); |
| 2594 | + let reclaim = isolates.reclaim_bell(); | |
| 2584 | 2595 | handle.spawn(async move { |
| 2585 | 2596 | // `interval` fires its first tick immediately, which |
| 2586 | 2597 | // reaped the isolate `warm` had just built and handed the |
| @@ -2591,11 +2602,29 @@ | ||
| 2591 | 2602 | ); |
| 2592 | 2603 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 2593 | 2604 | 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 { | |
| 2596 | 2611 | return; |
| 2597 | 2612 | }; |
| 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 | + } | |
| 2599 | 2628 | } |
| 2600 | 2629 | }); |
| 2601 | 2630 | } |
| @@ -3192,6 +3221,10 @@ | ||
| 3192 | 3221 | // ticket cannot be missed by a release landing between the two. Only the |
| 3193 | 3222 | // waiting happens out here, because a turn may not await. |
| 3194 | 3223 | let mut pending = Some(job); |
| 3224 | + let started_event = match pending.as_mut() { | |
| 3225 | + Some(CellJob::WsMessage { started, .. }) => started.take(), | |
| 3226 | + _ => None, | |
| 3227 | + }; | |
| 3195 | 3228 | let (begun, started, moves) = loop { |
| 3196 | 3229 | let mut waiting = None; |
| 3197 | 3230 | let taken = slot |
| @@ -3230,6 +3263,12 @@ | ||
| 3230 | 3263 | } |
| 3231 | 3264 | }; |
| 3232 | 3265 | // 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 | + } | |
| 3233 | 3272 | if let Some(order) = order.as_mut() { |
| 3234 | 3273 | order.delivered(); |
| 3235 | 3274 | } |
modifiedcrates/celld/storage.rs+73−100View file
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | use std::cell::RefCell; |
| 18 | 18 | use std::collections::{HashMap, HashSet}; |
| 19 | 19 | use std::ffi::{CStr, CString}; |
| 20 | +use std::ops::Bound; | |
| 20 | 21 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 21 | 22 | use std::sync::Arc; |
| 22 | 23 | |
| @@ -300,10 +301,17 @@ | ||
| 300 | 301 | generation: Option<i64>, |
| 301 | 302 | } |
| 302 | 303 | |
| 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. | |
| 303 | 309 | struct SyncListCursor { |
| 304 | 310 | 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, | |
| 307 | 315 | } |
| 308 | 316 | |
| 309 | 317 | struct SqlCursor { |
| @@ -339,17 +347,6 @@ | ||
| 339 | 347 | } |
| 340 | 348 | } |
| 341 | 349 | |
| 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 | - | |
| 353 | 350 | impl Drop for SqlCursor { |
| 354 | 351 | fn drop(&mut self) { |
| 355 | 352 | if self.statement.is_null() { |
| @@ -3823,39 +3820,28 @@ | ||
| 3823 | 3820 | reverse: bool, |
| 3824 | 3821 | ) -> anyhow::Result<u64> { |
| 3825 | 3822 | 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 | + }; | |
| 3859 | 3845 | let id = NEXT_SYNC_LIST_CURSOR.fetch_add(1, Ordering::Relaxed); |
| 3860 | 3846 | sync_list_cursors(|cursors| cursors.borrow_mut().insert(id, cursor)); |
| 3861 | 3847 | Ok(id) |
| @@ -3867,65 +3853,52 @@ | ||
| 3867 | 3853 | let cursor = cursors |
| 3868 | 3854 | .get_mut(&cursor_id) |
| 3869 | 3855 | .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))); | |
| 3873 | 3885 | 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; | |
| 3918 | 3896 | Ok(Some((key, value))) |
| 3919 | 3897 | } |
| 3920 | - rusqlite::ffi::SQLITE_DONE => { | |
| 3898 | + other => { | |
| 3921 | 3899 | cursors.remove(&cursor_id); |
| 3922 | - Ok(None) | |
| 3900 | + other | |
| 3923 | 3901 | } |
| 3924 | - _ => { | |
| 3925 | - let error = sqlite_failure(cursor.database, "step sync KV cursor"); | |
| 3926 | - cursors.remove(&cursor_id); | |
| 3927 | - Err(error) | |
| 3928 | - } | |
| 3929 | 3902 | } |
| 3930 | 3903 | }) |
| 3931 | 3904 | } |
modifiedcrates/celld/telemetry.rs+50−0View file
| @@ -346,9 +346,54 @@ | ||
| 346 | 346 | pub trace_id: Option<[u8; 16]>, |
| 347 | 347 | pub span_id: Option<[u8; 8]>, |
| 348 | 348 | pub time_unix_us: i64, |
| 349 | + pub severity: Severity, | |
| 349 | 350 | pub body: String, |
| 350 | 351 | } |
| 351 | 352 | |
| 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 | + | |
| 352 | 397 | impl Span { |
| 353 | 398 | pub fn new(ids: TraceIds, name: &'static str, kind: u8) -> Span { |
| 354 | 399 | Span { |
| @@ -1076,6 +1121,8 @@ | ||
| 1076 | 1121 | optional binary trace_id (STRING); |
| 1077 | 1122 | optional binary span_id (STRING); |
| 1078 | 1123 | required int64 time_unix_us; |
| 1124 | + required int32 severity_number; | |
| 1125 | + required binary severity_text (STRING); | |
| 1079 | 1126 | required binary body (STRING); |
| 1080 | 1127 | }"; |
| 1081 | 1128 | |
| @@ -1164,6 +1211,7 @@ | ||
| 1164 | 1211 | use parquet::basic::ZstdLevel; |
| 1165 | 1212 | use parquet::data_type::ByteArray; |
| 1166 | 1213 | use parquet::data_type::ByteArrayType; |
| 1214 | + use parquet::data_type::Int32Type; | |
| 1167 | 1215 | use parquet::data_type::Int64Type; |
| 1168 | 1216 | use parquet::file::properties::WriterProperties; |
| 1169 | 1217 | use parquet::file::writer::SerializedFileWriter; |
| @@ -1207,6 +1255,8 @@ | ||
| 1207 | 1255 | column!(ByteArrayType, opt each.clone().map(|l| l.trace_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>()); |
| 1208 | 1256 | column!(ByteArrayType, opt each.clone().map(|l| l.span_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>()); |
| 1209 | 1257 | 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<_>>()); | |
| 1210 | 1260 | column!(ByteArrayType, req each.clone().map(|l| text(&l.body)).collect::<Vec<_>>()); |
| 1211 | 1261 | |
| 1212 | 1262 | group.close()?; |
modifiedcrates/celld/ws_client.rs+3−3View file
| @@ -51,7 +51,7 @@ | ||
| 51 | 51 | /// The server answered and refused the upgrade. Callers read this: a 401 |
| 52 | 52 | /// revokes managed credentials, a stale-route header triggers a |
| 53 | 53 | /// redispatch, and the isolate surfaces the whole thing to `onerror`. |
| 54 | - Declined(Declined), | |
| 54 | + Declined(Box<Declined>), | |
| 55 | 55 | /// No answer to read -- DNS, TCP, TLS, or a malformed handshake. |
| 56 | 56 | Failed(anyhow::Error), |
| 57 | 57 | } |
| @@ -183,11 +183,11 @@ | ||
| 183 | 183 | .await |
| 184 | 184 | .map(|body| body.to_bytes().to_vec()) |
| 185 | 185 | .unwrap_or_default(); |
| 186 | - return Err(Error::Declined(Declined { | |
| 186 | + return Err(Error::Declined(Box::new(Declined { | |
| 187 | 187 | status, |
| 188 | 188 | headers, |
| 189 | 189 | body, |
| 190 | - })); | |
| 190 | + }))); | |
| 191 | 191 | } |
| 192 | 192 | if response |
| 193 | 193 | .headers() |
modifiedcrates/celld/ws_registry.rs+167−11View file
| @@ -58,6 +58,109 @@ | ||
| 58 | 58 | Close(u16, String), |
| 59 | 59 | } |
| 60 | 60 | |
| 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 | + | |
| 61 | 164 | /// The result of delivering one `webSocketMessage`. `frames` are the outbound |
| 62 | 165 | /// frames of the turn the handler answered in, captured by the output gate; a |
| 63 | 166 | /// turn the handler suspended in released its own frames as it ended, so those |
| @@ -66,7 +169,7 @@ | ||
| 66 | 169 | /// handler wrote, and its frames must be held until that position is durable. |
| 67 | 170 | /// `None` means no write: flush the frames. |
| 68 | 171 | pub struct WsDispatch { |
| 69 | - pub frames: Vec<(u64, WsOut)>, | |
| 172 | + pub frames: WsBatch, | |
| 70 | 173 | pub write_position: Option<u64>, |
| 71 | 174 | /// As on `HttpResponse`: what a handler that wrote nothing observed above |
| 72 | 175 | /// the cell's published baseline, for the gate to hold its frames behind |
| @@ -763,6 +866,52 @@ | ||
| 763 | 866 | flushing |
| 764 | 867 | } |
| 765 | 868 | |
| 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 | + | |
| 766 | 915 | /// Wait until no flush holds frames for `id` any more. |
| 767 | 916 | async fn await_flushes(&self, id: u64) { |
| 768 | 917 | loop { |
| @@ -883,6 +1032,21 @@ | ||
| 883 | 1032 | } |
| 884 | 1033 | |
| 885 | 1034 | 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 | + | |
| 886 | 1050 | /// Give the gate's verdict to every segment this flush holds, then |
| 887 | 1051 | /// deliver what each socket can now release. |
| 888 | 1052 | /// |
| @@ -1025,16 +1189,8 @@ | ||
| 1025 | 1189 | /// Release a batch into each socket's ordered stream. A socket whose |
| 1026 | 1190 | /// durability-ticket queue is still present joins that queue, so an Actor |
| 1027 | 1191 | /// 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(®istry, 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(())); | |
| 1038 | 1194 | } |
| 1039 | 1195 | |
| 1040 | 1196 | /// 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 @@ | ||
| 15 | 15 | pub mod dead_node_reconciliation; |
| 16 | 16 | pub mod drain; |
| 17 | 17 | pub mod durability; |
| 18 | +pub mod epoch_gc; | |
| 18 | 19 | pub mod format; |
| 19 | 20 | pub mod gate; |
| 20 | 21 | pub mod http; |
| @@ -1004,7 +1005,9 @@ | ||
| 1004 | 1005 | } |
| 1005 | 1006 | |
| 1006 | 1007 | /// 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. | |
| 1008 | 1011 | pub fn memory_headroom(&self) -> bool { |
| 1009 | 1012 | self.memory_headroom |
| 1010 | 1013 | } |
modifiedcrates/ltx/src/paged_vfs.rs+5−0View file
| @@ -162,6 +162,11 @@ | ||
| 162 | 162 | // Two faults of one run both fetch; the loser writes nothing. |
| 163 | 163 | let run = match reader.read_run(pgno) { |
| 164 | 164 | 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, | |
| 165 | 170 | Err(_) => return ffi::SQLITE_IOERR_READ, |
| 166 | 171 | }; |
| 167 | 172 | let mut hydrated = state.hydrated.lock().unwrap(); |
modifiedcrates/ltx/src/replica.rs+12−1View file
| @@ -527,6 +527,17 @@ | ||
| 527 | 527 | Ok(()) |
| 528 | 528 | } |
| 529 | 529 | |
| 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 | + | |
| 530 | 541 | async fn restore_from_plan_inner<C: ReplicaClient>( |
| 531 | 542 | client: &C, |
| 532 | 543 | output_path: &Path, |
| @@ -577,7 +588,7 @@ | ||
| 577 | 588 | client |
| 578 | 589 | .open_ltx_file(info.level, info.min_txid, info.max_txid) |
| 579 | 590 | .await |
| 580 | - .map_err(|e| Error::Other(format!("open ltx file: {e}").into())) | |
| 591 | + .map_err(classify_restore_open_error) | |
| 581 | 592 | } |
| 582 | 593 | }) |
| 583 | 594 | .buffered(RESTORE_DOWNLOAD_CONCURRENCY) |
modifieddocs/README.md+65−2View file
| @@ -33,7 +33,21 @@ | ||
| 33 | 33 | hibernatable WebSocket clients, and stays on its node, is **hibernated**. |
| 34 | 34 | A cell that no node holds is **inactive**. An inactive cell is only an |
| 35 | 35 | 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. | |
| 37 | 51 | |
| 38 | 52 | A cell keeps no memory across these transitions, so the constructor |
| 39 | 53 | runs again on the next event. A hibernated cell wakes the same way a |
| @@ -131,6 +145,7 @@ | ||
| 131 | 145 | - [Telemetry](telemetry.md) |
| 132 | 146 | - [Testing](testing.md) |
| 133 | 147 | - [WebAssembly](wasm.md) |
| 148 | +- [Python Workers](services/workers.md#python-workers) | |
| 134 | 149 | |
| 135 | 150 | ## Services |
| 136 | 151 | |
| @@ -643,6 +658,12 @@ | ||
| 643 | 658 | `resident_cells` value includes only the cells that consume the local |
| 644 | 659 | runtime capacity. |
| 645 | 660 | |
| 661 | +The shared runtime samples the process memory, open files, and CPU every | |
| 662 | +second, and once before the first lease acquisition. The lease and `/state` | |
| 663 | +report these values from the latest sample, so they are normally one sample | |
| 664 | +period old. The `allocator` and `libc_malloc` objects in `/state` are read | |
| 665 | +when the request arrives. | |
| 666 | + | |
| 646 | 667 | The internal listener answers `GET /state` with the live counters: |
| 647 | 668 | `owned_cells`, `occupied`, `capacity_waiting`, `activation_waiting`, `restoring`, |
| 648 | 669 | `shedding`, and the memory values. The `allocator` object reports the |
| @@ -880,6 +901,19 @@ | ||
| 880 | 901 | the entries-only format, so the v0.6.0 node refuses to start. A fleet |
| 881 | 902 | that uses `bucket` durability has no followers, so it can use a rolling |
| 882 | 903 | update. |
| 904 | +- The upgrade from v0.6.0 to v0.6.1 can use a rolling update. Do not set | |
| 905 | + `CELLD_LTX_RETENTION_SECS` on a node until every node runs v0.6.1. A | |
| 906 | + v0.6.0 node does not read `cells/<cell>/ltx/retired.json`, so it treats | |
| 907 | + the rows of a deleted epoch as unstored. That node keeps those bundle | |
| 908 | + rows, it cannot seal its log at shutdown, and its next start uploads the | |
| 909 | + rows again. No data is lost, but storage use and recovery time increase. | |
| 910 | + A v0.6.0 node refuses a Python Workers deployment, so deploy a Python | |
| 911 | + application only after every node runs v0.6.1. A v0.6.0 node also refuses | |
| 912 | + an asset index with a file larger than 25 MiB. Therefore, raise | |
| 913 | + `CELLD_MAX_ASSET_FILE_BYTES` above that size only after every node runs | |
| 914 | + v0.6.1. A rollback to v0.6.0 can | |
| 915 | + also use a rolling update. Unset `CELLD_LTX_RETENTION_SECS` on every node | |
| 916 | + first, so that no v0.6.1 node deletes an epoch while a v0.6.0 node runs. | |
| 883 | 917 | |
| 884 | 918 | The internal listener also provides an alpha operator API. `/state` |
| 885 | 919 | reports the node state, and its `node_load` object is the same load sample |
| @@ -985,6 +1019,29 @@ | ||
| 985 | 1019 | celld cell list --all --json --bucket "$CELLD_BUCKET" > cells.ndjson |
| 986 | 1020 | ``` |
| 987 | 1021 | |
| 1022 | +To see the superseded epoch prefixes that epoch GC can delete, run | |
| 1023 | +`celld cell gc --dry-run`. The command takes the same listing options and | |
| 1024 | +writes nothing. It prints one row for each cell that has candidates: the | |
| 1025 | +candidate epochs, their bytes, and the base of the cell's restore chain. | |
| 1026 | +The owners can delete later than the report shows, or not at all: | |
| 1027 | + | |
| 1028 | +- Only a fleet node with a positive `CELLD_LTX_RETENTION_SECS` deletes, | |
| 1029 | + and it uses that grace instead of `--grace-secs`. | |
| 1030 | +- A paged cell waits until its local file is complete. | |
| 1031 | +- An inactive cell waits until it is active again. | |
| 1032 | +- A cell that is not paged waits until its activation has a write, so a | |
| 1033 | + cell that is only read deletes nothing. After the write, the owner | |
| 1034 | + compacts at its next pass and deletes at the pass after it. With | |
| 1035 | + `CELLD_LTX_COMPACTION=0`, the cell waits for a handoff snapshot. | |
| 1036 | +- One pass deletes at most 64 epochs of a cell. | |
| 1037 | + | |
| 1038 | +If the command cannot read a cell, it reports the cell, continues, and | |
| 1039 | +exits with an error at the end. | |
| 1040 | + | |
| 1041 | +```sh | |
| 1042 | +celld cell gc --dry-run --bucket "$CELLD_BUCKET" --grace-secs 3600 | |
| 1043 | +``` | |
| 1044 | + | |
| 988 | 1045 | ## Hot-cell overload |
| 989 | 1046 | |
| 990 | 1047 | celld admits a maximum of 64 concurrent fetch events for one Durable Object. |
| @@ -1049,16 +1106,22 @@ | ||
| 1049 | 1106 | | `CELLD_LOG_PIPELINE` | The limit for fleet log rounds that can be in flight (default: 4) | |
| 1050 | 1107 | | `CELLD_LOG_HEDGE_MS` | The wait before a leader sends a second copy of a slow log append to a follower. The default is adaptive: celld derives the wait from the slowest recent append in the ensemble (4 times that append, at least 250 ms, and always below the eviction backstop), so a loaded fleet does not send copies for honest slow appends. Set a value to use a fixed wait in milliseconds, and set `0` to disable the second copy. An append is idempotent per sequence, so the copy is safe, and the leader uses the answer that arrives first and confirms | |
| 1051 | 1108 | | `CELLD_LTX_TRUNCATE_PAGES` | The WAL size, in pages, at which celld truncates an ordinary cell's WAL file at the next checkpoint (default: 128, a 512 KiB cap). A passive checkpoint does not shrink the WAL file, so each capture reads the stale region after a restart. The truncate keeps the read small. A truncate ends in a full image of the database, so a database larger than 4 MiB also waits until its WAL is larger than the database. Queue cells use passive checkpoints only. Set `0` to disable the truncate for all cells | |
| 1109 | +| `CELLD_LTX_RETENTION_SECS` | Unset or `0` by default, and then celld deletes no epoch prefix. A positive value enables epoch GC on a fleet node (`CELLD_DURABILITY=fleet`, the default); a node with `CELLD_DURABILITY=bucket` deletes nothing. After the owner of a cell activates it, the owner deletes each epoch prefix below the base of the cell's restore chain. The base is the epoch where a restore stops, because that epoch opens with a whole-database snapshot. A paged cell waits until its local file is complete, because until then it reads pages from the older epochs. A cell that is not paged waits until its activation has a write, so a cell that is only read deletes nothing. After the write, the owner compacts the new rows into the first L1 object of its epoch, even below `CELLD_LTX_COMPACTION_MIN_TXIDS`. That object lets the owner prove that a successor restores from its epoch. The owner compacts at its next pass after the write and deletes at the pass after the compaction, and each pass can come up to 5 minutes after the previous one. With `CELLD_LTX_COMPACTION=0` the owner does not compact, so the cell waits for a handoff snapshot. With `CELLD_LTX_HYDRATE_MBPS=0` a paged cell never completes its file, so epoch GC never runs for it. The owner keeps its own epoch and the epoch before it. It also keeps each epoch whose newest object is younger than the value, in seconds. The owner first writes `cells/<cell>/ltx/retired.json`, so that bundle GC and recovery treat the rows of those epochs as stored. Epoch GC skips facet streams. It needs a store with list-after-write consistency; see [the storage requirements](guarantees.md#what-the-bucket-must-provide). Run `celld cell gc --dry-run` to see the candidates | | |
| 1052 | 1110 | | `CELLD_LTX_COMPACTION` | The default is `1`: celld creates additive L1 objects, and a takeover reads tens of objects instead of thousands. Set `0` on every node of a mixed fleet until all nodes can read v0.5.2 block objects, because an old reader cannot take over a cell after its first L1 publication | |
| 1053 | 1111 | | `CELLD_LTX_COMPACTION_MIN_TXIDS` | The durable TXID distance that queues a background L1 attempt (default: 256) | |
| 1054 | 1112 | | `CELLD_LTX_COMPACTION_MIN_MB` | The L0 bytes since the last fold that queue a background L1 attempt, in MiB (default: 32, at most 64). The byte threshold lets a cell with large rows compact before it reaches the transaction threshold | |
| 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 | | |
| 1056 | 1114 | | `CELLD_LTX_PAGED_MIN_MB` | The chain size, in MiB, from which a restore pages instead of cloning (default: 256). A clone of a smaller chain takes seconds and fits the node's memory, so it needs no fault path and no hydration. Set `0` to page every chain | |
| 1057 | 1115 | | `CELLD_LTX_HYDRATE_MBPS` | The rate, in MiB per second, at which a paged cell's file fills in the background (default: 16). One cell fills at a time per node. Set `0` to keep a paged cell sparse, so every cold page is read from the bucket on first use | |
| 1058 | 1116 | | `CELLD_LTX_COMPACTIONS` | The node-wide limit for concurrent background L1 attempts (default: 2). `CELLD_RELEASES` bounds final handoff snapshots | |
| 1059 | 1117 | | `CELLD_LTX_DURABILITY_TIMEOUT_SECS` | The budget for one durability proof, in seconds (default: 10). The budget runs from the moment the node starts to upload the write. A write that waits behind the uploads of other cells waits while the node proves other writes, for at most six budgets. The same budget bounds the final snapshot or L0 fallback of a handoff. A slow object store can need a longer budget for a large write | |
| 1118 | +| `CELLD_TOKIO_THREADS` | The worker thread count of the host Tokio runtime (default: the CPU count) | | |
| 1060 | 1119 | | `RUST_LOG` | The runtime log filter | |
| 1061 | 1120 | |
| 1121 | +When a node starts, celld emits one `host_runtime` log event at the `info` | |
| 1122 | +level. The `worker_count` field reports the worker count of the host Tokio | |
| 1123 | +runtime, so an operator can verify the applied `CELLD_TOKIO_THREADS` setting. | |
| 1124 | + | |
| 1062 | 1125 | Each L1 compaction attempt merges at most 256 source objects. The buffer |
| 1063 | 1126 | budget for the source data is 64 MiB. If one source object exceeds this |
| 1064 | 1127 | budget, celld compacts that object through temporary files in the cell's |
modifieddocs/cloudflare-compat.md+1−1View file
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | | Hyperdrive | **No** | |
| 40 | 40 | | Browser Rendering | **No** | |
| 41 | 41 | | 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 | | |
| 43 | 43 | |
| 44 | 44 | ## Runtime APIs |
| 45 | 45 |
modifieddocs/guarantees.md+35−0View file
| @@ -25,6 +25,16 @@ | ||
| 25 | 25 | - Ranged reads: a read must return the requested byte range and the bytes |
| 26 | 26 | from that range. |
| 27 | 27 | |
| 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 | + | |
| 28 | 38 | The qualified stores are Amazon S3, Cloudflare R2, Tigris, Google Cloud |
| 29 | 39 | Storage, and Azure Blob Storage. celld's release tests run against R2, |
| 30 | 40 | and the S3 path uses the same client and the same headers. |
| @@ -291,6 +301,31 @@ | ||
| 291 | 301 | writes an epoch seal object, and a legacy `e<epoch>.seal.json` object does |
| 292 | 302 | not limit the chain. |
| 293 | 303 | |
| 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 | + | |
| 294 | 329 | A fenced node can append an unacknowledged tail to an older prefix. When |
| 295 | 330 | a successor opened with a whole-database snapshot, a later restore reads |
| 296 | 331 | the full chain and can expose that tail. This does not violate the |
modifieddocs/limitations.md+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Limitations |
| 2 | 2 | |
| 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 | |
| 4 | 4 | [Cloudflare compatibility](cloudflare-compat.md) for the supported services, |
| 5 | 5 | APIs, and Wrangler configuration. |
| 6 | 6 |
modifieddocs/security.md+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Security |
| 2 | 2 | |
| 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. | |
| 4 | 4 | Security fixes apply to the latest release only, so older beta releases do not |
| 5 | 5 | receive fixes. |
| 6 | 6 |
modifieddocs/services/durable-object-facets.md+13−3View file
| @@ -52,10 +52,20 @@ | ||
| 52 | 52 | is a `DurableObjectClass`, and two sources supply one. The first source is |
| 53 | 53 | `worker.getDurableObjectClass("App")` on a Worker Loader binding. The second is |
| 54 | 54 | `ctx.exports.App` for a `DurableObject` class that the Worker exports without a |
| 55 | -storage migration, and that facet runs in the isolate of its root. `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. | |
| 58 | 56 | |
| 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 | + | |
| 59 | 69 | The name alone selects the database, so a later call that keeps the name and |
| 60 | 70 | changes the `id` still reaches the stored data. A name has a limit of 256 bytes. |
| 61 | 71 | 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 @@ | ||
| 68 | 68 | |
| 69 | 69 | A Worker holds its stub on whichever node served the request. celld resolves |
| 70 | 70 | the owner of the cell and forwards the call to that node, so the object code |
| 71 | -runs on the owner and nowhere else. Inside the cell, one 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 | |
| 73 | 74 | holds a response until a durability proof covers every write that the response |
| 74 | 75 | can reveal, which is the behavior Cloudflare calls the |
| 75 | 76 | [output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/). |
| @@ -79,6 +80,11 @@ | ||
| 79 | 80 | Therefore a `webSocketMessage()` handler that sends a frame and then awaits |
| 80 | 81 | delivers that frame while it still runs, and an application can stream an |
| 81 | 82 | answer through one handler. |
| 83 | +On one socket, celld starts the message handlers in arrival order, but it does | |
| 84 | +not wait for a handler to finish before starting the next handler. Therefore | |
| 85 | +an incoming message can cancel work that an earlier handler awaits. | |
| 86 | +A hibernatable socket delivers the frames in send order across WebSocket | |
| 87 | +handlers and RPC methods, even when the output gate delays an earlier frame. | |
| 82 | 88 | |
| 83 | 89 |  |
| 84 | 90 | |
| @@ -109,6 +115,13 @@ | ||
| 109 | 115 | [storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/) |
| 110 | 116 | for the method signatures. |
| 111 | 117 | |
| 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 | + | |
| 112 | 125 | The durability of that database comes from the fleet, not from a managed |
| 113 | 126 | service. celld captures each write as an LTX segment and replicates the segment |
| 114 | 127 | 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 @@ | ||
| 1 | 1 | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 600" role="img" aria-labelledby="dwFlowTitle dwFlowDesc"> |
| 2 | 2 | <title id="dwFlowTitle">What a loader grants a Dynamic Worker, and what it withholds</title> |
| 3 | - <desc id="dwFlowDesc">One celld node runs one process that holds two V8 isolates, and not two machines and not a virtual machine. The host Worker isolate holds the deployment's bindings, vars, and secrets, and it calls env.LOADER.get(id, getCode), whose getCode runs once per id in that isolate. Only two things cross the boundary into the loaded isolate: the modules map with its mainModule, at most 64 MiB 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> | |
| 4 | 4 | <style> |
| 5 | 5 | svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } |
| 6 | 6 | text { font-size: 13px; fill: currentColor; } |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="200" width="184" height="142" rx="8" /> |
| 59 | 59 | <text class="d-acc lead" fill="currentColor" x="34" y="224">crosses the boundary</text> |
| 60 | 60 | <text class="d-ink mono" fill="currentColor" x="34" y="248">modules, mainModule</text> |
| 61 | - <text class="d-faint" fill="currentColor" x="34" y="266">64 MiB, compiled once</text> | |
| 61 | + <text class="d-faint" fill="currentColor" x="34" y="266">64 MiB default limit</text> | |
| 62 | 62 | <text class="d-ink mono" fill="currentColor" x="34" y="292">env, props</text> |
| 63 | 63 | <text class="d-faint" fill="currentColor" x="34" y="310">structured-clone values</text> |
| 64 | 64 | <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 @@ | ||
| 41 | 41 | module's name. Thus, `dir/a.js` can import `./b.js` when the map contains |
| 42 | 42 | `dir/b.js`. `compatibilityDate` is required, as in workerd, and |
| 43 | 43 | `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 | |
| 46 | 50 | `cpuMs` and `subRequests` for each invocation. celld refuses a `WorkerCode` |
| 47 | 51 | that sets `allowExperimental`. Read the |
| 48 | 52 | [API reference](https://developers.cloudflare.com/dynamic-workers/api-reference/) |
| @@ -104,17 +108,25 @@ | ||
| 104 | 108 | `get(id, getCode)` memoizes the load by id inside one loader binding of one |
| 105 | 109 | host isolate. The first use of an id runs `getCode` and compiles the modules, |
| 106 | 110 | 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. | |
| 111 | 116 | Cloudflare describes the same reuse as a possibility and not as a guarantee. |
| 112 | 117 | |
| 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. | |
| 117 | 124 | |
| 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 | + | |
| 118 | 130 | Every loaded Worker belongs to the isolate that created it. celld drops all of |
| 119 | 131 | them when that isolate retires, which happens when the request load falls or |
| 120 | 132 | 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 @@ | ||
| 133 | 133 | and reads no `If-Modified-Since` header. |
| 134 | 134 | - A `_headers` file cannot change `connection`, `content-length`, or |
| 135 | 135 | `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. | |
| 138 | 145 | - `celld deploy` accepts only `directory`, `binding`, `html_handling`, |
| 139 | 146 | `not_found_handling`, and `run_worker_first` in the `assets` block. |
| 140 | 147 | - `celld deploy` refuses a `.assetsignore` file, and it stops the deployment |
modifieddocs/services/workers.md+114−0View file
| @@ -84,3 +84,117 @@ | ||
| 84 | 84 | |
| 85 | 85 | The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the |
| 86 | 86 | 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 @@ | ||
| 56 | 56 | it, so a query can join the logs to the traces. The correlation |
| 57 | 57 | survives `await`. |
| 58 | 58 | |
| 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 | + | |
| 59 | 78 | celld reads the W3C `traceparent` header on incoming requests, so its |
| 60 | 79 | spans join the trace of the system in front of it. celld sends a |
| 61 | 80 | `traceparent` header on outbound `fetch()`, so downstream systems can |
| @@ -96,6 +115,9 @@ | ||
| 96 | 115 | SELECT name, duration_us, trace_id FROM traces |
| 97 | 116 | ORDER BY duration_us DESC LIMIT 20; |
| 98 | 117 | |
| 118 | +-- The error lines. | |
| 119 | +SELECT time_unix_us, body FROM logs WHERE severity_number >= 17; | |
| 120 | + | |
| 99 | 121 | -- Every log line, inside the span that wrote it. |
| 100 | 122 | SELECT l.body, t.name, t.duration_us FROM logs l |
| 101 | 123 | 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 @@ | ||
| 29 | 29 | in a container per sandbox; needs `npm install` and a Docker or Podman CLI |
| 30 | 30 | - `pi/` — the PiHarness agent loop in a Durable Object |
| 31 | 31 | - `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)) | |
| 32 | 34 | - `wasm/` — a Durable Object counter in Rust, compiled to Wasm with |
| 33 | 35 | [workers-rs](https://github.com/cloudflare/workers-rs); needs a build step |
| 34 | 36 | 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 | +} |