Diffinery

homeflare/celldpublic

celld/crates/celld/ltx_repl.rs
4464 lines · 186.5 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! In-process replication backend built on `celld-ltx`.
4//!
5//! One shared `object_store` client for the whole node, and a managed
6//! `celld_ltx::Db` per resident cell that captures the cell's committed WAL
7//! and uploads it on demand. No external process, no directory-watch lag — a
8//! just-written cell is registered the instant it activates, so the output
9//! gate can prove a fresh cell durable with no cold-start window.
10//!
11//! The object layout is `cells/<cell>/ltx/e<epoch>/` in the bucket, mirroring
12//! the local `<watch>/<cell>/ltx/e<epoch>/db.sqlite` tree. This backend builds
13//! its own object-store clients rather than going through `bucket::Bucket`, so
14//! it carries the fleet's key prefix itself: without that, two fleets sharing
15//! one bucket would replicate over each other.
16
17use std::collections::BTreeMap;
18use std::collections::BTreeSet;
19use std::path::Path;
20use std::path::PathBuf;
21use std::sync::atomic::AtomicBool;
22use std::sync::atomic::AtomicU64;
23use std::sync::atomic::Ordering;
24use std::sync::Arc;
25use std::sync::Mutex;
26use std::sync::Weak;
27use std::time::Duration;
28
29use anyhow::anyhow;
30use celld_ltx::client::epochs::EpochChain;
31use celld_ltx::object_store::ObjectStore;
32use celld_ltx::replica;
33use celld_ltx::replica_compactor::{CompactionResult, ReplicaCompactor};
34use celld_ltx::Db;
35use celld_ltx::HostTaskError;
36use celld_ltx::LtxHost;
37use celld_ltx::ObjectStoreClient;
38use celld_ltx::ObjectStoreConfig;
39use celld_ltx::Pos;
40use celld_ltx::Replica;
41use celld_ltx::ReplicaClient;
42use celld_ltx::TimestampMetadataKey;
43use celld_ltx::TXID;
44use tokio::sync::mpsc;
45use tokio::sync::Notify;
46use tokio::sync::Semaphore;
47use tracing::info;
48use tracing::warn;
49
50use crate::asyncrt;
51use crate::replication::sqlite_snapshot;
52use crate::replication::ActivationOptions;
53use crate::replication::ActivationResult;
54use crate::replication::RestoredSnapshot;
55use crate::replication::StorageCredentials;
56use crate::replication::SyncWait;
57use crate::replication::{EvictionAbandon, EvictionRestoreArtifact};
58use celld_logic::durability::{proof_deadline, ProofProgress, ProofWait};
59
60/// Max cells uploading concurrently across the node. Caps blocking-pool threads
61/// and in-flight object-store requests under high write fan-out.
62const SYNC_CONCURRENCY: usize = 64;
63
64/// The upload slots this node starts with. The simulation narrows them to
65/// put a second cell's upload in the queue on purpose, which is the state
66/// the durability wait's queued regime exists for.
67fn sync_concurrency() -> usize {
68 #[cfg(celld_internal_tests)]
69 if let Some(slots) = sync_concurrency_for_world() {
70 return slots;
71 }
72 SYNC_CONCURRENCY
73}
74
75/// Max LTX object downloads across every restore on this node. A hot cell can
76/// contain thousands of L0 files, so serial reads turn a takeover into minutes
77/// of terminal failures. This shared ceiling hides round-trip latency without
78/// multiplying the bound by the activation count.
79const RESTORE_DOWNLOAD_CONCURRENCY: usize = 64;
80
81/// One attempt consumes at most this many source objects. This bound keeps a
82/// first compaction of an old, write-hot cell from reading its complete L0
83/// history into memory.
84const COMPACTION_MAX_FILES: usize = 256;
85
86/// Bound buffered source data. An indivisible object above this budget uses
87/// scratch files and bounded range reads instead of stalling the level.
88const COMPACTION_MAX_INPUT_BYTES: u64 = 64 * 1024 * 1024;
89
90/// One captured-but-not-yet-uploaded L0 segment, the log tier's
91/// replication unit (`crate::node_log`).
92pub struct ShipEntry {
93 pub cell: String,
94 pub epoch: u64,
95 pub txid: u64,
96 pub bytes: Vec<u8>,
97}
98
99/// The result of one submitted ship round. The private reservation stays
100/// live until the ship loop applies or discards the result, so dropping either
101/// a pending future or a completed result releases the reconfigure barrier.
102pub struct ShipCompletion {
103 last_seq: Option<u64>,
104 _reservation: Option<Box<dyn Send>>,
105}
106
107impl ShipCompletion {
108 pub fn unreserved(last_seq: Option<u64>) -> Self {
109 Self {
110 last_seq,
111 _reservation: None,
112 }
113 }
114
115 pub fn reserved(last_seq: Option<u64>, reservation: impl Send + 'static) -> Self {
116 Self {
117 last_seq,
118 _reservation: Some(Box::new(reservation)),
119 }
120 }
121
122 pub fn last_seq(&self) -> Option<u64> {
123 self.last_seq
124 }
125}
126
127/// The fleet shipper the log tier installs: pipelined, all-member fsync
128/// confirmation. A completion without a sequence means the batch is not
129/// fleet-durable and the gate must ride the bucket upload instead.
130pub trait Shipper: Send + Sync + 'static {
131 /// Ship one batch; `covered_seq` is the highest sequence whose frames
132 /// are all bucket-covered, which followers may truncate behind.
133 /// `completion.last_seq() == Some(last_seq)` means every member confirmed
134 /// the whole batch. The completion owns the round's barrier reservation.
135 /// Owned arguments and a 'static future: the shipper runs its
136 /// synchronous prefix (sequence allocation, per-member lane enqueue)
137 /// before returning, so SUBMISSION order — not poll order — fixes the
138 /// per-member append order when several rounds are in flight.
139 fn ship(
140 &self,
141 batch: Vec<ShipEntry>,
142 covered_seq: u64,
143 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ShipCompletion> + Send + 'static>>;
144
145 /// Ship a batch captured under `expected_epoch`. A stable manager whose
146 /// delegate can change must override this method and select plus reserve
147 /// the matching delegate atomically.
148 fn ship_at_epoch(
149 &self,
150 expected_epoch: u64,
151 batch: Vec<ShipEntry>,
152 covered_seq: u64,
153 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ShipCompletion> + Send + 'static>> {
154 if self.epoch() != expected_epoch {
155 return Box::pin(std::future::ready(ShipCompletion::unreserved(None)));
156 }
157 self.ship(batch, covered_seq)
158 }
159
160 /// Rounds this shipper wants in flight at once. The loop applies
161 /// credits strictly in submission order regardless of the depth.
162 fn pipeline(&self) -> usize {
163 1
164 }
165
166 /// True while the shipper can take one more batch. The stream window
167 /// closes this on the slowest member's lane — appends or bytes — and
168 /// the loop then waits on a completion exactly as it does at depth.
169 fn admit(&self) -> bool {
170 true
171 }
172
173 /// A degraded shipper refuses instantly; the ship loop skips capture.
174 fn active(&self) -> bool;
175 /// The log epoch this shipper writes. Sequences restart at zero each
176 /// epoch, so the ship loop's truncation ledger must reset with it — a
177 /// stale covered watermark from the previous epoch would tell fresh
178 /// followers to delete entries they just fsync'd.
179 fn epoch(&self) -> u64;
180}
181
182/// The compactor-facing fetcher: one cell-epoch's view over whatever sink
183/// is currently installed. Reading the slot per call makes activation
184/// order irrelevant — a cell activated before the sink existed still sees
185/// bundles once it does.
186struct SinkFetcher {
187 registration: Arc<Mutex<RegistrationState>>,
188 cell: String,
189 epoch: u64,
190}
191
192impl celld_ltx::BundleFetcher for SinkFetcher {
193 fn rows<'a>(
194 &'a self,
195 ) -> std::pin::Pin<
196 Box<
197 dyn std::future::Future<Output = celld_ltx::Result<Vec<celld_ltx::LocatedRow>>>
198 + Send
199 + 'a,
200 >,
201 > {
202 Box::pin(async move {
203 let sink =
204 registered_durability(&self.registration).map(|targets| targets.manager.clone());
205 Ok(sink.map_or_else(Vec::new, |sink| sink.rows_for(&self.cell, self.epoch)))
206 })
207 }
208
209 fn fetch<'a>(
210 &'a self,
211 located: &'a celld_ltx::LocatedRow,
212 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = celld_ltx::Result<Vec<u8>>> + Send + 'a>>
213 {
214 Box::pin(async move {
215 let sink =
216 registered_durability(&self.registration).map(|targets| targets.manager.clone());
217 let Some(sink) = sink else {
218 return Err(celld_ltx::Error::Other("no bundle sink".into()));
219 };
220 let bytes = sink
221 .fetch_bundle(&located.source)
222 .await
223 .map_err(|e| celld_ltx::Error::Other(e.to_string().into()))?;
224 Ok(celld_ltx::bundle::slice(&bytes, &located.row)?.to_vec())
225 })
226 }
227
228 fn fetch_range<'a>(
229 &'a self,
230 located: &'a celld_ltx::LocatedRow,
231 offset: u64,
232 len: u64,
233 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = celld_ltx::Result<Vec<u8>>> + Send + 'a>>
234 {
235 Box::pin(async move {
236 let sink = registered_durability(&self.registration)
237 .map(|targets| targets.manager.clone())
238 .ok_or_else(|| celld_ltx::Error::Other("no bundle sink".into()))?;
239 sink.fetch_bundle_range(located, offset, len)
240 .await
241 .map_err(|error| celld_ltx::Error::Other(error.to_string().into()))
242 })
243 }
244}
245
246struct RegisteredDurability {
247 generation: u64,
248 targets: Weak<RegisteredTargets>,
249}
250
251struct RegisteredTargets {
252 shipper: Arc<dyn Shipper>,
253 manager: Arc<crate::node_log::NodeLogManager>,
254}
255
256#[derive(Default)]
257struct RegistrationState {
258 next_generation: u64,
259 current: Option<RegisteredDurability>,
260}
261
262fn registered_durability(
263 registration: &Arc<Mutex<RegistrationState>>,
264) -> Option<Arc<RegisteredTargets>> {
265 let state = registration.lock().unwrap();
266 state
267 .current
268 .as_ref()
269 .and_then(|current| current.targets.upgrade())
270}
271
272/// Removes one coupled shipper and bundle-sink registration on drop.
273///
274/// A newer installation supersedes an older guard. The generation check keeps
275/// the old guard from clearing the replacement when construction retries.
276#[must_use = "keep the registration alive for the durability owner's lifetime"]
277pub(crate) struct DurabilityRegistration {
278 registration: Weak<Mutex<RegistrationState>>,
279 generation: u64,
280 _targets: Arc<RegisteredTargets>,
281}
282
283#[derive(Clone)]
284#[doc(hidden)]
285pub struct StopToken {
286 state: Arc<StopState>,
287}
288
289struct StopState {
290 stopped: AtomicBool,
291 notify: Notify,
292}
293
294impl StopToken {
295 #[allow(clippy::new_without_default)]
296 #[doc(hidden)]
297 pub fn new() -> Self {
298 Self {
299 state: Arc::new(StopState {
300 stopped: AtomicBool::new(false),
301 notify: Notify::new(),
302 }),
303 }
304 }
305
306 pub(crate) fn request_stop(&self) {
307 self.state.stopped.store(true, Ordering::SeqCst);
308 self.state.notify.notify_waiters();
309 }
310
311 pub(crate) fn is_stopped(&self) -> bool {
312 self.state.stopped.load(Ordering::SeqCst)
313 }
314
315 pub(crate) async fn stopped(&self) {
316 loop {
317 let notified = self.state.notify.notified();
318 if self.is_stopped() {
319 return;
320 }
321 notified.await;
322 }
323 }
324}
325
326struct OwnedTask {
327 id: u64,
328 role: &'static str,
329 handle: asyncrt::TaskHandle<()>,
330}
331
332struct TaskGroupInner {
333 next_id: AtomicU64,
334 tasks: Mutex<Vec<OwnedTask>>,
335 #[cfg(celld_internal_tests)]
336 started_roles: Mutex<std::collections::BTreeSet<&'static str>>,
337 #[cfg(celld_internal_tests)]
338 joined_failures: AtomicU64,
339}
340
341struct TaskCompletion {
342 group: Weak<TaskGroupInner>,
343 id: u64,
344}
345
346struct JoiningTask {
347 group: Arc<TaskGroupInner>,
348 task: Option<OwnedTask>,
349}
350
351impl Drop for JoiningTask {
352 fn drop(&mut self) {
353 if let Some(task) = self.task.take() {
354 self.group.tasks.lock().unwrap().push(task);
355 }
356 }
357}
358
359impl Drop for TaskCompletion {
360 fn drop(&mut self) {
361 // A panic drops this guard before the runtime resolves the matching
362 // task handle to an error. Keep that handle for `join`, so shutdown
363 // reports the failed durability role instead of silently reaping it.
364 if std::thread::panicking() {
365 return;
366 }
367 let Some(group) = self.group.upgrade() else {
368 return;
369 };
370 group
371 .tasks
372 .lock()
373 .unwrap()
374 .retain(|task| task.id != self.id);
375 }
376}
377
378#[derive(Clone)]
379pub(crate) struct TaskGroup {
380 stop: StopToken,
381 inner: Arc<TaskGroupInner>,
382}
383
384impl TaskGroup {
385 pub(crate) fn new(stop: StopToken) -> Self {
386 Self {
387 stop,
388 inner: Arc::new(TaskGroupInner {
389 next_id: AtomicU64::new(0),
390 tasks: Mutex::new(Vec::new()),
391 #[cfg(celld_internal_tests)]
392 started_roles: Mutex::new(std::collections::BTreeSet::new()),
393 #[cfg(celld_internal_tests)]
394 joined_failures: AtomicU64::new(0),
395 }),
396 }
397 }
398
399 pub(crate) fn spawn_owned(
400 &self,
401 role: &'static str,
402 future: impl std::future::Future<Output = ()> + Send + 'static,
403 ) -> bool {
404 // Keep the lock until the handle is installed. A task can complete on
405 // another executor thread immediately after spawn, so its completion
406 // guard must not run before the matching handle becomes visible.
407 let mut tasks = self.inner.tasks.lock().unwrap();
408 if self.stop.is_stopped() {
409 return false;
410 }
411 let id = self.inner.next_id.fetch_add(1, Ordering::SeqCst);
412 #[cfg(celld_internal_tests)]
413 self.inner.started_roles.lock().unwrap().insert(role);
414 let completion = TaskCompletion {
415 group: Arc::downgrade(&self.inner),
416 id,
417 };
418 tasks.push(OwnedTask {
419 id,
420 role,
421 handle: asyncrt::spawn(async move {
422 let _completion = completion;
423 future.await;
424 }),
425 });
426 true
427 }
428
429 pub(crate) fn is_empty(&self) -> bool {
430 self.inner.tasks.lock().unwrap().is_empty()
431 }
432
433 pub(crate) fn stop_token(&self) -> StopToken {
434 self.stop.clone()
435 }
436
437 pub(crate) async fn join(&self) {
438 loop {
439 let Some(task) = self.inner.tasks.lock().unwrap().pop() else {
440 return;
441 };
442 let role = task.role;
443 // The lease puts its handle back when this join future is
444 // cancelled. A later shutdown join can therefore still prove
445 // completion for every admitted task.
446 let mut joining = JoiningTask {
447 group: self.inner.clone(),
448 task: Some(task),
449 };
450 let result = (&mut joining.task.as_mut().unwrap().handle).await;
451 let _completed = joining.task.take().unwrap();
452 if let Err(error) = result {
453 #[cfg(celld_internal_tests)]
454 self.inner.joined_failures.fetch_add(1, Ordering::SeqCst);
455 warn!(role, %error, "durability task stopped with an error");
456 }
457 }
458 }
459
460 #[cfg(celld_internal_tests)]
461 pub(crate) fn roles_for_world(&self) -> Vec<&'static str> {
462 self.inner
463 .started_roles
464 .lock()
465 .unwrap()
466 .iter()
467 .copied()
468 .collect()
469 }
470
471 #[cfg(celld_internal_tests)]
472 pub(crate) fn live_roles_for_world(&self) -> Vec<&'static str> {
473 self.inner
474 .tasks
475 .lock()
476 .unwrap()
477 .iter()
478 .map(|task| task.role)
479 .collect()
480 }
481}
482
483pub(crate) struct LtxTaskOwner {
484 tasks: TaskGroup,
485 replica_close_tasks: TaskGroup,
486}
487
488impl LtxTaskOwner {
489 pub(crate) fn request_stop(&self) {
490 self.tasks.stop.request_stop();
491 }
492
493 pub(crate) async fn join(&self) {
494 // Roots and their descendants share admission and completion tracking.
495 // Once stopped, no successor can enter; joining this group therefore
496 // needs no ordering between sync, compaction, and delayed requeues.
497 self.tasks.join().await;
498 // Release closes remain admissible after background work stops, until
499 // shutdown seals their separate admission gate.
500 self.replica_close_tasks.join().await;
501 }
502}
503
504impl Drop for DurabilityRegistration {
505 fn drop(&mut self) {
506 let Some(registration) = self.registration.upgrade() else {
507 return;
508 };
509 let mut state = registration.lock().unwrap();
510 if state
511 .current
512 .as_ref()
513 .is_some_and(|current| current.generation == self.generation)
514 {
515 state.current = None;
516 }
517 }
518}
519
520#[derive(Debug, Clone, Copy)]
521pub struct CompactionConfig {
522 pub min_txids: u64,
523 /// L0 bytes since the last fold that queue one independently of the txid
524 /// distance, so large rows do not accumulate a long uncompacted tail.
525 pub min_bytes: u64,
526 pub concurrency: usize,
527}
528
529struct CellCompaction {
530 cell: String,
531 epoch: u64,
532 client: celld_ltx::BundleOverlayClient<ObjectStoreClient>,
533 local_path: PathBuf,
534 host: LtxHost,
535 queue: mpsc::UnboundedSender<CompactionWork>,
536 /// The epoch's first txid: 1, or the cut a paged epoch continues from.
537 base_txid: u64,
538 min_txids: u64,
539 min_bytes: u64,
540 /// L0 bytes uploaded since the last fold, the size trigger's measure.
541 pending_bytes: AtomicU64,
542 compacted_txid: AtomicU64,
543 queued: AtomicBool,
544 cancelled: AtomicBool,
545 cancel: Notify,
546 #[cfg(all(test, celld_internal_tests))]
547 finish_pause: Mutex<Option<Arc<CompactionFinishPauseForWorld>>>,
548 /// Serializes threshold compaction with the final handoff snapshot. The
549 /// handoff path cancels background work, then waits here before it reads
550 /// the quiesced database image.
551 run: tokio::sync::Mutex<()>,
552}
553
554struct CompactionWork {
555 cell: Weak<Cell>,
556 queued_at_mono_ms: u64,
557}
558
559struct RemoteRestoreTiming {
560 started_mono_ms: u64,
561 from: u64,
562 source_lookup_us: u64,
563 plan_us: u64,
564 /// The page map's build, on a paged activation; zero on a download.
565 map_us: u64,
566 download_us: u64,
567 apply_us: u64,
568 objects: usize,
569 bytes: u64,
570 levels: String,
571 paged: bool,
572}
573
574/// A paged VFS registration that unregisters itself unless the activation
575/// reaches its handle: every failure after the registration (the managed
576/// db's open, the seed, the marker's upload, admission) otherwise leaked a
577/// registration and the page map it holds, once per retry.
578struct PagedRegistration(Option<String>);
579
580impl PagedRegistration {
581 fn keep(mut self) {
582 self.0 = None;
583 }
584}
585
586impl Drop for PagedRegistration {
587 fn drop(&mut self) {
588 if let Some(name) = self.0.take() {
589 let _ = celld_ltx::paged_vfs::unregister_paged_vfs(&name);
590 }
591 }
592}
593
594/// `L0:n L1:m ...` for a plan, as the restore_plan event prints it.
595fn by_level(plan: &[celld_ltx::FileInfo]) -> String {
596 let mut counts = std::collections::BTreeMap::new();
597 for info in plan {
598 *counts.entry(info.level).or_insert(0usize) += 1;
599 }
600 counts
601 .iter()
602 .map(|(level, count)| format!("L{level}:{count}"))
603 .collect::<Vec<_>>()
604 .join(" ")
605}
606
607struct HandoffSnapshot {
608 max_txid: TXID,
609 data: Vec<u8>,
610}
611
612/// One resident cell's replication state: the `celld_ltx::Db` shadowing its WAL
613/// (behind a `std::sync::Mutex` because the `rusqlite` handle is `!Sync` and
614/// must never cross an `.await`, so every capture+upload runs inside a
615/// `spawn_blocking` closure) plus the durability tickets the output gate waits
616/// on. `req_seq` counts durability requests; `synced_seq` is the highest ticket
617/// a completed background sync captured. A write waits for `synced_seq >= its
618/// ticket`, so concurrent writes to one cell ride a single batched upload —
619/// and, because a sync credits only tickets whose writes committed before it
620/// started (which the sync's `db.sync` captures), never one it did not upload.
621struct Cell {
622 /// A handoff snapshot of this cell did not publish inside the durability
623 /// deadline, or its size showed that it cannot. Every later eviction of
624 /// this epoch proves durability through the L0 chain instead of building
625 /// and timing out on the same snapshot again.
626 snapshot_declined: AtomicBool,
627 /// The paged VFS registered for this activation (paged restore only). The
628 /// local db is then a sparse cache of the cut: every reader of the file
629 /// must go through this VFS, the file is not a reusable eviction baseline,
630 /// and a handoff snapshot built from it would publish hole-zeros as data.
631 paged_vfs: Option<String>,
632 hydration: Option<Arc<CellHydration>>,
633 replica: Mutex<Option<Replica<ObjectStoreClient>>>,
634 /// The same epoch-prefix client the replica holds, for uploads that run
635 /// off the replica mutex.
636 client: ObjectStoreClient,
637 req_seq: AtomicU64,
638 synced_seq: AtomicU64,
639 /// Highest ticket whose write is fsync'd on every ensemble member —
640 /// the log tier's proof. The gate accepts either proof, so this stays 0
641 /// forever when no shipper is installed.
642 shipped_seq: AtomicU64,
643 /// Highest ticket included in a submitted fleet round. It can run ahead
644 /// of `shipped_seq` while the pipeline is in flight, so the next capture
645 /// does not submit the same write again.
646 submitted_seq: AtomicU64,
647 /// Highest TXID credited by the fleet (or already covered by the bucket).
648 shipped_txid: AtomicU64,
649 /// Highest TXID included in a submitted fleet round. A pipeline reset
650 /// rolls it back to `shipped_txid`, so the failed tail is retried once.
651 submitted_txid: AtomicU64,
652 durable_txid: AtomicU64,
653 /// Highest TXID the PER-CELL prefix provably covers through this
654 /// handle: the restored position at open, advanced only by the
655 /// per-cell sync upload. `durable_txid` cannot serve this role —
656 /// the bundle flush credits it, and the graceful seal already
657 /// learned that every ack counter counts bundle credits. Together
658 /// with `compacted_txid` (the drain's per-cell L1 fold) it bounds
659 /// what a successor restore will actually see, which is what
660 /// `note_undrained_tail` compares against (#473).
661 percell_txid: AtomicU64,
662 /// Set while a sync for this cell is in flight, so the loop never runs two
663 /// at once for one cell (they would serialize on the mutex and waste work).
664 syncing: AtomicBool,
665 /// Wall-clock ms of the last completed sync, the pacing anchor: with a
666 /// healthy shipper the bucket runs at most one upload per flush interval
667 /// behind, which is the tier's stated lag budget.
668 last_sync_ms: AtomicU64,
669 /// The highest `req_seq` a capture of this cell has begun for, and the
670 /// monotonic ms when that capture began. A waiter reads them to learn
671 /// whether the upload covering its ticket is in flight (the fixed proof
672 /// budget then runs from the capture) or still queued behind other cells'
673 /// uploads (the wait extends while the node proves anything). See
674 /// `celld_logic::durability`. A retry of the same tickets keeps the
675 /// original start, so a persistently failing upload still gives up one
676 /// budget after it first began.
677 capture_seq: AtomicU64,
678 capture_started_ms: AtomicU64,
679 /// Node-wide: monotonic ms of the last proof any cell landed, shared by
680 /// every handle. The queued-wait rule anchors on it.
681 node_proof_ms: Arc<AtomicU64>,
682 /// Notified when `synced_seq` advances (or a sync fails), waking waiters.
683 ready: Notify,
684 compaction: Option<CellCompaction>,
685 #[cfg(all(test, celld_internal_tests))]
686 observer_cell: String,
687 #[cfg(all(test, celld_internal_tests))]
688 observer_epoch: u64,
689 #[cfg(all(test, celld_internal_tests))]
690 durability_ticket_receipts: Mutex<Vec<LtxDurabilityTicketReceiptForWorldV1>>,
691 #[cfg(all(test, celld_internal_tests))]
692 upload_round_receipts: Mutex<Vec<LtxUploadRoundReceiptForWorldV1>>,
693 #[cfg(all(test, celld_internal_tests))]
694 fleet_credit_receipts: Mutex<Vec<LtxFleetCreditReceiptForWorldV1>>,
695}
696type CellHandle = Arc<Cell>;
697
698/// Both direct L0 drains and L1 folds publish per-cell coverage. Reading only
699/// the direct watermark makes recovery re-upload rows that L1 already holds.
700fn percell_coverage(handle: &Cell) -> u64 {
701 handle.percell_txid.load(Ordering::SeqCst).max(
702 handle.compaction.as_ref().map_or(0, |compaction| {
703 compaction.compacted_txid.load(Ordering::SeqCst)
704 }),
705 )
706}
707
708/// A capture covering tickets up to `captured` has begun for this cell. Only
709/// a capture that reaches new tickets moves the start: a retry of the same
710/// tickets keeps the budget it has already spent.
711fn note_capture(handle: &Cell, captured: u64) {
712 if handle.capture_seq.load(Ordering::SeqCst) < captured {
713 handle
714 .capture_started_ms
715 .store(asyncrt::mono_ms(), Ordering::SeqCst);
716 handle.capture_seq.fetch_max(captured, Ordering::SeqCst);
717 }
718}
719
720/// A proof landed for this cell: the node is making progress.
721fn note_proof(handle: &Cell) {
722 handle
723 .node_proof_ms
724 .fetch_max(asyncrt::mono_ms(), Ordering::SeqCst);
725}
726
727/// A writer that refuses to grow past its budget, so an oversized snapshot
728/// stops at the budget instead of materializing the whole database.
729struct BoundedWriter<'a> {
730 data: &'a mut Vec<u8>,
731 budget: usize,
732}
733
734impl std::io::Write for BoundedWriter<'_> {
735 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
736 if self.data.len().saturating_add(buf.len()) > self.budget {
737 self.data.resize(self.budget, 0);
738 return Err(std::io::Error::other("handoff snapshot exceeds its budget"));
739 }
740 self.data.extend_from_slice(buf);
741 Ok(buf.len())
742 }
743
744 fn flush(&mut self) -> std::io::Result<()> {
745 Ok(())
746 }
747}
748
749/// Bytes per millisecond of deadline that a handoff snapshot may occupy:
750/// 8 MiB/s, below the fleet-to-bucket rate seen on every lab run, so a
751/// snapshot inside the budget uploads inside the deadline with margin. The
752/// default deadline therefore carries 80 MiB; a larger database hands off
753/// through its L0 chain. Without this bound a 120 MB cell built its image,
754/// timed out, and retried forever, unreachable, on the 2026-09-03 fleet.
755const SNAPSHOT_BYTES_PER_MS: u64 = 8 * 1024;
756
757/// The default deadline for one durability proof, in seconds. A sustained
758/// write burst (a large upload landing in one cell) can legitimately need
759/// more than one capture+upload cycle to prove; on a slow or busy store a
760/// fixed 10s fences the cell out from under an active request, so operators
761/// can raise it via `CELLD_LTX_DURABILITY_TIMEOUT_SECS`.
762const DEFAULT_DURABILITY_TIMEOUT_SECS: u64 = 10;
763
764/// The TRUNCATE checkpoint threshold, in pages. Chosen from a measured
765/// threshold curve (2026-08-26): the read per sync is flat from 64 to 128
766/// pages (~68 KB against ~2.4 MB untruncated) and 128 pays half the
767/// boundary snapshots of 64, while 256 and above let the stale-tail reads
768/// back in. A 512 KB WAL cap keeps every capture's read small for the price
769/// of one boundary snapshot of the database per checkpoint cycle — which is
770/// only a small-cell price: the Db also requires the WAL to outgrow the
771/// database before it truncates, so a whale pays that image once per
772/// database's worth of writes, not once per 512 KB (its chain grew as the
773/// square of its size on the 2026-09-02 fleet before that bound).
774const DEFAULT_TRUNCATE_PAGES: u32 = 128;
775
776/// The chain size from which a restore pages, in MiB. A clone of this much
777/// takes a few seconds at fleet bandwidth and fits a node's memory with
778/// room to spare; the 5 GB whale's clone did not (OOM at 7.75 GB RSS on an
779/// 8 GB node), and its paged takeover moved 90 MiB.
780const DEFAULT_PAGED_MIN_MB: u64 = 256;
781
782/// The default background hydration rate of a paged cell, in MiB/s. A 2 GB
783/// whale fills in about two minutes; a fault of the foreground never waits
784/// on a hydration step, which fetches outside the hydration lock.
785const DEFAULT_HYDRATE_MBPS: u64 = 16;
786
787/// Pages one hydration step faults before it yields to the pacer: one run.
788const HYDRATE_STEP_PAGES: u32 = 256;
789
790/// The background fill of a paged cell: cancelled when the cell closes.
791struct CellHydration {
792 cancelled: AtomicBool,
793 complete: AtomicBool,
794}
795
796pub struct LtxRepl {
797 /// Local root: cell dbs live at `watch/<cell>/ltx/e<epoch>/db.sqlite`.
798 watch: PathBuf,
799 /// The object-metadata name for an LTX header timestamp. Azure refuses
800 /// a hyphen in a metadata name, so the fleet bucket's dialect picks it.
801 timestamp_metadata_key: TimestampMetadataKey,
802 bucket: String,
803 /// The bucket spec's key prefix: empty, or slash-terminated.
804 prefix: String,
805 endpoint: Option<String>,
806 region: String,
807 credentials: Option<StorageCredentials>,
808 /// One connection pool for the whole node, shared by every cell client.
809 store: Arc<dyn ObjectStore>,
810 ltx_host: LtxHost,
811 /// An explicit SQLite VFS for both managed connections. Production keeps
812 /// this unset.
813 vfs_name: Option<String>,
814 cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
815 stopped_cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
816 /// Serializes a release admission with the final shutdown snapshot. A
817 /// release that crosses shutdown must belong to either the retained close
818 /// group or the stopped-cell snapshot, never neither and never both.
819 replica_close_gate: Mutex<()>,
820 /// Keys whose owned blocking close failed before it proved that it took
821 /// the replica. A later release can admit one retry for the same handle.
822 failed_release_closes: Arc<Mutex<BTreeSet<(String, u64)>>>,
823 replica_close_stop: StopToken,
824 replica_close_tasks: TaskGroup,
825 /// The node's root task group, for the per-cell background hydration.
826 tasks: TaskGroup,
827 /// Woken when a cell's `committed` advances, so the background loop syncs
828 /// without polling; a slow tick backstops any missed notification.
829 dirty: Arc<Notify>,
830 /// Shared by every activation, so the restore bound is per node, not per
831 /// cell. The generic LTX restore keeps its sequential compatibility path.
832 restore_slots: Arc<Semaphore>,
833 compaction_queue: Option<mpsc::UnboundedSender<CompactionWork>>,
834 compaction_min_txids: u64,
835 compaction_min_bytes: u64,
836 /// Restore a taken-over cell by paging its pages in on demand (a fault-in
837 /// SQLite VFS) instead of downloading the whole chain, and continue its
838 /// chain from the cut. On unless `CELLD_LTX_PAGED=0`.
839 paged_restore: AtomicBool,
840 /// Whether every live lease in the fleet reads a paged epoch
841 /// (`celld_logic::format`). Off until the fleet sampler has seen every
842 /// lease at `BUCKET_FORMAT`, so a node in a rolling update clones a whale
843 /// the way the old release does instead of writing an epoch the old
844 /// release cannot restore. `CELLD_LTX_PAGED` is the operator's switch;
845 /// this one is the fleet's.
846 paged_fleet: AtomicBool,
847 /// The chain size, in bytes, from which a restore pages instead of
848 /// cloning (`CELLD_LTX_PAGED_MIN_MB`). Below it the clone is cheaper:
849 /// one download the node can afford, no fault path, no hydration.
850 paged_min_bytes: AtomicU64,
851 /// Bytes per second a paged cell hydrates in the background, 0 for none
852 /// (`CELLD_LTX_HYDRATE_MBPS`). A hydrated cell reads only its file.
853 hydrate_bytes_per_s: u64,
854 /// One paged cell hydrates at a time: a node with several whales pages
855 /// them all and fills them in turn.
856 hydrations: Arc<Semaphore>,
857 /// Preserved eviction snapshots, tracked in memory so the local-cache
858 /// prune answers without walking the data directory. See
859 /// [`crate::replication::PreservedCache`].
860 preserved: Mutex<crate::replication::PreservedCache>,
861 /// Woken when a gate ticket arrives, so the ship loop group-commits
862 /// without polling.
863 dirty_ship: Arc<Notify>,
864 /// Cells whose last epoch ended quietly with acked rows outside the
865 /// per-cell layout (`note_undrained_tail`'s predicate). The ending
866 /// itself cannot write — release serves fenced nodes — so the
867 /// SUCCESSOR folds: the next activation gathers the cell's stranded
868 /// tail per-cell before it restores (#473). In-memory only; a
869 /// process death hands the same duty to boot recovery, which drains
870 /// whole predecessor sessions.
871 dirty_tails: Mutex<BTreeSet<String>>,
872 registration: Arc<Mutex<RegistrationState>>,
873 stop: StopToken,
874 task_owner: Mutex<Option<LtxTaskOwner>>,
875 #[cfg(celld_internal_tests)]
876 activation_install_pause: Mutex<Option<Arc<LtxActivationInstallPause>>>,
877 #[cfg(celld_internal_tests)]
878 close_local_replicas_pause: Mutex<Option<Arc<LtxReplicaClosePause>>>,
879 #[cfg(celld_internal_tests)]
880 panic_next_release_close: AtomicBool,
881 /// The budget for one durability proof, in milliseconds. Fixed at
882 /// construction, so the hot write path pays no environment lookup.
883 durability_timeout_ms: u64,
884 /// Monotonic ms of the last proof any cell on this node landed. Every
885 /// cell handle shares it; see `Cell::node_proof_ms`.
886 node_proof_ms: Arc<AtomicU64>,
887 /// The largest handoff snapshot the durability deadline can carry. A
888 /// larger database hands off through its L0 chain without an attempt.
889 snapshot_budget_bytes: AtomicU64,
890 /// The highest txid this process has put in the bucket per cell epoch,
891 /// through a per-cell ship, a handoff snapshot, a recovered segment, or
892 /// an epoch marker, plus any bucket listing it had to do. Bundle GC and
893 /// the recovery gather ask for this watermark once per cell per pass;
894 /// answering from the bucket cost ten LISTs per cell, so a pass of a
895 /// 2 s budget judged about one bundle against roughly one new bundle a
896 /// second, and the retained backlog grew for the life of the process.
897 /// On 2026-09-03 a dead session's recovery read 209 of them.
898 covered_by_cell: Mutex<BTreeMap<(String, u64), u64>>,
899 /// The cell's TRUNCATE checkpoint threshold. Passive checkpoints never
900 /// shrink the WAL FILE, so after every periodic restart the capture's
901 /// tail read spans the stale high-water region — ~350 KB per sync on
902 /// the fleet ledger at the upstream threshold. `DEFAULT_TRUNCATE_PAGES`
903 /// unless `CELLD_LTX_TRUNCATE_PAGES` overrides it; 0 disables
904 /// truncation (the upstream behavior). Queue cells always disable it
905 /// because each truncate boundary emits a full image of their unbounded
906 /// backlog.
907 truncate_pages: Option<u32>,
908}
909
910impl LtxRepl {
911 /// Cfg-gated constructor over an injected store.
912 #[cfg(celld_internal_tests)]
913 pub fn start_with_store_for_test(watch: &Path, store: Arc<dyn ObjectStore>) -> Self {
914 Self::start_with_store(watch, store, None, 0)
915 }
916
917 /// Build the production loop topology over an injected object store.
918 #[cfg(celld_internal_tests)]
919 pub fn start_with_store(
920 watch: &Path,
921 store: Arc<dyn ObjectStore>,
922 compaction: Option<CompactionConfig>,
923 flush_ms: u64,
924 ) -> Self {
925 Self::start_with_store_and_optional_vfs(watch, store, compaction, flush_ms, None)
926 }
927
928 /// Build the same loop topology and route managed SQLite through `vfs`.
929 #[cfg(celld_internal_tests)]
930 pub fn start_with_store_on_vfs(
931 watch: &Path,
932 store: Arc<dyn ObjectStore>,
933 compaction: Option<CompactionConfig>,
934 flush_ms: u64,
935 vfs: &str,
936 ) -> Self {
937 Self::start_with_store_and_optional_vfs(
938 watch,
939 store,
940 compaction,
941 flush_ms,
942 Some(vfs.to_string()),
943 )
944 }
945
946 #[cfg(celld_internal_tests)]
947 fn start_with_store_and_optional_vfs(
948 watch: &Path,
949 store: Arc<dyn ObjectStore>,
950 compaction: Option<CompactionConfig>,
951 flush_ms: u64,
952 vfs_name: Option<String>,
953 ) -> Self {
954 Self::assemble(
955 watch,
956 store,
957 TimestampMetadataKey::default(),
958 "test".into(),
959 String::new(),
960 None,
961 "auto".into(),
962 None,
963 compaction,
964 flush_ms,
965 deterministic_ltx_host(),
966 vfs_name,
967 DEFAULT_DURABILITY_TIMEOUT_SECS * 1_000,
968 )
969 }
970
971 /// Cfg-gated constructor with additive L1 compaction enabled.
972 #[cfg(celld_internal_tests)]
973 pub fn start_with_compaction_for_test(
974 watch: &Path,
975 store: Arc<dyn ObjectStore>,
976 min_txids: u64,
977 concurrency: usize,
978 ) -> Self {
979 Self::assemble(
980 watch,
981 store,
982 TimestampMetadataKey::default(),
983 "test".into(),
984 String::new(),
985 None,
986 "auto".into(),
987 None,
988 Some(CompactionConfig {
989 min_txids,
990 min_bytes: COMPACTION_MAX_INPUT_BYTES / 2,
991 concurrency,
992 }),
993 0,
994 deterministic_ltx_host(),
995 None,
996 DEFAULT_DURABILITY_TIMEOUT_SECS * 1_000,
997 )
998 }
999
1000 pub(crate) fn start(
1001 watch: &Path,
1002 backend: crate::bucket::StorageBackend,
1003 bucket: String,
1004 prefix: String,
1005 endpoint: Option<String>,
1006 region: String,
1007 credentials: Option<StorageCredentials>,
1008 ) -> anyhow::Result<Self> {
1009 let compaction = compaction_config_from_env()?;
1010 // Everything downstream of the store is backend-agnostic already,
1011 // so the dialect decides construction and the metadata name, and
1012 // nothing else.
1013 let store = match backend {
1014 crate::bucket::StorageBackend::Gcs => crate::bucket::gcs_replica_store(&bucket)?,
1015 crate::bucket::StorageBackend::Azure => crate::bucket::azure_replica_store(&bucket)?,
1016 crate::bucket::StorageBackend::S3 => {
1017 node_config(&bucket, endpoint.as_deref(), &region, credentials.as_ref())
1018 .build_store()
1019 .map_err(|error| anyhow!("build shared object store: {error}"))?
1020 }
1021 crate::bucket::StorageBackend::Local => {
1022 Arc::new(crate::local_store::LocalStore::open(&bucket)?)
1023 }
1024 };
1025 // Azure blob metadata names must be C# identifiers, so the standard
1026 // Litestream key cannot carry its hyphen there. External Litestream
1027 // tooling reads that key, therefore an az:// replica gives up
1028 // Litestream-tool timestamp restore. celld never reads it back.
1029 let timestamp_metadata_key = match backend {
1030 crate::bucket::StorageBackend::Azure => TimestampMetadataKey::Underscore,
1031 crate::bucket::StorageBackend::S3
1032 | crate::bucket::StorageBackend::Gcs
1033 | crate::bucket::StorageBackend::Local => TimestampMetadataKey::Litestream,
1034 };
1035 // The tiering flush interval: with a healthy shipper, at most one
1036 // upload per cell per interval; it is simultaneously the bucket lag
1037 // budget. 0 disables pacing.
1038 let flush_ms = crate::env_vars::with_default("CELLD_LOG_FLUSH_MS", 2000)? as u64;
1039 // Saturating: an absurd seconds value must clamp, not wrap through
1040 // `as_millis() as u64` into a short deadline.
1041 let durability_timeout_ms = crate::env_vars::positive_or(
1042 "CELLD_LTX_DURABILITY_TIMEOUT_SECS",
1043 DEFAULT_DURABILITY_TIMEOUT_SECS,
1044 )?
1045 .saturating_mul(1_000);
1046 Ok(Self::assemble(
1047 watch,
1048 store,
1049 timestamp_metadata_key,
1050 bucket,
1051 prefix,
1052 endpoint,
1053 region,
1054 credentials,
1055 compaction,
1056 flush_ms,
1057 production_ltx_host(),
1058 None,
1059 durability_timeout_ms,
1060 ))
1061 }
1062
1063 /// The one constructor body for every field and every background loop.
1064 #[allow(clippy::too_many_arguments)]
1065 fn assemble(
1066 watch: &Path,
1067 store: Arc<dyn ObjectStore>,
1068 timestamp_metadata_key: TimestampMetadataKey,
1069 bucket: String,
1070 prefix: String,
1071 endpoint: Option<String>,
1072 region: String,
1073 credentials: Option<StorageCredentials>,
1074 compaction: Option<CompactionConfig>,
1075 flush_ms: u64,
1076 ltx_host: LtxHost,
1077 vfs_name: Option<String>,
1078 durability_timeout_ms: u64,
1079 ) -> Self {
1080 let cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>> = Arc::default();
1081 let dirty = Arc::new(Notify::new());
1082 let dirty_ship = Arc::new(Notify::new());
1083 let registration: Arc<Mutex<RegistrationState>> = Arc::default();
1084 let stop = StopToken::new();
1085 let tasks = TaskGroup::new(stop.clone());
1086 let replica_close_stop = StopToken::new();
1087 let replica_close_tasks = TaskGroup::new(replica_close_stop.clone());
1088 let preserved = Mutex::new(crate::replication::PreservedCache::new(
1089 ltx_host.filesystem(),
1090 ));
1091 // Retain every root until the unique durability owner claims them.
1092 // Dropping a task handle detaches the task, so a cloneable replicator
1093 // cannot be the final lifecycle capability.
1094 tasks.spawn_owned(
1095 "ltx_sync",
1096 sync_loop(
1097 cells.clone(),
1098 dirty.clone(),
1099 Arc::new(Semaphore::new(sync_concurrency())),
1100 registration.clone(),
1101 stop.clone(),
1102 tasks.clone(),
1103 flush_ms,
1104 ),
1105 );
1106 tasks.spawn_owned(
1107 "ltx_ship",
1108 ship_loop(
1109 cells.clone(),
1110 dirty_ship.clone(),
1111 registration.clone(),
1112 stop.clone(),
1113 crate::queue_batching::timing().log_ms,
1114 ),
1115 );
1116 tasks.spawn_owned(
1117 "ltx_bundle",
1118 bundle_loop(cells.clone(), registration.clone(), stop.clone(), flush_ms),
1119 );
1120 let compaction_queue =
1121 compaction.map(|config| start_compaction_loop(config, tasks.clone()));
1122 Self {
1123 watch: watch.to_path_buf(),
1124 timestamp_metadata_key,
1125 bucket,
1126 prefix,
1127 endpoint,
1128 region,
1129 credentials,
1130 store,
1131 ltx_host,
1132 vfs_name,
1133 cells,
1134 stopped_cells: Arc::new(Mutex::new(BTreeMap::new())),
1135 replica_close_gate: Mutex::new(()),
1136 failed_release_closes: Arc::new(Mutex::new(BTreeSet::new())),
1137 replica_close_stop,
1138 replica_close_tasks: replica_close_tasks.clone(),
1139 tasks: tasks.clone(),
1140 dirty,
1141 restore_slots: Arc::new(Semaphore::new(RESTORE_DOWNLOAD_CONCURRENCY)),
1142 compaction_queue,
1143 compaction_min_txids: compaction.map_or(0, |config| config.min_txids),
1144 compaction_min_bytes: compaction.map_or(u64::MAX, |config| config.min_bytes),
1145 paged_restore: AtomicBool::new(
1146 crate::env_vars::flag("CELLD_LTX_PAGED", true).unwrap_or(true),
1147 ),
1148 paged_fleet: AtomicBool::new(false),
1149 paged_min_bytes: AtomicU64::new(
1150 crate::env_vars::optional::<u64>("CELLD_LTX_PAGED_MIN_MB")
1151 .unwrap_or(None)
1152 .unwrap_or(DEFAULT_PAGED_MIN_MB)
1153 .saturating_mul(1 << 20),
1154 ),
1155 hydrate_bytes_per_s: crate::env_vars::optional::<u64>("CELLD_LTX_HYDRATE_MBPS")
1156 .unwrap_or(None)
1157 .unwrap_or(DEFAULT_HYDRATE_MBPS)
1158 .saturating_mul(1 << 20),
1159 hydrations: Arc::new(Semaphore::new(1)),
1160 preserved,
1161 dirty_ship,
1162 dirty_tails: Mutex::new(BTreeSet::new()),
1163 registration,
1164 stop: stop.clone(),
1165 task_owner: Mutex::new(Some(LtxTaskOwner {
1166 tasks,
1167 replica_close_tasks,
1168 })),
1169 #[cfg(celld_internal_tests)]
1170 activation_install_pause: Mutex::new(None),
1171 #[cfg(celld_internal_tests)]
1172 close_local_replicas_pause: Mutex::new(None),
1173 #[cfg(celld_internal_tests)]
1174 panic_next_release_close: AtomicBool::new(false),
1175 durability_timeout_ms,
1176 node_proof_ms: Arc::new(AtomicU64::new(0)),
1177 snapshot_budget_bytes: AtomicU64::new(
1178 durability_timeout_ms.saturating_mul(SNAPSHOT_BYTES_PER_MS),
1179 ),
1180 covered_by_cell: Mutex::new(BTreeMap::new()),
1181 truncate_pages: Some(
1182 crate::env_vars::optional::<u32>("CELLD_LTX_TRUNCATE_PAGES")
1183 .ok()
1184 .flatten()
1185 .unwrap_or(DEFAULT_TRUNCATE_PAGES),
1186 ),
1187 }
1188 }
1189
1190 pub(crate) fn take_task_owner(&self) -> LtxTaskOwner {
1191 self.task_owner
1192 .lock()
1193 .unwrap()
1194 .take()
1195 .expect("the LTX task owner was already claimed")
1196 }
1197
1198 pub(crate) fn shutdown_local_fallback(&self) {
1199 self.stop.request_stop();
1200 self.registration.lock().unwrap().current = None;
1201 let _close_gate = self.replica_close_gate.lock().unwrap();
1202 self.replica_close_stop.request_stop();
1203 // A capture holds the replica mutex across filesystem work. Closing a
1204 // replica here would turn the process-deadline fallback into another
1205 // unbounded wait. Detach every handle without touching its replica, so
1206 // awaited shutdown can close it after all admitted workers have joined.
1207 // The close gate makes this snapshot atomic with release admission.
1208 let cells = std::mem::take(&mut *self.cells.lock().unwrap());
1209 self.stopped_cells.lock().unwrap().extend(cells);
1210 }
1211
1212 pub(crate) fn start_close_local_replicas(&self) -> Option<asyncrt::TaskHandle<()>> {
1213 let _close_gate = self.replica_close_gate.lock().unwrap();
1214 let mut cells = std::mem::take(&mut *self.cells.lock().unwrap());
1215 cells.append(&mut *self.stopped_cells.lock().unwrap());
1216 let mut failed_release_closes = self.failed_release_closes.lock().unwrap();
1217 for key in cells.keys() {
1218 failed_release_closes.remove(key);
1219 }
1220 drop(failed_release_closes);
1221 if cells.is_empty() {
1222 return None;
1223 }
1224 #[cfg(celld_internal_tests)]
1225 let pause = self.take_replica_close_pause_for_world();
1226 Some(asyncrt::blocking(move || {
1227 #[cfg(celld_internal_tests)]
1228 pause_replica_close_for_world(pause);
1229 for ((cell, epoch), handle) in cells {
1230 close_replica_or_warn(&handle, &cell, epoch);
1231 }
1232 }))
1233 }
1234
1235 /// Install the manager's shipping and bundle operations as one unit.
1236 ///
1237 /// The shipper gates fleet proofs on its open bucket log record.
1238 /// Registration can precede that opening. The registration stores
1239 /// weak references because the manager already owns this replicator.
1240 pub(crate) fn register_durability(
1241 &self,
1242 manager: Arc<crate::node_log::NodeLogManager>,
1243 ) -> Option<DurabilityRegistration> {
1244 self.register_targets(RegisteredTargets {
1245 shipper: manager.clone(),
1246 manager,
1247 })
1248 }
1249
1250 #[cfg(all(test, celld_internal_tests))]
1251 pub(crate) fn register_durability_for_world(
1252 &self,
1253 manager: Arc<crate::node_log::NodeLogManager>,
1254 shipper: Arc<dyn Shipper>,
1255 ) -> Option<DurabilityRegistration> {
1256 self.register_targets(RegisteredTargets { shipper, manager })
1257 }
1258
1259 fn register_targets(&self, targets: RegisteredTargets) -> Option<DurabilityRegistration> {
1260 let targets = Arc::new(targets);
1261 let mut state = self.registration.lock().unwrap();
1262 // Shutdown publishes stop before it clears this slot under the same
1263 // mutex. A registration that linearizes first is cleared by shutdown;
1264 // one that linearizes later observes stop and cannot resurrect it.
1265 if self.stop.is_stopped() {
1266 return None;
1267 }
1268 state.next_generation = state
1269 .next_generation
1270 .checked_add(1)
1271 .expect("durability registration generation exhausted");
1272 let generation = state.next_generation;
1273 state.current = Some(RegisteredDurability {
1274 generation,
1275 targets: Arc::downgrade(&targets),
1276 });
1277 drop(state);
1278 self.dirty_ship.notify_one();
1279 self.dirty.notify_one();
1280 Some(DurabilityRegistration {
1281 registration: Arc::downgrade(&self.registration),
1282 generation,
1283 _targets: targets,
1284 })
1285 }
1286
1287 /// The ensemble-change barrier: every frame ever handed to a shipper is
1288 /// durable in the bucket. Old followers' fragments are abandonable
1289 /// garbage exactly when this holds.
1290 pub fn all_shipped_tiered(&self) -> bool {
1291 Self::all_cells_shipped_tiered(&self.cells.lock().unwrap())
1292 }
1293
1294 fn all_cells_shipped_tiered(cells: &BTreeMap<(String, u64), CellHandle>) -> bool {
1295 cells.values().all(|cell| {
1296 cell.durable_txid.load(Ordering::SeqCst) >= cell.shipped_txid.load(Ordering::SeqCst)
1297 })
1298 }
1299
1300 /// The final process-seal barrier. A cell that leaves the active map can
1301 /// still have fleet-acked rows outside the per-cell layout. Ending a cell
1302 /// installs that fact in `dirty_tails` before it removes the active handle,
1303 /// and this method reads the same two stores in that order. Therefore, the
1304 /// final check observes either the undrained active handle or its marker.
1305 pub(crate) fn all_tails_ready_for_graceful_seal(&self) -> bool {
1306 let cells = self.cells.lock().unwrap();
1307 Self::all_cells_shipped_tiered(&cells) && self.dirty_tails.lock().unwrap().is_empty()
1308 }
1309
1310 /// Recovery's primitive: PUT one gathered L0 segment to the exact key
1311 /// the dead leader's own upload would have used. Idempotent by key.
1312 /// The highest TXID the cell's per-cell prefix already covers, over
1313 /// every level. Recovery uses it to skip re-uploading rows the drain
1314 /// points (compaction, eviction sync) have already folded in — one
1315 /// LIST per level and cell instead of one PUT per historical row.
1316 pub async fn covered_txid(&self, cell: &str, epoch: u64) -> u64 {
1317 let key = (cell.to_string(), epoch);
1318 let resident = self
1319 .cells
1320 .lock()
1321 .unwrap()
1322 .get(&key)
1323 .map(|handle| percell_coverage(handle));
1324 let known = self.covered_by_cell.lock().unwrap().get(&key).copied();
1325 if let Some(covered) = resident.max(known).filter(|covered| *covered > 0) {
1326 return covered;
1327 }
1328 // Nothing this process put there: a cell it never served, or one it
1329 // has not shipped yet. Ask the bucket once, with one listing of the
1330 // epoch's whole prefix rather than one per level, and remember the
1331 // answer; the watermark only rises, so a remembered value never
1332 // over-reports. A restarting node recovers thousands of cells it
1333 // never served, so this listing is its whole recovery cost.
1334 let covered = self
1335 .client_for(cell, epoch)
1336 .max_txid_all_levels()
1337 .await
1338 .map(|txid| txid.0)
1339 .unwrap_or(0);
1340 self.note_covered(cell, epoch, covered);
1341 covered
1342 }
1343
1344 /// Remember that the bucket holds this cell epoch through `txid`.
1345 fn note_covered(&self, cell: &str, epoch: u64, txid: u64) {
1346 let mut covered = self.covered_by_cell.lock().unwrap();
1347 let entry = covered.entry((cell.to_string(), epoch)).or_insert(0);
1348 *entry = (*entry).max(txid);
1349 }
1350
1351 /// Highest contiguous TXID prefix proved by the live per-cell L0/L1 objects.
1352 ///
1353 /// Unlike `covered_txid`, this is an activation safety proof. A maximum
1354 /// past a hole cannot seed a replica because doing so would preserve the
1355 /// hole forever. Store errors also fail the proof instead of becoming zero.
1356 /// A zero would claim that the local directory can replay the complete
1357 /// epoch even though the store did not provide the required durable bound.
1358 async fn contiguous_covered_txid(&self, cell: &str, epoch: u64) -> anyhow::Result<u64> {
1359 let client = self.client_for(cell, epoch);
1360 let mut files = Vec::new();
1361 for level in 0..=1 {
1362 files.extend(
1363 client
1364 .ltx_files(level, TXID(0))
1365 .await
1366 .map_err(|error| anyhow!("list {cell} e{epoch} L{level}: {error}"))?,
1367 );
1368 }
1369 files.sort_unstable_by_key(|file| (file.min_txid.0, file.max_txid.0));
1370
1371 let mut covered = 0_u64;
1372 for file in files {
1373 if file.min_txid.0 > covered.saturating_add(1) {
1374 break;
1375 }
1376 covered = covered.max(file.max_txid.0);
1377 }
1378 Ok(covered)
1379 }
1380
1381 pub async fn upload_raw_l0(
1382 &self,
1383 cell: &str,
1384 epoch: u64,
1385 min_txid: u64,
1386 max_txid: u64,
1387 bytes: &[u8],
1388 ) -> anyhow::Result<()> {
1389 self.client_for(cell, epoch)
1390 .write_ltx_file(0, TXID(min_txid), TXID(max_txid), bytes)
1391 .await
1392 .map_err(|error| {
1393 anyhow!("upload recovered l0 {cell} e{epoch} t{min_txid}-{max_txid}: {error}")
1394 })?;
1395 self.note_covered(cell, epoch, max_txid);
1396 Ok(())
1397 }
1398
1399 /// Merge contiguous single-transaction LTX segments into one segment
1400 /// covering the whole range. Recovery uses it to upload each cell's
1401 /// gathered tail as ONE object instead of one per row: the lab's chaos
1402 /// soak measured per-kill outages growing 133 s -> 353 s because every
1403 /// crash added hundreds of single-row L0 objects for the object
1404 /// store's same-key throttling to fight and the next restore plan to
1405 /// read. Returns None when the rows are not a contiguous ascending
1406 /// chain — the caller falls back to per-row uploads, never guessing.
1407 pub fn merge_l0_rows(rows: &[(u64, Vec<u8>)]) -> Option<Vec<u8>> {
1408 if rows.len() < 2 {
1409 return None;
1410 }
1411 if rows.windows(2).any(|pair| pair[1].0 != pair[0].0 + 1) {
1412 return None;
1413 }
1414 let readers: Vec<std::io::Cursor<&[u8]>> = rows
1415 .iter()
1416 .map(|(_, bytes)| std::io::Cursor::new(bytes.as_slice()))
1417 .collect();
1418 let mut compactor = celld_ltx::compactor::Compactor::new(Vec::new(), readers);
1419 // The gathered frames are no-checksum WAL-segment files, so the
1420 // merged header must be too — a checksummed output header fails
1421 // encode validation against checksum-less inputs (the same flag
1422 // ReplicaCompactor sets for the L0->L1 fold).
1423 compactor.header_flags = celld_ltx::ltx::HEADER_FLAG_NO_CHECKSUM;
1424 match compactor.compact() {
1425 Ok(()) => Some(compactor.into_writer()),
1426 Err(error) => {
1427 // The fallback is safe (per-row uploads) but must never be
1428 // silent again: a swallowed error here hid a dead merge
1429 // through a full fleet round.
1430 warn!(%error, rows = rows.len(), "recovery tail merge failed; per-row fallback");
1431 None
1432 }
1433 }
1434 }
1435
1436 fn db_path(&self, cell: &str, epoch: u64) -> PathBuf {
1437 self.watch
1438 .join(cell)
1439 .join("ltx")
1440 .join(format!("e{epoch}"))
1441 .join("db.sqlite")
1442 }
1443
1444 fn truncate_pages_for_cell(&self, cell: &str) -> Option<u32> {
1445 let queue = cell
1446 .split_once(':')
1447 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS);
1448 if queue {
1449 // A Queue database grows with its backlog. A fixed WAL threshold
1450 // therefore turns every TRUNCATE boundary into an allocation and
1451 // LTX object proportional to every undelivered message (#472).
1452 // PASSIVE checkpoints still backfill the database, and the sparse
1453 // capture path reads the live tail without retaining the stale WAL
1454 // region, so Queue cells do not need that small-cell tradeoff.
1455 Some(0)
1456 } else {
1457 self.truncate_pages
1458 }
1459 }
1460
1461 /// A per-cell client over the shared store, keyed to the cell's epoch
1462 /// prefix. `cells/<cell>/ltx/e<epoch>` matches [`Self::db_path`]'s remote
1463 /// twin so the same coordinates address local and replica state.
1464 fn client_for(&self, cell: &str, epoch: u64) -> ObjectStoreClient {
1465 let mut config = node_config(
1466 &self.bucket,
1467 self.endpoint.as_deref(),
1468 &self.region,
1469 self.credentials.as_ref(),
1470 );
1471 config.path = format!("{}cells/{cell}/ltx/e{epoch}", self.prefix);
1472 config.timestamp_metadata_key = self.timestamp_metadata_key;
1473 ObjectStoreClient::with_store(config, self.store.clone())
1474 }
1475
1476 /// Highest epoch under `cells/<cell>/ltx/` that holds any LTX — the newest
1477 /// durable copy to restore on takeover.
1478 /// Every epoch under `cells/<cell>/ltx/` that holds any LTX, ascending. A
1479 /// restore composes them into one chain: a paged epoch continues the
1480 /// chain it paged in instead of opening with a snapshot, so the objects a
1481 /// restore needs can span epochs.
1482 async fn nonempty_epochs(&self, cell: &str) -> anyhow::Result<Vec<u64>> {
1483 use celld_ltx::object_store::path::Path as ObjPath;
1484 let base = ObjPath::from(format!("{}cells/{cell}/ltx", self.prefix));
1485 let listing = self.store.list_with_delimiter(Some(&base)).await?;
1486 let mut epochs: Vec<u64> = listing
1487 .common_prefixes
1488 .iter()
1489 .filter_map(|prefix| {
1490 prefix
1491 .filename()
1492 .and_then(|name| name.strip_prefix('e'))
1493 .and_then(|value| value.parse::<u64>().ok())
1494 })
1495 .collect();
1496 epochs.sort_unstable();
1497 Ok(epochs)
1498 }
1499
1500 /// The restore view over a cell's epochs below `epoch`: the chain from the
1501 /// newest non-empty epoch down to the one that opens with a snapshot.
1502 async fn epoch_chain(
1503 &self,
1504 cell: &str,
1505 epoch: u64,
1506 ) -> anyhow::Result<Option<EpochChain<ObjectStoreClient>>> {
1507 let epochs = self.nonempty_epochs(cell).await?;
1508 let Some(&newest) = epochs.last() else {
1509 return Ok(None);
1510 };
1511 anyhow::ensure!(
1512 newest < epoch,
1513 "refusing to restore {cell} from used epoch {newest} into writer epoch {epoch}"
1514 );
1515 let clients = epochs
1516 .into_iter()
1517 .map(|e| (e, self.client_for(cell, e)))
1518 .collect();
1519 Ok(Some(EpochChain::build(clients).await?))
1520 }
1521
1522 /// Does the bucket hold any LTX for this cell at this epoch? The fail-closed
1523 /// eviction gate: never delete the last local copy of state the bucket
1524 /// cannot restore.
1525 pub async fn epoch_replicated(&self, cell: &str, epoch: u64) -> bool {
1526 let client = self.client_for(cell, epoch);
1527 matches!(client.has_any_object().await, Ok(true))
1528 }
1529
1530 pub async fn activate(
1531 &self,
1532 options: ActivationOptions<'_>,
1533 ) -> anyhow::Result<ActivationResult> {
1534 anyhow::ensure!(
1535 !self.stop.is_stopped(),
1536 "LTX replication stopped before activation started"
1537 );
1538 let ActivationOptions {
1539 cell,
1540 epoch,
1541 fresh,
1542 took_over,
1543 resume_local,
1544 // Consumed by the interlock before the fold; the field stays
1545 // on the options because the core's claim still names it.
1546 prior: _,
1547 } = options;
1548 {
1549 let _close_gate = self.replica_close_gate.lock().unwrap();
1550 anyhow::ensure!(
1551 !self
1552 .stopped_cells
1553 .lock()
1554 .unwrap()
1555 .contains_key(&(cell.to_string(), epoch)),
1556 "managed replica close is incomplete for {cell} epoch {epoch}"
1557 );
1558 }
1559 let dst = self.db_path(cell, epoch);
1560 self.ltx_host.create_dir_all(dst.parent().unwrap())?;
1561
1562 // The takeover interlock moved OUT of this path (lease-fold): the
1563 // decision core gates foreign takeovers on the folded lease state
1564 // it already reads (Effect::RecoverNodeLog), and the boot order
1565 // recovers this node's own predecessor before the lease installs,
1566 // so by the time any activation reaches here the bucket is
1567 // provably complete for both the takeover and the named-me path.
1568
1569 // Reuse a preserved local eviction snapshot only as the previous
1570 // epoch's baseline. Eviction removes the LTX metadata, so reopening
1571 // that SQLite image starts a new writer generation at TXID 1. Pairing
1572 // it with the same remote epoch would mix that new lineage with the
1573 // old tail (#158). A clean process reload is the separate
1574 // `resume_local` path: it retains both the live database and its LTX
1575 // metadata, so it can safely continue the existing epoch.
1576 // `.evicted` is the current name; `.hibernated` is what releases
1577 // before 2026-08-05 wrote. Accept both, so an upgrade reuses the
1578 // snapshots already on disk instead of restoring every cell from the
1579 // bucket. Writes always use the new name, so the old one dies out.
1580 let legacy = |path: &PathBuf| path.with_extension("hibernated");
1581 let previous = celld_logic::restore::previous_epoch_reusable(epoch, took_over)
1582 .then(|| self.db_path(cell, epoch - 1).with_extension("evicted"));
1583 let is_file = |path: &PathBuf| {
1584 self.ltx_host
1585 .metadata(path)
1586 .is_ok_and(|metadata| metadata.is_file)
1587 };
1588 let first_present = |path: PathBuf| {
1589 if is_file(&path) {
1590 Some(path)
1591 } else {
1592 Some(legacy(&path)).filter(is_file)
1593 }
1594 };
1595 let local_snapshot = (!fresh && !resume_local)
1596 .then(|| previous.and_then(first_present))
1597 .flatten();
1598
1599 // Sample before a restore can replace the path. A non-certified live
1600 // database can contain rows which a crash or self-fence staged but did
1601 // not upload, so its local position needs a remote bound.
1602 let dst_existed = is_file(&dst);
1603 let mut restored = resume_local;
1604 let mut remote_restore = None;
1605 let mut paged_vfs_name: Option<String> = None;
1606 let mut registration = PagedRegistration(None);
1607 // A paged activation continues its chain from the cut: (last txid of
1608 // the chain, page count at the cut).
1609 let mut continuation: Option<(TXID, u32)> = None;
1610 if resume_local {
1611 anyhow::ensure!(
1612 is_file(&dst),
1613 "clean reload database is missing: {}",
1614 dst.display()
1615 );
1616 info!(cell, epoch, "resumed clean local replica");
1617 } else if let Some(snapshot) = local_snapshot {
1618 self.ltx_host.rename(&snapshot, &dst)?;
1619 self.preserved
1620 .lock()
1621 .expect("preserved cache poisoned")
1622 .forget(&snapshot);
1623 info!(cell, epoch, "reused local eviction snapshot");
1624 restored = true;
1625 } else if !fresh {
1626 // Restore the newest durable epoch's full contiguous chain. The
1627 // epoch seal that once capped this read is deleted: the
1628 // cut it fixed defended only never-acked resurrection — not a
1629 // promise anyone holds — and under the log tier late arrival of
1630 // ACKED rows into a per-cell prefix is normal (recovery gathers,
1631 // the drain folds, the healing pass repairs), so a permanent cap
1632 // turned ordering slips into permanent loss. Without it the
1633 // healed rows are simply picked up here.
1634 //
1635 // A predecessor epoch that ended quietly left fleet-acked rows
1636 // in node bundles, and this restore reads per-cell prefixes
1637 // only. Fold that tail first — this activation holds the new
1638 // epoch's authority, so the write the fenced ending could not
1639 // make is lawful here, and the fold must precede the source
1640 // lookup because the tail can name an epoch the per-cell
1641 // listing has never seen. Failing the activation on a failed
1642 // fold is deliberate: restoring past it would serve a
1643 // truncated database as read-write (#473).
1644 if self.dirty_tails.lock().unwrap().contains(cell) {
1645 let sink = registered_durability(&self.registration)
1646 .map(|targets| targets.manager.clone())
1647 .ok_or_else(|| {
1648 anyhow!("{cell} has an un-drained bundle tail and no bundle sink")
1649 })?;
1650 sink.fold_cell(cell)
1651 .await
1652 .map_err(|error| anyhow!("fold bundle tail for {cell}: {error}"))?;
1653 self.dirty_tails.lock().unwrap().remove(cell);
1654 }
1655 let remote_started_mono_ms = asyncrt::mono_ms();
1656 let source_lookup_started_mono_ms = asyncrt::mono_ms();
1657 let chain = self.epoch_chain(cell, epoch).await?;
1658 let source_lookup_us = asyncrt::mono_ms()
1659 .saturating_sub(source_lookup_started_mono_ms)
1660 .saturating_mul(1_000);
1661 if let Some(chain) = chain {
1662 let spans = chain.spans();
1663 let from = spans.last().map_or(0, |(e, _)| *e);
1664 let _ = self.ltx_host.remove_file(&dst);
1665 // Page the cell in on demand instead of downloading its
1666 // chain when the chain is large enough to be worth it: build
1667 // the page map from the plan, then open the db through a
1668 // fault-in VFS over an empty local file. The first request
1669 // reads only the pages it touches. The epoch then continues
1670 // the chain it paged in (`seed_continuation`) rather than
1671 // opening with a whole-database snapshot. A smaller chain is
1672 // cloned: the plan is over the chain's cached listings, so
1673 // deciding costs no request.
1674 let mut paged_plan = None;
1675 if self.paged_restore.load(Ordering::Relaxed)
1676 && self.paged_fleet.load(Ordering::Relaxed)
1677 {
1678 let plan_started = asyncrt::mono_ms();
1679 let plan = replica::calc_restore_plan(&chain, TXID(0))
1680 .await
1681 .map_err(|error| anyhow!("paged plan {cell} e{from}: {error}"))?;
1682 let plan_us = asyncrt::mono_ms()
1683 .saturating_sub(plan_started)
1684 .saturating_mul(1_000);
1685 let bytes: u64 = plan.iter().map(|info| info.size.max(0) as u64).sum();
1686 let min = self.paged_min_bytes.load(Ordering::Relaxed);
1687 if bytes >= min {
1688 paged_plan = Some((plan, plan_us));
1689 } else {
1690 info!(
1691 cell,
1692 from,
1693 to = epoch,
1694 bytes,
1695 min,
1696 "cloned below the paged threshold"
1697 );
1698 }
1699 }
1700 if let Some((plan, plan_us)) = paged_plan {
1701 let map_started = asyncrt::mono_ms();
1702 let map = celld_ltx::paged::build_page_map(&chain, &plan)
1703 .await
1704 .map_err(|error| anyhow!("paged map {cell} e{from}: {error}"))?;
1705 let map_us = asyncrt::mono_ms()
1706 .saturating_sub(map_started)
1707 .saturating_mul(1_000);
1708 let mut readers: Vec<(TXID, Box<dyn celld_ltx::paged::RangeReader>)> =
1709 Vec::with_capacity(spans.len());
1710 for (span_epoch, lo) in &spans {
1711 let reader = self
1712 .client_for(cell, *span_epoch)
1713 .blocking_range_reader()
1714 .await
1715 .map_err(|error| {
1716 anyhow!("paged reader {cell} e{span_epoch}: {error}")
1717 })?;
1718 readers.push((*lo, reader));
1719 }
1720 // The epoch continues at the txid after the cut. Its
1721 // marker, a zero-page object at that txid, is uploaded
1722 // before the cell serves: an empty epoch could not pass
1723 // the eviction barrier, and a fenced owner's late
1724 // snapshot in a lower epoch would outrank its chain
1725 // (CelldPersistencePaged.tla, `BreakNoMarker`).
1726 continuation = Some((TXID(chain.max_txid().0 + 1), map.commit));
1727 let reader = celld_ltx::paged::EpochChainReader::new(readers);
1728 let source = celld_ltx::paged::PageSource::new(map, Box::new(reader));
1729 let name = celld_ltx::paged_vfs::next_registration_name();
1730 celld_ltx::paged_vfs::register_paged_vfs(
1731 &name,
1732 self.vfs_name.as_deref(),
1733 &dst,
1734 std::sync::Arc::new(source),
1735 )
1736 .map_err(|error| anyhow!("register paged vfs {cell}: {error}"))?;
1737 registration = PagedRegistration(Some(name.clone()));
1738 remote_restore = Some(RemoteRestoreTiming {
1739 started_mono_ms: remote_started_mono_ms,
1740 from,
1741 source_lookup_us,
1742 plan_us,
1743 map_us,
1744 download_us: 0,
1745 apply_us: 0,
1746 objects: plan.len(),
1747 bytes: plan.iter().map(|info| info.size.max(0) as u64).sum(),
1748 levels: by_level(&plan),
1749 paged: true,
1750 });
1751 info!(
1752 cell,
1753 from,
1754 to = epoch,
1755 chain = ?spans.iter().map(|(e, _)| *e).collect::<Vec<_>>(),
1756 cut = chain.max_txid().0,
1757 vfs = %name,
1758 "paged remote replica"
1759 );
1760 paged_vfs_name = Some(name);
1761 restored = true;
1762 } else {
1763 let stats = replica::restore_timed_with_host_and_download_slots(
1764 &chain,
1765 &dst,
1766 TXID(0),
1767 self.ltx_host.clone(),
1768 self.restore_slots.clone(),
1769 )
1770 .await
1771 .map_err(|error| anyhow!("restore {cell} e{from}: {error}"))?;
1772 let levels = stats
1773 .plan
1774 .by_level
1775 .iter()
1776 .map(|(level, count)| format!("L{level}:{count}"))
1777 .collect::<Vec<_>>()
1778 .join(" ");
1779 remote_restore = Some(RemoteRestoreTiming {
1780 started_mono_ms: remote_started_mono_ms,
1781 from,
1782 source_lookup_us,
1783 plan_us: stats.plan_us,
1784 map_us: 0,
1785 download_us: stats.download_us,
1786 apply_us: stats.apply_us,
1787 objects: stats.plan.objects,
1788 bytes: stats.plan.bytes,
1789 paged: false,
1790 levels,
1791 });
1792 info!(cell, from, to = epoch, "restored remote replica");
1793 restored = true;
1794 }
1795 }
1796 }
1797
1798 let remote_seed = if !restored && dst_existed {
1799 Some(self.contiguous_covered_txid(cell, epoch).await?)
1800 } else {
1801 None
1802 };
1803
1804 // Open the managed Db (creates a fresh WAL db when nothing was restored)
1805 // and pair it with this epoch's client. Registration is immediate: the
1806 // cell can be proved durable on its very first write. The just-opened
1807 // db's position is the replica's candidate seed -- 0 for a fresh cell
1808 // and the restored max for a proved image. An uncertified reused image
1809 // is clamped to its remote contiguous prefix above. The first sync can
1810 // therefore skip the `calc_pos` listing that otherwise storms a
1811 // rate-limiting store without skipping a staged local row. On the rare
1812 // decode error, proved images fall back to that listing and uncertified
1813 // images fail closed because their local bound is unknown.
1814 let db_open_started_mono_ms = asyncrt::mono_ms();
1815 let dst_ = dst.clone();
1816 let ltx_host = self.ltx_host.clone();
1817 // The paged VFS (this activation) takes precedence over the fault VFS.
1818 let vfs_name = paged_vfs_name.clone().or_else(|| self.vfs_name.clone());
1819 let truncate_pages = self.truncate_pages_for_cell(cell);
1820 let (db, mut seed, marker) = asyncrt::blocking(move || {
1821 let open_db = |ltx_host: LtxHost| match vfs_name.as_deref() {
1822 Some(vfs_name) => Db::open_with_host_and_vfs(&dst_, ltx_host, vfs_name),
1823 None => Db::open_with_host(&dst_, ltx_host),
1824 };
1825 #[cfg(celld_internal_tests)]
1826 let mut db = crate::fault::with_connection_role("celld_ltx_db", || open_db(ltx_host))?;
1827 #[cfg(not(celld_internal_tests))]
1828 let mut db = open_db(ltx_host)?;
1829 if let Some(pages) = truncate_pages {
1830 db.truncate_page_n = pages;
1831 }
1832 let marker = match continuation {
1833 Some((txid, commit)) => Some((txid, db.seed_continuation(txid, commit)?)),
1834 None => None,
1835 };
1836 let seed = db.pos().ok();
1837 anyhow::Ok((db, seed, marker))
1838 })
1839 .await?
1840 .map_err(|error| anyhow!("open managed db {}: {error}", dst.display()))?;
1841 if let Some((txid, bytes)) = marker {
1842 self.client_for(cell, epoch)
1843 .write_ltx_file(0, txid, txid, &bytes)
1844 .await
1845 .map_err(|error| anyhow!("upload the epoch marker for {cell} e{epoch}: {error}"))?;
1846 self.note_covered(cell, epoch, txid.0);
1847 }
1848 if let Some(covered) = remote_seed {
1849 let local = seed.ok_or_else(|| {
1850 anyhow!("cannot prove local replica position for {cell} epoch {epoch}")
1851 })?;
1852 if local.txid.0 > covered {
1853 seed = Some(Pos::new(TXID(covered), 0));
1854 }
1855 }
1856 let db_open_us = asyncrt::mono_ms()
1857 .saturating_sub(db_open_started_mono_ms)
1858 .saturating_mul(1_000);
1859 if let Some(timing) = remote_restore {
1860 info!(
1861 event = "restore_plan",
1862 cell,
1863 epoch = timing.from,
1864 to = epoch,
1865 objects = timing.objects,
1866 bytes = timing.bytes,
1867 levels = %timing.levels,
1868 total_us = asyncrt::mono_ms()
1869 .saturating_sub(timing.started_mono_ms)
1870 .saturating_mul(1_000),
1871 source_lookup_us = timing.source_lookup_us,
1872 plan_us = timing.plan_us,
1873 map_us = timing.map_us,
1874 download_us = timing.download_us,
1875 apply_us = timing.apply_us,
1876 paged = timing.paged,
1877 db_open_us,
1878 "computed restore plan"
1879 );
1880 }
1881 let mut replica = Replica::new(db, self.client_for(cell, epoch));
1882 if let Some(pos) = seed {
1883 replica.seed_pos(pos);
1884 }
1885 let hydration = paged_vfs_name
1886 .as_ref()
1887 .filter(|_| self.hydrate_bytes_per_s > 0)
1888 .map(|_| {
1889 Arc::new(CellHydration {
1890 cancelled: AtomicBool::new(false),
1891 complete: AtomicBool::new(false),
1892 })
1893 });
1894 let handle = Arc::new(Cell {
1895 snapshot_declined: AtomicBool::new(false),
1896 paged_vfs: paged_vfs_name.clone(),
1897 hydration: hydration.clone(),
1898 replica: Mutex::new(Some(replica)),
1899 client: self.client_for(cell, epoch),
1900 req_seq: AtomicU64::new(0),
1901 synced_seq: AtomicU64::new(0),
1902 shipped_seq: AtomicU64::new(0),
1903 submitted_seq: AtomicU64::new(0),
1904 // Frames at or below the seed came from the bucket (or a proven
1905 // snapshot); the followers only ever need what follows.
1906 shipped_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
1907 submitted_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
1908 last_sync_ms: AtomicU64::new(asyncrt::wall_ms().max(0) as u64),
1909 capture_seq: AtomicU64::new(0),
1910 capture_started_ms: AtomicU64::new(0),
1911 node_proof_ms: self.node_proof_ms.clone(),
1912 durable_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
1913 // The restore read the per-cell prefix, so the seed IS the
1914 // per-cell coverage at open.
1915 percell_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
1916 syncing: AtomicBool::new(false),
1917 ready: Notify::new(),
1918 #[cfg(all(test, celld_internal_tests))]
1919 observer_cell: cell.to_string(),
1920 #[cfg(all(test, celld_internal_tests))]
1921 observer_epoch: epoch,
1922 #[cfg(all(test, celld_internal_tests))]
1923 durability_ticket_receipts: Mutex::new(Vec::new()),
1924 #[cfg(all(test, celld_internal_tests))]
1925 upload_round_receipts: Mutex::new(Vec::new()),
1926 #[cfg(all(test, celld_internal_tests))]
1927 fleet_credit_receipts: Mutex::new(Vec::new()),
1928 compaction: self.compaction_queue.as_ref().map(|queue| CellCompaction {
1929 cell: cell.to_string(),
1930 epoch,
1931 // The overlay lets compaction read bundle-resident frames
1932 // beside the per-cell objects; its output stays pure
1933 // per-cell L1s, which is the continuous drain.
1934 client: celld_ltx::BundleOverlayClient::new(
1935 self.client_for(cell, epoch),
1936 Some(Arc::new(SinkFetcher {
1937 registration: self.registration.clone(),
1938 cell: cell.to_string(),
1939 epoch,
1940 })),
1941 ),
1942 local_path: Db::meta_path_for_path(&dst),
1943 host: self.ltx_host.clone(),
1944 queue: queue.clone(),
1945 base_txid: continuation.map_or(1, |(txid, _)| txid.0),
1946 min_txids: self.compaction_min_txids,
1947 min_bytes: self.compaction_min_bytes,
1948 pending_bytes: AtomicU64::new(0),
1949 compacted_txid: AtomicU64::new(0),
1950 queued: AtomicBool::new(false),
1951 cancelled: AtomicBool::new(false),
1952 cancel: Notify::new(),
1953 #[cfg(all(test, celld_internal_tests))]
1954 finish_pause: Mutex::new(None),
1955 run: tokio::sync::Mutex::new(()),
1956 }),
1957 });
1958 #[cfg(celld_internal_tests)]
1959 self.pause_activation_install_for_world().await;
1960 // Shutdown publishes stop before it takes the close gate and this map.
1961 // An activation that linearizes first is in shutdown's snapshot; one
1962 // that linearizes later closes its just-opened database and cannot
1963 // recreate a post-owner persistence resource. A failed release also
1964 // keeps its key in the stopped map, so the same gate prevents a second
1965 // managed handle from installing on the path before owner cleanup.
1966 // Keep the on-disk image: a `resume_local` activation owns the clean-reload
1967 // baseline, and a restored activation can own LTX metadata that this
1968 // losing path cannot safely classify for deletion.
1969 let (admitted, close_incomplete) = {
1970 let _close_gate = self.replica_close_gate.lock().unwrap();
1971 let mut cells = self.cells.lock().unwrap();
1972 let close_incomplete = self
1973 .stopped_cells
1974 .lock()
1975 .unwrap()
1976 .contains_key(&(cell.to_string(), epoch));
1977 if self.stop.is_stopped() || close_incomplete {
1978 (false, close_incomplete)
1979 } else {
1980 cells.insert((cell.to_string(), epoch), handle.clone());
1981 registration.keep();
1982 (true, false)
1983 }
1984 };
1985 if !admitted {
1986 close_replica(&handle).map_err(|error| {
1987 anyhow!("close stopped activation for {cell} epoch {epoch}: {error}")
1988 })?;
1989 if close_incomplete {
1990 anyhow::bail!("managed replica close is incomplete for {cell} epoch {epoch}");
1991 }
1992 anyhow::bail!("LTX replication stopped before activation installed");
1993 }
1994 if let Some(pos) = seed {
1995 maybe_queue_compaction(&handle, pos.txid.0);
1996 }
1997 if let (Some(name), Some(hydration)) = (&paged_vfs_name, hydration) {
1998 self.spawn_hydration(cell, epoch, name.clone(), dst.clone(), hydration);
1999 }
2000
2001 Ok(ActivationResult {
2002 path: dst,
2003 restored,
2004 vfs: paged_vfs_name,
2005 })
2006 }
2007
2008 /// The paged VFS name of a resident activation, when its restore paged.
2009 /// The runtime opens the actor's connection through it; a plain open of a
2010 /// paged cell's sparse database file reads holes as data.
2011 /// Fills a paged cell's file in the background, a run per step at
2012 /// `CELLD_LTX_HYDRATE_MBPS`, one cell at a time per node, until the cut
2013 /// is complete or the cell closes. Steps fault through the VFS's own
2014 /// read path, so hydration is foreground faulting at a pace.
2015 fn spawn_hydration(
2016 &self,
2017 cell: &str,
2018 epoch: u64,
2019 name: String,
2020 path: PathBuf,
2021 hydration: Arc<CellHydration>,
2022 ) {
2023 let cell = cell.to_string();
2024 let permits = self.hydrations.clone();
2025 let step_ms =
2026 (u64::from(HYDRATE_STEP_PAGES) * 4096 * 1_000 / self.hydrate_bytes_per_s).max(1);
2027 self.tasks.spawn_owned("ltx-hydration", async move {
2028 let Ok(_permit) = permits.acquire().await else {
2029 return;
2030 };
2031 let started_mono_ms = asyncrt::mono_ms();
2032 let mut hydrator = match asyncrt::blocking({
2033 let name = name.clone();
2034 move || celld_ltx::paged_vfs::Hydrator::open(&name, &path)
2035 })
2036 .await
2037 {
2038 Ok(Ok(hydrator)) => hydrator,
2039 Ok(Err(error)) => {
2040 warn!(cell, epoch, %error, "paged hydration could not open the cell");
2041 return;
2042 }
2043 Err(_) => return,
2044 };
2045 let mut steps = 0u64;
2046 loop {
2047 if hydration.cancelled.load(Ordering::SeqCst) {
2048 return;
2049 }
2050 let step = asyncrt::blocking(move || {
2051 let progress = hydrator.step(HYDRATE_STEP_PAGES);
2052 (hydrator, progress)
2053 })
2054 .await;
2055 let progress = match step {
2056 Ok((hydrator_, Ok(progress))) => {
2057 hydrator = hydrator_;
2058 progress
2059 }
2060 Ok((_, Err(error))) => {
2061 warn!(cell, epoch, %error, "paged hydration stopped");
2062 return;
2063 }
2064 Err(_) => return,
2065 };
2066 steps += 1;
2067 if progress.complete() {
2068 hydration.complete.store(true, Ordering::SeqCst);
2069 info!(
2070 event = "paged_hydrated",
2071 cell,
2072 epoch,
2073 pages = progress.total,
2074 faults = progress.faults,
2075 steps,
2076 elapsed_ms = asyncrt::mono_ms().saturating_sub(started_mono_ms),
2077 "paged cell holds its whole cut"
2078 );
2079 return;
2080 }
2081 asyncrt::sleep(Duration::from_millis(step_ms)).await;
2082 }
2083 });
2084 }
2085
2086 /// How much of the cut a paged activation's file holds, for a world
2087 /// that waits on the background fill.
2088 #[cfg(all(test, celld_internal_tests))]
2089 pub fn hydration_for_test(
2090 &self,
2091 cell: &str,
2092 epoch: u64,
2093 ) -> Option<celld_ltx::paged_vfs::Hydration> {
2094 celld_ltx::paged_vfs::hydration(&self.paged_vfs_name(cell, epoch)?)
2095 }
2096
2097 /// The private suite's chain-size threshold for paging, so a world can
2098 /// page a small cut or clone one.
2099 #[cfg(all(test, celld_internal_tests))]
2100 pub fn set_paged_min_bytes_for_test(&self, bytes: u64) {
2101 self.paged_min_bytes.store(bytes, Ordering::Relaxed);
2102 }
2103
2104 /// The private suite's switch for paged restore, so a world runs its
2105 /// schedules over the fault path without the process environment. It
2106 /// pages every cut; `set_paged_min_bytes_for_test` restores a threshold.
2107 #[cfg(all(test, celld_internal_tests))]
2108 pub fn set_paged_restore_for_test(&self, on: bool) {
2109 self.paged_restore.store(on, Ordering::Relaxed);
2110 self.paged_fleet.store(on, Ordering::Relaxed);
2111 self.paged_min_bytes.store(0, Ordering::Relaxed);
2112 }
2113
2114 /// The fleet's answer to "can every live node read a paged epoch". The
2115 /// fleet sampler sets it from the leases; returns the prior value so the
2116 /// caller logs a transition once.
2117 pub fn set_paged_fleet(&self, ready: bool) -> bool {
2118 self.paged_fleet.swap(ready, Ordering::Relaxed)
2119 }
2120
2121 /// Whether this node would page a large takeover now.
2122 pub fn paged_fleet(&self) -> bool {
2123 self.paged_fleet.load(Ordering::Relaxed)
2124 }
2125
2126 /// The VFS the actor's connection must open through, for a resident
2127 /// activation: `Some` when it paged, `None` when its file is whole. An
2128 /// activation that is no longer resident is an error, not `None`: a
2129 /// plain open of an absent or sparse file would create or read the
2130 /// wrong database.
2131 pub fn activation_vfs(&self, cell: &str, epoch: u64) -> anyhow::Result<Option<String>> {
2132 let cells = self.cells.lock().unwrap();
2133 let handle = cells
2134 .get(&(cell.to_string(), epoch))
2135 .ok_or_else(|| anyhow!("{cell} epoch {epoch} is not resident"))?;
2136 Ok(handle.paged_vfs.clone())
2137 }
2138
2139 pub fn paged_vfs_name(&self, cell: &str, epoch: u64) -> Option<String> {
2140 self.cells
2141 .lock()
2142 .unwrap()
2143 .get(&(cell.to_string(), epoch))
2144 .and_then(|handle| handle.paged_vfs.clone())
2145 }
2146
2147 /// The output gate's primitive: take a durability ticket and return once a
2148 /// background sync that captured this write has completed, coalescing
2149 /// concurrent writes to one cell into a single upload. The write committed
2150 /// before this call, so any sync starting after our ticket captures it —
2151 /// we wait for `synced_seq >= my ticket`, not for a position, sidestepping
2152 /// the total_changes↔LTX-txid mismatch that a position compare would hit.
2153 /// Returns `position` (which the completed sync provably covered) for the
2154 /// core's coverage check.
2155 pub async fn await_durable(
2156 &self,
2157 cell: &str,
2158 epoch: u64,
2159 position: u64,
2160 ) -> anyhow::Result<(u64, celld_logic::ProofSource)> {
2161 let Some(handle) = self
2162 .cells
2163 .lock()
2164 .unwrap()
2165 .get(&(cell.to_string(), epoch))
2166 .cloned()
2167 else {
2168 anyhow::bail!("ltx cell not resident: {cell} epoch {epoch}");
2169 };
2170 let ticket = handle.req_seq.fetch_add(1, Ordering::SeqCst) + 1;
2171 #[cfg(all(test, celld_internal_tests))]
2172 handle.record_durability_ticket_for_world(position, ticket);
2173 self.dirty.notify_one();
2174 self.dirty_ship.notify_one();
2175 let source = self
2176 .wait_for_durability_ticket(&handle, cell, epoch, ticket)
2177 .await?;
2178 Ok((position, source))
2179 }
2180
2181 /// Prove that every write before handoff nomination reached either the
2182 /// bucket or the live durability ensemble. The fleet proof is sufficient
2183 /// to close the runtime because ownership still names this donor. The
2184 /// eviction barrier publishes the closed database before ownership can
2185 /// move, so a process loss between these phases still enters ordinary
2186 /// dead-node recovery.
2187 pub async fn handoff_wait(
2188 &self,
2189 cell: &str,
2190 epoch: u64,
2191 ) -> anyhow::Result<celld_logic::ProofSource> {
2192 let Some(handle) = self
2193 .cells
2194 .lock()
2195 .unwrap()
2196 .get(&(cell.to_string(), epoch))
2197 .cloned()
2198 else {
2199 anyhow::bail!("ltx cell not resident: {cell} epoch {epoch}");
2200 };
2201 let ticket = handle.req_seq.fetch_add(1, Ordering::SeqCst) + 1;
2202 self.dirty.notify_one();
2203 self.dirty_ship.notify_one();
2204 self.wait_for_durability_ticket(&handle, cell, epoch, ticket)
2205 .await
2206 }
2207
2208 /// The eviction gate: prove the cell is safe to give up, while the node
2209 /// can still change its mind.
2210 ///
2211 /// This runs in `Phase::EnsuringDurability`. The cell still serves there,
2212 /// and a request that arrives cancels the eviction and puts the cell back
2213 /// into service at its own epoch. `stop_cell` then takes close exclusion,
2214 /// drops the runtime, and only afterwards calls `evict`, which publishes
2215 /// the handoff snapshot and asks the bucket to confirm it. A request that
2216 /// arrives during that second half finds `Phase::Cleaning` and waits for a
2217 /// whole reactivation at a new epoch, so every second the eviction spends
2218 /// after the close is a second in which an idle sweep can still evict a
2219 /// cell that traffic made live again. A revocable eviction therefore does
2220 /// the remote work it can do here, where the answer can still be acted on.
2221 ///
2222 /// `handoff_wait` reports which mechanism proved the cell durable, and
2223 /// that names the successor's restore source. A bucket proof means the
2224 /// per-cell tiering is the acknowledgement path, so the objects under
2225 /// `cells/<cell>/ltx/e<epoch>` are already there. Ask the bucket whether
2226 /// they survived: an upload this process completed does not prove that
2227 /// they did. A fleet proof means the paced shipper is active, and
2228 /// `bundle_loop` then leaves the per-cell prefix untouched by design, so
2229 /// that prefix is legitimately empty and an unconditional question here
2230 /// would refuse every fleet-posture eviction.
2231 ///
2232 /// The fleet proof therefore keeps the window this closes for the bucket
2233 /// proof. Moving the handoff snapshot forward would not close it: the
2234 /// snapshot is a full image at one txid, `evict` publishes it as the
2235 /// successor's authoritative restore artifact, and a cell that keeps
2236 /// serving can commit past it. A cancelled eviction would then leave an
2237 /// image in the bucket that a later restore reads as complete. The cost
2238 /// of the remaining window is revocability and not durability, because
2239 /// `evict` still refuses to give up state the bucket cannot restore.
2240 /// Closing it needs the core to accept a request during `Phase::Cleaning`,
2241 /// which is an open decision (#818). Do not read the scoping as a claim
2242 /// that the fleet path needs no gate.
2243 ///
2244 /// A drain passes `revocable: false`. It has nowhere to put a cell back,
2245 /// so the answer could change nothing, and a drain that spent one bucket
2246 /// LIST per resident cell would pay for it out of its shutdown budget.
2247 pub async fn handoff_gate(
2248 &self,
2249 cell: &str,
2250 epoch: u64,
2251 revocable: bool,
2252 ) -> anyhow::Result<()> {
2253 let proof = self.handoff_wait(cell, epoch).await?;
2254 if revocable
2255 && matches!(proof, celld_logic::ProofSource::Bucket)
2256 && !self.epoch_replicated(cell, epoch).await
2257 {
2258 return Err(anyhow!(
2259 "no replica objects for {cell} epoch {epoch}; refusing to \
2260 evict state the bucket cannot restore"
2261 ));
2262 }
2263 Ok(())
2264 }
2265
2266 async fn wait_for_durability_ticket(
2267 &self,
2268 handle: &CellHandle,
2269 cell: &str,
2270 epoch: u64,
2271 ticket: u64,
2272 ) -> anyhow::Result<celld_logic::ProofSource> {
2273 let wait = ProofWait {
2274 started_ms: asyncrt::mono_ms(),
2275 ticket,
2276 budget_ms: self.durability_timeout_ms,
2277 };
2278 let started = wait.started_ms;
2279 loop {
2280 // Register the waiter before checking, so a sync that completes
2281 // between the check and the await is not missed. Either proof
2282 // releases the gate: the bucket upload, or every ensemble
2283 // member's fsync — whichever lands first.
2284 let ready = handle.ready.notified();
2285 // Prefer the fleet proof when both hold: it is the arbitrated
2286 // one, and it spares the caller an ownership read.
2287 let shipped = handle.shipped_seq.load(Ordering::SeqCst) >= ticket;
2288 if handle.synced_seq.load(Ordering::SeqCst) >= ticket || shipped {
2289 let source = if shipped {
2290 celld_logic::ProofSource::Fleet
2291 } else {
2292 celld_logic::ProofSource::Bucket
2293 };
2294 tracing::debug!(
2295 target: "timing",
2296 event = "durable_wait",
2297 cell,
2298 wait_us = asyncrt::mono_ms().saturating_sub(started).saturating_mul(1_000),
2299 proof = if shipped { "fleet" } else { "bucket" },
2300 "durability proof reached"
2301 );
2302 return Ok(source);
2303 }
2304 // The deadline moves: a proof landing anywhere on the node while
2305 // this write is queued, or this cell's capture beginning, each
2306 // push it out (`celld_logic::durability`). So a timer firing is
2307 // a cue to recompute, and only a deadline that is still in the
2308 // past fails the proof.
2309 let deadline = proof_deadline(
2310 &wait,
2311 &ProofProgress {
2312 node_proof_ms: handle.node_proof_ms.load(Ordering::SeqCst),
2313 capture_seq: handle.capture_seq.load(Ordering::SeqCst),
2314 capture_started_ms: handle.capture_started_ms.load(Ordering::SeqCst),
2315 },
2316 );
2317 if asyncrt::mono_ms() >= deadline {
2318 anyhow::bail!("ltx durability timed out for {cell} epoch {epoch}");
2319 }
2320 let _ = asyncrt::timeout_at(deadline, ready).await;
2321 }
2322 }
2323
2324 /// A direct, synchronous durability pass for the rare eviction
2325 /// gates (not the hot write path). Also advances the cell's durable position
2326 /// so any output-gate waiters ride it.
2327 pub async fn sync_wait(&self, cell: &str, epoch: u64, timeout: Duration) -> SyncWait {
2328 let Some(handle) = self
2329 .cells
2330 .lock()
2331 .unwrap()
2332 .get(&(cell.to_string(), epoch))
2333 .cloned()
2334 else {
2335 return SyncWait::Unsupported;
2336 };
2337 match asyncrt::timeout(timeout, sync_cell(handle.clone())).await {
2338 Ok(Some(true)) => SyncWait::Durable,
2339 Ok(Some(false)) | Err(_) => SyncWait::Failed,
2340 Ok(None) => SyncWait::Unsupported,
2341 }
2342 }
2343
2344 /// Return the configured durability deadline to a private deterministic
2345 /// world, so a bounded-liveness assertion uses the production value.
2346 #[cfg(all(test, celld_internal_tests))]
2347 pub(crate) fn durability_timeout_ms_for_world(&self) -> u64 {
2348 self.durability_timeout_ms
2349 }
2350
2351 /// Lower the handoff snapshot budget, so a private world can hand off a
2352 /// small database the way production hands off a whale.
2353 #[cfg(all(test, celld_internal_tests))]
2354 pub(crate) fn set_handoff_snapshot_budget_for_world(&self, bytes: u64) {
2355 self.snapshot_budget_bytes.store(bytes, Ordering::Relaxed);
2356 }
2357
2358 /// Close this cell after a final durability pass and install its database
2359 /// as the previous-epoch cache entry which the next activation consumes.
2360 ///
2361 /// A remote restore creates a live database at the successor epoch. Closing
2362 /// that database in place makes the next epoch ignore it because only a
2363 /// `.evicted` file is a certified reactivation base. The activation then
2364 /// downloads the same older snapshot again (#479). Use [`Self::close_in_place`]
2365 /// only when the caller cannot authorize a final durability pass.
2366 pub async fn release(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
2367 self.final_durability_barrier(cell, epoch).await?;
2368
2369 // Cleanup does not transfer ownership, so it does not need the L9
2370 // handoff snapshot that eviction publishes. The durable L0 chain and
2371 // this certified local base cover both a later node and this node's
2372 // successor activation.
2373 self.remove_local(cell, epoch, true);
2374 Ok(())
2375 }
2376
2377 /// Close this cell's managed database, leaving every file in place.
2378 ///
2379 /// Background work can retain the handle after registry removal. The method
2380 /// installs the close in the durability owner's task group before it waits
2381 /// for completion. Therefore, a cancelled caller cannot detach the close,
2382 /// and local shutdown joins the same operation instead of closing twice.
2383 /// If the blocking task fails before it takes the replica, the method
2384 /// returns an error and retains the handle. A later call retries the close,
2385 /// and the final owner shutdown also closes a retained handle.
2386 ///
2387 /// No durability pass here, deliberately. This runs on the stops that are
2388 /// not an orderly handoff, and a fenced node has lost the authority that
2389 /// would make writing more of this cell's history safe. `evict` below
2390 /// still syncs, and still refuses to drop a handle whose final pass
2391 /// failed, because that is the path where the node keeps the cell and is
2392 /// giving it up on purpose. The caller must require a successful result
2393 /// before it reuses the local path for another activation. Use
2394 /// [`Self::release`] when the caller can authorize a final durability pass.
2395 pub async fn close_in_place(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
2396 let key = (cell.to_string(), epoch);
2397 let (completed, admitted) = {
2398 // Keep the gate through active-to-stopped transfer and task
2399 // admission. Shutdown closes admission and snapshots both maps
2400 // under this same gate, so it cannot miss an in-flight release.
2401 let _close_gate = self.replica_close_gate.lock().unwrap();
2402 let handle = match self.remove_active_and_record_tail(cell, epoch) {
2403 Some(handle) => handle,
2404 None => {
2405 let stopped = self.stopped_cells.lock().unwrap().get(&key).cloned();
2406 let Some(handle) = stopped else {
2407 return Ok(());
2408 };
2409 if !self.failed_release_closes.lock().unwrap().remove(&key) {
2410 return Err(anyhow!(
2411 "managed replica close is incomplete for {cell} epoch {epoch}; wait for it or finish local shutdown"
2412 ));
2413 }
2414 handle
2415 }
2416 };
2417 self.note_undrained_tail(cell, &handle);
2418 self.stopped_cells
2419 .lock()
2420 .unwrap()
2421 .insert(key.clone(), handle.clone());
2422 if self.replica_close_stop.is_stopped() {
2423 self.failed_release_closes.lock().unwrap().insert(key);
2424 return Err(anyhow!(
2425 "managed replica close was deferred to local shutdown for {cell} epoch {epoch}"
2426 ));
2427 }
2428 #[cfg(celld_internal_tests)]
2429 let pause = self.take_replica_close_pause_for_world();
2430 #[cfg(celld_internal_tests)]
2431 let panic_close = self.take_release_close_panic_for_world();
2432 let stopped_cells = self.stopped_cells.clone();
2433 let failed_release_closes = self.failed_release_closes.clone();
2434 let close_key = key.clone();
2435 let close_cell = cell.to_string();
2436 let close_handle = handle.clone();
2437 let (completed_tx, completed_rx) = tokio::sync::oneshot::channel();
2438 let admitted = self.replica_close_tasks.spawn_owned(
2439 "ltx_replica_close",
2440 async move {
2441 let task_handle = close_handle.clone();
2442 let close_result = asyncrt::blocking(move || {
2443 #[cfg(celld_internal_tests)]
2444 assert!(!panic_close, "injected managed release-close panic");
2445 #[cfg(celld_internal_tests)]
2446 pause_replica_close_for_world(pause);
2447 close_replica(&task_handle)
2448 })
2449 .await;
2450 let (close_result, retry_during_shutdown) = match close_result {
2451 Ok(result) => (result, false),
2452 Err(error) => (
2453 Err(anyhow!("managed replica close task failed: {error}")),
2454 true,
2455 ),
2456 };
2457 if retry_during_shutdown {
2458 failed_release_closes
2459 .lock()
2460 .unwrap()
2461 .insert(close_key.clone());
2462 } else {
2463 let mut stopped = stopped_cells.lock().unwrap();
2464 if stopped
2465 .get(&close_key)
2466 .is_some_and(|current| Arc::ptr_eq(current, &close_handle))
2467 {
2468 stopped.remove(&close_key);
2469 }
2470 }
2471 if let Err(error) = close_result {
2472 if retry_during_shutdown {
2473 // The blocking lane failed before it proved that
2474 // it took the replica. Keep the stopped entry so a
2475 // later release or final shutdown retries it.
2476 warn!(cell = close_cell, epoch, %error, "managed replica close task failed during removal");
2477 let _ = completed_tx.send(Err(error.to_string()));
2478 } else {
2479 // close_replica took and dropped the database even
2480 // when read-lock release failed, so this path needs
2481 // no second close attempt.
2482 warn!(cell = close_cell, epoch, %error, "close managed replica failed during removal");
2483 let _ = completed_tx.send(Ok(()));
2484 }
2485 } else {
2486 let _ = completed_tx.send(Ok(()));
2487 }
2488 },
2489 );
2490 (completed_rx, admitted)
2491 };
2492 if admitted {
2493 completed
2494 .await
2495 .map_err(|_| anyhow!("managed replica close task ended without completion"))?
2496 .map_err(anyhow::Error::msg)
2497 } else {
2498 // Shutdown already owns the stopped entry and closes it from its
2499 // final snapshot. No new runtime can activate after this point.
2500 self.failed_release_closes.lock().unwrap().insert(key);
2501 Err(anyhow!(
2502 "managed replica close was deferred to local shutdown for {cell} epoch {epoch}"
2503 ))
2504 }
2505 }
2506
2507 /// Take the cell, or give it back.
2508 ///
2509 /// `abandon` carries the core's answer to "a request arrived for this
2510 /// cell". Reading it is the whole revocable half of an eviction stop, and
2511 /// where it can be read is fixed by what is already visible to a
2512 /// successor:
2513 ///
2514 /// - Before `prepare_handoff_snapshot`, nothing remote has happened and
2515 /// the isolate turn this pass waited for can be the slow part on a
2516 /// loaded node. Abandoning here costs nothing.
2517 /// - Before `publish_handoff_snapshot`, the snapshot exists only in this
2518 /// process. Abandoning here throws away one local capture.
2519 /// - After that PUT there is no way back. The snapshot is a full image at
2520 /// one txid, and `restore_plan` takes the highest snapshot at or below
2521 /// its target and then extends it only with the per-cell files above it.
2522 /// A resumed cell commits past that txid, and under a fleet proof those
2523 /// rows go to node bundles and not to the per-cell prefix, so a restore
2524 /// would read the image as a complete database that stops short of an
2525 /// acknowledged write. The rows are recoverable while the node-log
2526 /// session stays open, but that is a second mechanism and not a proof,
2527 /// so this pass does not rely on it.
2528 ///
2529 /// The PUT and the visibility LIST therefore stay unrevocable in both
2530 /// postures. A request that arrives during those two round trips still
2531 /// waits for the cell to start again at a new epoch.
2532 pub async fn evict(
2533 &self,
2534 cell: &str,
2535 epoch: u64,
2536 preserve_local: bool,
2537 abandon: Option<&crate::replication::EvictionAbandon>,
2538 ) -> anyhow::Result<EvictionRestoreArtifact> {
2539 // The runtime is closed before this pass, so the snapshot is the
2540 // definitive durability barrier. The paced shipper normally stores a
2541 // hot tail in node bundles. Re-reading every local L0 row to duplicate
2542 // that tail under the cell prefix made shutdown cost grow with the
2543 // cell's lifetime. One full snapshot has constant object count and
2544 // gives the successor the same closed database.
2545 let barrier_started_mono_ms = asyncrt::mono_ms();
2546 let handle = self
2547 .cells
2548 .lock()
2549 .unwrap()
2550 .get(&(cell.to_string(), epoch))
2551 .cloned()
2552 .ok_or_else(|| anyhow!("ltx cell not resident: {cell} epoch {epoch}"))?;
2553 let abandoned = || {
2554 anyhow::Error::new(crate::replication::EvictionAbandoned {
2555 cell: cell.to_string(),
2556 epoch,
2557 })
2558 };
2559 if abandon.is_some_and(EvictionAbandon::requested) {
2560 return Err(abandoned());
2561 }
2562 let snapshot = self.prepare_handoff_snapshot(&handle).await?;
2563 if abandon.is_some_and(EvictionAbandon::requested) {
2564 return Err(abandoned());
2565 }
2566 let deadline = barrier_started_mono_ms.saturating_add(self.durability_timeout_ms);
2567 let mut artifact = None;
2568 if let Some(snapshot) = snapshot {
2569 let published = asyncrt::timeout_at(
2570 deadline,
2571 self.publish_handoff_snapshot(cell, epoch, &snapshot),
2572 )
2573 .await;
2574 if matches!(published, Ok(Ok(()))) && self.epoch_replicated(cell, epoch).await {
2575 artifact = Some(EvictionRestoreArtifact::Snapshot);
2576 } else {
2577 handle.snapshot_declined.store(true, Ordering::Relaxed);
2578 warn!(
2579 event = "eviction_snapshot_fallback",
2580 cell,
2581 epoch,
2582 "the authoritative snapshot failed, so the handoff requires its L0 chain"
2583 );
2584 }
2585 }
2586 let artifact = match artifact {
2587 Some(artifact) => artifact,
2588 None => {
2589 let remaining_ms = deadline.saturating_sub(asyncrt::mono_ms());
2590 if remaining_ms == 0
2591 || !matches!(
2592 self.sync_wait(cell, epoch, Duration::from_millis(remaining_ms))
2593 .await,
2594 SyncWait::Durable
2595 )
2596 {
2597 return Err(anyhow!("final durability failed for {cell} epoch {epoch}"));
2598 }
2599 if !self.epoch_replicated(cell, epoch).await {
2600 return Err(anyhow!(
2601 "no replica objects for {cell} epoch {epoch}; refusing to evict state the bucket cannot restore"
2602 ));
2603 }
2604 EvictionRestoreArtifact::L0Chain
2605 }
2606 };
2607 info!(
2608 event = "eviction_durability_barrier",
2609 cell,
2610 epoch,
2611 artifact = ?artifact,
2612 elapsed_ms = asyncrt::mono_ms().saturating_sub(barrier_started_mono_ms),
2613 "final durability barrier passed"
2614 );
2615
2616 // Keep the local Db until one authoritative restore artifact is
2617 // remotely visible. A failed snapshot and failed L0 fallback retain
2618 // the handle, so the actor cannot release ownership.
2619 self.remove_local(cell, epoch, preserve_local);
2620 Ok(artifact)
2621 }
2622
2623 async fn final_durability_barrier(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
2624 let barrier_started_mono_ms = asyncrt::mono_ms();
2625 match self.sync_wait(cell, epoch, Duration::from_secs(10)).await {
2626 SyncWait::Durable => {}
2627 SyncWait::Unsupported => {
2628 return Err(anyhow!(
2629 "final durability is unsupported for {cell} epoch {epoch}"
2630 ));
2631 }
2632 SyncWait::Failed => {
2633 return Err(anyhow!("final durability failed for {cell} epoch {epoch}"));
2634 }
2635 }
2636 info!(
2637 event = "final_durability_barrier",
2638 cell,
2639 epoch,
2640 elapsed_ms = asyncrt::mono_ms().saturating_sub(barrier_started_mono_ms),
2641 "final durability barrier passed"
2642 );
2643 Ok(())
2644 }
2645
2646 /// Discard a reset runtime without another durability attempt.
2647 ///
2648 /// The proof that triggered Reset already failed. Retrying it here can keep
2649 /// the unproved database resident and contradicts Reset's keep-nothing
2650 /// contract, so this path removes the handle and every live local file.
2651 pub(crate) fn discard(&self, cell: &str, epoch: u64) {
2652 self.remove_local(cell, epoch, false);
2653 }
2654
2655 fn remove_local(&self, cell: &str, epoch: u64, preserve_local: bool) {
2656 let removed = self.remove_active_and_record_tail(cell, epoch);
2657 if let Some(handle) = &removed {
2658 self.note_covered(cell, epoch, percell_coverage(handle));
2659 }
2660 // A paged activation's file is a sparse cache of the cut, never a
2661 // certified reactivation baseline, and its VFS registration ends with
2662 // the activation. The io methods hold their own Arcs, so open files
2663 // outliving the unregistration stay safe.
2664 let paged_vfs = removed.as_ref().and_then(|handle| handle.paged_vfs.clone());
2665 let preserve_local = preserve_local && paged_vfs.is_none();
2666 if let Some(hydration) = removed
2667 .as_ref()
2668 .and_then(|handle| handle.hydration.as_ref())
2669 {
2670 hydration.cancelled.store(true, Ordering::SeqCst);
2671 }
2672 let close_result = removed.map_or(Ok(()), |handle| close_replica(&handle));
2673 if let Some(name) = paged_vfs {
2674 let _ = celld_ltx::paged_vfs::unregister_paged_vfs(&name);
2675 }
2676 self.finish_remove_local(cell, epoch, preserve_local, close_result);
2677 }
2678
2679 /// Move an active handle out only after its undrained-tail marker is
2680 /// visible. The graceful-seal check takes these locks in the same order,
2681 /// so it cannot observe the handle as absent before it can observe the
2682 /// marker that replaces it.
2683 fn remove_active_and_record_tail(&self, cell: &str, epoch: u64) -> Option<CellHandle> {
2684 let key = (cell.to_string(), epoch);
2685 let mut cells = self.cells.lock().unwrap();
2686 let handle = cells.get(&key)?;
2687 self.note_undrained_tail(cell, handle);
2688 cells.remove(&key)
2689 }
2690
2691 /// Record an ending that leaves acked rows outside the per-cell
2692 /// layout. Acked is the max of the fleet credit and the tiering
2693 /// credit — the bundle flush advances `durable_txid`, so neither
2694 /// alone is per-cell coverage. Covered is what a successor restore
2695 /// will actually see: the per-cell watermark plus the drain's L1
2696 /// fold. Anything acked above covered sits only in node bundles,
2697 /// where no restore looks (#473). Conservative on purpose: a stale
2698 /// `compacted_txid` marks a cell whose fold then finds nothing,
2699 /// which costs one bundle-prefix scan, never a lost row.
2700 fn note_undrained_tail(&self, cell: &str, handle: &Cell) {
2701 let acked = handle
2702 .shipped_txid
2703 .load(Ordering::SeqCst)
2704 .max(handle.durable_txid.load(Ordering::SeqCst));
2705 let covered = percell_coverage(handle);
2706 if acked > covered {
2707 self.dirty_tails.lock().unwrap().insert(cell.to_string());
2708 }
2709 }
2710
2711 fn finish_remove_local(
2712 &self,
2713 cell: &str,
2714 epoch: u64,
2715 preserve_local: bool,
2716 close_result: anyhow::Result<()>,
2717 ) {
2718 let preserve_local = match close_result {
2719 Ok(()) => preserve_local,
2720 Err(error) => {
2721 warn!(
2722 cell,
2723 epoch,
2724 %error,
2725 "close managed replica failed; discarding local snapshot"
2726 );
2727 // A failed close cannot qualify the live database as a
2728 // reusable baseline. An orderly eviction already published
2729 // its final snapshot, and every other caller requested no
2730 // local reuse, so force any next epoch through remote restore.
2731 false
2732 }
2733 };
2734 let db = self.db_path(cell, epoch);
2735 if preserve_local {
2736 let preserved = db.with_extension("evicted");
2737 if let Err(error) = self.ltx_host.rename(&db, &preserved) {
2738 warn!(cell, epoch, %error, "preserve local snapshot failed");
2739 } else {
2740 if let Err(error) = self
2741 .preserved
2742 .lock()
2743 .expect("preserved cache poisoned")
2744 .insert(preserved)
2745 {
2746 warn!(cell, epoch, %error, "index preserved local snapshot failed");
2747 }
2748 }
2749 }
2750 // Clear the WAL/meta siblings and the live db regardless: a reactivation
2751 // restores or reuses the `.hibernated` copy.
2752 for suffix in ["-wal", "-shm"] {
2753 let mut sibling = db.clone().into_os_string();
2754 sibling.push(suffix);
2755 let _ = self.ltx_host.remove_file(&PathBuf::from(sibling));
2756 }
2757 let _ = self.ltx_host.remove_dir_all(&Db::meta_path_for_path(&db));
2758 if !preserve_local {
2759 let _ = self.ltx_host.remove_file(&db);
2760 }
2761 }
2762
2763 /// Capture one full snapshot after the runtime closes.
2764 ///
2765 /// A retry reuses these bytes. Recreating the image for each failed PUT
2766 /// would spend local I/O without changing the closed database.
2767 async fn prepare_handoff_snapshot(
2768 &self,
2769 handle: &CellHandle,
2770 ) -> anyhow::Result<Option<HandoffSnapshot>> {
2771 // A paged activation's local file is sparse. The snapshot page
2772 // collector reads non-WAL pages from the file directly, so a handoff
2773 // snapshot built here would publish hole-zeros as authoritative data.
2774 // Skip it; the eviction then proves durability through the L0 chain,
2775 // which is complete by construction (every write synced through WAL).
2776 if handle.paged_vfs.is_some() || handle.snapshot_declined.load(Ordering::Relaxed) {
2777 return Ok(None);
2778 }
2779 cancel_compaction(handle);
2780 let _compaction_run = match &handle.compaction {
2781 Some(compaction) => Some(compaction.run.lock().await),
2782 None => None,
2783 };
2784
2785 let snapshot_handle = handle.clone();
2786 // The deadline covers the snapshot's upload. A database the deadline
2787 // cannot carry at a conservative store rate is not attempted, so a
2788 // whale does not allocate and time out on its whole image at every
2789 // retry; the L0 chain is its restore artifact, as for a paged cell.
2790 let budget = usize::try_from(self.snapshot_budget_bytes.load(Ordering::Relaxed))
2791 .unwrap_or(usize::MAX);
2792 asyncrt::blocking(move || -> anyhow::Result<Option<HandoffSnapshot>> {
2793 let mut replica_slot = snapshot_handle.replica.lock().unwrap();
2794 let replica = replica_slot
2795 .as_mut()
2796 .ok_or_else(|| anyhow!("handoff snapshot replica is closed"))?;
2797 let db = replica
2798 .db_mut()
2799 .ok_or_else(|| anyhow!("handoff snapshot database is unavailable"))?;
2800 db.sync()
2801 .map_err(|error| anyhow!("capture handoff database: {error}"))?;
2802 let durable_txid = db.pos()?.txid;
2803 if durable_txid == TXID(0) {
2804 return Ok(None);
2805 }
2806 let mut data = Vec::new();
2807 let position = match db.snapshot_to_writer(&mut BoundedWriter {
2808 data: &mut data,
2809 budget,
2810 }) {
2811 Ok(position) => position,
2812 Err(_) if data.len() >= budget => {
2813 snapshot_handle
2814 .snapshot_declined
2815 .store(true, Ordering::Relaxed);
2816 return Ok(None);
2817 }
2818 Err(error) => return Err(anyhow!("create handoff snapshot: {error}")),
2819 };
2820 anyhow::ensure!(
2821 position.txid == durable_txid,
2822 "handoff snapshot position {} does not match durable position {}",
2823 position.txid.0,
2824 durable_txid.0,
2825 );
2826 Ok(Some(HandoffSnapshot {
2827 max_txid: position.txid,
2828 data,
2829 }))
2830 })
2831 .await
2832 .map_err(|error| anyhow!("join handoff snapshot task: {error}"))?
2833 }
2834
2835 /// Publish one full L9 snapshot of a closed cell. A successful visibility
2836 /// check makes this snapshot the authoritative handoff proof.
2837 async fn publish_handoff_snapshot(
2838 &self,
2839 cell: &str,
2840 epoch: u64,
2841 snapshot: &HandoffSnapshot,
2842 ) -> anyhow::Result<()> {
2843 let started_mono_ms = asyncrt::mono_ms();
2844 let info = self
2845 .client_for(cell, epoch)
2846 .write_ltx_file(
2847 replica::SNAPSHOT_LEVEL,
2848 TXID(1),
2849 snapshot.max_txid,
2850 &snapshot.data,
2851 )
2852 .await
2853 .map_err(|error| anyhow!("publish handoff snapshot: {error}"))?;
2854 anyhow::ensure!(
2855 info.level == replica::SNAPSHOT_LEVEL
2856 && info.min_txid == TXID(1)
2857 && info.max_txid == snapshot.max_txid,
2858 "handoff snapshot metadata does not match the closed database",
2859 );
2860 info!(
2861 event = "ltx_handoff_snapshot",
2862 cell,
2863 epoch,
2864 max_txid = snapshot.max_txid.0,
2865 bytes = info.size,
2866 elapsed_ms = asyncrt::mono_ms().saturating_sub(started_mono_ms),
2867 "published authoritative handoff snapshot"
2868 );
2869 self.note_covered(cell, epoch, snapshot.max_txid.0);
2870 Ok(())
2871 }
2872
2873 /// Copy the live epoch into a private read-only snapshot for inspection.
2874 pub fn snapshot_active(
2875 &self,
2876 cell: &str,
2877 epoch: u64,
2878 ) -> anyhow::Result<Option<RestoredSnapshot>> {
2879 let source = self.db_path(cell, epoch);
2880 if !self
2881 .ltx_host
2882 .metadata(&source)
2883 .is_ok_and(|metadata| metadata.is_file)
2884 {
2885 return Ok(None);
2886 }
2887 let directory = self.watch.join(format!(".inspect-{cell}-e{epoch}"));
2888 let _ = self.ltx_host.remove_dir_all(&directory);
2889 self.ltx_host.create_dir_all(&directory)?;
2890 let path = directory.join("db.sqlite");
2891 // A paged activation's file is a sparse cache behind its VFS. A copy
2892 // of it in place would open the destination through the same
2893 // registration, and every page the backup writes there would mark
2894 // the cell's own hydration set without the cell's file holding it
2895 // (CelldPagedVfs.tla, `BreakSecondFileShares`): the live cell then
2896 // reads holes. Inspect a paged cell through the bucket instead.
2897 anyhow::ensure!(
2898 self.paged_vfs_name(cell, epoch).is_none(),
2899 "{cell} epoch {epoch} is paged in; inspect it from the bucket"
2900 );
2901 sqlite_snapshot(&source, &path, self.vfs_name.as_deref())?;
2902 Ok(Some(RestoredSnapshot::new(
2903 epoch,
2904 path,
2905 directory,
2906 self.ltx_host.filesystem(),
2907 )))
2908 }
2909
2910 /// Restore the newest durable replica into a private snapshot without
2911 /// claiming or activating the cell.
2912 pub async fn restore_snapshot(&self, cell: &str) -> anyhow::Result<Option<RestoredSnapshot>> {
2913 let Some(chain) = self.epoch_chain(cell, u64::MAX).await? else {
2914 return Ok(None);
2915 };
2916 let epoch = chain.spans().last().map_or(0, |(e, _)| *e);
2917 let directory = self.watch.join(format!(".restore-{cell}"));
2918 let _ = self.ltx_host.remove_dir_all(&directory);
2919 self.ltx_host.create_dir_all(&directory)?;
2920 let path = directory.join("db.sqlite");
2921 replica::restore_with_host_and_download_slots(
2922 &chain,
2923 &path,
2924 TXID(0),
2925 self.ltx_host.clone(),
2926 self.restore_slots.clone(),
2927 )
2928 .await
2929 .map_err(|error| anyhow!("restore snapshot {cell} e{epoch}: {error}"))?;
2930 Ok(Some(RestoredSnapshot::new(
2931 epoch,
2932 path,
2933 directory,
2934 self.ltx_host.filesystem(),
2935 )))
2936 }
2937
2938 pub fn prune_local_cache(&self, max_bytes: u64) -> std::io::Result<(usize, usize, u64)> {
2939 self.preserved
2940 .lock()
2941 .expect("preserved cache poisoned")
2942 .prune(&self.watch, max_bytes)
2943 }
2944
2945 /// Prove the stopped database position durable, then close the replicator
2946 /// while retaining the live database and WAL at their encoded path.
2947 pub async fn close_for_reload(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
2948 // Admission is already stopped, so this capture covers the exact
2949 // position that a clean reload preserves. Closing first can let the
2950 // next activation trust a local position that the bucket cannot
2951 // restore, and an aggregate shipper watermark cannot detect that gap.
2952 self.final_durability_barrier(cell, epoch).await?;
2953 // A paged cell's file is a sparse cache behind a VFS this process
2954 // registered; the next process has neither, so it cannot resume the
2955 // file in place (CelldPersistencePaged.tla, `BreakReloadKeepsPaged`).
2956 // Discard it after the proof, so the successor pages the complete
2957 // position in again from the bucket.
2958 if self.paged_vfs_name(cell, epoch).is_some() {
2959 self.remove_local(cell, epoch, false);
2960 return Ok(());
2961 }
2962 let removed = self
2963 .cells
2964 .lock()
2965 .unwrap()
2966 .remove(&(cell.to_string(), epoch));
2967 if let Some(handle) = removed {
2968 close_replica_for_reload(&handle, cell, epoch)?;
2969 }
2970 let path = self.db_path(cell, epoch);
2971 anyhow::ensure!(
2972 self.ltx_host
2973 .metadata(&path)
2974 .is_ok_and(|metadata| metadata.is_file),
2975 "resident database is missing: {}",
2976 path.display()
2977 );
2978 Ok(())
2979 }
2980
2981 /// Enumerate live-named databases. Cached `.evicted` files are separate
2982 /// and remain under the ordinary cache byte limit.
2983 pub fn local_cells(&self) -> Vec<celld_logic::LocalCell> {
2984 let mut cells = Vec::new();
2985 let filesystem = self.ltx_host.filesystem();
2986 let Ok(cell_dirs) = filesystem.read_dir(&self.watch) else {
2987 return cells;
2988 };
2989 for cell_dir in cell_dirs {
2990 if !cell_dir.is_dir {
2991 continue;
2992 }
2993 let Some(cell) = cell_dir.file_name.to_str().map(str::to_owned) else {
2994 continue;
2995 };
2996 let Ok(epochs) = filesystem.read_dir(&cell_dir.path.join("ltx")) else {
2997 continue;
2998 };
2999 for epoch_dir in epochs {
3000 let Some(epoch) = epoch_dir
3001 .file_name
3002 .to_str()
3003 .and_then(|name| name.strip_prefix('e'))
3004 .and_then(|epoch| epoch.parse::<u64>().ok())
3005 else {
3006 continue;
3007 };
3008 let is_file = |name: &str| {
3009 filesystem
3010 .metadata(&epoch_dir.path.join(name))
3011 .is_ok_and(|metadata| metadata.is_file)
3012 };
3013 // `.evicted` is what an eviction preserves; `.hibernated`
3014 // is the pre-2026-08-05 name of the same copy.
3015 let live = is_file("db.sqlite");
3016 if live || is_file("db.evicted") || is_file("db.hibernated") {
3017 cells.push(celld_logic::LocalCell {
3018 id: cell.clone(),
3019 epoch,
3020 live,
3021 });
3022 }
3023 }
3024 }
3025 cells.sort();
3026 cells.dedup();
3027 cells
3028 }
3029
3030 /// Delete stale live-named epochs after the runtime has identified and
3031 /// closed its exact resident set. Remote replicas remain authoritative.
3032 pub fn prune_stale_live(
3033 &self,
3034 keep: &std::collections::BTreeSet<(String, u64)>,
3035 ) -> anyhow::Result<usize> {
3036 let stale: Vec<_> = self
3037 .local_cells()
3038 .into_iter()
3039 .filter(|cell| cell.live && !keep.contains(&(cell.id.clone(), cell.epoch)))
3040 .collect();
3041 for cell in &stale {
3042 let db = self.db_path(&cell.id, cell.epoch);
3043 if let Some(parent) = db.parent() {
3044 self.ltx_host.remove_dir_all(parent)?;
3045 let mut preserved = self.preserved.lock().expect("preserved cache poisoned");
3046 preserved.forget(&db.with_extension("evicted"));
3047 preserved.forget(&db.with_extension("hibernated"));
3048 }
3049 }
3050 let remaining: std::collections::BTreeSet<_> = self
3051 .local_cells()
3052 .into_iter()
3053 .map(|cell| (cell.id, cell.epoch))
3054 .collect();
3055 anyhow::ensure!(
3056 &remaining == keep,
3057 "clean reload inventory mismatch after pruning: expected {}, found {}",
3058 keep.len(),
3059 remaining.len()
3060 );
3061 Ok(stale.len())
3062 }
3063
3064 /// There is no external process, so the in-process replicator is healthy while celld runs.
3065 pub fn process_status(&self) -> std::io::Result<Option<std::process::ExitStatus>> {
3066 Ok(None)
3067 }
3068}
3069
3070/// One capture+upload for a cell: advance its durable position on success and
3071/// wake its waiters. Everything committed before the capture is durable once
3072/// uploaded, so the target is read before `db.sync`.
3073///
3074/// The capture runs under the replica mutex on a blocking thread; the upload
3075/// runs OFF the mutex. A slow bucket PUT held the lock for its whole round
3076/// trip, and the log tier's ship capture queued behind it — the lab measured
3077/// 4-6 s ack spikes at every flush collision. Uploads are idempotent
3078/// overwrites keyed by TXID, and `syncing` already guarantees one pass per
3079/// cell, so staging then uploading lock-free is the same protocol
3080/// `Replica::sync` runs, minus the contention.
3081///
3082/// `Some(true)` means success, `Some(false)` means failure, and `None` means
3083/// that the replica lost its database.
3084async fn sync_cell(handle: CellHandle) -> Option<bool> {
3085 // Tickets taken before the capture: their writes committed before
3086 // `db.sync` runs, so it captures them. Read before the capture so a
3087 // ticket taken during the sync is credited by the next one, not this.
3088 type Staged = (u64, Vec<(u64, Vec<u8>)>);
3089 let handle_ = handle.clone();
3090 let staged: Option<Result<Staged, ()>> = asyncrt::blocking(move || {
3091 let captured = handle_.req_seq.load(Ordering::SeqCst);
3092 note_capture(&handle_, captured);
3093 let mut replica = handle_.replica.lock().unwrap();
3094 let from = replica.as_mut()?.pos().txid.0 + 1;
3095 let db = replica.as_mut()?.db_mut()?;
3096 if let Err(error) = db.sync() {
3097 warn!(%error, "ltx wal capture failed");
3098 return Some(Err(()));
3099 }
3100 let dpos = match db.pos() {
3101 Ok(pos) => pos,
3102 Err(error) => {
3103 warn!(%error, "ltx position read failed");
3104 return Some(Err(()));
3105 }
3106 };
3107 let mut files = Vec::new();
3108 for txid in from..=dpos.txid.0 {
3109 match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
3110 Ok(bytes) => files.push((txid, bytes)),
3111 Err(error) => {
3112 warn!(%error, txid, "read staged l0 failed");
3113 return Some(Err(()));
3114 }
3115 }
3116 }
3117 Some(Ok((captured, files)))
3118 })
3119 .await
3120 .unwrap_or(Some(Err(())));
3121 let (captured, files) = match staged {
3122 None => return None,
3123 Some(Err(())) => {
3124 handle.ready.notify_waiters();
3125 return Some(false);
3126 }
3127 Some(Ok(staged)) => staged,
3128 };
3129 let last = files.last().map(|(txid, _)| *txid);
3130 // A paced fleet normally keeps this tail in node bundles instead of the
3131 // per-cell prefix. A handoff must materialize that prefix before it can
3132 // delete the local copy, but one PUT per transaction makes the drain cost
3133 // grow with the hot cell's lifetime. Fold the contiguous tail exactly as
3134 // dead-node recovery does, so the durability cut has one remote write.
3135 // A malformed or discontinuous tail keeps the conservative per-row path.
3136 let merged = LtxRepl::merge_l0_rows(&files);
3137 let uploads: Vec<(u64, u64, &[u8])> = match (files.first(), files.last(), merged.as_ref()) {
3138 (Some((min_txid, _)), Some((max_txid, _)), Some(bytes)) => {
3139 vec![(*min_txid, *max_txid, bytes.as_slice())]
3140 }
3141 _ => files
3142 .iter()
3143 .map(|(txid, bytes)| (*txid, *txid, bytes.as_slice()))
3144 .collect(),
3145 };
3146 for (min_txid, max_txid, bytes) in &uploads {
3147 if let Some(compaction) = &handle.compaction {
3148 compaction
3149 .pending_bytes
3150 .fetch_add(bytes.len() as u64, Ordering::SeqCst);
3151 }
3152 #[cfg(all(test, celld_internal_tests))]
3153 let round_ordinal = handle.begin_upload_round_for_world(captured, *min_txid, *max_txid);
3154 if let Err(error) = handle
3155 .client
3156 .write_ltx_file(0, TXID(*min_txid), TXID(*max_txid), bytes)
3157 .await
3158 {
3159 #[cfg(all(test, celld_internal_tests))]
3160 handle.finish_upload_round_for_world(
3161 round_ordinal,
3162 LtxUploadRoundStatusForWorldV1::Failed,
3163 );
3164 warn!(%error, min_txid, max_txid, "ltx upload failed");
3165 handle
3166 .last_sync_ms
3167 .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
3168 handle.ready.notify_waiters();
3169 return Some(false);
3170 }
3171 #[cfg(all(test, celld_internal_tests))]
3172 handle.finish_upload_round_for_world(
3173 round_ordinal,
3174 LtxUploadRoundStatusForWorldV1::Completed,
3175 );
3176 }
3177 if let Some(last) = last {
3178 // Advance the replica's uploaded watermark; `syncing` serializes
3179 // passes, so nothing else moved it meanwhile.
3180 // A close can win after staging, so credit only a still-open replica.
3181 // The durable watermark remains valid when the replica is closed.
3182 if let Some(replica) = handle.replica.lock().unwrap().as_mut() {
3183 replica.seed_pos(Pos::new(TXID(last), 0));
3184 }
3185 handle.durable_txid.fetch_max(last, Ordering::SeqCst);
3186 handle.percell_txid.fetch_max(last, Ordering::SeqCst);
3187 }
3188 handle.synced_seq.fetch_max(captured, Ordering::SeqCst);
3189 maybe_queue_compaction(&handle, handle.durable_txid.load(Ordering::SeqCst));
3190 handle
3191 .last_sync_ms
3192 .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
3193 note_proof(&handle);
3194 handle.ready.notify_waiters();
3195 Some(true)
3196}
3197
3198fn maybe_queue_compaction(handle: &CellHandle, durable_txid: u64) {
3199 let Some(compaction) = &handle.compaction else {
3200 return;
3201 };
3202 let due_by_txids = durable_txid
3203 .saturating_sub(compaction.compacted_txid.load(Ordering::SeqCst))
3204 >= compaction.min_txids;
3205 let due_by_bytes = compaction.pending_bytes.load(Ordering::SeqCst) >= compaction.min_bytes;
3206 if compaction.cancelled.load(Ordering::SeqCst)
3207 || !(due_by_txids || due_by_bytes)
3208 || compaction
3209 .queued
3210 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
3211 .is_err()
3212 {
3213 return;
3214 }
3215 if compaction
3216 .queue
3217 .send(CompactionWork {
3218 cell: Arc::downgrade(handle),
3219 queued_at_mono_ms: asyncrt::mono_ms(),
3220 })
3221 .is_err()
3222 {
3223 compaction.queued.store(false, Ordering::SeqCst);
3224 }
3225}
3226
3227fn cancel_compaction(handle: &CellHandle) {
3228 let Some(compaction) = &handle.compaction else {
3229 return;
3230 };
3231 compaction.cancelled.store(true, Ordering::SeqCst);
3232 compaction.cancel.notify_waiters();
3233}
3234
3235fn start_compaction_loop(
3236 config: CompactionConfig,
3237 tasks: TaskGroup,
3238) -> mpsc::UnboundedSender<CompactionWork> {
3239 let (queue, mut work) = mpsc::unbounded_channel::<CompactionWork>();
3240 let slots = Arc::new(Semaphore::new(config.concurrency));
3241 let stop = tasks.stop_token();
3242 tasks
3243 .clone()
3244 .spawn_owned("ltx_compaction_dispatcher", async move {
3245 loop {
3246 let next = asyncrt::select_biased! {
3247 "a stop signal that ties queued compaction work starts no new worker";
3248 _ = stop.stopped() => break,
3249 next = work.recv() => next,
3250 };
3251 let Some(work) = next else { break };
3252 let permit = asyncrt::select_biased! {
3253 "a stop signal that ties slot acquisition starts no new compaction";
3254 _ = stop.stopped() => break,
3255 permit = slots.clone().acquire_owned() => permit,
3256 };
3257 let Ok(permit) = permit else {
3258 break;
3259 };
3260 let Some(cell) = work.cell.upgrade() else {
3261 continue;
3262 };
3263 let requeues = tasks.clone();
3264 tasks.spawn_owned("ltx_compaction_worker", async move {
3265 let _permit = permit;
3266 compact_cell(
3267 cell,
3268 work.queued_at_mono_ms,
3269 "threshold",
3270 true,
3271 Some(requeues),
3272 )
3273 .await;
3274 });
3275 }
3276 });
3277 queue
3278}
3279
3280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3281enum CompactionOutcome {
3282 Advanced,
3283 Current,
3284 Failed,
3285 Cancelled,
3286}
3287
3288async fn compact_cell(
3289 handle: CellHandle,
3290 queued_at_mono_ms: u64,
3291 trigger: &'static str,
3292 cancellable: bool,
3293 requeues: Option<TaskGroup>,
3294) -> CompactionOutcome {
3295 let Some(compaction) = &handle.compaction else {
3296 return CompactionOutcome::Current;
3297 };
3298 let cancelled = compaction.cancel.notified();
3299 tokio::pin!(cancelled);
3300 if cancellable && compaction.cancelled.load(Ordering::SeqCst) {
3301 compaction.queued.store(false, Ordering::SeqCst);
3302 return CompactionOutcome::Cancelled;
3303 }
3304 let _run = compaction.run.lock().await;
3305 if cancellable && compaction.cancelled.load(Ordering::SeqCst) {
3306 compaction.queued.store(false, Ordering::SeqCst);
3307 return CompactionOutcome::Cancelled;
3308 }
3309
3310 let source_position = || {
3311 (
3312 handle.durable_txid.load(Ordering::SeqCst),
3313 handle.percell_txid.load(Ordering::SeqCst),
3314 )
3315 };
3316 let source_at_start = source_position();
3317 let queue_ms = asyncrt::mono_ms().saturating_sub(queued_at_mono_ms);
3318 let started = asyncrt::mono_ms();
3319 let compactor = ReplicaCompactor::new(&compaction.client)
3320 .with_host(compaction.host.clone())
3321 .with_verification(true)
3322 .with_local_path(&compaction.local_path)
3323 .with_limits(COMPACTION_MAX_FILES, COMPACTION_MAX_INPUT_BYTES)
3324 .with_base(TXID(compaction.base_txid));
3325 let worker = compactor.compact_with_progress(1);
3326 tokio::pin!(worker);
3327 let result = if cancellable {
3328 asyncrt::select_biased! {
3329 "a cancellation that ties compaction completion discards the cancelled round";
3330 _ = &mut cancelled => None,
3331 result = &mut worker => Some(result),
3332 }
3333 } else {
3334 Some(worker.as_mut().await)
3335 };
3336
3337 #[cfg(all(test, celld_internal_tests))]
3338 {
3339 let pause = compaction.finish_pause.lock().unwrap().take();
3340 if let Some(pause) = pause {
3341 pause.reached.store(true, Ordering::SeqCst);
3342 pause.release.notified().await;
3343 }
3344 }
3345 let outcome = match result {
3346 Some(Ok(CompactionResult {
3347 output: Some(output),
3348 ..
3349 })) => {
3350 let info = output.info;
3351 compaction
3352 .compacted_txid
3353 .store(info.max_txid.0, Ordering::SeqCst);
3354 // The fold consumed the tail it saw; bytes that landed during it
3355 // count toward the next one only approximately, which delays it
3356 // by at most one window.
3357 compaction.pending_bytes.store(0, Ordering::SeqCst);
3358 info!(
3359 event = "ltx_compaction",
3360 trigger,
3361 cell = %compaction.cell,
3362 epoch = compaction.epoch,
3363 source_level = 0,
3364 destination_level = info.level,
3365 min_txid = info.min_txid.0,
3366 max_txid = info.max_txid.0,
3367 input_objects = output.input_files,
3368 input_bytes = output.input_bytes,
3369 local_input_objects = output.local_input_files,
3370 remote_input_objects = output.input_files - output.local_input_files,
3371 output_bytes = info.size,
3372 queue_ms,
3373 elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
3374 result = "ok",
3375 "compacted an additive LTX level"
3376 );
3377 CompactionOutcome::Advanced
3378 }
3379 Some(Ok(CompactionResult {
3380 covered_txid,
3381 output: None,
3382 })) => {
3383 compaction
3384 .compacted_txid
3385 .store(covered_txid.0, Ordering::SeqCst);
3386 info!(
3387 event = "ltx_compaction",
3388 trigger,
3389 cell = %compaction.cell,
3390 epoch = compaction.epoch,
3391 source_level = 0,
3392 destination_level = 1,
3393 queue_ms,
3394 elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
3395 result = "no_work",
3396 max_txid = covered_txid.0,
3397 "the additive LTX level has no visible source tail"
3398 );
3399 CompactionOutcome::Current
3400 }
3401 Some(Err(error)) => {
3402 warn!(
3403 event = "ltx_compaction",
3404 trigger,
3405 cell = %compaction.cell,
3406 epoch = compaction.epoch,
3407 source_level = 0,
3408 destination_level = 1,
3409 queue_ms,
3410 elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
3411 result = "error",
3412 %error,
3413 "additive LTX compaction failed"
3414 );
3415 CompactionOutcome::Failed
3416 }
3417 None => {
3418 info!(
3419 event = "ltx_compaction",
3420 trigger,
3421 cell = %compaction.cell,
3422 epoch = compaction.epoch,
3423 source_level = 0,
3424 destination_level = 1,
3425 queue_ms,
3426 elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
3427 result = "cancelled",
3428 "cancelled an additive LTX compaction"
3429 );
3430 CompactionOutcome::Cancelled
3431 }
3432 };
3433 compaction.queued.store(false, Ordering::SeqCst);
3434
3435 // A no-work result can mean that only old bundle metadata is missing.
3436 // Its truthful coverage stays behind durable_txid, so self-requeueing
3437 // would spin on the same empty listing. Preserve a publication that raced
3438 // this attempt: its queue request can lose the queued CAS. Read its two
3439 // watermarks after clearing queued, so a later publisher queues itself.
3440 let requeue = outcome == CompactionOutcome::Advanced
3441 || (outcome == CompactionOutcome::Current && source_position() != source_at_start);
3442 if requeue && !compaction.cancelled.load(Ordering::SeqCst) {
3443 // Pace consecutive rounds for one cell: a restart with a large tail
3444 // otherwise drains back-to-back for minutes. The pause matches the
3445 // round it follows (capped), so a cell compacts at half duty cycle
3446 // while the worker slot frees for other cells immediately. The owner
3447 // retains this delayed task, but the task does not retain the permit.
3448 let pause = Duration::from_millis(asyncrt::mono_ms().saturating_sub(started))
3449 .min(Duration::from_secs(2));
3450 let handle_ = Arc::downgrade(&handle);
3451 let Some(requeues) = requeues else {
3452 return outcome;
3453 };
3454 let stop = requeues.stop_token();
3455 requeues.spawn_owned("ltx_compaction_requeue", async move {
3456 asyncrt::select_biased! {
3457 "a stop signal that ties the requeue pause prevents another compaction round";
3458 _ = stop.stopped() => return,
3459 _ = asyncrt::sleep(pause) => {},
3460 }
3461 let Some(handle_) = handle_.upgrade() else {
3462 return;
3463 };
3464 let durable_txid = handle_.durable_txid.load(Ordering::SeqCst);
3465 maybe_queue_compaction(&handle_, durable_txid);
3466 });
3467 }
3468 outcome
3469}
3470
3471fn compaction_config_from_env() -> anyhow::Result<Option<CompactionConfig>> {
3472 // On by default. A mixed fleet must set `0` until every node can read
3473 // v0.5.2 block objects. An old reader cannot take over a cell after its
3474 // first L1 publication.
3475 let enabled = crate::env_vars::flag("CELLD_LTX_COMPACTION", true)?;
3476 if !enabled {
3477 return Ok(None);
3478 }
3479
3480 let min_txids = crate::env_vars::with_default("CELLD_LTX_COMPACTION_MIN_TXIDS", 256)?;
3481 let min_mb: u64 = crate::env_vars::with_default("CELLD_LTX_COMPACTION_MIN_MB", 32)?;
3482 let concurrency = crate::env_vars::with_default("CELLD_LTX_COMPACTIONS", 2)?;
3483 anyhow::ensure!(
3484 min_mb > 0 && min_mb << 20 <= COMPACTION_MAX_INPUT_BYTES,
3485 "CELLD_LTX_COMPACTION_MIN_MB must be between 1 and {}",
3486 COMPACTION_MAX_INPUT_BYTES >> 20
3487 );
3488 anyhow::ensure!(
3489 min_txids >= 2,
3490 "CELLD_LTX_COMPACTION_MIN_TXIDS must be at least 2"
3491 );
3492 anyhow::ensure!(concurrency > 0, "CELLD_LTX_COMPACTIONS must be positive");
3493 Ok(Some(CompactionConfig {
3494 min_txids: min_txids as u64,
3495 min_bytes: min_mb << 20,
3496 concurrency,
3497 }))
3498}
3499
3500/// The node's background sync loop: wake on a dirty cell (or a slow tick) and
3501/// launch a sync for every cell whose committed position runs ahead of its
3502/// durable one. Each cell's sync is an independent, self-rescheduling task —
3503/// the loop does *not* wait for the batch to finish — so one slow cell's upload
3504/// never stalls the others (a cell keeps its own cadence up to the concurrency
3505/// bound). A cell's writes reported between its syncs still clear on one upload:
3506/// the batching win, without the cross-cell head-of-line blocking.
3507async fn sync_loop(
3508 cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
3509 dirty: Arc<Notify>,
3510 slots: Arc<Semaphore>,
3511 registration: Arc<Mutex<RegistrationState>>,
3512 stop: StopToken,
3513 sync_tasks: TaskGroup,
3514 flush_ms: u64,
3515) {
3516 loop {
3517 asyncrt::select_biased! {
3518 "a stop signal that ties a sync-loop wake prevents another cell scan";
3519 _ = stop.stopped() => break,
3520 _ = async {
3521 asyncrt::select_biased! {
3522 "a dirty notification wins a tie with the fallback tick to retain wake order";
3523 _ = dirty.notified() => {},
3524 _ = asyncrt::sleep(Duration::from_millis(25)) => {},
3525 }
3526 } => {},
3527 }
3528 if stop.is_stopped() {
3529 break;
3530 }
3531 // The upload-cadence dial. With a healthy shipper installed, acks
3532 // ride the followers, so uploads become tiering and are PACED: an
3533 // immediate upload would hold the replica mutex for a bucket round
3534 // trip and the ship capture would queue behind it, putting the
3535 // bucket back on the ack path — the lab measured exactly that.
3536 // Without a shipper (or degraded), uploads run immediately: they
3537 // are the ack path again.
3538 let registered = registered_durability(&registration);
3539 let paced = flush_ms > 0
3540 && registered
3541 .as_ref()
3542 .is_some_and(|targets| targets.shipper.active());
3543 // With an active bundle sink, the bundle loop owns paced tiering
3544 // entirely — one PUT per node-flush instead of one per cell. This
3545 // loop then serves only the unpaced (degraded) mode and the direct
3546 // sync_wait callers, which are the drain points.
3547 let bundling = paced
3548 && registered
3549 .as_ref()
3550 .is_some_and(|targets| targets.manager.bundle_active());
3551 let now = asyncrt::wall_ms().max(0) as u64;
3552 let work: Vec<CellHandle> = {
3553 let map = cells.lock().unwrap();
3554 map.values()
3555 .filter(|c| {
3556 c.req_seq.load(Ordering::SeqCst) > c.synced_seq.load(Ordering::SeqCst)
3557 && !bundling
3558 && (!paced
3559 || now.saturating_sub(c.last_sync_ms.load(Ordering::SeqCst))
3560 >= flush_ms)
3561 })
3562 .cloned()
3563 .collect()
3564 };
3565 for cell in work {
3566 // Claim the cell; skip if a sync is already in flight for it.
3567 if cell
3568 .syncing
3569 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
3570 .is_err()
3571 {
3572 continue;
3573 }
3574 let slots = slots.clone();
3575 let dirty = dirty.clone();
3576 let worker_stop = stop.clone();
3577 sync_tasks.spawn_owned("ltx_cell_sync", async move {
3578 // Keep syncing this cell while it stays dirty, rather than
3579 // notifying the main loop to re-scan every completion — that made
3580 // the loop wake O(cells) times and starved throughput as cells
3581 // accumulated. This is not a busy loop: each iteration awaits an
3582 // object-store upload (~one round-trip). A *failed* sync would
3583 // not, so it backs off, keeping the only tight iterations the
3584 // ones that actually uploaded.
3585 loop {
3586 if worker_stop.is_stopped() {
3587 break;
3588 }
3589 let ok = {
3590 let _permit = slots.acquire().await;
3591 sync_cell(cell.clone()).await
3592 };
3593 // Registry removal closes the replica while this owned
3594 // task can still own the Cell. A closed slot cannot become
3595 // dirty again, so stop instead of retrying it forever.
3596 if ok.is_none() {
3597 break;
3598 }
3599 if cell.req_seq.load(Ordering::SeqCst) <= cell.synced_seq.load(Ordering::SeqCst)
3600 {
3601 break;
3602 }
3603 // Under pacing, one upload per wake: the next round waits
3604 // for the flush interval instead of re-syncing here.
3605 if paced {
3606 break;
3607 }
3608 if ok != Some(true) {
3609 asyncrt::select_biased! {
3610 "a stop signal that ties retry backoff prevents another sync attempt";
3611 _ = worker_stop.stopped() => break,
3612 _ = asyncrt::sleep(Duration::from_millis(50)) => {},
3613 }
3614 }
3615 }
3616 cell.syncing.store(false, Ordering::SeqCst);
3617 // A write landing in the clear window is picked up next tick;
3618 // nudge the loop so it does not wait the full interval.
3619 if !worker_stop.is_stopped()
3620 && cell.req_seq.load(Ordering::SeqCst) > cell.synced_seq.load(Ordering::SeqCst)
3621 {
3622 dirty.notify_one();
3623 }
3624 });
3625 }
3626 }
3627}
3628
3629/// The bundle loop: paced like the per-cell tiering it replaces, but the
3630/// unit is the node, not the cell. Every dirty cell's captured L0 segments
3631/// go up as ONE object per flush interval — the Class A collapse — and the
3632/// per-cell prefixes stay untouched until a drain point needs them. The
3633/// crediting mirrors sync_cell: `durable_txid` means bucket-covered,
3634/// whether by a per-cell object or a bundle row; the replica's own
3635/// position deliberately does NOT advance, so the direct sync_wait drain
3636/// still knows exactly which frames lack per-cell objects.
3637async fn bundle_loop(
3638 cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
3639 registration: Arc<Mutex<RegistrationState>>,
3640 stop: StopToken,
3641 flush_ms: u64,
3642) {
3643 if flush_ms == 0 {
3644 return;
3645 }
3646 let mut tick = asyncrt::interval(Duration::from_millis(flush_ms));
3647 tick.set_missed_tick_behavior(asyncrt::MissedTickBehavior::Delay);
3648 loop {
3649 asyncrt::select_biased! {
3650 "a stop signal that ties the bundle tick prevents another bucket flush";
3651 _ = stop.stopped() => break,
3652 _ = tick.tick() => {},
3653 }
3654 let installed = registered_durability(&registration).map(|targets| targets.manager.clone());
3655 let Some(active) = installed.filter(|sink| sink.bundle_active()) else {
3656 continue;
3657 };
3658 let work: Vec<((String, u64), CellHandle)> = {
3659 let map = cells.lock().unwrap();
3660 map.iter()
3661 .filter(|(_, cell)| {
3662 cell.req_seq.load(Ordering::SeqCst) > cell.synced_seq.load(Ordering::SeqCst)
3663 })
3664 .map(|(key, cell)| (key.clone(), cell.clone()))
3665 .collect()
3666 };
3667 if work.is_empty() {
3668 continue;
3669 }
3670 type Credits = Vec<(CellHandle, u64, u64)>;
3671 let (entries, credits): (Vec<celld_ltx::bundle::BundleEntry>, Credits) =
3672 asyncrt::blocking(move || {
3673 let mut entries = Vec::new();
3674 let mut credits = Vec::new();
3675 for ((cell, epoch), handle) in work {
3676 let tickets = handle.req_seq.load(Ordering::SeqCst);
3677 note_capture(&handle, tickets);
3678 let mut replica = handle.replica.lock().unwrap();
3679 let Some(db) = managed_db_mut(&mut replica) else {
3680 continue;
3681 };
3682 if db.sync().is_err() {
3683 continue;
3684 }
3685 let Ok(pos) = db.pos() else { continue };
3686 let from = handle.durable_txid.load(Ordering::SeqCst) + 1;
3687 let mut complete = true;
3688 for txid in from..=pos.txid.0 {
3689 match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
3690 Ok(bytes) => entries.push(celld_ltx::bundle::BundleEntry {
3691 cell: cell.clone(),
3692 cell_epoch: epoch,
3693 txid,
3694 bytes,
3695 }),
3696 Err(error) => {
3697 warn!(%error, txid, "read staged l0 for bundle failed");
3698 complete = false;
3699 break;
3700 }
3701 }
3702 }
3703 drop(replica);
3704 if complete {
3705 credits.push((handle, tickets, pos.txid.0));
3706 }
3707 }
3708 (entries, credits)
3709 })
3710 .await
3711 .unwrap_or_default();
3712 if credits.is_empty() {
3713 continue;
3714 }
3715 let count = entries.len();
3716 if entries.is_empty() || active.put_bundle(entries).await {
3717 if count > 0 {
3718 info!(
3719 event = "log_bundle_flush",
3720 entries = count,
3721 cells = credits.len(),
3722 "flushed a bundle"
3723 );
3724 }
3725 for (handle, tickets, position) in credits {
3726 handle.durable_txid.fetch_max(position, Ordering::SeqCst);
3727 handle.synced_seq.fetch_max(tickets, Ordering::SeqCst);
3728 handle
3729 .last_sync_ms
3730 .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
3731 // Bundle credits also queue the overlay compactor.
3732 maybe_queue_compaction(&handle, position);
3733 note_proof(&handle);
3734 handle.ready.notify_waiters();
3735 }
3736 }
3737 }
3738}
3739
3740/// The log tier's group-commit loop, `sync_loop`'s fleet twin: wake on a
3741/// gate ticket, capture every dirty cell's new L0 segments in one blocking
3742/// pass, ship them as one batch, and credit the tickets the capture covered.
3743/// Ordered member lanes keep each follower's pipelined fragment contiguous,
3744/// and nothing on this path waits for the bucket.
3745/// Advance a lap clock and return the elapsed microseconds — the ship
3746/// loop's closed-book accounting primitive: every await and every stretch
3747/// of work between two laps lands in exactly one bucket, so the buckets
3748/// plus the residual sum to the loop's wall time.
3749fn lap_us(lap: &mut u64) -> u64 {
3750 let now = asyncrt::mono_us();
3751 let delta = now.saturating_sub(*lap);
3752 *lap = now;
3753 delta
3754}
3755
3756async fn ship_loop(
3757 cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
3758 dirty_ship: Arc<Notify>,
3759 registration: Arc<Mutex<RegistrationState>>,
3760 stop: StopToken,
3761 group_commit_ms: u64,
3762) {
3763 // The truncation ledger is a core decision
3764 // (celld_logic::log_tier::ShipLedger): outstanding batches carry the
3765 // cells and top TXIDs, a batch is covered once every cell's durable
3766 // position passes its top TXID — bundle credits do this within a
3767 // flush interval — and the covered watermark rides the next append as
3768 // the followers' truncate_to. This is what bounds follower disks, and
3769 // the ledger's epoch reset is what keeps a stale watermark from
3770 // truncating a fresh fragment.
3771 let mut ledger: celld_logic::log_tier::ShipLedger<Vec<(CellHandle, u64)>> =
3772 celld_logic::log_tier::ShipLedger::default();
3773 // Rounds in flight, completed strictly in submission order. A later
3774 // round's ack waits here until every earlier round has credited or
3775 // failed, so a gate never releases past an unresolved earlier round.
3776 let mut inflight: futures_util::stream::FuturesOrdered<
3777 std::pin::Pin<Box<dyn std::future::Future<Output = ShipRound> + Send>>,
3778 > = futures_util::stream::FuturesOrdered::new();
3779 let mut current: Option<Arc<dyn Shipper>> = None;
3780 let mut current_epoch = None;
3781 let mut last_submit = asyncrt::mono_ms();
3782 const CAPTURE_WORKERS: usize = 8;
3783 // The loop's own time ledger: idle (nothing to do), stall (admission
3784 // or depth closed, waiting on a round), apply, scan, capture wall,
3785 // submit. Emitted cumulatively about once a second; wall minus the
3786 // sum is the loop's untracked residual and must stay small.
3787 let mut lap = asyncrt::mono_us();
3788 let (mut idle_us, mut stall_us, mut apply_us, mut scan_us) = (0_u64, 0_u64, 0_u64, 0_u64);
3789 let (mut group_us, mut capture_us, mut submit_us) = (0_u64, 0_u64, 0_u64);
3790 let mut loop_rounds = 0_u64;
3791 let mut ledger_emit = asyncrt::mono_us();
3792 'shipping: loop {
3793 if asyncrt::mono_us().saturating_sub(ledger_emit) >= 1_000_000 {
3794 info!(
3795 event = "log_ship_loop",
3796 wall_us = asyncrt::mono_us().saturating_sub(ledger_emit),
3797 idle_us,
3798 stall_us,
3799 apply_us,
3800 scan_us,
3801 group_us,
3802 capture_us,
3803 submit_us,
3804 rounds = loop_rounds,
3805 "ship loop time ledger"
3806 );
3807 ledger_emit = asyncrt::mono_us();
3808 idle_us = 0;
3809 stall_us = 0;
3810 apply_us = 0;
3811 scan_us = 0;
3812 group_us = 0;
3813 capture_us = 0;
3814 submit_us = 0;
3815 loop_rounds = 0;
3816 }
3817 if inflight.is_empty() {
3818 let _ = lap_us(&mut lap);
3819 asyncrt::select_biased! {
3820 "a stop signal that ties an idle ship-loop wake prevents another scan";
3821 _ = stop.stopped() => break 'shipping,
3822 _ = async {
3823 asyncrt::select_biased! {
3824 "a dirty notification wins a tie with the fallback tick to retain wake order";
3825 _ = dirty_ship.notified() => {},
3826 _ = asyncrt::sleep(Duration::from_millis(25)) => {},
3827 }
3828 } => {},
3829 }
3830 idle_us += lap_us(&mut lap);
3831 } else {
3832 let depth = current
3833 .as_ref()
3834 .map_or(1, |shipper| shipper.pipeline().max(1));
3835 let admitted = current.as_ref().is_none_or(|shipper| shipper.admit());
3836 if inflight.len() >= depth || !admitted {
3837 let _ = lap_us(&mut lap);
3838 let round = asyncrt::select_biased! {
3839 "a stop signal that ties a completed ship round prevents another ledger update";
3840 _ = stop.stopped() => break 'shipping,
3841 round = futures_util::StreamExt::next(&mut inflight) => round,
3842 };
3843 stall_us += lap_us(&mut lap);
3844 if let Some(round) = round {
3845 if !apply_round(&mut ledger, round) {
3846 inflight = futures_util::stream::FuturesOrdered::new();
3847 reset_submitted(&cells);
3848 }
3849 }
3850 apply_us += lap_us(&mut lap);
3851 continue;
3852 }
3853 let _ = lap_us(&mut lap);
3854 let event = asyncrt::select_biased! {
3855 "a stop signal that ties active shipping work ends the ship loop first";
3856 _ = stop.stopped() => break 'shipping,
3857 event = async {
3858 asyncrt::select_biased! {
3859 "a completed ship round wins a tie so its ordered ledger update runs first";
3860 round = futures_util::StreamExt::next(&mut inflight) => {
3861 futures_util::future::Either::Left(round)
3862 },
3863 _ = async {
3864 asyncrt::select_biased! {
3865 "a dirty notification wins a tie with the fallback tick to retain wake order";
3866 _ = dirty_ship.notified() => {},
3867 _ = asyncrt::sleep(Duration::from_millis(25)) => {},
3868 }
3869 } => futures_util::future::Either::Right(()),
3870 }
3871 } => event,
3872 };
3873 idle_us += lap_us(&mut lap);
3874 if let futures_util::future::Either::Left(round) = event {
3875 if let Some(round) = round {
3876 if !apply_round(&mut ledger, round) {
3877 inflight = futures_util::stream::FuturesOrdered::new();
3878 reset_submitted(&cells);
3879 }
3880 }
3881 apply_us += lap_us(&mut lap);
3882 continue;
3883 }
3884 }
3885 // Producer grouping shares a transaction within one Queue. This wait
3886 // also gathers writes from different Queues into one fleet capture.
3887 // Only pending Queue writes trigger it; other cell classes alone do
3888 // not add the wait. This preliminary scan is only a delay decision;
3889 // the authoritative work and shipper epoch are read after the wait.
3890 let queue_pending = if group_commit_ms == 0 {
3891 false
3892 } else {
3893 let map = cells.lock().unwrap();
3894 map.iter().any(|((cell, _), handle)| {
3895 cell.split_once(':')
3896 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS)
3897 && {
3898 let req = handle.req_seq.load(Ordering::SeqCst);
3899 req > handle.submitted_seq.load(Ordering::SeqCst)
3900 && req > handle.synced_seq.load(Ordering::SeqCst)
3901 }
3902 })
3903 };
3904 if queue_pending {
3905 let _ = lap_us(&mut lap);
3906 asyncrt::select_biased! {
3907 "a stop signal that ties the group-commit window prevents another capture";
3908 _ = stop.stopped() => break 'shipping,
3909 _ = asyncrt::sleep(Duration::from_millis(group_commit_ms)) => {},
3910 }
3911 group_us += lap_us(&mut lap);
3912 }
3913 let installed = registered_durability(&registration).map(|targets| targets.shipper.clone());
3914 let Some(active) = installed.filter(|shipper| shipper.active()) else {
3915 // The shipper is gone or degraded: outstanding rounds can never
3916 // credit under it, so they die uncredited — conservative, the
3917 // gates ride the bucket proof.
3918 if !inflight.is_empty() {
3919 inflight = futures_util::stream::FuturesOrdered::new();
3920 reset_submitted(&cells);
3921 }
3922 current = None;
3923 current_epoch = None;
3924 continue;
3925 };
3926 let capture_epoch = active.epoch();
3927 if current_epoch != Some(capture_epoch) {
3928 // An ensemble swap orphans the old shipper's rounds: their
3929 // credits belong to the retired epoch and must not apply.
3930 if !inflight.is_empty() {
3931 inflight = futures_util::stream::FuturesOrdered::new();
3932 reset_submitted(&cells);
3933 }
3934 current = Some(active.clone());
3935 current_epoch = Some(capture_epoch);
3936 }
3937 ledger.observe_epoch(capture_epoch);
3938 let work: Vec<((String, u64), CellHandle)> = {
3939 let map = cells.lock().unwrap();
3940 map.iter()
3941 .filter(|(_, cell)| {
3942 let req = cell.req_seq.load(Ordering::SeqCst);
3943 req > cell.submitted_seq.load(Ordering::SeqCst)
3944 && req > cell.synced_seq.load(Ordering::SeqCst)
3945 })
3946 .map(|(key, cell)| (key.clone(), cell.clone()))
3947 .collect()
3948 };
3949 scan_us += lap_us(&mut lap);
3950 if work.is_empty() {
3951 continue;
3952 }
3953 let round = asyncrt::mono_ms();
3954 // Capture fans out across cells: each chunk syncs and reads its
3955 // cells exactly as the serial walk did — per-cell contiguity and
3956 // the completeness check are per cell, so cross-cell order is
3957 // free — and the fan-out is what keeps a network disk's per-cell
3958 // sync latency out of the round's serial cost (#140, stage 2).
3959 let workers = work.len().clamp(1, CAPTURE_WORKERS);
3960 let mut chunks: Vec<Vec<((String, u64), CellHandle)>> =
3961 (0..workers).map(|_| Vec::new()).collect();
3962 for (index, item) in work.into_iter().enumerate() {
3963 chunks[index % workers].push(item);
3964 }
3965 type Credits = Vec<(CellHandle, u64, u64)>;
3966 let spawned = asyncrt::mono_us();
3967 let captures = futures_util::future::join_all(chunks.into_iter().map(|chunk| {
3968 asyncrt::blocking(move || {
3969 // The closed-book ledger: pool_wait is the blocking-pool
3970 // queue delay before this chunk ran at all; phases below
3971 // sum to the chunk's busy time.
3972 let pool_wait_us = asyncrt::mono_us().saturating_sub(spawned);
3973 let mut entries = Vec::new();
3974 let mut credits = Vec::new();
3975 let mut sync_us = 0_u64;
3976 let mut lock_us = 0_u64;
3977 let mut read_us = 0_u64;
3978 let mut timing = celld_ltx::db::SyncTiming::default();
3979 let mut snap_reasons = [0_u32; 9];
3980 let mut read_kinds = [0_u32; 4];
3981 let mut read_bytes = 0_u64;
3982 // The null-work probe: eight clock reads cost well under a
3983 // microsecond of intrinsic work, so this value is the
3984 // scheduler's preemption tax on this worker — the
3985 // discriminator between a phase that is slow and a phase
3986 // that was interrupted.
3987 let probe_started = asyncrt::mono_us();
3988 for _ in 0..8 {
3989 std::hint::black_box(asyncrt::mono_us());
3990 }
3991 let probe_us = asyncrt::mono_us().saturating_sub(probe_started);
3992 for ((cell, epoch), handle) in chunk {
3993 // Tickets taken before the capture are covered by it —
3994 // the same discipline as sync_cell.
3995 let tickets = handle.req_seq.load(Ordering::SeqCst);
3996 note_capture(&handle, tickets);
3997 let lock_started = asyncrt::mono_us();
3998 let mut replica = handle.replica.lock().unwrap();
3999 let sync_started = asyncrt::mono_us();
4000 lock_us += sync_started.saturating_sub(lock_started);
4001 let Some(db) = managed_db_mut(&mut replica) else {
4002 continue;
4003 };
4004 let synced = db.sync();
4005 sync_us += asyncrt::mono_us().saturating_sub(sync_started);
4006 let cell_timing = db.last_sync_timing();
4007 timing.prepare_us += cell_timing.prepare_us;
4008 timing.verify_us += cell_timing.verify_us;
4009 timing.encode_write_us += cell_timing.encode_write_us;
4010 timing.fsync_us += cell_timing.fsync_us;
4011 timing.checkpoint_us += cell_timing.checkpoint_us;
4012 timing.checkpoint_runs += cell_timing.checkpoint_runs;
4013 timing.checkpoint_wal_frames += cell_timing.checkpoint_wal_frames;
4014 timing.checkpoint_backfilled += cell_timing.checkpoint_backfilled;
4015 timing.checkpoint_busy += cell_timing.checkpoint_busy;
4016 timing.checkpoint_busy_errors += cell_timing.checkpoint_busy_errors;
4017 timing.checkpoint_restarts += cell_timing.checkpoint_restarts;
4018 timing.pos_us += cell_timing.pos_us;
4019 timing.wal_read_us += cell_timing.wal_read_us;
4020 timing.map_collect_us += cell_timing.map_collect_us;
4021 timing.ltx_encode_us += cell_timing.ltx_encode_us;
4022 timing.file_write_us += cell_timing.file_write_us;
4023 timing.wal_len_bytes += cell_timing.wal_len_bytes;
4024 if cell_timing.snapshot {
4025 timing.snapshot = true;
4026 snap_reasons[cell_timing.snapshot_reason.min(8) as usize] += 1;
4027 }
4028 read_kinds[cell_timing.wal_read_kind.min(3) as usize] += 1;
4029 read_bytes += cell_timing.wal_read_bytes;
4030 if synced.is_err() {
4031 continue;
4032 }
4033 let Ok(pos) = db.pos() else { continue };
4034 let from = handle.submitted_txid.load(Ordering::SeqCst) + 1;
4035 let mut complete = true;
4036 let read_started = asyncrt::mono_us();
4037 for txid in from..=pos.txid.0 {
4038 match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
4039 Ok(bytes) => entries.push(ShipEntry {
4040 cell: cell.clone(),
4041 epoch,
4042 txid,
4043 bytes,
4044 }),
4045 // A pruned L0 the bucket already holds is not a
4046 // gap the followers need filled; anything else
4047 // leaves the cell uncredited for this round.
4048 Err(_) if txid <= handle.durable_txid.load(Ordering::SeqCst) => {}
4049 Err(_) => {
4050 complete = false;
4051 break;
4052 }
4053 }
4054 }
4055 read_us += asyncrt::mono_us().saturating_sub(read_started);
4056 drop(replica);
4057 if complete {
4058 credits.push((handle, tickets, pos.txid.0));
4059 }
4060 }
4061 (
4062 entries,
4063 credits,
4064 sync_us,
4065 lock_us,
4066 read_us,
4067 pool_wait_us,
4068 timing,
4069 snap_reasons,
4070 read_kinds,
4071 read_bytes,
4072 probe_us,
4073 )
4074 })
4075 }))
4076 .await;
4077 let mut entries: Vec<ShipEntry> = Vec::new();
4078 let mut credits: Credits = Vec::new();
4079 let mut sync_us_total = 0_u64;
4080 let mut lock_us_total = 0_u64;
4081 let mut read_us_total = 0_u64;
4082 let mut pool_wait_us_max = 0_u64;
4083 let mut timing_total = celld_ltx::db::SyncTiming::default();
4084 let mut snap_reason_totals = [0_u32; 9];
4085 let mut read_kind_totals = [0_u32; 4];
4086 let mut read_bytes_total = 0_u64;
4087 let mut probe_us_max = 0_u64;
4088 for capture in captures {
4089 let (
4090 chunk_entries,
4091 chunk_credits,
4092 chunk_sync_us,
4093 chunk_lock_us,
4094 chunk_read_us,
4095 chunk_pool_wait_us,
4096 chunk_timing,
4097 chunk_snap_reasons,
4098 chunk_read_kinds,
4099 chunk_read_bytes,
4100 chunk_probe_us,
4101 ) = capture.unwrap_or_default();
4102 entries.extend(chunk_entries);
4103 credits.extend(chunk_credits);
4104 sync_us_total += chunk_sync_us;
4105 lock_us_total += chunk_lock_us;
4106 read_us_total += chunk_read_us;
4107 pool_wait_us_max = pool_wait_us_max.max(chunk_pool_wait_us);
4108 timing_total.prepare_us += chunk_timing.prepare_us;
4109 timing_total.verify_us += chunk_timing.verify_us;
4110 timing_total.encode_write_us += chunk_timing.encode_write_us;
4111 timing_total.fsync_us += chunk_timing.fsync_us;
4112 timing_total.checkpoint_us += chunk_timing.checkpoint_us;
4113 timing_total.checkpoint_runs += chunk_timing.checkpoint_runs;
4114 timing_total.checkpoint_wal_frames += chunk_timing.checkpoint_wal_frames;
4115 timing_total.checkpoint_backfilled += chunk_timing.checkpoint_backfilled;
4116 timing_total.checkpoint_busy += chunk_timing.checkpoint_busy;
4117 timing_total.checkpoint_busy_errors += chunk_timing.checkpoint_busy_errors;
4118 timing_total.checkpoint_restarts += chunk_timing.checkpoint_restarts;
4119 timing_total.pos_us += chunk_timing.pos_us;
4120 timing_total.wal_read_us += chunk_timing.wal_read_us;
4121 timing_total.map_collect_us += chunk_timing.map_collect_us;
4122 timing_total.ltx_encode_us += chunk_timing.ltx_encode_us;
4123 timing_total.file_write_us += chunk_timing.file_write_us;
4124 timing_total.wal_len_bytes += chunk_timing.wal_len_bytes;
4125 if chunk_timing.snapshot {
4126 timing_total.snapshot = true;
4127 }
4128 for (slot, count) in snap_reason_totals.iter_mut().zip(chunk_snap_reasons) {
4129 *slot += count;
4130 }
4131 for (slot, count) in read_kind_totals.iter_mut().zip(chunk_read_kinds) {
4132 *slot += count;
4133 }
4134 read_bytes_total += chunk_read_bytes;
4135 probe_us_max = probe_us_max.max(chunk_probe_us);
4136 }
4137 if credits.is_empty() {
4138 continue;
4139 }
4140 ledger.advance(|cells| {
4141 cells
4142 .iter()
4143 .all(|(handle, txid)| handle.durable_txid.load(Ordering::SeqCst) >= *txid)
4144 });
4145 let covered_seq = ledger.covered_seq();
4146 let captured_ms = asyncrt::mono_ms().saturating_sub(round);
4147 capture_us += lap_us(&mut lap);
4148 let entry_count = entries.len();
4149 let byte_count = entries.iter().map(|entry| entry.bytes.len()).sum::<usize>();
4150 let since_last = asyncrt::mono_ms().saturating_sub(last_submit);
4151 // No entries can mean that an earlier in-flight round owns every
4152 // frame, not only that the bucket already covers them. Queue the
4153 // empty credit through the same ordered pipeline, so an earlier
4154 // failure discards it instead of releasing an unproved fleet ticket.
4155 let append = if entries.is_empty() {
4156 None
4157 } else {
4158 last_submit = asyncrt::mono_ms();
4159 // The shipper's synchronous prefix runs HERE, at submission: the
4160 // sequence range and every member lane enqueue happen before the
4161 // future is queued, so pipelined rounds stay ordered per member.
4162 Some(active.ship_at_epoch(capture_epoch, entries, covered_seq))
4163 };
4164 for (handle, tickets, position) in &credits {
4165 handle.submitted_txid.fetch_max(*position, Ordering::SeqCst);
4166 handle.submitted_seq.fetch_max(*tickets, Ordering::SeqCst);
4167 }
4168 let submitted = asyncrt::mono_ms();
4169 inflight.push_back(Box::pin(async move {
4170 ShipRound {
4171 completion: match append {
4172 Some(append) => ShipRoundCompletion::Append(append.await),
4173 None => ShipRoundCompletion::OrderedEmpty,
4174 },
4175 credits,
4176 covered_seq,
4177 entries: entry_count,
4178 bytes: byte_count,
4179 capture_ms: captured_ms,
4180 sync_ms: sync_us_total / 1000,
4181 lock_ms: lock_us_total / 1000,
4182 gap_ms: since_last,
4183 submitted,
4184 read_us: read_us_total,
4185 pool_wait_us: pool_wait_us_max,
4186 sync_timing: timing_total,
4187 snap_reasons: snap_reason_totals,
4188 read_kinds: read_kind_totals,
4189 read_bytes: read_bytes_total,
4190 probe_us: probe_us_max,
4191 }
4192 }));
4193 submit_us += lap_us(&mut lap);
4194 loop_rounds += 1;
4195 }
4196}
4197
4198/// The proof carried by one ordered ship-loop round. `FuturesOrdered` holds an
4199/// `OrderedEmpty` no-op behind each earlier append, and a failed append
4200/// discards the complete later tail before the no-op can apply.
4201enum ShipRoundCompletion {
4202 Append(ShipCompletion),
4203 OrderedEmpty,
4204}
4205
4206/// One pipelined round's completion, applied strictly in submission order.
4207struct ShipRound {
4208 completion: ShipRoundCompletion,
4209 credits: Vec<(CellHandle, u64, u64)>,
4210 covered_seq: u64,
4211 entries: usize,
4212 bytes: usize,
4213 capture_ms: u64,
4214 /// Worker-summed per-cell db.sync time inside the capture.
4215 sync_ms: u64,
4216 /// Worker-summed replica-lock wait inside the capture.
4217 lock_ms: u64,
4218 /// Time since the previous round's submission — the cadence.
4219 gap_ms: u64,
4220 submitted: u64,
4221 /// The closed-book capture interior, worker-summed per round:
4222 /// frame reads, the worst chunk's blocking-pool queue delay, and the
4223 /// per-phase split of every db.sync (the log-lazy-local-sync
4224 /// attribution ledger).
4225 read_us: u64,
4226 pool_wait_us: u64,
4227 sync_timing: celld_ltx::db::SyncTiming,
4228 snap_reasons: [u32; 9],
4229 read_kinds: [u32; 4],
4230 read_bytes: u64,
4231 probe_us: u64,
4232}
4233
4234/// Apply one completed round. `false` means the round failed: the caller
4235/// must discard every later in-flight round uncredited — their frames may
4236/// be durable on the followers, which is safe, but crediting them would
4237/// release gates past an unresolved earlier round.
4238fn apply_round(
4239 ledger: &mut celld_logic::log_tier::ShipLedger<Vec<(CellHandle, u64)>>,
4240 round: ShipRound,
4241) -> bool {
4242 let proof_last_seq = match &round.completion {
4243 ShipRoundCompletion::Append(completion) => {
4244 let Some(last_seq) = completion.last_seq() else {
4245 return false;
4246 };
4247 if last_seq > round.covered_seq {
4248 ledger.shipped(
4249 last_seq,
4250 round
4251 .credits
4252 .iter()
4253 .map(|(handle, _, position)| (handle.clone(), *position))
4254 .collect(),
4255 );
4256 }
4257 Some(last_seq)
4258 }
4259 // No append completed for this round. Its credits are safe because
4260 // the ordered queue first applied every earlier append, or because
4261 // the bucket already held the captured position. Do not invent a
4262 // fleet sequence for this credit.
4263 ShipRoundCompletion::OrderedEmpty => None,
4264 };
4265 info!(
4266 event = "log_ship_round",
4267 entries = round.entries,
4268 cells = round.credits.len(),
4269 bytes = round.bytes,
4270 capture_ms = round.capture_ms,
4271 sync_ms = round.sync_ms,
4272 lock_ms = round.lock_ms,
4273 gap_ms = round.gap_ms,
4274 ship_ms = asyncrt::mono_ms().saturating_sub(round.submitted),
4275 read_us = round.read_us,
4276 pool_wait_us = round.pool_wait_us,
4277 prep_us = round.sync_timing.prepare_us,
4278 verify_us = round.sync_timing.verify_us,
4279 encode_us = round.sync_timing.encode_write_us,
4280 fsync_us = round.sync_timing.fsync_us,
4281 ckpt_us = round.sync_timing.checkpoint_us,
4282 ckpt_n = round.sync_timing.checkpoint_runs,
4283 ckpt_frames = round.sync_timing.checkpoint_wal_frames,
4284 ckpt_done = round.sync_timing.checkpoint_backfilled,
4285 ckpt_busy = round.sync_timing.checkpoint_busy,
4286 ckpt_busy_err = round.sync_timing.checkpoint_busy_errors,
4287 ckpt_restart = round.sync_timing.checkpoint_restarts,
4288 pos_us = round.sync_timing.pos_us,
4289 wal_read_us = round.sync_timing.wal_read_us,
4290 map_collect_us = round.sync_timing.map_collect_us,
4291 ltx_encode_us = round.sync_timing.ltx_encode_us,
4292 file_write_us = round.sync_timing.file_write_us,
4293 wal_len_bytes = round.sync_timing.wal_len_bytes,
4294 snapshot = round.sync_timing.snapshot,
4295 snap_first = round.snap_reasons[1],
4296 snap_truncated = round.snap_reasons[2],
4297 snap_salt = round.snap_reasons[3],
4298 snap_lastpage = round.snap_reasons[4],
4299 snap_ckpt = round.snap_reasons[5],
4300 snap_boundary = round.snap_reasons[6],
4301 snap_other = round.snap_reasons[7],
4302 snap_prebarrier = round.snap_reasons[8],
4303 read_tail = round.read_kinds[0],
4304 read_snap = round.read_kinds[1],
4305 read_start = round.read_kinds[2],
4306 read_fallback = round.read_kinds[3],
4307 read_bytes = round.read_bytes,
4308 probe_us = round.probe_us,
4309 proof_last_seq = ?proof_last_seq,
4310 "shipped a log batch"
4311 );
4312 for (handle, tickets, position) in round.credits {
4313 #[cfg(all(test, celld_internal_tests))]
4314 handle.record_fleet_credit_for_world(tickets, position, proof_last_seq);
4315 handle.shipped_txid.fetch_max(position, Ordering::SeqCst);
4316 handle.shipped_seq.fetch_max(tickets, Ordering::SeqCst);
4317 note_proof(&handle);
4318 handle.ready.notify_waiters();
4319 }
4320 true
4321}
4322
4323/// Discarding a pipeline makes every uncredited range eligible for capture
4324/// again. The credited watermarks are monotone, so concurrent bucket progress
4325/// remains intact while a failed fleet tail rolls back.
4326fn reset_submitted(cells: &Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>) {
4327 for handle in cells.lock().unwrap().values() {
4328 handle
4329 .submitted_txid
4330 .store(handle.shipped_txid.load(Ordering::SeqCst), Ordering::SeqCst);
4331 handle
4332 .submitted_seq
4333 .store(handle.shipped_seq.load(Ordering::SeqCst), Ordering::SeqCst);
4334 }
4335}
4336
4337/// Node-level object-store config (no per-cell prefix). `build_store` on this
4338/// yields the one shared client; per-cell clients set only `path`.
4339fn node_config(
4340 bucket: &str,
4341 endpoint: Option<&str>,
4342 region: &str,
4343 credentials: Option<&StorageCredentials>,
4344) -> ObjectStoreConfig {
4345 let endpoint = endpoint.unwrap_or_default().to_string();
4346 // Static credentials come from the managed control plane when present,
4347 // else the `AWS_*` env the node already carries. Without this,
4348 // `build_store` sees empty keys and object_store walks the refreshable
4349 // chain instead: web identity, ECS task credentials, EKS Pod Identity,
4350 // then the instance credential provider, which off-EC2 sends unsigned
4351 // requests (R2 answers "404 page not found"). A node that carries none of
4352 // those variables still reaches that unsigned case, and a node that
4353 // carries some of them silently replicates under an identity the control
4354 // plane did not issue.
4355 let env = |key: &str| std::env::var(key).ok().filter(|value| !value.is_empty());
4356 let access_key_id = credentials
4357 .map(|c| c.access_key_id.clone())
4358 .filter(|value| !value.is_empty())
4359 .or_else(|| env("AWS_ACCESS_KEY_ID"))
4360 .unwrap_or_default();
4361 let secret_access_key = credentials
4362 .map(|c| c.secret_access_key.clone())
4363 .filter(|value| !value.is_empty())
4364 .or_else(|| env("AWS_SECRET_ACCESS_KEY"))
4365 .unwrap_or_default();
4366 // Temporary R2/STS credentials require the session token, or signing fails.
4367 let session_token = credentials
4368 .and_then(|c| c.session_token.clone())
4369 .filter(|value| !value.is_empty())
4370 .or_else(|| env("AWS_SESSION_TOKEN"))
4371 .unwrap_or_default();
4372 ObjectStoreConfig {
4373 bucket: bucket.to_string(),
4374 path: String::new(),
4375 region: region.to_string(),
4376 // A custom endpoint (R2/MinIO) uses path-style addressing, matching
4377 // `ObjectStoreConfig::from_url`'s default for non-AWS hosts.
4378 force_path_style: !endpoint.is_empty(),
4379 endpoint,
4380 access_key_id,
4381 secret_access_key,
4382 session_token,
4383 skip_verify: false,
4384 part_size: 0,
4385 timestamp_metadata_key: TimestampMetadataKey::default(),
4386 }
4387}
4388
4389fn production_ltx_host() -> LtxHost {
4390 execution_domain_ltx_host()
4391}
4392
4393#[cfg(celld_internal_tests)]
4394fn deterministic_ltx_host() -> LtxHost {
4395 execution_domain_ltx_host()
4396}
4397
4398fn execution_domain_ltx_host() -> LtxHost {
4399 let filesystem = asyncrt::fs();
4400 let age_filesystem = filesystem.clone();
4401 let read_filesystem = filesystem.clone();
4402 LtxHost::new(
4403 asyncrt::wall_ms,
4404 move |path| file_age(age_filesystem.as_ref(), path),
4405 move |path| {
4406 let filesystem = read_filesystem.clone();
4407 async move {
4408 asyncrt::blocking(move || filesystem.read(&path))
4409 .await
4410 .map_err(|error| std::io::Error::other(error.to_string()))?
4411 }
4412 },
4413 |job| async move {
4414 asyncrt::blocking(job)
4415 .await
4416 .map_err(|error| HostTaskError::new(error.to_string()))
4417 },
4418 )
4419 .with_filesystem(filesystem)
4420}
4421
4422fn file_age(filesystem: &dyn celld_ltx::FileSystem, path: &Path) -> std::io::Result<Duration> {
4423 let modified = filesystem.metadata(path)?.modified_unix_millis;
4424 Ok(Duration::from_millis(
4425 asyncrt::wall_ms().saturating_sub(modified).max(0) as u64,
4426 ))
4427}
4428
4429fn close_replica_or_warn(handle: &CellHandle, cell: &str, epoch: u64) {
4430 if let Err(error) = close_replica(handle) {
4431 warn!(cell, epoch, %error, "close managed replica failed during removal");
4432 }
4433}
4434
4435fn managed_db_mut(replica: &mut Option<Replica<ObjectStoreClient>>) -> Option<&mut celld_ltx::Db> {
4436 replica.as_mut()?.db_mut()
4437}
4438
4439fn close_replica_for_reload(handle: &CellHandle, cell: &str, epoch: u64) -> anyhow::Result<()> {
4440 close_replica(handle)
4441 .map_err(|error| anyhow!("close managed replica for {cell} epoch {epoch}: {error}"))
4442}
4443
4444/// Stop new file users and close the managed database before its live path is
4445/// renamed or retained for another process. An upload or a compaction can keep
4446/// the `Cell` alive after registry removal, but none can keep the database once
4447/// this function takes it through the same mutex used by every capture.
4448fn close_replica(handle: &CellHandle) -> anyhow::Result<()> {
4449 cancel_compaction(handle);
4450 let replica = handle.replica.lock().unwrap().take();
4451 if let Some(db) = replica.and_then(Replica::into_db) {
4452 db.close().map_err(|error| anyhow!(error))?;
4453 }
4454 Ok(())
4455}
4456
4457impl Drop for LtxRepl {
4458 fn drop(&mut self) {
4459 self.shutdown_local_fallback();
4460 }
4461}
4462
4463#[cfg(celld_internal_tests)]
4464include!(env!("CELLD_INTERNAL_LTX_REPL_OBSERVERS"));