| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! v0 of the in-fleet replicated log tier (`CELLD_DURABILITY=fleet`). |
| 4 | //! |
| 5 | //! Each node streams the per-cell L0 LTX segments it has captured but not |
| 6 | //! yet uploaded to a small follower ensemble over the signed peer |
| 7 | //! transport. A write acknowledges when every member holds its segment on |
| 8 | //! disk — write-all, ack-all — or when the ordinary bucket upload proves |
| 9 | //! it first, whichever wins. The bucket upload path is unchanged and |
| 10 | //! remains the tiering mechanism, so node-log recovery re-creates exactly |
| 11 | //! the objects the dead leader would have uploaded and every per-cell |
| 12 | //! restore and compaction mechanism stays byte-for-byte as it is. |
| 13 | //! |
| 14 | //! `log/<node>.json` is the CAS-guarded root of truth for the ensemble and |
| 15 | //! the log epoch. It is created before the node's first fleet-durable ack |
| 16 | //! and never deleted, so a takeover that finds no record may treat the |
| 17 | //! bucket as complete. The decisions are `celld_logic::log_tier`; this |
| 18 | //! module is their executor. |
| 19 | //! |
| 20 | //! v0 limits, deliberate: entries travel as base64 JSON; a follower |
| 21 | //! failure degrades the node to bucket-proof acks until a periodic |
| 22 | //! re-recruit CASes a fresh ensemble; recovery gathers from every |
| 23 | //! reachable sealed member and requires at least one. |
| 24 | |
| 25 | use std::collections::BTreeMap; |
| 26 | use std::collections::BTreeSet; |
| 27 | use std::collections::HashMap; |
| 28 | use std::path::Path; |
| 29 | use std::path::PathBuf; |
| 30 | use std::sync::atomic::Ordering; |
| 31 | use std::sync::Arc; |
| 32 | use std::sync::Mutex; |
| 33 | |
| 34 | use anyhow::anyhow; |
| 35 | use anyhow::Context; |
| 36 | use celld_logic::log_tier; |
| 37 | use celld_logic::log_tier::LogState; |
| 38 | use tracing::info; |
| 39 | use tracing::warn; |
| 40 | |
| 41 | use futures_util::FutureExt; |
| 42 | use futures_util::StreamExt; |
| 43 | |
| 44 | use crate::bucket::Bucket; |
| 45 | use crate::ltx_repl::ShipEntry; |
| 46 | use crate::peer_auth::PeerAuth; |
| 47 | |
| 48 | mod recovery_progress; |
| 49 | |
| 50 | /// The one peer-POST boundary used by the node log. |
| 51 | /// |
| 52 | /// Production installs the signed `reqwest` implementation below. A |
| 53 | /// scheduler-controlled implementation can replace the transport while all |
| 54 | /// codecs and follower handlers remain the shipping ones. |
| 55 | pub trait LogTransport: Send + Sync + 'static { |
| 56 | fn post<'a>( |
| 57 | &'a self, |
| 58 | node: &'a str, |
| 59 | addr: &'a str, |
| 60 | path: &'a str, |
| 61 | body: Vec<u8>, |
| 62 | deadline: Option<std::time::Duration>, |
| 63 | ) -> std::pin::Pin< |
| 64 | Box<dyn std::future::Future<Output = anyhow::Result<bytes::Bytes>> + Send + 'a>, |
| 65 | >; |
| 66 | |
| 67 | /// Open one long-lived ordered byte stream to a member |
| 68 | /// (the ordered-transport design). The default refuses, so |
| 69 | /// every test transport keeps its request-shaped world unless a test |
| 70 | /// opts in. |
| 71 | fn open_stream<'a>( |
| 72 | &'a self, |
| 73 | node: &'a str, |
| 74 | addr: &'a str, |
| 75 | path: &'a str, |
| 76 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<LogStreamIo>> + Send + 'a>> |
| 77 | { |
| 78 | let _ = (node, addr, path); |
| 79 | Box::pin(async { anyhow::bail!("transport does not support ordered streams") }) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// The duplex an ordered stream rides. Anything tokio-readable and |
| 84 | /// -writable serves: a reqwest upgrade in production, a `tokio::io::duplex` |
| 85 | /// in the twins. |
| 86 | pub trait LogStreamDuplex: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin {} |
| 87 | impl<T> LogStreamDuplex for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin {} |
| 88 | pub type LogStreamIo = Box<dyn LogStreamDuplex>; |
| 89 | |
| 90 | /// One stream frame: a little-endian length prefix and the payload. |
| 91 | /// Leader-to-follower payloads are `encode_append` bodies; follower-to- |
| 92 | /// leader payloads are JSON `AppendResp`s, answered strictly in arrival |
| 93 | /// order. The cap bounds a corrupt or hostile length prefix. |
| 94 | const STREAM_FRAME_CAP: usize = 64 * 1024 * 1024; |
| 95 | |
| 96 | #[doc(hidden)] |
| 97 | pub async fn read_frame<R>(io: &mut R) -> anyhow::Result<Option<Vec<u8>>> |
| 98 | where |
| 99 | R: tokio::io::AsyncRead + Unpin, |
| 100 | { |
| 101 | use tokio::io::AsyncReadExt; |
| 102 | let mut len = [0_u8; 4]; |
| 103 | match io.read_exact(&mut len).await { |
| 104 | Ok(_) => {} |
| 105 | // EOF on a frame boundary is the peer closing; mid-frame EOF below |
| 106 | // is an error, exactly like a torn append body. |
| 107 | Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None), |
| 108 | Err(error) => return Err(error.into()), |
| 109 | } |
| 110 | let len = u32::from_le_bytes(len) as usize; |
| 111 | if len > STREAM_FRAME_CAP { |
| 112 | anyhow::bail!("stream frame of {len} bytes exceeds the cap"); |
| 113 | } |
| 114 | let mut payload = vec![0_u8; len]; |
| 115 | io.read_exact(&mut payload).await?; |
| 116 | Ok(Some(payload)) |
| 117 | } |
| 118 | |
| 119 | #[doc(hidden)] |
| 120 | pub async fn write_frame<W>(io: &mut W, payload: &[u8]) -> anyhow::Result<()> |
| 121 | where |
| 122 | W: tokio::io::AsyncWrite + Unpin, |
| 123 | { |
| 124 | use tokio::io::AsyncWriteExt; |
| 125 | io.write_all(&u32::try_from(payload.len())?.to_le_bytes()) |
| 126 | .await?; |
| 127 | io.write_all(payload).await?; |
| 128 | io.flush().await?; |
| 129 | Ok(()) |
| 130 | } |
| 131 | |
| 132 | /// Frames one commit may carry from one stream. The leader's window holds |
| 133 | /// eight frames per lane, so an honest burst is eight; the bound only keeps |
| 134 | /// a misbehaving peer from building an unbounded commit. |
| 135 | const SERVE_BATCH_FRAMES: usize = 64; |
| 136 | |
| 137 | /// The bytes one serve read asks for: enough that a burst of small frames |
| 138 | /// arrives in one read rather than one read per frame. |
| 139 | const SERVE_READ_CHUNK: usize = 64 * 1024; |
| 140 | |
| 141 | /// One complete frame from the front of `buf`, when it holds one. A partial |
| 142 | /// frame stays put for the next read; a header past the cap is the same |
| 143 | /// error `read_frame` reports. |
| 144 | fn take_buffered_frame(buf: &mut Vec<u8>) -> anyhow::Result<Option<Vec<u8>>> { |
| 145 | if buf.len() < 4 { |
| 146 | return Ok(None); |
| 147 | } |
| 148 | let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; |
| 149 | if len > STREAM_FRAME_CAP { |
| 150 | anyhow::bail!("stream frame of {len} bytes exceeds the cap"); |
| 151 | } |
| 152 | if buf.len() < 4 + len { |
| 153 | return Ok(None); |
| 154 | } |
| 155 | let frame = buf[4..4 + len].to_vec(); |
| 156 | buf.drain(..4 + len); |
| 157 | Ok(Some(frame)) |
| 158 | } |
| 159 | |
| 160 | /// Serve one ordered append stream as a group commit: block for the next |
| 161 | /// frame, take every further frame the socket has ALREADY delivered, commit |
| 162 | /// them as one batch, and answer each in order. Apply order equals arrival |
| 163 | /// order because this loop is the stream's only reader — that single fact |
| 164 | /// is what lets the leader keep several frames in flight without the |
| 165 | /// follower needing reorder state. Any error or EOF ends the stream with no |
| 166 | /// cleanup: the contiguity rule already treats a half-received stream |
| 167 | /// exactly like a half-delivered round, and the seal marks fence a zombie |
| 168 | /// leader's frames here just as they fence its one-shot appends. |
| 169 | /// |
| 170 | /// Why the commit is grouped (the 2026-09-01 write-latency ledger, 131k |
| 171 | /// served frames): the leader pipelines up to eight frames per lane, this |
| 172 | /// loop served them one at a time, and each `store.append` paid its own |
| 173 | /// fsync chain — ~4 ms of a ~5.8 ms serial service interval. A burst of |
| 174 | /// eight rounds therefore drained at eight chains, and the leader billed |
| 175 | /// every frame behind the head its queue position times that interval. |
| 176 | /// The frames a burst leaves on the socket are exactly the ones that can |
| 177 | /// share a chain. Merging at the leader instead was tried and refuted: the |
| 178 | /// lane drains its queue into the socket immediately, so there is never a |
| 179 | /// backlog on that side to merge. |
| 180 | pub async fn serve_log_stream<IO>(mut io: IO, store: Arc<FollowerStore>) -> anyhow::Result<()> |
| 181 | where |
| 182 | IO: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, |
| 183 | { |
| 184 | use tokio::io::AsyncReadExt; |
| 185 | let mut buf: Vec<u8> = Vec::new(); |
| 186 | // A delivered frame that belongs to another fragment: it could not ride |
| 187 | // the batch it arrived with, so it opens the next one. |
| 188 | let mut carried: Option<AppendReq> = None; |
| 189 | let mut cycle_started = mono_us(); |
| 190 | loop { |
| 191 | let head = match carried.take() { |
| 192 | Some(req) => req, |
| 193 | None => { |
| 194 | let frame = loop { |
| 195 | if let Some(frame) = take_buffered_frame(&mut buf)? { |
| 196 | break frame; |
| 197 | } |
| 198 | buf.reserve(SERVE_READ_CHUNK); |
| 199 | if io.read_buf(&mut buf).await? == 0 { |
| 200 | // EOF on a frame boundary is the peer closing; |
| 201 | // mid-frame EOF is an error, exactly like a torn |
| 202 | // append body. |
| 203 | if buf.is_empty() { |
| 204 | return Ok(()); |
| 205 | } |
| 206 | anyhow::bail!("stream closed mid-frame"); |
| 207 | } |
| 208 | }; |
| 209 | decode_append(&frame)? |
| 210 | } |
| 211 | }; |
| 212 | // The cycle split is the follower-side latency ledger: `read_ms` |
| 213 | // is time waiting for (and reading) the batch head, and the rest |
| 214 | // is this loop's serial service — the lane's throughput ceiling. |
| 215 | let read_done = mono_us(); |
| 216 | // The reader-idle ledger: a long read wait is either no traffic or a |
| 217 | // starved reader task; paired with the leader's head-stall event it |
| 218 | // tells which. One second is far past any honest inter-frame gap on |
| 219 | // a loaded lane. |
| 220 | let idle_ms = read_done.saturating_sub(cycle_started) / 1000; |
| 221 | if idle_ms >= 1_000 { |
| 222 | warn!( |
| 223 | event = "log_serve_idle", |
| 224 | idle_ms, "stream reader idle past one second" |
| 225 | ); |
| 226 | } |
| 227 | let mut batch = AppendBatch::new(head); |
| 228 | // The drain takes only what has already arrived. A single poll of |
| 229 | // `read_buf` is cancel-safe — a pending read consumes nothing — so |
| 230 | // the drain never waits on the wire and never tears a frame, which |
| 231 | // `read_frame` (a `read_exact` of the header, then the body) could |
| 232 | // not promise if it were polled once and dropped. |
| 233 | while batch.frame_count() < SERVE_BATCH_FRAMES { |
| 234 | let frame = match take_buffered_frame(&mut buf)? { |
| 235 | Some(frame) => frame, |
| 236 | None => { |
| 237 | buf.reserve(SERVE_READ_CHUNK); |
| 238 | match io.read_buf(&mut buf).now_or_never() { |
| 239 | // Nothing more delivered, or EOF: commit what is |
| 240 | // here. The blocking read above reports the EOF. |
| 241 | None | Some(Ok(0)) => break, |
| 242 | Some(Ok(_)) => continue, |
| 243 | Some(Err(error)) => return Err(error.into()), |
| 244 | } |
| 245 | } |
| 246 | }; |
| 247 | if let Err(other) = batch.try_push(decode_append(&frame)?) { |
| 248 | carried = Some(other); |
| 249 | break; |
| 250 | } |
| 251 | } |
| 252 | let decode_done = mono_us(); |
| 253 | let frames = batch.frame_count(); |
| 254 | let entries = batch.entry_count(); |
| 255 | let answers = store.append_batch(batch).await; |
| 256 | let append_done = mono_us(); |
| 257 | for resp in &answers { |
| 258 | write_frame(&mut io, &serde_json::to_vec(resp)?).await?; |
| 259 | } |
| 260 | let ack_done = mono_us(); |
| 261 | info!( |
| 262 | event = "log_serve_cycle", |
| 263 | frames, |
| 264 | entries, |
| 265 | read_ms = read_done.saturating_sub(cycle_started) / 1000, |
| 266 | decode_ms = decode_done.saturating_sub(read_done) / 1000, |
| 267 | append_ms = append_done.saturating_sub(decode_done) / 1000, |
| 268 | ack_ms = ack_done.saturating_sub(append_done) / 1000, |
| 269 | "served one stream append commit" |
| 270 | ); |
| 271 | cycle_started = ack_done; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | /// Concurrent per-cell upload lanes during node-log recovery. The |
| 276 | /// sequential version cost ~47 s for 180 entries on the lab fleet; more |
| 277 | /// than a few lanes multiplied across RACING recoverers (self-recovery |
| 278 | /// plus every survivor's eager sweep) tripped R2's same-object 429 rate |
| 279 | /// limit into a livelock, so the lanes are modest and each upload retries |
| 280 | /// 429-class refusals with backoff. |
| 281 | /// Recovery uploads one merged segment per cell epoch after one watermark |
| 282 | /// lookup each. A dead session on a loaded fleet holds thousands of cells, |
| 283 | /// and at eight in flight the 2026-09-03 restart spent 388 s of its 403 s |
| 284 | /// recovery in this phase; the bucket takes far more in flight than that. |
| 285 | const RECOVERY_UPLOAD_CONCURRENCY: usize = 32; |
| 286 | /// How many bytes of retained bundles one recovery gather window reads |
| 287 | /// before it folds that window's rows into the per-cell layout and releases |
| 288 | /// them. The whole-session gather held every row of every retained bundle |
| 289 | /// until the last bundle was read: about 0.95 GB of process memory per GB |
| 290 | /// of session, 7 GB for a ten-minute session at 2 MiB writes, and past 15 GB |
| 291 | /// the kernel OOM cascade of #964, where each killed gatherer became the |
| 292 | /// next dead session (#957). The fold holds at most about twice this budget |
| 293 | /// (the window's rows plus the per-cell merges in flight), whatever the |
| 294 | /// session's age. The cost is one L0 object per cell for each window the |
| 295 | /// cell has rows in, instead of one for the whole session; a session under |
| 296 | /// the budget folds exactly as before. |
| 297 | const RECOVERY_GATHER_WINDOW_BYTES: u64 = 512 * 1024 * 1024; |
| 298 | /// Per-cell coverage reads of the graceful seal and the uncovered-row scan |
| 299 | /// stay below a small fleet's cell count, so a close does not fan out one |
| 300 | /// listing per cell at once. |
| 301 | const COVERAGE_READ_CONCURRENCY: usize = 16; |
| 302 | const BUNDLE_ROW_INDEX_CAPACITY: usize = 512; |
| 303 | const BUNDLE_GC_EXAMINED_PER_TICK: usize = 512; |
| 304 | |
| 305 | struct IndexedBundle { |
| 306 | cells: BTreeSet<String>, |
| 307 | rows: Option<Vec<celld_ltx::bundle::BundleRow>>, |
| 308 | } |
| 309 | |
| 310 | #[derive(Default)] |
| 311 | struct BundleIndex { |
| 312 | bundles: BTreeMap<String, IndexedBundle>, |
| 313 | by_cell: BTreeMap<String, BTreeSet<String>>, |
| 314 | recent: std::collections::VecDeque<String>, |
| 315 | /// The highest txid whose row metadata left `recent`, per cell epoch. A |
| 316 | /// cell needs its evicted bundles only until its per-cell coverage passes |
| 317 | /// this cut, so a covered cell costs no bundle read. |
| 318 | evicted: BTreeMap<(String, u64), u64>, |
| 319 | } |
| 320 | |
| 321 | /// One cell epoch's view of the index. The rows, the evicted bundles, and |
| 322 | /// their cut come from one lock: an eviction between two reads could drop a |
| 323 | /// bundle from both the rows and the evicted set. |
| 324 | struct CellBundleRows { |
| 325 | located: Vec<celld_ltx::LocatedRow>, |
| 326 | evicted: Vec<String>, |
| 327 | evicted_through: Option<u64>, |
| 328 | } |
| 329 | |
| 330 | impl BundleIndex { |
| 331 | fn insert(&mut self, key: String, rows: Vec<celld_ltx::bundle::BundleRow>) { |
| 332 | let cells: BTreeSet<String> = rows.iter().map(|row| row.cell.clone()).collect(); |
| 333 | for cell in &cells { |
| 334 | self.by_cell |
| 335 | .entry(cell.clone()) |
| 336 | .or_default() |
| 337 | .insert(key.clone()); |
| 338 | } |
| 339 | self.recent.push_back(key.clone()); |
| 340 | let previous = self.bundles.insert( |
| 341 | key.clone(), |
| 342 | IndexedBundle { |
| 343 | cells, |
| 344 | rows: Some(rows), |
| 345 | }, |
| 346 | ); |
| 347 | debug_assert!( |
| 348 | previous.is_none(), |
| 349 | "bundle keys are unique within a session" |
| 350 | ); |
| 351 | while self.recent.len() > BUNDLE_ROW_INDEX_CAPACITY { |
| 352 | let oldest = self |
| 353 | .recent |
| 354 | .pop_front() |
| 355 | .expect("an over-capacity bundle row index is not empty"); |
| 356 | let rows = self |
| 357 | .bundles |
| 358 | .get_mut(&oldest) |
| 359 | .and_then(|bundle| bundle.rows.take()); |
| 360 | for row in rows.into_iter().flatten() { |
| 361 | let through = self.evicted.entry((row.cell, row.cell_epoch)).or_default(); |
| 362 | *through = (*through).max(row.txid); |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | fn rows(&self, key: &str) -> Option<Vec<celld_ltx::bundle::BundleRow>> { |
| 368 | self.bundles.get(key).and_then(|bundle| bundle.rows.clone()) |
| 369 | } |
| 370 | |
| 371 | fn bundles_for(&self, cell: &str) -> Vec<(String, Option<Vec<celld_ltx::bundle::BundleRow>>)> { |
| 372 | self.by_cell.get(cell).map_or_else(Vec::new, |keys| { |
| 373 | keys.iter() |
| 374 | .filter_map(|key| { |
| 375 | self.bundles |
| 376 | .get(key) |
| 377 | .map(|bundle| (key.clone(), bundle.rows.clone())) |
| 378 | }) |
| 379 | .collect() |
| 380 | }) |
| 381 | } |
| 382 | |
| 383 | fn cell_rows(&self, cell: &str, epoch: u64) -> CellBundleRows { |
| 384 | let mut located = Vec::new(); |
| 385 | let mut evicted = Vec::new(); |
| 386 | for key in self.by_cell.get(cell).into_iter().flatten() { |
| 387 | let Some(bundle) = self.bundles.get(key) else { |
| 388 | continue; |
| 389 | }; |
| 390 | match &bundle.rows { |
| 391 | Some(rows) => located.extend( |
| 392 | rows.iter() |
| 393 | .filter(|row| row.cell == cell && row.cell_epoch == epoch) |
| 394 | .map(|row| celld_ltx::LocatedRow { |
| 395 | source: key.clone(), |
| 396 | row: row.clone(), |
| 397 | }), |
| 398 | ), |
| 399 | None => evicted.push(key.clone()), |
| 400 | } |
| 401 | } |
| 402 | CellBundleRows { |
| 403 | located, |
| 404 | evicted, |
| 405 | evicted_through: self.evicted.get(&(cell.to_string(), epoch)).copied(), |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | fn remove(&mut self, keys: &[String]) { |
| 410 | let removed: BTreeSet<&str> = keys.iter().map(String::as_str).collect(); |
| 411 | for key in &removed { |
| 412 | let Some(bundle) = self.bundles.remove(*key) else { |
| 413 | continue; |
| 414 | }; |
| 415 | for cell in bundle.cells { |
| 416 | let empty = self.by_cell.get_mut(&cell).is_some_and(|cell_keys| { |
| 417 | cell_keys.remove(*key); |
| 418 | cell_keys.is_empty() |
| 419 | }); |
| 420 | if empty { |
| 421 | self.by_cell.remove(&cell); |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | self.recent.retain(|key| !removed.contains(key.as_str())); |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | /// A contender observes a live recovery before it tries to replace it. The |
| 430 | /// node-log tail is bounded to the flush window, so thirty seconds is enough |
| 431 | /// for the elected reader in normal operation and still leaves ninety seconds |
| 432 | /// inside the default rollout readiness bound after a crashed recoverer. |
| 433 | /// A recovery claim whose heartbeat is older than this is stale and may be |
| 434 | /// taken over. The claimant beats every `RECOVERY_HEARTBEAT`, so a live |
| 435 | /// claimant is never mistaken for a dead one by a slow bucket round trip. |
| 436 | pub(crate) const RECOVERY_CLAIM_TTL: std::time::Duration = std::time::Duration::from_secs(30); |
| 437 | const RECOVERY_CLAIM_POLL: std::time::Duration = std::time::Duration::from_millis(250); |
| 438 | const RECOVERY_HEARTBEAT: std::time::Duration = std::time::Duration::from_secs(5); |
| 439 | /// How long a boot waits behind another node's live claim before it says |
| 440 | /// so again in the log. |
| 441 | const RECOVERY_WAIT_REPORT: std::time::Duration = std::time::Duration::from_secs(30); |
| 442 | |
| 443 | /// What a recovery does when another node holds a live claim on the log. |
| 444 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 445 | pub(crate) enum RecoverMode { |
| 446 | /// A maintenance sweep: another node is on it, so there is nothing to |
| 447 | /// do here. Every peer used to take the claim over after a fixed wait |
| 448 | /// and repeat the same gather. |
| 449 | Sweep, |
| 450 | /// A boot, or a cold route that needs the seal: this node cannot go on |
| 451 | /// until the log is sealed, so it waits behind the claimant and takes |
| 452 | /// the claim over only once its heartbeat is stale. |
| 453 | Boot, |
| 454 | } |
| 455 | |
| 456 | /// The claimant's heartbeat while it gathers, beaten cooperatively at each |
| 457 | /// step of the gather and the upload. A cooperative beat cannot race the |
| 458 | /// seal, and it is deterministic under the simulated clock. |
| 459 | struct ClaimBeat { |
| 460 | last_mono_ms: u64, |
| 461 | } |
| 462 | |
| 463 | impl ClaimBeat { |
| 464 | fn new() -> Self { |
| 465 | Self { |
| 466 | last_mono_ms: mono_ms(), |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /// Process-monotonic milliseconds for follower-health bookkeeping: latency |
| 472 | /// windows and quarantine arithmetic must not jump with the wall clock. |
| 473 | fn mono_ms() -> u64 { |
| 474 | crate::asyncrt::mono_ms() |
| 475 | } |
| 476 | |
| 477 | fn mono_us() -> u64 { |
| 478 | crate::asyncrt::mono_us() |
| 479 | } |
| 480 | |
| 481 | /// The eviction policy, defaults per the design doc, every constant an E8 |
| 482 | /// target the lab can override. |
| 483 | pub fn eviction_policy_from_env() -> anyhow::Result<celld_logic::log_evict::EvictionPolicy> { |
| 484 | let default = celld_logic::log_evict::EvictionPolicy::default(); |
| 485 | Ok(celld_logic::log_evict::EvictionPolicy { |
| 486 | budget_ms: crate::env_vars::with_default("CELLD_LOG_EVICT_BUDGET_MS", default.budget_ms)?, |
| 487 | sibling_factor: default.sibling_factor, |
| 488 | sustain_ms: crate::env_vars::with_default( |
| 489 | "CELLD_LOG_EVICT_SUSTAIN_MS", |
| 490 | default.sustain_ms, |
| 491 | )?, |
| 492 | backstop_ms: crate::env_vars::with_default( |
| 493 | "CELLD_LOG_EVICT_BACKSTOP_MS", |
| 494 | default.backstop_ms, |
| 495 | )?, |
| 496 | quarantine_ms: crate::env_vars::with_default( |
| 497 | "CELLD_LOG_EVICT_QUARANTINE_MS", |
| 498 | default.quarantine_ms, |
| 499 | )?, |
| 500 | min_swap_interval_ms: default.min_swap_interval_ms, |
| 501 | window_ms: default.window_ms, |
| 502 | min_samples: default.min_samples, |
| 503 | hedge_floor_ms: default.hedge_floor_ms, |
| 504 | hedge_factor: default.hedge_factor, |
| 505 | }) |
| 506 | } |
| 507 | |
| 508 | // ── The record ────────────────────────────────────────────────────────────── |
| 509 | // |
| 510 | // Since the lease-fold, the log record LIVES in the node lease record: |
| 511 | // nodes/<node>.json carries a folded `log` object |
| 512 | // beside its authority fields, and a session's identity is the record's |
| 513 | // generation. Reading "session X/G" means reading X's lease and answering |
| 514 | // None unless it still carries generation G — a replaced record is a |
| 515 | // recovered-then-superseded session, and absence keeps meaning complete. |
| 516 | // Writes here are for DEAD sessions only (recovery's fence and seal): they |
| 517 | // CAS the full wire record, carrying every authority field through |
| 518 | // unchanged and never touching expiry. A LIVE session's own writes go |
| 519 | // through the core's lease chain instead (write_own_log below), because |
| 520 | // the lease has exactly one writer per process and a second one would |
| 521 | // race the renewal guard. |
| 522 | |
| 523 | fn lease_key(node: &str) -> String { |
| 524 | format!("nodes/{node}.json") |
| 525 | } |
| 526 | |
| 527 | pub(crate) struct FoldedRead { |
| 528 | pub(crate) record: log_tier::LogRecord, |
| 529 | /// Persisted acknowledgement history for `record.epoch`, not liveness. |
| 530 | /// The marker precedes the first fleet credit and survives bucket tiering. |
| 531 | pub(crate) may_have_fleet_acks: bool, |
| 532 | pub(crate) token: String, |
| 533 | pub(crate) wire: crate::ownership_store::NodeLeaseWire, |
| 534 | } |
| 535 | |
| 536 | fn log_from_wire(log: &crate::ownership_store::NodeLogWire) -> anyhow::Result<log_tier::LogRecord> { |
| 537 | Ok(log_tier::LogRecord { |
| 538 | epoch: log.epoch, |
| 539 | ensemble: log.ensemble.iter().cloned().collect(), |
| 540 | tiered: log.tiered, |
| 541 | state: match log.state.as_str() { |
| 542 | "open" => LogState::Open, |
| 543 | "recovering" => LogState::Recovering, |
| 544 | "sealed" => LogState::Sealed, |
| 545 | other => return Err(anyhow!("unknown log record state {other:?}")), |
| 546 | }, |
| 547 | claimant: log.claimant.clone(), |
| 548 | claimed_ms: log.claimed_ms, |
| 549 | }) |
| 550 | } |
| 551 | |
| 552 | pub(crate) fn log_to_wire( |
| 553 | record: &log_tier::LogRecord, |
| 554 | may_have_fleet_acks: bool, |
| 555 | ) -> crate::ownership_store::NodeLogWire { |
| 556 | crate::ownership_store::NodeLogWire { |
| 557 | state: match record.state { |
| 558 | LogState::Open => "open", |
| 559 | LogState::Recovering => "recovering", |
| 560 | LogState::Sealed => "sealed", |
| 561 | } |
| 562 | .to_string(), |
| 563 | epoch: record.epoch, |
| 564 | ensemble: record.ensemble.iter().cloned().collect(), |
| 565 | tiered: record.tiered, |
| 566 | may_have_fleet_acks, |
| 567 | claimant: record.claimant.clone(), |
| 568 | claimed_ms: record.claimed_ms, |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | pub(crate) async fn read_record( |
| 573 | bucket: &Bucket, |
| 574 | session: &str, |
| 575 | ) -> anyhow::Result<Option<FoldedRead>> { |
| 576 | let (node, generation) = session.split_once('/').unwrap_or((session, "")); |
| 577 | let Some((bytes, token)) = bucket.get(&lease_key(node)).await? else { |
| 578 | return Ok(None); |
| 579 | }; |
| 580 | let wire: crate::ownership_store::NodeLeaseWire = serde_json::from_slice(&bytes)?; |
| 581 | // A bare node name reads whatever session the record carries; a full |
| 582 | // <node>/<generation> pins it, and a superseded generation is a |
| 583 | // recovered-then-replaced session whose absence means complete. |
| 584 | if !generation.is_empty() && wire.generation != generation { |
| 585 | return Ok(None); |
| 586 | } |
| 587 | let Some(log) = wire.log.as_ref() else { |
| 588 | return Ok(None); |
| 589 | }; |
| 590 | Ok(Some(FoldedRead { |
| 591 | record: log_from_wire(log)?, |
| 592 | may_have_fleet_acks: log.may_have_fleet_acks, |
| 593 | token, |
| 594 | wire, |
| 595 | })) |
| 596 | } |
| 597 | |
| 598 | /// CAS a DEAD session's folded log fields. Authority fields ride through |
| 599 | /// from the wire the caller read; expiry is never extended, so this write |
| 600 | /// can only fence, never revive. |
| 601 | pub(crate) async fn write_dead_record( |
| 602 | bucket: &Bucket, |
| 603 | session: &str, |
| 604 | prior: &crate::ownership_store::NodeLeaseWire, |
| 605 | record: &log_tier::LogRecord, |
| 606 | may_have_fleet_acks: bool, |
| 607 | token: &str, |
| 608 | ) -> anyhow::Result<Option<String>> { |
| 609 | let (node, _) = session.split_once('/').unwrap_or((session, "")); |
| 610 | let mut wire = prior.clone(); |
| 611 | wire.log = Some(log_to_wire(record, may_have_fleet_acks)); |
| 612 | let body = serde_json::to_vec(&wire)?; |
| 613 | bucket.put_cas(&lease_key(node), body, Some(token)).await |
| 614 | } |
| 615 | |
| 616 | /// The LIVE session's writer for its own folded log: publish the desired |
| 617 | /// object to the ownership store, nudge the core into an immediate |
| 618 | /// renewal, and wait until an APPLIED lease write carries it. The lease |
| 619 | /// chain stays single-writer — this is how open, activation, and the |
| 620 | /// graceful seal become durable without racing the renewal guard. A |
| 621 | /// fenced node's renewals stop applying, so the wait times out and the |
| 622 | /// caller refuses, which is the fence doing its job. |
| 623 | pub struct OwnLog { |
| 624 | pub ownership: Arc<crate::ownership_store::BucketOwnership>, |
| 625 | pub nudge: Box<dyn Fn() + Send + Sync>, |
| 626 | /// One publish outstanding at a time: with the seq-tagged applied |
| 627 | /// notification, "applied seq >= mine" then implies the applied body |
| 628 | /// IS my object. The live transition capability holds its wider guard |
| 629 | /// across this publication and the decision that produced it. |
| 630 | pub write_lock: tokio::sync::Mutex<()>, |
| 631 | } |
| 632 | |
| 633 | impl OwnLog { |
| 634 | async fn write(&self, log: Option<crate::ownership_store::NodeLogWire>) -> anyhow::Result<()> { |
| 635 | let _serialized = self.write_lock.lock().await; |
| 636 | let mut rx = self.ownership.applied_log(); |
| 637 | let seq = self.ownership.set_own_log(log); |
| 638 | (self.nudge)(); |
| 639 | let deadline = crate::asyncrt::mono_ms().saturating_add(10_000); |
| 640 | loop { |
| 641 | if rx.borrow_and_update().1 >= seq { |
| 642 | return Ok(()); |
| 643 | } |
| 644 | crate::asyncrt::select_biased! { |
| 645 | "an applied-log change wins a tie so a completed write does not time out"; |
| 646 | changed = rx.changed() => { |
| 647 | anyhow::ensure!(changed.is_ok(), "the lease writer is gone"); |
| 648 | }, |
| 649 | _ = crate::asyncrt::sleep_until(deadline) => { |
| 650 | anyhow::bail!( |
| 651 | "no lease write carried the folded log within 10s; treating this session as fenced" |
| 652 | ); |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | fn current(&self) -> Option<crate::ownership_store::NodeLogWire> { |
| 659 | self.ownership.own_log() |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 664 | enum NodeLogLifecycle { |
| 665 | Running, |
| 666 | Quiescing, |
| 667 | } |
| 668 | |
| 669 | /// The one capability for a live session's record transitions. The guard |
| 670 | /// covers the current-record read, the transition decision, the durable |
| 671 | /// publication, and any in-memory value coupled to that publication. A |
| 672 | /// separate check before this guard cannot enforce shutdown because close |
| 673 | /// can start between that check and the record write. |
| 674 | struct LiveLogTransitions { |
| 675 | own_log: Arc<OwnLog>, |
| 676 | lifecycle: tokio::sync::Mutex<NodeLogLifecycle>, |
| 677 | } |
| 678 | |
| 679 | struct LiveLogTransition<'a> { |
| 680 | transitions: &'a LiveLogTransitions, |
| 681 | lifecycle: tokio::sync::MutexGuard<'a, NodeLogLifecycle>, |
| 682 | } |
| 683 | |
| 684 | impl LiveLogTransitions { |
| 685 | fn new(own_log: Arc<OwnLog>) -> Self { |
| 686 | Self { |
| 687 | own_log, |
| 688 | lifecycle: tokio::sync::Mutex::new(NodeLogLifecycle::Running), |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | async fn lock(&self) -> LiveLogTransition<'_> { |
| 693 | LiveLogTransition { |
| 694 | transitions: self, |
| 695 | lifecycle: self.lifecycle.lock().await, |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | async fn activate(&self, expected: &log_tier::LogRecord) -> anyhow::Result<bool> { |
| 700 | let transition = self.lock().await; |
| 701 | if !transition.is_running() { |
| 702 | return Ok(false); |
| 703 | } |
| 704 | let Some(current) = transition.current() else { |
| 705 | return Ok(false); |
| 706 | }; |
| 707 | let current_record = log_from_wire(¤t)?; |
| 708 | if current_record != *expected { |
| 709 | return Ok(false); |
| 710 | } |
| 711 | transition.write(Some(log_to_wire(expected, true))).await?; |
| 712 | Ok(true) |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | impl LiveLogTransition<'_> { |
| 717 | fn is_running(&self) -> bool { |
| 718 | *self.lifecycle == NodeLogLifecycle::Running |
| 719 | } |
| 720 | |
| 721 | fn begin_quiescing(&mut self) -> bool { |
| 722 | if !self.is_running() { |
| 723 | return false; |
| 724 | } |
| 725 | *self.lifecycle = NodeLogLifecycle::Quiescing; |
| 726 | true |
| 727 | } |
| 728 | |
| 729 | fn current(&self) -> Option<crate::ownership_store::NodeLogWire> { |
| 730 | self.transitions.own_log.current() |
| 731 | } |
| 732 | |
| 733 | async fn write(&self, log: Option<crate::ownership_store::NodeLogWire>) -> anyhow::Result<()> { |
| 734 | self.transitions.own_log.write(log).await |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | // ── Wire types for the peer endpoints ─────────────────────────────────────── |
| 739 | // |
| 740 | // The two byte-dominated messages — the append request and the tail |
| 741 | // response — travel as a small binary framing; every control message |
| 742 | // (append response, seal, tail request) stays JSON. The same entry |
| 743 | // encoding is the follower's on-disk `<seq>.entry` format, so one decoder |
| 744 | // serves the wire and the disk. All integers little-endian: |
| 745 | // |
| 746 | // append body: "CLA1" u16 leader_len leader u64 epoch u64 truncate_to |
| 747 | // u32 count entry* |
| 748 | // legacy tail: "CLT1" u32 count entry* |
| 749 | // ranged tail: "CLT2" u64 fragment_epoch u64 base u64 end |
| 750 | // u8 complete u32 count entry* |
| 751 | // entry: "CLE1" u64 seq u16 cell_len cell u64 cell_epoch |
| 752 | // u64 txid u32 len bytes |
| 753 | |
| 754 | const APPEND_MAGIC: &[u8; 4] = b"CLA1"; |
| 755 | // Keep distinct layouts and decoded variants: reading an old peer's entries |
| 756 | // does not prove that its retained range is complete. |
| 757 | const LEGACY_TAIL_MAGIC: &[u8; 4] = b"CLT1"; |
| 758 | const TAIL_MAGIC: &[u8; 4] = b"CLT2"; |
| 759 | const ENTRY_MAGIC: &[u8; 4] = b"CLE1"; |
| 760 | |
| 761 | pub struct Entry { |
| 762 | pub seq: u64, |
| 763 | pub cell: String, |
| 764 | pub cell_epoch: u64, |
| 765 | pub txid: u64, |
| 766 | pub bytes: Vec<u8>, |
| 767 | } |
| 768 | |
| 769 | pub struct AppendReq { |
| 770 | pub leader: String, |
| 771 | pub epoch: u64, |
| 772 | /// Follower may drop entries at or below this sequence; they are in the |
| 773 | /// bucket. |
| 774 | pub truncate_to: u64, |
| 775 | pub entries: Vec<Entry>, |
| 776 | } |
| 777 | |
| 778 | fn validate_log_leader(leader: &str) -> anyhow::Result<()> { |
| 779 | let validate = |name| crate::machine::validate_node_name(name); |
| 780 | match leader.split_once('/') { |
| 781 | Some((node, generation)) => { |
| 782 | validate(node)?; |
| 783 | validate(generation)?; |
| 784 | } |
| 785 | None => validate(leader)?, |
| 786 | } |
| 787 | Ok(()) |
| 788 | } |
| 789 | |
| 790 | fn deserialize_log_leader<'de, D>(deserializer: D) -> Result<String, D::Error> |
| 791 | where |
| 792 | D: serde::Deserializer<'de>, |
| 793 | { |
| 794 | let leader = <String as serde::Deserialize>::deserialize(deserializer)?; |
| 795 | validate_log_leader(&leader).map_err(|error| { |
| 796 | serde::de::Error::custom(format!("invalid log leader identity: {error}")) |
| 797 | })?; |
| 798 | Ok(leader) |
| 799 | } |
| 800 | |
| 801 | fn take<'a>(buf: &mut &'a [u8], n: usize, what: &str) -> anyhow::Result<&'a [u8]> { |
| 802 | if buf.len() < n { |
| 803 | return Err(anyhow!("log wire: truncated {what}")); |
| 804 | } |
| 805 | let (head, rest) = buf.split_at(n); |
| 806 | *buf = rest; |
| 807 | Ok(head) |
| 808 | } |
| 809 | |
| 810 | fn take_u16(buf: &mut &[u8], what: &str) -> anyhow::Result<u16> { |
| 811 | Ok(u16::from_le_bytes(take(buf, 2, what)?.try_into().unwrap())) |
| 812 | } |
| 813 | |
| 814 | fn take_u32(buf: &mut &[u8], what: &str) -> anyhow::Result<u32> { |
| 815 | Ok(u32::from_le_bytes(take(buf, 4, what)?.try_into().unwrap())) |
| 816 | } |
| 817 | |
| 818 | fn take_u64(buf: &mut &[u8], what: &str) -> anyhow::Result<u64> { |
| 819 | Ok(u64::from_le_bytes(take(buf, 8, what)?.try_into().unwrap())) |
| 820 | } |
| 821 | |
| 822 | fn take_string(buf: &mut &[u8], what: &str) -> anyhow::Result<String> { |
| 823 | let len = take_u16(buf, what)? as usize; |
| 824 | Ok(std::str::from_utf8(take(buf, len, what)?) |
| 825 | .map_err(|_| anyhow!("log wire: {what} not utf-8"))? |
| 826 | .to_string()) |
| 827 | } |
| 828 | |
| 829 | #[doc(hidden)] |
| 830 | pub fn encode_entry(entry: &Entry, out: &mut Vec<u8>) { |
| 831 | out.extend_from_slice(ENTRY_MAGIC); |
| 832 | out.extend_from_slice(&entry.seq.to_le_bytes()); |
| 833 | out.extend_from_slice(&(entry.cell.len() as u16).to_le_bytes()); |
| 834 | out.extend_from_slice(entry.cell.as_bytes()); |
| 835 | out.extend_from_slice(&entry.cell_epoch.to_le_bytes()); |
| 836 | out.extend_from_slice(&entry.txid.to_le_bytes()); |
| 837 | out.extend_from_slice(&(entry.bytes.len() as u32).to_le_bytes()); |
| 838 | out.extend_from_slice(&entry.bytes); |
| 839 | } |
| 840 | |
| 841 | fn decode_entry(buf: &mut &[u8]) -> anyhow::Result<Entry> { |
| 842 | if take(buf, 4, "entry magic")? != ENTRY_MAGIC { |
| 843 | return Err(anyhow!("log wire: bad entry magic")); |
| 844 | } |
| 845 | let seq = take_u64(buf, "entry seq")?; |
| 846 | let cell = take_string(buf, "entry cell")?; |
| 847 | let cell_epoch = take_u64(buf, "entry cell_epoch")?; |
| 848 | let txid = take_u64(buf, "entry txid")?; |
| 849 | let len = take_u32(buf, "entry len")? as usize; |
| 850 | let bytes = take(buf, len, "entry bytes")?.to_vec(); |
| 851 | Ok(Entry { |
| 852 | seq, |
| 853 | cell, |
| 854 | cell_epoch, |
| 855 | txid, |
| 856 | bytes, |
| 857 | }) |
| 858 | } |
| 859 | |
| 860 | pub fn encode_append(req: &AppendReq) -> Vec<u8> { |
| 861 | let mut out = Vec::new(); |
| 862 | out.extend_from_slice(APPEND_MAGIC); |
| 863 | out.extend_from_slice(&(req.leader.len() as u16).to_le_bytes()); |
| 864 | out.extend_from_slice(req.leader.as_bytes()); |
| 865 | out.extend_from_slice(&req.epoch.to_le_bytes()); |
| 866 | out.extend_from_slice(&req.truncate_to.to_le_bytes()); |
| 867 | out.extend_from_slice(&(req.entries.len() as u32).to_le_bytes()); |
| 868 | for entry in &req.entries { |
| 869 | encode_entry(entry, &mut out); |
| 870 | } |
| 871 | out |
| 872 | } |
| 873 | |
| 874 | pub fn decode_append(mut body: &[u8]) -> anyhow::Result<AppendReq> { |
| 875 | let buf = &mut body; |
| 876 | if take(buf, 4, "append magic")? != APPEND_MAGIC { |
| 877 | return Err(anyhow!("log wire: bad append magic")); |
| 878 | } |
| 879 | let leader = take_string(buf, "append leader")?; |
| 880 | validate_log_leader(&leader).context("invalid log leader identity")?; |
| 881 | let epoch = take_u64(buf, "append epoch")?; |
| 882 | let truncate_to = take_u64(buf, "append truncate_to")?; |
| 883 | let entries = decode_entries(buf, "append")?; |
| 884 | Ok(AppendReq { |
| 885 | leader, |
| 886 | epoch, |
| 887 | truncate_to, |
| 888 | entries, |
| 889 | }) |
| 890 | } |
| 891 | |
| 892 | /// The shared tail of both framed bodies: a count, that many entries, |
| 893 | /// and nothing after them. |
| 894 | fn decode_entries(buf: &mut &[u8], what: &str) -> anyhow::Result<Vec<Entry>> { |
| 895 | let count = take_u32(buf, what)? as usize; |
| 896 | let mut entries = Vec::with_capacity(count.min(4096)); |
| 897 | for _ in 0..count { |
| 898 | entries.push(decode_entry(buf)?); |
| 899 | } |
| 900 | if !buf.is_empty() { |
| 901 | return Err(anyhow!("log wire: trailing bytes after {what}")); |
| 902 | } |
| 903 | Ok(entries) |
| 904 | } |
| 905 | |
| 906 | pub fn encode_tail_resp(resp: &TailResp) -> Vec<u8> { |
| 907 | let mut out = Vec::new(); |
| 908 | out.extend_from_slice(TAIL_MAGIC); |
| 909 | out.extend_from_slice(&resp.range.fragment_epoch.to_le_bytes()); |
| 910 | out.extend_from_slice(&resp.range.base.to_le_bytes()); |
| 911 | out.extend_from_slice(&resp.range.end.to_le_bytes()); |
| 912 | out.push(u8::from(resp.range.complete)); |
| 913 | out.extend_from_slice(&(resp.entries.len() as u32).to_le_bytes()); |
| 914 | for entry in &resp.entries { |
| 915 | encode_entry(entry, &mut out); |
| 916 | } |
| 917 | out |
| 918 | } |
| 919 | |
| 920 | pub fn decode_tail_resp(mut body: &[u8]) -> anyhow::Result<TailReply> { |
| 921 | let buf = &mut body; |
| 922 | match take(buf, 4, "tail magic")? { |
| 923 | magic if magic == LEGACY_TAIL_MAGIC => { |
| 924 | return Ok(TailReply::Legacy { |
| 925 | entries: decode_entries(buf, "tail")?, |
| 926 | }); |
| 927 | } |
| 928 | magic if magic == TAIL_MAGIC => {} |
| 929 | _ => return Err(anyhow!("log wire: bad tail magic")), |
| 930 | } |
| 931 | let fragment_epoch = take_u64(buf, "tail fragment_epoch")?; |
| 932 | let base = take_u64(buf, "tail base")?; |
| 933 | let end = take_u64(buf, "tail end")?; |
| 934 | anyhow::ensure!(base <= end, "log wire: tail base is above its end"); |
| 935 | let complete = match take(buf, 1, "tail completeness")?[0] { |
| 936 | 0 => false, |
| 937 | 1 => true, |
| 938 | _ => anyhow::bail!("log wire: invalid tail completeness"), |
| 939 | }; |
| 940 | let range = TailRange { |
| 941 | fragment_epoch, |
| 942 | base, |
| 943 | end, |
| 944 | complete, |
| 945 | }; |
| 946 | let entries = decode_entries(buf, "tail")?; |
| 947 | if range.complete && !tail_covers_sealed_range(range.base, range.end, &entries) { |
| 948 | anyhow::bail!("log wire: complete tail does not cover its range"); |
| 949 | } |
| 950 | Ok(TailReply::Ranged(TailResp { range, entries })) |
| 951 | } |
| 952 | |
| 953 | /// The frames one commit may carry: consecutive stream frames of ONE |
| 954 | /// fragment. Growing a batch is the only way to build one, and it hands |
| 955 | /// back a frame for another leader or epoch, so `append_batch` never has to |
| 956 | /// decide what a mixed batch means — the caller keeps the refused frame and |
| 957 | /// opens the next batch with it. |
| 958 | pub struct AppendBatch { |
| 959 | frames: Vec<AppendReq>, |
| 960 | } |
| 961 | |
| 962 | impl AppendBatch { |
| 963 | pub fn new(first: AppendReq) -> Self { |
| 964 | Self { |
| 965 | frames: vec![first], |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | /// Add a frame of the same fragment, or hand it back untouched. |
| 970 | pub fn try_push(&mut self, req: AppendReq) -> Result<(), AppendReq> { |
| 971 | let head = &self.frames[0]; |
| 972 | if req.leader != head.leader || req.epoch != head.epoch { |
| 973 | return Err(req); |
| 974 | } |
| 975 | self.frames.push(req); |
| 976 | Ok(()) |
| 977 | } |
| 978 | |
| 979 | pub fn frame_count(&self) -> usize { |
| 980 | self.frames.len() |
| 981 | } |
| 982 | |
| 983 | pub fn entry_count(&self) -> usize { |
| 984 | self.frames.iter().map(|frame| frame.entries.len()).sum() |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | #[derive(serde::Serialize, serde::Deserialize)] |
| 989 | pub struct AppendResp { |
| 990 | pub ok: bool, |
| 991 | pub end: u64, |
| 992 | /// The fragment epoch the reported `end` belongs to. A refusal whose |
| 993 | /// echo matches the request epoch and whose end covers the batch still |
| 994 | /// confirms durability — the retransmission case — while a refusal |
| 995 | /// from another fragment says nothing about these sequences. Absent |
| 996 | /// from binaries that predate hedging, which reads as unconfirmable. |
| 997 | #[serde(default)] |
| 998 | pub epoch: Option<u64>, |
| 999 | } |
| 1000 | |
| 1001 | #[derive(serde::Serialize, serde::Deserialize)] |
| 1002 | pub struct SealReq { |
| 1003 | #[serde(deserialize_with = "deserialize_log_leader")] |
| 1004 | pub leader: String, |
| 1005 | pub epoch: u64, |
| 1006 | } |
| 1007 | |
| 1008 | #[derive(serde::Serialize, serde::Deserialize)] |
| 1009 | pub struct SealResp { |
| 1010 | pub end: u64, |
| 1011 | /// The highest sequence that this follower already removed after the |
| 1012 | /// bucket covered it. Recovery must receive every sequence in |
| 1013 | /// `(base, end]` before this follower is complete evidence. An older |
| 1014 | /// follower omits this field, so it cannot certify a recovery pass. |
| 1015 | #[serde(default)] |
| 1016 | pub base: Option<u64>, |
| 1017 | /// The fragment epoch that this response can certify. A name-reused |
| 1018 | /// machine with a fresh disk answers 0. A follower with an incomplete |
| 1019 | /// retained range also answers 0, so an older recovery caller cannot |
| 1020 | /// count a successful-looking response with a gap. |
| 1021 | #[serde(default)] |
| 1022 | pub fragment_epoch: u64, |
| 1023 | /// The fragment epoch that this follower actually holds. Recovery uses |
| 1024 | /// this field to distinguish an incomplete current fragment from a |
| 1025 | /// different fragment. An older follower omits it. |
| 1026 | #[serde(default)] |
| 1027 | pub held_fragment_epoch: Option<u64>, |
| 1028 | } |
| 1029 | |
| 1030 | #[derive(Clone, serde::Serialize, serde::Deserialize)] |
| 1031 | pub struct TailReq { |
| 1032 | #[serde(deserialize_with = "deserialize_log_leader")] |
| 1033 | pub leader: String, |
| 1034 | } |
| 1035 | |
| 1036 | #[derive(Clone, Copy, Default, serde::Serialize, serde::Deserialize)] |
| 1037 | #[serde(try_from = "u8", into = "u8")] |
| 1038 | enum TailFormat { |
| 1039 | #[default] |
| 1040 | Legacy, |
| 1041 | Ranged, |
| 1042 | } |
| 1043 | |
| 1044 | impl TryFrom<u8> for TailFormat { |
| 1045 | type Error = &'static str; |
| 1046 | |
| 1047 | fn try_from(value: u8) -> Result<Self, Self::Error> { |
| 1048 | match value { |
| 1049 | 1 => Ok(Self::Legacy), |
| 1050 | 2 => Ok(Self::Ranged), |
| 1051 | _ => Err("unsupported tail_format"), |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | impl From<TailFormat> for u8 { |
| 1057 | fn from(value: TailFormat) -> Self { |
| 1058 | match value { |
| 1059 | TailFormat::Legacy => 1, |
| 1060 | TailFormat::Ranged => 2, |
| 1061 | } |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | /// The wire envelope keeps response negotiation out of internal disk reads. |
| 1066 | /// Old requests omit `tail_format`, so they must receive the CLT1 layout. |
| 1067 | #[derive(serde::Serialize, serde::Deserialize)] |
| 1068 | pub struct TailWireReq { |
| 1069 | #[serde(flatten)] |
| 1070 | pub request: TailReq, |
| 1071 | #[serde(default)] |
| 1072 | tail_format: TailFormat, |
| 1073 | } |
| 1074 | |
| 1075 | impl TailWireReq { |
| 1076 | pub fn ranged(request: TailReq) -> Self { |
| 1077 | Self { |
| 1078 | request, |
| 1079 | tail_format: TailFormat::Ranged, |
| 1080 | } |
| 1081 | } |
| 1082 | |
| 1083 | pub fn encode_response(&self, response: &TailResp) -> anyhow::Result<Vec<u8>> { |
| 1084 | match self.tail_format { |
| 1085 | TailFormat::Ranged => Ok(encode_tail_resp(response)), |
| 1086 | TailFormat::Legacy => { |
| 1087 | // A legacy reader cannot see an incomplete range or an absent |
| 1088 | // fragment epoch. Stripping that evidence into a successful |
| 1089 | // entries-only response would revive silent partial recovery. |
| 1090 | anyhow::ensure!( |
| 1091 | response.range.fragment_epoch != 0 |
| 1092 | && response.range.complete |
| 1093 | && tail_covers_sealed_range( |
| 1094 | response.range.base, |
| 1095 | response.range.end, |
| 1096 | &response.entries, |
| 1097 | ), |
| 1098 | "log wire: legacy tail cannot certify the retained range" |
| 1099 | ); |
| 1100 | let mut out = Vec::new(); |
| 1101 | out.extend_from_slice(LEGACY_TAIL_MAGIC); |
| 1102 | out.extend_from_slice(&(response.entries.len() as u32).to_le_bytes()); |
| 1103 | for entry in &response.entries { |
| 1104 | encode_entry(entry, &mut out); |
| 1105 | } |
| 1106 | Ok(out) |
| 1107 | } |
| 1108 | } |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1113 | pub struct TailRange { |
| 1114 | pub fragment_epoch: u64, |
| 1115 | pub base: u64, |
| 1116 | pub end: u64, |
| 1117 | /// True only when the response contains every retained sequence and no |
| 1118 | /// unreadable batch can hide a sequence that the process forgot on restart. |
| 1119 | pub complete: bool, |
| 1120 | } |
| 1121 | |
| 1122 | pub struct TailResp { |
| 1123 | pub range: TailRange, |
| 1124 | pub entries: Vec<Entry>, |
| 1125 | } |
| 1126 | |
| 1127 | /// An old response is decodable data, not evidence of either completeness |
| 1128 | /// or loss. Never synthesize a retained range from its returned entries. |
| 1129 | pub enum TailReply { |
| 1130 | Legacy { entries: Vec<Entry> }, |
| 1131 | Ranged(TailResp), |
| 1132 | } |
| 1133 | |
| 1134 | // ── The follower side ─────────────────────────────────────────────────────── |
| 1135 | |
| 1136 | #[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Default, PartialEq, Eq)] |
| 1137 | #[doc(hidden)] |
| 1138 | pub struct FollowerState { |
| 1139 | pub fragment_epoch: u64, |
| 1140 | pub base: u64, |
| 1141 | pub end: u64, |
| 1142 | pub sealed_to: u64, |
| 1143 | } |
| 1144 | |
| 1145 | // A committed follower batch carries the state transition that its entries |
| 1146 | // make durable. The SHA-256 footer distinguishes a complete fsynced batch from |
| 1147 | // a crash-torn direct write, so the batch itself can be the recovery commit |
| 1148 | // point without a second state-file fsync and rename. |
| 1149 | // |
| 1150 | // batch: "CLB1" fragment_epoch base end sealed_to count entry* sha256 |
| 1151 | const COMMITTED_BATCH_MAGIC: &[u8; 4] = b"CLB1"; |
| 1152 | const COMMITTED_BATCH_DIGEST_LEN: usize = 32; |
| 1153 | |
| 1154 | struct CommittedBatch { |
| 1155 | state: FollowerState, |
| 1156 | entries: Vec<Entry>, |
| 1157 | } |
| 1158 | |
| 1159 | struct CommittedBatchScan { |
| 1160 | batches: Vec<CommittedBatch>, |
| 1161 | unreadable_ranges: Vec<(u64, u64)>, |
| 1162 | unknown_unreadable_range: bool, |
| 1163 | } |
| 1164 | |
| 1165 | #[derive(Clone, Copy)] |
| 1166 | enum SuspectEnd { |
| 1167 | Known(u64), |
| 1168 | Unknown, |
| 1169 | } |
| 1170 | |
| 1171 | #[derive(Clone, Copy)] |
| 1172 | struct DiskRecoveryGap { |
| 1173 | fragment_epoch: u64, |
| 1174 | suspect_end: SuspectEnd, |
| 1175 | } |
| 1176 | |
| 1177 | #[derive(Clone, Copy)] |
| 1178 | struct LoadedFollowerState { |
| 1179 | state: FollowerState, |
| 1180 | disk_recovery_gap: Option<DiskRecoveryGap>, |
| 1181 | } |
| 1182 | |
| 1183 | impl CommittedBatchScan { |
| 1184 | fn recovery_gap(&self, state: FollowerState) -> Option<DiskRecoveryGap> { |
| 1185 | if state.fragment_epoch == 0 { |
| 1186 | return None; |
| 1187 | } |
| 1188 | if self.unknown_unreadable_range { |
| 1189 | return Some(DiskRecoveryGap { |
| 1190 | fragment_epoch: state.fragment_epoch, |
| 1191 | suspect_end: SuspectEnd::Unknown, |
| 1192 | }); |
| 1193 | } |
| 1194 | let suspect_end = self |
| 1195 | .batches |
| 1196 | .iter() |
| 1197 | .filter(|batch| batch.state.fragment_epoch == state.fragment_epoch) |
| 1198 | .map(|batch| batch.state.end) |
| 1199 | .chain(self.unreadable_ranges.iter().map(|(_, last)| *last)) |
| 1200 | .max() |
| 1201 | .filter(|end| *end > state.end)?; |
| 1202 | Some(DiskRecoveryGap { |
| 1203 | fragment_epoch: state.fragment_epoch, |
| 1204 | suspect_end: SuspectEnd::Known(suspect_end), |
| 1205 | }) |
| 1206 | } |
| 1207 | } |
| 1208 | |
| 1209 | fn encode_committed_batch(state: FollowerState, entries: &[Entry]) -> Vec<u8> { |
| 1210 | use sha2::Digest as _; |
| 1211 | |
| 1212 | let mut out = Vec::new(); |
| 1213 | out.extend_from_slice(COMMITTED_BATCH_MAGIC); |
| 1214 | out.extend_from_slice(&state.fragment_epoch.to_le_bytes()); |
| 1215 | out.extend_from_slice(&state.base.to_le_bytes()); |
| 1216 | out.extend_from_slice(&state.end.to_le_bytes()); |
| 1217 | out.extend_from_slice(&state.sealed_to.to_le_bytes()); |
| 1218 | out.extend_from_slice(&(entries.len() as u32).to_le_bytes()); |
| 1219 | for entry in entries { |
| 1220 | encode_entry(entry, &mut out); |
| 1221 | } |
| 1222 | let digest = sha2::Sha256::digest(&out); |
| 1223 | out.extend_from_slice(&digest); |
| 1224 | out |
| 1225 | } |
| 1226 | |
| 1227 | fn decode_committed_batch(bytes: &[u8]) -> anyhow::Result<CommittedBatch> { |
| 1228 | use sha2::Digest as _; |
| 1229 | |
| 1230 | let payload_len = bytes |
| 1231 | .len() |
| 1232 | .checked_sub(COMMITTED_BATCH_DIGEST_LEN) |
| 1233 | .ok_or_else(|| anyhow!("follower batch is shorter than its digest"))?; |
| 1234 | let (payload, stored_digest) = bytes.split_at(payload_len); |
| 1235 | let actual_digest = sha2::Sha256::digest(payload); |
| 1236 | if actual_digest.as_slice() != stored_digest { |
| 1237 | anyhow::bail!("follower batch digest mismatch"); |
| 1238 | } |
| 1239 | |
| 1240 | let mut buf = payload; |
| 1241 | if take(&mut buf, 4, "follower batch magic")? != COMMITTED_BATCH_MAGIC { |
| 1242 | anyhow::bail!("bad follower batch magic"); |
| 1243 | } |
| 1244 | let state = FollowerState { |
| 1245 | fragment_epoch: take_u64(&mut buf, "follower batch epoch")?, |
| 1246 | base: take_u64(&mut buf, "follower batch base")?, |
| 1247 | end: take_u64(&mut buf, "follower batch end")?, |
| 1248 | sealed_to: take_u64(&mut buf, "follower batch seal")?, |
| 1249 | }; |
| 1250 | let entries = decode_entries(&mut buf, "follower batch")?; |
| 1251 | let Some(first) = entries.first() else { |
| 1252 | anyhow::bail!("follower batch has no entries"); |
| 1253 | }; |
| 1254 | let last = entries.last().expect("a non-empty batch has a last entry"); |
| 1255 | if state.fragment_epoch == 0 || state.base > state.end || state.end != last.seq { |
| 1256 | anyhow::bail!("follower batch state does not cover its entries"); |
| 1257 | } |
| 1258 | if entries |
| 1259 | .windows(2) |
| 1260 | .any(|pair| pair[1].seq != pair[0].seq.saturating_add(1)) |
| 1261 | { |
| 1262 | anyhow::bail!("follower batch entries are not contiguous"); |
| 1263 | } |
| 1264 | if first.seq <= state.base { |
| 1265 | anyhow::bail!("follower batch starts at or below its base"); |
| 1266 | } |
| 1267 | Ok(CommittedBatch { state, entries }) |
| 1268 | } |
| 1269 | |
| 1270 | fn follower_batch_range(name: &str, suffix: &str) -> Option<(u64, u64)> { |
| 1271 | let stem = name.strip_suffix(suffix)?; |
| 1272 | let (first, last) = stem.split_once('-')?; |
| 1273 | Some((first.parse().ok()?, last.parse().ok()?)) |
| 1274 | } |
| 1275 | |
| 1276 | #[cfg(celld_internal_tests)] |
| 1277 | #[doc(hidden)] |
| 1278 | pub fn sync_directory(path: &Path) -> std::io::Result<()> { |
| 1279 | let filesystem = celld_ltx::DirectFileSystem; |
| 1280 | celld_ltx::FileSystem::sync_all(&filesystem, path) |
| 1281 | } |
| 1282 | |
| 1283 | #[cfg(celld_internal_tests)] |
| 1284 | type DirectorySyncForTest = dyn Fn(&Path) -> std::io::Result<()> + Send + Sync; |
| 1285 | |
| 1286 | #[derive(Default)] |
| 1287 | struct FollowerPersistTiming { |
| 1288 | write_us: u64, |
| 1289 | fsync_us: u64, |
| 1290 | rename_us: u64, |
| 1291 | directory_us: u64, |
| 1292 | } |
| 1293 | |
| 1294 | /// One node's store of the log fragments that it follows. |
| 1295 | /// |
| 1296 | /// Each follower session uses `<root>/peerlog/<node>/<generation>/`. The store |
| 1297 | /// persists the seal mark before it sends the response, so the mark survives a |
| 1298 | /// follower restart. The store also reads the former flat layout during an |
| 1299 | /// upgrade. |
| 1300 | pub struct FollowerStore { |
| 1301 | root: PathBuf, |
| 1302 | filesystem: Arc<dyn celld_ltx::FileSystem>, |
| 1303 | bucket: Option<Arc<Bucket>>, |
| 1304 | node: String, |
| 1305 | /// A fresh process can recover a smaller end after it finds a damaged |
| 1306 | /// batch or a gap between valid batches. Keep that evidence beside the |
| 1307 | /// recovered state, so an empty recovered range cannot certify completeness. |
| 1308 | logs: Mutex<HashMap<String, LoadedFollowerState>>, |
| 1309 | /// Per-leader mutual exclusion over the whole read-modify-write of a |
| 1310 | /// fragment. Without it, an append that loaded state before a seal |
| 1311 | /// persists writes the stale `sealed_to` back afterwards — the seal |
| 1312 | /// mark is atomic in the model and must be atomic here. |
| 1313 | guards: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>, |
| 1314 | /// Leaders whose directory chain this process has already fsynced to |
| 1315 | /// the data root. Ancestor directory entries only change when the |
| 1316 | /// leader directory is created, so re-syncing them on every state |
| 1317 | /// persist was one serial fsync chain per append — the write-latency |
| 1318 | /// floor the 2026-08-25 gate decomposition landed on. A restart |
| 1319 | /// starts empty and conservatively re-syncs each chain once. |
| 1320 | synced_namespaces: Mutex<std::collections::BTreeSet<String>>, |
| 1321 | #[cfg(celld_internal_tests)] |
| 1322 | directory_sync_for_test: Arc<DirectorySyncForTest>, |
| 1323 | } |
| 1324 | |
| 1325 | impl FollowerStore { |
| 1326 | pub fn new(root: &Path, bucket: Option<Arc<Bucket>>, node: &str) -> Self { |
| 1327 | let filesystem = crate::asyncrt::fs(); |
| 1328 | #[cfg(celld_internal_tests)] |
| 1329 | let directory_filesystem = filesystem.clone(); |
| 1330 | Self { |
| 1331 | root: root.join("peerlog"), |
| 1332 | filesystem, |
| 1333 | bucket, |
| 1334 | node: node.to_string(), |
| 1335 | logs: Mutex::new(HashMap::new()), |
| 1336 | guards: Mutex::new(HashMap::new()), |
| 1337 | synced_namespaces: Mutex::new(std::collections::BTreeSet::new()), |
| 1338 | #[cfg(celld_internal_tests)] |
| 1339 | directory_sync_for_test: Arc::new(move |path| directory_filesystem.sync_all(path)), |
| 1340 | } |
| 1341 | } |
| 1342 | |
| 1343 | #[cfg(celld_internal_tests)] |
| 1344 | #[doc(hidden)] |
| 1345 | pub fn new_with_directory_sync_for_test( |
| 1346 | root: &Path, |
| 1347 | bucket: Option<Arc<Bucket>>, |
| 1348 | node: &str, |
| 1349 | directory_sync: impl Fn(&Path) -> std::io::Result<()> + Send + Sync + 'static, |
| 1350 | ) -> Self { |
| 1351 | let mut store = Self::new(root, bucket, node); |
| 1352 | store.directory_sync_for_test = Arc::new(directory_sync); |
| 1353 | store |
| 1354 | } |
| 1355 | |
| 1356 | /// A store over an injected filesystem, so a test can count every |
| 1357 | /// fsync the serve path issues — the directory sync included, which is |
| 1358 | /// why the directory seam is wired to the same filesystem here. |
| 1359 | #[cfg(celld_internal_tests)] |
| 1360 | #[doc(hidden)] |
| 1361 | pub fn new_with_filesystem_for_test( |
| 1362 | root: &Path, |
| 1363 | bucket: Option<Arc<Bucket>>, |
| 1364 | node: &str, |
| 1365 | filesystem: Arc<dyn celld_ltx::FileSystem>, |
| 1366 | ) -> Self { |
| 1367 | let mut store = Self::new(root, bucket, node); |
| 1368 | let directory_filesystem = filesystem.clone(); |
| 1369 | store.filesystem = filesystem; |
| 1370 | store.directory_sync_for_test = Arc::new(move |path| directory_filesystem.sync_all(path)); |
| 1371 | store |
| 1372 | } |
| 1373 | |
| 1374 | #[cfg(celld_internal_tests)] |
| 1375 | fn sync_directory(&self, path: &Path) -> std::io::Result<()> { |
| 1376 | (self.directory_sync_for_test)(path) |
| 1377 | } |
| 1378 | |
| 1379 | #[cfg(not(celld_internal_tests))] |
| 1380 | fn sync_directory(&self, path: &Path) -> std::io::Result<()> { |
| 1381 | self.filesystem.sync_all(path) |
| 1382 | } |
| 1383 | |
| 1384 | /// Barrier every directory entry from the session leaf through the data |
| 1385 | /// root. A follower session is `<node>/<generation>`, so the chain is |
| 1386 | /// four directories deep, and a leaf-only fsync leaves the two |
| 1387 | /// intermediate entries outside the barrier the acknowledgment claims. |
| 1388 | /// |
| 1389 | /// The chain is walked on every persist, not only when `create_dir_all` |
| 1390 | /// reports a fresh directory. A predecessor process can create the |
| 1391 | /// chain and die before its own barrier completes; this process would |
| 1392 | /// then find the directories present, skip the fsync, and acknowledge |
| 1393 | /// over a chain that was never durable. The price is four directory |
| 1394 | /// fsyncs for each persist — nine for a steady-state append, which |
| 1395 | /// persists twice for the truncate and syncs the leaf once more for the |
| 1396 | /// entry files. |
| 1397 | fn sync_namespace_to_data_root(&self, leaf: &Path) -> anyhow::Result<()> { |
| 1398 | let data_root = self |
| 1399 | .root |
| 1400 | .parent() |
| 1401 | .ok_or_else(|| anyhow!("peerlog root has no data-root parent"))?; |
| 1402 | for directory in leaf.ancestors() { |
| 1403 | self.sync_directory(directory)?; |
| 1404 | if directory == data_root { |
| 1405 | return Ok(()); |
| 1406 | } |
| 1407 | } |
| 1408 | Err(anyhow!( |
| 1409 | "follower directory {} is outside data root {}", |
| 1410 | leaf.display(), |
| 1411 | data_root.display() |
| 1412 | )) |
| 1413 | } |
| 1414 | |
| 1415 | /// Make the leader directory durable, and the first time this process |
| 1416 | /// commits anything for `leader`, its ancestor chain as well. The leaf |
| 1417 | /// sync makes a rename or a new batch file durable on every commit; the |
| 1418 | /// ancestor chain only holds the directory's creation, so it is synced |
| 1419 | /// once per (process, leader) rather than on every append serve cycle, |
| 1420 | /// and a failed chain sync re-arms so the next commit retries it. A |
| 1421 | /// predecessor can create the chain and die before its own barrier |
| 1422 | /// completes, so a directory that already exists proves nothing. Both |
| 1423 | /// the state chain and the batch commit go through here: a batch |
| 1424 | /// acknowledged over a chain this process never synced would claim a |
| 1425 | /// durability its directory entries do not have. |
| 1426 | fn sync_leader_directory(&self, leader: &str, dir: &Path) -> anyhow::Result<()> { |
| 1427 | let first_commit = self |
| 1428 | .synced_namespaces |
| 1429 | .lock() |
| 1430 | .unwrap() |
| 1431 | .insert(leader.to_string()); |
| 1432 | if first_commit { |
| 1433 | if let Err(error) = self.sync_namespace_to_data_root(dir) { |
| 1434 | self.synced_namespaces.lock().unwrap().remove(leader); |
| 1435 | return Err(error); |
| 1436 | } |
| 1437 | return Ok(()); |
| 1438 | } |
| 1439 | self.sync_directory(dir)?; |
| 1440 | Ok(()) |
| 1441 | } |
| 1442 | |
| 1443 | fn guard(&self, leader: &str) -> Arc<tokio::sync::Mutex<()>> { |
| 1444 | self.guards |
| 1445 | .lock() |
| 1446 | .unwrap() |
| 1447 | .entry(leader.to_string()) |
| 1448 | .or_default() |
| 1449 | .clone() |
| 1450 | } |
| 1451 | |
| 1452 | fn dir(&self, leader: &str) -> PathBuf { |
| 1453 | self.root.join(leader) |
| 1454 | } |
| 1455 | |
| 1456 | fn followed_sessions(&self) -> Vec<String> { |
| 1457 | let mut sessions = Vec::new(); |
| 1458 | let Ok(nodes) = self.filesystem.read_dir(&self.root) else { |
| 1459 | return sessions; |
| 1460 | }; |
| 1461 | for node in nodes.into_iter().filter(|item| item.is_dir) { |
| 1462 | let Some(node_name) = node.file_name.to_str().map(str::to_string) else { |
| 1463 | continue; |
| 1464 | }; |
| 1465 | if self |
| 1466 | .filesystem |
| 1467 | .metadata(&node.path.join("state.json")) |
| 1468 | .is_ok_and(|metadata| metadata.is_file) |
| 1469 | { |
| 1470 | // Keep fragments written by the former flat leader identity |
| 1471 | // reachable during an upgrade. |
| 1472 | sessions.push(node_name.clone()); |
| 1473 | } |
| 1474 | let Ok(generations) = self.filesystem.read_dir(&node.path) else { |
| 1475 | continue; |
| 1476 | }; |
| 1477 | for generation in generations.into_iter().filter(|item| item.is_dir) { |
| 1478 | let Some(generation_name) = generation.file_name.to_str().map(str::to_string) |
| 1479 | else { |
| 1480 | continue; |
| 1481 | }; |
| 1482 | if self |
| 1483 | .filesystem |
| 1484 | .metadata(&generation.path.join("state.json")) |
| 1485 | .is_ok_and(|metadata| metadata.is_file) |
| 1486 | { |
| 1487 | sessions.push(format!("{node_name}/{generation_name}")); |
| 1488 | } |
| 1489 | } |
| 1490 | } |
| 1491 | sessions.sort(); |
| 1492 | sessions.dedup(); |
| 1493 | sessions |
| 1494 | } |
| 1495 | |
| 1496 | fn scan_committed_batches(&self, leader: &str) -> anyhow::Result<CommittedBatchScan> { |
| 1497 | let dir = self.dir(leader); |
| 1498 | let read = match self.filesystem.read_dir(&dir) { |
| 1499 | Ok(read) => read, |
| 1500 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(), |
| 1501 | // A failed observation is retryable, not evidence of a damaged |
| 1502 | // batch. Caching it as an unknown gap would reject healthy tails |
| 1503 | // for the rest of the epoch and could declare a false loss. |
| 1504 | Err(error) => return Err(error.into()), |
| 1505 | }; |
| 1506 | let mut batches = Vec::new(); |
| 1507 | let mut unreadable_ranges = Vec::new(); |
| 1508 | let mut unknown_unreadable_range = false; |
| 1509 | for item in read { |
| 1510 | let Some(name) = item.file_name.to_str() else { |
| 1511 | if item |
| 1512 | .path |
| 1513 | .extension() |
| 1514 | .is_some_and(|suffix| suffix == "batch") |
| 1515 | { |
| 1516 | unknown_unreadable_range = true; |
| 1517 | warn!( |
| 1518 | leader, |
| 1519 | path = %item.path.display(), |
| 1520 | "follower batch has a non-UTF-8 name" |
| 1521 | ); |
| 1522 | } |
| 1523 | continue; |
| 1524 | }; |
| 1525 | if !name.ends_with(".batch") { |
| 1526 | continue; |
| 1527 | } |
| 1528 | let Some((named_first, named_last)) = follower_batch_range(name, ".batch") else { |
| 1529 | unknown_unreadable_range = true; |
| 1530 | warn!( |
| 1531 | leader, |
| 1532 | path = %item.path.display(), |
| 1533 | "follower batch name does not contain a valid range" |
| 1534 | ); |
| 1535 | continue; |
| 1536 | }; |
| 1537 | if named_first > named_last { |
| 1538 | unknown_unreadable_range = true; |
| 1539 | warn!( |
| 1540 | leader, |
| 1541 | path = %item.path.display(), |
| 1542 | "follower batch name contains a reversed range" |
| 1543 | ); |
| 1544 | continue; |
| 1545 | } |
| 1546 | let decoded = self |
| 1547 | .filesystem |
| 1548 | .read(&item.path) |
| 1549 | .map_err(anyhow::Error::from) |
| 1550 | .and_then(|bytes| decode_committed_batch(&bytes)); |
| 1551 | match decoded { |
| 1552 | Ok(batch) |
| 1553 | if batch.entries.first().map(|entry| entry.seq) == Some(named_first) |
| 1554 | && batch.entries.last().map(|entry| entry.seq) == Some(named_last) => |
| 1555 | { |
| 1556 | batches.push(batch); |
| 1557 | } |
| 1558 | Ok(_) => { |
| 1559 | unreadable_ranges.push((named_first, named_last)); |
| 1560 | warn!( |
| 1561 | leader, |
| 1562 | path = %item.path.display(), |
| 1563 | "follower batch filename does not match its committed range" |
| 1564 | ); |
| 1565 | } |
| 1566 | Err(error) => { |
| 1567 | unreadable_ranges.push((named_first, named_last)); |
| 1568 | warn!( |
| 1569 | leader, |
| 1570 | path = %item.path.display(), |
| 1571 | %error, |
| 1572 | "invalid committed follower batch ignored" |
| 1573 | ); |
| 1574 | } |
| 1575 | } |
| 1576 | } |
| 1577 | batches.sort_by_key(|batch| batch.entries.first().map_or(0, |entry| entry.seq)); |
| 1578 | Ok(CommittedBatchScan { |
| 1579 | batches, |
| 1580 | unreadable_ranges, |
| 1581 | unknown_unreadable_range, |
| 1582 | }) |
| 1583 | } |
| 1584 | |
| 1585 | /// Recover the newest checksum-valid state whose live suffix is complete. |
| 1586 | /// The durable state file proves its prefix. A later batch can advance the |
| 1587 | /// base past a missing prefix because its `base` is a bucket watermark; |
| 1588 | /// every sequence above that base must still be present without a gap. |
| 1589 | fn recover_committed_state( |
| 1590 | &self, |
| 1591 | seed: FollowerState, |
| 1592 | batches: &[CommittedBatch], |
| 1593 | ) -> FollowerState { |
| 1594 | if seed.fragment_epoch == 0 { |
| 1595 | return seed; |
| 1596 | } |
| 1597 | let mut candidates: Vec<&CommittedBatch> = batches |
| 1598 | .iter() |
| 1599 | .filter(|batch| { |
| 1600 | batch.state.fragment_epoch == seed.fragment_epoch && batch.state.end > seed.end |
| 1601 | }) |
| 1602 | .collect(); |
| 1603 | candidates.sort_by_key(|batch| std::cmp::Reverse(batch.state.end)); |
| 1604 | for candidate in candidates { |
| 1605 | let mut covered = seed.end.max(candidate.state.base); |
| 1606 | for batch in batches |
| 1607 | .iter() |
| 1608 | .filter(|batch| batch.state.fragment_epoch == seed.fragment_epoch) |
| 1609 | { |
| 1610 | let first = batch |
| 1611 | .entries |
| 1612 | .first() |
| 1613 | .expect("committed batches are non-empty") |
| 1614 | .seq; |
| 1615 | let last = batch |
| 1616 | .entries |
| 1617 | .last() |
| 1618 | .expect("committed batches are non-empty") |
| 1619 | .seq; |
| 1620 | if last <= covered { |
| 1621 | continue; |
| 1622 | } |
| 1623 | if first > covered.saturating_add(1) { |
| 1624 | break; |
| 1625 | } |
| 1626 | covered = covered.max(last); |
| 1627 | } |
| 1628 | if covered >= candidate.state.end { |
| 1629 | return FollowerState { |
| 1630 | fragment_epoch: seed.fragment_epoch, |
| 1631 | base: seed.base.max(candidate.state.base), |
| 1632 | end: candidate.state.end, |
| 1633 | sealed_to: seed.sealed_to.max(candidate.state.sealed_to), |
| 1634 | }; |
| 1635 | } |
| 1636 | } |
| 1637 | seed |
| 1638 | } |
| 1639 | |
| 1640 | #[doc(hidden)] |
| 1641 | pub fn load(&self, leader: &str) -> anyhow::Result<FollowerState> { |
| 1642 | if let Some(loaded) = self.logs.lock().unwrap().get(leader) { |
| 1643 | return Ok(loaded.state); |
| 1644 | } |
| 1645 | let seed = self |
| 1646 | .filesystem |
| 1647 | .read(&self.dir(leader).join("state.json")) |
| 1648 | .ok() |
| 1649 | .and_then(|bytes| serde_json::from_slice(&bytes).ok()) |
| 1650 | .unwrap_or_default(); |
| 1651 | // Use one directory observation for both recovery and its evidence. |
| 1652 | // A second scan could lose the invalid or later file that explains why |
| 1653 | // recovery stopped, then certify the shortened state as complete. |
| 1654 | let batch_scan = self.scan_committed_batches(leader)?; |
| 1655 | let state = self.recover_committed_state(seed, &batch_scan.batches); |
| 1656 | self.logs.lock().unwrap().insert( |
| 1657 | leader.to_string(), |
| 1658 | LoadedFollowerState { |
| 1659 | state, |
| 1660 | disk_recovery_gap: batch_scan.recovery_gap(state), |
| 1661 | }, |
| 1662 | ); |
| 1663 | Ok(state) |
| 1664 | } |
| 1665 | |
| 1666 | fn cache_state(&self, leader: &str, state: FollowerState) { |
| 1667 | let mut logs = self.logs.lock().unwrap(); |
| 1668 | let disk_recovery_gap = logs.get(leader).and_then(|loaded| { |
| 1669 | let gap = loaded.disk_recovery_gap?; |
| 1670 | (gap.fragment_epoch == state.fragment_epoch |
| 1671 | && !matches!(gap.suspect_end, SuspectEnd::Known(end) if state.end >= end)) |
| 1672 | .then_some(gap) |
| 1673 | }); |
| 1674 | logs.insert( |
| 1675 | leader.to_string(), |
| 1676 | LoadedFollowerState { |
| 1677 | state, |
| 1678 | disk_recovery_gap, |
| 1679 | }, |
| 1680 | ); |
| 1681 | } |
| 1682 | |
| 1683 | fn recovered_disk_range_complete(&self, leader: &str) -> bool { |
| 1684 | self.logs |
| 1685 | .lock() |
| 1686 | .unwrap() |
| 1687 | .get(leader) |
| 1688 | .is_none_or(|loaded| loaded.disk_recovery_gap.is_none()) |
| 1689 | } |
| 1690 | |
| 1691 | #[doc(hidden)] |
| 1692 | pub fn persist(&self, leader: &str, state: FollowerState) -> anyhow::Result<()> { |
| 1693 | self.persist_timed(leader, state).map(|_| ()) |
| 1694 | } |
| 1695 | |
| 1696 | fn persist_timed( |
| 1697 | &self, |
| 1698 | leader: &str, |
| 1699 | state: FollowerState, |
| 1700 | ) -> anyhow::Result<FollowerPersistTiming> { |
| 1701 | let dir = self.dir(leader); |
| 1702 | self.filesystem.create_dir_all(&dir)?; |
| 1703 | let path = dir.join("state.json"); |
| 1704 | let tmp = dir.join("state.json.tmp"); |
| 1705 | let write_started = mono_us(); |
| 1706 | self.filesystem.write(&tmp, &serde_json::to_vec(&state)?)?; |
| 1707 | let write_us = mono_us().saturating_sub(write_started); |
| 1708 | let fsync_started = mono_us(); |
| 1709 | self.filesystem.sync_all(&tmp)?; |
| 1710 | let fsync_us = mono_us().saturating_sub(fsync_started); |
| 1711 | let rename_started = mono_us(); |
| 1712 | self.filesystem.rename(&tmp, &path)?; |
| 1713 | let rename_us = mono_us().saturating_sub(rename_started); |
| 1714 | let dir_started = mono_us(); |
| 1715 | self.sync_leader_directory(leader, &dir)?; |
| 1716 | let directory_us = mono_us().saturating_sub(dir_started); |
| 1717 | self.cache_state(leader, state); |
| 1718 | Ok(FollowerPersistTiming { |
| 1719 | write_us, |
| 1720 | fsync_us, |
| 1721 | rename_us, |
| 1722 | directory_us, |
| 1723 | }) |
| 1724 | } |
| 1725 | |
| 1726 | /// Adopt a new fragment epoch — only against the record. A leader's |
| 1727 | /// stream announcing an epoch is not authority: a fenced leader could |
| 1728 | /// invent one above our seal mark and talk past the fence, so the view |
| 1729 | /// change is verified against `log/<leader>.json` before any entry at |
| 1730 | /// the new epoch is accepted. |
| 1731 | async fn adopt(&self, leader: &str, epoch: u64, first_seq: u64) -> bool { |
| 1732 | let Some(bucket) = &self.bucket else { |
| 1733 | return false; |
| 1734 | }; |
| 1735 | let record = match read_record(bucket, leader).await { |
| 1736 | Ok(Some(folded)) => folded.record, |
| 1737 | _ => return false, |
| 1738 | }; |
| 1739 | let member = record.ensemble.contains(&self.node); |
| 1740 | let Ok(state) = self.load(leader) else { |
| 1741 | return false; |
| 1742 | }; |
| 1743 | if record.epoch != epoch |
| 1744 | || record.state != LogState::Open |
| 1745 | || !member |
| 1746 | || state.sealed_to >= epoch |
| 1747 | || first_seq != 1 |
| 1748 | { |
| 1749 | return false; |
| 1750 | } |
| 1751 | // A new fragment has no durable records before its first append. |
| 1752 | // Starting above sequence 1 would let its seal response certify an |
| 1753 | // epoch whose missing prefix cannot be gathered during recovery. |
| 1754 | // Old-fragment entries are garbage the record no longer references. |
| 1755 | // A damaged old batch has no readable epoch. If cleanup fails, its |
| 1756 | // range can poison the new fragment's completeness evidence. Refuse |
| 1757 | // adoption until cleanup succeeds; persist also syncs these deletions. |
| 1758 | if let Err(error) = self.remove_entries_below(leader, u64::MAX) { |
| 1759 | warn!(leader, epoch, %error, "fragment adoption could not remove the old files"); |
| 1760 | return false; |
| 1761 | } |
| 1762 | self.persist( |
| 1763 | leader, |
| 1764 | FollowerState { |
| 1765 | fragment_epoch: epoch, |
| 1766 | base: first_seq.saturating_sub(1), |
| 1767 | end: first_seq.saturating_sub(1), |
| 1768 | sealed_to: state.sealed_to, |
| 1769 | }, |
| 1770 | ) |
| 1771 | .is_ok() |
| 1772 | } |
| 1773 | |
| 1774 | fn remove_entries_below(&self, leader: &str, seq: u64) -> anyhow::Result<()> { |
| 1775 | let dir = self.dir(leader); |
| 1776 | let read = match self.filesystem.read_dir(&dir) { |
| 1777 | Ok(read) => read, |
| 1778 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), |
| 1779 | Err(error) => return Err(error.into()), |
| 1780 | }; |
| 1781 | for item in read { |
| 1782 | let name = item.file_name; |
| 1783 | let Some(name) = name.to_str() else { continue }; |
| 1784 | if let Some(stem) = name.strip_suffix(".entry") { |
| 1785 | if stem.parse::<u64>().is_ok_and(|s| s <= seq) { |
| 1786 | self.filesystem.remove_file(&item.path)?; |
| 1787 | } |
| 1788 | } else if let Some(stem) = name.strip_suffix(".entries") { |
| 1789 | // A batch file goes only when its WHOLE range is behind the |
| 1790 | // watermark. A straddling batch keeps its covered entries: |
| 1791 | // truncation is space reclamation, not a correctness |
| 1792 | // boundary, so retaining them is free. |
| 1793 | if stem |
| 1794 | .split_once('-') |
| 1795 | .and_then(|(_, last)| last.parse::<u64>().ok()) |
| 1796 | .is_some_and(|last| last <= seq) |
| 1797 | { |
| 1798 | self.filesystem.remove_file(&item.path)?; |
| 1799 | } |
| 1800 | } else if follower_batch_range(name, ".batch").is_some_and(|(_, last)| last <= seq) { |
| 1801 | self.filesystem.remove_file(&item.path)?; |
| 1802 | } |
| 1803 | } |
| 1804 | Ok(()) |
| 1805 | } |
| 1806 | |
| 1807 | /// One frame through the batch commit: the stream and the one-shot |
| 1808 | /// `/peer/log/append` share a single implementation, so an answer |
| 1809 | /// means the same thing on both transports. |
| 1810 | pub async fn append(&self, req: AppendReq) -> AppendResp { |
| 1811 | let mut answers = self.append_batch(AppendBatch::new(req)).await; |
| 1812 | debug_assert_eq!(answers.len(), 1, "one frame in, one answer out"); |
| 1813 | answers.pop().expect("append_batch answers every frame") |
| 1814 | } |
| 1815 | |
| 1816 | /// Commit a batch of consecutive frames of one fragment as ONE |
| 1817 | /// durability chain and answer every frame from the committed end. |
| 1818 | /// |
| 1819 | /// Each frame's answer is its own: confirmed when the committed end |
| 1820 | /// reaches its last sequence, refused otherwise — exactly what it |
| 1821 | /// would have received alone, because the contiguity rule accepts the |
| 1822 | /// batch's entries in the order the frames arrived and a refusal stops |
| 1823 | /// the batch where a lone frame would have been refused. The cost this |
| 1824 | /// removes is one fsync chain per frame; see `serve_log_stream`. |
| 1825 | pub async fn append_batch(&self, batch: AppendBatch) -> Vec<AppendResp> { |
| 1826 | fn refusals(count: usize, state: FollowerState) -> Vec<AppendResp> { |
| 1827 | (0..count) |
| 1828 | .map(|_| AppendResp { |
| 1829 | ok: false, |
| 1830 | end: state.end, |
| 1831 | epoch: Some(state.fragment_epoch), |
| 1832 | }) |
| 1833 | .collect() |
| 1834 | } |
| 1835 | let frames = batch.frames; |
| 1836 | let leader = frames[0].leader.clone(); |
| 1837 | let epoch = frames[0].epoch; |
| 1838 | let total_entries: usize = frames.iter().map(|frame| frame.entries.len()).sum(); |
| 1839 | let handled = mono_us(); |
| 1840 | let guard = self.guard(&leader); |
| 1841 | let guard_started = mono_us(); |
| 1842 | let _held = guard.lock().await; |
| 1843 | let guard_us = mono_us().saturating_sub(guard_started); |
| 1844 | let _emit = HandleTiming { |
| 1845 | handled, |
| 1846 | guard_us, |
| 1847 | entries: total_entries, |
| 1848 | }; |
| 1849 | let mut state = match self.load(&leader) { |
| 1850 | Ok(state) => state, |
| 1851 | Err(error) => { |
| 1852 | warn!(leader, %error, "append could not recover the follower state"); |
| 1853 | return refusals(frames.len(), FollowerState::default()); |
| 1854 | } |
| 1855 | }; |
| 1856 | if state.fragment_epoch != epoch { |
| 1857 | if total_entries == 0 { |
| 1858 | // An idle probe at an epoch we do not hold: adopting here |
| 1859 | // would fix the fragment base at zero and poison the next |
| 1860 | // real append, so refuse — the probe measured the guard |
| 1861 | // lock and nothing else. |
| 1862 | return refusals(frames.len(), state); |
| 1863 | } |
| 1864 | let first = frames |
| 1865 | .iter() |
| 1866 | .flat_map(|frame| frame.entries.first()) |
| 1867 | .map(|entry| entry.seq) |
| 1868 | .next() |
| 1869 | .unwrap_or(0); |
| 1870 | if !self.adopt(&leader, epoch, first).await { |
| 1871 | // A refusal here degrades the leader to bucket acks; the |
| 1872 | // silent version cost the lab an unattributed 85 s window. |
| 1873 | warn!( |
| 1874 | leader, |
| 1875 | epoch, |
| 1876 | held_epoch = state.fragment_epoch, |
| 1877 | sealed_to = state.sealed_to, |
| 1878 | "append refused: fragment adoption failed against the record" |
| 1879 | ); |
| 1880 | return refusals(frames.len(), state); |
| 1881 | } |
| 1882 | // Successful adoption installed its state in the cache. |
| 1883 | state = match self.load(&leader) { |
| 1884 | Ok(state) => state, |
| 1885 | Err(_) => return refusals(frames.len(), state), |
| 1886 | }; |
| 1887 | } |
| 1888 | // The shipping decision is celld_logic::log_tier::FollowerLog; drive |
| 1889 | // it entry by entry so the seal and contiguity refusals are exactly |
| 1890 | // the modeled ones. |
| 1891 | let mut log = log_tier::FollowerLog { |
| 1892 | fragment_epoch: state.fragment_epoch, |
| 1893 | base: state.base, |
| 1894 | end: state.end, |
| 1895 | sealed_to: state.sealed_to, |
| 1896 | }; |
| 1897 | let dir = self.dir(&leader); |
| 1898 | if self.filesystem.create_dir_all(&dir).is_err() { |
| 1899 | return refusals(frames.len(), state); |
| 1900 | } |
| 1901 | // The accepted prefix of every frame in the burst persists as ONE |
| 1902 | // checksum-protected commit file. It carries the entries and their |
| 1903 | // resulting follower state, so one file fsync plus the directory |
| 1904 | // barrier makes the whole transition recoverable — per burst, not |
| 1905 | // per frame. A crash-torn direct write has no valid digest and is |
| 1906 | // ignored; a later state-file rewrite is not on the hot append path. |
| 1907 | let persist_started = mono_ms(); |
| 1908 | let mut entry_write_us = 0_u64; |
| 1909 | let mut entry_fsync_us = 0_u64; |
| 1910 | let mut entry_directory_us = 0_u64; |
| 1911 | // Each frame's answer needs its own last sequence after the frames |
| 1912 | // have given up their entries to the commit below. |
| 1913 | let frame_count = frames.len(); |
| 1914 | let lasts: Vec<Option<u64>> = frames |
| 1915 | .iter() |
| 1916 | .map(|frame| frame.entries.last().map(|entry| entry.seq)) |
| 1917 | .collect(); |
| 1918 | let truncate_to = frames |
| 1919 | .iter() |
| 1920 | .map(|frame| frame.truncate_to) |
| 1921 | .max() |
| 1922 | .unwrap_or(0); |
| 1923 | let mut accepted: Vec<Entry> = Vec::new(); |
| 1924 | 'accept: for frame in frames { |
| 1925 | // A frame the fragment already covers confirms from the end |
| 1926 | // without reapplying — the resume rule's follower half. The |
| 1927 | // model refuses a covered sequence as a contiguity break, and |
| 1928 | // alone that refusal is harmless because the frame's answer is |
| 1929 | // read off the end anyway; in a batch it must not stop the |
| 1930 | // frames behind it, which a retransmission delivers in the same |
| 1931 | // burst as the duplicate. Only a real gap or seal stops the |
| 1932 | // batch, where it would have refused the lone frame too. |
| 1933 | if frame |
| 1934 | .entries |
| 1935 | .last() |
| 1936 | .is_none_or(|entry| entry.seq <= log.end) |
| 1937 | { |
| 1938 | continue; |
| 1939 | } |
| 1940 | for entry in frame.entries { |
| 1941 | if !log.accept_append(epoch, entry.seq) { |
| 1942 | warn!( |
| 1943 | leader, |
| 1944 | epoch, |
| 1945 | seq = entry.seq, |
| 1946 | end = log.end, |
| 1947 | sealed_to = log.sealed_to, |
| 1948 | "append refused: seal or contiguity" |
| 1949 | ); |
| 1950 | break 'accept; |
| 1951 | } |
| 1952 | accepted.push(entry); |
| 1953 | } |
| 1954 | } |
| 1955 | let mut new_state = FollowerState { |
| 1956 | fragment_epoch: log.fragment_epoch, |
| 1957 | base: log.base, |
| 1958 | end: log.end, |
| 1959 | sealed_to: log.sealed_to, |
| 1960 | }; |
| 1961 | // The truncate folds into the commit file's state. The watermark is |
| 1962 | // monotone per lane, so the burst's newest value is what applying |
| 1963 | // each frame's in turn would leave — capped below the burst's first |
| 1964 | // accepted sequence, because `decode_committed_batch` rejects a |
| 1965 | // file whose first entry is at or below its base, and a later |
| 1966 | // frame's watermark can cover an earlier frame's range once the |
| 1967 | // bucket proves it mid-burst. The rest of the truncation arrives |
| 1968 | // with the next round's watermark. |
| 1969 | let truncate_to = match accepted.first() { |
| 1970 | Some(first) => truncate_to.min(first.seq.saturating_sub(1)), |
| 1971 | None => truncate_to, |
| 1972 | }; |
| 1973 | if truncate_to > 0 { |
| 1974 | let mut truncated = log_tier::FollowerLog { |
| 1975 | fragment_epoch: new_state.fragment_epoch, |
| 1976 | base: new_state.base, |
| 1977 | end: new_state.end, |
| 1978 | sealed_to: new_state.sealed_to, |
| 1979 | }; |
| 1980 | truncated.truncate(truncate_to.min(new_state.end)); |
| 1981 | new_state.base = truncated.base; |
| 1982 | } |
| 1983 | |
| 1984 | let mut commit_ok = true; |
| 1985 | if !accepted.is_empty() { |
| 1986 | let first = accepted |
| 1987 | .first() |
| 1988 | .expect("an accepted batch has a first entry") |
| 1989 | .seq; |
| 1990 | let last = accepted |
| 1991 | .last() |
| 1992 | .expect("an accepted batch has a last entry") |
| 1993 | .seq; |
| 1994 | let path = dir.join(format!("{first}-{last}.batch")); |
| 1995 | let encoded = encode_committed_batch(new_state, &accepted); |
| 1996 | let write_started = mono_us(); |
| 1997 | let write = self.filesystem.write(&path, &encoded); |
| 1998 | entry_write_us = mono_us().saturating_sub(write_started); |
| 1999 | let write = write.and_then(|()| { |
| 2000 | let fsync_started = mono_us(); |
| 2001 | let result = self.filesystem.sync_all(&path); |
| 2002 | entry_fsync_us = mono_us().saturating_sub(fsync_started); |
| 2003 | result |
| 2004 | }); |
| 2005 | if write.is_err() { |
| 2006 | commit_ok = false; |
| 2007 | } else { |
| 2008 | let directory_started = mono_us(); |
| 2009 | if let Err(error) = self.sync_leader_directory(&leader, &dir) { |
| 2010 | // The complete file can survive despite a failed barrier. |
| 2011 | // Recovering it is safe because its own fsync finished; if |
| 2012 | // its name disappears, the failed append was never acked. |
| 2013 | warn!( |
| 2014 | leader, |
| 2015 | epoch, |
| 2016 | end = state.end, |
| 2017 | %error, |
| 2018 | "append refused: batch directory sync failed" |
| 2019 | ); |
| 2020 | commit_ok = false; |
| 2021 | } |
| 2022 | entry_directory_us = mono_us().saturating_sub(directory_started); |
| 2023 | } |
| 2024 | } |
| 2025 | let handle_ms = mono_us().saturating_sub(_emit.handled) / 1000; |
| 2026 | let persist_ms = mono_ms().saturating_sub(persist_started); |
| 2027 | let state_started = mono_ms(); |
| 2028 | let state_persist = if !commit_ok { |
| 2029 | Err(anyhow!("the follower batch did not reach its commit point")) |
| 2030 | } else if !accepted.is_empty() { |
| 2031 | self.cache_state(&leader, new_state); |
| 2032 | // Reclaim committed ranges only after the new base is durable. |
| 2033 | // The deletion is best-effort and needs no second directory sync: |
| 2034 | // a crash can retain covered files, which `tail` already hides. |
| 2035 | let _ = self.remove_entries_below(&leader, new_state.base); |
| 2036 | Ok(FollowerPersistTiming::default()) |
| 2037 | } else if new_state != state { |
| 2038 | // A duplicate append can still advance only the bucket watermark. |
| 2039 | // With no new batch to carry it, retain the ordinary state chain. |
| 2040 | self.persist_timed(&leader, new_state) |
| 2041 | } else { |
| 2042 | Ok(FollowerPersistTiming::default()) |
| 2043 | }; |
| 2044 | let state_ok = state_persist.is_ok(); |
| 2045 | let state_timing = state_persist.unwrap_or_default(); |
| 2046 | info!( |
| 2047 | event = "log_append_serve", |
| 2048 | leader, |
| 2049 | frames = frame_count, |
| 2050 | entries = total_entries, |
| 2051 | guard_ms = _emit.guard_us / 1000, |
| 2052 | handle_ms, |
| 2053 | persist_ms, |
| 2054 | state_ms = mono_ms().saturating_sub(state_started), |
| 2055 | entry_write_us, |
| 2056 | entry_fsync_us, |
| 2057 | entry_directory_us, |
| 2058 | state_write_us = state_timing.write_us, |
| 2059 | state_fsync_us = state_timing.fsync_us, |
| 2060 | state_rename_us = state_timing.rename_us, |
| 2061 | state_directory_us = state_timing.directory_us, |
| 2062 | "follower persisted an append batch" |
| 2063 | ); |
| 2064 | if !state_ok { |
| 2065 | return refusals(frame_count, state); |
| 2066 | } |
| 2067 | lasts |
| 2068 | .into_iter() |
| 2069 | .map(|last| { |
| 2070 | let last = last.unwrap_or(new_state.end); |
| 2071 | AppendResp { |
| 2072 | ok: new_state.end >= last, |
| 2073 | end: new_state.end, |
| 2074 | epoch: Some(new_state.fragment_epoch), |
| 2075 | } |
| 2076 | }) |
| 2077 | .collect() |
| 2078 | } |
| 2079 | |
| 2080 | /// Persist the seal mark BEFORE answering: once the response leaves, |
| 2081 | /// this follower must refuse the sealed epoch forever, including across |
| 2082 | /// a restart. |
| 2083 | pub async fn seal(&self, req: &SealReq) -> anyhow::Result<SealResp> { |
| 2084 | let guard = self.guard(&req.leader); |
| 2085 | let _held = guard.lock().await; |
| 2086 | let state = self.load(&req.leader)?; |
| 2087 | let mut log = log_tier::FollowerLog { |
| 2088 | fragment_epoch: state.fragment_epoch, |
| 2089 | base: state.base, |
| 2090 | end: state.end, |
| 2091 | sealed_to: state.sealed_to, |
| 2092 | }; |
| 2093 | let end = log.seal(req.epoch); |
| 2094 | self.persist( |
| 2095 | &req.leader, |
| 2096 | FollowerState { |
| 2097 | sealed_to: log.sealed_to, |
| 2098 | ..state |
| 2099 | }, |
| 2100 | )?; |
| 2101 | // `fragment_epoch` is the field that older recovery callers already |
| 2102 | // use as their certificate. Inspect the frozen tail before returning |
| 2103 | // it, so a torn current fragment fails closed even when the caller |
| 2104 | // ignores the newer range fields. The actual epoch travels |
| 2105 | // separately so a new caller can still gather the readable prefix |
| 2106 | // and classify the incomplete fragment conclusively. |
| 2107 | let tail = self.read_tail(&TailReq { |
| 2108 | leader: req.leader.clone(), |
| 2109 | })?; |
| 2110 | let range = tail.range; |
| 2111 | let retained_complete = range.fragment_epoch == state.fragment_epoch |
| 2112 | && range.base == state.base |
| 2113 | && range.end == end |
| 2114 | && range.complete |
| 2115 | && tail_covers_sealed_range(range.base, range.end, &tail.entries); |
| 2116 | if !retained_complete { |
| 2117 | warn!( |
| 2118 | leader = req.leader, |
| 2119 | fragment_epoch = state.fragment_epoch, |
| 2120 | base = state.base, |
| 2121 | end, |
| 2122 | "sealed follower cannot certify its incomplete retained range" |
| 2123 | ); |
| 2124 | } |
| 2125 | Ok(SealResp { |
| 2126 | end, |
| 2127 | base: Some(state.base), |
| 2128 | fragment_epoch: if retained_complete { |
| 2129 | state.fragment_epoch |
| 2130 | } else { |
| 2131 | 0 |
| 2132 | }, |
| 2133 | held_fragment_epoch: Some(state.fragment_epoch), |
| 2134 | }) |
| 2135 | } |
| 2136 | |
| 2137 | /// One fragment-GC pass over every leader this node follows. A |
| 2138 | /// fragment is garbage when its epoch is closed: the record moved past |
| 2139 | /// it (reconfiguration or a reopened incarnation force-tiered or |
| 2140 | /// recovered it away), or the record at its epoch is Sealed (recovery |
| 2141 | /// certified and uploaded the tail, so this copy is redundant by |
| 2142 | /// write-all). The deletion runs under the per-leader guard, keeps the |
| 2143 | /// state file, and extends the seal mark over the closed epoch, so a |
| 2144 | /// straggling append at it is refused rather than resurrected. |
| 2145 | pub async fn gc_fragments(&self) { |
| 2146 | let Some(bucket) = &self.bucket else { return }; |
| 2147 | let leaders = self.followed_sessions(); |
| 2148 | for leader in leaders { |
| 2149 | let Ok(Some(folded)) = read_record(bucket, &leader).await else { |
| 2150 | continue; |
| 2151 | }; |
| 2152 | let record = folded.record; |
| 2153 | let guard = self.guard(&leader); |
| 2154 | let _held = guard.lock().await; |
| 2155 | let Ok(state) = self.load(&leader) else { |
| 2156 | continue; |
| 2157 | }; |
| 2158 | if state.fragment_epoch == 0 { |
| 2159 | continue; |
| 2160 | } |
| 2161 | let closed = log_tier::fragment_closed(&record, state.fragment_epoch); |
| 2162 | if !closed { |
| 2163 | continue; |
| 2164 | } |
| 2165 | if state.base == state.end |
| 2166 | && self |
| 2167 | .filesystem |
| 2168 | .metadata(&self.dir(&leader).join("state.json")) |
| 2169 | .is_ok_and(|metadata| metadata.is_file) |
| 2170 | { |
| 2171 | // Already empty; nothing to remove, and the state file |
| 2172 | // stays as the seal-mark carrier. |
| 2173 | let _ = self.persist( |
| 2174 | &leader, |
| 2175 | FollowerState { |
| 2176 | sealed_to: state.sealed_to.max(state.fragment_epoch), |
| 2177 | ..state |
| 2178 | }, |
| 2179 | ); |
| 2180 | continue; |
| 2181 | } |
| 2182 | let _ = self.remove_entries_below(&leader, u64::MAX); |
| 2183 | if self |
| 2184 | .persist( |
| 2185 | &leader, |
| 2186 | FollowerState { |
| 2187 | fragment_epoch: state.fragment_epoch, |
| 2188 | base: state.end, |
| 2189 | end: state.end, |
| 2190 | sealed_to: state.sealed_to.max(state.fragment_epoch), |
| 2191 | }, |
| 2192 | ) |
| 2193 | .is_ok() |
| 2194 | { |
| 2195 | info!( |
| 2196 | leader, |
| 2197 | epoch = state.fragment_epoch, |
| 2198 | "fragment GC: closed epoch's fragments removed" |
| 2199 | ); |
| 2200 | } |
| 2201 | } |
| 2202 | } |
| 2203 | |
| 2204 | /// Return the range and its entries while append, seal, adoption, and GC |
| 2205 | /// cannot change the fragment. The range and the data therefore describe |
| 2206 | /// one follower state rather than two observations around a concurrent write. |
| 2207 | pub async fn tail(&self, req: &TailReq) -> anyhow::Result<TailResp> { |
| 2208 | let guard = self.guard(&req.leader); |
| 2209 | let _held = guard.lock().await; |
| 2210 | self.read_tail(req) |
| 2211 | } |
| 2212 | |
| 2213 | fn read_tail(&self, req: &TailReq) -> anyhow::Result<TailResp> { |
| 2214 | // Entries above the persisted end are unacked debris a crash may |
| 2215 | // legitimately tear (the entry syncs before the state does), and |
| 2216 | // including or losing an unacked frame is free. A torn entry ABOVE |
| 2217 | // the base and AT OR BELOW the end would be an acked frame's only |
| 2218 | // local copy, so it is skipped LOUDLY — write-all means another |
| 2219 | // member still has it, and the line attributes the anomaly. |
| 2220 | let state = self.load(&req.leader)?; |
| 2221 | let base = state.base; |
| 2222 | let end = state.end; |
| 2223 | let batch_scan = self.scan_committed_batches(&req.leader)?; |
| 2224 | // A checksum-invalid batch above `base` is ambiguous after a restart: |
| 2225 | // it can be an unacknowledged interrupted write, or a committed batch |
| 2226 | // damaged after its acknowledgement. Treating it as complete can lose |
| 2227 | // data, so the recovered gap stays until retransmission covers its end. |
| 2228 | // Replay can use different batch boundaries and leave the torn file |
| 2229 | // behind. Sequence coverage, not the health of every overlapping file, |
| 2230 | // proves that its retained rows have replacements. An unparseable name |
| 2231 | // still has no bounded range that replacement coverage can discharge. |
| 2232 | let mut retained_files_complete = |
| 2233 | !batch_scan.unknown_unreadable_range && self.recovered_disk_range_complete(&req.leader); |
| 2234 | let mut entries: Vec<Entry> = batch_scan |
| 2235 | .batches |
| 2236 | .into_iter() |
| 2237 | .filter(|batch| batch.state.fragment_epoch == state.fragment_epoch) |
| 2238 | .flat_map(|batch| batch.entries) |
| 2239 | .filter(|entry| entry.seq > base) |
| 2240 | .collect(); |
| 2241 | let dir = self.dir(&req.leader); |
| 2242 | match self.filesystem.read_dir(&dir) { |
| 2243 | Ok(read) => { |
| 2244 | for item in read { |
| 2245 | let name = item.file_name; |
| 2246 | let Some(name) = name.to_str() else { continue }; |
| 2247 | if let Some(stem) = name.strip_suffix(".entry") { |
| 2248 | let Ok(sequence) = stem.parse::<u64>() else { |
| 2249 | retained_files_complete = false; |
| 2250 | warn!( |
| 2251 | leader = req.leader, |
| 2252 | path = %item.path.display(), |
| 2253 | "follower entry file name does not contain a valid sequence" |
| 2254 | ); |
| 2255 | continue; |
| 2256 | }; |
| 2257 | match self.filesystem.read(&item.path) { |
| 2258 | Ok(bytes) => match decode_entry(&mut bytes.as_slice()) { |
| 2259 | Ok(entry) => { |
| 2260 | if entry.seq != sequence { |
| 2261 | let retained = sequence > base && sequence <= end; |
| 2262 | retained_files_complete &= !retained; |
| 2263 | warn!( |
| 2264 | leader = req.leader, |
| 2265 | path = %item.path.display(), |
| 2266 | named = sequence, |
| 2267 | decoded = entry.seq, |
| 2268 | "follower entry name does not match its contents" |
| 2269 | ); |
| 2270 | } else if entry.seq > base { |
| 2271 | entries.push(entry); |
| 2272 | } |
| 2273 | } |
| 2274 | Err(error) => { |
| 2275 | let retained = sequence > base && sequence <= end; |
| 2276 | retained_files_complete &= !retained; |
| 2277 | if retained { |
| 2278 | warn!( |
| 2279 | leader = req.leader, |
| 2280 | path = %item.path.display(), |
| 2281 | %error, |
| 2282 | "torn entry at or below the fragment end skipped in tail" |
| 2283 | ); |
| 2284 | } |
| 2285 | } |
| 2286 | }, |
| 2287 | Err(error) => { |
| 2288 | let retained = sequence > base && sequence <= end; |
| 2289 | retained_files_complete &= !retained; |
| 2290 | if retained { |
| 2291 | warn!( |
| 2292 | leader = req.leader, |
| 2293 | path = %item.path.display(), |
| 2294 | %error, |
| 2295 | "retained follower entry could not be read" |
| 2296 | ); |
| 2297 | } |
| 2298 | } |
| 2299 | } |
| 2300 | } else if name.ends_with(".entries") { |
| 2301 | let Some((named_first, named_last)) = |
| 2302 | follower_batch_range(name, ".entries") |
| 2303 | .filter(|(first, last)| first <= last) |
| 2304 | else { |
| 2305 | retained_files_complete = false; |
| 2306 | warn!( |
| 2307 | leader = req.leader, |
| 2308 | path = %item.path.display(), |
| 2309 | "follower batch file name does not contain a valid range" |
| 2310 | ); |
| 2311 | continue; |
| 2312 | }; |
| 2313 | let retained = named_first <= end && named_last > base; |
| 2314 | let Ok(bytes) = self.filesystem.read(&item.path) else { |
| 2315 | retained_files_complete &= !retained; |
| 2316 | if retained { |
| 2317 | warn!( |
| 2318 | leader = req.leader, |
| 2319 | path = %item.path.display(), |
| 2320 | "retained follower batch could not be read" |
| 2321 | ); |
| 2322 | } |
| 2323 | continue; |
| 2324 | }; |
| 2325 | // Decode the batch until the tear, keeping every intact |
| 2326 | // entry. The first undecoded sequence starts at the |
| 2327 | // filename's range and follows the last decoded entry, |
| 2328 | // so the retained-tear classification is exact. |
| 2329 | let mut next = Some(named_first); |
| 2330 | let mut buf = bytes.as_slice(); |
| 2331 | while !buf.is_empty() { |
| 2332 | match decode_entry(&mut buf) { |
| 2333 | Ok(entry) => { |
| 2334 | next = Some(entry.seq + 1); |
| 2335 | if entry.seq > base { |
| 2336 | entries.push(entry); |
| 2337 | } |
| 2338 | } |
| 2339 | Err(error) => { |
| 2340 | let retained = next.is_some_and(|seq| seq > base && seq <= end); |
| 2341 | retained_files_complete &= !retained; |
| 2342 | if retained { |
| 2343 | warn!( |
| 2344 | leader = req.leader, |
| 2345 | path = %item.path.display(), |
| 2346 | %error, |
| 2347 | "torn batch at or below the fragment end skipped in tail" |
| 2348 | ); |
| 2349 | } |
| 2350 | break; |
| 2351 | } |
| 2352 | } |
| 2353 | } |
| 2354 | } |
| 2355 | } |
| 2356 | } |
| 2357 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 2358 | retained_files_complete = false; |
| 2359 | if state.fragment_epoch != 0 { |
| 2360 | warn!( |
| 2361 | leader = req.leader, |
| 2362 | %error, |
| 2363 | "follower directory could not be read while building a tail" |
| 2364 | ); |
| 2365 | } |
| 2366 | } |
| 2367 | Err(error) => return Err(error.into()), |
| 2368 | } |
| 2369 | entries.sort_by_key(|entry| entry.seq); |
| 2370 | // Batch files can overlap: a torn batch leaves its file above the |
| 2371 | // persisted end, and the retransmission of its unanswered frames |
| 2372 | // commits again under whatever batch boundaries the socket had |
| 2373 | // then. One fragment sequence is one set of bytes — a leader |
| 2374 | // assigns each sequence once per epoch and adoption clears an old |
| 2375 | // epoch's files — so a repeated sequence is the same entry twice, |
| 2376 | // never a conflict. |
| 2377 | entries.dedup_by_key(|entry| entry.seq); |
| 2378 | let complete = retained_files_complete && tail_covers_sealed_range(base, end, &entries); |
| 2379 | Ok(TailResp { |
| 2380 | range: TailRange { |
| 2381 | fragment_epoch: state.fragment_epoch, |
| 2382 | base, |
| 2383 | end, |
| 2384 | complete, |
| 2385 | }, |
| 2386 | entries, |
| 2387 | }) |
| 2388 | } |
| 2389 | } |
| 2390 | |
| 2391 | /// Flush order of a retained bundle key, `log/<session>/bundle/e<epoch>-<seq>.ltxb`, |
| 2392 | /// as the numeric (epoch, seq) pair: the shipper's sequence counter is |
| 2393 | /// monotonic for the session and the epoch only rises, so this is the order |
| 2394 | /// the rows were captured in. A key sort is not: `e10-` sorts before `e9-`. |
| 2395 | /// A key that does not parse sorts last, after every bundle the shipper |
| 2396 | /// named, so a foreign object under the prefix cannot move a real bundle. |
| 2397 | fn bundle_flush_order(key: &str) -> (u64, u64, String) { |
| 2398 | let parsed = key |
| 2399 | .rsplit('/') |
| 2400 | .next() |
| 2401 | .and_then(|name| name.strip_prefix('e')) |
| 2402 | .and_then(|name| name.strip_suffix(".ltxb")) |
| 2403 | .and_then(|name| name.split_once('-')) |
| 2404 | .and_then(|(epoch, seq)| Some((epoch.parse::<u64>().ok()?, seq.parse::<u64>().ok()?))); |
| 2405 | match parsed { |
| 2406 | Some((epoch, seq)) => (epoch, seq, String::new()), |
| 2407 | None => (u64::MAX, u64::MAX, key.to_string()), |
| 2408 | } |
| 2409 | } |
| 2410 | |
| 2411 | /// Split the listed bundles, `(key, size)`, into the gather windows of a |
| 2412 | /// recovery: consecutive bundles in flush order whose sizes sum to at most |
| 2413 | /// `budget`. A bundle larger than the budget is a window of its own, so the |
| 2414 | /// fold always advances, and an empty listing is one empty window, so the |
| 2415 | /// follower tails still fold. The listing's size is the bound on the rows a |
| 2416 | /// window's bundles can carry, so the plan needs no read. |
| 2417 | fn gather_windows(mut bundles: Vec<(String, u64)>, budget: u64) -> Vec<Vec<String>> { |
| 2418 | bundles.sort_by_cached_key(|(key, _)| bundle_flush_order(key)); |
| 2419 | let mut windows: Vec<Vec<String>> = vec![Vec::new()]; |
| 2420 | let mut held = 0_u64; |
| 2421 | for (key, size) in bundles { |
| 2422 | let open = windows.last_mut().expect("a gather window is always open"); |
| 2423 | if !open.is_empty() && held.saturating_add(size) > budget { |
| 2424 | windows.push(vec![key]); |
| 2425 | held = size; |
| 2426 | } else { |
| 2427 | open.push(key); |
| 2428 | held = held.saturating_add(size); |
| 2429 | } |
| 2430 | } |
| 2431 | windows |
| 2432 | } |
| 2433 | |
| 2434 | fn tail_covers_sealed_range(base: u64, end: u64, entries: &[Entry]) -> bool { |
| 2435 | if base > end { |
| 2436 | return false; |
| 2437 | } |
| 2438 | // `(base, end]` is empty here. `tail` can still expose an entry above |
| 2439 | // `end` because an entry-file sync precedes the state commit, but that |
| 2440 | // unacknowledged debris says nothing about this retained range. |
| 2441 | if base == end { |
| 2442 | return true; |
| 2443 | } |
| 2444 | let mut covered = base; |
| 2445 | for entry in entries { |
| 2446 | if entry.seq <= covered { |
| 2447 | continue; |
| 2448 | } |
| 2449 | if covered.checked_add(1) != Some(entry.seq) { |
| 2450 | return false; |
| 2451 | } |
| 2452 | covered = entry.seq; |
| 2453 | if covered == end { |
| 2454 | return true; |
| 2455 | } |
| 2456 | } |
| 2457 | covered == end |
| 2458 | } |
| 2459 | |
| 2460 | /// The signed production implementation. It preserves the previous request |
| 2461 | /// construction, authentication, response validation, and timeout behavior. |
| 2462 | struct SignedPeerTransport { |
| 2463 | http: reqwest::Client, |
| 2464 | auth: Arc<PeerAuth>, |
| 2465 | } |
| 2466 | |
| 2467 | impl SignedPeerTransport { |
| 2468 | fn new(auth: Arc<PeerAuth>) -> Self { |
| 2469 | Self { |
| 2470 | http: reqwest::Client::builder() |
| 2471 | .timeout(std::time::Duration::from_secs(10)) |
| 2472 | .tcp_nodelay(true) |
| 2473 | .build() |
| 2474 | .expect("build log peer client"), |
| 2475 | auth, |
| 2476 | } |
| 2477 | } |
| 2478 | } |
| 2479 | |
| 2480 | impl LogTransport for SignedPeerTransport { |
| 2481 | fn post<'a>( |
| 2482 | &'a self, |
| 2483 | node: &'a str, |
| 2484 | addr: &'a str, |
| 2485 | path: &'a str, |
| 2486 | body: Vec<u8>, |
| 2487 | deadline: Option<std::time::Duration>, |
| 2488 | ) -> std::pin::Pin< |
| 2489 | Box<dyn std::future::Future<Output = anyhow::Result<bytes::Bytes>> + Send + 'a>, |
| 2490 | > { |
| 2491 | Box::pin(async move { |
| 2492 | let mut builder = self.http.post(format!("http://{addr}{path}")); |
| 2493 | if let Some(deadline) = deadline { |
| 2494 | builder = builder.timeout(deadline); |
| 2495 | } |
| 2496 | let request = self.auth.sign(builder, "POST", path, &body, node)?; |
| 2497 | let response = request.body(body).send().await?; |
| 2498 | // Status before response-auth: an older peer can answer an |
| 2499 | // unsigned route error, and callers need that status to classify |
| 2500 | // a protocol-incapable member separately from transport failure. |
| 2501 | if !response.status().is_success() { |
| 2502 | let status = response.status(); |
| 2503 | return Err(anyhow::Error::new(PeerHttpError { status }) |
| 2504 | .context(format!("peer {node} answered {status}"))); |
| 2505 | } |
| 2506 | crate::peer_auth::validate_response(response.headers())?; |
| 2507 | Ok(response.bytes().await?) |
| 2508 | }) |
| 2509 | } |
| 2510 | |
| 2511 | fn open_stream<'a>( |
| 2512 | &'a self, |
| 2513 | node: &'a str, |
| 2514 | addr: &'a str, |
| 2515 | path: &'a str, |
| 2516 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<LogStreamIo>> + Send + 'a>> |
| 2517 | { |
| 2518 | Box::pin(async move { |
| 2519 | // A dedicated client: the shared one carries a 10 s whole-request |
| 2520 | // timeout that would sever a healthy long-lived stream. The |
| 2521 | // handshake is authenticated both ways — the request by the |
| 2522 | // peer HMAC, the 101 by the response validation — and the |
| 2523 | // upgraded byte channel inherits that establishment, which is |
| 2524 | // the same trust shape as every other authenticated connection. |
| 2525 | let client = reqwest::Client::builder() |
| 2526 | .connect_timeout(std::time::Duration::from_secs(5)) |
| 2527 | .tcp_nodelay(true) |
| 2528 | .build()?; |
| 2529 | let builder = client |
| 2530 | .post(format!("http://{addr}{path}")) |
| 2531 | .header(hyper::header::CONNECTION, "upgrade") |
| 2532 | .header(hyper::header::UPGRADE, "celld-log-stream"); |
| 2533 | let request = self.auth.sign(builder, "POST", path, &[], node)?; |
| 2534 | let response = request.send().await?; |
| 2535 | if response.status() != reqwest::StatusCode::SWITCHING_PROTOCOLS { |
| 2536 | let status = response.status(); |
| 2537 | return Err(anyhow::Error::new(PeerHttpError { status }) |
| 2538 | .context(format!("peer {node} refused the stream: {status}"))); |
| 2539 | } |
| 2540 | crate::peer_auth::validate_response(response.headers())?; |
| 2541 | Ok(Box::new(response.upgrade().await?) as LogStreamIo) |
| 2542 | }) |
| 2543 | } |
| 2544 | } |
| 2545 | |
| 2546 | /// A peer answered with an HTTP error status: typed so callers can tell |
| 2547 | /// "the route is not there" from transport silence. |
| 2548 | #[derive(Debug)] |
| 2549 | struct PeerHttpError { |
| 2550 | status: reqwest::StatusCode, |
| 2551 | } |
| 2552 | |
| 2553 | impl std::fmt::Display for PeerHttpError { |
| 2554 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 2555 | write!(f, "peer answered {}", self.status) |
| 2556 | } |
| 2557 | } |
| 2558 | |
| 2559 | impl std::error::Error for PeerHttpError {} |
| 2560 | |
| 2561 | // ── The leader side ───────────────────────────────────────────────────────── |
| 2562 | |
| 2563 | #[derive(Clone)] |
| 2564 | #[doc(hidden)] |
| 2565 | pub struct Member { |
| 2566 | pub node: String, |
| 2567 | pub addr: String, |
| 2568 | } |
| 2569 | |
| 2570 | /// One round's work for one member lane: the shared request and the slot |
| 2571 | /// its answer lands in. |
| 2572 | #[doc(hidden)] |
| 2573 | pub struct LaneJob { |
| 2574 | pub req: Arc<AppendReq>, |
| 2575 | /// Submission time, for the lane-wait split in the rtt event. |
| 2576 | pub enqueued: u64, |
| 2577 | /// The request's entry bytes, released from the stream window when the |
| 2578 | /// member answers. |
| 2579 | pub bytes: u64, |
| 2580 | pub resp: tokio::sync::oneshot::Sender<Option<(String, u64)>>, |
| 2581 | } |
| 2582 | |
| 2583 | /// One outstanding round, counted from submission until its completion is |
| 2584 | /// applied or discarded. The completion owns this guard after the network |
| 2585 | /// future resolves, so cancellation releases every reservation exactly once. |
| 2586 | /// Follower-side handler timing carrier for the serve event. |
| 2587 | struct HandleTiming { |
| 2588 | handled: u64, |
| 2589 | guard_us: u64, |
| 2590 | #[allow(dead_code)] |
| 2591 | entries: usize, |
| 2592 | } |
| 2593 | |
| 2594 | struct OutstandingRound(Arc<std::sync::atomic::AtomicU64>); |
| 2595 | |
| 2596 | impl Drop for OutstandingRound { |
| 2597 | fn drop(&mut self) { |
| 2598 | self.0.fetch_sub(1, Ordering::SeqCst); |
| 2599 | } |
| 2600 | } |
| 2601 | |
| 2602 | /// The fleet shipper for ONE ensemble at one epoch: assigns sequence |
| 2603 | /// numbers, POSTs pipelined batches to every member, and reports all-acked. |
| 2604 | /// Each member's ordered lane keeps its fragment contiguous. Membership and |
| 2605 | /// epoch are immutable, so an ensemble change builds and swaps a new shipper. |
| 2606 | /// The stream window (the stream-window design): per-member |
| 2607 | /// append accounting and the fleet watermark. Each ordered lane keeps the |
| 2608 | /// contiguous acked end its follower reports, the watermark is the minimum |
| 2609 | /// across members, and admission is bounded per lane by appends and bytes, |
| 2610 | /// so a slow member becomes bounded backpressure instead of unbounded |
| 2611 | /// queueing. `CELLD_LOG_WINDOW=0` (the default) disables the stream and |
| 2612 | /// the ship loop keeps today's round bound. |
| 2613 | #[doc(hidden)] |
| 2614 | pub struct StreamWindow { |
| 2615 | /// Appends one lane may hold in flight. |
| 2616 | window: u64, |
| 2617 | /// Request bytes one lane may hold in flight. |
| 2618 | byte_cap: u64, |
| 2619 | lanes: Vec<StreamLane>, |
| 2620 | /// The fleet watermark: the minimum contiguous acked end across |
| 2621 | /// members. Monotone by `fetch_max`; a concurrent stale minimum can |
| 2622 | /// only be conservative, never ahead. |
| 2623 | watermark: std::sync::atomic::AtomicU64, |
| 2624 | } |
| 2625 | |
| 2626 | struct StreamLane { |
| 2627 | inflight: std::sync::atomic::AtomicU64, |
| 2628 | bytes: std::sync::atomic::AtomicU64, |
| 2629 | /// This member's contiguous acked end. Monotone because the lane is |
| 2630 | /// one ordered worker and `append_confirms` only accepts an end that |
| 2631 | /// covers the batch at the leader's fragment epoch. |
| 2632 | acked: std::sync::atomic::AtomicU64, |
| 2633 | } |
| 2634 | |
| 2635 | impl StreamWindow { |
| 2636 | #[doc(hidden)] |
| 2637 | pub fn new(window: u64, byte_cap: u64, members: usize) -> Self { |
| 2638 | Self { |
| 2639 | window, |
| 2640 | byte_cap, |
| 2641 | lanes: (0..members) |
| 2642 | .map(|_| StreamLane { |
| 2643 | inflight: std::sync::atomic::AtomicU64::new(0), |
| 2644 | bytes: std::sync::atomic::AtomicU64::new(0), |
| 2645 | acked: std::sync::atomic::AtomicU64::new(0), |
| 2646 | }) |
| 2647 | .collect(), |
| 2648 | watermark: std::sync::atomic::AtomicU64::new(0), |
| 2649 | } |
| 2650 | } |
| 2651 | |
| 2652 | /// True while every lane has room for one more append. The slowest |
| 2653 | /// member closes the window; its lane refilling is what reopens it. |
| 2654 | #[doc(hidden)] |
| 2655 | pub fn admit(&self) -> bool { |
| 2656 | self.lanes.iter().all(|lane| { |
| 2657 | lane.inflight.load(Ordering::SeqCst) < self.window |
| 2658 | && lane.bytes.load(Ordering::SeqCst) < self.byte_cap |
| 2659 | }) |
| 2660 | } |
| 2661 | |
| 2662 | #[doc(hidden)] |
| 2663 | pub fn submitted(&self, lane: usize, bytes: u64) { |
| 2664 | self.lanes[lane].inflight.fetch_add(1, Ordering::SeqCst); |
| 2665 | self.lanes[lane].bytes.fetch_add(bytes, Ordering::SeqCst); |
| 2666 | } |
| 2667 | |
| 2668 | #[doc(hidden)] |
| 2669 | pub fn answered(&self, lane: usize, bytes: u64) { |
| 2670 | self.lanes[lane].inflight.fetch_sub(1, Ordering::SeqCst); |
| 2671 | self.lanes[lane].bytes.fetch_sub(bytes, Ordering::SeqCst); |
| 2672 | } |
| 2673 | |
| 2674 | /// A confirmed append: advance the lane's acked end to what its |
| 2675 | /// follower reported and recompute the watermark. Returns the new |
| 2676 | /// watermark when it moved. A refusal or failure never reaches here, |
| 2677 | /// so a lagging or refusing member pins the watermark in place. |
| 2678 | #[doc(hidden)] |
| 2679 | pub fn confirmed(&self, lane: usize, end: u64) -> Option<u64> { |
| 2680 | self.lanes[lane].acked.fetch_max(end, Ordering::SeqCst); |
| 2681 | let minimum = self |
| 2682 | .lanes |
| 2683 | .iter() |
| 2684 | .map(|lane| lane.acked.load(Ordering::SeqCst)) |
| 2685 | .min() |
| 2686 | .unwrap_or(0); |
| 2687 | let prior = self.watermark.fetch_max(minimum, Ordering::SeqCst); |
| 2688 | (minimum > prior).then_some(minimum) |
| 2689 | } |
| 2690 | |
| 2691 | #[cfg(celld_internal_tests)] |
| 2692 | #[doc(hidden)] |
| 2693 | pub fn watermark(&self) -> u64 { |
| 2694 | self.watermark.load(Ordering::SeqCst) |
| 2695 | } |
| 2696 | } |
| 2697 | |
| 2698 | /// The fleet shipper for ONE ensemble at one epoch: assigns sequence |
| 2699 | /// numbers, POSTs one in-flight batch to every member, and reports |
| 2700 | /// all-acked. One batch at a time is what keeps each follower's fragment |
| 2701 | /// contiguous. Membership and epoch are immutable — an ensemble change |
| 2702 | /// builds a new shipper and the manager swaps it. |
| 2703 | pub struct FleetShipper { |
| 2704 | node: String, |
| 2705 | transport: Arc<dyn LogTransport>, |
| 2706 | live_log: Arc<LiveLogTransitions>, |
| 2707 | record: log_tier::LogRecord, |
| 2708 | /// True only after the authoritative record applies `may_have_fleet_acks` |
| 2709 | /// for this epoch. The first eligible batch publishes the marker before |
| 2710 | /// its acknowledgements are credited; a failed publication permanently |
| 2711 | /// degrades the shipper. Recovery uses the marker to distinguish an epoch |
| 2712 | /// without fleet credits from an all-amnesiac ensemble with possible acks. |
| 2713 | activated: Arc<std::sync::atomic::AtomicBool>, |
| 2714 | epoch: u64, |
| 2715 | members: Vec<Member>, |
| 2716 | /// One ordered lane per member: a single worker serves that member's |
| 2717 | /// rounds strictly in submission order, so pipelining across rounds |
| 2718 | /// can never reorder appends at a follower — contiguity holds by |
| 2719 | /// construction and the follower needs no reorder state. |
| 2720 | lanes: Vec<tokio::sync::mpsc::UnboundedSender<LaneJob>>, |
| 2721 | /// Rounds the ship loop may keep in flight at once. |
| 2722 | pipeline: usize, |
| 2723 | seq: std::sync::atomic::AtomicU64, |
| 2724 | /// A failed member degrades the shipper permanently: fleet proofs stop |
| 2725 | /// and every ack rides the bucket, which is always safe, until the |
| 2726 | /// maintenance loop CASes a fresh ensemble. |
| 2727 | degraded: Arc<std::sync::atomic::AtomicBool>, |
| 2728 | /// Batches between capture and credit, one count per round. The |
| 2729 | /// reconfigure barrier cannot see such a batch in the shipped/tiered |
| 2730 | /// counters — its frames credit only after the round completes — so |
| 2731 | /// `maintain` must refuse to step epochs while any is out, or a frame |
| 2732 | /// covered only by the old ensemble could ack under a record that no |
| 2733 | /// longer names its holders. |
| 2734 | outstanding: Arc<std::sync::atomic::AtomicU64>, |
| 2735 | /// The gray-follower ledger lives with the member lanes now: append |
| 2736 | /// timings feed it from each lane worker, and it outlives this shipper |
| 2737 | /// so quarantine survives the swap. |
| 2738 | policy: Arc<celld_logic::log_evict::EvictionPolicy>, |
| 2739 | /// The stream window, when `CELLD_LOG_WINDOW` enables it. `None` keeps |
| 2740 | /// the round-bounded ship loop unchanged. |
| 2741 | stream: Option<Arc<StreamWindow>>, |
| 2742 | } |
| 2743 | |
| 2744 | impl crate::ltx_repl::Shipper for FleetShipper { |
| 2745 | fn ship( |
| 2746 | &self, |
| 2747 | batch: Vec<ShipEntry>, |
| 2748 | covered_seq: u64, |
| 2749 | ) -> std::pin::Pin< |
| 2750 | Box<dyn std::future::Future<Output = crate::ltx_repl::ShipCompletion> + Send + 'static>, |
| 2751 | > { |
| 2752 | self.ship_batch(batch, covered_seq) |
| 2753 | } |
| 2754 | |
| 2755 | fn active(&self) -> bool { |
| 2756 | self.is_active() |
| 2757 | } |
| 2758 | |
| 2759 | fn epoch(&self) -> u64 { |
| 2760 | self.epoch |
| 2761 | } |
| 2762 | |
| 2763 | fn pipeline(&self) -> usize { |
| 2764 | self.pipeline |
| 2765 | } |
| 2766 | |
| 2767 | fn admit(&self) -> bool { |
| 2768 | self.stream.as_ref().is_none_or(|stream| stream.admit()) |
| 2769 | } |
| 2770 | } |
| 2771 | |
| 2772 | impl FleetShipper { |
| 2773 | fn degrade(&self, why: &str) { |
| 2774 | degrade_shared(&self.degraded, self.epoch, why); |
| 2775 | } |
| 2776 | |
| 2777 | async fn post_append(&self, member: &Member, req: &AppendReq) -> AppendSend { |
| 2778 | post_append_to(&self.transport, &self.policy, member, req).await |
| 2779 | } |
| 2780 | |
| 2781 | fn is_active(&self) -> bool { |
| 2782 | !self.degraded.load(Ordering::SeqCst) |
| 2783 | } |
| 2784 | } |
| 2785 | |
| 2786 | /// One member's answer to one append POST, classified for the health |
| 2787 | /// ledger: a parsed response, a protocol-level incapability (route |
| 2788 | /// missing or body unparseable — quarantine), or a transient transport |
| 2789 | /// failure (retry). |
| 2790 | enum AppendSend { |
| 2791 | Answered(AppendResp), |
| 2792 | Incapable(anyhow::Error), |
| 2793 | Failed(#[allow(dead_code)] anyhow::Error), |
| 2794 | } |
| 2795 | |
| 2796 | /// Whether one member's answer confirms this append. Direct acceptance |
| 2797 | /// confirms; a refusal still confirms when the follower echoes the same |
| 2798 | /// fragment epoch and its contiguous end covers the batch — the entries are |
| 2799 | /// durable there, which is all write-all needs, and it is exactly the shape |
| 2800 | /// a hedged retransmission produces when the original landed first. The |
| 2801 | /// epoch echo is what makes the refusal reading sound: a follower on |
| 2802 | /// another fragment reports an end that says nothing about these sequences. |
| 2803 | #[doc(hidden)] |
| 2804 | pub fn append_confirms(req_epoch: u64, last: u64, resp: &AppendResp) -> bool { |
| 2805 | resp.ok || (resp.epoch == Some(req_epoch) && resp.end >= last) |
| 2806 | } |
| 2807 | |
| 2808 | /// Whether one ATTEMPT confirms this append. Only a well-formed answer can: |
| 2809 | /// a transport failure and a protocol-level incapability report on the |
| 2810 | /// attempt, not on what the follower holds. |
| 2811 | fn send_confirms(req_epoch: u64, last: u64, send: &AppendSend) -> bool { |
| 2812 | matches!(send, AppendSend::Answered(resp) if append_confirms(req_epoch, last, resp)) |
| 2813 | } |
| 2814 | |
| 2815 | fn degrade_shared(degraded: &std::sync::atomic::AtomicBool, epoch: u64, why: &str) { |
| 2816 | if !degraded.swap(true, Ordering::SeqCst) { |
| 2817 | warn!(epoch, why, "log ensemble degraded; acks ride the bucket"); |
| 2818 | } |
| 2819 | } |
| 2820 | |
| 2821 | /// The append POST: a binary body (the entries dominate it), a JSON |
| 2822 | /// response. Bounded by the eviction backstop, not the generic client |
| 2823 | /// timeout: an append slower than the backstop triggers the evict |
| 2824 | /// regardless, and a gray follower must not pin the in-flight batch |
| 2825 | /// (and with it the reconfigure barrier) for ten seconds. |
| 2826 | async fn post_append_to( |
| 2827 | transport: &Arc<dyn LogTransport>, |
| 2828 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 2829 | member: &Member, |
| 2830 | req: &AppendReq, |
| 2831 | ) -> AppendSend { |
| 2832 | let deadline = std::time::Duration::from_millis(policy.backstop_ms + 100); |
| 2833 | let encode_started = mono_us(); |
| 2834 | let body = encode_append(req); |
| 2835 | let encode_us = mono_us().saturating_sub(encode_started); |
| 2836 | let body_len = body.len(); |
| 2837 | let bytes = match transport |
| 2838 | .post( |
| 2839 | &member.node, |
| 2840 | &member.addr, |
| 2841 | "/peer/log/append", |
| 2842 | body, |
| 2843 | Some(deadline), |
| 2844 | ) |
| 2845 | .await |
| 2846 | { |
| 2847 | Ok(bytes) => bytes, |
| 2848 | // A missing or unimplemented route is a binary that does not |
| 2849 | // speak the log tier — the mixed-version seam. Everything |
| 2850 | // else (timeouts, resets, 5xx) stays a transient failure. |
| 2851 | Err(error) => { |
| 2852 | let incapable = error |
| 2853 | .downcast_ref::<PeerHttpError>() |
| 2854 | .is_some_and(|http| matches!(http.status.as_u16(), 404 | 405 | 501)); |
| 2855 | return if incapable { |
| 2856 | AppendSend::Incapable(error) |
| 2857 | } else { |
| 2858 | AppendSend::Failed(error) |
| 2859 | }; |
| 2860 | } |
| 2861 | }; |
| 2862 | tracing::debug!( |
| 2863 | target: "timing", |
| 2864 | event = "log_append_encode", |
| 2865 | encode_us, |
| 2866 | body_len, |
| 2867 | "append body encoded" |
| 2868 | ); |
| 2869 | match serde_json::from_slice(&bytes) { |
| 2870 | Ok(resp) => AppendSend::Answered(resp), |
| 2871 | // A 200 whose body is not an AppendResp is no celld follower. |
| 2872 | Err(error) => AppendSend::Incapable(error.into()), |
| 2873 | } |
| 2874 | } |
| 2875 | |
| 2876 | /// How the lane arms its hedge deadline. `Fixed` is the lab override |
| 2877 | /// (`CELLD_LOG_HEDGE_MS`; 0 disables hedging); `Adaptive` derives the |
| 2878 | /// deadline from the follower-health ledger per arming, so the deadline |
| 2879 | /// tracks the fleet's measured honest tail instead of a constant that a |
| 2880 | /// loaded fleet's tail can cross (the log-hedge-deadline design). |
| 2881 | #[derive(Clone, Copy)] |
| 2882 | #[doc(hidden)] |
| 2883 | pub enum HedgeMode { |
| 2884 | Fixed(u64), |
| 2885 | Adaptive, |
| 2886 | } |
| 2887 | |
| 2888 | fn resolve_hedge_ms( |
| 2889 | tuning: &LaneTuning, |
| 2890 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 2891 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 2892 | ) -> u64 { |
| 2893 | match tuning.hedge { |
| 2894 | HedgeMode::Fixed(ms) => ms, |
| 2895 | HedgeMode::Adaptive => health.lock().unwrap().hedge_deadline_ms(policy, mono_ms()), |
| 2896 | } |
| 2897 | } |
| 2898 | |
| 2899 | /// The per-lane knobs that ride beside the transport handles: the hedge |
| 2900 | /// deadline, this lane's slot in the stream window when the window is on, |
| 2901 | /// and whether the lane speaks the ordered stream transport. |
| 2902 | #[doc(hidden)] |
| 2903 | pub struct LaneTuning { |
| 2904 | pub hedge: HedgeMode, |
| 2905 | pub stream: Option<(Arc<StreamWindow>, usize)>, |
| 2906 | pub stream_transport: bool, |
| 2907 | } |
| 2908 | |
| 2909 | /// Resolve one append's answer: the health sample, the rtt event, the |
| 2910 | /// confirmation reading, the window accounting, and the caller's oneshot. |
| 2911 | /// Shared by the serial lane, the stream lane, and the stream lane's |
| 2912 | /// hedge and fallback paths, so every transport reads an answer the same |
| 2913 | /// way. |
| 2914 | #[allow(clippy::too_many_arguments)] |
| 2915 | fn resolve_append( |
| 2916 | member: &Member, |
| 2917 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 2918 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 2919 | tuning: &LaneTuning, |
| 2920 | job: LaneJob, |
| 2921 | started: u64, |
| 2922 | write_ms: u64, |
| 2923 | resp: AppendSend, |
| 2924 | ) { |
| 2925 | let done = mono_ms(); |
| 2926 | health |
| 2927 | .lock() |
| 2928 | .unwrap() |
| 2929 | .append_completed(&member.node, done, done.saturating_sub(started)); |
| 2930 | info!( |
| 2931 | event = "log_append_rtt", |
| 2932 | member = member.node, |
| 2933 | entries = job.req.entries.len(), |
| 2934 | lane_wait_ms = started.saturating_sub(job.enqueued), |
| 2935 | rtt_ms = done.saturating_sub(started), |
| 2936 | write_ms, |
| 2937 | "append round trip completed" |
| 2938 | ); |
| 2939 | let last = job.req.entries.last().map_or(0, |entry| entry.seq); |
| 2940 | let outcome = match resp { |
| 2941 | AppendSend::Answered(resp) if append_confirms(job.req.epoch, last, &resp) => { |
| 2942 | Some((member.node.clone(), resp.end)) |
| 2943 | } |
| 2944 | AppendSend::Incapable(error) => { |
| 2945 | // Fast rejections read as healthy latency samples, so |
| 2946 | // the gray verdicts never fire on this member and the |
| 2947 | // rebuild re-picks it forever (#95): quarantine it |
| 2948 | // here and the next rebuild recruits around it. |
| 2949 | warn!( |
| 2950 | member = member.node, |
| 2951 | %error, |
| 2952 | "follower cannot serve log appends; quarantined from recruitment" |
| 2953 | ); |
| 2954 | health |
| 2955 | .lock() |
| 2956 | .unwrap() |
| 2957 | .append_incapable(policy, &member.node, done); |
| 2958 | None |
| 2959 | } |
| 2960 | AppendSend::Answered(_) | AppendSend::Failed(_) => None, |
| 2961 | }; |
| 2962 | // The window accounting settles BEFORE the round future can |
| 2963 | // resolve: by the time the ship loop sees a completed round, every |
| 2964 | // one of its lane slots is already released. |
| 2965 | if let Some((window, index)) = &tuning.stream { |
| 2966 | window.answered(*index, job.bytes); |
| 2967 | if let Some((_, end)) = &outcome { |
| 2968 | if let Some(watermark) = window.confirmed(*index, *end) { |
| 2969 | info!( |
| 2970 | event = "log_watermark_advance", |
| 2971 | watermark, |
| 2972 | member = member.node, |
| 2973 | "fleet watermark advanced" |
| 2974 | ); |
| 2975 | } |
| 2976 | } |
| 2977 | } |
| 2978 | let _ = job.resp.send(outcome); |
| 2979 | } |
| 2980 | |
| 2981 | /// One job through the one-shot HTTP path, hedged: the serial lane's whole |
| 2982 | /// step, also the stream lane's fallback for an old follower. |
| 2983 | async fn http_append_job( |
| 2984 | member: &Member, |
| 2985 | transport: &Arc<dyn LogTransport>, |
| 2986 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 2987 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 2988 | tuning: &LaneTuning, |
| 2989 | job: LaneJob, |
| 2990 | ) { |
| 2991 | let started = mono_ms(); |
| 2992 | health.lock().unwrap().append_started(&member.node, started); |
| 2993 | let last = job.req.entries.last().map_or(0, |entry| entry.seq); |
| 2994 | // The hedge: appends are idempotent per sequence — a duplicate of a |
| 2995 | // persisted range refuses with an end that covers it, which |
| 2996 | // `append_confirms` reads as the ack — so a round trip stuck in a |
| 2997 | // platform tail is raced by a second copy. This is what keeps one |
| 2998 | // slow append from stalling its round and every round behind it |
| 2999 | // (#140). |
| 3000 | // |
| 3001 | // The race is for the first CONFIRMING answer, never for the first |
| 3002 | // answer: a duplicate may only ever turn a non-confirmation into a |
| 3003 | // confirmation, so in every other case the round's verdict and the |
| 3004 | // health-ledger classification are the ORIGINAL attempt's, exactly |
| 3005 | // as if no duplicate had been sent. Returning whichever attempt |
| 3006 | // merely resolved first instead lets a hedge that fails fast cancel |
| 3007 | // a healthy original — failing a round the original was about to |
| 3008 | // confirm, degrading the whole shipper onto bucket acks for a tail |
| 3009 | // it had already absorbed, and quarantining a live member for |
| 3010 | // `quarantine_ms` when the duplicate's answer is an `Incapable` one. |
| 3011 | // The lane therefore waits the loser out whenever the winner does |
| 3012 | // not confirm. That wait is bounded and small: both attempts carry |
| 3013 | // the same eviction-backstop deadline, so the lane holds a job for |
| 3014 | // at most `hedge_ms` longer than the un-hedged path did. |
| 3015 | let hedge_ms = resolve_hedge_ms(tuning, policy, health); |
| 3016 | let resp = if hedge_ms == 0 { |
| 3017 | post_append_to(transport, policy, member, &job.req).await |
| 3018 | } else { |
| 3019 | let mut original = std::pin::pin!(post_append_to(transport, policy, member, &job.req)); |
| 3020 | let inside_deadline = crate::asyncrt::select_biased! { |
| 3021 | "the original response wins a tie with the hedge deadline so no duplicate is sent"; |
| 3022 | resp = &mut original => Some(resp), |
| 3023 | _ = crate::asyncrt::sleep(std::time::Duration::from_millis(hedge_ms)) => None, |
| 3024 | }; |
| 3025 | match inside_deadline { |
| 3026 | // Answered before the deadline: no duplicate is sent, and |
| 3027 | // the answer stands whether or not it confirms. |
| 3028 | Some(resp) => resp, |
| 3029 | None => { |
| 3030 | info!( |
| 3031 | event = "log_append_hedge", |
| 3032 | member = member.node, |
| 3033 | entries = job.req.entries.len(), |
| 3034 | hedge_ms, |
| 3035 | "append hedged after the deadline" |
| 3036 | ); |
| 3037 | let mut hedged = |
| 3038 | std::pin::pin!(post_append_to(transport, policy, member, &job.req)); |
| 3039 | let (winner, winner_is_original) = crate::asyncrt::select_biased! { |
| 3040 | "the original attempt wins simultaneous replies so it retains the verdict"; |
| 3041 | resp = &mut original => (resp, true), |
| 3042 | resp = &mut hedged => (resp, false), |
| 3043 | }; |
| 3044 | if send_confirms(job.req.epoch, last, &winner) { |
| 3045 | winner |
| 3046 | } else if winner_is_original { |
| 3047 | // Give the duplicate the rest of its deadline, and |
| 3048 | // take it only to upgrade a non-confirmation. |
| 3049 | let late = hedged.await; |
| 3050 | if send_confirms(job.req.epoch, last, &late) { |
| 3051 | late |
| 3052 | } else { |
| 3053 | winner |
| 3054 | } |
| 3055 | } else { |
| 3056 | // The duplicate answered first and did not confirm: |
| 3057 | // whatever it said, the original owns the verdict. |
| 3058 | original.await |
| 3059 | } |
| 3060 | } |
| 3061 | } |
| 3062 | }; |
| 3063 | resolve_append(member, policy, health, tuning, job, started, 0, resp); |
| 3064 | } |
| 3065 | |
| 3066 | /// One member's ordered append lane. A single worker serves the member's |
| 3067 | /// rounds strictly in submission order, so several rounds in flight can |
| 3068 | /// never reorder appends at this follower; the worker exits when its |
| 3069 | /// shipper is dropped and the channel closes. With the stream transport |
| 3070 | /// the same worker pumps one long-lived duplex instead of awaiting each |
| 3071 | /// request round trip. |
| 3072 | #[doc(hidden)] |
| 3073 | pub async fn member_lane( |
| 3074 | member: Member, |
| 3075 | transport: Arc<dyn LogTransport>, |
| 3076 | policy: Arc<celld_logic::log_evict::EvictionPolicy>, |
| 3077 | health: Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3078 | tuning: LaneTuning, |
| 3079 | mut jobs: tokio::sync::mpsc::UnboundedReceiver<LaneJob>, |
| 3080 | stop: crate::ltx_repl::StopToken, |
| 3081 | ) { |
| 3082 | if tuning.stream_transport { |
| 3083 | stream_lane( |
| 3084 | &member, &transport, &policy, &health, &tuning, &mut jobs, &stop, |
| 3085 | ) |
| 3086 | .await; |
| 3087 | return; |
| 3088 | } |
| 3089 | loop { |
| 3090 | let job = crate::asyncrt::select_biased! { |
| 3091 | "a stop signal that ties queued work prevents the lane from taking another job"; |
| 3092 | _ = stop.stopped() => break, |
| 3093 | job = jobs.recv() => job, |
| 3094 | }; |
| 3095 | let Some(job) = job else { break }; |
| 3096 | let work = http_append_job(&member, &transport, &policy, &health, &tuning, job); |
| 3097 | tokio::pin!(work); |
| 3098 | crate::asyncrt::select_biased! { |
| 3099 | "a stop signal that ties one-shot completion ends the lane before more work"; |
| 3100 | _ = stop.stopped() => break, |
| 3101 | _ = &mut work => {}, |
| 3102 | } |
| 3103 | } |
| 3104 | } |
| 3105 | |
| 3106 | /// One frame the stream lane has written and not yet matched to a |
| 3107 | /// response. `job` empties when the hedge answers first; the entry then |
| 3108 | /// only holds the FIFO slot for the stream's late duplicate answer. |
| 3109 | struct StreamInFlight { |
| 3110 | job: Option<LaneJob>, |
| 3111 | frame: Vec<u8>, |
| 3112 | /// When the frame was written — queue residency starts here. |
| 3113 | started: u64, |
| 3114 | /// How long the socket write itself blocked the lane worker. Nonzero |
| 3115 | /// values mean TCP backpressure paces the lane; ~zero means the lane |
| 3116 | /// waits on the follower's serve cycle, not on the wire. |
| 3117 | write_ms: u64, |
| 3118 | /// The head-stall event fired for this frame (once per frame). |
| 3119 | stall_reported: bool, |
| 3120 | /// When the frame became the pipeline head — the follower's service |
| 3121 | /// clock. The health ledger and the hedge run on THIS, not on the |
| 3122 | /// write time: with W frames queued, write-to-resolve includes up to |
| 3123 | /// W round trips of residency, and a ledger built for one-in-flight |
| 3124 | /// lanes reads that as grayness and evicts a healthy member (the |
| 3125 | /// 2026-08-21 stall attribution). |
| 3126 | head_started: Option<u64>, |
| 3127 | hedged: bool, |
| 3128 | } |
| 3129 | |
| 3130 | #[derive(Clone, Copy)] |
| 3131 | enum StreamProgress { |
| 3132 | AwaitingFirstResponse, |
| 3133 | ReceivedResponse, |
| 3134 | } |
| 3135 | |
| 3136 | impl StreamProgress { |
| 3137 | fn after_response(self) -> Self { |
| 3138 | match self { |
| 3139 | Self::AwaitingFirstResponse => Self::ReceivedResponse, |
| 3140 | Self::ReceivedResponse => self, |
| 3141 | } |
| 3142 | } |
| 3143 | |
| 3144 | fn permits_replay(self) -> bool { |
| 3145 | matches!(self, Self::ReceivedResponse) |
| 3146 | } |
| 3147 | } |
| 3148 | |
| 3149 | /// The progress recovered by consuming and fully retiring one connection. |
| 3150 | /// Replay code cannot carry progress away from a live connection. |
| 3151 | struct RetiredStream { |
| 3152 | progress: StreamProgress, |
| 3153 | } |
| 3154 | |
| 3155 | impl RetiredStream { |
| 3156 | fn permits_replay(&self) -> bool { |
| 3157 | self.progress.permits_replay() |
| 3158 | } |
| 3159 | } |
| 3160 | |
| 3161 | /// One physical append stream, its reader, and the progress observed on that |
| 3162 | /// stream. A new connection always starts without progress. Only a response |
| 3163 | /// matched to a frame advances its state, so a one-shot answer cannot permit a |
| 3164 | /// replay on a silent stream. Dropping `responses` closes the reader's sender; |
| 3165 | /// `retire` then joins the reader before a replacement stream can start. |
| 3166 | struct StreamConnection { |
| 3167 | write: tokio::io::WriteHalf<LogStreamIo>, |
| 3168 | responses: tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>, |
| 3169 | reader: crate::asyncrt::TaskHandle<()>, |
| 3170 | progress: StreamProgress, |
| 3171 | } |
| 3172 | |
| 3173 | impl StreamConnection { |
| 3174 | fn new( |
| 3175 | write: tokio::io::WriteHalf<LogStreamIo>, |
| 3176 | responses: tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>, |
| 3177 | reader: crate::asyncrt::TaskHandle<()>, |
| 3178 | ) -> Self { |
| 3179 | Self { |
| 3180 | write, |
| 3181 | responses, |
| 3182 | reader, |
| 3183 | progress: StreamProgress::AwaitingFirstResponse, |
| 3184 | } |
| 3185 | } |
| 3186 | |
| 3187 | fn record_matched_response(&mut self) { |
| 3188 | self.progress = self.progress.after_response(); |
| 3189 | } |
| 3190 | |
| 3191 | async fn retire(self) -> RetiredStream { |
| 3192 | let Self { |
| 3193 | write, |
| 3194 | responses, |
| 3195 | reader, |
| 3196 | progress, |
| 3197 | } = self; |
| 3198 | drop(write); |
| 3199 | drop(responses); |
| 3200 | let _ = reader.await; |
| 3201 | RetiredStream { progress } |
| 3202 | } |
| 3203 | } |
| 3204 | |
| 3205 | /// Arm the service clock on the current head — the first unresolved |
| 3206 | /// frame — and give the health ledger its start sample. |
| 3207 | fn arm_head( |
| 3208 | member: &Member, |
| 3209 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3210 | inflight: &mut std::collections::VecDeque<StreamInFlight>, |
| 3211 | ) { |
| 3212 | if let Some(head) = inflight.iter_mut().find(|entry| entry.job.is_some()) { |
| 3213 | if head.head_started.is_none() { |
| 3214 | let now = mono_ms(); |
| 3215 | head.head_started = Some(now); |
| 3216 | health.lock().unwrap().append_started(&member.node, now); |
| 3217 | } |
| 3218 | } |
| 3219 | } |
| 3220 | |
| 3221 | /// The stream lane (the ordered-transport design): pump queued |
| 3222 | /// jobs down one ordered duplex and match responses strictly FIFO, so W |
| 3223 | /// frames ride the wire while the follower's single reader keeps apply |
| 3224 | /// order equal to submission order. The resume rule: on a broken stream, |
| 3225 | /// redial once and retransmit every unanswered frame in order — the |
| 3226 | /// follower's covering-end reading turns duplicates into acks, so the |
| 3227 | /// follower's own state decides what was persisted, never the leader's |
| 3228 | /// sent count (BrokenStreamResumeBlind is the model tooth). A break with |
| 3229 | /// no progress since the last dial fails every outstanding job instead, |
| 3230 | /// which degrades the shipper exactly as a failed append does today. A |
| 3231 | /// head frame stalled past the hedge deadline is raced by a one-shot |
| 3232 | /// duplicate; an old follower without the route drops the lane to the |
| 3233 | /// one-shot path for its lifetime. |
| 3234 | async fn stream_lane( |
| 3235 | member: &Member, |
| 3236 | transport: &Arc<dyn LogTransport>, |
| 3237 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 3238 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3239 | tuning: &LaneTuning, |
| 3240 | jobs: &mut tokio::sync::mpsc::UnboundedReceiver<LaneJob>, |
| 3241 | stop: &crate::ltx_repl::StopToken, |
| 3242 | ) { |
| 3243 | let mut conn: Option<StreamConnection> = None; |
| 3244 | let mut inflight: std::collections::VecDeque<StreamInFlight> = |
| 3245 | std::collections::VecDeque::new(); |
| 3246 | let mut hedge_rx: Option<tokio::sync::oneshot::Receiver<AppendSend>> = None; |
| 3247 | |
| 3248 | fn spawn_reader( |
| 3249 | read: tokio::io::ReadHalf<LogStreamIo>, |
| 3250 | ) -> ( |
| 3251 | tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>, |
| 3252 | crate::asyncrt::TaskHandle<()>, |
| 3253 | ) { |
| 3254 | let (send, receive) = tokio::sync::mpsc::unbounded_channel(); |
| 3255 | let reader = crate::asyncrt::spawn(async move { |
| 3256 | let mut read = read; |
| 3257 | loop { |
| 3258 | let frame = crate::asyncrt::select_biased! { |
| 3259 | "reader cancellation wins a tie with a frame from the retired connection"; |
| 3260 | _ = send.closed() => return, |
| 3261 | frame = read_frame(&mut read) => frame, |
| 3262 | }; |
| 3263 | match frame { |
| 3264 | Ok(Some(frame)) => { |
| 3265 | if send.send(frame).is_err() { |
| 3266 | return; |
| 3267 | } |
| 3268 | } |
| 3269 | Ok(None) | Err(_) => return, |
| 3270 | } |
| 3271 | } |
| 3272 | }); |
| 3273 | (receive, reader) |
| 3274 | } |
| 3275 | |
| 3276 | async fn dial( |
| 3277 | member: &Member, |
| 3278 | transport: &Arc<dyn LogTransport>, |
| 3279 | ) -> anyhow::Result<StreamConnection> { |
| 3280 | let io = transport |
| 3281 | .open_stream(&member.node, &member.addr, "/peer/log/stream") |
| 3282 | .await?; |
| 3283 | let (read, write) = tokio::io::split(io); |
| 3284 | let (responses, reader) = spawn_reader(read); |
| 3285 | Ok(StreamConnection::new(write, responses, reader)) |
| 3286 | } |
| 3287 | |
| 3288 | async fn retire_connection(conn: &mut Option<StreamConnection>) { |
| 3289 | if let Some(conn) = conn.take() { |
| 3290 | let _ = conn.retire().await; |
| 3291 | } |
| 3292 | } |
| 3293 | |
| 3294 | /// Fail every unanswered frame; the round futures then fail and the |
| 3295 | /// shipper degrades through the existing path. |
| 3296 | fn fail_all( |
| 3297 | member: &Member, |
| 3298 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 3299 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3300 | tuning: &LaneTuning, |
| 3301 | inflight: &mut std::collections::VecDeque<StreamInFlight>, |
| 3302 | ) { |
| 3303 | for entry in inflight.drain(..) { |
| 3304 | if let Some(job) = entry.job { |
| 3305 | resolve_append( |
| 3306 | member, |
| 3307 | policy, |
| 3308 | health, |
| 3309 | tuning, |
| 3310 | job, |
| 3311 | entry.started, |
| 3312 | entry.write_ms, |
| 3313 | AppendSend::Failed(anyhow::anyhow!("append stream failed")), |
| 3314 | ); |
| 3315 | } |
| 3316 | } |
| 3317 | } |
| 3318 | |
| 3319 | loop { |
| 3320 | // Disconnected: wait for work, then establish. |
| 3321 | if conn.is_none() { |
| 3322 | let job = crate::asyncrt::select_biased! { |
| 3323 | "a stop signal that ties queued work prevents a new stream connection"; |
| 3324 | _ = stop.stopped() => None, |
| 3325 | job = jobs.recv() => job, |
| 3326 | }; |
| 3327 | let Some(job) = job else { return }; |
| 3328 | match dial(member, transport).await { |
| 3329 | Ok(established) => conn = Some(established), |
| 3330 | Err(error) => { |
| 3331 | let incapable = error |
| 3332 | .downcast_ref::<PeerHttpError>() |
| 3333 | .is_some_and(|http| matches!(http.status.as_u16(), 404 | 405 | 501)); |
| 3334 | if incapable { |
| 3335 | // An old follower: this lane speaks one-shot HTTP for |
| 3336 | // its lifetime. The mixed fleet is safe and merely |
| 3337 | // slow on this member. |
| 3338 | info!( |
| 3339 | member = member.node, |
| 3340 | "follower has no stream route; lane falls back to one-shot appends" |
| 3341 | ); |
| 3342 | http_append_job(member, transport, policy, health, tuning, job).await; |
| 3343 | while let Some(job) = jobs.recv().await { |
| 3344 | http_append_job(member, transport, policy, health, tuning, job).await; |
| 3345 | } |
| 3346 | return; |
| 3347 | } |
| 3348 | let started = mono_ms(); |
| 3349 | health.lock().unwrap().append_started(&member.node, started); |
| 3350 | resolve_append( |
| 3351 | member, |
| 3352 | policy, |
| 3353 | health, |
| 3354 | tuning, |
| 3355 | job, |
| 3356 | started, |
| 3357 | 0, |
| 3358 | AppendSend::Failed(error), |
| 3359 | ); |
| 3360 | continue; |
| 3361 | } |
| 3362 | } |
| 3363 | // Fall through with the job still to write. |
| 3364 | let write = &mut conn.as_mut().expect("just established").write; |
| 3365 | let frame = encode_append(&job.req); |
| 3366 | let started = mono_ms(); |
| 3367 | if write_frame(write, &frame).await.is_err() { |
| 3368 | retire_connection(&mut conn).await; |
| 3369 | health.lock().unwrap().append_started(&member.node, started); |
| 3370 | resolve_append( |
| 3371 | member, |
| 3372 | policy, |
| 3373 | health, |
| 3374 | tuning, |
| 3375 | job, |
| 3376 | started, |
| 3377 | mono_ms().saturating_sub(started), |
| 3378 | AppendSend::Failed(anyhow::anyhow!("append stream write failed")), |
| 3379 | ); |
| 3380 | continue; |
| 3381 | } |
| 3382 | inflight.push_back(StreamInFlight { |
| 3383 | job: Some(job), |
| 3384 | frame, |
| 3385 | started, |
| 3386 | write_ms: mono_ms().saturating_sub(started), |
| 3387 | stall_reported: false, |
| 3388 | head_started: None, |
| 3389 | hedged: false, |
| 3390 | }); |
| 3391 | arm_head(member, health, &mut inflight); |
| 3392 | continue; |
| 3393 | } |
| 3394 | |
| 3395 | // The hedge deadline for the head frame, when one is eligible. |
| 3396 | let armed_hedge_ms = if hedge_rx.is_none() { |
| 3397 | resolve_hedge_ms(tuning, policy, health) |
| 3398 | } else { |
| 3399 | 0 |
| 3400 | }; |
| 3401 | let hedge_deadline = if armed_hedge_ms > 0 { |
| 3402 | inflight |
| 3403 | .iter() |
| 3404 | .find(|entry| entry.job.is_some()) |
| 3405 | .filter(|entry| !entry.hedged) |
| 3406 | .and_then(|entry| Some(entry.head_started? + armed_hedge_ms)) |
| 3407 | } else { |
| 3408 | None |
| 3409 | }; |
| 3410 | // The head-stall ledger (the overload-stability design): a head |
| 3411 | // outstanding past half the backstop is on its way to evicting a |
| 3412 | // member, and this is the leader's only view of WHERE the frame |
| 3413 | // sat — write_ms says whether the socket write drained; a frame |
| 3414 | // that wrote in ~0 ms yet goes unanswered was not read. |
| 3415 | { |
| 3416 | let now = mono_ms(); |
| 3417 | let queued = inflight.len(); |
| 3418 | if let Some(head) = inflight.iter_mut().find(|entry| entry.job.is_some()) { |
| 3419 | if let Some(head_started) = head.head_started { |
| 3420 | let age_ms = now.saturating_sub(head_started); |
| 3421 | if !head.stall_reported && age_ms >= policy.backstop_ms / 2 { |
| 3422 | head.stall_reported = true; |
| 3423 | warn!( |
| 3424 | event = "log_head_stall", |
| 3425 | member = member.node, |
| 3426 | age_ms, |
| 3427 | queue_residency_ms = head_started.saturating_sub(head.started), |
| 3428 | write_ms = head.write_ms, |
| 3429 | entries = head.job.as_ref().map_or(0, |job| job.req.entries.len()), |
| 3430 | bytes = head.frame.len(), |
| 3431 | queued, |
| 3432 | "stream head outstanding past half the backstop" |
| 3433 | ); |
| 3434 | } |
| 3435 | } |
| 3436 | } |
| 3437 | } |
| 3438 | |
| 3439 | let responses = &mut conn.as_mut().expect("connected").responses; |
| 3440 | enum LaneEvent { |
| 3441 | Job(Option<LaneJob>), |
| 3442 | Response(Option<Vec<u8>>), |
| 3443 | HedgeFire, |
| 3444 | HedgeAnswer(AppendSend), |
| 3445 | Stopped, |
| 3446 | } |
| 3447 | let hedge_side = async { |
| 3448 | crate::asyncrt::select_biased! { |
| 3449 | "an armed hedge deadline wins a tie with the preceding hedge answer"; |
| 3450 | fired = async { |
| 3451 | match hedge_deadline { |
| 3452 | Some(deadline) => { |
| 3453 | let wait = deadline.saturating_sub(mono_ms()); |
| 3454 | crate::asyncrt::sleep(std::time::Duration::from_millis(wait)).await |
| 3455 | } |
| 3456 | None => std::future::pending().await, |
| 3457 | } |
| 3458 | } => { |
| 3459 | let () = fired; |
| 3460 | LaneEvent::HedgeFire |
| 3461 | }, |
| 3462 | answer = async { |
| 3463 | match &mut hedge_rx { |
| 3464 | Some(receiver) => match receiver.await { |
| 3465 | Ok(answer) => answer, |
| 3466 | Err(_) => AppendSend::Failed(anyhow::anyhow!("hedge task dropped")), |
| 3467 | }, |
| 3468 | None => std::future::pending().await, |
| 3469 | } |
| 3470 | } => LaneEvent::HedgeAnswer(answer), |
| 3471 | } |
| 3472 | }; |
| 3473 | let event = crate::asyncrt::select_biased! { |
| 3474 | "a lane event wins a tie with hedge work so ordered stream progress runs first"; |
| 3475 | event = async { |
| 3476 | crate::asyncrt::select_biased! { |
| 3477 | "a stop signal that ties stream activity closes the lane first"; |
| 3478 | stopped = async { |
| 3479 | stop.stopped().await; |
| 3480 | LaneEvent::Stopped |
| 3481 | } => stopped, |
| 3482 | event = async { |
| 3483 | crate::asyncrt::select_biased! { |
| 3484 | "a queued append wins a tie with a response to preserve legacy lane order"; |
| 3485 | job = jobs.recv() => LaneEvent::Job(job), |
| 3486 | response = responses.recv() => LaneEvent::Response(response), |
| 3487 | } |
| 3488 | } => event, |
| 3489 | } |
| 3490 | } => event, |
| 3491 | event = hedge_side => event, |
| 3492 | }; |
| 3493 | |
| 3494 | match event { |
| 3495 | LaneEvent::Stopped => { |
| 3496 | fail_all(member, policy, health, tuning, &mut inflight); |
| 3497 | retire_connection(&mut conn).await; |
| 3498 | return; |
| 3499 | } |
| 3500 | LaneEvent::Job(None) => { |
| 3501 | retire_connection(&mut conn).await; |
| 3502 | return; |
| 3503 | } |
| 3504 | LaneEvent::Job(Some(job)) => { |
| 3505 | let write = &mut conn.as_mut().expect("connected").write; |
| 3506 | let frame = encode_append(&job.req); |
| 3507 | let started = mono_ms(); |
| 3508 | let written = write_frame(write, &frame).await; |
| 3509 | let write_ms = mono_ms().saturating_sub(started); |
| 3510 | match written { |
| 3511 | Ok(()) => { |
| 3512 | inflight.push_back(StreamInFlight { |
| 3513 | job: Some(job), |
| 3514 | frame, |
| 3515 | started, |
| 3516 | write_ms, |
| 3517 | stall_reported: false, |
| 3518 | head_started: None, |
| 3519 | hedged: false, |
| 3520 | }); |
| 3521 | arm_head(member, health, &mut inflight); |
| 3522 | } |
| 3523 | Err(_) => { |
| 3524 | inflight.push_back(StreamInFlight { |
| 3525 | job: Some(job), |
| 3526 | frame, |
| 3527 | started, |
| 3528 | write_ms, |
| 3529 | stall_reported: false, |
| 3530 | head_started: None, |
| 3531 | hedged: false, |
| 3532 | }); |
| 3533 | conn = reconnect( |
| 3534 | conn.take().expect("connected"), |
| 3535 | member, |
| 3536 | transport, |
| 3537 | policy, |
| 3538 | health, |
| 3539 | tuning, |
| 3540 | &mut inflight, |
| 3541 | ) |
| 3542 | .await; |
| 3543 | } |
| 3544 | } |
| 3545 | } |
| 3546 | LaneEvent::Response(Some(payload)) => { |
| 3547 | let Some(mut entry) = inflight.pop_front() else { |
| 3548 | // A response with no frame outstanding is a protocol |
| 3549 | // violation; drop the stream and let redial sort it out. |
| 3550 | conn = reconnect( |
| 3551 | conn.take().expect("connected"), |
| 3552 | member, |
| 3553 | transport, |
| 3554 | policy, |
| 3555 | health, |
| 3556 | tuning, |
| 3557 | &mut inflight, |
| 3558 | ) |
| 3559 | .await; |
| 3560 | continue; |
| 3561 | }; |
| 3562 | conn.as_mut().expect("connected").record_matched_response(); |
| 3563 | let Some(job) = entry.job.take() else { |
| 3564 | // The hedge already answered this frame; the stream's |
| 3565 | // duplicate only frees the FIFO slot. |
| 3566 | arm_head(member, health, &mut inflight); |
| 3567 | continue; |
| 3568 | }; |
| 3569 | let service_started = entry.head_started.unwrap_or(entry.started); |
| 3570 | match serde_json::from_slice::<AppendResp>(&payload) { |
| 3571 | Ok(resp) => { |
| 3572 | resolve_append( |
| 3573 | member, |
| 3574 | policy, |
| 3575 | health, |
| 3576 | tuning, |
| 3577 | job, |
| 3578 | service_started, |
| 3579 | entry.write_ms, |
| 3580 | AppendSend::Answered(resp), |
| 3581 | ); |
| 3582 | arm_head(member, health, &mut inflight); |
| 3583 | } |
| 3584 | Err(error) => { |
| 3585 | resolve_append( |
| 3586 | member, |
| 3587 | policy, |
| 3588 | health, |
| 3589 | tuning, |
| 3590 | job, |
| 3591 | service_started, |
| 3592 | entry.write_ms, |
| 3593 | AppendSend::Failed(error.into()), |
| 3594 | ); |
| 3595 | conn = reconnect( |
| 3596 | conn.take().expect("connected"), |
| 3597 | member, |
| 3598 | transport, |
| 3599 | policy, |
| 3600 | health, |
| 3601 | tuning, |
| 3602 | &mut inflight, |
| 3603 | ) |
| 3604 | .await; |
| 3605 | } |
| 3606 | } |
| 3607 | } |
| 3608 | LaneEvent::Response(None) => { |
| 3609 | conn = reconnect( |
| 3610 | conn.take().expect("connected"), |
| 3611 | member, |
| 3612 | transport, |
| 3613 | policy, |
| 3614 | health, |
| 3615 | tuning, |
| 3616 | &mut inflight, |
| 3617 | ) |
| 3618 | .await; |
| 3619 | } |
| 3620 | LaneEvent::HedgeFire => { |
| 3621 | if let Some(entry) = inflight |
| 3622 | .iter_mut() |
| 3623 | .find(|entry| entry.job.is_some()) |
| 3624 | .filter(|entry| !entry.hedged) |
| 3625 | { |
| 3626 | entry.hedged = true; |
| 3627 | info!( |
| 3628 | event = "log_append_hedge", |
| 3629 | member = member.node, |
| 3630 | hedge_ms = armed_hedge_ms, |
| 3631 | "stream head hedged after the deadline" |
| 3632 | ); |
| 3633 | let (send, receive) = tokio::sync::oneshot::channel(); |
| 3634 | hedge_rx = Some(receive); |
| 3635 | let transport = transport.clone(); |
| 3636 | let policy_owned = policy.clone(); |
| 3637 | let member_owned = member.clone(); |
| 3638 | let req = entry |
| 3639 | .job |
| 3640 | .as_ref() |
| 3641 | .map(|job| job.req.clone()) |
| 3642 | .expect("checked job.is_some"); |
| 3643 | crate::asyncrt::spawn(async move { |
| 3644 | let resp = |
| 3645 | post_append_to(&transport, &policy_owned, &member_owned, &req).await; |
| 3646 | let _ = send.send(resp); |
| 3647 | }) |
| 3648 | .detach(); |
| 3649 | } |
| 3650 | } |
| 3651 | LaneEvent::HedgeAnswer(resp) => { |
| 3652 | hedge_rx = None; |
| 3653 | let mut confirmed = None; |
| 3654 | if let Some(entry) = inflight |
| 3655 | .iter_mut() |
| 3656 | .find(|entry| entry.hedged && entry.job.is_some()) |
| 3657 | { |
| 3658 | // The one-shot duplicate may only ever turn a |
| 3659 | // non-confirmation into a confirmation (the #199 race |
| 3660 | // rule): a duplicate that failed fast or answered |
| 3661 | // Incapable proves nothing about what the follower |
| 3662 | // holds, and the stream's own answer — bounded by the |
| 3663 | // reconnect deadline — owns the verdict. |
| 3664 | let last = entry |
| 3665 | .job |
| 3666 | .as_ref() |
| 3667 | .map(|job| job.req.entries.last().map_or(0, |entry| entry.seq)) |
| 3668 | .unwrap_or(0); |
| 3669 | let epoch = entry.job.as_ref().map(|job| job.req.epoch).unwrap_or(0); |
| 3670 | if send_confirms(epoch, last, &resp) { |
| 3671 | if let Some(job) = entry.job.take() { |
| 3672 | let service_started = entry.head_started.unwrap_or(entry.started); |
| 3673 | confirmed = Some((job, service_started, entry.write_ms)); |
| 3674 | } |
| 3675 | } |
| 3676 | } |
| 3677 | if let Some((job, service_started, write_ms)) = confirmed { |
| 3678 | // A one-shot answer proves that the follower is reachable, |
| 3679 | // but it is not progress on this stream connection. Retire |
| 3680 | // the stalled connection now, so its complete unresolved |
| 3681 | // queue shares one deadline. `reconnect` permits one ordered |
| 3682 | // replay only when this stream previously returned a frame. |
| 3683 | let retired = conn.take().expect("connected").retire().await; |
| 3684 | resolve_append( |
| 3685 | member, |
| 3686 | policy, |
| 3687 | health, |
| 3688 | tuning, |
| 3689 | job, |
| 3690 | service_started, |
| 3691 | write_ms, |
| 3692 | resp, |
| 3693 | ); |
| 3694 | conn = redial_after_retire( |
| 3695 | retired, |
| 3696 | member, |
| 3697 | transport, |
| 3698 | policy, |
| 3699 | health, |
| 3700 | tuning, |
| 3701 | &mut inflight, |
| 3702 | ) |
| 3703 | .await; |
| 3704 | } else { |
| 3705 | arm_head(member, health, &mut inflight); |
| 3706 | } |
| 3707 | } |
| 3708 | } |
| 3709 | } |
| 3710 | |
| 3711 | /// Redial once and retransmit every unanswered frame in order. The |
| 3712 | /// follower's reported state decides what those retransmissions mean: |
| 3713 | /// a persisted range refuses with a covering end, which reads as the |
| 3714 | /// ack. A break with no answer since the last dial fails everything |
| 3715 | /// instead of looping. |
| 3716 | async fn reconnect( |
| 3717 | established: StreamConnection, |
| 3718 | member: &Member, |
| 3719 | transport: &Arc<dyn LogTransport>, |
| 3720 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 3721 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3722 | tuning: &LaneTuning, |
| 3723 | inflight: &mut std::collections::VecDeque<StreamInFlight>, |
| 3724 | ) -> Option<StreamConnection> { |
| 3725 | let retired = established.retire().await; |
| 3726 | redial_after_retire(retired, member, transport, policy, health, tuning, inflight).await |
| 3727 | } |
| 3728 | |
| 3729 | async fn redial_after_retire( |
| 3730 | retired: RetiredStream, |
| 3731 | member: &Member, |
| 3732 | transport: &Arc<dyn LogTransport>, |
| 3733 | policy: &celld_logic::log_evict::EvictionPolicy, |
| 3734 | health: &Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3735 | tuning: &LaneTuning, |
| 3736 | inflight: &mut std::collections::VecDeque<StreamInFlight>, |
| 3737 | ) -> Option<StreamConnection> { |
| 3738 | if !retired.permits_replay() { |
| 3739 | fail_all(member, policy, health, tuning, inflight); |
| 3740 | return None; |
| 3741 | } |
| 3742 | // Hedge-resolved slots have no response coming on the new stream. |
| 3743 | inflight.retain(|entry| entry.job.is_some()); |
| 3744 | // The retransmission restarts every frame's service; a stale head |
| 3745 | // clock would bill the outage to the follower's health. |
| 3746 | for entry in inflight.iter_mut() { |
| 3747 | entry.head_started = None; |
| 3748 | } |
| 3749 | match dial(member, transport).await { |
| 3750 | Ok(mut conn) => { |
| 3751 | for entry in inflight.iter() { |
| 3752 | if write_frame(&mut conn.write, &entry.frame).await.is_err() { |
| 3753 | conn.retire().await; |
| 3754 | fail_all(member, policy, health, tuning, inflight); |
| 3755 | return None; |
| 3756 | } |
| 3757 | } |
| 3758 | arm_head(member, health, inflight); |
| 3759 | Some(conn) |
| 3760 | } |
| 3761 | Err(_) => { |
| 3762 | fail_all(member, policy, health, tuning, inflight); |
| 3763 | None |
| 3764 | } |
| 3765 | } |
| 3766 | } |
| 3767 | } |
| 3768 | |
| 3769 | impl FleetShipper { |
| 3770 | /// Ship one batch to every member through its ordered lane. |
| 3771 | /// |
| 3772 | /// The synchronous prefix allocates the sequence range and enqueues the |
| 3773 | /// round on every member lane BEFORE returning the future, so submission |
| 3774 | /// order — not poll order — fixes the per-member append order. The |
| 3775 | /// returned future only collects the answers: `Some(last_seq)` when |
| 3776 | /// every member confirmed every entry fsync'd — the ack-all rule. Any |
| 3777 | /// failure degrades the shipper: fleet proofs stop and the gate rides |
| 3778 | /// the bucket upload, which is always safe. `covered_seq` rides along |
| 3779 | /// as the followers' truncate_to. |
| 3780 | fn ship_batch( |
| 3781 | &self, |
| 3782 | batch: Vec<ShipEntry>, |
| 3783 | covered_seq: u64, |
| 3784 | ) -> std::pin::Pin< |
| 3785 | Box<dyn std::future::Future<Output = crate::ltx_repl::ShipCompletion> + Send + 'static>, |
| 3786 | > { |
| 3787 | if self.members.is_empty() || batch.is_empty() { |
| 3788 | return Box::pin(std::future::ready( |
| 3789 | crate::ltx_repl::ShipCompletion::unreserved(None), |
| 3790 | )); |
| 3791 | } |
| 3792 | // The count rises BEFORE the degraded check: |
| 3793 | // maintain sets degraded and then reads the outstanding count as |
| 3794 | // its drain barrier, so the old order let a batch slip past a |
| 3795 | // reconfiguration's decision and fleet-ack frames on the retired |
| 3796 | // ensemble that the barrier never counted. |
| 3797 | self.outstanding.fetch_add(1, Ordering::SeqCst); |
| 3798 | let outstanding = OutstandingRound(self.outstanding.clone()); |
| 3799 | if self.degraded.load(Ordering::SeqCst) { |
| 3800 | return Box::pin(async move { |
| 3801 | crate::ltx_repl::ShipCompletion::reserved(None, outstanding) |
| 3802 | }); |
| 3803 | } |
| 3804 | let first = self.seq.fetch_add(batch.len() as u64, Ordering::SeqCst) + 1; |
| 3805 | let entries: Vec<Entry> = batch |
| 3806 | .into_iter() |
| 3807 | .enumerate() |
| 3808 | .map(|(index, entry)| Entry { |
| 3809 | seq: first + index as u64, |
| 3810 | cell: entry.cell, |
| 3811 | cell_epoch: entry.epoch, |
| 3812 | txid: entry.txid, |
| 3813 | bytes: entry.bytes, |
| 3814 | }) |
| 3815 | .collect(); |
| 3816 | let last = first + entries.len() as u64 - 1; |
| 3817 | let req = Arc::new(AppendReq { |
| 3818 | leader: self.node.clone(), |
| 3819 | epoch: self.epoch, |
| 3820 | truncate_to: covered_seq, |
| 3821 | entries, |
| 3822 | }); |
| 3823 | let req_bytes = req |
| 3824 | .entries |
| 3825 | .iter() |
| 3826 | .map(|entry| entry.bytes.len() as u64) |
| 3827 | .sum::<u64>(); |
| 3828 | let receivers: Vec<tokio::sync::oneshot::Receiver<Option<(String, u64)>>> = self |
| 3829 | .lanes |
| 3830 | .iter() |
| 3831 | .enumerate() |
| 3832 | .map(|(index, lane)| { |
| 3833 | if let Some(stream) = &self.stream { |
| 3834 | stream.submitted(index, req_bytes); |
| 3835 | } |
| 3836 | let (resp, receive) = tokio::sync::oneshot::channel(); |
| 3837 | let _ = lane.send(LaneJob { |
| 3838 | req: req.clone(), |
| 3839 | enqueued: mono_ms(), |
| 3840 | bytes: req_bytes, |
| 3841 | resp, |
| 3842 | }); |
| 3843 | receive |
| 3844 | }) |
| 3845 | .collect(); |
| 3846 | let view = log_tier::LeaderView { |
| 3847 | epoch: self.epoch, |
| 3848 | ensemble: self.record.ensemble.clone(), |
| 3849 | }; |
| 3850 | let activated = self.activated.clone(); |
| 3851 | let degraded = self.degraded.clone(); |
| 3852 | let live_log = self.live_log.clone(); |
| 3853 | let record = self.record.clone(); |
| 3854 | let epoch = self.epoch; |
| 3855 | Box::pin(async move { |
| 3856 | // Write-all, ack-all is the core's decision: every ensemble |
| 3857 | // member must confirm a contiguous end at or past the batch — a |
| 3858 | // member that refused, errored, or answered short is a failed |
| 3859 | // batch. |
| 3860 | let ends: BTreeMap<String, u64> = futures_util::future::join_all(receivers) |
| 3861 | .await |
| 3862 | .into_iter() |
| 3863 | .flatten() |
| 3864 | .flatten() |
| 3865 | .collect(); |
| 3866 | if log_tier::ack_fleet_allowed(&view, &ends, last) { |
| 3867 | // The activation fence: before the epoch's first fleet ack |
| 3868 | // is credited, the record must set `may_have_fleet_acks`, or |
| 3869 | // recovery meeting only amnesiac members would seal an empty |
| 3870 | // gather as if nothing had ever been acked. |
| 3871 | if !activated.load(Ordering::SeqCst) { |
| 3872 | let activation_applied = live_log.activate(&record).await.unwrap_or(false); |
| 3873 | // Through the core's lease chain (lease-fold): a fenced |
| 3874 | // session's renewals stop applying, so the wait fails |
| 3875 | // and the ack must not credit. |
| 3876 | if activation_applied { |
| 3877 | activated.store(true, Ordering::SeqCst); |
| 3878 | } else { |
| 3879 | degrade_shared(°raded, epoch, "activation transition not applied"); |
| 3880 | return crate::ltx_repl::ShipCompletion::reserved(None, outstanding); |
| 3881 | } |
| 3882 | } |
| 3883 | return crate::ltx_repl::ShipCompletion::reserved(Some(last), outstanding); |
| 3884 | } |
| 3885 | degrade_shared(°raded, epoch, "member append failed"); |
| 3886 | crate::ltx_repl::ShipCompletion::reserved(None, outstanding) |
| 3887 | }) |
| 3888 | } |
| 3889 | } |
| 3890 | |
| 3891 | // ── Recovery and the takeover interlock ───────────────────────────────────── |
| 3892 | |
| 3893 | /// Everything node-log recovery needs from the node: the bucket, the signed |
| 3894 | /// peer client, address resolution, and the raw per-cell upload. |
| 3895 | pub struct NodeLogManager { |
| 3896 | node: String, |
| 3897 | /// The single-writer path for our own folded log state: publishes to |
| 3898 | /// the ownership store and rides the core's immediate renewal. |
| 3899 | live_log: Arc<LiveLogTransitions>, |
| 3900 | /// This process session's log identity: `<node>/<generation>`, the |
| 3901 | /// generation from the node lease record. Every self record, bundle, |
| 3902 | /// fragment, and loss key hangs off it. |
| 3903 | session: String, |
| 3904 | bucket: Arc<Bucket>, |
| 3905 | ownership: Arc<crate::ownership_store::BucketOwnership>, |
| 3906 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 3907 | transport: Arc<dyn LogTransport>, |
| 3908 | /// The current ensemble's shipper, swapped whole by the maintenance |
| 3909 | /// loop. The manager itself is the installed `Shipper`, delegating here. |
| 3910 | inner: Mutex<Option<Arc<FleetShipper>>>, |
| 3911 | bundle_seq: std::sync::atomic::AtomicU64, |
| 3912 | /// The leader's own index of the bundles it wrote this run. Cell |
| 3913 | /// membership stays complete for the process session, while full row |
| 3914 | /// metadata stays bounded. A restart loses the index safely because it |
| 3915 | /// creates a new session and recovers the previous session as one unit. |
| 3916 | bundle_index: Mutex<BundleIndex>, |
| 3917 | /// Resume after examined bundles, including those not yet covered. |
| 3918 | /// Serialize passes so overlapping callers cannot move the cursor back. |
| 3919 | bundle_gc_cursor: tokio::sync::Mutex<Option<String>>, |
| 3920 | /// Sessions whose bundle subtree one sweep pass confirmed empty: |
| 3921 | /// a permanent tombstone (dead-lease GC never deletes a folded |
| 3922 | /// record) must not cost a bundle LIST on every sweep tick forever |
| 3923 | /// Process-local; a restart re-confirms once. |
| 3924 | gc_confirmed_empty: Mutex<std::collections::HashSet<String>>, |
| 3925 | /// Retained bundles this process has already declared unreadable. The |
| 3926 | /// record is the durable one; this only keeps one process from |
| 3927 | /// rewriting the same declaration on every scan. |
| 3928 | declared_bundle_losses: Mutex<BTreeSet<String>>, |
| 3929 | /// One-slot cache for the compactor's fetches: bundles are read many |
| 3930 | /// rows at a time, and re-GETting per row would refund the savings. |
| 3931 | bundle_cache: tokio::sync::Mutex<Option<(String, Arc<Vec<u8>>)>>, |
| 3932 | /// The gray-follower ledger: append timings in, eviction verdicts and |
| 3933 | /// the quarantine out. Outlives every shipper swap. |
| 3934 | health: Arc<Mutex<celld_logic::log_evict::FollowerHealth>>, |
| 3935 | policy: Arc<celld_logic::log_evict::EvictionPolicy>, |
| 3936 | /// A correlated member stall latched self-suspicion: every ensemble |
| 3937 | /// member stuck at once means our own connectivity is the suspect, |
| 3938 | /// so recruitment parks — no reopen CAS churn into a partition — |
| 3939 | /// until any peer answers anything successfully. Cleared by a probe |
| 3940 | /// or append Ok; 37 doomed epochs in one 45 s partition taught the |
| 3941 | /// alternative. |
| 3942 | suspect_self: Arc<std::sync::atomic::AtomicBool>, |
| 3943 | /// When we last said that the fleet posture is requested and not |
| 3944 | /// achieved. `maintain` runs on a ticker and used to return silently |
| 3945 | /// whenever it found no peer to recruit, so a fleet that never formed an |
| 3946 | /// ensemble logged nothing at all — only a fleet that formed one and lost |
| 3947 | /// it did. A single node then paid the bucket for every write with no |
| 3948 | /// line anywhere saying why, or that a second node changes it. |
| 3949 | shortfall_logged_ms: Arc<std::sync::atomic::AtomicU64>, |
| 3950 | /// The shutdown latch: once set, the bundle sink refuses new flushes |
| 3951 | /// so the graceful seal's uncovered-scan cannot go stale between the |
| 3952 | /// LIST and the seal CAS. |
| 3953 | closing: std::sync::atomic::AtomicBool, |
| 3954 | /// A bundle flush between its PUT and its credit; the graceful seal |
| 3955 | /// waits this out after latching `closing`. |
| 3956 | flush_in_flight: std::sync::atomic::AtomicBool, |
| 3957 | #[cfg(all(test, celld_internal_tests))] |
| 3958 | close_transition_pause: Mutex<Option<Arc<NodeLogTransitionPause>>>, |
| 3959 | #[cfg(all(test, celld_internal_tests))] |
| 3960 | maintenance_install_pause: Mutex<Option<Arc<NodeLogTransitionPause>>>, |
| 3961 | #[cfg(all(test, celld_internal_tests))] |
| 3962 | maintenance_publish_pause: Mutex<Option<Arc<NodeLogTransitionPause>>>, |
| 3963 | #[cfg(all(test, celld_internal_tests))] |
| 3964 | shipper_injection_calls: std::sync::atomic::AtomicU64, |
| 3965 | /// The gather window budget. A test override lowers it to fold a |
| 3966 | /// small session in several windows. |
| 3967 | #[cfg(all(test, celld_internal_tests))] |
| 3968 | recovery_gather_window_bytes: std::sync::atomic::AtomicU64, |
| 3969 | /// The most row bytes one gather window held at once, the measure of |
| 3970 | /// the memory a recovery costs. |
| 3971 | #[cfg(all(test, celld_internal_tests))] |
| 3972 | recovery_gather_peak_bytes: std::sync::atomic::AtomicU64, |
| 3973 | /// Every predecessor session's log is proven recovered; see |
| 3974 | /// `ensure_predecessors_recovered` for why this can latch. |
| 3975 | predecessors_clean: std::sync::atomic::AtomicBool, |
| 3976 | /// Process-local single-flight locks for dead-session recovery. The map |
| 3977 | /// stores weak values, so observing many historical sessions does not |
| 3978 | /// retain one allocation per session for the process lifetime. |
| 3979 | recovery_locks: Mutex<BTreeMap<String, std::sync::Weak<tokio::sync::Mutex<()>>>>, |
| 3980 | /// Sessions for which this process won the Open -> Recovering CAS. A |
| 3981 | /// failed elected pass can retry immediately; other processes wait for |
| 3982 | /// the bounded claim before they compete to replace it. |
| 3983 | task_stop: crate::ltx_repl::StopToken, |
| 3984 | child_tasks: crate::ltx_repl::TaskGroup, |
| 3985 | } |
| 3986 | |
| 3987 | struct NodeLogTaskOwner { |
| 3988 | stop: crate::ltx_repl::StopToken, |
| 3989 | roots: crate::ltx_repl::TaskGroup, |
| 3990 | children: crate::ltx_repl::TaskGroup, |
| 3991 | } |
| 3992 | |
| 3993 | struct FollowerTaskOwner { |
| 3994 | store: Option<Arc<FollowerStore>>, |
| 3995 | follower_stop: crate::ltx_repl::StopToken, |
| 3996 | follower_tasks: crate::ltx_repl::TaskGroup, |
| 3997 | } |
| 3998 | |
| 3999 | struct OwnedDurabilityStack { |
| 4000 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 4001 | manager: Arc<NodeLogManager>, |
| 4002 | registration: Option<crate::ltx_repl::DurabilityRegistration>, |
| 4003 | ltx_tasks: Option<crate::ltx_repl::LtxTaskOwner>, |
| 4004 | replica_close_task: Option<crate::asyncrt::TaskHandle<()>>, |
| 4005 | node_log_tasks: NodeLogTaskOwner, |
| 4006 | fleet: bool, |
| 4007 | } |
| 4008 | |
| 4009 | /// The daemon's unique owner for one local durability stack. |
| 4010 | /// |
| 4011 | /// Cloneable runtime handles can borrow the replicator and the manager, but |
| 4012 | /// only this value controls their coupled registration and background tasks. |
| 4013 | /// A drop requests the local fallback but does not join tasks. Call |
| 4014 | /// [`Self::shutdown_local`] to prove that all admitted tasks completed. |
| 4015 | pub struct DurabilityOwner { |
| 4016 | stack: Option<OwnedDurabilityStack>, |
| 4017 | follower_tasks: FollowerTaskOwner, |
| 4018 | } |
| 4019 | |
| 4020 | impl DurabilityOwner { |
| 4021 | /// Creates the unique owner for a runtime durability stack. |
| 4022 | /// |
| 4023 | /// Set `fleet` to install the coupled node-log registration. |
| 4024 | /// The fleet shipper and bundle sink are always installed together. |
| 4025 | /// |
| 4026 | /// # Panics |
| 4027 | /// |
| 4028 | /// The function panics if another owner controls the LTX task set. It also |
| 4029 | /// panics if a fleet registration targets a stopped LTX service. |
| 4030 | pub fn new(manager: Arc<NodeLogManager>, fleet: bool) -> Self { |
| 4031 | let ltx = manager.ltx.clone(); |
| 4032 | // Claim the unique lifecycle capability before changing the coupled |
| 4033 | // registration. A duplicate construction fails here, so its unwind |
| 4034 | // cannot supersede and then clear the live owner's generation. |
| 4035 | let ltx_tasks = ltx.take_task_owner(); |
| 4036 | let registration = fleet.then(|| { |
| 4037 | ltx.register_durability(manager.clone()) |
| 4038 | .expect("a new durability owner cannot install on a stopped LTX service") |
| 4039 | }); |
| 4040 | Self::from_claimed_registration(manager, fleet, ltx, ltx_tasks, registration) |
| 4041 | } |
| 4042 | |
| 4043 | /// Installs a gated shipper decorator at the shipping registration seam. |
| 4044 | /// The lifecycle owner still retains the real manager, so the decorator |
| 4045 | /// cannot replace its maintenance, shutdown, or bundle ownership. |
| 4046 | #[cfg(all(test, celld_internal_tests))] |
| 4047 | pub(crate) fn new_with_shipper_for_world( |
| 4048 | manager: Arc<NodeLogManager>, |
| 4049 | fleet: bool, |
| 4050 | shipper: Arc<dyn crate::ltx_repl::Shipper>, |
| 4051 | ) -> Self { |
| 4052 | manager |
| 4053 | .shipper_injection_calls |
| 4054 | .fetch_add(1, Ordering::SeqCst); |
| 4055 | let ltx = manager.ltx.clone(); |
| 4056 | let ltx_tasks = ltx.take_task_owner(); |
| 4057 | let registration = fleet.then(|| { |
| 4058 | ltx.register_durability_for_world(manager.clone(), shipper) |
| 4059 | .expect("a new durability owner cannot install on a stopped LTX service") |
| 4060 | }); |
| 4061 | Self::from_claimed_registration(manager, fleet, ltx, ltx_tasks, registration) |
| 4062 | } |
| 4063 | |
| 4064 | fn from_claimed_registration( |
| 4065 | manager: Arc<NodeLogManager>, |
| 4066 | fleet: bool, |
| 4067 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 4068 | ltx_tasks: crate::ltx_repl::LtxTaskOwner, |
| 4069 | registration: Option<crate::ltx_repl::DurabilityRegistration>, |
| 4070 | ) -> Self { |
| 4071 | let follower_stop = crate::ltx_repl::StopToken::new(); |
| 4072 | let node_log_stop = manager.task_stop.clone(); |
| 4073 | let child_tasks = manager.child_tasks.clone(); |
| 4074 | Self { |
| 4075 | stack: Some(OwnedDurabilityStack { |
| 4076 | ltx, |
| 4077 | manager, |
| 4078 | registration, |
| 4079 | ltx_tasks: Some(ltx_tasks), |
| 4080 | replica_close_task: None, |
| 4081 | node_log_tasks: NodeLogTaskOwner { |
| 4082 | stop: node_log_stop.clone(), |
| 4083 | roots: crate::ltx_repl::TaskGroup::new(node_log_stop), |
| 4084 | children: child_tasks, |
| 4085 | }, |
| 4086 | fleet, |
| 4087 | }), |
| 4088 | follower_tasks: FollowerTaskOwner { |
| 4089 | store: None, |
| 4090 | follower_stop: follower_stop.clone(), |
| 4091 | follower_tasks: crate::ltx_repl::TaskGroup::new(follower_stop), |
| 4092 | }, |
| 4093 | } |
| 4094 | } |
| 4095 | |
| 4096 | /// Creates an owner for a follower store without a runtime durability stack. |
| 4097 | /// |
| 4098 | /// The owner starts and retains the follower fragment collector. |
| 4099 | /// |
| 4100 | /// # Panics |
| 4101 | /// |
| 4102 | /// The function panics outside the asynchronous runtime. |
| 4103 | pub fn new_follower(follower: Arc<FollowerStore>) -> Self { |
| 4104 | let follower_stop = crate::ltx_repl::StopToken::new(); |
| 4105 | let follower_tasks = crate::ltx_repl::TaskGroup::new(follower_stop.clone()); |
| 4106 | spawn_fragment_gc(follower.clone(), follower_stop.clone(), &follower_tasks); |
| 4107 | Self { |
| 4108 | stack: None, |
| 4109 | follower_tasks: FollowerTaskOwner { |
| 4110 | store: Some(follower), |
| 4111 | follower_stop, |
| 4112 | follower_tasks, |
| 4113 | }, |
| 4114 | } |
| 4115 | } |
| 4116 | |
| 4117 | /// Starts the background tasks for a runtime durability stack. |
| 4118 | /// |
| 4119 | /// The optional follower store adds the follower fragment collector. |
| 4120 | /// |
| 4121 | /// # Panics |
| 4122 | /// |
| 4123 | /// The function panics for a follower-only owner or outside the asynchronous |
| 4124 | /// runtime. It also panics while node-log roots are active or when a |
| 4125 | /// follower store is already installed. |
| 4126 | pub fn start_background(&mut self, follower: Option<Arc<FollowerStore>>) { |
| 4127 | let stack = self |
| 4128 | .stack |
| 4129 | .as_ref() |
| 4130 | .expect("the durability stack must be installed"); |
| 4131 | assert!( |
| 4132 | stack.node_log_tasks.roots.is_empty(), |
| 4133 | "node-log background tasks were already started" |
| 4134 | ); |
| 4135 | if stack.fleet { |
| 4136 | spawn_maintenance( |
| 4137 | stack.manager.clone(), |
| 4138 | stack.node_log_tasks.stop.clone(), |
| 4139 | &stack.node_log_tasks.roots, |
| 4140 | ); |
| 4141 | } |
| 4142 | if let Some(follower) = follower { |
| 4143 | assert!( |
| 4144 | self.follower_tasks.store.is_none(), |
| 4145 | "follower background tasks were already started" |
| 4146 | ); |
| 4147 | self.follower_tasks.store = Some(follower.clone()); |
| 4148 | spawn_fragment_gc( |
| 4149 | follower, |
| 4150 | self.follower_tasks.follower_stop.clone(), |
| 4151 | &self.follower_tasks.follower_tasks, |
| 4152 | ); |
| 4153 | } |
| 4154 | } |
| 4155 | |
| 4156 | /// Stops the node-log roots, seals covered data, and joins the roots. |
| 4157 | /// |
| 4158 | /// This method has no deadline. Use [`Self::quiesce_and_seal_within`] during |
| 4159 | /// a bounded process shutdown. |
| 4160 | pub async fn quiesce_and_seal(&mut self) { |
| 4161 | let Some(stack) = &self.stack else { |
| 4162 | return; |
| 4163 | }; |
| 4164 | stack.node_log_tasks.stop.request_stop(); |
| 4165 | stack.manager.close_gracefully().await; |
| 4166 | stack.node_log_tasks.roots.join().await; |
| 4167 | } |
| 4168 | |
| 4169 | /// Quiesces the durability stack within the specified remaining time. |
| 4170 | /// |
| 4171 | /// The method returns `true` after a complete quiesce. It runs the local |
| 4172 | /// fallback and returns `false` after a timeout. |
| 4173 | #[must_use] |
| 4174 | pub async fn quiesce_and_seal_within(&mut self, remaining: std::time::Duration) -> bool { |
| 4175 | if crate::asyncrt::timeout(remaining, self.quiesce_and_seal()) |
| 4176 | .await |
| 4177 | .is_ok() |
| 4178 | { |
| 4179 | true |
| 4180 | } else { |
| 4181 | // Cancellation can drop a join while it holds an admitted task |
| 4182 | // handle. Publish the local stop state immediately, so no task or |
| 4183 | // registration can recreate a durability resource after the |
| 4184 | // process deadline. The process exits without requiring a join. |
| 4185 | self.stop_local_now(); |
| 4186 | false |
| 4187 | } |
| 4188 | } |
| 4189 | |
| 4190 | /// Stops local admission and joins all admitted durability tasks. |
| 4191 | /// |
| 4192 | /// The caller must await this method to prove that all tasks completed and |
| 4193 | /// all registered managed replicas are closed. The caller must first stop |
| 4194 | /// and join the runtime operations that can open a replica. This method has |
| 4195 | /// no deadline. Use [`Self::shutdown_local_within`] during a bounded process |
| 4196 | /// shutdown. |
| 4197 | pub async fn shutdown_local(&mut self) { |
| 4198 | self.follower_tasks.follower_stop.request_stop(); |
| 4199 | if let Some(stack) = &mut self.stack { |
| 4200 | stack.node_log_tasks.stop.request_stop(); |
| 4201 | if let Some(tasks) = &stack.ltx_tasks { |
| 4202 | tasks.request_stop(); |
| 4203 | } |
| 4204 | stack.registration.take(); |
| 4205 | stack.manager.shutdown_local_fallback(); |
| 4206 | stack.ltx.shutdown_local_fallback(); |
| 4207 | stack.node_log_tasks.roots.join().await; |
| 4208 | if let Some(tasks) = &stack.ltx_tasks { |
| 4209 | tasks.join().await; |
| 4210 | } |
| 4211 | // Keep the owner installed until its join completes. A deadline |
| 4212 | // can cancel this future while one handle is claimed, and the |
| 4213 | // task group returns that handle for a later shutdown attempt. |
| 4214 | stack.ltx_tasks.take(); |
| 4215 | stack.node_log_tasks.children.join().await; |
| 4216 | // A direct durability pass is not in an owned task group and can |
| 4217 | // still hold a replica mutex. Every admitted release close has |
| 4218 | // joined now. Snapshot the remaining registered replicas, run the |
| 4219 | // close loop off the executor, and retain its handle before await. |
| 4220 | if stack.replica_close_task.is_none() { |
| 4221 | stack.replica_close_task = stack.ltx.start_close_local_replicas(); |
| 4222 | } |
| 4223 | if let Some(close) = &mut stack.replica_close_task { |
| 4224 | if let Err(error) = close.await { |
| 4225 | warn!(%error, "managed replica close task stopped with an error"); |
| 4226 | } |
| 4227 | } |
| 4228 | stack.replica_close_task.take(); |
| 4229 | } |
| 4230 | self.follower_tasks.follower_tasks.join().await; |
| 4231 | self.follower_tasks.store.take(); |
| 4232 | } |
| 4233 | |
| 4234 | /// Stops local admission and joins tasks within the specified remaining time. |
| 4235 | /// |
| 4236 | /// The method returns `true` after all admitted tasks complete and all |
| 4237 | /// registered managed replicas are closed. The caller must first stop and |
| 4238 | /// join the runtime operations that can open a replica. It runs the local |
| 4239 | /// fallback and returns `false` after a timeout. |
| 4240 | #[must_use] |
| 4241 | pub async fn shutdown_local_within(&mut self, remaining: std::time::Duration) -> bool { |
| 4242 | if crate::asyncrt::timeout(remaining, self.shutdown_local()) |
| 4243 | .await |
| 4244 | .is_ok() |
| 4245 | { |
| 4246 | true |
| 4247 | } else { |
| 4248 | // A cancelled group join returns its claimed handle, and the owner |
| 4249 | // retains every admitted release close plus the final snapshot |
| 4250 | // close. Publish fallback without taking a replica mutex, so a |
| 4251 | // blocked capture cannot extend the process deadline a second time. |
| 4252 | self.stop_local_now(); |
| 4253 | false |
| 4254 | } |
| 4255 | } |
| 4256 | |
| 4257 | /// Stops local admission and breaks component cycles without waiting. |
| 4258 | /// |
| 4259 | /// The daemon uses this fallback after its shutdown deadline. A completed |
| 4260 | /// [`Self::shutdown_local`] call proves that all admitted tasks completed |
| 4261 | /// and all registered managed replicas are closed. A `true` result from |
| 4262 | /// [`Self::shutdown_local_within`] gives the same proof. |
| 4263 | pub fn stop_local_now(&mut self) { |
| 4264 | self.shutdown_local_fallback(); |
| 4265 | } |
| 4266 | |
| 4267 | fn shutdown_local_fallback(&mut self) { |
| 4268 | self.follower_tasks.follower_stop.request_stop(); |
| 4269 | self.follower_tasks.store.take(); |
| 4270 | if let Some(stack) = &mut self.stack { |
| 4271 | stack.node_log_tasks.stop.request_stop(); |
| 4272 | stack.registration.take(); |
| 4273 | stack.manager.shutdown_local_fallback(); |
| 4274 | stack.ltx.shutdown_local_fallback(); |
| 4275 | } |
| 4276 | } |
| 4277 | } |
| 4278 | |
| 4279 | impl Drop for DurabilityOwner { |
| 4280 | fn drop(&mut self) { |
| 4281 | self.shutdown_local_fallback(); |
| 4282 | } |
| 4283 | } |
| 4284 | |
| 4285 | impl crate::ltx_repl::Shipper for NodeLogManager { |
| 4286 | fn ship( |
| 4287 | &self, |
| 4288 | batch: Vec<ShipEntry>, |
| 4289 | covered_seq: u64, |
| 4290 | ) -> std::pin::Pin< |
| 4291 | Box<dyn std::future::Future<Output = crate::ltx_repl::ShipCompletion> + Send + 'static>, |
| 4292 | > { |
| 4293 | let epoch = self.epoch(); |
| 4294 | self.ship_at_epoch(epoch, batch, covered_seq) |
| 4295 | } |
| 4296 | |
| 4297 | fn ship_at_epoch( |
| 4298 | &self, |
| 4299 | expected_epoch: u64, |
| 4300 | batch: Vec<ShipEntry>, |
| 4301 | covered_seq: u64, |
| 4302 | ) -> std::pin::Pin< |
| 4303 | Box<dyn std::future::Future<Output = crate::ltx_repl::ShipCompletion> + Send + 'static>, |
| 4304 | > { |
| 4305 | // Select the delegate and reserve its round under the same manager |
| 4306 | // lock that maintenance uses to replace it. A capture that finishes |
| 4307 | // after an epoch swap cannot reach the new followers with the old |
| 4308 | // epoch's truncation watermark. |
| 4309 | let round = self |
| 4310 | .inner |
| 4311 | .lock() |
| 4312 | .unwrap() |
| 4313 | .as_ref() |
| 4314 | .filter(|shipper| shipper.epoch == expected_epoch) |
| 4315 | .map(|shipper| shipper.ship_batch(batch, covered_seq)); |
| 4316 | let suspect_self = self.suspect_self.clone(); |
| 4317 | Box::pin(async move { |
| 4318 | let shipped = match round { |
| 4319 | Some(round) => round.await, |
| 4320 | None => crate::ltx_repl::ShipCompletion::unreserved(None), |
| 4321 | }; |
| 4322 | if shipped.last_seq().is_some() { |
| 4323 | suspect_self.store(false, Ordering::SeqCst); |
| 4324 | } |
| 4325 | shipped |
| 4326 | }) |
| 4327 | } |
| 4328 | |
| 4329 | fn pipeline(&self) -> usize { |
| 4330 | self.inner |
| 4331 | .lock() |
| 4332 | .unwrap() |
| 4333 | .as_ref() |
| 4334 | .map_or(1, |shipper| shipper.pipeline) |
| 4335 | } |
| 4336 | |
| 4337 | fn active(&self) -> bool { |
| 4338 | self.inner |
| 4339 | .lock() |
| 4340 | .unwrap() |
| 4341 | .as_ref() |
| 4342 | .is_some_and(|shipper| shipper.is_active()) |
| 4343 | } |
| 4344 | |
| 4345 | fn epoch(&self) -> u64 { |
| 4346 | self.inner |
| 4347 | .lock() |
| 4348 | .unwrap() |
| 4349 | .as_ref() |
| 4350 | .map_or(0, |shipper| shipper.epoch) |
| 4351 | } |
| 4352 | |
| 4353 | fn admit(&self) -> bool { |
| 4354 | self.inner |
| 4355 | .lock() |
| 4356 | .unwrap() |
| 4357 | .as_ref() |
| 4358 | .is_none_or(|shipper| shipper.stream.as_ref().is_none_or(|stream| stream.admit())) |
| 4359 | } |
| 4360 | } |
| 4361 | |
| 4362 | impl NodeLogManager { |
| 4363 | #[cfg(all(test, celld_internal_tests))] |
| 4364 | pub fn reset_shipper_injection_calls_for_world(&self) { |
| 4365 | self.shipper_injection_calls.store(0, Ordering::SeqCst); |
| 4366 | } |
| 4367 | |
| 4368 | #[cfg(all(test, celld_internal_tests))] |
| 4369 | pub fn shipper_injection_calls_for_world(&self) -> u64 { |
| 4370 | self.shipper_injection_calls.load(Ordering::SeqCst) |
| 4371 | } |
| 4372 | |
| 4373 | /// `session` is the process's full log identity, `<node>/<generation>`, |
| 4374 | /// with the generation taken from the node lease record. |
| 4375 | pub fn new( |
| 4376 | session: &str, |
| 4377 | bucket: Arc<Bucket>, |
| 4378 | own_log: Arc<OwnLog>, |
| 4379 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 4380 | auth: Arc<PeerAuth>, |
| 4381 | policy: celld_logic::log_evict::EvictionPolicy, |
| 4382 | ) -> Self { |
| 4383 | Self::new_with_log_transport( |
| 4384 | session, |
| 4385 | bucket, |
| 4386 | own_log, |
| 4387 | ltx, |
| 4388 | Arc::new(SignedPeerTransport::new(auth)), |
| 4389 | policy, |
| 4390 | ) |
| 4391 | } |
| 4392 | |
| 4393 | #[cfg(all(test, celld_internal_tests))] |
| 4394 | pub(crate) fn new_with_transport( |
| 4395 | session: &str, |
| 4396 | bucket: Arc<Bucket>, |
| 4397 | own_log: Arc<OwnLog>, |
| 4398 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 4399 | transport: Arc<dyn LogTransport>, |
| 4400 | policy: celld_logic::log_evict::EvictionPolicy, |
| 4401 | ) -> Self { |
| 4402 | Self::new_with_log_transport(session, bucket, own_log, ltx, transport, policy) |
| 4403 | } |
| 4404 | |
| 4405 | fn new_with_log_transport( |
| 4406 | session: &str, |
| 4407 | bucket: Arc<Bucket>, |
| 4408 | own_log: Arc<OwnLog>, |
| 4409 | ltx: Arc<crate::ltx_repl::LtxRepl>, |
| 4410 | transport: Arc<dyn LogTransport>, |
| 4411 | policy: celld_logic::log_evict::EvictionPolicy, |
| 4412 | ) -> Self { |
| 4413 | let ownership = own_log.ownership.clone(); |
| 4414 | let live_log = Arc::new(LiveLogTransitions::new(own_log)); |
| 4415 | let task_stop = crate::ltx_repl::StopToken::new(); |
| 4416 | let child_tasks = crate::ltx_repl::TaskGroup::new(task_stop.clone()); |
| 4417 | Self { |
| 4418 | node: session.split('/').next().unwrap_or(session).to_string(), |
| 4419 | session: session.to_string(), |
| 4420 | live_log, |
| 4421 | bucket, |
| 4422 | ownership, |
| 4423 | ltx, |
| 4424 | transport, |
| 4425 | inner: Mutex::new(None), |
| 4426 | bundle_seq: std::sync::atomic::AtomicU64::new(0), |
| 4427 | bundle_index: Mutex::new(BundleIndex::default()), |
| 4428 | bundle_gc_cursor: tokio::sync::Mutex::new(None), |
| 4429 | bundle_cache: tokio::sync::Mutex::new(None), |
| 4430 | health: Arc::new(Mutex::new(celld_logic::log_evict::FollowerHealth::default())), |
| 4431 | policy: Arc::new(policy), |
| 4432 | suspect_self: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 4433 | shortfall_logged_ms: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 4434 | closing: std::sync::atomic::AtomicBool::new(false), |
| 4435 | flush_in_flight: std::sync::atomic::AtomicBool::new(false), |
| 4436 | #[cfg(all(test, celld_internal_tests))] |
| 4437 | close_transition_pause: Mutex::new(None), |
| 4438 | #[cfg(all(test, celld_internal_tests))] |
| 4439 | maintenance_install_pause: Mutex::new(None), |
| 4440 | #[cfg(all(test, celld_internal_tests))] |
| 4441 | maintenance_publish_pause: Mutex::new(None), |
| 4442 | #[cfg(all(test, celld_internal_tests))] |
| 4443 | shipper_injection_calls: std::sync::atomic::AtomicU64::new(0), |
| 4444 | #[cfg(all(test, celld_internal_tests))] |
| 4445 | recovery_gather_window_bytes: std::sync::atomic::AtomicU64::new( |
| 4446 | RECOVERY_GATHER_WINDOW_BYTES, |
| 4447 | ), |
| 4448 | #[cfg(all(test, celld_internal_tests))] |
| 4449 | recovery_gather_peak_bytes: std::sync::atomic::AtomicU64::new(0), |
| 4450 | predecessors_clean: std::sync::atomic::AtomicBool::new(false), |
| 4451 | recovery_locks: Mutex::new(BTreeMap::new()), |
| 4452 | gc_confirmed_empty: Mutex::new(std::collections::HashSet::new()), |
| 4453 | declared_bundle_losses: Mutex::new(BTreeSet::new()), |
| 4454 | task_stop, |
| 4455 | child_tasks, |
| 4456 | } |
| 4457 | } |
| 4458 | |
| 4459 | /// Recover the predecessor session's log, read from this NODE's own |
| 4460 | /// lease record: until our install replaces it, the record carries the |
| 4461 | /// predecessor's generation and folded state, and recovery-before- |
| 4462 | /// install is the invariant that lets a successor write log: None. |
| 4463 | /// DONE-ONCE per process: after one clean pass the latch holds — a |
| 4464 | /// predecessor state can only reappear if another process supersedes |
| 4465 | /// our lease, and then we are fenced regardless. The latch sets only |
| 4466 | /// on success; a failed pass retries on the next cold path. |
| 4467 | async fn ensure_predecessors_recovered(&self) -> anyhow::Result<()> { |
| 4468 | if self.predecessors_clean.load(Ordering::SeqCst) { |
| 4469 | return Ok(()); |
| 4470 | } |
| 4471 | if let Some(folded) = read_record(&self.bucket, &self.node).await? { |
| 4472 | let session = format!("{}/{}", self.node, folded.wire.generation); |
| 4473 | if session != self.session |
| 4474 | && log_tier::takeover_gate(Some(&folded.record)) |
| 4475 | == log_tier::TakeoverGate::RecoverFirst |
| 4476 | { |
| 4477 | info!(session, "recovering a predecessor session's node log"); |
| 4478 | self.recover_as(&session, RecoverMode::Boot).await?; |
| 4479 | } |
| 4480 | } |
| 4481 | // The install about to follow erases the record's only pointer to |
| 4482 | // the predecessor generation, and no GC path can rediscover a |
| 4483 | // sealed subtree with no pointer: the boot is |
| 4484 | // the one moment that knows every stale generation, so it sweeps |
| 4485 | // them here. Non-fatal — the leak is storage cost, not safety, |
| 4486 | // and the next restart retries. |
| 4487 | if let Err(error) = self.gc_stale_generation_bundles().await { |
| 4488 | warn!(%error, "stale-generation bundle GC failed; retried at the next restart"); |
| 4489 | } |
| 4490 | self.predecessors_clean.store(true, Ordering::SeqCst); |
| 4491 | Ok(()) |
| 4492 | } |
| 4493 | |
| 4494 | /// Delete every bundle and recovery checkpoint under this node from a |
| 4495 | /// generation other than the running session's. Recovery-before- |
| 4496 | /// install has already sealed the predecessor by the time this runs, |
| 4497 | /// and a sealed session's bundles are garbage (recovery folded every |
| 4498 | /// acked row per-cell first). Its recovery checkpoints are obsolete too. |
| 4499 | /// Loss declarations and all other keys stay untouched. |
| 4500 | async fn gc_stale_generation_bundles(&self) -> anyhow::Result<()> { |
| 4501 | let prefix = format!("log/{}/", self.node); |
| 4502 | let mut stale: Vec<String> = Vec::new(); |
| 4503 | for meta in self.bucket.list(&prefix).await? { |
| 4504 | let key = meta.location.as_ref().to_string(); |
| 4505 | let Some(rest) = key.strip_prefix(&prefix) else { |
| 4506 | continue; |
| 4507 | }; |
| 4508 | let Some((generation, tail)) = rest.split_once('/') else { |
| 4509 | continue; |
| 4510 | }; |
| 4511 | if !tail.starts_with("bundle/") && !tail.starts_with("recovered/") { |
| 4512 | continue; |
| 4513 | } |
| 4514 | if format!("{}/{generation}", self.node) == self.session { |
| 4515 | continue; |
| 4516 | } |
| 4517 | stale.push(key); |
| 4518 | } |
| 4519 | if stale.is_empty() { |
| 4520 | return Ok(()); |
| 4521 | } |
| 4522 | let count = stale.len(); |
| 4523 | let gone = self.bucket.delete_many(&stale).await; |
| 4524 | if gone.len() != count { |
| 4525 | anyhow::bail!( |
| 4526 | "{} of {count} stale-generation recovery objects survived the delete", |
| 4527 | count - gone.len() |
| 4528 | ); |
| 4529 | } |
| 4530 | info!( |
| 4531 | objects = count, |
| 4532 | "stale predecessor generations' recovery objects retired" |
| 4533 | ); |
| 4534 | Ok(()) |
| 4535 | } |
| 4536 | |
| 4537 | /// The fast eviction watch, one poll: any member the policy says to |
| 4538 | /// evict degrades the shipper now (acks fall to the bucket, which is |
| 4539 | /// always safe) and joins the quarantine; the caller runs `maintain` |
| 4540 | /// immediately so the swap costs detection plus flush plus CAS, not a |
| 4541 | /// maintenance tick. Returns whether anything was evicted. |
| 4542 | pub fn evict_gray_followers(&self) -> bool { |
| 4543 | let inner = self.inner.lock().unwrap().clone(); |
| 4544 | let Some(shipper) = inner else { return false }; |
| 4545 | if !shipper.is_active() { |
| 4546 | return false; |
| 4547 | } |
| 4548 | let now = mono_ms(); |
| 4549 | let members: Vec<String> = shipper |
| 4550 | .members |
| 4551 | .iter() |
| 4552 | .map(|member| member.node.clone()) |
| 4553 | .collect(); |
| 4554 | let mut health = self.health.lock().unwrap(); |
| 4555 | // Every member stuck at once is OUR fault, not theirs: degrade |
| 4556 | // without quarantining anyone, so the pool is intact the moment |
| 4557 | // connectivity returns. |
| 4558 | if health.correlated_stall(&self.policy, &members, now) { |
| 4559 | drop(health); |
| 4560 | self.suspect_self.store(true, Ordering::SeqCst); |
| 4561 | shipper.degrade("correlated member stall; suspecting ourselves"); |
| 4562 | return true; |
| 4563 | } |
| 4564 | if !health.swap_allowed(&self.policy, now) { |
| 4565 | return false; |
| 4566 | } |
| 4567 | for member in &members { |
| 4568 | if health.verdict(&self.policy, member, &members, now) |
| 4569 | == celld_logic::log_evict::Verdict::Evict |
| 4570 | { |
| 4571 | // The evidence is a second, idempotent read of the same |
| 4572 | // ledger at the same instant: the eviction path is rare, |
| 4573 | // and the decision entry stays the one the DST drives. |
| 4574 | let (_, detail) = health.verdict_detailed(&self.policy, member, &members, now); |
| 4575 | health.evicted(&self.policy, member, now); |
| 4576 | drop(health); |
| 4577 | // The evidence, not just the sentence: which rule, and the |
| 4578 | // numbers it saw. Reconstructing this after the fact from |
| 4579 | // completed appends is impossible for the backstop, whose |
| 4580 | // evidence is the append that never completed. |
| 4581 | warn!( |
| 4582 | event = "log_evict_verdict", |
| 4583 | member, |
| 4584 | rule = detail.rule, |
| 4585 | outstanding_ms = detail.outstanding_ms, |
| 4586 | own_median_ms = detail.own_median_ms, |
| 4587 | samples = detail.samples, |
| 4588 | sibling_median_ms = detail.sibling_median_ms, |
| 4589 | threshold_ms = detail.threshold_ms, |
| 4590 | suspect_ms = detail.suspect_ms, |
| 4591 | backstop_ms = self.policy.backstop_ms, |
| 4592 | budget_ms = self.policy.budget_ms, |
| 4593 | "gray follower evicted" |
| 4594 | ); |
| 4595 | shipper.degrade(&format!("gray follower {member} evicted")); |
| 4596 | return true; |
| 4597 | } |
| 4598 | } |
| 4599 | false |
| 4600 | } |
| 4601 | |
| 4602 | /// Idle disk probes: an empty append still persists (and fsyncs) the |
| 4603 | /// follower's state file, so a quiet fleet finds a dying follower disk |
| 4604 | /// before load does. One owned probe runs per quiet member per interval. |
| 4605 | /// A hanging probe marks the member outstanding and the backstop acts. |
| 4606 | pub fn probe_followers(self: &Arc<Self>) { |
| 4607 | const PROBE_QUIET_MS: u64 = 2_000; |
| 4608 | let inner = self.inner.lock().unwrap().clone(); |
| 4609 | let Some(shipper) = inner else { return }; |
| 4610 | // Probes run DEGRADED too — a degraded shipper is exactly when |
| 4611 | // connectivity evidence matters: the probe's signed 200 is what |
| 4612 | // lifts self-suspicion after a partition heals, and gating probes |
| 4613 | // on health once parked recruitment forever. |
| 4614 | let now = mono_ms(); |
| 4615 | for member in &shipper.members { |
| 4616 | if !self |
| 4617 | .health |
| 4618 | .lock() |
| 4619 | .unwrap() |
| 4620 | .probe_due(&member.node, now, PROBE_QUIET_MS) |
| 4621 | { |
| 4622 | continue; |
| 4623 | } |
| 4624 | let shipper = shipper.clone(); |
| 4625 | let node = member.node.clone(); |
| 4626 | let health = self.health.clone(); |
| 4627 | let suspect_self = self.suspect_self.clone(); |
| 4628 | let stop = self.task_stop.clone(); |
| 4629 | self.child_tasks |
| 4630 | .spawn_owned("node_log_follower_probe", async move { |
| 4631 | let member = shipper |
| 4632 | .members |
| 4633 | .iter() |
| 4634 | .find(|member| member.node == node) |
| 4635 | .expect("probed member is in the ensemble"); |
| 4636 | let req = AppendReq { |
| 4637 | leader: shipper.node.clone(), |
| 4638 | epoch: shipper.epoch, |
| 4639 | truncate_to: 0, |
| 4640 | entries: Vec::new(), |
| 4641 | }; |
| 4642 | let started = mono_ms(); |
| 4643 | health.lock().unwrap().append_started(&node, started); |
| 4644 | let outcome = crate::asyncrt::select_biased! { |
| 4645 | "a stop signal that ties a probe response prevents recording stale health"; |
| 4646 | _ = stop.stopped() => return, |
| 4647 | outcome = shipper.post_append(member, &req) => outcome, |
| 4648 | }; |
| 4649 | let done = mono_ms(); |
| 4650 | health.lock().unwrap().append_completed( |
| 4651 | &node, |
| 4652 | done, |
| 4653 | done.saturating_sub(started), |
| 4654 | ); |
| 4655 | // ANY well-formed peer response — even an append refusal, |
| 4656 | // which is still a signed HTTP 200 — proves connectivity |
| 4657 | // and lifts self-suspicion. An incapable answer proves |
| 4658 | // the peer is the wrong binary, not that we are cut off, |
| 4659 | // and it quarantines here exactly as a shipped batch |
| 4660 | // would — an idle ensemble must not keep a 0.2.x member |
| 4661 | // recruit-eligible just because no writes arrive. |
| 4662 | match outcome { |
| 4663 | AppendSend::Answered(_) => { |
| 4664 | suspect_self.store(false, Ordering::SeqCst); |
| 4665 | } |
| 4666 | AppendSend::Incapable(error) => { |
| 4667 | warn!( |
| 4668 | member = node, |
| 4669 | %error, |
| 4670 | "follower cannot serve log appends; quarantined from recruitment" |
| 4671 | ); |
| 4672 | health |
| 4673 | .lock() |
| 4674 | .unwrap() |
| 4675 | .append_incapable(&shipper.policy, &node, done); |
| 4676 | } |
| 4677 | AppendSend::Failed(_) => {} |
| 4678 | } |
| 4679 | }); |
| 4680 | } |
| 4681 | } |
| 4682 | |
| 4683 | async fn post<Req: serde::Serialize, Resp: serde::de::DeserializeOwned>( |
| 4684 | &self, |
| 4685 | node: &str, |
| 4686 | addr: &str, |
| 4687 | path: &str, |
| 4688 | req: &Req, |
| 4689 | ) -> anyhow::Result<Resp> { |
| 4690 | let bytes = self |
| 4691 | .transport |
| 4692 | .post(node, addr, path, serde_json::to_vec(req)?, None) |
| 4693 | .await?; |
| 4694 | Ok(serde_json::from_slice(&bytes)?) |
| 4695 | } |
| 4696 | |
| 4697 | /// The tail POST: a JSON request, a binary response (the entries |
| 4698 | /// dominate it). |
| 4699 | async fn post_tail(&self, node: &str, addr: &str, req: &TailReq) -> anyhow::Result<TailReply> { |
| 4700 | let bytes = self |
| 4701 | .transport |
| 4702 | .post( |
| 4703 | node, |
| 4704 | addr, |
| 4705 | "/peer/log/tail", |
| 4706 | serde_json::to_vec(&TailWireReq::ranged(req.clone()))?, |
| 4707 | None, |
| 4708 | ) |
| 4709 | .await?; |
| 4710 | decode_tail_resp(&bytes) |
| 4711 | } |
| 4712 | |
| 4713 | /// Node-log recovery, the model's StartRecovery/SealFollower/ |
| 4714 | /// FinishRecovery in one pass: fence via CAS, seal every reachable |
| 4715 | /// member, gather their tails, require one matching member to return its |
| 4716 | /// complete retained range, upload each entry to the exact per-cell key |
| 4717 | /// the dead leader would have used, and CAS the record sealed. Every step |
| 4718 | /// is a CAS or an idempotent PUT, so racing recoverers re-run harmlessly. |
| 4719 | /// Upload gathered rows into the per-cell layout: grouped per |
| 4720 | /// (cell, epoch), each group's contiguous tail merged into ONE L0 |
| 4721 | /// segment (per-row fallback for non-contiguous chains), skipping |
| 4722 | /// rows the per-cell watermark already covers. Shared by recovery's |
| 4723 | /// gather and the reopen healing pass. Any failure propagates — |
| 4724 | /// callers must not seal past an incomplete fold. A recovery passes |
| 4725 | /// its claim and its progress record, which carries the watermarks |
| 4726 | /// from one gather window to the next. |
| 4727 | async fn upload_gathered( |
| 4728 | &self, |
| 4729 | gathered: BTreeMap<(String, u64, u64), Vec<u8>>, |
| 4730 | mut claim: Option<(&str, &mut ClaimBeat, &mut recovery_progress::Progress)>, |
| 4731 | ) -> anyhow::Result<usize> { |
| 4732 | if gathered.is_empty() { |
| 4733 | return Ok(0); |
| 4734 | } |
| 4735 | type CellRows = Vec<(u64, Vec<u8>)>; |
| 4736 | let mut groups: BTreeMap<(String, u64), CellRows> = BTreeMap::new(); |
| 4737 | for ((cell, cell_epoch, txid), bytes) in gathered { |
| 4738 | groups |
| 4739 | .entry((cell, cell_epoch)) |
| 4740 | .or_default() |
| 4741 | .push((txid, bytes)); |
| 4742 | } |
| 4743 | if let Some((_, _, progress)) = claim.as_ref() { |
| 4744 | groups.retain(|(cell, epoch), rows| { |
| 4745 | if let Some(through) = progress.through(cell, *epoch) { |
| 4746 | rows.retain(|(txid, _)| *txid > through); |
| 4747 | } |
| 4748 | !rows.is_empty() |
| 4749 | }); |
| 4750 | } |
| 4751 | let uploads = groups.into_iter().map(|((cell, cell_epoch), rows)| { |
| 4752 | let ltx = self.ltx.clone(); |
| 4753 | async move { |
| 4754 | let through = rows.last().expect("a gathered cell has at least one row").0; |
| 4755 | let watermark = ltx.covered_txid(&cell, cell_epoch).await; |
| 4756 | let rows: Vec<(u64, Vec<u8>)> = rows |
| 4757 | .into_iter() |
| 4758 | .filter(|(txid, _)| *txid > watermark) |
| 4759 | .collect(); |
| 4760 | if rows.is_empty() { |
| 4761 | return anyhow::Ok((recovery_progress::CoveredCell { cell, epoch: cell_epoch, through }, 0_usize)); |
| 4762 | } |
| 4763 | let uploaded = rows.len(); |
| 4764 | let puts: Vec<(u64, u64, Vec<u8>)> = |
| 4765 | match crate::ltx_repl::LtxRepl::merge_l0_rows(&rows) { |
| 4766 | Some(merged) => { |
| 4767 | vec![(rows[0].0, rows[uploaded - 1].0, merged)] |
| 4768 | } |
| 4769 | None => rows |
| 4770 | .into_iter() |
| 4771 | .map(|(txid, bytes)| (txid, txid, bytes)) |
| 4772 | .collect(), |
| 4773 | }; |
| 4774 | for (min_txid, max_txid, bytes) in puts { |
| 4775 | // Racing recoverers PUT the same idempotent keys, and |
| 4776 | // the object store answers the collision with a |
| 4777 | // retryable refusal, not corruption — one recoverer |
| 4778 | // backing off is all it takes to converge. |
| 4779 | let mut attempt = 0_u32; |
| 4780 | loop { |
| 4781 | match ltx |
| 4782 | .upload_raw_l0(&cell, cell_epoch, min_txid, max_txid, &bytes) |
| 4783 | .await |
| 4784 | { |
| 4785 | Ok(()) => break, |
| 4786 | Err(error) if attempt < 4 => { |
| 4787 | attempt += 1; |
| 4788 | let jitter = (min_txid.wrapping_mul(2654435761) >> 27) % 97; |
| 4789 | let wait = 150_u64 * (1 << attempt) + jitter; |
| 4790 | warn!(%error, cell, min_txid, attempt, "recovery upload refused; backing off"); |
| 4791 | crate::asyncrt::sleep(std::time::Duration::from_millis(wait)).await; |
| 4792 | } |
| 4793 | Err(error) => { |
| 4794 | return Err(error).with_context(|| { |
| 4795 | format!( |
| 4796 | "recovery upload {cell} e{cell_epoch} \ |
| 4797 | t{min_txid}-{max_txid}" |
| 4798 | ) |
| 4799 | }); |
| 4800 | } |
| 4801 | } |
| 4802 | } |
| 4803 | } |
| 4804 | anyhow::Ok((recovery_progress::CoveredCell { cell, epoch: cell_epoch, through }, uploaded)) |
| 4805 | } |
| 4806 | }); |
| 4807 | let mut count = 0_usize; |
| 4808 | let mut uploads = |
| 4809 | futures_util::stream::iter(uploads).buffer_unordered(RECOVERY_UPLOAD_CONCURRENCY); |
| 4810 | while let Some(uploaded) = futures_util::StreamExt::next(&mut uploads).await { |
| 4811 | let (cell, uploaded) = uploaded?; |
| 4812 | count += uploaded; |
| 4813 | if let Some((dead, beat, progress)) = claim.as_mut() { |
| 4814 | progress.completed(&self.bucket, cell).await; |
| 4815 | self.beat_claim(dead, beat).await?; |
| 4816 | } |
| 4817 | } |
| 4818 | Ok(count) |
| 4819 | } |
| 4820 | |
| 4821 | /// Recover one dead SESSION's log: `dead` is `<node>/<generation>`. |
| 4822 | pub async fn recover(&self, dead: &str) -> anyhow::Result<()> { |
| 4823 | self.recover_as(dead, RecoverMode::Sweep).await |
| 4824 | } |
| 4825 | |
| 4826 | pub(crate) async fn recover_as(&self, dead: &str, mode: RecoverMode) -> anyhow::Result<()> { |
| 4827 | let recovery_lock = { |
| 4828 | let mut locks = self.recovery_locks.lock().unwrap(); |
| 4829 | locks.retain(|_, lock| lock.strong_count() > 0); |
| 4830 | match locks.get(dead).and_then(std::sync::Weak::upgrade) { |
| 4831 | Some(lock) => lock, |
| 4832 | None => { |
| 4833 | let lock = Arc::new(tokio::sync::Mutex::new(())); |
| 4834 | locks.insert(dead.to_string(), Arc::downgrade(&lock)); |
| 4835 | lock |
| 4836 | } |
| 4837 | } |
| 4838 | }; |
| 4839 | // A sweep that finds this process already recovering the session, |
| 4840 | // for a boot or a cold route, has nothing to add; waiting here held |
| 4841 | // the maintenance ticker for the length of the recovery. |
| 4842 | let _single_flight = match mode { |
| 4843 | RecoverMode::Boot => recovery_lock.lock().await, |
| 4844 | RecoverMode::Sweep => match recovery_lock.try_lock() { |
| 4845 | Ok(guard) => guard, |
| 4846 | Err(_) => { |
| 4847 | info!(dead, "this node is already recovering the log"); |
| 4848 | return Ok(()); |
| 4849 | } |
| 4850 | }, |
| 4851 | }; |
| 4852 | self.recover_serial(dead, mode).await |
| 4853 | } |
| 4854 | |
| 4855 | /// Refresh the claim's heartbeat once `RECOVERY_HEARTBEAT` has passed. |
| 4856 | /// An error means another node took the claim over because this one |
| 4857 | /// looked stale; the gather stops and the caller re-resolves. |
| 4858 | async fn beat_claim(&self, dead: &str, beat: &mut ClaimBeat) -> anyhow::Result<()> { |
| 4859 | if mono_ms().saturating_sub(beat.last_mono_ms) < RECOVERY_HEARTBEAT.as_millis() as u64 { |
| 4860 | return Ok(()); |
| 4861 | } |
| 4862 | let Some(folded) = read_record(&self.bucket, dead).await? else { |
| 4863 | return Ok(()); |
| 4864 | }; |
| 4865 | let now = crate::ownership_store::now_ms(); |
| 4866 | let Some(refreshed) = log_tier::refresh_recovery(&folded.record, &self.node, now) else { |
| 4867 | anyhow::bail!("node-log recovery for {dead} was taken over by another node"); |
| 4868 | }; |
| 4869 | // A lost CAS is a concurrent record write, not a lost claim; the |
| 4870 | // next beat re-reads and refreshes again. |
| 4871 | let _ = write_dead_record( |
| 4872 | &self.bucket, |
| 4873 | dead, |
| 4874 | &folded.wire, |
| 4875 | &refreshed, |
| 4876 | folded.may_have_fleet_acks, |
| 4877 | &folded.token, |
| 4878 | ) |
| 4879 | .await?; |
| 4880 | beat.last_mono_ms = mono_ms(); |
| 4881 | Ok(()) |
| 4882 | } |
| 4883 | |
| 4884 | async fn recover_serial(&self, dead: &str, mode: RecoverMode) -> anyhow::Result<()> { |
| 4885 | let stale_after_ms = RECOVERY_CLAIM_TTL.as_millis() as u64; |
| 4886 | for _attempt in 0..5 { |
| 4887 | let Some(folded) = read_record(&self.bucket, dead).await? else { |
| 4888 | return Ok(()); |
| 4889 | }; |
| 4890 | let FoldedRead { |
| 4891 | record, |
| 4892 | may_have_fleet_acks, |
| 4893 | token, |
| 4894 | wire, |
| 4895 | } = folded; |
| 4896 | // Re-judge deadness on the record actually being fenced: the |
| 4897 | // caller's verdict may be stale — an owner |
| 4898 | // can restart between the read that justified this call and |
| 4899 | // now, and the spec's RecoverLog is enabled only past expiry |
| 4900 | // AT the step. A live lease is an error, not a skip: the |
| 4901 | // caller's claim must refuse and re-resolve to routing. |
| 4902 | let now = crate::ownership_store::now_ms(); |
| 4903 | anyhow::ensure!( |
| 4904 | wire.expires_ms <= now, |
| 4905 | "refusing to fence {dead}: its lease is live again (expires in {}ms)", |
| 4906 | wire.expires_ms.saturating_sub(now) |
| 4907 | ); |
| 4908 | // No justification pin: the record is keyed by session, so a |
| 4909 | // revived process writes a NEW key and can never step this one. |
| 4910 | // The only concurrent writer is a rival recoverer, and every |
| 4911 | // recovery step is a CAS or an idempotent upload — a lost CAS |
| 4912 | // re-reads and converges on the rival's outcome. |
| 4913 | match record.state { |
| 4914 | LogState::Sealed => return Ok(()), |
| 4915 | LogState::Open => { |
| 4916 | let Some(recovering) = log_tier::start_recovery(&record, &self.node, now) |
| 4917 | else { |
| 4918 | continue; |
| 4919 | }; |
| 4920 | if write_dead_record( |
| 4921 | &self.bucket, |
| 4922 | dead, |
| 4923 | &wire, |
| 4924 | &recovering, |
| 4925 | may_have_fleet_acks, |
| 4926 | &token, |
| 4927 | ) |
| 4928 | .await? |
| 4929 | .is_none() |
| 4930 | { |
| 4931 | continue; // lost the CAS; re-read |
| 4932 | } |
| 4933 | } |
| 4934 | LogState::Recovering if log_tier::recovery_claimed_by(&record, &self.node) => {} |
| 4935 | LogState::Recovering |
| 4936 | if log_tier::recovery_claim_live(&record, now, stale_after_ms) => |
| 4937 | { |
| 4938 | // The Open -> Recovering CAS elects one reader, and its |
| 4939 | // heartbeat is the proof it is still reading. A sweep |
| 4940 | // leaves it alone. A boot cannot go on without the seal, |
| 4941 | // so it waits; the wait ends when the log seals or the |
| 4942 | // heartbeat goes stale, and the next pass takes over. |
| 4943 | let claimant = record.claimant.clone().unwrap_or_default(); |
| 4944 | if mode == RecoverMode::Sweep { |
| 4945 | info!(dead, claimant, "another node is recovering this log"); |
| 4946 | return Ok(()); |
| 4947 | } |
| 4948 | let waited_from = mono_ms(); |
| 4949 | let mut reported = waited_from; |
| 4950 | loop { |
| 4951 | crate::asyncrt::sleep(RECOVERY_CLAIM_POLL).await; |
| 4952 | let Some(current) = read_record(&self.bucket, dead).await? else { |
| 4953 | return Ok(()); |
| 4954 | }; |
| 4955 | let now = crate::ownership_store::now_ms(); |
| 4956 | if current.record.state == LogState::Sealed { |
| 4957 | return Ok(()); |
| 4958 | } |
| 4959 | if !log_tier::recovery_claim_live(¤t.record, now, stale_after_ms) { |
| 4960 | break; |
| 4961 | } |
| 4962 | if mono_ms().saturating_sub(reported) |
| 4963 | >= RECOVERY_WAIT_REPORT.as_millis() as u64 |
| 4964 | { |
| 4965 | reported = mono_ms(); |
| 4966 | info!( |
| 4967 | dead, |
| 4968 | claimant, |
| 4969 | waited_ms = mono_ms().saturating_sub(waited_from), |
| 4970 | "waiting behind another node's live recovery" |
| 4971 | ); |
| 4972 | } |
| 4973 | } |
| 4974 | continue; |
| 4975 | } |
| 4976 | LogState::Recovering => { |
| 4977 | let Some(taken) = |
| 4978 | log_tier::take_over_recovery(&record, &self.node, now, stale_after_ms) |
| 4979 | else { |
| 4980 | continue; |
| 4981 | }; |
| 4982 | warn!( |
| 4983 | dead, |
| 4984 | stale_claimant = record.claimant.as_deref().unwrap_or("none"), |
| 4985 | "taking over a stale recovery claim" |
| 4986 | ); |
| 4987 | if write_dead_record( |
| 4988 | &self.bucket, |
| 4989 | dead, |
| 4990 | &wire, |
| 4991 | &taken, |
| 4992 | may_have_fleet_acks, |
| 4993 | &token, |
| 4994 | ) |
| 4995 | .await? |
| 4996 | .is_none() |
| 4997 | { |
| 4998 | continue; // lost the CAS; re-read |
| 4999 | } |
| 5000 | } |
| 5001 | } |
| 5002 | let mut beat = ClaimBeat::new(); |
| 5003 | let Some(folded) = read_record(&self.bucket, dead).await? else { |
| 5004 | return Ok(()); |
| 5005 | }; |
| 5006 | let FoldedRead { |
| 5007 | record, |
| 5008 | may_have_fleet_acks, |
| 5009 | token: _, |
| 5010 | wire: _, |
| 5011 | } = folded; |
| 5012 | if record.state == LogState::Sealed { |
| 5013 | return Ok(()); |
| 5014 | } |
| 5015 | |
| 5016 | let now = crate::ownership_store::now_ms(); |
| 5017 | let pass_started = mono_ms(); |
| 5018 | let mut complete_witnesses = 0_usize; |
| 5019 | // A member is CONCLUSIVE when its fate is known: lease provably |
| 5020 | // expired and unreachable, reachable with a different fragment |
| 5021 | // epoch, or reachable with an explicitly incomplete retained |
| 5022 | // range. A failed tail or an old response without that range is |
| 5023 | // inconclusive. Only a fully conclusive, witness-free epoch with |
| 5024 | // possible fleet acknowledgements may declare bounded loss. |
| 5025 | let mut inconclusive = 0_usize; |
| 5026 | let mut gathered: BTreeMap<(String, u64, u64), Vec<u8>> = BTreeMap::new(); |
| 5027 | // "A blink is not death" applies to loss declaration too: a |
| 5028 | // member whose lease merely lapsed (a restart, a fleet-wide |
| 5029 | // power cycle) is NOT conclusively gone — its fsync'd fragments |
| 5030 | // boot back in seconds, and declaring loss against boot order |
| 5031 | // would discard acked writes sitting intact on disk — so a |
| 5032 | // 3x-TTL grace applies to MEMBER fate here, unrelated to the |
| 5033 | // sweep (which, under the fold, judges the record's own |
| 5034 | // published expiry with no grace). |
| 5035 | let grace_ms = (self.ownership.lease_ttl_ms() * 3).max(20_000); |
| 5036 | for member in &record.ensemble { |
| 5037 | self.beat_claim(dead, &mut beat).await?; |
| 5038 | let lease = self.ownership.read_node_lease(member).await; |
| 5039 | let lease_live = matches!(&lease, Ok(Some(lease)) if lease.expires_ms > now); |
| 5040 | let lease_long_dead = matches!( |
| 5041 | &lease, |
| 5042 | Ok(Some(lease)) if lease.expires_ms.saturating_add(grace_ms) < now |
| 5043 | ); |
| 5044 | let addr = match lease { |
| 5045 | Ok(Some(lease)) => Some(lease.addr), |
| 5046 | _ => None, |
| 5047 | }; |
| 5048 | let Some(addr) = addr else { |
| 5049 | if lease_live || !lease_long_dead { |
| 5050 | inconclusive += 1; |
| 5051 | } |
| 5052 | continue; |
| 5053 | }; |
| 5054 | let seal = SealReq { |
| 5055 | leader: dead.to_string(), |
| 5056 | epoch: record.epoch, |
| 5057 | }; |
| 5058 | let sealed = match self |
| 5059 | .post::<_, SealResp>(member, &addr, "/peer/log/seal", &seal) |
| 5060 | .await |
| 5061 | { |
| 5062 | Ok(sealed) => sealed, |
| 5063 | Err(error) => { |
| 5064 | // Startup serves follower requests before it renews |
| 5065 | // the lease. An HTTP error proves a response, not a |
| 5066 | // missing fragment: a transient scan failure on an |
| 5067 | // expired member must not seal away its intact rows. |
| 5068 | let answered = error.downcast_ref::<PeerHttpError>().is_some() |
| 5069 | || error.downcast_ref::<serde_json::Error>().is_some(); |
| 5070 | if answered || lease_live || !lease_long_dead { |
| 5071 | inconclusive += 1; |
| 5072 | } |
| 5073 | continue; |
| 5074 | } |
| 5075 | }; |
| 5076 | let held_fragment_epoch = |
| 5077 | sealed.held_fragment_epoch.unwrap_or(sealed.fragment_epoch); |
| 5078 | let tail = TailReq { |
| 5079 | leader: dead.to_string(), |
| 5080 | }; |
| 5081 | let mut tail = match self.post_tail(member, &addr, &tail).await { |
| 5082 | Ok(TailReply::Ranged(tail)) => tail, |
| 5083 | Ok(TailReply::Legacy { .. }) => { |
| 5084 | // A legacy body has no retained range, even when the |
| 5085 | // seal claims an empty or different fragment. Do not |
| 5086 | // turn missing evidence into conclusive amnesia through |
| 5087 | // the failed-read classifier below. |
| 5088 | inconclusive += 1; |
| 5089 | warn!( |
| 5090 | member, |
| 5091 | dead, |
| 5092 | epoch = record.epoch, |
| 5093 | "recovery received a legacy tail without range evidence" |
| 5094 | ); |
| 5095 | continue; |
| 5096 | } |
| 5097 | Err(error) => { |
| 5098 | // The seal answer and the fragment are TWO requests, |
| 5099 | // and only the second carries the data. Counting the |
| 5100 | // witness on the first let a fragment this pass never |
| 5101 | // read satisfy the certify guard: recovery sealed the |
| 5102 | // record as "the bucket is complete" while the acked |
| 5103 | // frames sat fsync'd on a member that had just |
| 5104 | // answered, and the fragment GC then deleted the last |
| 5105 | // copy. A member that sealed has a live disk, so its |
| 5106 | // fate is open, not conclusive — it joins the loud |
| 5107 | // retry instead. |
| 5108 | warn!( |
| 5109 | member, |
| 5110 | dead, |
| 5111 | epoch = record.epoch, |
| 5112 | %error, |
| 5113 | "recovery could not read a sealed member's tail" |
| 5114 | ); |
| 5115 | if held_fragment_epoch == record.epoch { |
| 5116 | inconclusive += 1; |
| 5117 | } |
| 5118 | continue; |
| 5119 | } |
| 5120 | }; |
| 5121 | tail.entries.sort_by_key(|entry| entry.seq); |
| 5122 | // A matching fragment epoch identifies the right fragment, |
| 5123 | // but it does not prove that every retained sequence is still |
| 5124 | // readable. The seal and tail responses must describe the same |
| 5125 | // range, and the ranged tail must certify its own complete read. |
| 5126 | // A legacy response was kept inconclusive above, so it cannot |
| 5127 | // certify recovery or declare loss. |
| 5128 | if held_fragment_epoch == record.epoch { |
| 5129 | match sealed.base { |
| 5130 | Some(base) |
| 5131 | if tail.range.fragment_epoch == held_fragment_epoch |
| 5132 | && tail.range.base == base |
| 5133 | && tail.range.end == sealed.end |
| 5134 | && tail.range.complete |
| 5135 | && sealed.fragment_epoch == held_fragment_epoch |
| 5136 | && tail_covers_sealed_range(base, sealed.end, &tail.entries) => |
| 5137 | { |
| 5138 | complete_witnesses += 1; |
| 5139 | } |
| 5140 | Some(base) |
| 5141 | if tail.range.fragment_epoch == held_fragment_epoch |
| 5142 | && tail.range.base == base |
| 5143 | && tail.range.end == sealed.end |
| 5144 | && (!tail.range.complete |
| 5145 | || !tail_covers_sealed_range( |
| 5146 | base, |
| 5147 | sealed.end, |
| 5148 | &tail.entries, |
| 5149 | )) => |
| 5150 | { |
| 5151 | warn!( |
| 5152 | dead, |
| 5153 | member, |
| 5154 | base, |
| 5155 | end = sealed.end, |
| 5156 | "sealed follower returned an incomplete tail" |
| 5157 | ); |
| 5158 | } |
| 5159 | Some(base) => { |
| 5160 | inconclusive += 1; |
| 5161 | warn!( |
| 5162 | dead, |
| 5163 | member, |
| 5164 | base, |
| 5165 | end = sealed.end, |
| 5166 | tail_epoch = tail.range.fragment_epoch, |
| 5167 | tail_base = tail.range.base, |
| 5168 | tail_end = tail.range.end, |
| 5169 | tail_complete = tail.range.complete, |
| 5170 | "sealed follower returned inconsistent tail metadata" |
| 5171 | ); |
| 5172 | } |
| 5173 | None => { |
| 5174 | inconclusive += 1; |
| 5175 | warn!( |
| 5176 | dead, |
| 5177 | member, "sealed follower did not report its retained range" |
| 5178 | ); |
| 5179 | } |
| 5180 | } |
| 5181 | } |
| 5182 | for entry in tail.entries { |
| 5183 | gathered.insert((entry.cell, entry.cell_epoch, entry.txid), entry.bytes); |
| 5184 | } |
| 5185 | } |
| 5186 | let members_ms = mono_ms().saturating_sub(pass_started); |
| 5187 | // `may_have_fleet_acks` was CASed before the epoch's first fleet |
| 5188 | // credit, so this marker without a complete witness means that |
| 5189 | // acked frames can be missing. If any member's state remains |
| 5190 | // inconclusive, keep failing loudly because its data can still |
| 5191 | // become readable. If every member is conclusive, declare the |
| 5192 | // bounded loss AS A RECORD: a permanent object beside the log |
| 5193 | // record stating what was unrecoverable, then proceed to the |
| 5194 | // drain and the seal. "Loss is a record, never a prompt." The |
| 5195 | // verdict rests on the members alone, so it is reached before |
| 5196 | // the bundle drain: a pass that must refuse to seal refuses |
| 5197 | // before it reads the session, not after. |
| 5198 | if complete_witnesses == 0 && may_have_fleet_acks && !record.ensemble.is_empty() { |
| 5199 | anyhow::ensure!( |
| 5200 | inconclusive == 0, |
| 5201 | "node-log recovery for {dead}: no complete true witness among {:?} and \ |
| 5202 | {inconclusive} member(s) undecided; refusing to seal while \ |
| 5203 | member state remains unverified", |
| 5204 | record.ensemble |
| 5205 | ); |
| 5206 | let loss = serde_json::json!({ |
| 5207 | "leader": dead, |
| 5208 | "epoch": record.epoch, |
| 5209 | "declared_at_ms": now, |
| 5210 | "declared_by": self.node, |
| 5211 | "ensemble": record.ensemble.iter().collect::<Vec<_>>(), |
| 5212 | "note": "no complete true witness survived; acked writes within the \ |
| 5213 | final flush window may be unrecovered", |
| 5214 | }); |
| 5215 | self.bucket |
| 5216 | .put( |
| 5217 | &format!("log/{dead}.e{}.loss.json", record.epoch), |
| 5218 | serde_json::to_vec(&loss)?, |
| 5219 | ) |
| 5220 | .await?; |
| 5221 | warn!( |
| 5222 | dead, |
| 5223 | epoch = record.epoch, |
| 5224 | "declared bounded loss: no complete true witness for an active log; \ |
| 5225 | recovery record written" |
| 5226 | ); |
| 5227 | } |
| 5228 | // The dead leader's un-drained bundles are bucket-durable |
| 5229 | // coverage that recovery folds into the per-cell prefixes — |
| 5230 | // one GET per bundle, sliced locally, the same idempotent |
| 5231 | // per-cell PUTs as the follower gather. This runs regardless |
| 5232 | // of the witness outcome: even a declared loss drains what |
| 5233 | // the bucket already holds. EVERY retained bundle, not only |
| 5234 | // the record epoch's: a live reconfiguration steps the epoch |
| 5235 | // behind a barrier that counts bundle coverage as tiered, so |
| 5236 | // rows can be durable only in a prior epoch's bundle — an |
| 5237 | // epoch filter here sealed them out of the per-cell layout |
| 5238 | // forever (the RecoveryEpochFilter tooth). What bounds this |
| 5239 | // gather to the true un-drained window is bundle GC deleting |
| 5240 | // covered bundles, not a filter that can orphan acked rows; |
| 5241 | // the covered-txid check in the upload still bounds the |
| 5242 | // uploads. Concurrent GETs: the profiling round measured the |
| 5243 | // serial gather at 89-112 s over ~1,300 bundles — the whole |
| 5244 | // outage. |
| 5245 | // |
| 5246 | // The bundles fold in WINDOWS of `RECOVERY_GATHER_WINDOW_BYTES`, |
| 5247 | // each read, uploaded per cell, and released before the next is |
| 5248 | // read, so the process holds one window of the session and not |
| 5249 | // the session (#957: the whole-session gather cost 0.95 GB of |
| 5250 | // process memory per GB of session and OOM-killed a 16 GB node |
| 5251 | // past a 40-minute session). Windows make the fold ORDER- |
| 5252 | // DEPENDENT where the whole-session gather was not: a window |
| 5253 | // raises the per-cell watermark to the last txid it uploads, |
| 5254 | // and every later window skips rows at or below it, which is |
| 5255 | // correct only if every later window's rows for a cell epoch |
| 5256 | // lie at or above that txid. Flush order guarantees this: the |
| 5257 | // shipper reads each cell from its durable txid upward, so |
| 5258 | // consecutive bundles carry adjacent ranges (a credited flush) |
| 5259 | // or a repeat that extends the earlier one (an uncredited |
| 5260 | // flush re-read from the same durable txid), and never a lower |
| 5261 | // range. Flush order is numeric (epoch, seq) order — a key sort |
| 5262 | // puts `e10-` before `e9-` — and the follower tails, the newest |
| 5263 | // acked rows of the current epoch, fold with the LAST window; |
| 5264 | // folded first, their txids would have raised the watermark |
| 5265 | // over every bundled row behind them and orphaned the session. |
| 5266 | let bundle_metas = self |
| 5267 | .bucket |
| 5268 | .list(&format!("log/{dead}/bundle/")) |
| 5269 | .await |
| 5270 | .with_context(|| format!("list retained recovery bundles for {dead}"))?; |
| 5271 | let bundles_read = bundle_metas.len(); |
| 5272 | #[cfg(all(test, celld_internal_tests))] |
| 5273 | let window_bytes = self.recovery_gather_window_bytes.load(Ordering::SeqCst); |
| 5274 | #[cfg(not(all(test, celld_internal_tests)))] |
| 5275 | let window_bytes = RECOVERY_GATHER_WINDOW_BYTES; |
| 5276 | let windows = gather_windows( |
| 5277 | bundle_metas |
| 5278 | .into_iter() |
| 5279 | .map(|meta| (meta.location.as_ref().to_string(), meta.size)) |
| 5280 | .collect(), |
| 5281 | window_bytes, |
| 5282 | ); |
| 5283 | let window_count = windows.len(); |
| 5284 | // Loaded ahead of the first upload, as before the windows: a |
| 5285 | // session with nothing to fold costs no checkpoint listing. |
| 5286 | let mut progress: Option<recovery_progress::Progress> = None; |
| 5287 | let mut count = 0_usize; |
| 5288 | let mut bundles_ms = 0_u64; |
| 5289 | let mut upload_ms = 0_u64; |
| 5290 | let mut gathered_bytes = 0_u64; |
| 5291 | let mut tail = Some(std::mem::take(&mut gathered)); |
| 5292 | for (index, window) in windows.into_iter().enumerate() { |
| 5293 | let fetch_started = mono_ms(); |
| 5294 | let fetches = window.into_iter().map(|key| { |
| 5295 | let bucket = self.bucket.clone(); |
| 5296 | async move { |
| 5297 | let fetched = bucket |
| 5298 | .get(&key) |
| 5299 | .await |
| 5300 | .with_context(|| format!("read retained recovery bundle {key}"))?; |
| 5301 | let (bytes, _) = fetched |
| 5302 | .ok_or_else(|| anyhow!("listed recovery bundle {key} disappeared"))?; |
| 5303 | anyhow::Ok((key, bytes)) |
| 5304 | } |
| 5305 | }); |
| 5306 | let mut fetches = futures_util::stream::iter(fetches) |
| 5307 | .buffer_unordered(RECOVERY_UPLOAD_CONCURRENCY); |
| 5308 | while let Some(fetched) = futures_util::StreamExt::next(&mut fetches).await { |
| 5309 | self.beat_claim(dead, &mut beat).await?; |
| 5310 | let (key, bytes) = fetched?; |
| 5311 | let rows = celld_ltx::bundle::decode_rows(&bytes) |
| 5312 | .with_context(|| format!("decode retained recovery bundle {key}"))?; |
| 5313 | for row in rows { |
| 5314 | let payload = celld_ltx::bundle::slice(&bytes, &row) |
| 5315 | .with_context(|| format!("read a row from recovery bundle {key}"))?; |
| 5316 | gathered |
| 5317 | .entry((row.cell, row.cell_epoch, row.txid)) |
| 5318 | .or_insert_with(|| payload.to_vec()); |
| 5319 | } |
| 5320 | } |
| 5321 | drop(fetches); |
| 5322 | if index + 1 == window_count { |
| 5323 | // The same bytes under the same key wherever a row is |
| 5324 | // held; the follower's copy stays the one uploaded, as |
| 5325 | // it was when the whole session folded at once. |
| 5326 | for (key, bytes) in tail.take().into_iter().flatten() { |
| 5327 | gathered.insert(key, bytes); |
| 5328 | } |
| 5329 | } |
| 5330 | bundles_ms += mono_ms().saturating_sub(fetch_started); |
| 5331 | let held: u64 = gathered.values().map(|bytes| bytes.len() as u64).sum(); |
| 5332 | #[cfg(all(test, celld_internal_tests))] |
| 5333 | self.recovery_gather_peak_bytes |
| 5334 | .fetch_max(held, Ordering::SeqCst); |
| 5335 | gathered_bytes += held; |
| 5336 | // Skip rows the drain points already folded into the |
| 5337 | // per-cell prefix: one listing per cell bounds uploads to |
| 5338 | // the true un-drained tail, so recovery cost tracks the |
| 5339 | // flush window, not the epoch's age. LTX TXIDs are |
| 5340 | // contiguous per epoch, so coverage up to the listed |
| 5341 | // maximum is coverage of everything at or below it. Cells |
| 5342 | // drive concurrently — the sequential version cost the lab |
| 5343 | // ~47 s for 180 entries — while rows within a cell stay |
| 5344 | // ordered; any failure aborts the pass before the record |
| 5345 | // can seal. |
| 5346 | if gathered.is_empty() { |
| 5347 | continue; |
| 5348 | } |
| 5349 | let upload_started = mono_ms(); |
| 5350 | if progress.is_none() { |
| 5351 | progress = |
| 5352 | Some(recovery_progress::Progress::load(self, dead, &mut beat).await?); |
| 5353 | } |
| 5354 | let loaded = progress |
| 5355 | .as_mut() |
| 5356 | .expect("the progress record is loaded before the first upload"); |
| 5357 | count += self |
| 5358 | .upload_gathered( |
| 5359 | std::mem::take(&mut gathered), |
| 5360 | Some((dead, &mut beat, loaded)), |
| 5361 | ) |
| 5362 | .await?; |
| 5363 | upload_ms += mono_ms().saturating_sub(upload_started); |
| 5364 | } |
| 5365 | // The record is re-read for the token the beats moved. |
| 5366 | let mut sealed = false; |
| 5367 | for _ in 0..3 { |
| 5368 | let Some(current) = read_record(&self.bucket, dead).await? else { |
| 5369 | return Ok(()); |
| 5370 | }; |
| 5371 | if current.record.state == LogState::Sealed { |
| 5372 | return Ok(()); |
| 5373 | } |
| 5374 | anyhow::ensure!( |
| 5375 | log_tier::recovery_claimed_by(¤t.record, &self.node), |
| 5376 | "node-log recovery for {dead} was taken over by another node" |
| 5377 | ); |
| 5378 | let Some(done) = log_tier::finish_recovery(¤t.record, record.tiered) else { |
| 5379 | break; |
| 5380 | }; |
| 5381 | if write_dead_record( |
| 5382 | &self.bucket, |
| 5383 | dead, |
| 5384 | ¤t.wire, |
| 5385 | &done, |
| 5386 | current.may_have_fleet_acks, |
| 5387 | ¤t.token, |
| 5388 | ) |
| 5389 | .await? |
| 5390 | .is_some() |
| 5391 | { |
| 5392 | sealed = true; |
| 5393 | break; |
| 5394 | } |
| 5395 | } |
| 5396 | if sealed { |
| 5397 | info!( |
| 5398 | dead, |
| 5399 | entries = count, |
| 5400 | pass = _attempt, |
| 5401 | members_ms, |
| 5402 | bundles_read, |
| 5403 | windows = window_count, |
| 5404 | gathered_bytes, |
| 5405 | bundles_ms, |
| 5406 | upload_ms, |
| 5407 | total_ms = mono_ms().saturating_sub(pass_started), |
| 5408 | "node log recovered and sealed" |
| 5409 | ); |
| 5410 | return Ok(()); |
| 5411 | } |
| 5412 | } |
| 5413 | Err(anyhow!("node-log recovery for {dead} lost every CAS race")) |
| 5414 | } |
| 5415 | |
| 5416 | /// The takeover interlock: may this cell's takeover treat the bucket as |
| 5417 | /// complete? Runs before the restore reads or seals anything. `prior` |
| 5418 | /// arrives through the decision core's Claim, so an acquire confirmed by |
| 5419 | /// reconciliation names the displaced owner exactly like one confirmed |
| 5420 | /// by the CAS response — the v0 ambiguous-CAS window is closed. `None` |
| 5421 | /// means the consumed record was released or absent, which the release |
| 5422 | /// path already proved durable. Absence of a log record is a proof (the |
| 5423 | /// node never acked past the bucket); a sealed record means recovery |
| 5424 | /// already ran; anything else runs it now. |
| 5425 | pub async fn ensure_recovered(&self, prior: Option<&str>) -> anyhow::Result<()> { |
| 5426 | self.ensure_predecessors_recovered().await?; |
| 5427 | let Some(prior) = prior else { |
| 5428 | return Ok(()); |
| 5429 | }; |
| 5430 | if prior == self.node { |
| 5431 | return Ok(()); |
| 5432 | } |
| 5433 | // ONE rule for every cold path, at the cost of ONE read the core |
| 5434 | // usually already performed: before restoring a cell last owned |
| 5435 | // by node X, X's folded log state must be sealed or absent. The |
| 5436 | // lease record holds at most one session's state — recovery- |
| 5437 | // before-install is what keeps a predecessor's Open state from |
| 5438 | // being replaced unrecovered — so a single GET decides. |
| 5439 | let folded = read_record(&self.bucket, prior).await?; |
| 5440 | let session = folded |
| 5441 | .as_ref() |
| 5442 | .map(|folded| format!("{prior}/{}", folded.wire.generation)); |
| 5443 | match log_tier::takeover_gate(folded.as_ref().map(|folded| &folded.record)) { |
| 5444 | log_tier::TakeoverGate::BucketComplete => {} |
| 5445 | log_tier::TakeoverGate::RecoverFirst => { |
| 5446 | self.recover_as( |
| 5447 | &session.expect("a record implies a session"), |
| 5448 | RecoverMode::Boot, |
| 5449 | ) |
| 5450 | .await? |
| 5451 | } |
| 5452 | } |
| 5453 | Ok(()) |
| 5454 | } |
| 5455 | |
| 5456 | fn shipper_batch_in_flight(shipper: &FleetShipper) -> bool { |
| 5457 | shipper.outstanding.load(Ordering::SeqCst) > 0 |
| 5458 | } |
| 5459 | |
| 5460 | /// The graceful-shutdown drain point: stop fleet acks, wait for the |
| 5461 | /// ticking bundle loop to tier what was shipped, then seal our own |
| 5462 | /// record. The next incarnation finds Sealed and opens a fresh epoch |
| 5463 | /// with no gather at all — without this, a routine restart hands |
| 5464 | /// recovery a whole epoch of already-drained bundles to re-fold. |
| 5465 | /// Best-effort: any failure leaves the record Open, and recovery |
| 5466 | /// does what it always does. |
| 5467 | pub async fn close_gracefully(&self) { |
| 5468 | let shipper = { |
| 5469 | let mut transition = self.live_log.lock().await; |
| 5470 | if !transition.begin_quiescing() { |
| 5471 | return; |
| 5472 | } |
| 5473 | // Quiesce the sink before degrading the shipper. The lifecycle |
| 5474 | // guard makes both decisions visible before any maintenance or |
| 5475 | // first-ack transition can enter its publication section. |
| 5476 | self.closing.store(true, Ordering::SeqCst); |
| 5477 | self.inner.lock().unwrap().clone() |
| 5478 | }; |
| 5479 | let Some(shipper) = shipper else { return }; |
| 5480 | shipper.degrade("graceful shutdown"); |
| 5481 | for _ in 0..50 { |
| 5482 | if self.ltx.all_shipped_tiered() { |
| 5483 | break; |
| 5484 | } |
| 5485 | crate::asyncrt::sleep(std::time::Duration::from_millis(200)).await; |
| 5486 | } |
| 5487 | for _ in 0..30 { |
| 5488 | if !self.flush_in_flight.load(Ordering::SeqCst) { |
| 5489 | break; |
| 5490 | } |
| 5491 | crate::asyncrt::sleep(std::time::Duration::from_millis(100)).await; |
| 5492 | } |
| 5493 | #[cfg(all(test, celld_internal_tests))] |
| 5494 | { |
| 5495 | // Capture the real folded record before the test pause. The |
| 5496 | // final transition deliberately re-reads it under a fresh guard. |
| 5497 | let transition = self.live_log.lock().await; |
| 5498 | let _captured = transition.current(); |
| 5499 | drop(transition); |
| 5500 | self.pause_close_transition_for_world().await; |
| 5501 | } |
| 5502 | let transition = self.live_log.lock().await; |
| 5503 | debug_assert!(!transition.is_running()); |
| 5504 | // eprintln, not tracing: this runs on the way out of the process, |
| 5505 | // and buffered stdout may never flush before exit. |
| 5506 | let Some(current) = transition.current() else { |
| 5507 | eprintln!("node-log close: no folded log; nothing to seal"); |
| 5508 | return; |
| 5509 | }; |
| 5510 | let Ok(record) = log_from_wire(¤t) else { |
| 5511 | eprintln!("node-log close: folded log unreadable; left as is"); |
| 5512 | return; |
| 5513 | }; |
| 5514 | let may_have_fleet_acks = current.may_have_fleet_acks; |
| 5515 | // "Tiered" includes bundle coverage, but a sealed |
| 5516 | // record tells every future recovery there is nothing to gather — |
| 5517 | // so the seal requires every acked row as a per-cell object. The |
| 5518 | // barrier is the RETAINED BUNDLE SCAN, not a cell counter: the |
| 5519 | // gate's synced_seq is advanced by bundle credits (it must be — |
| 5520 | // it is the ack counter), so the old all_synced_per_cell check |
| 5521 | // never actually demanded the per-cell layout, and the class-A |
| 5522 | // hour sealed 1,300 acked rows into orphanhood behind epoch 156. |
| 5523 | // An Open record is always safe: the next incarnation's recovery |
| 5524 | // drains the bundles. |
| 5525 | let per_cell_complete = self.ltx.all_tails_tiered() |
| 5526 | && match self.uncovered_bundle_rows().await { |
| 5527 | Ok(uncovered) => uncovered.is_empty(), |
| 5528 | Err(_) => false, |
| 5529 | }; |
| 5530 | if !log_tier::graceful_seal_allowed( |
| 5531 | &record, |
| 5532 | shipper.epoch, |
| 5533 | Self::shipper_batch_in_flight(&shipper), |
| 5534 | per_cell_complete, |
| 5535 | ) { |
| 5536 | eprintln!( |
| 5537 | "node-log close: not sealable (record epoch {} state {:?}, shipper epoch {}); record left open", |
| 5538 | record.epoch, record.state, shipper.epoch |
| 5539 | ); |
| 5540 | return; |
| 5541 | } |
| 5542 | let sealed = log_tier::LogRecord { |
| 5543 | state: LogState::Sealed, |
| 5544 | ..record |
| 5545 | }; |
| 5546 | match transition |
| 5547 | .write(Some(log_to_wire(&sealed, may_have_fleet_acks))) |
| 5548 | .await |
| 5549 | { |
| 5550 | Ok(()) => eprintln!("node-log close: sealed epoch {}", sealed.epoch), |
| 5551 | Err(error) => eprintln!("node-log close: seal not durable: {error:#}"), |
| 5552 | } |
| 5553 | } |
| 5554 | |
| 5555 | /// Startup: recover every predecessor session's open log — their |
| 5556 | /// acked tails may sit on our old followers or our own staged files, |
| 5557 | /// and nothing may ack against a fresh ensemble until those tails are |
| 5558 | /// in the bucket. Our own session's record cannot exist yet, so this |
| 5559 | /// is ordinary dead-session recovery under other keys. |
| 5560 | pub async fn recover_self(&self) -> anyhow::Result<()> { |
| 5561 | self.ensure_predecessors_recovered().await |
| 5562 | } |
| 5563 | |
| 5564 | /// Is the fleet tier serving acknowledgements? |
| 5565 | /// |
| 5566 | /// One follower is the floor, not two. Recruitment still takes two, so a |
| 5567 | /// healthy fleet holds three copies; the floor is what the ensemble may |
| 5568 | /// shrink to and keep acknowledging, which is the shape an in-sync replica |
| 5569 | /// set has: Kafka recruits a replication factor and serves while at least |
| 5570 | /// `min.insync.replicas` are in sync, canonically three and two. |
| 5571 | /// |
| 5572 | /// Two copies is where surviving the loss of the leader begins, and the |
| 5573 | /// bucket upload races every fleet acknowledgement regardless. Requiring |
| 5574 | /// two followers put the fast tier one node past the guarantee that |
| 5575 | /// matters, and made a single eviction on a three-node fleet drop every |
| 5576 | /// acknowledgement to the bucket, because the ensemble fell under the |
| 5577 | /// floor with nothing left to recruit. |
| 5578 | /// Say that the fleet posture is requested and not achieved, at most |
| 5579 | /// once every five minutes. |
| 5580 | /// |
| 5581 | /// Silence is the failure that costs the most here. `log ensemble |
| 5582 | /// degraded` fires only when an ensemble that existed was lost, so a node |
| 5583 | /// that never formed one said nothing, and a single-node fleet ran the |
| 5584 | /// default fleet posture on bucket acknowledgements forever with no line |
| 5585 | /// explaining the latency or naming the fix. |
| 5586 | /// |
| 5587 | /// The two cases differ. No live peer is an ordinary single-node fleet and |
| 5588 | /// the message is an invitation: a second node acknowledges from a |
| 5589 | /// follower's disk instead of a storage round trip. Live peers that are |
| 5590 | /// all ineligible is a fault the operator can act on. |
| 5591 | fn report_fleet_shortfall(&self, live_peers: usize, now_ms: u64) { |
| 5592 | const REPORT_INTERVAL_MS: u64 = 300_000; |
| 5593 | let last = match self.shortfall_logged_ms.load(Ordering::SeqCst) { |
| 5594 | 0 => None, |
| 5595 | stamp => Some(stamp), |
| 5596 | }; |
| 5597 | let Some(shortfall) = |
| 5598 | log_tier::fleet_shortfall(live_peers, now_ms, last, REPORT_INTERVAL_MS) |
| 5599 | else { |
| 5600 | return; |
| 5601 | }; |
| 5602 | self.shortfall_logged_ms.store(now_ms, Ordering::SeqCst); |
| 5603 | match shortfall { |
| 5604 | log_tier::Shortfall::NoPeer => info!( |
| 5605 | live_peers, |
| 5606 | "fleet durability requested and no peer is available; writes \ |
| 5607 | wait for the bucket. A second node acknowledges a write when \ |
| 5608 | its follower holds it on disk, which is much faster" |
| 5609 | ), |
| 5610 | log_tier::Shortfall::NoEligiblePeer => warn!( |
| 5611 | live_peers, |
| 5612 | "fleet durability requested and no peer is eligible; writes \ |
| 5613 | wait for the bucket. Every live peer is quarantined for \ |
| 5614 | incapability or has not been recruited yet" |
| 5615 | ), |
| 5616 | } |
| 5617 | } |
| 5618 | |
| 5619 | pub fn healthy(&self) -> bool { |
| 5620 | self.inner |
| 5621 | .lock() |
| 5622 | .unwrap() |
| 5623 | .as_ref() |
| 5624 | .is_some_and(|shipper| shipper.is_active() && !shipper.members.is_empty()) |
| 5625 | } |
| 5626 | |
| 5627 | fn shutdown_local_fallback(&self) { |
| 5628 | self.task_stop.request_stop(); |
| 5629 | self.closing.store(true, Ordering::SeqCst); |
| 5630 | if let Some(shipper) = self.inner.lock().unwrap().take() { |
| 5631 | shipper.degrade("local durability shutdown"); |
| 5632 | } |
| 5633 | } |
| 5634 | |
| 5635 | /// One ensemble-maintenance pass: if the shipper is absent, degraded, |
| 5636 | /// or under-strength while better peers exist, rebuild it. The order is |
| 5637 | /// the model's reconfiguration discipline, enforced against live |
| 5638 | /// uploads: deactivate (acks fall to the bucket), drain until every |
| 5639 | /// shipped frame is tiered (the force-tier barrier — old fragments |
| 5640 | /// become garbage), CAS the record at the next epoch, then install the |
| 5641 | /// new shipper. A lost CAS leaves us at bucket posture; the next pass |
| 5642 | /// re-reads and retries. |
| 5643 | pub async fn maintain(&self) -> anyhow::Result<()> { |
| 5644 | // Avoid every remote read after local ownership has ended. Shutdown |
| 5645 | // can still race a pass after this check, so publication has a second |
| 5646 | // check under the lifecycle transition below. |
| 5647 | if self.task_stop.is_stopped() { |
| 5648 | return Ok(()); |
| 5649 | } |
| 5650 | if self.healthy() { |
| 5651 | return Ok(()); |
| 5652 | } |
| 5653 | // Self-suspicion parks recruitment: opening epochs into our own |
| 5654 | // partition churns records and proves nothing. Any successful |
| 5655 | // peer response lifts it. |
| 5656 | if self.suspect_self.load(Ordering::SeqCst) { |
| 5657 | return Ok(()); |
| 5658 | } |
| 5659 | let peers = self.ownership.read_capacity_peers().await?; |
| 5660 | let now = crate::ownership_store::now_ms(); |
| 5661 | let mono = mono_ms(); |
| 5662 | // Kept before the filters consume the vector: a fleet with no peer at |
| 5663 | // all is a different message from a fleet whose peers are all |
| 5664 | // ineligible, and an operator needs to be told which one they have. |
| 5665 | let live_peers = peers |
| 5666 | .iter() |
| 5667 | .filter(|peer| peer.node != self.node && peer.expires_ms > now) |
| 5668 | .count(); |
| 5669 | let members: Vec<Member> = peers |
| 5670 | .into_iter() |
| 5671 | .filter(|peer| peer.node != self.node && peer.expires_ms > now) |
| 5672 | // Only a follower that cannot serve appends at all sits out a |
| 5673 | // term. A gray one is recruitable again at once, because the |
| 5674 | // latency rule can judge it again and the swap rate cap is what |
| 5675 | // bounds flapping. |
| 5676 | .filter(|peer| !self.health.lock().unwrap().quarantined(&peer.node, mono)) |
| 5677 | // Recruit up to two followers — three copies — while the ensemble |
| 5678 | // may serve on one. Replication factor and the in-sync floor are |
| 5679 | // separate numbers. |
| 5680 | .take(2) |
| 5681 | .map(|peer| Member { |
| 5682 | node: peer.node, |
| 5683 | addr: peer.addr, |
| 5684 | }) |
| 5685 | .collect(); |
| 5686 | // Peer discovery is intentionally outside the transition guard. |
| 5687 | // Recheck the lifecycle after that await, then keep the snapshot, |
| 5688 | // publication, and successor installation in one critical section. |
| 5689 | let transition = self.live_log.lock().await; |
| 5690 | if !transition.is_running() { |
| 5691 | return Ok(()); |
| 5692 | } |
| 5693 | { |
| 5694 | let inner = self.inner.lock().unwrap().clone(); |
| 5695 | if let Some(current) = inner { |
| 5696 | // Same strength available: nothing to improve. |
| 5697 | if current.is_active() && members.len() <= current.members.len() { |
| 5698 | return Ok(()); |
| 5699 | } |
| 5700 | // Deactivate first: acks fall to the bucket and pacing |
| 5701 | // stops, so the drain below converges. |
| 5702 | current.degraded.store(true, Ordering::SeqCst); |
| 5703 | // The reconfiguration barrier is a core decision: a batch |
| 5704 | // between capture and credit is invisible to the coverage |
| 5705 | // counters, and every fleet-shipped frame must be |
| 5706 | // bucket-covered before the old fragments become |
| 5707 | // abandonable. Wait it out; the next tick retries. |
| 5708 | if !log_tier::may_reconfigure( |
| 5709 | current.outstanding.load(Ordering::SeqCst) > 0, |
| 5710 | self.ltx.all_fragment_rows_tiered(), |
| 5711 | ) { |
| 5712 | return Ok(()); |
| 5713 | } |
| 5714 | } |
| 5715 | } |
| 5716 | if members.is_empty() { |
| 5717 | self.report_fleet_shortfall(live_peers, mono); |
| 5718 | return Ok(()); |
| 5719 | } |
| 5720 | if !self.ltx.all_fragment_rows_tiered() { |
| 5721 | return Ok(()); // re-checked: the drain may regress between locks |
| 5722 | } |
| 5723 | let ensemble: BTreeSet<String> = members.iter().map(|member| member.node.clone()).collect(); |
| 5724 | // The in-process folded state IS the record (single lease writer): |
| 5725 | // no bucket read, and no CAS-lost re-read loop — the only |
| 5726 | // concurrent mutation is a peer's recovery of our EXPIRED lease, |
| 5727 | // and then our renewals stop applying and write_own_log fails. |
| 5728 | let prior = transition |
| 5729 | .current() |
| 5730 | .as_ref() |
| 5731 | .map(log_from_wire) |
| 5732 | .transpose()?; |
| 5733 | let step = log_tier::maintain_step(prior.as_ref()); |
| 5734 | let record = match step { |
| 5735 | log_tier::MaintainStep::CreateFresh => log_tier::create_record(ensemble.clone(), 0) |
| 5736 | .ok_or_else(|| anyhow!("empty ensemble"))?, |
| 5737 | log_tier::MaintainStep::Wait => return Ok(()), |
| 5738 | // v0 tiers per cell, so the record's tiered offset stays 0 |
| 5739 | // and the drain barrier above is what makes the old |
| 5740 | // fragments abandonable — the same precondition |
| 5741 | // plan_reconfigure encodes for the bundle tier. The reopen |
| 5742 | // healing pass is deleted with the per-session key: a |
| 5743 | // within-session reopen sits behind the drain barrier (every |
| 5744 | // shipped row tiered), and a new session recovers its |
| 5745 | // predecessors before its first open, so no reopen can strand |
| 5746 | // bundle rows behind a record it never owned. |
| 5747 | log_tier::MaintainStep::Reopen(epoch) => log_tier::LogRecord { |
| 5748 | epoch, |
| 5749 | ensemble: ensemble.clone(), |
| 5750 | tiered: 0, |
| 5751 | state: LogState::Open, |
| 5752 | claimant: None, |
| 5753 | claimed_ms: None, |
| 5754 | }, |
| 5755 | }; |
| 5756 | // A fresh epoch has no fleet acknowledgements: `may_have_fleet_acks` |
| 5757 | // flips through the lease chain before its first fleet credit. The |
| 5758 | // open itself rides an immediate renewal; a failure means our lease |
| 5759 | // is not applying and the posture stays bucket. |
| 5760 | #[cfg(all(test, celld_internal_tests))] |
| 5761 | self.pause_maintenance_publish_for_world().await; |
| 5762 | // Keep this check under the transition guard and immediately before |
| 5763 | // the remote write. A pass stopped before this point cannot publish. |
| 5764 | // A write admitted here can finish after fallback, so dead-session |
| 5765 | // recovery remains responsible for that remote Open record. |
| 5766 | if self.task_stop.is_stopped() { |
| 5767 | return Ok(()); |
| 5768 | } |
| 5769 | transition.write(Some(log_to_wire(&record, false))).await?; |
| 5770 | #[cfg(all(test, celld_internal_tests))] |
| 5771 | self.pause_maintenance_install_for_world().await; |
| 5772 | info!( |
| 5773 | epoch = record.epoch, |
| 5774 | members = ?record.ensemble, |
| 5775 | "log ensemble open; fleet acks enabled" |
| 5776 | ); |
| 5777 | self.health.lock().unwrap().reset(); |
| 5778 | // An unset override selects the adaptive deadline; a set value is |
| 5779 | // the lab's fixed override, and 0 disables hedging entirely. |
| 5780 | let hedge = match crate::env_vars::optional::<u64>("CELLD_LOG_HEDGE_MS") |
| 5781 | .ok() |
| 5782 | .flatten() |
| 5783 | { |
| 5784 | Some(ms) => HedgeMode::Fixed(ms), |
| 5785 | None => HedgeMode::Adaptive, |
| 5786 | }; |
| 5787 | // Local shutdown publishes stop before it takes `inner`. Keep the |
| 5788 | // stop recheck and successor installation under that same mutex: an |
| 5789 | // install that wins is removed by shutdown, and an install that loses |
| 5790 | // cannot resurrect a shipper or its member lanes afterward. |
| 5791 | let mut installed = self.inner.lock().unwrap(); |
| 5792 | if self.task_stop.is_stopped() { |
| 5793 | return Ok(()); |
| 5794 | } |
| 5795 | // The stream window (the stream-window design): a nonzero |
| 5796 | // CELLD_LOG_WINDOW is the appends-per-lane bound and takes over the |
| 5797 | // ship loop's depth; zero keeps the round pipeline unchanged. |
| 5798 | let window = crate::env_vars::optional::<u64>("CELLD_LOG_WINDOW") |
| 5799 | .ok() |
| 5800 | .flatten() |
| 5801 | .unwrap_or(0); |
| 5802 | let byte_cap = crate::env_vars::optional::<u64>("CELLD_LOG_WINDOW_BYTES") |
| 5803 | .ok() |
| 5804 | .flatten() |
| 5805 | .unwrap_or(8 * 1024 * 1024); |
| 5806 | let stream = (window > 0) |
| 5807 | .then(|| Arc::new(StreamWindow::new(window, byte_cap.max(1), members.len()))); |
| 5808 | // The ordered stream transport (the ordered-transport design) |
| 5809 | // ships dark: an unset or "http" value keeps the one-shot lanes. |
| 5810 | let stream_transport = crate::env_vars::value("CELLD_LOG_TRANSPORT") |
| 5811 | .ok() |
| 5812 | .flatten() |
| 5813 | .is_some_and(|value| value == "stream"); |
| 5814 | let pipeline = if window > 0 { |
| 5815 | window as usize |
| 5816 | } else { |
| 5817 | crate::env_vars::positive_or("CELLD_LOG_PIPELINE", 4_usize).unwrap_or(4) |
| 5818 | }; |
| 5819 | let mut lanes = Vec::with_capacity(members.len()); |
| 5820 | for (index, member) in members.iter().enumerate() { |
| 5821 | let (send, receive) = tokio::sync::mpsc::unbounded_channel(); |
| 5822 | self.child_tasks.spawn_owned( |
| 5823 | "node_log_member_lane", |
| 5824 | member_lane( |
| 5825 | member.clone(), |
| 5826 | self.transport.clone(), |
| 5827 | self.policy.clone(), |
| 5828 | self.health.clone(), |
| 5829 | LaneTuning { |
| 5830 | hedge, |
| 5831 | stream: stream.clone().map(|window| (window, index)), |
| 5832 | stream_transport, |
| 5833 | }, |
| 5834 | receive, |
| 5835 | self.task_stop.clone(), |
| 5836 | ), |
| 5837 | ); |
| 5838 | lanes.push(send); |
| 5839 | } |
| 5840 | *installed = Some(Arc::new(FleetShipper { |
| 5841 | // The wire leader identity IS the session string: followers key |
| 5842 | // fragments and seal marks by it, so a restarted process's |
| 5843 | // appends can never collide with its predecessor's fragments. |
| 5844 | node: self.session.clone(), |
| 5845 | transport: self.transport.clone(), |
| 5846 | record: record.clone(), |
| 5847 | live_log: self.live_log.clone(), |
| 5848 | activated: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 5849 | epoch: record.epoch, |
| 5850 | members, |
| 5851 | lanes, |
| 5852 | pipeline, |
| 5853 | seq: std::sync::atomic::AtomicU64::new(0), |
| 5854 | degraded: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 5855 | outstanding: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 5856 | policy: self.policy.clone(), |
| 5857 | stream, |
| 5858 | })); |
| 5859 | // The successor record and its in-memory shipper form one state |
| 5860 | // transition. Keep shutdown excluded until both values are visible. |
| 5861 | drop(transition); |
| 5862 | Ok(()) |
| 5863 | } |
| 5864 | } |
| 5865 | |
| 5866 | impl NodeLogManager { |
| 5867 | /// Bundle GC: delete a bundle object once every row it carries is |
| 5868 | /// covered by the per-cell layout. The watermark is what keeps |
| 5869 | /// recovery's whole-prefix gather bounded to the true un-drained |
| 5870 | /// window without an epoch filter that could orphan acked rows — a |
| 5871 | /// bundle is deletable exactly when nothing could ever need to gather |
| 5872 | /// it. Bounded per tick; rows come from the in-memory index when this |
| 5873 | /// incarnation wrote the bundle, one GET otherwise. An unreadable |
| 5874 | /// bundle is never deleted on a guess: it stays, and stays cheap. |
| 5875 | /// Every retained bundle row above its (cell, epoch) per-cell |
| 5876 | /// covered watermark — the rows a sealed record would ORPHAN. The |
| 5877 | /// graceful seal refuses while any exist, and the reopen path folds |
| 5878 | /// them per-cell first (the healing pass). The previous barrier sealed |
| 5879 | /// over exactly this set: `all_synced_per_cell` counted |
| 5880 | /// bundle credits (the gate's counter must), so the old barrier |
| 5881 | /// never actually demanded the per-cell layout. |
| 5882 | pub async fn uncovered_bundle_rows( |
| 5883 | &self, |
| 5884 | ) -> anyhow::Result<BTreeMap<(String, u64, u64), Vec<u8>>> { |
| 5885 | self.uncovered_bundle_rows_for(None).await |
| 5886 | } |
| 5887 | |
| 5888 | /// The same scan bounded to one cell. The reactivation fold uses the |
| 5889 | /// complete process-session membership index, so it does not list the |
| 5890 | /// bundle prefix or read a bundle that cannot contain the named cell. |
| 5891 | async fn uncovered_bundle_rows_for( |
| 5892 | &self, |
| 5893 | only_cell: Option<&str>, |
| 5894 | ) -> anyhow::Result<BTreeMap<(String, u64, u64), Vec<u8>>> { |
| 5895 | let prefix = format!("log/{}/bundle/", self.session); |
| 5896 | let mut uncovered: BTreeMap<(String, u64, u64), Vec<u8>> = BTreeMap::new(); |
| 5897 | // The index first, GETs only for the misses, and those |
| 5898 | // concurrently: the first cut GET every retained bundle serially |
| 5899 | // and blew systemd's stop budget — the graceful close timed out |
| 5900 | // into SIGKILL and the seal never happened at all. |
| 5901 | // Where one bundle's rows come from: its payload, or the bounded |
| 5902 | // index that already holds them. |
| 5903 | enum Fetched { |
| 5904 | Payload(bytes::Bytes), |
| 5905 | Indexed(Vec<celld_ltx::bundle::BundleRow>), |
| 5906 | } |
| 5907 | let candidates = match only_cell { |
| 5908 | Some(cell) => self.bundle_index.lock().unwrap().bundles_for(cell), |
| 5909 | None => self |
| 5910 | .bucket |
| 5911 | .list(&prefix) |
| 5912 | .await? |
| 5913 | .into_iter() |
| 5914 | .map(|meta| { |
| 5915 | let key = meta.location.as_ref().to_string(); |
| 5916 | let rows = self.bundle_index.lock().unwrap().rows(&key); |
| 5917 | (key, rows) |
| 5918 | }) |
| 5919 | .collect(), |
| 5920 | }; |
| 5921 | let fetches = candidates.into_iter().map(|(key, indexed)| { |
| 5922 | let bucket = self.bucket.clone(); |
| 5923 | async move { |
| 5924 | // The rows travel WITH the index hit. Looking them up again |
| 5925 | // after the fetch let a rotation out of the bounded row index |
| 5926 | // drop the bundle from the scan between the two lookups, and a |
| 5927 | // dropped bundle reads as a bundle with no rows -- the same |
| 5928 | // silent gap a failed read used to leave. |
| 5929 | if let Some(rows) = indexed { |
| 5930 | return anyhow::Ok(Some((key, Fetched::Indexed(rows)))); |
| 5931 | } |
| 5932 | match bucket.get(&key).await { |
| 5933 | Ok(Some((bytes, _))) => Ok(Some((key, Fetched::Payload(bytes)))), |
| 5934 | // Absent IS an answer: bundle GC deletes a bundle only |
| 5935 | // once the per-cell layout covers every row it carries, |
| 5936 | // so a listed-then-absent bundle carries nothing this |
| 5937 | // scan must report. A read FAILURE is not an answer. |
| 5938 | // Reporting one as a bundle with no rows is what let the |
| 5939 | // graceful seal call an unread bundle drained and orphan |
| 5940 | // its acked rows behind a record that says the bucket is |
| 5941 | // complete; the callers both fail closed on an error, so |
| 5942 | // the error has to reach them. |
| 5943 | Ok(None) => Ok(None), |
| 5944 | Err(error) => Err(error.context(format!( |
| 5945 | "read retained bundle {key} for the uncovered-row scan" |
| 5946 | ))), |
| 5947 | } |
| 5948 | } |
| 5949 | }); |
| 5950 | let mut fetched = Vec::new(); |
| 5951 | let mut fetches = |
| 5952 | futures_util::stream::iter(fetches).buffer_unordered(COVERAGE_READ_CONCURRENCY); |
| 5953 | while let Some(item) = futures_util::StreamExt::next(&mut fetches).await { |
| 5954 | if let Some(item) = item? { |
| 5955 | fetched.push(item); |
| 5956 | } |
| 5957 | } |
| 5958 | drop(fetches); |
| 5959 | // Bundles whose bytes this pass read and could not use. They are |
| 5960 | // declared together below, before the scan answers, so no caller |
| 5961 | // proceeds past an undeclared loss. |
| 5962 | let mut unreadable: BTreeMap<String, (String, Vec<celld_ltx::bundle::BundleRow>)> = |
| 5963 | BTreeMap::new(); |
| 5964 | let mut bundles = Vec::new(); |
| 5965 | for (key, item) in fetched { |
| 5966 | let (rows, bytes) = match item { |
| 5967 | Fetched::Payload(bytes) => match celld_ltx::bundle::decode_rows(&bytes) { |
| 5968 | Ok(rows) => (rows, Some(bytes)), |
| 5969 | // The envelope is unreadable, so the object no longer |
| 5970 | // says what it held and the declaration cannot name a |
| 5971 | // row. Skipping it instead reported a bundle with no |
| 5972 | // rows, which seals over whatever it carried. |
| 5973 | Err(error) => { |
| 5974 | unreadable |
| 5975 | .entry(key) |
| 5976 | .or_insert_with(|| (error.to_string(), Vec::new())); |
| 5977 | continue; |
| 5978 | } |
| 5979 | }, |
| 5980 | Fetched::Indexed(rows) => (rows, None), |
| 5981 | }; |
| 5982 | bundles.push((key, rows, bytes)); |
| 5983 | } |
| 5984 | |
| 5985 | // A coverage watermark costs one object-store listing for each LTX |
| 5986 | // level. Awaiting every distinct cell here serialized hundreds of |
| 5987 | // pairs on the process-exit path, after the handoff itself had |
| 5988 | // completed. Collect the exact unique set first and overlap it under |
| 5989 | // the same bound recovery uses. An unbounded fan-out would trade the |
| 5990 | // shutdown delay for a store burst and recreate the recovery storm |
| 5991 | // this barrier exists to avoid. |
| 5992 | let cells = bundles |
| 5993 | .iter() |
| 5994 | .flat_map(|(_, rows, _)| rows.iter().map(|row| (row.cell.clone(), row.cell_epoch))) |
| 5995 | .filter(|(cell, _)| only_cell.is_none_or(|only| only == cell)) |
| 5996 | .collect::<BTreeSet<_>>(); |
| 5997 | let ltx = &self.ltx; |
| 5998 | let lookups = cells.into_iter().map(|(cell, epoch)| async move { |
| 5999 | let watermark = ltx.covered_txid(&cell, epoch).await; |
| 6000 | ((cell, epoch), watermark) |
| 6001 | }); |
| 6002 | let mut lookups = |
| 6003 | futures_util::stream::iter(lookups).buffer_unordered(COVERAGE_READ_CONCURRENCY); |
| 6004 | let mut covered: HashMap<(String, u64), u64> = HashMap::new(); |
| 6005 | while let Some((cell, watermark)) = lookups.next().await { |
| 6006 | covered.insert(cell, watermark); |
| 6007 | } |
| 6008 | drop(lookups); |
| 6009 | |
| 6010 | for (key, rows, mut bytes) in bundles { |
| 6011 | for row in rows { |
| 6012 | if only_cell.is_some_and(|only| only != row.cell) { |
| 6013 | continue; |
| 6014 | } |
| 6015 | let cache_key = (row.cell.clone(), row.cell_epoch); |
| 6016 | let watermark = covered.get(&cache_key).copied().unwrap_or_default(); |
| 6017 | // The twin-gated decision IS the predicate: a row the |
| 6018 | // per-cell layout covers is deletable; anything else is |
| 6019 | // exactly what a seal would orphan. Routing through |
| 6020 | // bundle_deletable keeps this barrier inside the ratchet |
| 6021 | // instead of an inline comparison free to drift again. |
| 6022 | if !log_tier::bundle_deletable([(row.txid, watermark)]) { |
| 6023 | // Index-hit bundles were not fetched; an uncovered row |
| 6024 | // forces the one lazy GET its payload needs. |
| 6025 | if bytes.is_none() { |
| 6026 | // Same rule as the first pass: absence is an answer, |
| 6027 | // a failed read is not. |
| 6028 | bytes = self |
| 6029 | .bucket |
| 6030 | .get(&key) |
| 6031 | .await |
| 6032 | .with_context(|| { |
| 6033 | format!("read retained bundle {key} for the uncovered-row scan") |
| 6034 | })? |
| 6035 | .map(|(bytes, _)| bytes); |
| 6036 | } |
| 6037 | let Some(bytes) = bytes.as_ref() else { |
| 6038 | continue; |
| 6039 | }; |
| 6040 | match celld_ltx::bundle::slice(bytes, &row) { |
| 6041 | Ok(payload) => { |
| 6042 | uncovered |
| 6043 | .entry((row.cell.clone(), row.cell_epoch, row.txid)) |
| 6044 | .or_insert_with(|| payload.to_vec()); |
| 6045 | } |
| 6046 | // The envelope decoded, and this row does not lie |
| 6047 | // inside the object. The row reached here only |
| 6048 | // because the per-cell layout does not cover it, so |
| 6049 | // this is one acknowledged row with no remaining |
| 6050 | // bucket copy, and the declaration can name it. |
| 6051 | Err(error) => { |
| 6052 | let entry = unreadable |
| 6053 | .entry(key.clone()) |
| 6054 | .or_insert_with(|| (error.to_string(), Vec::new())); |
| 6055 | entry.1.push(row); |
| 6056 | } |
| 6057 | } |
| 6058 | } |
| 6059 | } |
| 6060 | } |
| 6061 | // Declare before answering. A caller that seals or restores on this |
| 6062 | // answer must do it against a durable record of what was lost. |
| 6063 | for (key, (reason, rows)) in unreadable { |
| 6064 | self.declare_bundle_loss(&key, &rows, &reason).await?; |
| 6065 | } |
| 6066 | Ok(uncovered) |
| 6067 | } |
| 6068 | |
| 6069 | /// Record a retained bundle that this session wrote and cannot read |
| 6070 | /// back. |
| 6071 | /// |
| 6072 | /// The scan reads `log/<session>/bundle/` only, so the writer is this |
| 6073 | /// process running this binary. Bytes that do not decode are therefore |
| 6074 | /// corruption, not a newer envelope this reader does not know, and no |
| 6075 | /// retry and no other reader can do better. That leaves a permanent |
| 6076 | /// refusal or a record. A refusal wedges every activation waiting on |
| 6077 | /// the fold, so the loss becomes a record and the scan continues -- |
| 6078 | /// the shape the amnesiac ensemble already uses, and the reason "loss |
| 6079 | /// is a record, never a prompt" is a rule here. |
| 6080 | /// |
| 6081 | /// `rows` names what was lost when one row failed to slice out of an |
| 6082 | /// envelope that decoded. It is empty when the envelope itself was |
| 6083 | /// unreadable, because the object then no longer says what it held. |
| 6084 | /// |
| 6085 | /// The record sits beside `log/<session>/`, never inside its `bundle/` |
| 6086 | /// subtree, so no bundle listing tries to decode a declaration. |
| 6087 | async fn declare_bundle_loss( |
| 6088 | &self, |
| 6089 | key: &str, |
| 6090 | rows: &[celld_ltx::bundle::BundleRow], |
| 6091 | reason: &str, |
| 6092 | ) -> anyhow::Result<()> { |
| 6093 | if !self |
| 6094 | .declared_bundle_losses |
| 6095 | .lock() |
| 6096 | .unwrap() |
| 6097 | .insert(key.to_string()) |
| 6098 | { |
| 6099 | return Ok(()); |
| 6100 | } |
| 6101 | let name = key.rsplit('/').next().unwrap_or(key); |
| 6102 | let record = format!("log/{}.bundle-{name}.loss.json", self.session); |
| 6103 | let body = serde_json::json!({ |
| 6104 | "session": self.session, |
| 6105 | "bundle": key, |
| 6106 | "declared_at_ms": crate::ownership_store::now_ms(), |
| 6107 | "declared_by": self.node, |
| 6108 | "reason": reason, |
| 6109 | "rows": rows |
| 6110 | .iter() |
| 6111 | .map(|row| { |
| 6112 | serde_json::json!({ |
| 6113 | "cell": row.cell, |
| 6114 | "cell_epoch": row.cell_epoch, |
| 6115 | "txid": row.txid, |
| 6116 | }) |
| 6117 | }) |
| 6118 | .collect::<Vec<_>>(), |
| 6119 | "note": "a retained bundle this session wrote could not be read \ |
| 6120 | back; an acknowledged row it carried that the per-cell \ |
| 6121 | layout does not cover is unrecovered", |
| 6122 | }); |
| 6123 | if let Err(error) = self.bucket.put(&record, serde_json::to_vec(&body)?).await { |
| 6124 | // The scan must not answer until the record is durable, so a |
| 6125 | // failed declaration un-latches and the next pass retries it. |
| 6126 | self.declared_bundle_losses.lock().unwrap().remove(key); |
| 6127 | return Err(error.context(format!("declare the unreadable bundle {key}"))); |
| 6128 | } |
| 6129 | warn!( |
| 6130 | bundle = key, |
| 6131 | reason, |
| 6132 | rows = rows.len(), |
| 6133 | "declared a retained bundle this session cannot read back" |
| 6134 | ); |
| 6135 | Ok(()) |
| 6136 | } |
| 6137 | |
| 6138 | pub async fn gc_bundles(&self) -> anyhow::Result<()> { |
| 6139 | // Bound both the listing and the work. Restarting at the prefix |
| 6140 | // every tick starved newer, covered bundles behind an undrained |
| 6141 | // prefix forever. Advance after every examination, even a failed GET, |
| 6142 | // and wrap only when the page reaches the end of the session. |
| 6143 | const TICK_BUDGET: std::time::Duration = std::time::Duration::from_secs(2); |
| 6144 | let mut cursor = self.bundle_gc_cursor.lock().await; |
| 6145 | let started = mono_ms(); |
| 6146 | let prefix = format!("log/{}/bundle/", self.session); |
| 6147 | let page = self |
| 6148 | .bucket |
| 6149 | .list_page( |
| 6150 | &prefix, |
| 6151 | cursor.as_deref(), |
| 6152 | BUNDLE_GC_EXAMINED_PER_TICK, |
| 6153 | None, |
| 6154 | ) |
| 6155 | .await?; |
| 6156 | let mut covered: HashMap<(String, u64), u64> = HashMap::new(); |
| 6157 | let mut deletable: Vec<(String, usize)> = Vec::new(); |
| 6158 | let mut exhausted = true; |
| 6159 | for (examined, meta) in page.objects.into_iter().enumerate() { |
| 6160 | // Always examine one object so a slow listing cannot prevent |
| 6161 | // progress. The budget can stop the remainder of the page. |
| 6162 | if examined > 0 && mono_ms().saturating_sub(started) > TICK_BUDGET.as_millis() as u64 { |
| 6163 | exhausted = false; |
| 6164 | break; |
| 6165 | } |
| 6166 | let key = meta.key; |
| 6167 | *cursor = Some(key.clone()); |
| 6168 | let indexed = { |
| 6169 | let index = self.bundle_index.lock().unwrap(); |
| 6170 | index.rows(&key) |
| 6171 | }; |
| 6172 | let rows = match indexed { |
| 6173 | Some(rows) => rows, |
| 6174 | None => { |
| 6175 | let Ok(Some((bytes, _))) = self.bucket.get(&key).await else { |
| 6176 | continue; |
| 6177 | }; |
| 6178 | match celld_ltx::bundle::decode_rows(&bytes) { |
| 6179 | Ok(rows) => rows, |
| 6180 | Err(_) => continue, |
| 6181 | } |
| 6182 | } |
| 6183 | }; |
| 6184 | let mut paired = Vec::with_capacity(rows.len()); |
| 6185 | for row in &rows { |
| 6186 | let cache_key = (row.cell.clone(), row.cell_epoch); |
| 6187 | let watermark = match covered.get(&cache_key) { |
| 6188 | Some(watermark) => *watermark, |
| 6189 | None => { |
| 6190 | let watermark = self.ltx.covered_txid(&row.cell, row.cell_epoch).await; |
| 6191 | covered.insert(cache_key, watermark); |
| 6192 | watermark |
| 6193 | } |
| 6194 | }; |
| 6195 | paired.push((row.txid, watermark)); |
| 6196 | // One uncovered row retains the whole bundle. Do not pay |
| 6197 | // for every other cell before reaching the same answer. |
| 6198 | if !log_tier::bundle_deletable([(row.txid, watermark)]) { |
| 6199 | break; |
| 6200 | } |
| 6201 | } |
| 6202 | if !log_tier::bundle_deletable(paired) { |
| 6203 | continue; |
| 6204 | } |
| 6205 | deletable.push((key, rows.len())); |
| 6206 | } |
| 6207 | if exhausted && !page.truncated { |
| 6208 | *cursor = None; |
| 6209 | } |
| 6210 | if deletable.is_empty() { |
| 6211 | return Ok(()); |
| 6212 | } |
| 6213 | // One DeleteObjects request instead of one DELETE per bundle: the |
| 6214 | // lab priced the per-key path at 9k class A operations an hour. |
| 6215 | let keys: Vec<String> = deletable.iter().map(|(key, _)| key.clone()).collect(); |
| 6216 | let gone = self.bucket.delete_many(&keys).await; |
| 6217 | if !gone.is_empty() { |
| 6218 | let rows: usize = deletable |
| 6219 | .iter() |
| 6220 | .filter(|(key, _)| gone.contains(key)) |
| 6221 | .map(|(_, rows)| rows) |
| 6222 | .sum(); |
| 6223 | self.bundle_index.lock().unwrap().remove(&gone); |
| 6224 | info!( |
| 6225 | bundles = gone.len(), |
| 6226 | rows, "bundle GC: drained bundles deleted in one batch" |
| 6227 | ); |
| 6228 | } |
| 6229 | Ok(()) |
| 6230 | } |
| 6231 | |
| 6232 | /// Eager recovery ("Recovery is one verb"): every maintenance tick, |
| 6233 | /// sweep `log/` for a foreign, unsealed record whose owner's lease has |
| 6234 | /// expired, and recover it — traffic or none. Lazy-only recovery left |
| 6235 | /// an idle dead owner's un-tiered tail on two follower disks for an |
| 6236 | /// unbounded time; the sweep bounds that exposure at roughly one tick |
| 6237 | /// past lease expiry. Every survivor sweeps; racing recoverers collapse |
| 6238 | /// onto the CAS like every other recovery race. |
| 6239 | pub async fn sweep_dead_leaders(&self) -> anyhow::Result<()> { |
| 6240 | let now = crate::ownership_store::now_ms(); |
| 6241 | for meta in self.bucket.list("nodes/").await? { |
| 6242 | let Some(node) = meta |
| 6243 | .location |
| 6244 | .as_ref() |
| 6245 | .strip_prefix("nodes/") |
| 6246 | .and_then(|name| name.strip_suffix(".json")) |
| 6247 | .filter(|name| !name.contains('/')) |
| 6248 | .map(str::to_string) |
| 6249 | else { |
| 6250 | continue; |
| 6251 | }; |
| 6252 | if node == self.node { |
| 6253 | continue; |
| 6254 | } |
| 6255 | // One unreadable record must not end the sweep for every node |
| 6256 | // sorted after it. |
| 6257 | let Ok(Some(folded)) = read_record(&self.bucket, &node).await else { |
| 6258 | continue; |
| 6259 | }; |
| 6260 | let session = format!("{node}/{}", folded.wire.generation); |
| 6261 | let record = folded.record; |
| 6262 | // Under the fold, the lease we just read IS the record: a |
| 6263 | // session is dead the moment its published expiry passed. A |
| 6264 | // restarted node replaces the record (generation and all) |
| 6265 | // through recovery-before-install, so the sweep never |
| 6266 | // contends with a returning leader; an expired same- |
| 6267 | // generation lease is a process that self-fenced or is about |
| 6268 | // to, and recovery's CAS fences its remaining renewals. |
| 6269 | let dead = folded.wire.expires_ms <= now; |
| 6270 | if record.state == LogState::Sealed { |
| 6271 | // A dead session's sealed subtree is one GC unit: recovery |
| 6272 | // folded every acked row per-cell before the seal, so the |
| 6273 | // retained bundles are garbage, and deleting the record |
| 6274 | // afterwards keeps the invariant — absence means complete, |
| 6275 | // exactly as sealed did. Bundles go FIRST so a session |
| 6276 | // record never vanishes while its subtree still holds |
| 6277 | // objects; loss records are declarations and stay forever. |
| 6278 | // Racing sweepers double-delete idempotently. Without this, |
| 6279 | // log/ grows one record per restart for the fleet's |
| 6280 | // lifetime, and every sweep and takeover LIST scales with |
| 6281 | // restart history. |
| 6282 | if dead && !self.gc_confirmed_empty.lock().unwrap().contains(&session) { |
| 6283 | match self.gc_sealed_session(&session).await { |
| 6284 | Ok(empty) => { |
| 6285 | if empty { |
| 6286 | self.gc_confirmed_empty.lock().unwrap().insert(session); |
| 6287 | } |
| 6288 | } |
| 6289 | Err(error) => warn!(session, %error, "sealed-session GC failed"), |
| 6290 | } |
| 6291 | } |
| 6292 | continue; |
| 6293 | } |
| 6294 | if !dead { |
| 6295 | continue; |
| 6296 | } |
| 6297 | info!(session, "eager recovery: dead session with an open log"); |
| 6298 | if let Err(error) = self.recover(&session).await { |
| 6299 | warn!(session, %error, "eager node-log recovery failed"); |
| 6300 | } |
| 6301 | } |
| 6302 | Ok(()) |
| 6303 | } |
| 6304 | |
| 6305 | /// Delete a dead, sealed session's retained bundles. Under the fold |
| 6306 | /// the record itself lives in the lease and is retired by dead-lease |
| 6307 | /// GC; a sealed session leaves bundles and recovery checkpoints behind. |
| 6308 | /// Recovery folded every acked row per-cell before the seal, so both |
| 6309 | /// subtrees are garbage. Batched: a session can retain hundreds, and |
| 6310 | /// the lab priced one-key-at-a-time GC at 9k class A operations an |
| 6311 | /// hour. A key that fails stays for the next sweep tick. |
| 6312 | async fn gc_sealed_session(&self, session: &str) -> anyhow::Result<bool> { |
| 6313 | let prefix = format!("log/{session}/"); |
| 6314 | let keys: Vec<String> = self |
| 6315 | .bucket |
| 6316 | .list(&prefix) |
| 6317 | .await? |
| 6318 | .into_iter() |
| 6319 | .map(|meta| meta.location.as_ref().to_string()) |
| 6320 | .filter(|key| { |
| 6321 | key.strip_prefix(&prefix).is_some_and(|tail| { |
| 6322 | tail.starts_with("bundle/") || tail.starts_with("recovered/") |
| 6323 | }) |
| 6324 | }) |
| 6325 | .collect(); |
| 6326 | if keys.is_empty() { |
| 6327 | return Ok(true); |
| 6328 | } |
| 6329 | let count = keys.len(); |
| 6330 | let gone = self.bucket.delete_many(&keys).await; |
| 6331 | if gone.len() != count { |
| 6332 | anyhow::bail!( |
| 6333 | "{} of {count} recovery objects survived the delete; retrying next tick", |
| 6334 | count - gone.len() |
| 6335 | ); |
| 6336 | } |
| 6337 | info!( |
| 6338 | session, |
| 6339 | objects = count, |
| 6340 | "sealed session's recovery objects retired" |
| 6341 | ); |
| 6342 | Ok(true) |
| 6343 | } |
| 6344 | } |
| 6345 | |
| 6346 | /// The maintenance cadence: recruit at startup, repair forever after, and |
| 6347 | /// sweep for dead leaders' open logs. Beside it, the fast eviction watch: |
| 6348 | /// gray-follower detection cannot wait thirty seconds when one slow fsync |
| 6349 | /// tail is every ack's tail, so verdicts poll at a sub-second cadence and |
| 6350 | /// an eviction repairs the ensemble immediately. |
| 6351 | fn spawn_maintenance( |
| 6352 | manager: Arc<NodeLogManager>, |
| 6353 | stop: crate::ltx_repl::StopToken, |
| 6354 | roots: &crate::ltx_repl::TaskGroup, |
| 6355 | ) { |
| 6356 | let maintenance_manager = Arc::downgrade(&manager); |
| 6357 | let watcher = Arc::downgrade(&manager); |
| 6358 | let maintenance_stop = stop.clone(); |
| 6359 | roots.spawn_owned("node_log_maintenance", async move { |
| 6360 | let mut tick = crate::asyncrt::interval(std::time::Duration::from_secs(30)); |
| 6361 | tick.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay); |
| 6362 | loop { |
| 6363 | crate::asyncrt::select_biased! { |
| 6364 | "a stop signal that ties the maintenance tick prevents another maintenance pass"; |
| 6365 | _ = maintenance_stop.stopped() => break, |
| 6366 | _ = tick.tick() => {}, |
| 6367 | } |
| 6368 | let Some(manager) = maintenance_manager.upgrade() else { |
| 6369 | break; |
| 6370 | }; |
| 6371 | // The watchdog for #490: on the 2026-08-28 fleet this loop's |
| 6372 | // heartbeat stopped mid-pass and never returned — no error, no |
| 6373 | // panic, no recovery line — and the silence cost the diagnosis. |
| 6374 | // Every phase must end; a phase that outlives the warning |
| 6375 | // budget names itself while it is still stuck, so the next |
| 6376 | // occurrence is a one-line diagnosis plus a stack, not an |
| 6377 | // archaeology session. The pass still runs to completion — |
| 6378 | // this observes, it does not cancel: an aborted maintenance |
| 6379 | // phase could orphan a half-installed ensemble. |
| 6380 | for (phase, work) in [ |
| 6381 | ("maintain", manager.maintain().boxed()), |
| 6382 | ("dead-leader sweep", manager.sweep_dead_leaders().boxed()), |
| 6383 | ("bundle GC", manager.gc_bundles().boxed()), |
| 6384 | ] { |
| 6385 | let started = mono_ms(); |
| 6386 | let mut work = work; |
| 6387 | loop { |
| 6388 | match crate::asyncrt::timeout(std::time::Duration::from_secs(60), &mut work) |
| 6389 | .await |
| 6390 | { |
| 6391 | Ok(Ok(())) => break, |
| 6392 | Ok(Err(error)) => { |
| 6393 | warn!(%error, phase, "log maintenance phase failed"); |
| 6394 | break; |
| 6395 | } |
| 6396 | Err(_) => { |
| 6397 | warn!( |
| 6398 | phase, |
| 6399 | stuck_ms = mono_ms().saturating_sub(started), |
| 6400 | "log maintenance phase has not returned; \ |
| 6401 | the ticker is blocked behind it (#490)" |
| 6402 | ); |
| 6403 | } |
| 6404 | } |
| 6405 | } |
| 6406 | } |
| 6407 | } |
| 6408 | }); |
| 6409 | roots.spawn_owned("node_log_posture_watch", async move { |
| 6410 | let mut tick = crate::asyncrt::interval(std::time::Duration::from_millis(250)); |
| 6411 | tick.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay); |
| 6412 | let mut repair_since: Option<u64> = None; |
| 6413 | let mut last_repair_try = mono_ms().saturating_sub(2_000); |
| 6414 | let mut repair_interval = std::time::Duration::from_secs(1); |
| 6415 | loop { |
| 6416 | crate::asyncrt::select_biased! { |
| 6417 | "a stop signal that ties the posture tick prevents another repair attempt"; |
| 6418 | _ = stop.stopped() => break, |
| 6419 | _ = tick.tick() => {}, |
| 6420 | } |
| 6421 | let Some(watcher) = watcher.upgrade() else { |
| 6422 | break; |
| 6423 | }; |
| 6424 | watcher.probe_followers(); |
| 6425 | watcher.evict_gray_followers(); |
| 6426 | // Posture repair does not wait for the 30 s maintenance tick: |
| 6427 | // while the shipper is absent or degraded, retry about once a |
| 6428 | // second — the first attempt after an eviction usually loses |
| 6429 | // to the drain barrier, and E8's first light measured a 22 s |
| 6430 | // hole where nothing retried until the tick. The repair |
| 6431 | // latency line is the E8 recruit-repair metric. |
| 6432 | if watcher.healthy() { |
| 6433 | if let Some(since) = repair_since.take() { |
| 6434 | info!( |
| 6435 | event = "posture_repair", |
| 6436 | degraded_ms = mono_ms().saturating_sub(since), |
| 6437 | "fleet posture repaired" |
| 6438 | ); |
| 6439 | } |
| 6440 | repair_interval = std::time::Duration::from_secs(1); |
| 6441 | continue; |
| 6442 | } |
| 6443 | repair_since.get_or_insert_with(mono_ms); |
| 6444 | // The first repair after a degrade is immediate — that is the |
| 6445 | // 0.7s swap — but successive failed repairs back off to the |
| 6446 | // swap rate cap: a full peer partition once opened seventeen |
| 6447 | // doomed epochs in twenty seconds at the flat retry rate. |
| 6448 | if mono_ms().saturating_sub(last_repair_try) >= repair_interval.as_millis() as u64 { |
| 6449 | last_repair_try = mono_ms(); |
| 6450 | let epoch_before = crate::ltx_repl::Shipper::epoch(&*watcher); |
| 6451 | if let Err(error) = watcher.maintain().await { |
| 6452 | warn!(%error, "posture repair failed"); |
| 6453 | } |
| 6454 | let stepped = crate::ltx_repl::Shipper::epoch(&*watcher) != epoch_before; |
| 6455 | repair_interval = if watcher.healthy() { |
| 6456 | std::time::Duration::from_secs(1) |
| 6457 | } else if stepped { |
| 6458 | (repair_interval * 2).min(std::time::Duration::from_secs(10)) |
| 6459 | } else { |
| 6460 | std::time::Duration::from_secs(1) |
| 6461 | }; |
| 6462 | } |
| 6463 | } |
| 6464 | }); |
| 6465 | } |
| 6466 | |
| 6467 | /// The follower-side fragment GC: a fragment whose epoch the record has |
| 6468 | /// moved past (a reconfiguration or a reopened incarnation), or whose |
| 6469 | /// epoch's record is Sealed (recovery certified and uploaded the tail), is |
| 6470 | /// garbage no gather will ever consult — without this sweep a follower |
| 6471 | /// that is never re-recruited keeps one closed epoch's fragments per |
| 6472 | /// leader forever. The seal mark is preserved and extended: a closed |
| 6473 | /// epoch is refused from here on, which is also what makes the deletion |
| 6474 | /// safe against any straggling append. |
| 6475 | fn spawn_fragment_gc( |
| 6476 | store: Arc<FollowerStore>, |
| 6477 | stop: crate::ltx_repl::StopToken, |
| 6478 | tasks: &crate::ltx_repl::TaskGroup, |
| 6479 | ) { |
| 6480 | tasks.spawn_owned("follower_fragment_gc", async move { |
| 6481 | let mut tick = crate::asyncrt::interval(std::time::Duration::from_secs(600)); |
| 6482 | tick.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay); |
| 6483 | loop { |
| 6484 | crate::asyncrt::select_biased! { |
| 6485 | "a stop signal that ties the fragment-GC tick prevents another deletion pass"; |
| 6486 | _ = stop.stopped() => break, |
| 6487 | _ = tick.tick() => {}, |
| 6488 | } |
| 6489 | store.gc_fragments().await; |
| 6490 | } |
| 6491 | }); |
| 6492 | } |
| 6493 | |
| 6494 | impl NodeLogManager { |
| 6495 | /// One object per node-flush: `log/<node>/bundle/e<epoch>-<seq>.ltxb`, |
| 6496 | /// verbatim L0 segments plus the footer (`crate::bundle`). Keys are |
| 6497 | /// unique per (epoch, seq), so the PUT needs no condition; the epoch in |
| 6498 | /// the key scopes recovery's gather and the eventual GC sweep. |
| 6499 | pub(crate) async fn put_bundle(&self, entries: Vec<celld_ltx::bundle::BundleEntry>) -> bool { |
| 6500 | struct FlushGuard<'a>(&'a std::sync::atomic::AtomicBool); |
| 6501 | impl Drop for FlushGuard<'_> { |
| 6502 | fn drop(&mut self) { |
| 6503 | self.0.store(false, Ordering::SeqCst); |
| 6504 | } |
| 6505 | } |
| 6506 | self.flush_in_flight.store(true, Ordering::SeqCst); |
| 6507 | let _flush = FlushGuard(&self.flush_in_flight); |
| 6508 | let (epoch, flusher) = { |
| 6509 | let inner = self.inner.lock().unwrap(); |
| 6510 | match inner.as_ref() { |
| 6511 | Some(shipper) => (shipper.epoch, shipper.clone()), |
| 6512 | None => return false, |
| 6513 | } |
| 6514 | }; |
| 6515 | let seq = self.bundle_seq.fetch_add(1, Ordering::SeqCst); |
| 6516 | let body = match celld_ltx::bundle::encode(&entries) { |
| 6517 | Ok(body) => body, |
| 6518 | Err(error) => { |
| 6519 | warn!(%error, "bundle encode failed"); |
| 6520 | return false; |
| 6521 | } |
| 6522 | }; |
| 6523 | let rows = match celld_ltx::bundle::decode_rows(&body) { |
| 6524 | Ok(rows) => rows, |
| 6525 | Err(error) => { |
| 6526 | warn!(%error, "bundle self-decode failed"); |
| 6527 | return false; |
| 6528 | } |
| 6529 | }; |
| 6530 | let key = format!("log/{}/bundle/e{epoch}-{seq:08}.ltxb", self.session); |
| 6531 | match self.bucket.put(&key, body).await { |
| 6532 | Ok(()) => { |
| 6533 | // The credit check: the PUT is unconditional, so by |
| 6534 | // itself it proves nothing to the ack path — a healed |
| 6535 | // zombie whose record a recoverer already sealed can |
| 6536 | // still land bundle objects, and crediting them would |
| 6537 | // ack rows no future takeover reads (the sealed record |
| 6538 | // says the bucket is complete, and takeovers read |
| 6539 | // per-cell prefixes). Durability credits only if the |
| 6540 | // record is still Open at this shipper's epoch AFTER |
| 6541 | // the PUT: any recovery that fences later must list |
| 6542 | // after this PUT completed and therefore gathers it. |
| 6543 | // A BUCKET read on purpose: the hazard is a peer's |
| 6544 | // recovery CAS fencing this record, which the |
| 6545 | // in-process copy cannot see. |
| 6546 | let credit = log_tier::bundle_credit_allowed( |
| 6547 | read_record(&self.bucket, &self.session) |
| 6548 | .await |
| 6549 | .ok() |
| 6550 | .flatten() |
| 6551 | .as_ref() |
| 6552 | .map(|folded| &folded.record), |
| 6553 | epoch, |
| 6554 | ); |
| 6555 | if !credit { |
| 6556 | // Degrade the shipper that OWNED this flush's |
| 6557 | // epoch, not whichever is installed now: a flush |
| 6558 | // racing a legitimate reconfiguration must not |
| 6559 | // poison the successor ensemble it knows nothing |
| 6560 | // about. For a true zombie the flusher IS the |
| 6561 | // installed shipper and stops exactly as before; |
| 6562 | // for a swap race this degrades a retired object, |
| 6563 | // which is the correct no-op — the lab measured |
| 6564 | // the alternative as an epoch-churn loop. |
| 6565 | flusher.degrade("record moved under a bundle flush"); |
| 6566 | warn!(key, "bundle flush not credited: record moved"); |
| 6567 | return false; |
| 6568 | } |
| 6569 | self.bundle_index.lock().unwrap().insert(key, rows); |
| 6570 | true |
| 6571 | } |
| 6572 | Err(error) => { |
| 6573 | warn!(%error, key, "bundle put failed"); |
| 6574 | false |
| 6575 | } |
| 6576 | } |
| 6577 | } |
| 6578 | |
| 6579 | pub(crate) fn bundle_active(&self) -> bool { |
| 6580 | // Draining rides the bundle path even while the shipper is |
| 6581 | // DEGRADED: degrade stops fleet proofs, not tiering. The credit |
| 6582 | // check against the record is the safety gate (a sealed or |
| 6583 | // stepped record refuses the credit), and demoting the |
| 6584 | // post-eviction drain to sequential per-cell PUTs was measured at |
| 6585 | // 57 s of bucket-posture acks under load — where the design |
| 6586 | // promised one flush. The one exception is the shutdown latch: |
| 6587 | // once the graceful close begins its seal scan, a new flush could |
| 6588 | // credit rows the scan never saw, so `closing` quiesces the sink |
| 6589 | // and late writes ride per-cell acks instead. |
| 6590 | !self.closing.load(Ordering::SeqCst) && self.inner.lock().unwrap().is_some() |
| 6591 | } |
| 6592 | |
| 6593 | /// One cell epoch's retained bundle rows, for the compaction overlay. |
| 6594 | /// A slow cell can outlive the bounded row index, so a row that left the |
| 6595 | /// index is read from the persisted bundles that the membership names. |
| 6596 | pub(crate) async fn rows_for( |
| 6597 | &self, |
| 6598 | cell: &str, |
| 6599 | epoch: u64, |
| 6600 | ) -> anyhow::Result<Vec<celld_ltx::LocatedRow>> { |
| 6601 | let CellBundleRows { |
| 6602 | mut located, |
| 6603 | evicted, |
| 6604 | evicted_through, |
| 6605 | } = self.bundle_index.lock().unwrap().cell_rows(cell, epoch); |
| 6606 | let covered = self.ltx.covered_txid(cell, epoch).await; |
| 6607 | if evicted_through.is_some_and(|through| covered < through) { |
| 6608 | // A cache is not the source of truth. A slow cell can lose its |
| 6609 | // first row long before it reaches the compaction threshold. |
| 6610 | // Fetch only the evicted bundles that contain the cell, with |
| 6611 | // bounded concurrency. A failed read must fail the compaction; |
| 6612 | // treating it as no rows would hide a gap or report false |
| 6613 | // completion. |
| 6614 | let fetches = evicted.into_iter().map(|key| async move { |
| 6615 | let rows = match self.bucket.get(&key).await? { |
| 6616 | Some((bytes, _)) => celld_ltx::bundle::decode_rows(&bytes)?, |
| 6617 | // GC removes only rows covered by the per-cell layout. |
| 6618 | // A concurrent deletion is safe to omit. |
| 6619 | None => Vec::new(), |
| 6620 | }; |
| 6621 | anyhow::Ok((key, rows)) |
| 6622 | }); |
| 6623 | let mut fetches = |
| 6624 | futures_util::stream::iter(fetches).buffer_unordered(COVERAGE_READ_CONCURRENCY); |
| 6625 | while let Some(fetched) = fetches.next().await { |
| 6626 | let (key, rows) = fetched?; |
| 6627 | located.extend( |
| 6628 | rows.into_iter() |
| 6629 | .filter(|row| row.cell == cell && row.cell_epoch == epoch) |
| 6630 | .map(|row| celld_ltx::LocatedRow { |
| 6631 | source: key.clone(), |
| 6632 | row, |
| 6633 | }), |
| 6634 | ); |
| 6635 | } |
| 6636 | } |
| 6637 | // A folded L0 can cover several rows still in the index. The |
| 6638 | // overlay deduplicates file starts, not interior transactions; |
| 6639 | // returning those rows merges the same transaction twice. |
| 6640 | located.retain(|located| located.row.txid > covered); |
| 6641 | Ok(located) |
| 6642 | } |
| 6643 | |
| 6644 | pub(crate) async fn fetch_bundle(&self, source: &str) -> anyhow::Result<Vec<u8>> { |
| 6645 | { |
| 6646 | let cache = self.bundle_cache.lock().await; |
| 6647 | if let Some((key, bytes)) = cache.as_ref() { |
| 6648 | if key == source { |
| 6649 | return Ok(bytes.as_ref().clone()); |
| 6650 | } |
| 6651 | } |
| 6652 | } |
| 6653 | let Some((bytes, _)) = self.bucket.get(source).await? else { |
| 6654 | anyhow::bail!("bundle {source} vanished"); |
| 6655 | }; |
| 6656 | let bytes: Vec<u8> = bytes.to_vec(); |
| 6657 | *self.bundle_cache.lock().await = Some((source.to_string(), Arc::new(bytes.clone()))); |
| 6658 | Ok(bytes) |
| 6659 | } |
| 6660 | |
| 6661 | /// Compaction can encounter a snapshot row larger than its input budget. |
| 6662 | /// Read only that row's requested bytes, without cloning or caching its |
| 6663 | /// complete bundle. The compactor validates the assembled LTX checksum. |
| 6664 | pub(crate) async fn fetch_bundle_range( |
| 6665 | &self, |
| 6666 | located: &celld_ltx::LocatedRow, |
| 6667 | offset: u64, |
| 6668 | len: u64, |
| 6669 | ) -> anyhow::Result<Vec<u8>> { |
| 6670 | use crate::bucket::{BlobConditions, BlobRange, BlobRead}; |
| 6671 | let len = len.min(located.row.len.saturating_sub(offset)); |
| 6672 | if len == 0 { |
| 6673 | return Ok(Vec::new()); |
| 6674 | } |
| 6675 | let offset = located |
| 6676 | .row |
| 6677 | .offset |
| 6678 | .checked_add(offset) |
| 6679 | .ok_or_else(|| anyhow!("bundle row range overflows"))?; |
| 6680 | let BlobRead::Hit(mut blob) = self |
| 6681 | .bucket |
| 6682 | .get_blob( |
| 6683 | &located.source, |
| 6684 | BlobRange::Bounded { |
| 6685 | offset, |
| 6686 | length: len, |
| 6687 | }, |
| 6688 | &BlobConditions::default(), |
| 6689 | ) |
| 6690 | .await? |
| 6691 | else { |
| 6692 | anyhow::bail!("bundle {} vanished", located.source); |
| 6693 | }; |
| 6694 | let mut bytes = Vec::new(); |
| 6695 | while let Some(chunk) = blob.body.next().await { |
| 6696 | bytes.extend_from_slice(&chunk.map_err(|error| anyhow!(error))?); |
| 6697 | } |
| 6698 | anyhow::ensure!(bytes.len() as u64 == len, "bundle row range is short"); |
| 6699 | Ok(bytes) |
| 6700 | } |
| 6701 | |
| 6702 | /// Recovery's gather for one cell, run by the successor of a quiet |
| 6703 | /// ending before its restore. The tail can live in two places: this |
| 6704 | /// node's own retained bundles, and the live members' fragments — a |
| 6705 | /// fleet ack proves follower fsync, not a bundle flush, so the member |
| 6706 | /// gather is the one the field incident needed. No seal: the leader |
| 6707 | /// is alive, the cell's epoch is closed, and rows at or below the ack |
| 6708 | /// are immutable. An epoch with possible fleet acknowledgements needs a |
| 6709 | /// ranged tail proving that a current member returned every retained |
| 6710 | /// sequence. Without that proof, activation fails rather than exposing a |
| 6711 | /// database that is missing acknowledged data. |
| 6712 | /// `upload_gathered` skips rows the per-cell watermark covers and |
| 6713 | /// merges the contiguous tail into one object, so a re-run after a |
| 6714 | /// partial failure repeats no upload. |
| 6715 | pub(crate) async fn fold_cell(&self, cell: &str) -> anyhow::Result<()> { |
| 6716 | let mut gathered = BTreeMap::new(); |
| 6717 | let folded = read_record(&self.bucket, &self.session) |
| 6718 | .await? |
| 6719 | .ok_or_else(|| anyhow!("fold session {} has no log record", self.session))?; |
| 6720 | let record = folded.record; |
| 6721 | let mut complete_witnesses = 0_usize; |
| 6722 | for member in &record.ensemble { |
| 6723 | let addr = match self.ownership.read_node_lease(member).await { |
| 6724 | Ok(Some(lease)) => lease.addr, |
| 6725 | Ok(None) => { |
| 6726 | warn!(cell, member, "live-session fold member has no lease"); |
| 6727 | continue; |
| 6728 | } |
| 6729 | Err(error) => { |
| 6730 | warn!(cell, member, %error, "live-session fold could not read a member lease"); |
| 6731 | continue; |
| 6732 | } |
| 6733 | }; |
| 6734 | let mut tail = match self |
| 6735 | .post_tail( |
| 6736 | member, |
| 6737 | &addr, |
| 6738 | &TailReq { |
| 6739 | leader: self.session.clone(), |
| 6740 | }, |
| 6741 | ) |
| 6742 | .await |
| 6743 | { |
| 6744 | Ok(TailReply::Ranged(tail)) => tail, |
| 6745 | Ok(TailReply::Legacy { .. }) => { |
| 6746 | warn!( |
| 6747 | cell, |
| 6748 | member, "live-session fold received a legacy tail without range evidence" |
| 6749 | ); |
| 6750 | continue; |
| 6751 | } |
| 6752 | Err(error) => { |
| 6753 | warn!(cell, member, %error, "live-session fold could not read a follower tail"); |
| 6754 | continue; |
| 6755 | } |
| 6756 | }; |
| 6757 | tail.entries.sort_by_key(|entry| entry.seq); |
| 6758 | let range = tail.range; |
| 6759 | if range.fragment_epoch != record.epoch { |
| 6760 | warn!( |
| 6761 | cell, |
| 6762 | member, |
| 6763 | record_epoch = record.epoch, |
| 6764 | tail_epoch = range.fragment_epoch, |
| 6765 | "live-session fold received a different fragment epoch" |
| 6766 | ); |
| 6767 | continue; |
| 6768 | } |
| 6769 | if range.complete && tail_covers_sealed_range(range.base, range.end, &tail.entries) { |
| 6770 | complete_witnesses += 1; |
| 6771 | } else { |
| 6772 | warn!( |
| 6773 | cell, |
| 6774 | member, |
| 6775 | base = range.base, |
| 6776 | end = range.end, |
| 6777 | tail_complete = range.complete, |
| 6778 | "live-session fold rejected an incomplete follower tail" |
| 6779 | ); |
| 6780 | } |
| 6781 | for entry in tail.entries { |
| 6782 | if entry.cell != cell { |
| 6783 | continue; |
| 6784 | } |
| 6785 | gathered |
| 6786 | .entry((entry.cell, entry.cell_epoch, entry.txid)) |
| 6787 | .or_insert(entry.bytes); |
| 6788 | } |
| 6789 | } |
| 6790 | // Activation is durable before the epoch's first fleet credit. An |
| 6791 | // epoch without fleet acknowledgements can credit a bundle PUT without |
| 6792 | // appending to any follower, so requiring a follower would strand a |
| 6793 | // bucket-only tail. Possible fleet acknowledgements need the proof. |
| 6794 | anyhow::ensure!( |
| 6795 | !folded.may_have_fleet_acks || complete_witnesses > 0, |
| 6796 | "fold session {} has no complete follower tail for {cell}", |
| 6797 | self.session |
| 6798 | ); |
| 6799 | // Read the bundle index after the epoch and follower observations. |
| 6800 | // Publishing a bundle can permit epoch replacement or truncation of |
| 6801 | // the old fragments. An earlier snapshot could miss that bundle and |
| 6802 | // then accept a newer inactive epoch or already-truncated tail as |
| 6803 | // empty, losing the acknowledged rows that enabled the transition. |
| 6804 | gathered.extend(self.uncovered_bundle_rows_for(Some(cell)).await?); |
| 6805 | if gathered.is_empty() { |
| 6806 | return Ok(()); |
| 6807 | } |
| 6808 | let uploaded = self.upload_gathered(gathered, None).await?; |
| 6809 | info!( |
| 6810 | cell, |
| 6811 | uploaded, "folded a quietly stranded tail before reactivation" |
| 6812 | ); |
| 6813 | Ok(()) |
| 6814 | } |
| 6815 | } |
| 6816 | |
| 6817 | #[cfg(all(test, celld_internal_tests))] |
| 6818 | include!(env!("CELLD_INTERNAL_NODE_LOG_OBSERVERS")); |